Compare commits

..
Author SHA1 Message Date
Antigravity AI 461944271b Resolve merge conflicts with main 2026-05-10 11:28:49 +12:00
dependabot[bot] 0b64459cfe build(deps): bump the dependencies group with 17 updates (#73)
Bumps the dependencies group with 17 updates:

| Package | From | To |
| --- | --- | --- |
| [@auth/prisma-adapter](https://github.com/nextauthjs/next-auth) | `2.11.1` | `2.11.2` |
| [@prisma/adapter-pg](https://github.com/prisma/prisma/tree/HEAD/packages/adapter-pg) | `7.6.0` | `7.8.0` |
| [@prisma/client](https://github.com/prisma/prisma/tree/HEAD/packages/client) | `7.6.0` | `7.8.0` |
| [@prisma/client-runtime-utils](https://github.com/prisma/prisma/tree/HEAD/packages/client-runtime-utils) | `7.6.0` | `7.8.0` |
| [@sentry/nextjs](https://github.com/getsentry/sentry-javascript) | `10.48.0` | `10.52.0` |
| [@supabase/supabase-js](https://github.com/supabase/supabase-js/tree/HEAD/packages/core/supabase-js) | `2.100.1` | `2.105.4` |
| [cesium](https://github.com/CesiumGS/cesium) | `1.139.1` | `1.141.0` |
| [hls.js](https://github.com/video-dev/hls.js) | `1.6.15` | `1.6.16` |
| [jose](https://github.com/panva/jose) | `6.2.2` | `6.2.3` |
| [next](https://github.com/vercel/next.js) | `16.2.3` | `16.2.6` |
| [prisma](https://github.com/prisma/prisma/tree/HEAD/packages/cli) | `7.6.0` | `7.8.0` |
| [react](https://github.com/facebook/react/tree/HEAD/packages/react) | `19.2.3` | `19.2.6` |
| [react-dom](https://github.com/facebook/react/tree/HEAD/packages/react-dom) | `19.2.3` | `19.2.6` |
| [resium](https://github.com/reearth/resium) | `1.19.4` | `1.21.0` |
| [zustand](https://github.com/pmndrs/zustand) | `5.0.12` | `5.0.13` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.0.8` | `8.0.11` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.2` | `4.1.5` |


Updates `@auth/prisma-adapter` from 2.11.1 to 2.11.2
- [Release notes](https://github.com/nextauthjs/next-auth/releases)
- [Commits](https://github.com/nextauthjs/next-auth/compare/@auth/[email protected]...@auth/[email protected])

Updates `@prisma/adapter-pg` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/adapter-pg)

Updates `@prisma/client` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/client)

Updates `@prisma/client-runtime-utils` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/client-runtime-utils)

Updates `@sentry/nextjs` from 10.48.0 to 10.52.0
- [Release notes](https://github.com/getsentry/sentry-javascript/releases)
- [Changelog](https://github.com/getsentry/sentry-javascript/blob/develop/CHANGELOG.md)
- [Commits](https://github.com/getsentry/sentry-javascript/compare/10.48.0...10.52.0)

Updates `@supabase/supabase-js` from 2.100.1 to 2.105.4
- [Release notes](https://github.com/supabase/supabase-js/releases)
- [Changelog](https://github.com/supabase/supabase-js/blob/develop/packages/core/supabase-js/CHANGELOG.md)
- [Commits](https://github.com/supabase/supabase-js/commits/v2.105.4/packages/core/supabase-js)

Updates `cesium` from 1.139.1 to 1.141.0
- [Release notes](https://github.com/CesiumGS/cesium/releases)
- [Changelog](https://github.com/CesiumGS/cesium/blob/main/CHANGES.md)
- [Commits](https://github.com/CesiumGS/cesium/compare/1.139.1...1.141)

Updates `hls.js` from 1.6.15 to 1.6.16
- [Release notes](https://github.com/video-dev/hls.js/releases)
- [Changelog](https://github.com/video-dev/hls.js/blob/master/docs/release-process.md)
- [Commits](https://github.com/video-dev/hls.js/compare/v1.6.15...v1.6.16)

Updates `jose` from 6.2.2 to 6.2.3
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.2...v6.2.3)

Updates `next` from 16.2.3 to 16.2.6
- [Release notes](https://github.com/vercel/next.js/releases)
- [Changelog](https://github.com/vercel/next.js/blob/canary/release.js)
- [Commits](https://github.com/vercel/next.js/compare/v16.2.3...v16.2.6)

Updates `prisma` from 7.6.0 to 7.8.0
- [Release notes](https://github.com/prisma/prisma/releases)
- [Commits](https://github.com/prisma/prisma/commits/7.8.0/packages/cli)

Updates `react` from 19.2.3 to 19.2.6
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.6/packages/react)

Updates `react-dom` from 19.2.3 to 19.2.6
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.6/packages/react-dom)

Updates `resium` from 1.19.4 to 1.21.0
- [Release notes](https://github.com/reearth/resium/releases)
- [Changelog](https://github.com/reearth/resium/blob/main/CHANGELOG.md)
- [Commits](https://github.com/reearth/resium/compare/v1.19.4...v1.21.0)

Updates `zustand` from 5.0.12 to 5.0.13
- [Release notes](https://github.com/pmndrs/zustand/releases)
- [Commits](https://github.com/pmndrs/zustand/compare/v5.0.12...v5.0.13)

Updates `vite` from 8.0.8 to 8.0.11
- [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.11/packages/vite)

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

---
updated-dependencies:
- dependency-name: "@auth/prisma-adapter"
  dependency-version: 2.11.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: "@prisma/adapter-pg"
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@prisma/client"
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@prisma/client-runtime-utils"
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@sentry/nextjs"
  dependency-version: 10.52.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: "@supabase/supabase-js"
  dependency-version: 2.105.4
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: cesium
  dependency-version: 1.141.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: hls.js
  dependency-version: 1.6.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: jose
  dependency-version: 6.2.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: next
  dependency-version: 16.2.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: prisma
  dependency-version: 7.8.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: react
  dependency-version: 19.2.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: react-dom
  dependency-version: 19.2.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: resium
  dependency-version: 1.21.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependencies
- dependency-name: zustand
  dependency-version: 5.0.13
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vite
  dependency-version: 8.0.11
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependencies
- dependency-name: vitest
  dependency-version: 4.1.5
  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-10 11:10:16 +12:00
dependabot[bot] e917caf7f1 build(deps): bump docker/setup-buildx-action from 3 to 4 (#72)
Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 3 to 4.
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  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-10 11:10:11 +12:00
dependabot[bot] 6730aaff13 build(deps): bump actions/setup-node from 4 to 6 (#71)
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  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-10 11:10:07 +12:00
dependabot[bot] 7c1fce98bd build(deps): bump actions/checkout from 4 to 6 (#70)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  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-10 11:10:02 +12:00
GodisDeadxandnullptr 30bee799e1 modified: .gitignore (#65)
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

Co-authored-by: nullptr <[email protected]>
2026-05-10 11:06:55 +12:00
031a073cf9 fix(plugins): surface NEXT_PUBLIC_WWV_PLUGIN_* vars to plugin context (#60)
`PluginManager.registerPlugin` builds `ctx.env` for each plugin by iterating
`Object.entries(process.env)` and copying entries whose keys start with
`NEXT_PUBLIC_WWV_PLUGIN_`. In the browser bundle this loop comes back
empty even when those vars are set at build time, because Next.js only
inlines `process.env.NEXT_PUBLIC_*` at *static reference sites* — and
`Object.entries(process.env)` isn't a static reference. The result: any
plugin reading `ctx.env.SOMETHING` to override a default URL silently
gets `undefined` and falls back to its hardcoded cloud URL.

Concrete impact: setting `NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` to a
self-hosted data-engine URL has no effect on the marketplace plugins that
read `ctx.env.DATA_ENGINE_URL` (e.g. `wwv-plugin-aviation`) — they keep
calling `https://dataengine.worldwideview.dev/data/...` even when the
operator has explicitly redirected away from it.

Add explicit static references so the values land in `envVars`. Done as
a small allow-list (currently just `DATA_ENGINE_URL`) so adding new keys
is one line.

Also declare `ARG NEXT_PUBLIC_WWV_PLUGIN_DATA_ENGINE_URL` in the
Dockerfile next to the existing public-arg block. Without it, the build
arg passed in via compose isn't visible to Next.js at build time, so
Webpack inlines `undefined` even when the operator sets the env var.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:56 +12:00
43d6a057ba feat(analytics): make first-party analytics opt-in (default off) (#57)
The hosted Umami beacon at analytics.worldwideview.dev/script.js is
loaded unconditionally from src/app/layout.tsx, so every self-hosted
instance (anyone running this from GitHub) phones page-view and event
data home to the maintainer's analytics server. There is no env var,
no docs note, and no opt-out — operators discover the call only by
inspecting their browser's network tab.

Self-hosting is the default audience for an open-source project
distributed on GitHub. Defaulting telemetry on for that audience
silently routes their usage data to a third party they didn't choose
to send it to. Privacy posture aside, it's a surprise.

Gate the Umami script tag behind NEXT_PUBLIC_WWV_ANALYTICS === "true".
Default off — the maintainer's own hosted deployment can flip it on
explicitly via build env, status quo for that environment. Self-hosters
get no analytics by default and can opt in if they choose to.

This does not remove the integration, change Umami's website-id, or
alter the CSP allow-list. It only makes the script-tag conditional.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:51 +12:00
9c03edb65c feat(build): warn when NEXT_PUBLIC_CESIUM_ION_TOKEN is missing at build time (#55)
Self-hosters who skip Cesium Ion token setup get a globe that boots fine,
then 401s on world terrain and base imagery from `api.cesium.com`. The
cause is invisible — Cesium ships a default Ion token inside its npm
package that they periodically revoke when usage spikes — and most users
don't realize the build inlined an empty `NEXT_PUBLIC_CESIUM_ION_TOKEN`
until they're staring at network logs.

Add a `prebuild` step that prints an actionable warning (token name,
why it matters, where to get a free one) when the var is missing, so
the gap is surfaced when it can still be fixed cheaply. Non-fatal —
build continues — because demo and existing setups may legitimately
rely on the bundled default until it stops working for them.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:45 +12:00
9f1f39203e fix(proxy): detect secure cookie when behind TLS-terminating reverse proxy (#54)
When self-hosted behind a reverse proxy that terminates TLS (e.g. Caddy,
Nginx, Traefik), Auth.js sets the session cookie with the `__Secure-`
prefix because the public URL is https. The middleware's `getToken()` call,
however, sees a plain-http request internally and its auto-detection looks
for the unprefixed cookie name — which never exists — so authenticated
users are infinite-looped back to /login.

Detect the public scheme via X-Forwarded-Proto, AUTH_URL/NEXTAUTH_URL, or
the request URL's own protocol, and pass `secureCookie` explicitly to
getToken().

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:02:40 +12:00
9b459206d6 feat(camera): auto-refresh JPEG/MJPEG snapshot sources (#61)
Most state DOTs (NCDOT, WSDOT, GDOT, fallback HLS-failure paths from
Caltrans/511NY) serve traffic cameras as JPEG snapshots that update
server-side every 5–30 seconds rather than as continuous video streams.
The current `<img src={resolvedUrl}>` in `CameraStream.tsx` renders the
URL once and the browser caches the result — so the camera "loads" then
freezes on the first frame, which reads as broken even when the source
is fine.

Add a cache-busted refresh tick that increments every 10s while the
stream is playing and an image source is active. Skipped for HLS, iframe,
and known video platforms (they manage their own playback). Interval is
cleared when the stream stops, so no leaks on tab switch / pop-out.

The bumped query param is namespaced (`_t=`) and appended with the
correct separator depending on whether the source URL already has query
params (NCDOT's `?filename=...` pattern in particular).

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Co-authored-by: Silvertakana <[email protected]>
2026-05-10 11:01:50 +12:00
cd44a41c5d refactor(api/camera): adapter pattern + registry + selectable sources (#62)
The five existing camera fetchers (Caltrans, GDOT, TfL — and 511NY +
WSDOT, here introduced as adapters) follow the same shape — fetch from
upstream, normalize, return GeoJSON features — but each one is wired up
by hand: a fetcher file, often a route file, plus an entry in
`traffic/route.ts`'s `Promise.allSettled` block. Adding a new source
required surgery in three places, the shared type was named after the
first adapter (`GdotCameraFeature`), and the aggregator was take-it-or-
leave-it (no way to ask for a subset).

This PR introduces a small adapter pattern:

- `adapters/types.ts` defines `CameraFeature` (replacing the old
  `GdotCameraFeature` alias) and a `CameraAdapter` interface.
- `adapters/registry.ts` collects all adapters, manages per-adapter
  caching with overridable TTL, exposes `getAdapterMetadata()` for
  client-side discovery, and provides `fetchManyAdapters(ids)` for
  selective merging.
- `adapters/{caltrans,gdot,tfl,ny511,wsdot}.ts` are thin wrappers
  around the existing fetcher functions. The GDOT adapter additionally
  filters out URLs from the retired `navigator-c2c.dot.ga.gov` and
  `vss5live.dot.ga.gov` hosts so clients don't ERR_NAME_NOT_RESOLVED
  on click.
- 511NY (`/data/getcameras`, ~1,500 enabled cams w/ HLS) and WSDOT
  (`/HighwayCameras/.../GetCamerasAsJson`, ~1,600 cams + ~70 ODOT
  border crossings) are introduced here. WSDOT requires a key
  (`WSDOT_API_KEY`); the adapter declares this so the client can
  surface a "needs key, sign up here" hint.
- `traffic/route.ts` reads from the registry and accepts `?sources=`
  (comma-separated ids, "all", or "none"). Default behavior with no
  query is unchanged — all adapters merge — so existing clients
  continue working without modification.
- New `list/route.ts` returns adapter metadata for client-side source
  pickers (settings UIs that render dynamic checkboxes per source,
  including health/key-required state).
- Old `gdot/route.ts` removed (subsumed by the registry); the matching
  `gdotFetcher.ts` is retained so adapters can `import` from it.

After this lands, adding a new state's DOT to the system is one new
file in `adapters/` plus one line in `registry.ts`. No more
`traffic/route.ts` edits, no merge conflicts when two source PRs are
in flight, no plugin updates required (clients pick up new sources via
`/list`).

Supersedes the standalone 511NY (#58) and WSDOT (#59) PRs, which I've
closed; their fetchers and adapters land here as part of the cohesive
restructure.

Co-authored-by: Sapphire <sapphire@tiktokcoach>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-10 11:00:08 +12:00
dependabot[bot] 82cc79fa45 build(deps): bump node from 22-alpine to 26-alpine (#69)
Bumps node from 22-alpine to 26-alpine.

---
updated-dependencies:
- dependency-name: node
  dependency-version: 26-alpine
  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-10 10:57:40 +12:00
dependabot[bot] fdc722de51 build(deps): bump pnpm/action-setup from 4 to 6 (#68)
Bumps [pnpm/action-setup](https://github.com/pnpm/action-setup) from 4 to 6.
- [Release notes](https://github.com/pnpm/action-setup/releases)
- [Commits](https://github.com/pnpm/action-setup/compare/v4...v6)

---
updated-dependencies:
- dependency-name: pnpm/action-setup
  dependency-version: '6'
  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-10 10:57:35 +12:00
dependabot[bot] be692fadaa build(deps): bump docker/metadata-action from 5 to 6 (#67)
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5 to 6.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-version: '6'
  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-10 10:57:30 +12:00
Silvertakana eb12866d03 Configure Dependabot for multiple ecosystems
Added configurations for npm, Docker, and GitHub Actions updates.
2026-05-10 10:49:31 +12:00
Silvertakana c279b7c3d1 Revise SECURITY.md with support versions and reporting (#66)
Updated the security policy to include supported versions and reporting guidelines.
2026-05-10 10:46:03 +12:00
Antigravity AI b6d14dd720 docs(readme): enhance README with standard badges and architecture overview
- docs: added CI, Codecov, NPM, and Discord badges
- docs: added mermaid project architecture diagram
- docs: added key features, structure tree, and prerequisites
- chore: relocated old plan documents to .agents/plans
2026-05-10 10:30:57 +12:00
Antigravity AI 72f485f405 docs(agents): track all remaining agent rules 2026-05-10 10:14:29 +12:00
Antigravity AI 8f82310e3d docs(agents): update gitignore and add coding principles rule 2026-05-10 10:04:15 +12:00
Antigravity AI 3fe9edf6f3 checkout: temporary commit for worktree checkout 2026-05-10 09:51:44 +12:00
Antigravity AI 0156ead243 fix(deployment): resolve stale image issues and legacy migration commands
- Bump version to 2.1.6
- fix: update setup scripts to pull latest image before starting
- fix: set pull_policy to always in self-host compose file
- fix: auto-detect compose container for legacy migration script in setup UI
2026-05-10 01:20:22 +12:00
Antigravity AI 7bd6b32121 refactor: change default legacy DB path to data/wwv.db 2026-05-10 00:41:08 +12:00
Antigravity AI bc10b09788 fix: resolve undefined ID error when migrating settings from legacy SQLite 2026-05-10 00:40:29 +12:00
Antigravity AI 45c41fd2a0 refactor: update setup scripts to download docker-compose.yml and .env.example 2026-05-10 00:34:26 +12:00
Antigravity AI 78fb1dc484 fix(core): update legacy migration script and Dockerfile for Prisma 7 [Patch]
- fix migrate-legacy.mjs to use explicit pg adapter and accept db path arg [Patch]

- copy migrate-legacy.mjs to final docker image [Patch]
2026-05-10 00:06:33 +12:00
Antigravity AI 5fb36069ac fix(core): migrate changes and resolve cors issues [Patch]
- fix marketplace CORS by allowing x-marketplace-ping header [Patch]

- update setup page and docker entrypoint for legacy migrations [Patch]
2026-05-09 23:30:18 +12:00
Silvertakana c4207bd6e1 feat(core): migrate to Prisma 7 and unify PostgreSQL architecture (#56)
* feat(cloud): implement Postgres DB adapter, fix static build crashes, and containerize NextAuth/Stripe integrations

* test(marketplace): fix mocks and assertions for multi-tenant Postgres architecture

* feat: rsa jwt license key verification and state integration

* feat: add internal workspace validation route for Edge Functions

* refactor: clean up hub routes and finalize db proxy/adapter for multi-tenant cloud deploy

* feat(cloud): finalize multi-tenant Prisma extensions and workspace routing

* fix(db): correct Prisma 7 better-sqlite3 adapter initialization [Patch]

- update better-sqlite3 adapter instantiation to use configuration object ({ url }) required by Prisma 7 instead of raw Database instance [Patch]
- fix PrismaClientConstructorValidationError by generating client with adapter support [Patch]

* fix(auth): support dynamic origins for local proxies and multi-tenant subdomains [Patch]

- prioritize forwarded headers and request host over hardcoded envOrigin in getRequestOrigin to support subdomain routing [Patch]
- allow ALLOWED_DEV_ORIGIN in marketplace install redirect checks to fix local network development login flows [Patch]

* fix(marketplace): enable dynamic CORS reflection for marketplace API [Patch]

- remove explicit origin array, replacing with origin header reflection to allow marketplace hosted on any domain or local IP [Patch]

- remove global wildcard CORS headers from next.config.ts to harden security against broader app injection [Patch]

* feat(db): create initial postgresql migration

* refactor(db): update remaining files for postgresql

* feat(db): unify database adapter to PostgreSQL-only [Minor]

- replace SQLite adapter with PostgreSQL PrismaPg [Minor]
- remove better-sqlite3 dependencies [Patch]
- finalize docs and implementation plan [Patch]

* fix: resolve prisma client generation and script execution issues with tsx and type module

* feat(db): port tenant isolation logic to new PostgreSQL adapter

* docs: add rule for transparent and narrated agent actions

* BREAKING CHANGE(core): migrate to PostgreSQL and add auto-migration pipeline [Major]

- unified database adapter to exclusively use PostgreSQL [Major]
- implement auto-migration pipeline to pipe legacy SQLite data to Postgres [Major]
- add sqlite to runner stage to support extraction pipeline [Patch]

* feat(core): migrate to Prisma 7 and unify PostgreSQL architecture [Minor]

- removed legacy Prisma SQLite driver and all Better-Sqlite dependencies [Minor]
- updated schema to utilize purely postgresql providers [Patch]
- modified migration scripts to seamlessly convert local sqlite DBs to PostgreSQL containers using keinos/sqlite3 [Minor]
- updated deployment scripts, Coolify pipelines, and Nginx proxy support [Patch]
- injected Prisma Client Extensions for multi-tenant Row Level Security isolation [Minor]
- stabilized PrismaClient initialization utilizing the official adapter-pg runtime pattern [Patch]
- bumped version to 2.1.0

* fix(core): resolve TypeScript compilation errors for CI [Patch]

- fixed NextResponse.json() 3-arg calls to use 2-arg ResponseInit form [Patch]
- replaced invalid 'developer' TrustTier with 'unverified' in parseWwvManifest and load-unpacked route [Patch]
- removed non-existent pluginManager.hotReload() call in DevModeSubscriber, replaced with disable/reload cycle [Patch]
- updated Stripe API version from '2024-04-10' to '2026-04-22.dahlia' to match installed SDK [Patch]
- excluded local-scripts/ from tsconfig to prevent debug scripts from breaking CI [Patch]

* fix(ci): resolve pnpm version conflict in GitHub Actions [Patch]

- removed explicit version: 9 from pnpm/action-setup@v4 — v4 auto-reads packageManager from package.json [Patch]
- updated build job DATABASE_URL from SQLite to PostgreSQL format [Patch]

* fix(docker): add explicit Prisma generator output path for Docker builds [Patch]

- Prisma 7 changed default output location, causing COPY --from=builder to fail
- added output = '../src/generated/prisma' to generator block for consistency

* fix(prisma): update client import path and resolve CI type errors [Patch]

- updated PrismaClient import in db.ts to point to custom generated output path
- resolved implicit 'any' error in marketplace check-updates route
- verified clean local build with tsc --noEmit

* chore(deps): sync Prisma versions to 7.6.0 [Patch]
2026-05-09 22:44:30 +12:00
Antigravity AI 9ae8e58380 fix(core): allow universal CORS access in marketplace [Patch]
- allow any origin in marketplace bridge to ensure universal connectivity [Patch]
- remove dead origin filter code [Patch]
- bump version to 1.20.5 [Patch]
2026-05-09 15:45:33 +12:00
Antigravity AI 91e09ff53a fix(core): install prisma globally in docker to prevent offline network failures [Patch] 2026-05-09 15:39:24 +12:00
Silvertakana 138ea6c721 feat: local Docker HTTPS proxy for Firefox marketplace bridge compatibility (#50)
* feat: implement local docker HTTPS proxy for marketplace bridge

Generates self-signed certs automatically in docker-entrypoint and spins up a native Node HTTPS proxy on port 3001 to resolve Firefox Mixed Content blocks when fetching from local containers via the live marketplace.

* fix(core): fix docker build and marketplace origin parsing [Patch]

- fix pnpm run generate script failure in Dockerfile [Patch]
- implement robust origin parsing for marketplace endpoints [Patch]
2026-05-09 11:02:46 +12:00
Antigravity AI dc10e8ad5c fix(build): downgrade pnpm to v9.15.4 to bypass v10 strict script approvals 2026-05-09 10:13:08 +12:00
Antigravity AI 84f694f93b chore: approve sentry/cli build script to fix docker build 2026-05-09 10:07:22 +12:00
Antigravity AI fa60f845c1 chore: update lockfile for version bump 2026-05-09 09:59:31 +12:00
Antigravity AI 6e3a8ab625 fix(cors): allow permissive CORS and private network access 2026-05-09 09:55:16 +12:00
Antigravity AI 739bffa05b fix: trigger vercel deployment after correcting git email 2026-05-08 14:20:42 +12:00
SilvertakanaandAntigravity AI 9888f11a4b feat(ui): add layer search and right panel deselection persistence (#47)
* feat(ui): add layer search and persist right panel on deselection

* feat(ui): add resizable drag handles to both sidebars

* feat(ui): dynamic toggle button positioning during panel resize

* fix(ui): instantly follow cursor during panel resize without transition delay

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-05-01 22:29:04 +12:00
SilvertakanaandAntigravity AI 7354b414e7 fix: Enlarge panel pull tab trigger areas (#46)
* fix: enlarge panel pull tab trigger areas for better touch targets

* fix: extend trigger area further inward towards panels

* fix(globe): increase mobile pinch zoom sensitivity [Patch]

- decrease _zoomFactor to 5 to make pinch zooming more responsive on touch devices [Patch]
- conditionally allow dev origins in next config [Patch]

---------

Co-authored-by: Antigravity AI <[email protected]>
2026-04-29 23:59:52 +12:00
SilvertakanaandAntigravity AI 196380c0af fix: resolve GlitchTip crashes in core components (#44)
Co-authored-by: Antigravity AI <[email protected]>
2026-04-29 12:43:45 +12:00
135 changed files with 7009 additions and 2264 deletions

No files matched your search

@@ -0,0 +1,118 @@
# Persistent Custom OSM Tags Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Allow users to persistently save custom OSM tags to local storage so they remain available across sessions, and track their usage via Umami analytics.
**Architecture:** We will use `useState` and `useEffect` in the `OSMSidebar` component to sync `customTags` to the browser's `localStorage`. When the user enters a custom tag, we'll store it, render it with a small delete button (so the list doesn't get cluttered over time), and fire an event to `window.umami.track`.
**Tech Stack:** React Hooks, `localStorage`, Umami Analytics
---
### Task 1: Add Custom Tag State and Persistence
**Files:**
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-plugin-osm-search\src\components\OSMSidebar.tsx`
- [ ] **Step 1: Add customTags state and persistence effects**
In `OSMSidebar.tsx`, below the existing `const [activeTags, setActiveTags] = useState<string[]>([]);` line, add:
```tsx
const [customTags, setCustomTags] = useState<string[]>([]);
React.useEffect(() => {
try {
const saved = localStorage.getItem("wwv_osm_custom_tags");
if (saved) setCustomTags(JSON.parse(saved));
} catch {}
}, []);
React.useEffect(() => {
localStorage.setItem("wwv_osm_custom_tags", JSON.stringify(customTags));
}, [customTags]);
```
- [ ] **Step 2: Include customTags in the rendered list**
Replace `const customTagMatch = searchText.includes("=") ? [searchText.trim()] : [];` and `const renderedTags = ...` with:
```tsx
const renderedTags = Array.from(new Set([...filteredCommon, ...dynamicTags, ...customTags]));
```
- [ ] **Step 3: Update Enter key handler to save tags and track**
Inside the `input`'s `onKeyDown` handler:
```tsx
onKeyDown={e => {
if (e.key === "Enter" && searchText.includes("=")) {
const tag = searchText.trim();
if (!activeTags.includes(tag)) {
setActiveTags(prev => [...prev, tag]);
}
if (!customTags.includes(tag)) {
setCustomTags(prev => [...prev, tag]);
try {
(window as any).umami?.track("osm-search-custom-tag", { tag });
} catch {}
}
setSearchText("");
}
}}
```
- [ ] **Step 4: Add a delete button to custom tags**
Inside the `.map(tag => {` block, update the `button` contents to include a delete span if it's a custom tag:
```tsx
<button
key={tag}
style={{
background: isActive ? "var(--accent-blue)" : "rgba(255,255,255,0.05)",
color: isActive ? "#fff" : "var(--text-secondary)",
padding: "4px 10px",
borderRadius: "14px",
border: `1px solid ${isActive ? "transparent" : "rgba(255,255,255,0.1)"}`,
fontSize: "11px",
cursor: "pointer",
transition: "all 0.2s",
display: "flex",
alignItems: "center",
gap: "4px"
}}
onClick={() => setActiveTags(prev => prev.includes(tag) ? prev.filter(t=>t!==tag) : [...prev, tag])}
>
{tag.replace("=", ": ")}
{customTags.includes(tag) && (
<span
onClick={(e) => {
e.stopPropagation();
setCustomTags(prev => prev.filter(t => t !== tag));
setActiveTags(prev => prev.filter(t => t !== tag));
}}
style={{
marginLeft: "2px",
padding: "0 4px",
borderRadius: "50%",
background: "rgba(255,255,255,0.15)",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
×
</span>
)}
</button>
```
- [ ] **Step 5: Commit changes**
```bash
git add packages/wwv-plugin-osm-search/src/components/OSMSidebar.tsx
git commit -m "feat(osm-search): persist custom tags and track via umami"
```
@@ -0,0 +1,132 @@
# Robust Plugin Linking Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Ensure that when developers link local plugins using `wwv-cli link`, the main engine's database is automatically updated to prioritize the local code instead of accidentally loading the published version from the cloud CDN.
**Architecture:** We will implement a dedicated development API route in the main app (`/api/plugins/dev-link`) that allows the `wwv-cli` to safely push local plugin manifests directly into the `InstalledPlugin` database table without requiring Marketplace authentication. The CLI will be updated to make this request immediately after copying the bundle.
**Tech Stack:** Next.js API Routes, Prisma, Node.js `fetch`
---
### Task 1: Create the Dev-Link API Route
**Files:**
- Create: `c:\dev\worldwideview\src\app\api\plugins\dev-link\route.ts`
- [ ] **Step 1: Write the API Route**
```typescript
import { NextResponse } from "next/server";
import { upsertPlugin } from "@/lib/marketplace/repository";
import { validateManifest } from "@/core/plugins/validateManifest";
import { isPluginInstallEnabled } from "@/core/edition";
export async function POST(request: Request) {
// 1. Security Check: Only allow in development mode or local editions
if (process.env.NODE_ENV !== "development" && !isPluginInstallEnabled) {
return NextResponse.json({ error: "Dev-link is only available in development environments" }, { status: 403 });
}
try {
const body = await request.json();
const { manifest } = body;
if (!manifest || !manifest.id) {
return NextResponse.json({ error: "Invalid payload. 'manifest' with an 'id' is required." }, { status: 400 });
}
// 2. Validate the manifest
const validation = validateManifest(manifest);
if (!validation.valid) {
console.error(`[Dev-Link] Invalid manifest for ${manifest.id}:`, validation.errors);
return NextResponse.json({ error: "Invalid manifest", details: validation.errors }, { status: 400 });
}
// 3. Upsert into database
const config = JSON.stringify(manifest);
const record = await upsertPlugin(manifest.id, manifest.version || "1.0.0", config);
console.log(`[Dev-Link] Successfully synced local plugin config for: ${manifest.id}`);
return NextResponse.json({ success: true, pluginId: record.pluginId });
} catch (err) {
console.error("[Dev-Link] Server Error:", err);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
```
- [ ] **Step 2: Commit API Route**
```bash
git add src/app/api/plugins/dev-link/route.ts
git commit -m "feat(api): add dev-link route to sync local plugin manifests"
```
### Task 2: Update the CLI Link Command
**Files:**
- Modify: `c:\dev\worldwideview-plugins\packages\wwv-cli\src\commands\link.ts`
- [ ] **Step 1: Add the sync request to linkCommand**
Find the `linkCommand` function. Below the `fs.writeFileSync` that writes `plugin.json` (around line 67), add a network request to sync the database.
```typescript
fs.writeFileSync(path.join(finalDestDir, 'plugin.json'), JSON.stringify(manifest, null, 2));
console.log(green(`✅ Proxy manifest injected to WWV instance: ${pluginId}`));
// --- NEW CODE: Sync with database ---
fetch('http://localhost:3000/api/plugins/dev-link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ manifest })
})
.then(res => res.json())
.then(data => {
if (data.success) {
console.log(green(`✅ Database successfully synced to point to local files.`));
} else {
console.log(red(`⚠️ Warning: Database sync failed: ${data.error}`));
}
})
.catch(err => {
console.log(red(`⚠️ Warning: Could not reach dev server to sync DB. Is localhost:3000 running?`));
});
// --- END NEW CODE ---
```
- [ ] **Step 2: Rebuild the CLI**
```bash
cd packages/wwv-cli
pnpm build
```
- [ ] **Step 3: Commit CLI Update**
```bash
git add packages/wwv-cli/src/commands/link.ts
git commit -m "feat(cli): auto-sync local plugin manifests with engine database during link"
```
### Task 3: Test the Integration
- [ ] **Step 1: Run the Sync Command**
Run the updated sync command in the plugins repo to verify it pushes the manifest properly to the API.
```bash
cd c:\dev\worldwideview-plugins
pnpm run sync:all
```
- [ ] **Step 2: Verify Output**
Expected output in the plugins terminal should include:
`[wwv-plugin-osm-search] ✅ Database successfully synced to point to local files.`
Expected output in the main WorldWideView terminal should include:
`[Dev-Link] Successfully synced local plugin config for: osm-search`
@@ -0,0 +1,105 @@
# Phase 1: Database Adapter Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Modify Prisma schema and client initialization to support both SQLite (local/demo) and PostgreSQL (cloud).
**Architecture:** We use a pre-generation script to swap the Prisma provider based on `NEXT_PUBLIC_WWV_EDITION`. Abstract `src/lib/db.ts` to inject the correct adapter (better-sqlite3 vs pg) based on the edition.
**Tech Stack:** Prisma, PostgreSQL, SQLite.
---
### Task 1: Create Schema Swap Script
**Files:**
- Create: `scripts/prepare-schema.mjs`
- Modify: `package.json`
- [ ] **Step 1: Create a schema swap script**
```javascript
// scripts/prepare-schema.mjs
import fs from 'fs';
import path from 'path';
const schemaPath = path.join(process.cwd(), 'prisma', 'schema.prisma');
let schema = fs.readFileSync(schemaPath, 'utf-8');
if (process.env.NEXT_PUBLIC_WWV_EDITION === 'cloud') {
schema = schema.replace(/provider\s*=\s*"sqlite"/, 'provider = "postgresql"');
console.log("Swapped Prisma provider to PostgreSQL for cloud edition.");
} else {
// Revert back to sqlite just in case it was swapped
schema = schema.replace(/provider\s*=\s*"postgresql"/, 'provider = "sqlite"');
}
fs.writeFileSync(schemaPath, schema);
```
- [ ] **Step 2: Update package.json scripts**
Modify `package.json` to run the prepare script before prisma generate:
```json
"pregenerate": "node scripts/prepare-schema.mjs",
"generate": "prisma generate"
```
### Task 2: Create DB Adapter Factory
**Files:**
- Modify: `src/lib/db.ts`
- Create: `src/core/adapters/db.ts`
- [ ] **Step 1: Create the adapter factory**
```typescript
// src/core/adapters/db.ts
import { isCloud } from "@/core/edition";
import { PrismaClient } from "../../generated/prisma/client";
export function createPrismaClient(): PrismaClient {
if (isCloud) {
// Cloud uses native pg driver or connection pool via standard url
return new PrismaClient({
datasources: {
db: {
url: process.env.DATABASE_URL,
},
},
});
} else {
// Local uses better-sqlite3 adapter (already set up)
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || "file:./data/wwv.db",
});
return new PrismaClient({ adapter });
}
}
```
- [ ] **Step 2: Refactor `src/lib/db.ts`**
```typescript
// src/lib/db.ts
import { PrismaClient } from "../generated/prisma/client";
import { createPrismaClient } from "@/core/adapters/db";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
```
- [ ] **Step 3: Commit**
```bash
git add package.json scripts/ src/lib/ src/core/adapters/
git commit -m "feat: multi-provider database adapter for cloud"
```
@@ -0,0 +1,152 @@
# Phase 2: Tenant System Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement single-container multi-tenancy using PostgreSQL Row-Level Security (RLS) and Next.js middleware to resolve subdomains.
**Architecture:** Middleware extracts the subdomain (e.g., `acme.app.worldwideview.dev`) and sets an `x-tenant-id` header. Prisma extension wraps all queries to `SET LOCAL app.tenant_id = '...'` to enforce RLS in PostgreSQL.
**Tech Stack:** Next.js Middleware, Prisma Client Extensions, PostgreSQL RLS.
---
### Task 1: Database Schema Tenant Column
**Files:**
- Modify: `prisma/schema.prisma`
- [ ] **Step 1: Add tenant columns to models**
Add `tenantId String?` to all relevant models (`InstalledPlugin`, `Favorite`, `Setting`).
For local SQLite, `tenantId` is ignored (null). For cloud, it's enforced via RLS.
```prisma
model InstalledPlugin {
id String @id @default(uuid())
tenantId String? // NULL for local, UUID for cloud
pluginId String
version String
config String @default("{}")
enabled Boolean @default(true)
installedAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([tenantId, pluginId]) // Replaces @@unique([pluginId])
@@map("installed_plugins")
}
model Setting {
id String @id @default(uuid())
tenantId String?
key String
value String
@@unique([tenantId, key])
@@map("settings")
}
```
- [ ] **Step 2: Update primary keys if needed**
Ensure `Setting` uses `id` as `@id` instead of `key` since `key` is no longer globally unique (it's unique per tenant).
- [ ] **Step 3: Commit**
```bash
git add prisma/schema.prisma
git commit -m "feat: add tenantId columns to schema"
```
### Task 2: Subdomain Middleware
**Files:**
- Modify: `src/middleware.ts` (or create if doesn't exist)
- [ ] **Step 1: Create Next.js middleware**
```typescript
// src/middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(req: NextRequest) {
const hostname = req.headers.get("host") || "";
// Extract subdomain if on cloud
if (process.env.NEXT_PUBLIC_WWV_EDITION === "cloud") {
const isApp = hostname.includes(".app.worldwideview.dev");
if (isApp) {
const subdomain = hostname.replace(".app.worldwideview.dev", "");
if (subdomain && subdomain !== "app") {
const res = NextResponse.next();
res.headers.set("x-tenant-subdomain", subdomain);
return res;
}
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api/auth|_next/static|_next/image|favicon.ico).*)"],
};
```
### Task 3: Prisma RLS Extension
**Files:**
- Modify: `src/core/adapters/db.ts`
- [ ] **Step 1: Wrap Prisma with RLS extension for Cloud**
Modify `createPrismaClient` to wrap the client if in cloud mode:
```typescript
// src/core/adapters/db.ts
import { isCloud } from "@/core/edition";
import { PrismaClient } from "../../generated/prisma/client";
import { headers } from "next/headers";
export function createPrismaClient() {
if (isCloud) {
const client = new PrismaClient({
datasources: { db: { url: process.env.DATABASE_URL } },
});
// Use Prisma Client Extension to inject RLS
return client.$extends({
query: {
$allModels: {
async $allOperations({ args, query }) {
const headersList = await headers();
const tenantSubdomain = headersList.get("x-tenant-subdomain");
if (tenantSubdomain) {
const [, result] = await client.$transaction([
client.$executeRaw`SELECT set_config('app.tenant_id', ${tenantSubdomain}, TRUE)`,
query(args),
]);
return result;
}
return query(args);
},
},
},
});
} else {
const { PrismaBetterSqlite3 } = require("@prisma/adapter-better-sqlite3");
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || "file:./data/wwv.db",
});
return new PrismaClient({ adapter });
}
}
```
- [ ] **Step 2: Commit**
```bash
git add src/middleware.ts src/core/adapters/db.ts
git commit -m "feat: multi-tenant middleware and RLS prisma extension"
```
@@ -0,0 +1,117 @@
# Phase 3: Auth Upgrade Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Integrate Supabase Auth for the cloud edition while maintaining the existing Credentials provider for the local edition.
**Architecture:** Use the NextAuth adapter pattern. Modify `src/lib/auth.ts` to dynamically include the Supabase provider and Supabase Adapter if `isCloud` is true.
**Tech Stack:** NextAuth v5, Supabase Auth.
---
### Task 1: Supabase Adapter Integration
**Files:**
- Modify: `src/lib/auth.ts`
- Modify: `package.json`
- [ ] **Step 1: Install Supabase NextAuth Adapter**
Run: `pnpm add @auth/supabase-adapter`
- [ ] **Step 2: Update `src/lib/auth.ts` to branch providers**
```typescript
// src/lib/auth.ts
import NextAuth from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { compareSync } from "bcryptjs";
import { timingSafeEqual } from "crypto";
import { prisma } from "@/lib/db";
import { isDemo, isCloud, getDemoAdminSecret, DEMO_ADMIN_ROLE } from "@/core/edition";
import { authConfig } from "@/lib/auth.config";
import { SupabaseAdapter } from "@auth/supabase-adapter";
// Extract local credentials logic to a helper
const localCredentialsProvider = Credentials({
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
// ... existing credentials logic ...
return null;
}
});
export const { handlers, auth, signIn, signOut } = NextAuth({
...authConfig,
session: { strategy: "jwt" },
adapter: isCloud ? SupabaseAdapter({
url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
secret: process.env.SUPABASE_SERVICE_ROLE_KEY!,
}) : undefined,
providers: isCloud
? [] // If using standard GoTrue via custom logic, or add providers here if using NextAuth OAuth
: [localCredentialsProvider],
callbacks: {
...authConfig.callbacks,
// ... existing callbacks ...
},
});
```
### Task 2: Login Form Cloud Adaptation
**Files:**
- Modify: `src/app/login/page.tsx`
- Modify: `src/app/login/actions.ts`
- [ ] **Step 1: Update Login Form for Cloud Mode**
```typescript
// src/app/login/actions.ts
import { signIn } from "@/lib/auth";
import { isCloud } from "@/core/edition";
import { createClient } from "@supabase/supabase-js";
export async function loginAction(formData: FormData) {
const email = formData.get("email") as string;
const password = formData.get("password") as string;
if (isCloud) {
// Use Supabase GoTrue
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
const { data, error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) return { success: false, error: error.message };
return { success: true };
} else {
// Use NextAuth Credentials
try {
await signIn("credentials", {
email,
password,
redirect: false,
});
return { success: true };
} catch (error: any) {
return { success: false, error: "Invalid credentials" };
}
}
}
```
- [ ] **Step 2: Commit**
```bash
git add package.json pnpm-lock.yaml src/lib/auth.ts src/app/login/actions.ts
git commit -m "feat: supabase auth adapter for cloud edition"
```
@@ -0,0 +1,99 @@
# Phase 4: License Keys & Tiers Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement RSA-signed JWT license keys to gate Pro and Enterprise features on both Local and Cloud editions.
**Architecture:** A hardcoded public key verifies the JWT. The JWT payload dictates the tier (`free`, `pro`, `enterprise`) and expiration. The `uiSlice` state provides easy access to the active tier.
**Tech Stack:** `jose` for JWT verification.
---
### Task 1: License Verification Module
**Files:**
- Create: `src/core/license/verifyLicense.ts`
- Create: `src/core/license/tiers.ts`
- [ ] **Step 1: Create Tier Definitions**
```typescript
// src/core/license/tiers.ts
export type LicenseTier = "free" | "pro" | "team" | "enterprise";
export interface TierFeatures {
maxUsers: number;
storageQuotaBytes: number;
historyEnabled: boolean;
snapshotCapture: boolean;
customDomains: boolean;
}
export const TIER_FEATURES: Record<LicenseTier, TierFeatures> = {
free: { maxUsers: 3, storageQuotaBytes: 500 * 1024 * 1024, historyEnabled: false, snapshotCapture: false, customDomains: false },
pro: { maxUsers: 20, storageQuotaBytes: 5 * 1024 * 1024 * 1024, historyEnabled: true, snapshotCapture: true, customDomains: false },
team: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: false },
enterprise: { maxUsers: -1, storageQuotaBytes: -1, historyEnabled: true, snapshotCapture: true, customDomains: true },
};
```
- [ ] **Step 2: Create JWT Verification**
```typescript
// src/core/license/verifyLicense.ts
import * as jose from "jose";
// Public key is safe to hardcode/ship to client
const PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu... (generate real one)
-----END PUBLIC KEY-----`;
export interface LicensePayload {
tier: "pro" | "team" | "enterprise";
exp: number;
org: string;
}
export async function verifyLicenseKey(token: string): Promise<LicensePayload | null> {
try {
const publicKey = await jose.importSPKI(PUBLIC_KEY_PEM, "RS256");
const { payload } = await jose.jwtVerify(token, publicKey);
return payload as unknown as LicensePayload;
} catch {
return null;
}
}
```
### Task 2: State Integration
**Files:**
- Modify: `src/core/state/configSlice.ts`
- Modify: `src/components/panels/SettingsPanel.tsx`
- [ ] **Step 1: Add license to configSlice**
```typescript
// src/core/state/configSlice.ts
// Add to DataConfig:
export interface DataConfig {
// ... existing ...
licenseKey: string | null;
activeTier: "free" | "pro" | "team" | "enterprise";
}
// Add to initial state:
// licenseKey: null, activeTier: "free"
```
- [ ] **Step 2: Add License input UI**
Add a text input in `SettingsPanel` for users to paste their license key, dispatching an action to verify and save it to the DB and Zustand store.
- [ ] **Step 3: Commit**
```bash
git add src/core/license/ src/core/state/configSlice.ts src/components/panels/
git commit -m "feat: rsa jwt license key verification"
```
@@ -0,0 +1,76 @@
# Phase 5: Cloud Deployment Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Create the Docker Compose configuration and routing layer necessary to run the multi-tenant cloud application.
**Architecture:** Use Traefik or nginx to route wildcard subdomains to the Next.js container. Provide environment variable overrides.
**Tech Stack:** Docker Compose, Traefik.
---
### Task 1: Docker Compose Setup
**Files:**
- Create: `deploy/cloud/docker-compose.yml`
- Create: `deploy/cloud/.env.example`
- [ ] **Step 1: Create compose file**
```yaml
# deploy/cloud/docker-compose.yml
services:
wwv-cloud:
image: ghcr.io/silvertakana/worldwideview:latest
restart: always
environment:
NEXT_PUBLIC_WWV_EDITION: cloud
DATABASE_URL: ${SUPABASE_PG_URL}
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY}
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY}
labels:
- "traefik.enable=true"
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`)"
- "traefik.http.routers.wwv.entrypoints=websecure"
- "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
traefik:
image: traefik:v3.0
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
- "--certificatesresolvers.letsencrypt.acme.tlschallenge=true"
- "--certificatesresolvers.letsencrypt.acme.email=${ACME_EMAIL}"
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
- "letsencrypt:/letsencrypt"
volumes:
letsencrypt:
```
- [ ] **Step 2: Create example env file**
```env
# deploy/cloud/.env.example
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
SUPABASE_URL=https://xyz.supabase.co
SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
ACME_EMAIL=[email protected]
```
- [ ] **Step 3: Commit**
```bash
git add deploy/
git commit -m "chore: add cloud deployment compose configuration"
```
@@ -0,0 +1,77 @@
# Phase 6: Stripe Billing Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Implement Stripe subscriptions for the cloud edition, generating license keys upon payment.
**Architecture:** Use Stripe Checkout Sessions for upgrades. Use Stripe Webhooks to listen for `checkout.session.completed` and `customer.subscription.updated` to update the user's tier in the database and generate their JWT license key.
**Tech Stack:** Stripe Node SDK, Next.js API Routes.
---
### Task 1: Stripe Integration
**Files:**
- Modify: `package.json`
- Create: `src/lib/stripe/client.ts`
- Create: `src/app/api/billing/webhook/route.ts`
- Create: `src/app/api/billing/checkout/route.ts`
- [ ] **Step 1: Install SDK**
Run: `pnpm add stripe`
- [ ] **Step 2: Create Stripe Client**
```typescript
// src/lib/stripe/client.ts
import Stripe from "stripe";
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2024-04-10",
});
```
- [ ] **Step 3: Create Checkout Route**
```typescript
// src/app/api/billing/checkout/route.ts
import { stripe } from "@/lib/stripe/client";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
export async function POST(req: Request) {
const session = await auth();
if (!session?.user) return new NextResponse("Unauthorized", { status: 401 });
const { priceId } = await req.json();
const checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?success=true`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?canceled=true`,
client_reference_id: session.user.id,
});
return NextResponse.json({ url: checkoutSession.url });
}
```
- [ ] **Step 4: Create Webhook Handler**
```typescript
// src/app/api/billing/webhook/route.ts
import { stripe } from "@/lib/stripe/client";
import { NextResponse } from "next/server";
// ... basic webhook payload verification and logging ...
```
- [ ] **Step 5: Commit**
```bash
git add package.json pnpm-lock.yaml src/lib/stripe/ src/app/api/billing/
git commit -m "feat: stripe checkout and webhook integration"
```
@@ -0,0 +1,51 @@
# Cloud Hosting & Plans — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Transform WorldWideView from a local-only SQLite app into a multi-tenant cloud platform with `[user].app.worldwideview.dev` subdomains, PostgreSQL RLS isolation, Supabase Auth, cryptographic license keys, and Stripe billing.
**Architecture:** Single Docker container serves all tenants. nginx wildcard routes `*.app.worldwideview.dev` → Next.js. Middleware reads subdomain → sets `tenant_id` → PostgreSQL RLS scopes all queries. Same codebase, three editions (`local`/`cloud`/`demo`), adapter pattern for DB/auth/storage/tenant.
**Tech Stack:** Next.js 16, Prisma (multi-provider), PostgreSQL + RLS, Supabase Auth, Supabase Storage, RSA-signed JWTs (license keys), Stripe Checkout + Webhooks, nginx wildcard SSL.
---
## Current State Summary
| Component | Status |
|---|---|
| Edition system (`edition.ts`) | ✅ `local`/`cloud`/`demo` flags exist |
| Auth (`src/lib/auth.ts`) | ✅ Credentials provider (bcrypt + SQLite) |
| Database (`src/lib/db.ts`) | ⚠️ Hardcoded to `better-sqlite3` adapter |
| Prisma schema | ⚠️ `provider = "sqlite"` only |
| Tenant isolation | ❌ Not implemented |
| Cloud auth (Supabase) | ❌ Not implemented |
| License keys | ❌ Not implemented |
| Storage adapter | ❌ Not implemented |
| Stripe billing | ❌ Not implemented |
| Cloud deployment repo | ❌ Not created |
---
## Phase Breakdown
Each phase is a self-contained deliverable. Phases 1–3 are foundational. Phases 4–6 add monetization.
| Phase | File | What It Builds | Depends On |
|---|---|---|---|
| 1 | [01-database-adapter.md](./01-database-adapter.md) | Prisma multi-provider (SQLite + PostgreSQL) | Nothing |
| 2 | [02-tenant-system.md](./02-tenant-system.md) | RLS isolation, middleware, tenant context | Phase 1 |
| 3 | [03-auth-upgrade.md](./03-auth-upgrade.md) | Supabase Auth provider for cloud edition | Phase 1 |
| 4 | [04-license-keys.md](./04-license-keys.md) | RSA-signed JWT license keys, tier gating | Phase 1 |
| 5 | [05-cloud-deployment.md](./05-cloud-deployment.md) | `worldwideview-cloud` repo, nginx, Docker Compose | Phases 1–3 |
| 6 | [06-stripe-billing.md](./06-stripe-billing.md) | Stripe Checkout, webhooks, subscription management | Phases 3–4 |
---
## Key Design Decisions
1. **Adapter pattern** — Three thin files (`src/core/adapters/db.ts`, `auth.ts`, `storage.ts`, `tenant.ts`) branch on `edition`. Everything else is edition-unaware.
2. **Prisma multi-provider** — Use a build-time script to swap the provider in `schema.prisma` before generating the client if building for cloud. One schema, two providers.
3. **RLS over application-level filtering** — PostgreSQL physically refuses cross-tenant data. Even bugs can't leak.
4. **License keys are RSA JWTs** — Marketplace signs with private key; app verifies with hardcoded public key. No phone-home required.
5. **Stripe is the only payment processor** — Checkout Sessions for signup, Webhooks for lifecycle events.
@@ -0,0 +1,533 @@
# WorldWideView CLI Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Build `@worldwideview/cli`, a standalone CLI tool that scaffolds, hot-reloads, and packages WWV plugins using the Chrome Extension model, completely decoupled from the main monorepo build pipeline.
**Architecture:** A Node.js CLI built with `commander`. It uses `vite` programmatically to serve and build plugins. For dev mode, it attaches a `ws` WebSocket server to the Vite dev server to broadcast hot-reload events to the running WWV web app, and communicates with `/api/dev/load-unpacked` to inject the plugin. Publishing creates a `.wwvpkg` ZIP archive via `archiver`.
**Tech Stack:** Node.js, TypeScript, Commander, Vite, WebSocket (`ws`), Archiver, Vitest.
---
### Task 1: Initialize Package & CLI Entry Point
**Files:**
- Create: `packages/wwv-cli/package.json`
- Create: `packages/wwv-cli/tsconfig.json`
- Create: `packages/wwv-cli/bin/wwv.js`
- Create: `packages/wwv-cli/src/index.ts`
- Create: `packages/wwv-cli/tests/index.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/index.test.ts
import { describe, it, expect } from "vitest";
import { execSync } from "child_process";
import path from "path";
describe("wwv cli", () => {
it("should print help information", () => {
const binPath = path.resolve(__dirname, "../bin/wwv.js");
const output = execSync(`node ${binPath} --help`).toString();
expect(output).toContain("Usage: wwv [options] [command]");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test`
Expected: FAIL (File not found or missing package.json setup)
- [ ] **Step 3: Write minimal implementation**
```json
// packages/wwv-cli/package.json
{
"name": "@worldwideview/cli",
"version": "1.0.0",
"bin": { "wwv": "./bin/wwv.js" },
"scripts": {
"build": "tsc",
"test": "vitest run"
},
"dependencies": {
"commander": "^11.1.0"
},
"devDependencies": {
"typescript": "^5.0.0",
"vitest": "^1.0.0",
"@types/node": "^20.0.0"
}
}
```
```json
// packages/wwv-cli/tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"]
}
```
```javascript
// packages/wwv-cli/bin/wwv.js
#!/usr/bin/env node
require('../dist/index.js');
```
```typescript
// packages/wwv-cli/src/index.ts
import { Command } from "commander";
const program = new Command();
program
.name("wwv")
.description("WorldWideView Plugin CLI")
.version("1.0.0");
program.parse();
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm install && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): initialize cli package and entry point"
```
---
### Task 2: Implement `wwv create` (Scaffolding)
**Files:**
- Create: `packages/wwv-cli/src/commands/create.ts`
- Create: `packages/wwv-cli/tests/create.test.ts`
- Modify: `packages/wwv-cli/src/index.ts:10-15`
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/create.test.ts
import { describe, it, expect, afterEach } from "vitest";
import { createPlugin } from "../src/commands/create";
import fs from "fs";
import path from "path";
describe("create command", () => {
const testDir = path.join(__dirname, "test-plugin");
afterEach(() => {
if (fs.existsSync(testDir)) fs.rmSync(testDir, { recursive: true, force: true });
});
it("should scaffold a new plugin folder with manifest and index.ts", async () => {
await createPlugin("test-plugin", __dirname);
expect(fs.existsSync(path.join(testDir, "wwv-manifest.json"))).toBe(true);
expect(fs.existsSync(path.join(testDir, "src", "index.ts"))).toBe(true);
const manifest = JSON.parse(fs.readFileSync(path.join(testDir, "wwv-manifest.json"), "utf-8"));
expect(manifest.id).toBe("test-plugin");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test tests/create.test.ts`
Expected: FAIL ("createPlugin is not defined")
- [ ] **Step 3: Write minimal implementation**
```typescript
// packages/wwv-cli/src/commands/create.ts
import fs from "fs";
import path from "path";
export async function createPlugin(name: string, basePath: string = process.cwd()) {
const targetDir = path.join(basePath, name);
if (fs.existsSync(targetDir)) {
throw new Error(`Directory ${name} already exists`);
}
fs.mkdirSync(targetDir, { recursive: true });
fs.mkdirSync(path.join(targetDir, "src"), { recursive: true });
const manifest = {
manifest_version: 1,
id: name,
name: name,
version: "1.0.0",
description: "A WorldWideView plugin",
type: "data-layer",
category: "custom",
icon: "Box",
capabilities: ["data:own"],
entry: "dist/frontend.mjs",
dev_entry: "src/index.ts"
};
fs.writeFileSync(
path.join(targetDir, "wwv-manifest.json"),
JSON.stringify(manifest, null, 2)
);
const indexContent = `export default class MyPlugin {
id = "${name}";
name = "${name}";
version = "1.0.0";
category = "custom";
icon = "Box";
async initialize(ctx) {
console.log("Initialized", this.id);
}
destroy() {}
async fetch(timeRange) {
return [];
}
getPollingInterval() {
return 5000;
}
getLayerConfig() {
return { color: "#3b82f6", clusterEnabled: true, clusterDistance: 50 };
}
renderEntity(entity) {
return { type: "point", color: "#3b82f6", size: 6 };
}
}
`;
fs.writeFileSync(path.join(targetDir, "src", "index.ts"), indexContent);
console.log(`Plugin ${name} scaffolded successfully in ./${name}`);
}
```
```typescript
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
import { createPlugin } from "./commands/create";
program
.command("create <name>")
.description("Scaffold a new WorldWideView plugin")
.action(async (name) => {
try {
await createPlugin(name);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): implement create command for scaffolding"
```
---
### Task 3: Implement `wwv dev` (Vite Server + WebSocket)
**Files:**
- Create: `packages/wwv-cli/src/commands/dev.ts`
- Create: `packages/wwv-cli/tests/dev.test.ts`
- Modify: `packages/wwv-cli/src/index.ts:25-30`
- Modify: `packages/wwv-cli/package.json:13-15` (Add vite, ws)
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/dev.test.ts
import { describe, it, expect, vi } from "vitest";
import { startDevServer } from "../src/commands/dev";
// Mock vite and ws
vi.mock("vite", () => ({
createServer: vi.fn().mockResolvedValue({
listen: vi.fn(),
httpServer: { on: vi.fn() },
ws: { on: vi.fn() }
})
}));
describe("dev command", () => {
it("should export startDevServer function", () => {
expect(typeof startDevServer).toBe("function");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test tests/dev.test.ts`
Expected: FAIL ("startDevServer is not defined")
- [ ] **Step 3: Write minimal implementation**
Add `vite` and `ws` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
```json
"dependencies": {
"commander": "^11.1.0",
"vite": "^5.0.0",
"ws": "^8.16.0"
},
"devDependencies": {
"@types/ws": "^8.5.10"
}
```
```typescript
// packages/wwv-cli/src/commands/dev.ts
import fs from "fs";
import path from "path";
import { createServer } from "vite";
import { WebSocketServer } from "ws";
export async function startDevServer(targetUrl: string = "http://localhost:3000") {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
const port = 24601;
// Start Vite Dev Server
const vite = await createServer({
root: cwd,
server: { port, cors: true, hmr: false }, // We handle HMR via custom WS
plugins: [{
name: 'wwv-hmr',
handleHotUpdate({ server }) {
// When Vite detects file changes, broadcast to our custom WS
wss.clients.forEach(client => {
client.send(JSON.stringify({ type: "plugin:updated", pluginId: manifest.id }));
});
return []; // Prevent default Vite HMR
}
}]
});
await vite.listen();
// Attach custom WebSocket server for WWV DevModeSubscriber
const wss = new WebSocketServer({ server: vite.httpServer as any, path: "/__wwv_dev__" });
wss.on("connection", (ws) => {
console.log(`[WWV CLI] Connected to WorldWideView instance`);
ws.send(JSON.stringify({ type: "plugin:added", manifest }));
});
// Notify WorldWideView via API
try {
const fetch = (await import('node-fetch')).default || globalThis.fetch;
await fetch(`${targetUrl}/api/dev/load-unpacked`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...manifest,
entry: `http://localhost:${port}/${manifest.dev_entry || "src/index.ts"}`
})
});
console.log(`[WWV CLI] Registered with WorldWideView at ${targetUrl}`);
} catch (err: any) {
console.error(`[WWV CLI] Failed to connect to ${targetUrl}: ${err.message}`);
console.log(`Waiting for WorldWideView to connect via WebSocket...`);
}
console.log(`\n🚀 Dev server running on http://localhost:${port}`);
console.log(`Watching for file changes in ${cwd}...\n`);
}
```
```typescript
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
import { startDevServer } from "./commands/dev";
program
.command("dev")
.description("Start the plugin development server with hot-reload")
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
.action(async (options) => {
try {
await startDevServer(options.target);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): implement dev command with vite and websockets"
```
---
### Task 4: Implement `wwv publish` (.wwvpkg creation)
**Files:**
- Create: `packages/wwv-cli/src/commands/publish.ts`
- Create: `packages/wwv-cli/tests/publish.test.ts`
- Modify: `packages/wwv-cli/src/index.ts:40-45`
- Modify: `packages/wwv-cli/package.json:16-17` (Add archiver)
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/publish.test.ts
import { describe, it, expect } from "vitest";
import { buildPackage } from "../src/commands/publish";
describe("publish command", () => {
it("should export buildPackage function", () => {
expect(typeof buildPackage).toBe("function");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `cd packages/wwv-cli && pnpm test tests/publish.test.ts`
Expected: FAIL ("buildPackage is not defined")
- [ ] **Step 3: Write minimal implementation**
Add `archiver` to dependencies in `packages/wwv-cli/package.json` and run `pnpm install`:
```json
"dependencies": {
"archiver": "^7.0.1"
},
"devDependencies": {
"@types/archiver": "^6.0.2"
}
```
```typescript
// packages/wwv-cli/src/commands/publish.ts
import fs from "fs";
import path from "path";
import { build } from "vite";
import archiver from "archiver";
export async function buildPackage() {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
console.log(`[WWV CLI] Building production bundle...`);
await build({
root: cwd,
build: {
lib: {
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
name: 'WWVPlugin',
formats: ['es'],
fileName: () => 'frontend.mjs'
},
outDir: 'dist',
emptyOutDir: true
}
});
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
const outputPath = path.join(cwd, pkgName);
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const archive = archiver("zip", { zlib: { level: 9 } });
output.on("close", () => resolve());
archive.on("error", (err) => reject(err));
archive.pipe(output);
archive.file(manifestPath, { name: "wwv-manifest.json" });
archive.directory(path.join(cwd, "dist"), "dist");
if (fs.existsSync(path.join(cwd, "data"))) {
archive.directory(path.join(cwd, "data"), "data");
}
archive.finalize();
});
console.log(`\n🎉 Success! Package created at ${outputPath}`);
console.log(`You can now upload this file to the WorldWideView Marketplace.`);
}
```
```typescript
// Modify packages/wwv-cli/src/index.ts (add this before program.parse())
import { buildPackage } from "./commands/publish";
program
.command("publish")
.description("Build and package the plugin into a .wwvpkg file")
.action(async () => {
try {
await buildPackage();
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
```
- [ ] **Step 4: Run test to verify it passes**
Run: `cd packages/wwv-cli && pnpm run build && pnpm test`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli
git commit -m "feat(wwv-cli): implement publish command for wwvpkg creation"
```
@@ -0,0 +1,323 @@
# Split CLI Publish into Package and Publish Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Split the CLI publish command into `package` (for local .wwvpkg zip creation) and `publish` (for NPM distribution and marketplace registry updates).
**Architecture:**
The current `publish` command creates a `.wwvpkg` file. We will rename this functionality to the `package` command. Then, we will create a true `publish` command that handles building the plugin, automatically generating a valid `package.json` from the `wwv-manifest.json`, running `npm publish` via a child process, and finally notifying the marketplace of the new release.
**Tech Stack:** TypeScript, Vite, Node.js `child_process`, Node.js `fs`.
---
### Task 1: Rename current publish to package
We will rename the file and its internal function from `buildPackage` to `packagePlugin`.
**Files:**
- Modify: `packages/wwv-cli/src/commands/publish.ts` -> rename to `packages/wwv-cli/src/commands/package.ts`
- Modify: `packages/wwv-cli/tests/publish.test.ts` -> rename to `packages/wwv-cli/tests/package.test.ts`
- [ ] **Step 1: Rename the command file and update function name**
```typescript
// packages/wwv-cli/src/commands/package.ts
import fs from "fs";
import path from "path";
import { build } from "vite";
import archiver from "archiver";
export async function packagePlugin() {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
console.log(`[WWV CLI] Building production bundle...`);
await build({
root: cwd,
build: {
lib: {
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
name: 'WWVPlugin',
formats: ['es'],
fileName: () => 'frontend.mjs'
},
outDir: 'dist',
emptyOutDir: true
}
});
const pkgName = `${manifest.id}-${manifest.version}.wwvpkg`;
const outputPath = path.join(cwd, pkgName);
console.log(`[WWV CLI] Creating archive ${pkgName}...`);
await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const archive = archiver("zip", { zlib: { level: 9 } });
output.on("close", () => resolve());
archive.on("error", (err) => reject(err));
archive.pipe(output);
archive.file(manifestPath, { name: "wwv-manifest.json" });
archive.directory(path.join(cwd, "dist"), "dist");
if (fs.existsSync(path.join(cwd, "data"))) {
archive.directory(path.join(cwd, "data"), "data");
}
archive.finalize();
});
console.log(`\n🎉 Success! Package created at ${outputPath}`);
console.log(`You can use this file to sideload the plugin into your WWV instance.`);
}
```
- [ ] **Step 2: Rename and update the test**
```typescript
// packages/wwv-cli/tests/package.test.ts
import { describe, it, expect } from "vitest";
import { packagePlugin } from "../src/commands/package";
describe("package command", () => {
it("should export packagePlugin function", () => {
expect(typeof packagePlugin).toBe("function");
});
});
```
- [ ] **Step 3: Remove old files**
Run: `git rm packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts`
Expected: Files deleted.
- [ ] **Step 4: Commit**
```bash
git add packages/wwv-cli/src/commands/package.ts packages/wwv-cli/tests/package.test.ts
git commit -m "refactor(wwv-cli): rename publish to package for wwvpkg creation"
```
---
### Task 2: Implement true NPM Publish command
**Files:**
- Create: `packages/wwv-cli/src/commands/publish.ts`
- Create: `packages/wwv-cli/tests/publish.test.ts`
- [ ] **Step 1: Write the failing test**
```typescript
// packages/wwv-cli/tests/publish.test.ts
import { describe, it, expect, vi } from "vitest";
import { publishToNpm } from "../src/commands/publish";
vi.mock("child_process", () => ({
execSync: vi.fn()
}));
vi.mock("vite", () => ({
build: vi.fn().mockResolvedValue({})
}));
describe("publish command", () => {
it("should export publishToNpm function", () => {
expect(typeof publishToNpm).toBe("function");
});
});
```
- [ ] **Step 2: Run test to verify it fails**
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
Expected: FAIL because `publishToNpm` does not exist.
- [ ] **Step 3: Write the publish implementation**
```typescript
// packages/wwv-cli/src/commands/publish.ts
import fs from "fs";
import path from "path";
import { build } from "vite";
import { execSync } from "child_process";
export async function publishToNpm() {
const cwd = process.cwd();
const manifestPath = path.join(cwd, "wwv-manifest.json");
if (!fs.existsSync(manifestPath)) {
throw new Error("No wwv-manifest.json found in current directory");
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
console.log(`[WWV CLI] Compiling bundle for NPM...`);
await build({
root: cwd,
build: {
lib: {
entry: path.resolve(cwd, manifest.dev_entry || "src/index.ts"),
name: 'WWVPlugin',
formats: ['es'],
fileName: () => 'frontend.mjs'
},
outDir: 'dist',
emptyOutDir: true
}
});
console.log(`[WWV CLI] Generating package.json...`);
// Create a temporary package.json required for NPM publish
const packageJsonPath = path.join(cwd, "package.json");
const packageJson = {
name: manifest.id, // e.g. @username/my-plugin
version: manifest.version,
description: manifest.description,
main: "dist/frontend.mjs",
type: "module",
files: ["dist", "wwv-manifest.json", "data"],
keywords: ["worldwideview", "plugin", manifest.category],
author: manifest.author || ""
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
console.log(`[WWV CLI] Publishing to NPM...`);
try {
execSync(`npm publish --access public`, { stdio: "inherit", cwd });
} catch (err) {
console.error(`[WWV CLI] NPM publish failed. Please ensure you are logged in via 'npm login'.`);
throw err;
} finally {
// Clean up the generated package.json so it doesn't clutter the dev's repo
fs.unlinkSync(packageJsonPath);
}
console.log(`[WWV CLI] Notifying WorldWideView Marketplace...`);
try {
const targetUrl = process.env.WWV_MARKETPLACE_URL || "https://marketplace.worldwideview.dev";
await fetch(`${targetUrl}/api/webhooks/npm-publish`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ pluginId: manifest.id, version: manifest.version })
});
console.log(`[WWV CLI] Marketplace notified.`);
} catch (err: any) {
console.warn(`[WWV CLI] Could not notify marketplace: ${err.message}. It will be indexed on the next sweep.`);
}
console.log(`\n🚀 Success! Version ${manifest.version} published globally to NPM.`);
}
```
- [ ] **Step 4: Run test to verify it passes**
Run: `pnpm test tests/publish.test.ts` inside `packages/wwv-cli`
Expected: PASS
- [ ] **Step 5: Commit**
```bash
git add packages/wwv-cli/src/commands/publish.ts packages/wwv-cli/tests/publish.test.ts
git commit -m "feat(wwv-cli): implement npm publish and marketplace webhook ping"
```
---
### Task 3: Update CLI Entry Point
**Files:**
- Modify: `packages/wwv-cli/src/index.ts:36-50`
- [ ] **Step 1: Write the updated entry point logic**
Replace the existing `publish` command logic with both `package` and `publish`:
```typescript
// Edit packages/wwv-cli/src/index.ts
import { Command } from "commander";
import { createPlugin } from "./commands/create";
import { startDevServer } from "./commands/dev";
import { packagePlugin } from "./commands/package";
import { publishToNpm } from "./commands/publish";
const program = new Command();
program
.name("wwv")
.description("WorldWideView Plugin CLI")
.version("1.0.0");
program
.command("create <name>")
.description("Scaffold a new WorldWideView plugin")
.action(async (name) => {
try {
await createPlugin(name);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program
.command("dev")
.description("Start the plugin development server with hot-reload")
.option("-t, --target <url>", "Target WorldWideView URL", "http://localhost:3000")
.action(async (options) => {
try {
await startDevServer(options.target);
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program
.command("package")
.description("Build and package the plugin into a .wwvpkg file for sideloading")
.action(async () => {
try {
await packagePlugin();
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program
.command("publish")
.description("Publish the plugin to NPM and notify the WWV Marketplace")
.action(async () => {
try {
await publishToNpm();
} catch (err: any) {
console.error("Error:", err.message);
process.exit(1);
}
});
program.parse();
```
- [ ] **Step 2: Build to verify no TypeScript errors**
Run: `pnpm run build` inside `packages/wwv-cli`
Expected: Clean build.
- [ ] **Step 3: Commit**
```bash
git add packages/wwv-cli/src/index.ts
git commit -m "feat(wwv-cli): register package and npm publish commands"
```
@@ -0,0 +1,53 @@
# Prisma 7 Setup Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Finalize the Prisma 7 adapter architecture by removing legacy `url` parameters from the schema, syncing the local database, and validating the end-to-end connection.
**Architecture:** Prisma 7 strictly separates connection logic from the schema. The schema only defines the provider (`postgresql`), while connection strings for CLI commands like `db push` are handled by `prisma.config.ts`, and runtime connections are handled by the explicit `@prisma/adapter-pg` driver instance passed to the `PrismaClient` constructor.
**Tech Stack:** Prisma 7, PostgreSQL, Next.js, Node.js
---
### Task 1: Update Prisma Schema
**Files:**
- Modify: `prisma/schema.prisma:5-8`
- [ ] **Step 1: Remove the legacy `url` property from the datasource block**
```prisma
datasource db {
provider = "postgresql"
}
```
### Task 2: Push Schema to Local Database
- [ ] **Step 1: Execute Prisma db push to create the tables in the newly running Docker Postgres container**
Run: `npx dotenv-cli -e .env.local -- npx prisma db push`
Expected: PASS with "Your database is now in sync with your schema."
### Task 3: Generate Prisma Client
- [ ] **Step 1: Regenerate the Prisma Client types to ensure they match the schema**
Run: `npx dotenv-cli -e .env.local -- npx prisma generate`
Expected: PASS with "Generated Prisma Client"
### Task 4: Verify End-to-End Connection
- [ ] **Step 1: Run the user management script to prove the `adapter-pg` runtime can connect and query the new tables**
Run: `npx tsx --env-file=.env.local scripts/manage-users.ts list`
Expected: PASS with no errors (it should just exit silently if there are no users, rather than throwing a `P2021 TableDoesNotExist` or `P1001` error).
### Task 5: Restart the Development Server
- [ ] **Step 1: Restart the Next.js dev server**
Because the server has been running while we were debugging the `PrismaClientInitializationError`, Webpack may have cached the broken client. We need to kill the current `pnpm run dev` and start it fresh so we can test the API routes in the browser.
Run: Terminate the current `pnpm run dev` terminal, then run: `pnpm run dev`
Expected: Next.js starts successfully without any Prisma instantiation crashes.
@@ -0,0 +1,618 @@
# Unify Database Adapter (PostgreSQL-Only) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking.
**Goal:** Replace the dual SQLite/PostgreSQL database system with a single PostgreSQL adapter, using Prisma's built-in `prisma dev` for zero-install local development.
**Architecture:** The app currently has two database paths — `@prisma/adapter-better-sqlite3` for local and `@prisma/adapter-pg` for cloud — which causes constant migration conflicts and config drift. We unify to `@prisma/adapter-pg` everywhere. Local developers use `npx prisma dev` (PGLite-backed local Postgres managed by Prisma CLI) or their own Postgres instance. Production connects to Supabase via the same adapter and connection string swap.
**Tech Stack:** Prisma 7, `@prisma/adapter-pg`, `pg`, PostgreSQL, Next.js 16
---
## File Structure
| Action | File | Responsibility |
|---|---|---|
| Modify | `prisma/schema.prisma` | Change provider to `postgresql` |
| **Rewrite** | `src/lib/db.ts` | Single PostgreSQL adapter factory |
| Delete | `src/core/adapters/db.ts` | Remove cloud-branch adapter factory (merge into `db.ts`) |
| Modify | `package.json` | Remove `better-sqlite3` + adapter deps, add `pg` |
| Modify | `next.config.ts` | Remove `better-sqlite3` from `serverExternalPackages` |
| Modify | `docker-entrypoint.sh` | Update comments, remove SQLite references |
| Modify | `Dockerfile` | Remove SQLite build step, update env defaults |
| Modify | `local-dev.ps1` | Add `prisma dev` startup guidance |
| Modify | `.env` | Change default `DATABASE_URL` to local PostgreSQL |
| Modify | `prisma.config.ts` | No changes needed (already reads `DATABASE_URL`) |
| Modify | `scripts/cleanup-plugins.ts` | Use shared `db.ts` instead of hardcoded SQLite |
| Modify | `scripts/manage-users.ts` | Use shared `db.ts` instead of hardcoded SQLite |
| Keep | `scripts/migrate-aviation-history.ts` | This is a one-off Supabase-to-SQLite migration tool. Leave as-is but mark deprecated |
| **Delete** | `prisma/migrations/` | Remove old SQLite migrations (will regenerate for PostgreSQL) |
| **Create** | `prisma/migrations/` | Fresh PostgreSQL init migration |
---
### Task 1: Update Prisma Schema Provider
**Files:**
- Modify: `prisma/schema.prisma:1-6`
- [x] **Step 1: Change the datasource provider from SQLite to PostgreSQL**
Open `prisma/schema.prisma` and replace the datasource block:
```prisma
// 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"
}
```
Leave the `generator` block and all models unchanged.
- [x] **Step 2: Verify the schema is valid**
Run:
```powershell
npx prisma validate
```
Expected: `The schema at prisma/schema.prisma is valid.`
- [x] **Step 3: Commit**
```powershell
git add prisma/schema.prisma
git commit -m "refactor(db): switch schema provider from sqlite to postgresql"
```
---
### Task 2: Remove SQLite Dependencies
**Files:**
- Modify: `package.json:22-80`
- Modify: `next.config.ts:5`
- [x] **Step 1: Remove better-sqlite3 packages from package.json**
In `package.json`, remove these lines from `dependencies`:
```diff
- "@prisma/adapter-better-sqlite3": "^7.5.0",
```
Remove from `pnpm.onlyBuiltDependencies`:
```diff
- "better-sqlite3",
```
Ensure `@prisma/adapter-pg` and `pg` remain (they're already present):
```json
"@prisma/adapter-pg": "^7.8.0",
"pg": "^8.20.0",
```
- [x] **Step 2: Update serverExternalPackages in next.config.ts**
In `next.config.ts` line 5, replace:
```typescript
serverExternalPackages: ["better-sqlite3", "@prisma/adapter-better-sqlite3", "@prisma/client", "prisma"],
```
With:
```typescript
serverExternalPackages: ["@prisma/client", "prisma", "pg"],
```
- [x] **Step 3: Install to update lockfile**
Run:
```powershell
pnpm install
```
Expected: Clean install with no `better-sqlite3` compilation step.
- [x] **Step 4: Commit**
```powershell
git add package.json next.config.ts pnpm-lock.yaml
git commit -m "refactor(db): remove better-sqlite3 dependencies"
```
---
### Task 3: Rewrite the Database Adapter Factory
**Files:**
- Rewrite: `src/lib/db.ts`
- [x] **Step 1: Replace db.ts with a unified PostgreSQL adapter**
Replace the entire contents of `src/lib/db.ts` with:
```typescript
import { PrismaClient } from "../generated/prisma";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
/**
* Prisma client singleton — PostgreSQL only.
*
* Local dev: Run `npx prisma dev` for a zero-install local Postgres.
* Production: Set DATABASE_URL to your Supabase/Postgres connection string.
*
* Uses globalThis to survive Next.js HMR in development.
*/
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
function createPrismaClient(): PrismaClient {
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error(
"[db] DATABASE_URL is not set. " +
"Run `npx prisma dev` for local development, " +
"or set DATABASE_URL to your PostgreSQL connection string."
);
}
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
return new PrismaClient({ adapter } as any);
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient();
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
```
> **Note:** The `feature/cloud-hosting-core` branch has a more complex version at `src/core/adapters/db.ts` with tenant isolation via `applyTenantIsolation()`. When merging that branch later, the tenant isolation extension should be layered on top of this unified base — it does NOT need a separate SQLite path.
- [x] **Step 2: Verify TypeScript compilation**
Run:
```powershell
npx tsc --noEmit --pretty 2>&1 | Select-String "db.ts"
```
Expected: No errors related to `db.ts`.
- [x] **Step 3: Commit**
```powershell
git add src/lib/db.ts
git commit -m "refactor(db): unify adapter to postgresql-only via PrismaPg"
```
---
### Task 4: Update Utility Scripts
**Files:**
- Modify: `scripts/cleanup-plugins.ts`
- Modify: `scripts/manage-users.ts`
- [x] **Step 1: Rewrite cleanup-plugins.ts to use shared db**
Replace the entire contents of `scripts/cleanup-plugins.ts`:
```typescript
import { PrismaClient } from "../src/generated/prisma/index.js";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter } as any);
async function main() {
const plugins = await prisma.installedPlugin.findMany();
console.log("Installed plugins:");
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
const geojson = plugins.find((p) => p.pluginId === "geojson");
if (geojson) {
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
console.log("\nDeleted orphaned 'geojson' record.");
} else {
console.log("\nNo orphaned 'geojson' record found.");
}
const remaining = await prisma.installedPlugin.findMany();
console.log("\nRemaining plugins:");
remaining.forEach((p) => console.log(` ${p.pluginId}`));
await prisma.$disconnect();
}
main().catch(console.error);
```
- [x] **Step 2: Rewrite manage-users.ts to use shared db**
Replace the entire contents of `scripts/manage-users.ts`:
```typescript
import { PrismaClient } from "../src/generated/prisma/index.js";
import { PrismaPg } from "@prisma/adapter-pg";
import { Pool } from "pg";
import { hashSync } from "bcryptjs";
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter } as any);
async function main() {
const action = process.argv[2];
if (action === "list") {
const users = await prisma.user.findMany();
if (users.length === 0) {
console.log("No users found — visit /setup to create one.");
} else {
users.forEach((u) =>
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
);
}
} else if (action === "reset") {
const email = process.argv[3];
const newPass = process.argv[4];
if (!email || !newPass) {
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
return;
}
const hashed = hashSync(newPass, 12);
await prisma.user.update({
where: { email },
data: { hashedPassword: hashed },
});
console.log(`Password reset for ${email}`);
} else if (action === "delete-all") {
await prisma.user.deleteMany();
console.log("All users deleted — visit /setup to create a new admin.");
} else {
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
}
await prisma.$disconnect();
}
main().catch(console.error);
```
- [x] **Step 3: Add deprecation notice to migrate-aviation-history.ts**
Add this comment at the top of `scripts/migrate-aviation-history.ts`:
```typescript
/**
* @deprecated This script uses better-sqlite3 directly to migrate data
* from Supabase into the legacy data engine's SQLite database.
* It is NOT part of the main application's database layer.
* It will be removed once the data engine migration is complete.
*/
```
- [x] **Step 4: Commit**
```powershell
git add scripts/cleanup-plugins.ts scripts/manage-users.ts scripts/migrate-aviation-history.ts
git commit -m "refactor(scripts): update utility scripts to use postgresql adapter"
```
---
### Task 5: Create Fresh PostgreSQL Migration
**Files:**
- Delete: `prisma/migrations/` (entire directory)
- Create: `prisma/migrations/YYYYMMDD_init/migration.sql` (generated by Prisma)
- [x] **Step 1: Delete old SQLite migrations**
```powershell
Remove-Item -Recurse -Force prisma/migrations
```
- [x] **Step 2: Ensure a local PostgreSQL is available**
Either:
- Run `npx prisma dev` in a separate terminal, OR
- Use your existing local PostgreSQL at `127.0.0.1:5432`
Verify the connection string in `.env.local` points to a reachable PostgreSQL instance:
```
DATABASE_URL="postgresql://postgres:[email protected]:5432/postgres?schema=public"
```
- [x] **Step 3: Reset and create initial migration**
```powershell
npx prisma migrate reset --force
npx prisma migrate dev --name init
```
Expected output:
```
Applying migration `YYYYMMDDHHMMSS_init`
The following migration(s) have been created and applied...
```
- [x] **Step 4: Verify migration_lock.toml says postgresql**
```powershell
Get-Content prisma/migrations/migration_lock.toml
```
Expected:
```
provider = "postgresql"
```
- [x] **Step 5: Commit**
```powershell
git add prisma/migrations
git commit -m "feat(db): create initial postgresql migration"
```
---
### Task 6: Update Dockerfile and Entrypoint
**Files:**
- Modify: `Dockerfile:11,36-38,49,54`
- Modify: `docker-entrypoint.sh:3-5`
- [x] **Step 1: Update Dockerfile**
Make these changes to `Dockerfile`:
**Line 11** — Remove `python3 make g++` (no longer need to compile better-sqlite3 native bindings):
```dockerfile
RUN apk add --no-cache python3 make g++
```
Replace with:
```dockerfile
# python3/make/g++ no longer needed — removed better-sqlite3 native compilation
```
**Lines 36-38** — Remove the conditional SQLite build step entirely:
```dockerfile
# Create an empty SQLite database with all tables applied ONLY IF NOT CLOUD
# (For cloud, we'll run migrations against Postgres at runtime)
RUN if [ "$NEXT_PUBLIC_WWV_EDITION" != "cloud" ]; then mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy; fi
```
Replace with:
```dockerfile
# Database migrations run at container startup via docker-entrypoint.sh
# DATABASE_URL must be set to a PostgreSQL connection string
```
**Line 49** — Keep `prisma` global install (needed for `migrate deploy` at runtime).
**Line 54** — Remove the SQLite default DATABASE_URL:
```dockerfile
ENV DATABASE_URL=file:./data/wwv.db
```
Replace with:
```dockerfile
# DATABASE_URL must be provided via environment variable (no default)
# Example: postgresql://user:pass@host:5432/dbname
```
- [x] **Step 2: Update docker-entrypoint.sh comments**
Replace lines 2-5 of `docker-entrypoint.sh`:
```bash
# ─── Docker Entrypoint ───────────────────────────────────────
# Ensures the SQLite database exists and is migrated before
# starting the application. On first run with a fresh volume
# the DB file won't exist yet, so we run prisma migrate deploy.
```
With:
```bash
# ─── Docker Entrypoint ───────────────────────────────────────
# Ensures the PostgreSQL database is migrated before starting
# the application. DATABASE_URL must point to a PostgreSQL
# instance (Supabase, self-hosted, etc).
```
Remove `mkdir -p ./data` from line 9 (no longer creating a local SQLite file):
```bash
set -e
echo "[entrypoint] Running database migrations..."
prisma migrate deploy
echo "[entrypoint] Migrations complete."
```
- [x] **Step 3: Commit**
```powershell
git add Dockerfile docker-entrypoint.sh
git commit -m "refactor(docker): remove sqlite from build and runtime"
```
---
### Task 7: Update Environment Defaults and Dev Scripts
**Files:**
- Modify: `.env:1`
- Modify: `package.json:13` (predev script)
- Modify: `local-dev.ps1`
- [x] **Step 1: Update .env default DATABASE_URL**
Replace line 1 of `.env`:
```
DATABASE_URL=file:./data/wwv.db
```
With:
```
# PostgreSQL connection string.
# For local dev: run `npx prisma dev` and use the URL it prints.
# For production: set to your Supabase/Postgres connection string.
# DATABASE_URL=postgresql://postgres:[email protected]:5432/worldwideview
```
> **Important:** The default is now commented out. The `.env.local` file (or `npx prisma dev`) must provide the actual value. This forces contributors to explicitly set up their database rather than silently falling back to a potentially broken SQLite path.
- [x] **Step 2: Simplify the predev script**
In `package.json`, the `predev` script currently runs `npx prisma migrate deploy`. This will fail if no Postgres is running. Change it to only copy Cesium assets and generate the Prisma client:
```json
"predev": "npx prisma generate && node scripts/copy-cesium.mjs",
```
> **Rationale:** `prisma migrate deploy` should only run in production (Docker entrypoint) or explicitly by the developer. During local dev, `npx prisma dev` handles migrations automatically.
- [x] **Step 3: Update local-dev.ps1**
Replace the entire contents of `local-dev.ps1`:
```powershell
Write-Host "[*] Setting up WorldWideView for Local Development..."
# Check for pnpm
try {
$null = Get-Command pnpm -ErrorAction Stop
} catch {
Write-Host "[Error] pnpm is not installed or not in PATH."
Write-Host "Please install it first: https://pnpm.io/installation"
exit 1
}
Write-Host "[*] Installing dependencies..."
pnpm install
Write-Host "[*] Running initial setup (generating secrets)..."
pnpm run setup
Write-Host "[*] Generating Prisma client..."
npx prisma generate
# Check for the sibling Data Engine repository
if (-not (Test-Path "../wwv-data-engine")) {
Write-Host ""
Write-Host "=====================================================================" -ForegroundColor Yellow
Write-Host "[!] NOTICE: Local Data Engine not found at ../wwv-data-engine" -ForegroundColor Yellow
Write-Host ""
Write-Host "Frontend-Only Mode: You are developing the frontend UI." -ForegroundColor Green
Write-Host "WorldWideView will automatically stream data from the Cloud Engine." -ForegroundColor Green
Write-Host ""
Write-Host "Full-Stack Mode: If you want to develop backend data seeders, you" -ForegroundColor Cyan
Write-Host "must clone the open-source data engine as a sibling directory:" -ForegroundColor Cyan
Write-Host " cd ..; git clone https://github.com/silvertakana/wwv-data-engine"
Write-Host " cd wwv-data-engine; pnpm install"
Write-Host "=====================================================================" -ForegroundColor Yellow
Write-Host ""
}
Write-Host ""
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
Write-Host ""
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
Write-Host ""
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
Write-Host " npx prisma dev" -ForegroundColor Yellow
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
Write-Host ""
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "[*] Starting local Next.js frontend server..."
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
pnpm run dev
```
- [x] **Step 4: Commit**
```powershell
git add .env package.json local-dev.ps1
git commit -m "refactor(dev): update env defaults and dev scripts for postgresql"
```
---
### Task 8: Run Tests and Validate
**Files:**
- No file changes — validation only
- [x] **Step 1: Generate Prisma client**
```powershell
npx prisma generate
```
Expected: `Generated Prisma Client to ./src/generated/prisma`
- [x] **Step 2: Run the test suite**
```powershell
pnpm test
```
Expected: All tests pass. The repository tests mock `db.ts`, so the adapter change should be transparent to them.
- [x] **Step 3: Start the dev server**
Ensure your `.env.local` has a valid `DATABASE_URL` pointing to PostgreSQL, then:
```powershell
pnpm run dev
```
Expected: Server starts at `http://localhost:3000` without `P3005` or `P3018` errors.
- [x] **Step 4: Verify database operations work**
1. Navigate to `http://localhost:3000/setup` — create a test user
2. Log in
3. Open the Plugins panel — verify installed plugins load
4. Star a favorite entity — verify it persists across reload
- [x] **Step 5: Final commit**
```powershell
git add -A
git commit -m "test(db): verify postgresql-only adapter works end-to-end"
```
---
## Post-Implementation Notes
### For the `feature/cloud-hosting-core` merge
When merging the cloud-hosting-core branch back into main, the `src/core/adapters/db.ts` file with `applyTenantIsolation()` should be integrated into `src/lib/db.ts` as a wrapper around the single `PrismaPg` adapter. The conditional SQLite path in that file can be completely removed.
### For self-hosted Docker users
Add a note to the release changelog:
> **Breaking Change:** WorldWideView now requires a PostgreSQL database. SQLite is no longer supported.
> Self-hosted users must provide a `DATABASE_URL` environment variable pointing to a PostgreSQL instance.
> The easiest option is a free Supabase project, or run `docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=pass postgres:17-alpine` alongside your WWV container.
### For the migrate-aviation-history.ts script
This script uses `better-sqlite3` directly to talk to the data engine's separate SQLite database (not the platform database). It is unrelated to this migration and can remain as-is. If `better-sqlite3` is needed for this script, install it as a `devDependency` only, or move the script to the data engine repo where it belongs.
+34
View File
@@ -0,0 +1,34 @@
---
trigger: glob
description: Strict guidelines for rendering geospatial entities, handling 3D terrain clipping, and applying dynamic animation properties against Cesium's runtime engine.
globs: "src/core/globe/**/*"
---
# Cesium Rendering Rules
## Purpose
Strict guidelines for rendering geospatial entities, handling 3D terrain clipping, and applying dynamic animation properties against Cesium's runtime engine.
## When to Apply
Whenever writing code for plugins, visual layers, or modifying components like `EntityRenderer` or `GlobeView`.
## Critical Limitations
### `HeightReference.CLAMP_TO_GROUND` Warning
> [!WARNING]
> Do **not** apply `HeightReference.CLAMP_TO_GROUND` to label text rendering (`LabelGraphics`). Due to a known issue in Cesium 1.121+, clamping tens of thousands of dynamic labels blocks the UI thread continuously because Cesium recalculates the terrain intersection each frame.
### Primitive Restrictions
When creating primitive objects:
- **Points** (`PointPrimitive`): Can use `size`, `outlineWidth`, and `outlineColor`.
- **Billboards** (`BillboardGraphics` for SVG/Icons): Must **NOT** use `size`, `outlineWidth`, or `outlineColor`. You must use `iconScale` to resize them. Mixing point properties on billboards causes severe shader clipping.
## Performance Culling
> [!TIP]
> Do not rely solely on depth buffering (`disableDepthTestDistance`) when viewing the backside of the globe. Use CPU-side calculating (dot-product against the Earth's radius) to implement manual horizon culling. Render nothing if the scalar projection is behind the tangential threshold.
## LOD & Stacking
1. Convert distant entities to `billboard` representations.
2. If closely grouped, the `StackManager` should spiderify components circularly. Non-hub objects fade to 0.4 opacity when expanded to reduce visual clutter.
3. Use the `useModelRendering` hook exclusively for transitioning high-importance entities (like aircraft or ships) into full 3D GLTF models on approach.
+21
View File
@@ -0,0 +1,21 @@
---
trigger: always_on
---
# Context and Memory Synchronization
## 1. Purpose
This specification ensures that any agent maintains persistent, accurate project context by pointing them directly to the Single Source of Truth for this repository.
## 2. Synchronization Target
The agent MUST orient itself by immediately reading:
1. `c:\dev\worldwideview\AGENTS.md` (The root index of all technical stack details)
2. `c:\dev\worldwideview\.agents\context\01-platform-overview.md` (The high-level platform goals)
If deep technical rules are required for a specific domain (e.g., UI state, Map Rendering, Monorepo management), the agent MUST consult the relevant file in `c:\dev\worldwideview\.agents\rules\`.
## 3. Reflecting Changes
If the architecture fundamentally changes (e.g., migrating off Zustand, or removing Cesium), the agent MUST proactively update the `AGENTS.md` and relevant files in `.agents/rules/` to reflect this new reality.
## 4. Goal
A new chat instance MUST be able to reconstruct an accurate, comprehensive understanding of the project solely from reading the root `AGENTS.md` file and branching out to the specific rules as necessary. This prevents context bloat and ensures accuracy.
+3 -3
View File
@@ -4,8 +4,8 @@
When making database schema changes, you must ensure that generated migrations are resilient against environmental discrepancies.
- **Review Generated SQL**: Always review the `.sql` files generated by `npx prisma migrate dev`.
- **Add "IF EXISTS" clauses**: SQLite and Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs (e.g., the index was already dropped or never created), manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
- **Data Preservation**: When dropping columns or renaming, SQLite does not cleanly support it and requires table recreation. Carefully review the `INSERT INTO "new_table" SELECT ...` clauses to ensure data is correctly mapped.
- **Add "IF EXISTS" clauses**: Prisma can sometimes produce brittle drop statements (`DROP INDEX "my_index"`). To prevent migrations from crashing if a state desynchronization occurs, manually edit the migration file to use `DROP INDEX IF EXISTS "my_index";` or `DROP TABLE IF EXISTS "table_name";`.
- **Data Preservation**: When dropping columns or renaming, carefully review the migration to ensure data is correctly mapped. In PostgreSQL, ensure that cascaded drops don't accidentally remove required data.
## 2. Managing Failed Migrations
If a migration fails in production:
@@ -13,4 +13,4 @@ If a migration fails in production:
- If you use `resolve --applied`, Prisma will permanently skip that migration in the future, leaving your database structurally out of sync with your Prisma Client.
## 3. Backups Before DDL
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database (via Prisma or direct SQLite access) without first confirming an automated backup exists, or manually taking a backup of the `wwv.db` file.
Never perform direct DDL operations (ALTER, DROP, CREATE) on a production database without first confirming an automated backup exists, or manually taking a `pg_dump` backup of the database.
+30
View File
@@ -0,0 +1,30 @@
---
trigger: model_decision
description: Strict rules for operating within the pnpm monorepo workspace environment structure across frontend and backend services.
globs: ""
---
# Monorepo Workflow Guidelines
## Purpose
Strict rules for operating within the `pnpm` monorepo workspace environment structure across frontend and backend services.
## Directory Isolation
- The Next.js frontend is located at root `.`.
- Individual standalone plugins are located at `packages/wwv-plugin-[name]`.
- For heavy plugin processing, microservice backends are located at `packages/wwv-plugin-[name]/backend`.
## Critical Workspace Rule
> [!IMPORTANT]
> Because plugins use internal workspace references, you MUST strictly use `"workspace:*"` instead of `"*"` in `package.json` dependencies (e.g. `"@worldwideview/wwv-plugin-sdk": "workspace:*"`). Using `"*"` can cause pnpm to eagerly resolve cached registry versions instead of strictly linking your local code, resulting in opaque TypeScript and compilation errors.
> **Whenever you add a new plugin package or adjust the SDK, you MUST run `pnpm install` then `pnpm build` from the project ROOT directory to propagate TS types properly.**
## Start/Exec Flow
Running `pnpm start:backends` from the project root employs `concurrently` to spin up Fastify services attached to specific plugins containing `/backend` folders.
## Next.js Monorepo Exceptions
When modifying `next.config.ts`, if new UI components or plugins are added that require SSR/transpilation, ensure they are appended to the `transpilePackages: []` array, or they will throw Next-Router unresolved import errors on production build.
+83
View File
@@ -0,0 +1,83 @@
---
trigger: model_decision
description: The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
---
# Plugin Architecture & Data Flow
## Purpose
The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
## The WorldPlugin Contract
All data ingest flows through `WorldPlugin` (defined entirely within `@worldwideview/wwv-plugin-sdk`).
A valid plugin class MUST provide:
1. `id` and `version` (The `version` MUST be dynamically imported via `import pkg from "../package.json"` to prevent duplicate tracking during CI/releases for built-in plugins).
2. `fetch(timeRange)` method logic.
3. `renderEntity(GeoEntity)` to determine visual style.
4. `getPollingInterval()` (defaults fallback securely to standard store config).
## Plugin Architectures (Manifest Formats)
Plugins are defined via `PluginManifest` and operate on an **All-Bundle** architecture.
All frontend extensions must eventually be compiled into a JS bundle that exports a `WorldPlugin`.
1. **`bundle` (Dynamic CDN Loaded / Internal)**: Plugins dynamically imported at runtime via ES module references (e.g., `unpkg.com` or local `/plugins/myplugin/frontend.mjs`). Handled by `loadPluginFromManifest` referencing `manifest.entry`.
2. **`static` (Legacy)**: Now compiled via `wwvStaticCompiler` into a dynamic bundle. The raw `StaticDataPlugin` runtime class has been removed.
3. **`declarative` (Legacy)**: Now compiled or wrapped into bundles.
No matter the source, the engine evaluates it by directly loading the `entry` file dynamically:
`const module = await import(/* webpackIgnore: true */ entry);`
## Package Metadata (`package.json`)
All plugins MUST define their identity and compatibility via a `"worldwideview"` block in their `package.json`. This acts as the source-of-truth for generating the `PluginManifest` for the registry. If a plugin does not define `"type"`, validation functions will reject the manifest entirely or rely on legacy fallbacks.
```json
{
"name": "@worldwideview/wwv-plugin-myplugin",
"version": "1.0.0",
"worldwideview": {
"id": "myplugin", // REQUIRED: Must match the directory name & API routes.
"type": "data-layer", // REQUIRED: "data-layer" or "extension"
"format": "bundle", // REQUIRED: "bundle", "declarative", or "static"
"category": "Aviation", // REQUIRED: Matches PluginCategory union in SDK
"icon": "Plane", // RECOMMENDED: Lucide icon name
"capabilities": [ // REQUIRED: What the plugin can do
"data:own", // (e.g. injects its own data)
"globe:overlay", // (e.g. renders 3D elements)
"network:fetch"
]
}
}
```
## The Registration Pipeline
> [!NOTE]
> All plugin interactions run through three singleton services:
> `PluginRegistry` / `InstalledPluginsLoader` -> `PluginManager` -> `PollingManager` -> `DataBus`
### `InstalledPluginsLoader`
Scans the PostgreSQL database at startup for dynamically installed marketplace manifests. Parses, validates (`validateManifest`), and registers valid plugins via `pluginManager.loadFromManifest`.
### `PluginManager`
The orchestrator. Exposes `registerPlugin`, `enablePlugin`, `disablePlugin`. Never bypass the manager to push data manually to the cache. Supports dynamic loading via `loadFromManifest`.
### `PollingManager`
Coordinates interval execution. Implements **exponential backoff**. When a plugin errors, it retries at increasing scales (e.g., 2s → 4s → 8s) automatically.
### `DataBus`
The typed generic event bus separating React UI components from background execution.
```typescript
// How data gets pushed onto the rendering surface securely:
DataBus.getInstance().emit('dataUpdated', {
pluginId: "mytracker",
entities: newEntities
});
```
## 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.
+43
View File
@@ -0,0 +1,43 @@
---
trigger: glob
description: Guidelines on managing the single source of truth across WorldWideView using Zustand, avoiding prop-drilling, and isolating UI rerenders.
globs: "src/core/state/**/*, src/components/**/*"
---
# Zustand State Management
## Purpose
Guidelines on managing the single source of truth across WorldWideView using Zustand, avoiding prop-drilling, and isolating UI rerenders.
## Single Centralized State
WorldWideView utilizes a monolithic Zustand store located at `src/core/state/store.ts`. It is broken down into exactly 9 semantic slices.
| Slice Name | Purpose | Example State |
|---|---|---|
| **Globe** | Cesium Viewer state | `cameraPosition`, `selectedEntity` |
| **Layers** | Loaded map tiles/overlays | `activeTileSets` |
| **Timeline** | Application current time | `currentTimeRange` |
| **UI** | Global overlay states | `isFilterMenuOpen` |
| **Filters** | Active visual filtration | `searchQuery`, `categoryFilter` |
| **Data** | Entity registry | `entitiesByPlugin` |
| **Config** | User preferences | `pollingIntervals`, `pluginSettings` |
| **Favorites**| Pinned entities | `favoriteIds` |
| **GeoJSON** | Local files loaded in | `localImports` |
## When to Apply
When passing deep state across components, or when a plugin must push state configurations onto the screen.
## Best Practices
### Avoid Prop Drilling
**Never** pass props further than two levels down. If a component deeper in the tree needs access to something (e.g., `cameraPosition`), it must `useStore(s => s.globe.cameraPosition)`.
### Selector Destructuring Avoidance
> [!WARNING]
> Do not destructure wide objects in selectors.
> Right: `const isHUD = useStore(state => state.ui.hudVisible);`
> Wrong: `const { hudVisible } = useStore(state => state.ui);`
> The wrong approach rerenders the component any time *anything* in the `ui` slice changes.
### Config and Plugins
If your plugin has user-configurable values (e.g., color settings, toggle states), its data MUST live inside `state.config.dataConfig.pluginSettings[pluginId]`. Do not spawn un-bound `useState` hooks for UI properties if they affect the global app state.
+10 -1
View File
@@ -1,4 +1,13 @@
DATABASE_URL=file:./data/wwv.db
# 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
+2 -2
View File
@@ -4,8 +4,8 @@
# This file is tracked by git. Only put non-secret values here.
# Prisma reads DATABASE_URL from this file.
# Database (SQLite for local — zero config; PostgreSQL for cloud)
DATABASE_URL=file:./data/wwv.db
# Database (PostgreSQL)
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/worldwideview
# ============================================================
# .env.local — NOT committed (secrets & API keys)
+29
View File
@@ -0,0 +1,29 @@
version: 2
updates:
# 1. Maintain Node.js / pnpm dependencies
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
# Group all minor/patch updates into a single PR so it doesn't spam you
groups:
dependencies:
patterns:
- "*"
update-types:
- "minor"
- "patch"
# 2. Maintain Docker base images
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
# 3. Maintain GitHub Actions workflows
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly" # Actions update less frequently, monthly is fine
+10 -16
View File
@@ -9,11 +9,9 @@ jobs:
name: Type Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
@@ -25,11 +23,9 @@ jobs:
name: Unit Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
@@ -42,15 +38,13 @@ jobs:
runs-on: ubuntu-latest
needs: [typecheck, test]
env:
DATABASE_URL: file:./data/wwv.db
DATABASE_URL: postgresql://ci:ci@localhost:5432/ci
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
NEXT_PUBLIC_WWV_EDITION: local
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 9
- uses: actions/setup-node@v4
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 22
cache: pnpm
+1 -1
View File
@@ -27,7 +27,7 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 1
+1 -1
View File
@@ -26,7 +26,7 @@ jobs:
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
with:
fetch-depth: 1
+3 -3
View File
@@ -20,10 +20,10 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v4
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
uses: docker/setup-buildx-action@v4
- name: Log in to the Container registry
uses: docker/login-action@v3
@@ -34,7 +34,7 @@ jobs:
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
+2 -2
View File
@@ -12,9 +12,9 @@ jobs:
contents: read
id-token: write # Required for OIDC trusted publishing (no NPM_TOKEN needed)
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
- uses: actions/setup-node@v6
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
+29 -10
View File
@@ -19,7 +19,7 @@ Our primary design, feature-set, and operational layout goal is to mimic the str
| State | Zustand (slice-based: globe, layers, timeline, UI, filters, data, config, favorites, geojson) |
| Event Bus | Custom typed `DataBus` (pub/sub singleton) |
| Styling | Vanilla CSS — **no Tailwind** |
| Database | SQLite via Prisma (local), PostgreSQL (cloud) |
| Database | PostgreSQL via Prisma 7 (local and cloud) |
| Auth | NextAuth v5 beta (Credentials provider, JWT sessions) |
| Package Manager | pnpm (monorepo with `pnpm-workspace.yaml`) |
| Testing | Vitest + jsdom + React Testing Library |
@@ -77,7 +77,7 @@ worldwideview/
├── prisma/ # schema.prisma, migrations/
├── public/ # Static assets, Cesium workers, plugin GeoJSON data
├── scripts/ # Build scripts (copy-cesium, scaffold-osm-plugin, setup)
├── data/ # SQLite database (gitignored, Docker volume)
├── data/ # PostgreSQL data volume (gitignored)
├── Dockerfile # Multi-stage production build
├── docker-compose.yml # Main app + microservice backends
└── .agents/ # Agent documentation, rules, skills, workflows
@@ -102,7 +102,7 @@ Visibility Toggle → DataBusSubscriber subscribes to layer via WsClient
```
Four plugin architectures exist (All-Bundle Model):
1. **Data Engine Seeder** — Standalone Fastify container with SQLite microservice or unified seeders (e.g., `iranwarlive-backend`).
1. **Data Engine Seeder** — Standalone Fastify container with PostgreSQL microservice or unified seeders (e.g., `iranwarlive-backend`).
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`).
@@ -213,6 +213,7 @@ Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRe
> - **MUST**: You MUST update Semantic Versioning numbering inside the relevant `package.json` file prior to executing any code commits, adhering strictly to the `[/commit]` workflow rules (`feat:` -> Minor, `fix/refactor/perf:` -> Patch).
> - **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**: You MUST always be transparent about what you are doing. Narrate your goals, your current step in the process, and exactly what actions you are taking or tools you are executing **before** or **while** you do them, not after they are done. Do not work in silence or lock all your reasoning behind hidden "thought" blocks. Use visible chat messages to bring the user along the journey by describing your plan as it unfolds. **Crucially, keep this narration conversational and natural.** Avoid stiff, robotic templates (e.g., "My Goal: X. My Step: Y."). Just occasionally drop a brief, casual note about what you are checking or doing next so the user isn't left in the dark.
### 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.
@@ -223,7 +224,7 @@ Whenever agents generate temporary debugging scripts, test REST endpoints via `.
| Variable | Required | Description |
|---|---|---|
| `DATABASE_URL` | Yes | SQLite: `file:./data/wwv.db` |
| `DATABASE_URL` | Yes | PostgreSQL connection string |
| `AUTH_SECRET` | Yes | JWT signing secret (generate with `openssl rand -hex 32`) |
| `NEXT_PUBLIC_CESIUM_ION_TOKEN` | No | Cesium Ion access token |
| `NEXT_PUBLIC_BING_MAPS_KEY` | No | Bing Maps imagery |
@@ -244,14 +245,14 @@ Secrets go in `.env.local` (gitignored). Non-secrets go in `.env` (committed).
```bash
pnpm install # Install all workspace dependencies
pnpm run setup # Generate .env.local with AUTH_SECRET (first-time setup)
pnpm dev # Next.js frontend only (auto-runs prisma migrate deploy + copy-cesium)
pnpm dev # Next.js frontend only (auto-runs prisma db push + copy-cesium)
pnpm dev:all # Frontend + wwv-data-engine concurrently (normal development)
pnpm dev:backends # Run only the data engine in dev mode
pnpm build # Production build
pnpm test # Run all Vitest tests (scoped to src/lib, src/core, src/plugins)
pnpm db:reset # Reset and re-migrate the frontend SQLite database (destructive)
pnpm db:reset # Reset and re-migrate the frontend database (destructive)
pnpm start:backends # Start all plugin microservice backends in parallel
pnpm clean:backends # Wipe all plugin SQLite databases
pnpm clean:backends # Wipe all plugin database records
pnpm run scaffold-osm-plugin <name> # Generate a new plugin from scaffold
```
@@ -266,8 +267,8 @@ Frontend runs at `http://localhost:3000`.
- **Cesium assets**: Copied to `public/cesium/` via `scripts/copy-cesium.mjs` at build time, excluded from output tracing.
- **Prisma Configuration**: `prisma.config.ts` must export a native javascript object instead of dynamically importing CLI wrapper binaries (`prisma/config` or `dotenv`). The standalone Next.js tracer strips CLI devDependencies during the build, which will cause fatal runtime container crashes if imported.
- **Microservices**: Separate containers defined in `docker-compose.yml`, proxied via `next.config.ts` rewrites.
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell. Persistent storage mount required at `/app/data` for the SQLite root node database.
- **Docker volumes**: Mount `/app/data` (frontend SQLite), `/app/packages/wwv-data-engine/data` (data engine SQLite), `/data` (Redis)
- **Coolify**: Deployed via Dockerfile builder natively mapping environment variables continuously into the container shell.
- **Docker volumes**: Ensure PostgreSQL data and Redis volumes are mounted for persistence.
---
@@ -314,7 +315,7 @@ Read the relevant rule file when working in that domain:
| `plugin-architecture` | Creating/modifying plugins, lifecycle, registration | `.agents/rules/plugin-architecture.md` |
| `cesium-rendering` | Globe rendering, entity types, primitives, LOD, culling | `.agents/rules/cesium-rendering.md` |
| `state-management` | Zustand slices, store access, plugin settings | `.agents/rules/state-management.md` |
| `database-migrations` | Prisma schema changes, migrations, SQLite/Postgres | `.agents/rules/database-migrations.md` |
| `database-migrations` | Prisma schema changes, migrations, PostgreSQL | `.agents/rules/database-migrations.md` |
| `continuous-improvement` | When to create/update rules, skills, or workflows | `.agents/rules/continuous-improvement.md` |
| `context-and-memory` | How to orient and maintain project context between sessions | `.agents/rules/context-and-memory.md` |
@@ -361,3 +362,21 @@ Refer to these skill documents for specialized tasks:
### Global Skills
52 skills are available across all projects. See `.agents/global-skills-index.md` for the full list and invocation paths.
---
## 15. Pull Request & Commit Guidelines
- **Commit Format**: We strictly enforce Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`).
- **Workflow**: You **MUST** use the `/commit` workflow before every git commit to ensure proper semantic versioning bumps.
- **Required Checks**: Ensure `pnpm test` and `pnpm build` complete successfully before proposing a merge.
- **Review Process**: Use `/pr-review` to conduct a comprehensive multi-role review on any pull request.
---
## 16. Debugging and Troubleshooting
- **Prisma & PostgreSQL Sync Issues**: If the local database state falls out of sync with Prisma schema, do not manually drop tables. Instead, run `pnpm db:reset` to cleanly wipe and re-apply all migrations.
- **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`.
+27 -15
View File
@@ -6,47 +6,56 @@ RUN find . -type f \! -name 'package.json' \! -name 'pnpm-workspace.yaml' \! -na
find . -type d -empty -delete
# Stage 1: Install ALL dependencies (needed for build)
FROM node:22-alpine AS deps
RUN corepack enable pnpm
RUN apk add --no-cache python3 make g++
FROM node:26-alpine AS deps
RUN npm install -g [email protected]
WORKDIR /app
# Copy only the extracted package.jsons
COPY --from=extractor /app ./
# Install dependencies with cache mount for pnpm store
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install --frozen-lockfile
RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm install
# Stage 3: Build the application
FROM deps AS builder
# Copy full source code
COPY . .
RUN DATABASE_URL="file:./data/wwv.db" npx prisma generate
# Create an empty SQLite database with all tables applied
RUN mkdir -p ./data && DATABASE_URL=file:./data/wwv.db npx prisma migrate deploy
# Next.js inlines NEXT_PUBLIC_* vars at build time — must be declared as ARGs
ARG NEXT_PUBLIC_CESIUM_ION_TOKEN
ARG NEXT_PUBLIC_GOOGLE_MAPS_API_KEY
ARG NEXT_PUBLIC_BING_MAPS_KEY
ARG NEXT_PUBLIC_WWV_EDITION
ARG NEXT_PUBLIC_WS_ENGINE_URL
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
# Run our pregenerate schema swap script and then generate Prisma client
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
# 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
# Deploy flattened production dependencies
RUN pnpm --filter worldwideview deploy --prod /app/prod
# Stage 4: Production runner
FROM node:22-alpine AS runner
FROM node:26-alpine AS runner
WORKDIR /app
RUN apk add --no-cache openssl
RUN npm install -g [email protected]
ENV NODE_ENV=production
ENV HOSTNAME=0.0.0.0
ENV PORT=3000
ENV DATABASE_URL=file:./data/wwv.db
# DATABASE_URL must be provided via environment variable (no default)
# Example: postgresql://user:pass@host:5432/dbname
ENV AUTH_TRUST_HOST=true
# Copy Prisma schema + migrations for runtime DB init
@@ -59,20 +68,23 @@ COPY --from=builder /app/src/generated ./src/generated
# Copy standalone server output
COPY --from=builder /app/.next/standalone ./
# Copy deployed production node_modules
COPY --from=builder /app/prod/node_modules ./node_modules
# We no longer copy proddeps/node_modules. Next.js standalone output
# already traces and copies all the exact node_modules needed for production.
# Copy static assets that standalone mode does NOT include
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
# Entrypoint: migrate DB on first run, then start server
COPY docker-entrypoint.sh ./docker-entrypoint.sh
RUN sed -i 's/\r$//' ./docker-entrypoint.sh
RUN chmod +x ./docker-entrypoint.sh
# Declare /app/data as a persistent volume mount point.
VOLUME ["/app/data"]
EXPOSE 3000
EXPOSE 3000 3001
ENTRYPOINT ["./docker-entrypoint.sh"]
BIN
View File
Binary file not shown.
+91 -2
View File
@@ -7,6 +7,20 @@
*A modular situational awareness platform designed to ingest live data streams and render them as interactive, cinematic layers on a high-fidelity CesiumJS 3D globe.*
[![CI Build](https://github.com/silvertakana/worldwideview/actions/workflows/ci.yml/badge.svg)](https://github.com/silvertakana/worldwideview/actions/workflows/ci.yml)
[![Codecov](https://img.shields.io/codecov/c/github/silvertakana/worldwideview.svg)](https://codecov.io/gh/silvertakana/worldwideview)
[![NPM Version](https://img.shields.io/npm/v/@worldwideview/wwv-plugin-sdk.svg)](https://www.npmjs.com/package/@worldwideview/wwv-plugin-sdk)
[![GitHub Release](https://img.shields.io/github/v/release/silvertakana/worldwideview?sort=semver)](https://github.com/silvertakana/worldwideview/releases)
[![Contributors](https://img.shields.io/github/contributors/silvertakana/worldwideview.svg)](https://github.com/silvertakana/worldwideview/graphs/contributors)
<br>
[![Next.js 16](https://img.shields.io/badge/Next.js-16-black?logo=next.js)](https://nextjs.org/)
[![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)
[![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)
![WorldWideView Interface](docs/assets/screenshot.png)
</div>
@@ -15,15 +29,56 @@
WorldWideView is a real-time geospatial engine visualizing live global data on an interactive 3D globe. Utilizing a dynamic "All-Bundle" plugin architecture, independent data sources—like live aircraft, maritime vessels, or conflict events—are ingested and rendered decoupled from the core 3D viewer.
## Key Features
- **"All-Bundle" Plugin Architecture**: Ingest any data source dynamically without touching the core platform.
- **High-Fidelity 3D Rendering**: Google Photorealistic 3D Tiles and LOD modeling powered by CesiumJS.
- **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.
## Core Technologies
- **Frontend:** Next.js 16 (App Router), React 19, TypeScript 5
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles)
- **State Management:** Zustand
- **Event Bus:** Custom typed `DataBus` for high-frequency WebSocket updates
- **Database:** SQLite via Prisma (local), PostgreSQL (cloud)
- **Database:** PostgreSQL via Prisma 7
- **Deployment:** Docker multi-stage build, Coolify
## Project Architecture
WorldWideView separates the data acquisition layer from the frontend rendering loop, using a real-time event bus to bridge them.
```mermaid
flowchart TD
subgraph Data Sources
A[Public APIs] -->|Poll| B[Data Engine Seeders]
C[Microservices] -->|Stream| B
end
subgraph Frontend Pipeline
B -->|WebSocket /stream| D[DataBus & WsClient]
D -->|Hydrate| E[Zustand Store]
E -->|Memoized Entities| F[Entity Renderer]
F -->|Primitives| G[CesiumJS Globe]
end
subgraph Plugins
H[Plugin Registry] -->|Load| I[Dynamic Import CDNs]
end
H -.-> D
```
## Prerequisites
Before running the application, ensure you have the following installed:
- [Node.js](https://nodejs.org/) (v18+)
- [pnpm](https://pnpm.io/) (v9+)
- [Docker](https://www.docker.com/) (for self-hosting or full local dev)
- PostgreSQL (or rely on the `coolify-db` / local compose container)
## Quick Start (Self-Hosting)
WorldWideView uses a multi-stage Dockerfile designed for standalone output. To deploy instantly on your own server:
@@ -41,7 +96,7 @@ Invoke-WebRequest -Uri https://raw.githubusercontent.com/silvertakana/worldwidev
```
> [!NOTE]
> Ensure you mount the `/app/data` volume to persist the SQLite database across container restarts.
> Ensure you connect a PostgreSQL database via the `DATABASE_URL` environment variable for production deployments.
## Quick Start (Local Development)
@@ -56,6 +111,24 @@ pnpm run dev:all # boots the UI, cache layers, and the data engine
```
Visit `http://localhost:3000` to see the live globe.
## Project Structure
The codebase utilizes a `pnpm` monorepo configuration:
```text
worldwideview/
├── src/ # Core frontend app
│ ├── app/ # Next.js App Router (pages, API routes)
│ ├── components/ # Shared UI, Globe panels, and 3D layouts
│ ├── core/ # DataBus, Polling, PluginManager, Store
│ └── plugins/ # Built-in plugins and registry logic
├── packages/ # Monorepo packages
│ ├── wwv-plugin-sdk/ # SDK interfaces and manifest schemas
│ └── wwv-plugin-*/ # Individual plugins & their backends
├── prisma/ # Database schemas & migrations
└── .agents/ # Agent rules, workflows, and documentation
```
## Plugin Ecosystem
WorldWideView operates on an open-core philosophy. The platform itself is data-agnostic; all data sources are dynamically imported as plugins at runtime.
@@ -73,6 +146,22 @@ WorldWideView is distributed across several specialized repositories:
4. **`worldwideview-marketplace`**: The web application driving the plugin directory.
5. **`worldwideview-web`**: Marketing and landing site.
## Development & Workflow
- **Branching & Commits:** We strictly enforce [Conventional Commits](https://www.conventionalcommits.org/) (`feat:`, `fix:`, `refactor:`). Every commit should utilize our semantic versioning `[/commit]` workflow.
- **Coding Standards:** We emphasize vanilla CSS (no Tailwind), strict TypeScript 5, and file modularity (max 150 lines per file).
- **Testing:** We use Vitest with `jsdom`. All new core logic should be accompanied by tests, running via `pnpm test`.
See [Docs: Development](docs/development.md) and [Docs: Testing](docs/testing.md) for more details.
## Contributing
We welcome community contributions! Please review our coding standards and PR processes before submitting code. For detailed instructions on local development and setting up your environment, see our [CONTRIBUTING.md](CONTRIBUTING.md).
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## Documentation Index
Explore our comprehensive documentation suite for detailed engineering insights:
+3 -3
View File
@@ -26,11 +26,11 @@ Each stage is **self-contained and demo-able**. Any stage can be shipped indepen
---
## Stage 3: Prisma ORM & Local Database ✅
**Demo:** "Run `pnpm run dev` on a fresh clone. SQLite auto-creates. App works with zero config."
**Demo:** "Run `pnpm run dev` on a fresh clone with a valid DATABASE_URL. App works seamlessly."
- [x] Prisma (`prisma` + `@prisma/client`)
- [x] Schema: `InstalledPlugin`, `Setting`, `User`, `AviationHistory`, `NpmCache`
- [x] SQLite default: `DATABASE_URL=file:./data/wwv.db`
- [x] PostgreSQL default: `DATABASE_URL` required
- [x] `predev` script: `prisma migrate deploy`
- [x] DB auto-creates on first run — zero manual setup
@@ -142,7 +142,7 @@ Each stage is **self-contained and demo-able**. Any stage can be shipped indepen
| **License** | EL2.0 for WorldWideView core; Open Source for marketplace |
| **Shared types** | `@worldwideview/plugin-sdk` npm package (MIT) |
| **Hosting** | Coolify (ThinkPad T480s). Landing page on Vercel (static export) |
| **Database** | Supabase PostgreSQL (cloud), SQLite (local), Prisma ORM |
| **Database** | PostgreSQL, Prisma ORM |
| **Tenant isolation** | Row-Level Security (RLS) in shared PostgreSQL |
| **User settings** | Runtime settings store in DB, not `.env` |
| **Bot prevention** | Email verification + Cloudflare Turnstile + rate limiting |
+37
View File
@@ -0,0 +1,37 @@
# Security Policy
Security is a priority for our project. We appreciate the efforts of security researchers and the open-source community in helping us keep our software secure.
## Supported Versions
Security updates are provided for the following versions of the project. We highly recommend all users stay on the latest stable release.
| Version | Supported | Notes |
| ------- | ------------------ | ----- |
| 2.x.x | :white_check_mark: | Current main release. Receives all security updates. |
| 1.x.x | :x: | Legacy version. No longer receiving updates. |
| < 1.0 | :x: | Beta versions are not supported. |
## Reporting a Vulnerability
**Please do not report security vulnerabilities through public GitHub issues.**
If you believe you have found a security vulnerability in this project, please report it privately so we have time to fix it before the vulnerability is made public.
### How to Report
1. **Email us directly:** Send your report to **[support@worldwideview.dev]**.
2. **GitHub Security Advisories:** Alternatively, if this repository has Private Vulnerability Reporting enabled, you can click on the `Security` tab -> `Advisories` -> `Report a vulnerability`.
### What to Include
To help us quickly validate and fix the issue, please include the following in your report:
* A description of the vulnerability and its potential impact.
* The steps required to reproduce the issue (a proof of concept is highly appreciated).
* Any relevant environment details (OS, browser, version).
### What to Expect
* **Acknowledgment:** We will acknowledge receipt of your vulnerability report within **48 hours**.
* **Triage & Fix:** We will review the report, determine its severity, and work on a patch. We will keep you updated on our progress.
* **Disclosure:** Once the vulnerability is patched and a new version is released, we will publish a security advisory. We are happy to credit you for the discovery if you would like!
*Note: As an open-source project, we currently do not offer financial bug bounties, but we deeply appreciate your contributions to keeping our users safe.*
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
SUPABASE_PG_URL=postgresql://postgres:[email protected]:5432/postgres
SUPABASE_URL=https://xyz.supabase.co
SUPABASE_ANON_KEY=eyJ...
SUPABASE_SERVICE_ROLE_KEY=eyJ...
ACME_EMAIL=[email protected]
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
+47
View File
@@ -0,0 +1,47 @@
services:
db:
image: postgres:15-alpine
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: password
POSTGRES_DB: postgres
ports:
- "5432:5432"
wwv-cloud:
build:
context: ../..
dockerfile: Dockerfile
args:
- NEXT_PUBLIC_WWV_EDITION=cloud
restart: always
environment:
NEXT_PUBLIC_WWV_EDITION: cloud
DATABASE_URL: postgresql://postgres:password@db:5432/postgres
NEXT_PUBLIC_SUPABASE_URL: ${SUPABASE_URL:-http://dummy}
NEXT_PUBLIC_SUPABASE_ANON_KEY: ${SUPABASE_ANON_KEY:-dummy}
SUPABASE_SERVICE_ROLE_KEY: ${SUPABASE_SERVICE_ROLE_KEY:-dummy}
AUTH_SECRET: ${AUTH_SECRET:-dummy_secret_for_local_testing_only_1234567890}
ports:
- "3001:3000"
labels:
- "traefik.enable=true"
- "traefik.http.routers.wwv.rule=HostRegexp(`{user:[a-z0-9-]+}.app.worldwideview.dev`) || Host(`app.worldwideview.dev`) || Host(`localhost`) || HostRegexp(`{user:[a-z0-9-]+}.localhost`)"
- "traefik.http.routers.wwv.entrypoints=web,websecure"
# - "traefik.http.routers.wwv.tls.certresolver=letsencrypt"
- "traefik.http.services.wwv.loadbalancer.server.port=3000"
depends_on:
- db
traefik:
image: traefik:v3.0
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
ports:
- "80:80"
- "443:443"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
+25
View File
@@ -12,9 +12,34 @@ 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}"
depends_on:
db:
condition: service_healthy
db:
image: postgres:15-alpine
restart: always
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
ports:
- "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
interval: 5s
timeout: 5s
retries: 5
start_period: 60s
profiles:
- "${WWV_SKIP_LOCAL_DB:-}"
volumes:
wwv-data:
postgres-data:
networks:
coolify:
+38 -5
View File
@@ -1,14 +1,47 @@
#!/bin/sh
# ─── Docker Entrypoint ───────────────────────────────────────
# Ensures the SQLite database exists and is migrated before
# starting the application. On first run with a fresh volume
# the DB file won't exist yet, so we run prisma migrate deploy.
# Ensures the PostgreSQL database is migrated before starting
# the application. DATABASE_URL must point to a PostgreSQL
# instance (Supabase, self-hosted, etc).
set -e
mkdir -p ./data
if [ -z "$DATABASE_URL" ]; then
echo "────────────────────────────────────────────────────────────────"
echo "🚨 CRITICAL: DATABASE_URL IS NOT SET"
echo "────────────────────────────────────────────────────────────────"
echo "WorldWideView has migrated to PostgreSQL. If you are an old user,"
echo "please update your docker-compose.yml to include a Postgres service."
echo ""
echo "To migrate your legacy data after setting up Postgres, run:"
echo "docker exec -it <container_name> node scripts/migrate-legacy.mjs"
echo "────────────────────────────────────────────────────────────────"
# If dev.db exists, we know they are upgrading. Don't crash, just wait for config.
if [ -f "prisma/dev.db" ]; then
echo "[entrypoint] Legacy data detected. Waiting for DATABASE_URL to be configured..."
# We don't exit here, we'll let the app try to start or just sleep.
# For now, let's just let it proceed so they can see the setup page error.
else
echo "[entrypoint] Exiting. Please provide a DATABASE_URL."
exit 1
fi
fi
echo "[entrypoint] Running database migrations..."
npx -y prisma migrate deploy
prisma migrate deploy
echo "[entrypoint] Migrations complete."
# Generate self-signed SSL certificates for local HTTPS bridging if they don't exist
if [ ! -f "./data/localhost.crt" ] || [ ! -f "./data/localhost.key" ]; then
echo "[entrypoint] Generating self-signed SSL certificates for port 3001..."
mkdir -p ./data
openssl req -nodes -new -x509 -keyout ./data/localhost.key -out ./data/localhost.crt -days 365 -subj "/CN=localhost" 2>/dev/null || echo "[entrypoint] Warning: Failed to generate SSL certs"
fi
# Start the HTTPS proxy in the background
if [ -f "./scripts/https-proxy.mjs" ]; then
node ./scripts/https-proxy.mjs &
fi
exec node server.js
+1 -1
View File
@@ -12,7 +12,7 @@ The core design philosophy is the "All-Bundle Model," where plugins are dynamica
- **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 local SQLite or cloud PostgreSQL (in `prisma/`).
- **Database Layer:** Prisma ORM connecting to PostgreSQL (in `prisma/`).
## Key Files
- `src/core/plugins/PluginManager.ts` - The PluginManager class. Core registry that instantiates plugins, calls `initialize()`, and handles lifecycle events.
+1 -1
View File
@@ -20,7 +20,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 SQLite tables exist in `data/wwv.db`.
- **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.
- **Microservices:** Data engine seeders and standalone Fastify backend plugins (like `wwv-plugin-iranwarlive/backend`) are started via `pnpm start:backends` and managed locally inside `packages/*/backend`.
- **Plugin Packages:** Internal plugin packages must be properly listed in `tsconfig.json` paths and `next.config.ts`'s `transpilePackages` array.
+35 -3
View File
@@ -18,17 +18,49 @@ WorldWideView utilizes a containerized deployment strategy based on Docker's mul
### Coolify Integration
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:** SQLite requires a persistent volume mounted to `/app/data` to ensure the frontend registry (installed plugins, user configs) survives container rebuilds.
- **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.
- **Microservices Deployment:** The `wwv-data-engine-internal` and associated plugin seeders are deployed as separate Coolify services communicating over private internal networks.
### 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.
- **Compose:** Local multi-container emulation is handled via `docker-compose.yml`.
## Reverse Proxies (Nginx Proxy Manager)
When deploying WorldWideView behind a reverse proxy like Nginx Proxy Manager (NPM), you must configure both the proxy and the container environment correctly to prevent NextAuth from hanging during login, and to allow the real-time Cesium data stream to function.
### Container Environment Variables
NextAuth v5 requires strict host trust when placed behind a proxy. Add the following to your Docker `.env` file or Coolify environment variables:
```bash
# Required: Tells NextAuth to trust the reverse proxy headers
AUTH_TRUST_HOST=true
# Required: The exact external URL your users visit
NEXTAUTH_URL=https://your-domain.com
```
### Nginx Proxy Manager Configuration
In the NPM UI for your WorldWideView Proxy Host:
1. **Details Tab:** Ensure **Websockets Support** is toggled **ON** (Required for the live `/stream` telemetry).
2. **Details Tab:** Ensure **Force SSL** is toggled **ON**. NextAuth will often refuse authentication flows over plain HTTP.
3. **Advanced Tab:** Nginx Proxy Manager sometimes fails to pass the correct host headers required by Next.js. Add the following to the Custom Nginx Configuration box:
```nginx
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header Host $host;
# Optional: Disable proxy buffering if 3D tiles load slowly
proxy_buffering off;
proxy_request_buffering off;
```
## Reference
- **Standalone Config:** `next.config.ts` (sets `output: "standalone"`).
- **Prisma Export:** `prisma.config.ts` ensures no CLI wrappers are invoked inside the standalone container, preventing fatal `MODULE_NOT_FOUND` runtime crashes.
- **Docker Mounts:**
- Main App: `/app/data` (SQLite DB)
- Data Engine: `/app/packages/wwv-data-engine/data` (SQLite DB)
- Main App: PostgreSQL data volume (if running in-cluster)
- Data Engine: PostgreSQL data volume (if running in-cluster)
- Cache: `/data` (Redis)
+1 -1
View File
@@ -24,7 +24,7 @@ The system is highly modularized to separate React UI rendering from heavy Cesiu
- `docker-compose.yml` - Defines the orchestration of the frontend, Redis cache, and all local plugin microservice backends (`wwv-data-engine`).
## Configuration
- `prisma/schema.prisma` - Local SQLite and cloud PostgreSQL database schema for storing user settings and installed plugin manifests.
- `prisma/schema.prisma` - PostgreSQL database schema for storing user settings and installed plugin manifests.
- `scripts/copy-cesium.mjs` - Crucial build-time script that extracts and copies CesiumJS static web workers to `public/cesium/`.
- `public/` - Static assets, plugin icons, and compiled Cesium workers.
+1 -1
View File
@@ -17,7 +17,7 @@ The core value proposition of WorldWideView is mapping diverse, decoupled intell
- **3D Engine:** CesiumJS + Resium (Google Photorealistic 3D Tiles) — `src/core/globe/GlobeView.tsx`
- **State Management:** Zustand — `src/core/state/` (slice-based store)
- **Event Bus:** Custom typed `DataBus` — `src/core/data/DataBus.ts`
- **Database:** SQLite via Prisma (local), PostgreSQL (cloud) — `prisma/schema.prisma`
- **Database:** PostgreSQL via Prisma 7 — `prisma/schema.prisma`
- **Styling:** Vanilla CSS (no Tailwind) — `src/app/globals.css`
## Platform Support
+18
View File
@@ -15,6 +15,9 @@ pnpm install
Write-Host "[*] Running initial setup (generating secrets)..."
pnpm run setup
Write-Host "[*] Generating Prisma client..."
npx prisma generate
# Check for the sibling Data Engine repository
if (-not (Test-Path "../wwv-data-engine")) {
Write-Host ""
@@ -32,6 +35,21 @@ if (-not (Test-Path "../wwv-data-engine")) {
Write-Host ""
}
Write-Host ""
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host "[!] DATABASE SETUP REQUIRED" -ForegroundColor Cyan
Write-Host ""
Write-Host "WorldWideView uses PostgreSQL. Choose one option:" -ForegroundColor White
Write-Host ""
Write-Host " Option A (Easiest): Run Prisma's built-in local database:" -ForegroundColor Green
Write-Host " npx prisma dev" -ForegroundColor Yellow
Write-Host " (Copy the DATABASE_URL it prints into your .env.local file)" -ForegroundColor Gray
Write-Host ""
Write-Host " Option B: Use your own PostgreSQL or Supabase instance:" -ForegroundColor Green
Write-Host " Set DATABASE_URL in .env.local to your connection string" -ForegroundColor Gray
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "[*] Starting local Next.js frontend server..."
Write-Host " (To run the data engine backends concurrently, run: pnpm dev:all)"
pnpm run dev
+9 -6
View File
@@ -2,16 +2,17 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
serverExternalPackages: ["better-sqlite3", "@prisma/adapter-better-sqlite3", "@prisma/client", "prisma"],
transpilePackages: ["@worldwideview/wwv-plugin-sdk","resium",
"react-player",
"satellite.js"
],
serverExternalPackages: ["@prisma/client", "prisma"],
transpilePackages: ["@worldwideview/wwv-plugin-sdk", "resium", "react-player", "satellite.js"],
allowedDevOrigins: process.env.ALLOWED_DEV_ORIGIN ? [process.env.ALLOWED_DEV_ORIGIN] : undefined,
experimental: {
memoryBasedWorkersCount: true,
cpus: 2,
optimizePackageImports: ["lucide-react"],
},
outputFileTracingIncludes: {
"/*": ["./scripts/**/*"],
},
typescript: {
ignoreBuildErrors: true,
},
@@ -54,7 +55,9 @@ const nextConfig: NextConfig = {
},
outputFileTracingExcludes: {
"*": ["./public/cesium/**"],
"*": [
"./public/cesium/**"
],
},
env: {
CESIUM_BASE_URL: "/cesium",
+31 -22
View File
@@ -1,7 +1,9 @@
{
"name": "worldwideview",
"version": "1.19.5",
"version": "2.1.6",
"private": true,
"type": "module",
"packageManager": "[email protected]",
"scripts": {
"setup": "node scripts/setup.mjs",
"test-worktree": "node scripts/test-worktree.mjs",
@@ -9,39 +11,46 @@
"dev": "next dev --webpack",
"dev:all": "concurrently -n \"next,backends\" -c \"magenta,blue\" \"pnpm dev\" \"pnpm dev:backends\"",
"dev:backends": "cd ../wwv-data-engine && pnpm dev",
"predev": "npx prisma migrate deploy && node scripts/copy-cesium.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",
"copy-cesium": "node scripts/copy-cesium.mjs",
"prebuild": "node scripts/check-build-env.mjs",
"build": "next build --webpack",
"start": "next start",
"test": "vitest run",
"db:reset": "npx prisma migrate reset --force"
"db:reset": "npx prisma migrate reset --force",
"generate": "prisma generate"
},
"dependencies": {
"@auth/prisma-adapter": "^2.11.1",
"@prisma/adapter-better-sqlite3": "^7.5.0",
"@prisma/client": "^7.5.0",
"@sentry/nextjs": "^10.48.0",
"@supabase/supabase-js": "^2.98.0",
"@auth/prisma-adapter": "^2.11.2",
"@auth/supabase-adapter": "^1.11.2",
"@prisma/adapter-pg": "^7.8.0",
"@prisma/client": "^7.8.0",
"@prisma/client-runtime-utils": "7.8.0",
"@sentry/nextjs": "^10.52.0",
"@supabase/supabase-js": "^2.105.4",
"@types/pg": "^8.20.0",
"@vercel/analytics": "^1.6.1",
"@worldwideview/wwv-plugin-sdk": "workspace:*",
"bcryptjs": "^3.0.3",
"cesium": "^1.139.0",
"cesium": "^1.141.0",
"cheerio": "^1.2.0",
"hls.js": "^1.6.15",
"hls.js": "^1.6.16",
"insecam-api": "^0.0.3",
"jose": "^6.2.2",
"jose": "^6.2.3",
"lucide-react": "^0.576.0",
"next": "16.2.3",
"next": "16.2.6",
"next-auth": "^5.0.0-beta.30",
"prisma": "^7.5.0",
"react": "19.2.3",
"react-dom": "19.2.3",
"pg": "^8.20.0",
"prisma": "^7.8.0",
"react": "19.2.6",
"react-dom": "19.2.6",
"react-player": "^3.4.0",
"resium": "1.19.4",
"resium": "1.21.0",
"satellite.js": "^7.0.0",
"stripe": "^22.1.1",
"tslib": "^2.8.1",
"ws": "^8.14.2",
"zustand": "^5.0.11"
"zustand": "^5.0.13"
},
"devDependencies": {
"@testing-library/dom": "^10.4.1",
@@ -57,19 +66,19 @@
"copy-webpack-plugin": "^14.0.0",
"jsdom": "^28.1.0",
"rollup-plugin-external-globals": "^0.13.0",
"tsx": "^4.21.0",
"typescript": "^5",
"vite": "^8.0.8",
"vitest": "^4.0.18"
"vite": "^8.0.11",
"vitest": "^4.1.5"
},
"pnpm": {
"onlyBuiltDependencies": [
"@prisma/engines",
"better-sqlite3",
"esbuild",
"@sentry/cli",
"prisma",
"protobufjs",
"sharp",
"unrs-resolver"
"esbuild"
]
}
}
+1089 -1737
View File
File diff suppressed because it is too large. Load diff
+14 -4
View File
@@ -5,14 +5,24 @@ let dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
try {
const envPath = path.resolve(process.cwd(), ".env");
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, "utf8");
const match = envContent.match(/^DATABASE_URL=(.*)$/m);
const envLocalPath = path.resolve(process.cwd(), ".env.local");
if (fs.existsSync(envLocalPath)) {
const envContent = fs.readFileSync(envLocalPath, "utf8");
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
if (match) {
dbUrl = match[1].trim();
}
}
if (!dbUrl) {
const envPath = path.resolve(process.cwd(), ".env");
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, "utf8");
const match = envContent.match(/^DATABASE_URL=["']?(.*?)["']?$/m);
if (match) {
dbUrl = match[1].trim();
}
}
}
} catch (e) {
// Ignore
}
@@ -0,0 +1,103 @@
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"tenantId" TEXT,
"email" TEXT NOT NULL,
"name" TEXT NOT NULL,
"hashedPassword" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'user',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "favorites" (
"id" TEXT NOT NULL,
"tenantId" TEXT,
"entityId" TEXT NOT NULL,
"pluginId" TEXT NOT NULL,
"label" TEXT NOT NULL,
"pluginName" TEXT NOT NULL,
"lastSeen" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"userId" TEXT NOT NULL,
CONSTRAINT "favorites_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "installed_plugins" (
"id" TEXT NOT NULL,
"tenantId" TEXT,
"pluginId" TEXT NOT NULL,
"version" TEXT NOT NULL,
"config" TEXT NOT NULL DEFAULT '{}',
"enabled" BOOLEAN NOT NULL DEFAULT true,
"installedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "installed_plugins_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "settings" (
"id" TEXT NOT NULL,
"tenantId" TEXT,
"key" TEXT NOT NULL,
"value" TEXT NOT NULL,
CONSTRAINT "settings_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "workspaces" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"subdomain" TEXT NOT NULL,
"status" TEXT NOT NULL DEFAULT 'trialing',
"plan" TEXT NOT NULL DEFAULT 'basic',
"stripeCustomerId" TEXT,
"stripeSubscriptionId" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "workspaces_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "workspace_members" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"workspaceId" TEXT NOT NULL,
"role" TEXT NOT NULL DEFAULT 'member',
"joinedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "workspace_members_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "users_tenantId_email_key" ON "users"("tenantId", "email");
-- CreateIndex
CREATE UNIQUE INDEX "favorites_userId_entityId_key" ON "favorites"("userId", "entityId");
-- CreateIndex
CREATE UNIQUE INDEX "installed_plugins_tenantId_pluginId_key" ON "installed_plugins"("tenantId", "pluginId");
-- CreateIndex
CREATE UNIQUE INDEX "settings_tenantId_key_key" ON "settings"("tenantId", "key");
-- CreateIndex
CREATE UNIQUE INDEX "workspaces_subdomain_key" ON "workspaces"("subdomain");
-- CreateIndex
CREATE UNIQUE INDEX "workspace_members_userId_workspaceId_key" ON "workspace_members"("userId", "workspaceId");
-- AddForeignKey
ALTER TABLE "favorites" ADD CONSTRAINT "favorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "workspace_members" ADD CONSTRAINT "workspace_members_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "workspace_members" ADD CONSTRAINT "workspace_members_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES "workspaces"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+1 -1
View File
@@ -1,3 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "sqlite"
provider = "postgresql"
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (e.g., Git)
provider = "sqlite"
+49 -8
View File
@@ -1,29 +1,34 @@
// Prisma schema — SQLite for local, PostgreSQL for cloud.
// Connection URL configured in prisma.config.ts
// 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 = "sqlite"
provider = "postgresql"
}
generator client {
provider = "prisma-client"
provider = "prisma-client-js"
output = "../src/generated/prisma"
}
model User {
id String @id @default(uuid())
email String @unique
tenantId String?
email String
name String
hashedPassword String
role String @default("user")
createdAt DateTime @default(now())
favorites Favorite[]
memberships WorkspaceMember[]
@@unique([tenantId, email])
@@map("users")
}
model Favorite {
id String @id @default(uuid())
tenantId String?
entityId String
pluginId String
label String
@@ -58,19 +63,55 @@ model Favorite {
model InstalledPlugin {
id String @id @default(uuid())
pluginId String @unique
tenantId String?
pluginId String
version String
config String @default("{}")
enabled Boolean @default(true)
installedAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([tenantId, pluginId])
@@map("installed_plugins")
}
model Setting {
key String @id
value String
id String @id @default(uuid())
tenantId String?
key String
value String
@@unique([tenantId, key])
@@map("settings")
}
// NEW — Global workspace registry
model Workspace {
id String @id @default(uuid())
name String
subdomain String @unique
status String @default("trialing")
plan String @default("basic")
stripeCustomerId String?
stripeSubscriptionId String?
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)
@@unique([userId, workspaceId])
@@map("workspace_members")
}
Vendored Regular → Executable
View File
File mode changed.
+64
View File
@@ -0,0 +1,64 @@
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
// Load environment variables manually since dotenv might not be installed globally
const loadEnv = (file) => {
try {
if (fs.existsSync(file)) {
const content = fs.readFileSync(file, 'utf8');
content.split('\n').forEach(line => {
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
if (match) {
const key = match[1];
let value = match[2] || '';
// Remove quotes
if (value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
if (value.startsWith("'") && value.endsWith("'")) value = value.slice(1, -1);
process.env[key] = value;
}
});
}
} catch (e) {
// Ignore read errors
}
};
loadEnv('.env');
loadEnv('.env.local');
const skipLocalDb = process.env.WWV_SKIP_LOCAL_DB === 'true' || process.env.WWV_SKIP_LOCAL_DB === '1';
if (skipLocalDb) {
console.log('⏭️ Skipping local PostgreSQL startup (WWV_SKIP_LOCAL_DB is set).');
process.exit(0);
}
console.log('🚀 Checking local PostgreSQL database...');
try {
// Check if docker is installed
try {
execSync('docker --version', { stdio: 'ignore' });
} catch (e) {
console.log('⚠️ Docker is not installed or not in PATH. Skipping local database startup.');
console.log('💡 If you want to run a local database automatically, please install Docker Desktop.');
process.exit(0);
}
// Start the db service using docker compose
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);
console.log('✅ Local PostgreSQL database is ready!');
} catch (error) {
console.error('❌ Failed to start local database:', error.message);
console.log('💡 You may need to start it manually or set WWV_SKIP_LOCAL_DB=true to use an external database.');
}
+30
View File
@@ -0,0 +1,30 @@
/**
* Pre-build sanity check for build-time public env vars.
*
* Some NEXT_PUBLIC_* vars are inlined into the client bundle by Next.js at
* build time, so they must be set when `next build` runs (not just at runtime).
* Missing ones don't fail the build — most have library defaults — but they
* surface as opaque runtime 401s / blank panes that are painful to diagnose.
*
* This script prints actionable warnings instead.
*/
const checks = [
{
name: "NEXT_PUBLIC_CESIUM_ION_TOKEN",
why: "Cesium ships a built-in default Ion token, but Cesium periodically revokes it. Without your own token, base imagery and world terrain may return 401 Unauthorized at runtime.",
how: "Get a free token at https://ion.cesium.com and set NEXT_PUBLIC_CESIUM_ION_TOKEN before building (e.g. in .env).",
},
];
const missing = checks.filter(c => !process.env[c.name]);
if (missing.length === 0) process.exit(0);
const yellow = (s) => `\x1b[33m${s}\x1b[0m`;
console.warn(yellow("\n⚠ Build-time env vars not set:"));
for (const c of missing) {
console.warn(yellow(`\n ${c.name}`));
console.warn(` ${c.why}`);
console.warn(` Fix: ${c.how}`);
}
console.warn(yellow("\nContinuing build — these are warnings, not errors.\n"));
+23
View File
@@ -0,0 +1,23 @@
import { prisma } from "../src/lib/db";
async function main() {
const plugins = await prisma.installedPlugin.findMany();
console.log("Installed plugins:");
plugins.forEach((p) => console.log(` ${p.pluginId} | config: ${p.config.substring(0, 60)}`));
const geojson = plugins.find((p) => p.pluginId === "geojson");
if (geojson) {
await prisma.installedPlugin.delete({ where: { id: geojson.id } });
console.log("\nDeleted orphaned 'geojson' record.");
} else {
console.log("\nNo orphaned 'geojson' record found.");
}
const remaining = await prisma.installedPlugin.findMany();
console.log("\nRemaining plugins:");
remaining.forEach((p) => console.log(` ${p.pluginId}`));
await prisma.$disconnect();
}
main().catch(console.error);
+51
View File
@@ -0,0 +1,51 @@
import https from 'https';
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const targetPort = 3000;
const listenPort = 3001;
const certPath = path.join(process.cwd(), 'data', 'localhost.crt');
const keyPath = path.join(process.cwd(), 'data', 'localhost.key');
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
console.error('[HTTPS Proxy] Certificates not found. Proxy will not start.');
process.exit(1);
}
const options = {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath)
};
const server = https.createServer(options, (req, res) => {
const proxyReq = http.request({
hostname: '127.0.0.1',
port: targetPort,
path: req.url,
method: req.method,
headers: {
...req.headers,
'x-forwarded-proto': 'https',
'x-forwarded-port': String(listenPort)
}
}, (proxyRes) => {
res.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});
proxyReq.on('error', (e) => {
console.error(`[HTTPS Proxy] Error proxying request to ${req.url}:`, e.message);
res.writeHead(502);
res.end('Bad Gateway');
});
req.pipe(proxyReq, { end: true });
});
server.listen(listenPort, '0.0.0.0', () => {
console.log(`[HTTPS Proxy] Secure bridge listening on https://0.0.0.0:${listenPort} (forwarding to http://127.0.0.1:${targetPort})`);
});
+39
View File
@@ -0,0 +1,39 @@
import { prisma } from "../src/lib/db";
import { hashSync } from "bcryptjs";
async function main() {
const action = process.argv[2];
if (action === "list") {
const users = await prisma.user.findMany();
if (users.length === 0) {
console.log("No users found — visit /setup to create one.");
} else {
users.forEach((u) =>
console.log(` ${u.email} | ${u.name} | ${u.role} | ${u.createdAt}`)
);
}
} else if (action === "reset") {
const email = process.argv[3];
const newPass = process.argv[4];
if (!email || !newPass) {
console.log("Usage: tsx scripts/manage-users.ts reset <email> <password>");
return;
}
const hashed = hashSync(newPass, 12);
await prisma.user.update({
where: { email },
data: { hashedPassword: hashed },
});
console.log(`Password reset for ${email}`);
} else if (action === "delete-all") {
await prisma.user.deleteMany();
console.log("All users deleted — visit /setup to create a new admin.");
} else {
console.log("Usage: tsx scripts/manage-users.ts <list|reset|delete-all>");
}
await prisma.$disconnect();
}
main().catch(console.error);
+125
View File
@@ -0,0 +1,125 @@
/**
* @deprecated This script uses better-sqlite3 directly to migrate data
* from Supabase into the legacy data engine's SQLite database.
* It is NOT part of the main application's database layer.
* It will be removed once the data engine migration is complete.
*/
import { createClient } from "@supabase/supabase-js";
import Database from "better-sqlite3";
import path from "path";
import fs from "fs";
import dotenv from "dotenv";
// Load environment from .env.local
const envPath = path.resolve(process.cwd(), ".env.local");
if (fs.existsSync(envPath)) {
dotenv.config({ path: envPath });
} else {
dotenv.config();
}
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const SUPABASE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
if (!SUPABASE_URL || !SUPABASE_KEY) {
console.error("Missing Supabase credentials in .env.local");
process.exit(1);
}
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY);
// Connect to SQLite DB (respects DB_PATH, fallback to data engine location)
const defaultDbPath = path.resolve(process.cwd(), "packages/wwv-data-engine/data/engine.db");
const dbPath = process.env.DB_PATH || defaultDbPath;
console.log(`Connecting to SQLite at ${dbPath}...`);
// Ensure DB directory exists
const dbDir = path.dirname(dbPath);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');
// Ensure table exists (mirroring what we'll inject into Data Engine later)
db.exec(`
CREATE TABLE IF NOT EXISTS aviation_history (
icao24 TEXT NOT NULL,
ts INTEGER NOT NULL,
lat REAL,
lon REAL,
alt REAL,
hdg REAL,
spd REAL,
fetched_at INTEGER NOT NULL,
PRIMARY KEY (icao24, ts)
)
`);
const insertHistory = db.prepare(`
INSERT OR IGNORE INTO aviation_history (icao24, ts, lat, lon, alt, hdg, spd, fetched_at)
VALUES (@icao24, @ts, @lat, @lon, @alt, @hdg, @spd, @fetched_at)
`);
async function migrate() {
console.log("Fetching existing aviation_history records from Supabase...");
let offset = 0;
const limit = 10000; // Chunk size
let totalInserted = 0;
while (true) {
const { data, error } = await supabase
.from("aviation_history")
.select("*")
.range(offset, offset + limit - 1);
if (error) {
console.error("Fetch error:", error);
process.exit(1);
}
if (!data || data.length === 0) {
console.log("No more records to fetch.");
break;
}
console.log(`Processing ${data.length} records (Offset: ${offset})...`);
// Batch insert to SQLite
const insertMany = db.transaction((records) => {
for (const r of records) {
// Determine timestamp logic: Postgres is Timestamp so convert to epoch seconds
const tsMs = new Date(r.timestamp).getTime();
insertHistory.run({
icao24: r.icao24,
ts: Math.floor(tsMs / 1000),
lat: r.latitude,
lon: r.longitude,
alt: r.altitude,
hdg: r.heading,
spd: r.speed,
fetched_at: Math.floor(Date.now() / 1000)
});
}
});
try {
insertMany(data);
totalInserted += data.length;
} catch (err) {
console.error("SQLite Insert Error:", err);
}
if (data.length < limit) {
break;
}
offset += limit;
}
console.log(`Migration complete! Successfully injected ~${totalInserted} records into SQLite.`);
}
migrate();
+97
View File
@@ -0,0 +1,97 @@
import { DatabaseSync } from "node:sqlite";
import { PrismaClient } from "../src/generated/prisma/index.js";
import { PrismaPg } from "@prisma/adapter-pg";
import pg from "pg";
import path from "node:path";
import fs from "node:fs";
async function migrate() {
const targetPath = process.argv[2] || "data/wwv.db";
const sqlitePath = path.resolve(process.cwd(), targetPath);
if (!fs.existsSync(sqlitePath)) {
console.error(`❌ No legacy SQLite database found at ${targetPath}`);
console.error("💡 Usage: node scripts/migrate-legacy.mjs [path-to-db]");
process.exit(1);
}
console.log(`📂 Found legacy database at ${targetPath}. Initializing migration...`);
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });
const db = new DatabaseSync(sqlitePath);
try {
// 1. Migrate Users
console.log("👤 Migrating users...");
const users = db.prepare("SELECT * FROM users").all();
for (const user of users) {
await prisma.user.upsert({
where: { id: user.id },
update: {},
create: {
id: user.id,
email: user.email,
name: user.name,
hashedPassword: user.hashedPassword,
role: user.role,
createdAt: new Date(user.createdAt),
}
});
}
// 2. Migrate Favorites
console.log("⭐️ Migrating favorites...");
const favorites = db.prepare("SELECT * FROM favorites").all();
for (const fav of favorites) {
await prisma.favorite.upsert({
where: { id: fav.id },
update: {},
create: {
id: fav.id,
userId: fav.userId,
entityId: fav.entityId,
pluginId: fav.pluginId,
label: fav.label,
pluginName: fav.pluginName,
lastSeen: new Date(fav.lastSeen),
}
});
}
// 3. Migrate Settings
console.log("⚙️ Migrating settings...");
const settings = db.prepare("SELECT * FROM settings").all();
for (const setting of settings) {
const existing = await prisma.setting.findFirst({
where: { key: setting.key, tenantId: setting.tenantId || null }
});
if (existing) {
await prisma.setting.update({
where: { id: existing.id },
data: { value: setting.value }
});
} else {
await prisma.setting.create({
data: {
id: setting.id || undefined, // Let Prisma generate if undefined
tenantId: setting.tenantId || null,
key: setting.key,
value: setting.value,
}
});
}
}
console.log("✅ Migration successful! All data moved to PostgreSQL.");
console.log("💡 You can now safely delete prisma/dev.db");
} catch (error) {
console.error("❌ Migration failed:", error);
} finally {
await prisma.$disconnect();
}
}
migrate();
+42
View File
@@ -0,0 +1,42 @@
services:
wwv:
image: ghcr.io/silvertakana/worldwideview:latest
pull_policy: always
ports:
- "3000:3000"
volumes:
- wwv-data:/app/data
env_file:
- path: .env
required: false
environment:
- "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
depends_on:
db:
condition: service_healthy
db:
image: postgres:15-alpine
restart: unless-stopped
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: worldwideview
ports:
- "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres -d worldwideview"]
interval: 5s
timeout: 5s
retries: 5
start_period: 60s
volumes:
wwv-data:
postgres-data:
+8 -21
View File
@@ -20,25 +20,8 @@ try {
}
# Generate docker-compose.yml
Write-Host "[*] Creating docker-compose.yml..."
$dockerCompose = @(
"services:"
" wwv:"
" image: ghcr.io/silvertakana/worldwideview:latest"
" ports:"
" - `"3000:3000`""
" volumes:"
" - wwv-data:/app/data"
" env_file:"
" - .env"
" restart: unless-stopped"
""
"volumes:"
" wwv-data:"
)
$dockerCompose | Out-File -FilePath docker-compose.yml -Encoding utf8
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)) {
@@ -46,8 +29,12 @@ if (-Not (Test-Path .env)) {
$bytes = New-Object Byte[] 32
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$secret = -join ($bytes | ForEach-Object { $_.ToString("x2") })
"AUTH_SECRET=$secret" | Out-File -FilePath .env -Encoding ascii
"NEXT_PUBLIC_WWV_EDITION=local" | Out-File -FilePath .env -Encoding ascii -Append
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."
}
+9 -19
View File
@@ -17,23 +17,9 @@ if ! docker compose version > /dev/null 2>&1; then
exit 1
fi
# 1. Generate docker-compose.yml
echo "📦 Creating docker-compose.yml..."
cat > docker-compose.yml << 'EOF'
services:
wwv:
image: ghcr.io/silvertakana/worldwideview:latest
ports:
- "3000:3000"
volumes:
- wwv-data:/app/data
env_file:
- .env
restart: unless-stopped # ← Auto-starts on boot
volumes:
wwv-data:
EOF
# 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
@@ -44,8 +30,12 @@ if [ ! -f .env ]; then
else
SECRET=$(head -c 32 /dev/urandom | xxd -p)
fi
echo "AUTH_SECRET=$SECRET" > .env
echo "NEXT_PUBLIC_WWV_EDITION=local" >> .env
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
+11 -21
View File
@@ -20,25 +20,8 @@ try {
}
# Generate docker-compose.yml
Write-Host "[*] Creating docker-compose.yml..."
$dockerCompose = @(
"services:"
" wwv:"
" image: ghcr.io/silvertakana/worldwideview:latest"
" ports:"
" - `"3000:3000`""
" volumes:"
" - wwv-data:/app/data"
" env_file:"
" - .env"
" restart: unless-stopped"
""
"volumes:"
" wwv-data:"
)
$dockerCompose | Out-File -FilePath docker-compose.yml -Encoding utf8
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)) {
@@ -46,12 +29,19 @@ if (-Not (Test-Path .env)) {
$bytes = New-Object Byte[] 32
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$secret = -join ($bytes | ForEach-Object { $_.ToString("x2") })
"AUTH_SECRET=$secret" | Out-File -FilePath .env -Encoding ascii
"NEXT_PUBLIC_WWV_EDITION=local" | Out-File -FilePath .env -Encoding ascii -Append
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 "[*] Pulling latest image updates..."
docker compose pull
Write-Host "[*] Starting Docker container..."
docker compose up -d
+12 -19
View File
@@ -17,23 +17,9 @@ if ! docker compose version > /dev/null 2>&1; then
exit 1
fi
# 1. Generate docker-compose.yml
echo "📦 Creating docker-compose.yml..."
cat > docker-compose.yml << 'EOF'
services:
wwv:
image: ghcr.io/silvertakana/worldwideview:latest
ports:
- "3000:3000"
volumes:
- wwv-data:/app/data
env_file:
- .env
restart: unless-stopped # ← Auto-starts on boot
volumes:
wwv-data:
EOF
# 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
@@ -44,13 +30,20 @@ if [ ! -f .env ]; then
else
SECRET=$(head -c 32 /dev/urandom | xxd -p)
fi
echo "AUTH_SECRET=$SECRET" > .env
echo "NEXT_PUBLIC_WWV_EDITION=local" >> .env
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 "📥 Pulling latest image updates..."
docker compose pull
echo "🚀 Starting Docker container..."
docker compose up -d
+18
View File
@@ -31,6 +31,24 @@
"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",
+21
View File
@@ -0,0 +1,21 @@
import { stripe } from "@/lib/stripe/client";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
export async function POST(req: Request) {
const session = await auth();
if (!session?.user) return new NextResponse("Unauthorized", { status: 401 });
const { priceId } = await req.json();
const checkoutSession = await stripe.checkout.sessions.create({
mode: "subscription",
payment_method_types: ["card"],
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?success=true`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/settings?canceled=true`,
client_reference_id: session.user.id,
});
return NextResponse.json({ url: checkoutSession.url });
}
+26
View File
@@ -0,0 +1,26 @@
import { stripe } from "@/lib/stripe/client";
import { NextResponse } from "next/server";
export async function POST(req: Request) {
const body = await req.text();
const sig = req.headers.get("stripe-signature");
let event;
try {
event = stripe.webhooks.constructEvent(
body,
sig!,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (err: any) {
return new NextResponse(`Webhook Error: ${err.message}`, { status: 400 });
}
if (event.type === "checkout.session.completed") {
console.log("Subscription completed!");
// Update user tier in DB, send license key via email
}
return new NextResponse(null, { status: 200 });
}
+9
View File
@@ -0,0 +1,9 @@
import { fetchCaltransCameras } from "../caltrans/caltransFetcher";
import type { CameraAdapter, CameraFeature } from "./types";
export const caltransAdapter: CameraAdapter = {
id: "caltrans",
displayName: "Caltrans (California)",
region: "United States — California",
fetch: async () => (await fetchCaltransCameras()) as CameraFeature[],
};
+35
View File
@@ -0,0 +1,35 @@
import { fetchGdotCameras } from "../gdot/gdotFetcher";
import type { CameraAdapter, CameraFeature } from "./types";
// GDOT's snapshot infrastructure (navigator-c2c.dot.ga.gov, vss5live.dot.ga.gov)
// has been retired upstream as of 2026 — both hosts NXDOMAIN. The metadata
// API still returns those URLs, so strip them so the client doesn't trigger
// DNS errors on click. Drop these entries from the filter list once GDOT
// publishes a working snapshot endpoint.
const DEAD_STREAM_HOSTS = [
"navigator-c2c.dot.ga.gov",
"vss5live.dot.ga.gov",
];
function isDeadHost(url: string | null | undefined): boolean {
if (!url) return false;
return DEAD_STREAM_HOSTS.some((h) => url.includes(h));
}
export const gdotAdapter: CameraAdapter = {
id: "gdot",
displayName: "GDOT (Georgia)",
region: "United States — Georgia",
fetch: async () => {
const features = (await fetchGdotCameras()) as CameraFeature[];
return features.map((f) => {
const p = f.properties;
const stream = isDeadHost(p.stream) ? null : (p.stream ?? null);
const hls = isDeadHost(p.hls) ? null : (p.hls ?? null);
return {
...f,
properties: { ...p, stream, hls },
};
});
},
};
+9
View File
@@ -0,0 +1,9 @@
import { fetch511NyCameras } from "../ny511/ny511Fetcher";
import type { CameraAdapter, CameraFeature } from "./types";
export const ny511Adapter: CameraAdapter = {
id: "ny511",
displayName: "511NY (New York State)",
region: "United States — New York",
fetch: async () => (await fetch511NyCameras()) as CameraFeature[],
};
+131
View File
@@ -0,0 +1,131 @@
import type { CameraAdapter, CameraAdapterMeta, CameraFeature } from "./types";
import { caltransAdapter } from "./caltrans";
import { gdotAdapter } from "./gdot";
import { tflAdapter } from "./tfl";
import { ny511Adapter } from "./ny511";
import { wsdotAdapter } from "./wsdot";
/**
* All registered adapters. To add a new source, add an import + push the
* adapter object here. No other file needs to change for the new source
* to appear in `/api/camera/list`, `/api/camera/traffic?sources=...`, and
* the client's source-picker UI.
*/
export const ALL_ADAPTERS: CameraAdapter[] = [
caltransAdapter,
gdotAdapter,
tflAdapter,
ny511Adapter,
wsdotAdapter,
];
const ADAPTERS_BY_ID: Map<string, CameraAdapter> = new Map(
ALL_ADAPTERS.map((a) => [a.id, a]),
);
const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
interface CacheEntry {
data: CameraFeature[];
expiry: number;
fetchedAt: string;
error?: string;
}
const cache: Map<string, CacheEntry> = new Map();
export function getAdapter(id: string): CameraAdapter | undefined {
return ADAPTERS_BY_ID.get(id);
}
/**
* Resolve a `?sources=` query value into a list of adapter ids.
* - empty / unset / "all" → all known adapter ids
* - "none" → empty list (clients use this to short-circuit)
* - comma-separated list → only the registered ones, unknown ids dropped
*/
export function resolveSources(raw: string | null): string[] {
if (!raw || raw === "all") return ALL_ADAPTERS.map((a) => a.id);
if (raw === "none") return [];
const requested = raw.split(",").map((s) => s.trim()).filter(Boolean);
return requested.filter((id) => ADAPTERS_BY_ID.has(id));
}
function isKeyAvailable(adapter: CameraAdapter): boolean {
if (!adapter.requiresKey) return true;
return !!process.env[adapter.requiresKey.envVar];
}
/** Return all adapter metadata for `/api/camera/list`. */
export function getAdapterMetadata(): CameraAdapterMeta[] {
return ALL_ADAPTERS.map((a) => {
const c = cache.get(a.id);
const keyOk = isKeyAvailable(a);
return {
id: a.id,
displayName: a.displayName,
region: a.region,
requiresKey: a.requiresKey,
healthy: keyOk && !!c && !c.error,
lastFetchedAt: c?.fetchedAt ?? null,
lastFeatureCount: c ? c.data.length : null,
lastError: c?.error,
};
});
}
/**
* Fetch a single adapter's data with per-adapter caching.
* Each adapter has its own TTL (default 24h, overridable via `cacheTtlMs`),
* so fast sources can refresh hourly while slow ones stay daily.
*
* On error: returns the stale cached value if present, or rethrows. Either
* way, the cache entry's `error` field is set so `/api/camera/list` can
* report unhealthy adapters.
*/
export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeature[]> {
if (!isKeyAvailable(adapter)) {
return [];
}
const now = Date.now();
const ttl = adapter.cacheTtlMs ?? DEFAULT_TTL_MS;
const c = cache.get(adapter.id);
if (c && now < c.expiry && !c.error) {
return c.data;
}
try {
const data = await adapter.fetch();
cache.set(adapter.id, {
data,
expiry: now + ttl,
fetchedAt: new Date(now).toISOString(),
});
return data;
} catch (e: any) {
const errMsg = e?.message ?? String(e);
if (c) {
cache.set(adapter.id, { ...c, error: errMsg });
return c.data;
}
cache.set(adapter.id, {
data: [],
expiry: now + 60_000, // short retry window on first failure
fetchedAt: new Date(now).toISOString(),
error: errMsg,
});
throw e;
}
}
/** Fetch many adapters in parallel and merge the results. */
export async function fetchManyAdapters(ids: string[]): Promise<CameraFeature[]> {
const adapters = ids
.map((id) => ADAPTERS_BY_ID.get(id))
.filter((a): a is CameraAdapter => !!a);
const results = await Promise.allSettled(adapters.map(fetchAdapter));
const out: CameraFeature[] = [];
for (const r of results) {
if (r.status === "fulfilled") out.push(...r.value);
}
return out;
}
+9
View File
@@ -0,0 +1,9 @@
import { fetchTflCameras } from "../tfl/tflFetcher";
import type { CameraAdapter, CameraFeature } from "./types";
export const tflAdapter: CameraAdapter = {
id: "tfl",
displayName: "TfL JamCams (London)",
region: "United Kingdom — London",
fetch: async () => (await fetchTflCameras()) as CameraFeature[],
};
+97
View File
@@ -0,0 +1,97 @@
/**
* Public-camera adapter interface.
*
* Each upstream camera source (Caltrans, GDOT, TfL, 511NY, WSDOT, …)
* implements `CameraAdapter`. The registry collects them; `/api/camera/traffic`
* merges; `/api/camera/list` exposes their metadata for client-side source
* discovery + selection UI.
*
* `CameraFeature` is the normalized record shape every adapter returns.
* Replaces the legacy `GdotCameraFeature` alias which leaked the first
* adapter's name into every other one.
*/
export type StreamType = "image" | "hls" | "mp4" | "iframe" | null;
export interface CameraFeature {
type: "Feature";
geometry: {
type: "Point";
coordinates: [number, number]; // [lon, lat]
};
properties: {
/** Stable identifier within source (used as React key on client). */
id?: string;
/**
* Adapter id ("caltrans", "gdot", "ny511", ...). Plugins use this
* for filtering and for routing clicks to the right player.
*/
source: string;
/**
* Direct snapshot/stream URL the client should render. May be null
* when the upstream source provides location-only data or the
* adapter has detected a dead host.
*/
stream: string | null;
streamType?: StreamType;
/** Optional HLS-specific URL when both image + HLS are available. */
hls?: string | null;
// Display + filter fields — adapters fill what they have.
name?: string;
country?: string;
region?: string;
city?: string;
route?: string;
direction?: string;
location_description?: string;
categories?: string[];
/**
* Adapter-specific extras (mile markers, county ids, etc.). Kept
* under one key so the top-level shape stays predictable.
*/
extra?: Record<string, unknown>;
};
}
/** Metadata about an adapter, exposed via `/api/camera/list`. */
export interface CameraAdapterMeta {
/** Stable id used in `?sources=` and as the `properties.source` value. */
id: string;
/** Human-readable name for settings UI ("Caltrans (California)"). */
displayName: string;
/** Geographic scope, used for grouping in source-picker UIs. */
region: string;
/** True if the adapter requires an env var to function. */
requiresKey?: {
envVar: string;
signupUrl: string;
};
/** True iff a successful fetch landed within the last cache window. */
healthy: boolean;
/** ISO timestamp of the last successful fetch, or null if never. */
lastFetchedAt: string | null;
/** Number of features returned by the most recent successful fetch. */
lastFeatureCount: number | null;
/** Brief error from the last fetch, if any. */
lastError?: string;
}
/** Adapter implementation contract. */
export interface CameraAdapter {
readonly id: string;
readonly displayName: string;
readonly region: string;
readonly requiresKey?: { envVar: string; signupUrl: string };
/** Default cache TTL for this adapter's feed. Defaults to 24h. */
readonly cacheTtlMs?: number;
/** Fetch the source's full feed and normalize to CameraFeature[]. */
fetch(): Promise<CameraFeature[]>;
}
/**
* Legacy alias — every existing fetcher imports this name. Kept as alias
* to `CameraFeature` so old code keeps compiling while we migrate.
*
* @deprecated Use `CameraFeature` from `adapters/types` directly.
*/
export type GdotCameraFeatureLegacy = CameraFeature;
+13
View File
@@ -0,0 +1,13 @@
import { fetchWsdotCameras } from "../wsdot/wsdotFetcher";
import type { CameraAdapter, CameraFeature } from "./types";
export const wsdotAdapter: CameraAdapter = {
id: "wsdot",
displayName: "WSDOT (Washington State)",
region: "United States — Washington",
requiresKey: {
envVar: "WSDOT_API_KEY",
signupUrl: "https://wsdot.wa.gov/traffic/api/",
},
fetch: async () => (await fetchWsdotCameras()) as CameraFeature[],
};
-31
View File
@@ -1,31 +0,0 @@
import { NextResponse } from "next/server";
import { fetchGdotCameras, type GdotCameraFeature } from "./gdotFetcher";
/** In-memory cache with TTL. */
let cache: { data: GdotCameraFeature[]; expiry: number } | null = null;
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
export async function GET() {
try {
const now = Date.now();
if (cache && now < cache.expiry) {
return NextResponse.json({ cameras: cache.data, cached: true });
}
const cameras = await fetchGdotCameras();
cache = { data: cameras, expiry: now + CACHE_TTL_MS };
return NextResponse.json({ cameras, cached: false });
} catch (error: any) {
console.error("[GDOT API] Error:", error);
// Serve stale cache on error if available
if (cache) {
return NextResponse.json({ cameras: cache.data, cached: true, stale: true });
}
return NextResponse.json(
{ error: "Failed to fetch GDOT cameras" },
{ status: 502 },
);
}
}
+12
View File
@@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { getAdapterMetadata } from "../adapters/registry";
/**
* Returns metadata for every registered camera adapter so the client plugin
* can render a dynamic settings UI (source toggles, key-required hints,
* health indicators) without hardcoding the adapter list. Adding a source
* to `adapters/registry.ts` makes it appear here automatically.
*/
export async function GET() {
return NextResponse.json({ adapters: getAdapterMetadata() });
}
+80
View File
@@ -0,0 +1,80 @@
/**
* Fetches all NYSDOT / 511NY traffic cameras.
*
* API: https://511ny.org/api/getcameras?key=<KEY>&format=json
* Public API; key parameter is required but the endpoint accepts any value.
* Self-hosters can set NY511_API_KEY to a real key (free at
* https://511ny.org/developers) for first-class rate-limit treatment.
*
* Returns ~1,500 enabled cameras across NY State, ~80% with HLS streams.
*/
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
const NY511_BASE = "https://511ny.org/api/getcameras";
interface Ny511Camera {
Latitude: number;
Longitude: number;
ID: string;
Name: string | null;
DirectionOfTravel: string | null;
RoadwayName: string | null;
Url: string | null;
VideoUrl: string | null;
Disabled: boolean;
Blocked: boolean;
}
/** Pull a county/region hint out of `RoadwayName [Region]` if present. */
function extractCity(roadwayName: string | null): string {
if (!roadwayName) return "New York";
const m = roadwayName.match(/\[([^\]]+)\]/);
return m ? m[1].trim() : "New York";
}
function toGeoJsonFeature(c: Ny511Camera): GdotCameraFeature | null {
if (c.Disabled || c.Blocked) return null;
if (typeof c.Latitude !== "number" || typeof c.Longitude !== "number") return null;
const hls = c.VideoUrl ?? null;
return {
type: "Feature",
geometry: { type: "Point", coordinates: [c.Longitude, c.Latitude] },
properties: {
stream: hls || c.Url || "",
hls,
country: "United States",
region: "New York",
city: extractCity(c.RoadwayName),
source: "ny511",
name: c.ID || "",
route: c.RoadwayName?.replace(/\s*\[[^\]]+\]\s*$/, "").trim() || "",
direction: c.DirectionOfTravel === "Unknown" ? "" : (c.DirectionOfTravel ?? ""),
location_description: c.Name ?? "",
categories: ["traffic"],
},
};
}
/** Fetch all 511NY cameras. */
export async function fetch511NyCameras(): Promise<GdotCameraFeature[]> {
const key = process.env.NY511_API_KEY || "test";
const url = `${NY511_BASE}?key=${encodeURIComponent(key)}&format=json`;
const res = await fetch(url, {
headers: { "User-Agent": "WorldWideView/1.0" },
});
if (!res.ok) throw new Error(`511NY API returned ${res.status}`);
const data = await res.json();
if (!Array.isArray(data)) return [];
const cameras: GdotCameraFeature[] = [];
for (const c of data) {
const f = toGeoJsonFeature(c as Ny511Camera);
if (f) cameras.push(f);
}
return cameras;
}
+24 -46
View File
@@ -1,60 +1,38 @@
import { NextResponse } from "next/server";
import { fetchGdotCameras, type GdotCameraFeature } from "../gdot/gdotFetcher";
import { fetchTflCameras } from "../tfl/tflFetcher";
import { fetchCaltransCameras } from "../caltrans/caltransFetcher";
/** In-memory cache for traffic cameras with 24h TTL. */
let cache: { data: GdotCameraFeature[]; expiry: number } | null = null;
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
import { NextResponse, type NextRequest } from "next/server";
import { fetchManyAdapters, resolveSources } from "../adapters/registry";
/**
* Merge all traffic camera sources.
* Add new fetchers here as they are implemented.
* Aggregator. Reads the adapter registry and fetches the requested sources.
* Per-adapter caching lives in the registry, so individual sources can have
* different TTLs without colliding here.
*
* Query params:
* ?sources=caltrans,gdot → only those adapters
* ?sources=all (default) → all registered adapters (back-compat with
* the old behavior — every existing client
* that hits this URL with no query continues
* to receive the merged-everything payload)
* ?sources=none → empty list (used by clients to short-circuit
* without changing the default-on behavior of
* this endpoint)
*
* Response shape kept backwards-compatible with the old /traffic endpoint:
* { cameras: CameraFeature[], total: number, sources: string[] }
*/
async function fetchAllTrafficCameras(): Promise<GdotCameraFeature[]> {
const results = await Promise.allSettled([
fetchGdotCameras(),
fetchTflCameras(),
fetchCaltransCameras(),
]);
const all: GdotCameraFeature[] = [];
for (const r of results) {
if (r.status === "fulfilled") all.push(...r.value);
export async function GET(req: NextRequest) {
const sources = resolveSources(req.nextUrl.searchParams.get("sources"));
if (sources.length === 0) {
return NextResponse.json({ cameras: [], total: 0, sources: [] });
}
return all;
}
export async function GET() {
try {
const now = Date.now();
if (cache && now < cache.expiry) {
return NextResponse.json({
cameras: cache.data,
total: cache.data.length,
cached: true,
});
}
const cameras = await fetchAllTrafficCameras();
cache = { data: cameras, expiry: now + CACHE_TTL_MS };
const cameras = await fetchManyAdapters(sources);
return NextResponse.json({
cameras,
total: cameras.length,
cached: false,
sources,
});
} catch (error: any) {
console.error("[TrafficCameras] Error:", error);
if (cache) {
return NextResponse.json({
cameras: cache.data,
total: cache.data.length,
cached: true,
stale: true,
});
}
return NextResponse.json(
{ error: "Failed to fetch traffic cameras" },
{ status: 502 },
+104
View File
@@ -0,0 +1,104 @@
/**
* Fetches all WSDOT (Washington State DOT) highway cameras.
*
* API: https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson?AccessCode=<KEY>
* Requires a free WSDOT Traveler Information API key
* (https://wsdot.wa.gov/traffic/api/). Returns ~1,600 active cameras across
* Washington State plus ~70 ODOT-shared cameras at I-5/I-205 border
* crossings into Oregon. All cameras return direct JPG snapshot URLs.
*
* Without WSDOT_API_KEY set, the fetcher returns [] (logged once on first
* call) so the combined endpoint stays operational.
*/
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
const WSDOT_BASE =
"https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
interface WsdotCamera {
CameraID: number;
CameraLocation: {
Description: string | null;
Direction: string | null;
Latitude: number;
Longitude: number;
MilePost: number | null;
RoadName: string | null;
};
CameraOwner: string | null;
Description: string | null;
DisplayLatitude: number;
DisplayLongitude: number;
ImageHeight: number;
ImageWidth: number;
ImageURL: string;
IsActive: boolean;
OwnerURL: string | null;
Region: string | null;
SortOrder: number;
Title: string | null;
}
let warnedMissingKey = false;
function toGeoJsonFeature(c: WsdotCamera): GdotCameraFeature | null {
if (!c.IsActive) return null;
if (!c.ImageURL) return null;
const lat = c.DisplayLatitude ?? c.CameraLocation?.Latitude;
const lon = c.DisplayLongitude ?? c.CameraLocation?.Longitude;
if (typeof lat !== "number" || typeof lon !== "number") return null;
const owner = c.CameraOwner ?? "";
const isOdot = /odot|tripcheck/i.test(owner);
return {
type: "Feature",
geometry: { type: "Point", coordinates: [lon, lat] },
properties: {
stream: c.ImageURL,
hls: null,
country: "United States",
region: isOdot ? "Oregon" : "Washington",
city: isOdot ? "Oregon" : "Washington",
source: "wsdot",
name: c.Title ?? `Camera ${c.CameraID}`,
route: c.CameraLocation?.RoadName ?? "",
direction: c.CameraLocation?.Direction ?? "",
location_description: c.Title ?? c.Description ?? "",
categories: ["traffic"],
},
};
}
/** Fetch all WSDOT cameras. Requires WSDOT_API_KEY env var. */
export async function fetchWsdotCameras(): Promise<GdotCameraFeature[]> {
const key = process.env.WSDOT_API_KEY;
if (!key) {
if (!warnedMissingKey) {
console.warn(
"[WSDOT] WSDOT_API_KEY not set — skipping. " +
"Get a free key at https://wsdot.wa.gov/traffic/api/",
);
warnedMissingKey = true;
}
return [];
}
const url = `${WSDOT_BASE}?AccessCode=${encodeURIComponent(key)}`;
const res = await fetch(url, {
headers: { "User-Agent": "WorldWideView/1.0" },
});
if (!res.ok) throw new Error(`WSDOT API returned ${res.status}`);
const data = await res.json();
if (!Array.isArray(data)) return [];
const cameras: GdotCameraFeature[] = [];
for (const c of data) {
const f = toGeoJsonFeature(c as WsdotCamera);
if (f) cameras.push(f);
}
return cameras;
}
+59
View File
@@ -0,0 +1,59 @@
import { NextResponse } from "next/server";
import { validateManifest } from "@/core/plugins/validateManifest";
import { parseWwvManifest } from "@/core/plugins/parseWwvManifest";
export async function OPTIONS() {
// Allows the WWV CLI (running on a different port) to hit this endpoint
return new NextResponse(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
});
}
/**
* POST /api/dev/load-unpacked
*
* Called by the `@worldwideview/cli` dev server when it starts.
* It sends the `wwv-manifest.json` + `devUrl` (the CLI dev server URL).
*/
export async function POST(request: Request) {
if (process.env.NODE_ENV !== "development") {
return NextResponse.json(
{ error: "Developer mode is only available in development environments" },
{ status: 403, headers: { "Access-Control-Allow-Origin": "*" } }
);
}
try {
const body = await request.json();
// Convert wwv-manifest.json format to PluginManifest format
const manifest = parseWwvManifest(body);
// Dev-loaded plugins are unverified by default
manifest.trust = "unverified";
const validation = validateManifest(manifest);
if (!validation.valid) {
return NextResponse.json(
{ error: "Invalid manifest", details: validation.errors },
{ status: 400, headers: { "Access-Control-Allow-Origin": "*" } }
);
}
return NextResponse.json(
{ status: "loaded", manifest },
{ status: 200, headers: { "Access-Control-Allow-Origin": "*" } }
);
} catch (err) {
console.error("[Load Unpacked] Error:", err);
return NextResponse.json(
{ error: "Failed to parse or load unpacked manifest" },
{ status: 500, headers: { "Access-Control-Allow-Origin": "*" } }
);
}
}
@@ -0,0 +1,32 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { isCloud } from "@/core/edition";
export async function GET(
request: Request,
{ params }: { params: Promise<{ subdomain: string }> }
) {
if (!isCloud) {
return NextResponse.json({ status: "active", plan: "basic" });
}
// Await params as required in Next.js 15+
const resolvedParams = await params;
const subdomain = resolvedParams.subdomain;
try {
const workspace = await prisma.workspace.findUnique({
where: { subdomain },
select: { status: true, plan: true }
});
if (!workspace) {
return NextResponse.json({ error: "Workspace not found" }, { status: 404 });
}
return NextResponse.json(workspace);
} catch (e) {
console.error("Failed to lookup workspace", e);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
@@ -10,11 +10,11 @@ export async function GET(request: Request) {
if (rateLimited) return rateLimited;
try {
// Fetch currently installed plugins from local SQLite
// Fetch currently installed plugins from PostgreSQL
const installedPlugins = await getInstalledPlugins();
// Exclude built-in versions, only check genuine semver strings or unverified records.
const updatablePlugins = installedPlugins.filter(p => p.version !== "built-in");
const updatablePlugins = installedPlugins.filter((p: any) => p.version !== "built-in");
if (updatablePlugins.length === 0) {
return NextResponse.json({ updates: {} });
+2 -2
View File
@@ -5,6 +5,7 @@ import { issueMarketplaceToken } from "@/lib/marketplace/marketplaceToken";
import { grantTokenLimiter } from "@/lib/rateLimiters";
import { getClientIp } from "@/lib/rateLimit";
import { isPluginInstallEnabled, isDemo, isDemoAdmin } from "@/core/edition";
import { getRequestOrigin } from "@/lib/origin";
const ALLOWED_REDIRECT_HOSTS = new Set([
"localhost",
@@ -50,8 +51,7 @@ export async function GET(request: NextRequest) {
const session = await auth();
if (!session?.user) {
// Use configured app URL to prevent Host header injection open redirects
const origin = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || request.nextUrl.origin;
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
// Construct a relative path for callback to ensure it redirects back to the identical host
@@ -9,6 +9,7 @@ import { installLimiter } from "@/lib/rateLimiters";
import { getClientIp } from "@/lib/rateLimit";
import { isPluginInstallEnabled, isDemo, isDemoAdmin } from "@/core/edition";
import { getVerifiedPluginIds } from "@/lib/marketplace/registryClient";
import { getRequestOrigin } from "@/lib/origin";
const ALLOWED_REDIRECT_HOSTS = new Set([
"localhost",
@@ -16,6 +17,10 @@ const ALLOWED_REDIRECT_HOSTS = new Set([
"worldwideview.dev",
]);
if (process.env.ALLOWED_DEV_ORIGIN) {
ALLOWED_REDIRECT_HOSTS.add(process.env.ALLOWED_DEV_ORIGIN);
}
function isSafeRedirect(url: string): boolean {
try {
const parsed = new URL(url);
@@ -49,7 +54,8 @@ export async function GET(request: NextRequest) {
// Not logged in — send to login with this URL as callbackUrl
if (!session?.user) {
const origin = process.env.NEXT_PUBLIC_APP_URL || process.env.APP_URL || request.nextUrl.origin;
const origin = getRequestOrigin(request);
const loginUrl = new URL("/login", origin);
const callbackPath = request.nextUrl.pathname + request.nextUrl.search;
loginUrl.searchParams.set("callbackUrl", callbackPath);
+3 -3
View File
@@ -104,9 +104,9 @@ export async function POST(request: Request) {
return withCors(
NextResponse.json({
status: "installed",
pluginId: record.pluginId,
version: record.version,
installedAt: record.installedAt,
pluginId: record!.pluginId,
version: record!.version,
installedAt: record!.installedAt,
}),
request,
);
+29 -4
View File
@@ -1250,6 +1250,31 @@ html, body {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
}
body.is-resizing-sidebar .panel-toggle-btn,
body.is-resizing-sidebar .sidebar {
transition: none !important;
}
/* Invisible pseudo-element to expand the effective touch/click trigger area */
.panel-toggle-btn::after {
content: "";
position: absolute;
top: -20px;
bottom: -20px;
left: -25px;
right: -25px;
z-index: -1;
}
/* Extend inward trigger area so it's harder to miss when coming from the panel */
.panel-toggle-btn--left::after {
left: -60px;
}
.panel-toggle-btn--right::after {
right: -60px;
}
.panel-toggle-btn:hover {
background: var(--bg-glass-active);
color: var(--text-primary);
@@ -1272,8 +1297,8 @@ html, body {
}
.panel-toggle-btn--left.panel-toggle-btn--open {
/* Attach to the right edge of the left panel (width 280px + left padding 24px) */
left: calc(280px + var(--space-lg));
/* Attach to the right edge of the left panel */
left: calc(var(--left-sidebar-width, 280px) + var(--space-lg));
border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
border-left: none;
/* Stay slightly hidden under the panel to look attached, poke out 24px */
@@ -1300,8 +1325,8 @@ html, body {
}
.panel-toggle-btn--right.panel-toggle-btn--open {
/* Attach to the left edge of the right panel (width 320px + right padding 24px) */
right: calc(320px + var(--space-lg) + var(--ad-strip-inset, 0px));
/* Attach to the left edge of the right panel */
right: calc(var(--right-sidebar-width, 320px) + var(--space-lg) + var(--ad-strip-inset, 0px));
border-radius: var(--radius-sm) 0 0 var(--radius-sm);
border-right: none;
/* Stay slightly hidden under the panel to look attached, poke out 24px */
+7 -5
View File
@@ -40,11 +40,13 @@ export default function RootLayout({
<body suppressHydrationWarning>
{children}
{process.env.VERCEL && <Analytics />}
<Script
src="https://analytics.worldwideview.dev/script.js"
data-website-id="2c8f6c09-2651-4a2a-af99-b8cee1612b9a"
strategy="afterInteractive"
/>
{process.env.NEXT_PUBLIC_WWV_ANALYTICS === "true" && (
<Script
src="https://analytics.worldwideview.dev/script.js"
data-website-id="2c8f6c09-2651-4a2a-af99-b8cee1612b9a"
strategy="afterInteractive"
/>
)}
</body>
</html>
);
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff. Show more