Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
784a70986c | ||
|
|
6d62ca5677 | ||
|
|
58aac77a0b | ||
|
|
0462ab1f88 | ||
|
|
60fca4d540 | ||
|
|
dba5d49448 | ||
|
|
1633c7bb7b | ||
|
|
7eda6c50a4 | ||
|
|
f2ae2a7de7 | ||
|
|
3210b3bd15 | ||
|
|
9fad051f75 | ||
|
|
a818822023 | ||
|
|
012184af30 | ||
|
|
c1f7ffb5b4 | ||
|
|
6816081644 | ||
|
|
433004598d | ||
|
|
02d8355a83 | ||
|
|
89010b2425 | ||
|
|
0ff1d23e4a | ||
|
|
fd29865e7a | ||
|
|
42564b537f | ||
|
|
598e00171c | ||
|
|
b849bb2b4d | ||
|
|
fc7dd02ee2 | ||
|
|
caf1638fdc | ||
|
|
ad3c7845a5 | ||
|
|
339bf6c0f3 | ||
|
|
16c82c9184 | ||
|
|
ad324a6592 | ||
|
|
0a51e198d7 | ||
|
|
1d6381182e | ||
|
|
beb295445f | ||
|
|
dd62116351 | ||
|
|
d675d91441 | ||
|
|
fb07195ec2 | ||
|
|
1838f1a5cd | ||
|
|
28e4e67043 | ||
|
|
594f85afb2 | ||
|
|
b29133fca0 | ||
|
|
ac0092c8a8 | ||
|
|
f0daefd53d |
No files matched your search
@@ -0,0 +1,17 @@
|
||||
# On-Demand Context Index
|
||||
|
||||
Read these files when the task requires their domain knowledge. They are NOT auto-loaded — read them explicitly.
|
||||
|
||||
| When to read | File |
|
||||
|---|---|
|
||||
| Product vision, business model, Edition system, repository map | `platform-architecture.md` |
|
||||
| Feature/UX decisions — who is affected, stakeholder impact matrix | `stakeholders-and-human-centered-design.md` |
|
||||
| Finding files, repo layout, directory tree | `directory-structure.md` |
|
||||
| Routing a fix to wwv-data-engine, wwv-seeders, marketplace, etc. | `ecosystem-repositories.md` |
|
||||
| Debugging broken plugin data, namespace collisions, latency, logging | `troubleshooting-and-debugging.md` |
|
||||
| SSH into server, Coolify MCP operations | `server-management.md` |
|
||||
| Next.js App Router, data pipeline, Redis architecture, DB schema | `application-architecture.md` |
|
||||
| `.env` variables and secrets | `environment-config.md` |
|
||||
| Coding principles, Definition of Done checklist, antipatterns | `coding-principles.md` |
|
||||
| Boy Scout rule, when to update rules/skills/workflows | `continuous-improvement.md` |
|
||||
| How to orient and maintain context between sessions | `context-and-memory.md` |
|
||||
File renamed without changes.
@@ -0,0 +1,280 @@
|
||||
# Coding Principles
|
||||
|
||||
You are about to write or modify code. **Read this file first.** It exists to prevent the failure mode where every fix makes the next harder — the kind of accumulated coupling and band-aid-on-band-aid that turns a clean codebase into a fragile one over months. This file is the constitution that keeps that from happening.
|
||||
|
||||
## The hard rule
|
||||
|
||||
> **Always interface-based, extensible, composable, modular. Never band-aids on band-aids.**
|
||||
|
||||
If you find yourself adding a flag, an `if`-check, or a special case to make a problem go away, you are probably band-aiding. Stop and find the seam where the abstraction broke. Fix it there.
|
||||
|
||||
## Core principles
|
||||
|
||||
### 1. Interfaces before implementations
|
||||
|
||||
Define the contract first. The contract is what other components depend on; the implementation is replaceable. Public functions accept the interface, not the concrete type.
|
||||
|
||||
```ts
|
||||
// Yes
|
||||
function attachSource(source: DataSource) { ... }
|
||||
|
||||
// No
|
||||
function attachPostgresSource(pg: PostgresInstance) { ... }
|
||||
```
|
||||
|
||||
When a pattern repeats across two modules, refactor it into an interface immediately. Don't wait for the third copy to "earn" the abstraction — by then the costs have compounded.
|
||||
|
||||
### 2. Loose coupling through explicit contracts
|
||||
|
||||
Components communicate through well-defined contracts: typed function signatures, events on a bus, message queues, or capability registries. Pick the form that fits, but pick *one* and make it the only path.
|
||||
|
||||
Components do **not** communicate through:
|
||||
|
||||
- Direct imports of each other's internal modules
|
||||
- Shared mutable state outside the contract
|
||||
- Synchronous request/response when async fits the actual data flow
|
||||
- "Just this once" backdoors that bypass the contract
|
||||
|
||||
If you're tempted to write `import { internalThing } from '../other-module/internal'`, you are doing it wrong. If the symbol you need isn't part of the other module's public contract, either it should be — propose adding it — or you're solving the problem in the wrong place.
|
||||
|
||||
### 3. Domain boundaries are sacred
|
||||
|
||||
Each domain (module, service, bounded context, plugin) owns its own state and its own surface. Cross-domain access is **explicit, gated, and audited** — never a shortcut.
|
||||
|
||||
Forbidden:
|
||||
- Reading another domain's storage directly
|
||||
- Calling another domain's private functions
|
||||
- Hardcoded `if (tenant === 'X')` or `if (mode === 'special')` branches in shared code
|
||||
|
||||
Allowed:
|
||||
- A documented capability or API on the other domain that you call
|
||||
- A configuration field on the relevant record that drives the strategy
|
||||
- Cross-domain access gated by explicit policy (default **deny**, opt-in per case), with the access itself logged
|
||||
|
||||
The rule of thumb: if removing a domain would require code archaeology in three other domains to figure out what depends on its internals, the boundary has already been violated. Treat that as a bug.
|
||||
|
||||
### 4. Don't bend your architecture to fit a dependency
|
||||
|
||||
When you bring in a library or framework, use it where it fits cleanly; build natively where it doesn't.
|
||||
|
||||
Let the dependency handle (don't reinvent):
|
||||
- The thing it's specifically good at, in the shape it expects
|
||||
|
||||
Your code owns (the dependency can't represent):
|
||||
- Anything that's specifically your domain
|
||||
- Anything that requires identity, lifecycle, or invariants the dependency doesn't model
|
||||
- The integration seams between the dependency and your domain
|
||||
|
||||
If you find yourself bending your design to fit a library convenience, stop. Either the library has a hook for what you need, or you build it natively. Don't compromise architecture for the convenience of pulling in someone else's defaults.
|
||||
|
||||
### 5. Data lifetimes are deliberate, not incidental
|
||||
|
||||
Different data has different lifetimes. Get this wrong and you'll either retain garbage forever or delete things users care about. Common categories:
|
||||
|
||||
- **Operational telemetry** (logs, metrics, internal events) — short rolling window. Useful for crash recovery and immediate investigation; not useful enough to keep forever.
|
||||
- **User content** (messages, documents, records the user created or that represent their lived experience with the system) — **permanent unless the user explicitly deletes it.** Never pruned by a sweep, never deleted by a retention policy authored for telemetry.
|
||||
- **Resumable session state** — bounded window appropriate to the use case; archived (state flag flipped) rather than deleted.
|
||||
|
||||
Name each category in your codebase. Write the retention policy for each one separately. Never propose a sweep that crosses categories — "delete events older than 30 days" is fine if events are telemetry; the same policy applied to user content is data loss masquerading as housekeeping. If storage pressure ever becomes real for content, introduce cold-tiered storage, not deletion.
|
||||
|
||||
### 6. Optional features must be truly removable
|
||||
|
||||
Every optional feature (plugin, extension, integration, side module) declares its surface explicitly and communicates through the same contracts as everything else. No optional feature reaches into another's internals.
|
||||
|
||||
Test for whether something is core vs. optional: **if removing this feature should break the system, it's core. Otherwise it's optional, and it should be removable without leaving residue.**
|
||||
|
||||
If you can't delete an "optional" module's directory and have the system keep running, it isn't optional. Either fix the coupling or move it into core honestly.
|
||||
|
||||
### 7. Put code where it belongs
|
||||
|
||||
When a feature spans layers (a trigger lives here, the action lives there, the data model lives somewhere else), resist the urge to fold it all into one place "for convenience." The feature lives in three places because each piece belongs to a different domain. Routing across them is the job — not collapsing them.
|
||||
|
||||
The general rule: if a feature needs to read/write durable state, it's a tool/extension on top of the layer that owns that state; if it's "the system should know about this concept," it's a configuration or contract change. Often it's both, with a thin handler that wires them together. That thin handler is fine — it's load-bearing — but it doesn't justify smashing the layers together.
|
||||
|
||||
## Antipatterns to refuse
|
||||
|
||||
These are common failure modes that, repeated over time, calcify a codebase. Refuse them when you catch yourself reaching for them.
|
||||
|
||||
| Antipattern | Better answer |
|
||||
|---|---|
|
||||
| Adding a new flag to an existing function instead of extracting a strategy | Extract the strategy interface; existing call sites pass the default strategy |
|
||||
| Patching around a bug at the call site | Find the seam where the abstraction broke; fix it there |
|
||||
| Direct database access from a feature module | Go through the layer that owns the data; if no surface exists, propose one |
|
||||
| Hardcoded paths, model names, IDs, environment specifics in business logic | Configuration; or look up via registry |
|
||||
| `if (tenant === 'X') { ... }` in shared code | Strategy on the record, or a per-tenant config field |
|
||||
| Inheriting one layer's concerns into another (or vice versa) | Cross the boundary through the documented contract |
|
||||
| "It works for now" — inline coupling between layers | If the layers are real, draw the contract; if they're not, merge them honestly |
|
||||
| Adding a defensive `try/catch` to swallow an error | Find why the error happens; gate cleanly at the right boundary |
|
||||
| Writing a comment to explain what code does | Rename and refactor so the code reads itself |
|
||||
| Copying a snippet from one module into another "to avoid the dependency" | Either it belongs in a shared module, or the duplicate will drift — pick |
|
||||
|
||||
## Debugging discipline
|
||||
|
||||
When something breaks:
|
||||
|
||||
1. **Reproduce it.** Don't trust intuition about what's failing.
|
||||
2. **Find the seam.** Where did the abstraction break? Which contract is being violated, and by whom?
|
||||
3. **Fix at the seam.** Not at the call site. Not at the consumer. At the boundary that's wrong.
|
||||
4. **If you can't find the seam, surface it.** Tell the user explicitly: "this is a design gap; the right fix needs an architectural decision, not a patch." Do not paper over.
|
||||
|
||||
If a fix doesn't work, **don't add another guard on top.** Find the real seam and gate cleanly. Stacked defensive layers are how clean codebases become unmaintainable.
|
||||
|
||||
## Lifecycle invariants and state-changing operations
|
||||
|
||||
Most recurring bugs cluster around the same shape: an operation crosses lifecycle state without checking, and the result is silent corruption, lost data, or orphan rows. The recipe that prevents recurrences:
|
||||
|
||||
1. **Name the invariant.** "Closed sessions don't accept work." "Scoped grants need a scope id." "Subscriptions past retention can't deliver swept events." Write it down before reaching for code.
|
||||
2. **Throw a typed error at the seam.** The single function that crosses the invariant refuses the bad case with a typed, named error — not a boolean return, not a silent skip, not a generic `Error`.
|
||||
3. **Pre-check at every call site that mutates *before* reaching the seam.** If the seam check fires after `store.append()`, you've left an orphan row. The pre-check is hygiene; the seam check is correctness — both are required. When the same pre-check appears at a second call site, extract a helper.
|
||||
4. **Validate, then mutate — never the reverse.** Within a single function, resolve all inputs that could fail (key derivation, lookups, permission checks) before touching durable state. A validation throw should leave nothing half-applied. If you can't separate validation from mutation, the function is doing two jobs.
|
||||
5. **A documented unsafe API is still unsafe.** A docstring that says "don't use this when X" is a foot-gun, not a warranty disclaimer. Either make the API safe in case X (drain, throw, refuse) or remove it.
|
||||
|
||||
If you're tempted to skip step 3 because "the seam check covers it," check whether the call site writes anything before reaching the seam. If yes, you need the pre-check.
|
||||
|
||||
## Definition of done — checklist for adding or updating a function
|
||||
|
||||
Every code change must satisfy the relevant checklist before merge. Refusal triggers below mean **stop and surface to the user** — do not ship a half-met checklist.
|
||||
|
||||
### Adding a new function
|
||||
|
||||
All must be true:
|
||||
|
||||
- [ ] Belongs in this module (not somewhere else)
|
||||
- [ ] Fulfills an existing interface, OR a new interface is added with it (and reasons documented in a spec doc / ADR)
|
||||
- [ ] Has a doc-comment header (purpose + params + returns + thrown errors if relevant)
|
||||
- [ ] Has at least one test that targets the contract (not implementation details)
|
||||
- [ ] Test passes locally and in CI
|
||||
- [ ] Doesn't introduce direct cross-module imports of internals — communication through public contracts only
|
||||
- [ ] Doesn't touch storage owned by another component — route through that component's surface
|
||||
- [ ] Matches the spec doc's contract for this component (if no spec covers it, update the spec first)
|
||||
- [ ] Name is clear enough that the header comment is a summary, not an explanation
|
||||
|
||||
### Updating an existing function
|
||||
|
||||
All must be true:
|
||||
|
||||
- [ ] Reason for change is clear (bug fix / new requirement / refactor / spec change)
|
||||
- [ ] Doc-comment still accurate after change (update if not)
|
||||
- [ ] Existing tests cover the new behavior (add new tests if not)
|
||||
- [ ] Build is green (all tests passing)
|
||||
- [ ] If this changes the contract: spec doc updated AND an ADR added if the change is load-bearing
|
||||
- [ ] Fix is at the seam, not at the symptom (no band-aid patches)
|
||||
- [ ] No new flags or special cases added in lieu of strategy extraction
|
||||
|
||||
### Refusal triggers (any one means stop)
|
||||
|
||||
- Adding `if (tenant === 'X')` to shared code → use per-tenant config instead
|
||||
- Adding a flag to make a problem go away → extract the abstraction the flag implies
|
||||
- Direct DB or filesystem access from a feature module → route through the owning component
|
||||
- `try`/`catch` swallowing an error → find why the error happens, gate cleanly
|
||||
- Test omitted because "it's trivial" → no
|
||||
- Function-header skipped because "it's obvious" → no
|
||||
- "Just add another guard here" when a guard didn't work → find the real seam
|
||||
- Patch shipped to "unblock the build" without root-cause fix → no, surface the design gap
|
||||
|
||||
If any criterion isn't met, stop. Surface to the user as a design question. Don't paper over.
|
||||
|
||||
## Code-style minimums
|
||||
|
||||
### Comments
|
||||
|
||||
**Every function gets a doc-comment header** in your language's idiomatic format (TSDoc, JSDoc, Python docstrings, Rust `///`, Javadoc, etc.). Not optional. Long-running codebases get re-read after gaps; function-header docs are how re-onboarding stays cheap.
|
||||
|
||||
Required content:
|
||||
|
||||
- One-line summary at a contract level (what the function guarantees, not what the code does line-by-line)
|
||||
- Each parameter and what it represents
|
||||
- Return value
|
||||
- Thrown errors / failure conditions if relevant
|
||||
- Example usage when the call shape is non-obvious
|
||||
|
||||
Apply this to public, internal, exported, and private functions. Apply to methods on classes too.
|
||||
|
||||
**Inline comments inside function bodies** still follow the standard rule: only for non-obvious WHY (hidden constraints, workarounds, surprising behavior, references to bug reports). Don't comment WHAT the code does — well-named identifiers and the function-header doc cover that.
|
||||
|
||||
### Tests
|
||||
|
||||
**Every function ships with at least one test. Tests passing is a build requirement.**
|
||||
|
||||
- Tests target the contract (function signature + documented behavior + invariants), not implementation details. Refactoring should not break tests; behavior changes should.
|
||||
- A new implementation of an interface must pass the same contract test suite (write tests against the interface, not against a specific implementation).
|
||||
- Test names describe the case being verified, not the function: `it('refuses resume after archival window expires')` not `it('resumeSession')`.
|
||||
- For storage code: tests use a real (temporary) instance of the storage layer, created and torn down per test or per suite. Don't mock the storage engine — you're testing the wrong thing if you do.
|
||||
- For integration code that depends on an external library's hooks: contract tests against that library's surface so a dependency bump catches behavior changes.
|
||||
- Build pipeline (CI or local) runs all tests; non-zero exit = build fails. There is no "build succeeded but tests failed" state.
|
||||
|
||||
### Logging
|
||||
|
||||
**Every new feature with a non-happy-path ships with a log line at each rare branch.** Use a structured logger with module-scoped child loggers. The log file is where "something's not working" turns into "what actually happened."
|
||||
|
||||
Level guidance:
|
||||
|
||||
- **info** — expected-but-noteworthy edges: a UI race that hits a closed resource, a permission bypass for a privileged principal. Correct behavior an operator might want to confirm fired.
|
||||
- **warn** — should be rare and worth investigating: race past a pre-check, lost events past retention, programmer/operator errors (calling a method after stop, a key that should have resolved didn't).
|
||||
- **error** — actual failures the operator must respond to: handler crashes, dispatch loop crashes, integration failures.
|
||||
- **debug** — high-volume internal state changes; always pair with a `module` field so it can be filtered.
|
||||
|
||||
Pass structured fields, not interpolated strings — fields are what makes a log queryable:
|
||||
|
||||
```ts
|
||||
// Yes
|
||||
logger.warn({ session_id, state }, "rejected append against non-live session");
|
||||
|
||||
// No
|
||||
logger.warn(`session ${session_id} (${state}) rejected append`);
|
||||
```
|
||||
|
||||
If you add a new typed error or a new event topic, also log it. The typed error tells the immediate caller; the event tells subscribers; the log tells the operator. The three are independent surfaces for the same fact, and all three are needed — events don't show up in the log, logs don't show up on the bus, errors don't survive the catch.
|
||||
|
||||
### Structure
|
||||
|
||||
- Keep modules small. If a file is over ~500 lines, ask whether it has more than one responsibility.
|
||||
- Prefer explicit composition (caller wires things together) over implicit dependency-injection magic.
|
||||
- One public concept per module. If a file exports both `Foo` and `unrelatedHelperUsedNowhereElse`, the helper has the wrong home.
|
||||
|
||||
### Dependencies
|
||||
|
||||
**Always check the registry for the current version before adding or updating a dependency.** Don't pick versions from memory.
|
||||
|
||||
The simple test: did you actually run `<package-manager> view <pkg> version` (or its equivalent) before pinning? If not, you're guessing — and the guess is almost always behind, sometimes by a major version with active deprecation.
|
||||
|
||||
Why this matters:
|
||||
|
||||
- **Long-running codebases.** Stale dependency anchors compound. A v3 you picked because that's what was on your mind will still be v3 a year later, and the v4 migration gets harder every month it waits.
|
||||
- **Active deprecations are real.** Common libraries are mid-deprecation cycles for older majors. Pinning to a soon-deprecated version on day one means the eventual upgrade is forced rather than chosen.
|
||||
- **"Latest" doesn't mean "use without thinking."** Read the changelog for breaking changes; decide whether to take them now or pin behind explicitly. But the *default* posture should be: pick latest, and justify in writing if pinning behind.
|
||||
|
||||
If you must pin behind latest, leave a comment in the manifest (or a CHANGELOG note) explaining why — a known incompatibility with another dep, an in-progress migration, a tested-and-rejected major bump. *"I haven't checked"* is not an acceptable reason.
|
||||
|
||||
Apply to: adding a new dep, updating an existing one, scaffolding a new package. *Not* required for routine no-op installs that don't touch versions.
|
||||
|
||||
### Doc-vs-spec discipline
|
||||
|
||||
Specification documents (the deeper ones that describe how a component must behave) are **functional specifications**, not narrative essays. The discipline:
|
||||
|
||||
- **Concrete data structures** — type definitions, schemas, DDL, JSON examples
|
||||
- **Concrete function signatures** — input/output types, error types
|
||||
- **Concrete event/message payloads** — name + schema + example
|
||||
- **Concrete API signatures** — input/output schemas, side effects, permission requirements
|
||||
- **Flow pseudocode** — when orchestration is non-obvious
|
||||
- **Invariants** — explicitly listed: "after X happens, Y is always true"
|
||||
- **Failure modes** — enumerated: "if X fails, the system does Y"
|
||||
- **Acceptance tests** — statements another engineer can implement: "given input X, output Y"
|
||||
|
||||
Avoid in spec docs:
|
||||
- Long prose explaining motivation (that goes in ADRs / decision records)
|
||||
- Discussion of alternatives considered (also ADRs)
|
||||
- Background context (README handles this)
|
||||
- Marketing/aspirational tone
|
||||
|
||||
Spec docs are for implementation. Read one and you should know what to build.
|
||||
|
||||
## When in doubt
|
||||
|
||||
Ask the human user. Specifically:
|
||||
|
||||
- "I don't see a clean seam for this; the options I see are A or B. Which fits the architecture you have in mind?"
|
||||
- "This requires a new contract / capability / interface. Should I draft it before implementing?"
|
||||
- "I'm about to add a special case here; that smells like a missing abstraction. Do you want me to extract the abstraction or note the smell and defer?"
|
||||
|
||||
Don't ship band-aids and ask forgiveness later. The user has explicitly said: prevent that pattern.
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
trigger: always_on
|
||||
trigger: model_decision
|
||||
---
|
||||
|
||||
# Context and Memory Synchronization
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
trigger: always_on
|
||||
trigger: model_decision
|
||||
description: Guidelines for ongoing project maintenance, cleanliness, and self-correction during everyday development tasks.
|
||||
---
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+23
-1
@@ -26,7 +26,29 @@ When an AI agent or developer is executing CLI commands via tools in this projec
|
||||
- **Rule**: NEVER use the `&&` operator to chain commands in PowerShell. It will result in parser errors.
|
||||
- **Resolution**: Use sequential execution, run commands separately, or use PowerShell-safe chaining like `; if ($?) { }`.
|
||||
|
||||
## 5. Next.js vs. Undici Fetch Type Mismatches
|
||||
## 5. UTF-8 BOM in `package.json` Crashing Node Scripts
|
||||
If `pnpm dev` (or any workspace script) dies with `SyntaxError: Unexpected token '', "{ ..." is not valid JSON`, the offending file has a UTF-8 BOM (`EF BB BF`) at byte 0.
|
||||
- **Root Cause**: Windows PowerShell 5.1 `Set-Content -Encoding UTF8` and Notepad's "Save as UTF-8" both emit a BOM. Node's `fs.readFileSync(p, 'utf-8')` does NOT strip it, so `JSON.parse` rejects the leading ``. pnpm/npm strip BOMs silently, which is why this only blows up in custom workspace scripts.
|
||||
- **Diagnosis** (PowerShell):
|
||||
```powershell
|
||||
Get-ChildItem local-plugins -Directory | ForEach-Object {
|
||||
$p = Join-Path $_.FullName 'package.json'
|
||||
if (Test-Path $p) {
|
||||
$b = [System.IO.File]::ReadAllBytes($p) | Select-Object -First 3
|
||||
if ($b[0] -eq 0xEF -and $b[1] -eq 0xBB -and $b[2] -eq 0xBF) { $_.Name }
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Fix at the seam (preferred)**: In any script that parses externally-authored JSON, strip the BOM before parsing. See `readJsonFile()` in [`scripts/sync-local-plugins.mjs`](../../scripts/sync-local-plugins.mjs) as the canonical helper:
|
||||
```js
|
||||
let text = fs.readFileSync(filePath, "utf-8");
|
||||
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
|
||||
return JSON.parse(text);
|
||||
```
|
||||
- **Clean existing files** (one-time): rewrite each file without its first 3 bytes via `[System.IO.File]::WriteAllBytes($p, $bytes[3..($bytes.Length - 1)])`.
|
||||
- **Prevention**: When authoring files via PowerShell, use `Out-File -Encoding utf8NoBOM` (PS 7+) or `[System.IO.File]::WriteAllText($p, $text, [System.Text.UTF8Encoding]::new($false))` (any PS). Never edit `package.json` in Notepad.
|
||||
|
||||
## 6. Next.js vs. Undici Fetch Type Mismatches
|
||||
When implementing SSRF protections (e.g., DNS IP Pinning via custom `Dispatcher`), you will likely use `undici.Agent`.
|
||||
- **Root Cause**: Passing global Next.js `RequestInit` options directly into `undici.fetch` will throw strict TypeScript errors because the `BodyInit` and `RequestCache` signatures differ, and `dns.lookup` returns a generic `number` instead of exactly `4 | 6` for IP families.
|
||||
- **Resolution**: Strip out Next.js specific keys, explicitly cast `body` as `any`, and explicitly type `resolvedFamily: number` when interfacing between Next.js request streams and the `undici` library.
|
||||
@@ -1,7 +1,9 @@
|
||||
---
|
||||
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/**/*"
|
||||
paths:
|
||||
- "src/core/globe/**/*"
|
||||
- "src/plugins/**/*"
|
||||
- "packages/wwv-plugin-*/src/**/*"
|
||||
---
|
||||
|
||||
# Cesium Rendering Rules
|
||||
@@ -23,6 +25,23 @@ 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.
|
||||
|
||||
## Sizing Conventions
|
||||
|
||||
| Entity type | Knob | Default | Typical band | Source |
|
||||
|-------------|--------------|------------------------------------|------------------|--------|
|
||||
| `point` | `size` | `8` desktop / `12` mobile | 5–12 | `src/core/globe/primitiveOps.ts` (`defaultPointSize`) |
|
||||
| `billboard` | `iconScale` | `0.7` (`DEFAULT_BILLBOARD_SCALE`) | 0.6–0.9 | `src/core/globe/primitiveOps.ts` (`DEFAULT_BILLBOARD_SCALE`) |
|
||||
| `model` | `modelScale` | `1.0` + `modelMinPixelSize` | varies per asset | `src/core/globe/ModelManager.ts`, `src/core/globe/hooks/useModelRendering.ts` |
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Cross-plugin parity rule.** If your plugin renders alongside maritime / aviation / military-aviation on the globe, **leave `iconScale` unset** (or pick a value inside 0.6–0.9). A value below 0.5 will look visibly broken next to peer plugins. A value above 1.0 will dominate the globe.
|
||||
|
||||
> [!CAUTION]
|
||||
> **Silent-ignore footgun.** `size` is a `PointPrimitive` property. If you set `size` on a `billboard` entity it is **silently dropped** — Cesium does not error and the billboard simply renders at `DEFAULT_BILLBOARD_SCALE`. When converting a point plugin to a billboard plugin, replace `size: N` with `iconScale: ~N/16` (the canvas base is `getBaseSize() = 48px` desktop) — do not delete it and do not translate it literally as `iconScale: N/10`. This footgun has shipped at least once (see commit history on `local-plugins/wwv-plugin-satellite`).
|
||||
|
||||
> [!NOTE]
|
||||
> **Backdrop stack.** `createSvgIconUrl` (in the SDK) already wraps the icon in a 44×44 SVG with a dark backdrop circle. `src/core/globe/iconUpscaler.ts` then redraws onto a 48px canvas with **another** backdrop circle (`DEFAULT_BG = "rgba(15, 23, 42, 0.55)"`). Pass `background: false` to `createSvgIconUrl` when you want only the host's circle. Don't add a third backdrop in your own SVG.
|
||||
|
||||
## Performance Culling
|
||||
|
||||
> [!TIP]
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: Cloud edition implementation details, PostgreSQL Row-Level Security (RLS) isolation, cross-subdomain auth, and cryptographic license keys.
|
||||
paths:
|
||||
- "src/lib/auth*"
|
||||
- "src/app/api/auth/**/*"
|
||||
- "src/core/auth.ts"
|
||||
- "src/core/storage.ts"
|
||||
- "src/core/tenant.ts"
|
||||
---
|
||||
|
||||
# WorldWideView — Cloud & Auth Architecture
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: Architecture rules and dependency management guidelines for wwv-data-engine seeders.
|
||||
description: Architecture rules and dependency management guidelines for wwv-data-engine seeders, pnpm workspace dependency loading, and WebSocket payload contracts.
|
||||
paths:
|
||||
- "packages/**/*"
|
||||
- "local-seeders/**/*"
|
||||
- "docker-compose.yml"
|
||||
---
|
||||
|
||||
# Data Engine V2 Architecture & Dependency Loading
|
||||
@@ -29,3 +32,60 @@ In production, the `wwv-data-engine-v2` does NOT mount the local file system. In
|
||||
|
||||
## 5. Namespace Separation Rule
|
||||
To prevent collisions and `404` or `ERR_MODULE_NOT_FOUND` errors, seeders **MUST NOT** exist simultaneously in both the community (`wwv-seeders-community`) and private (`wwv-seeders-private`) repositories. Namespace overlaps will cause module resolution failures when the V2 engine attempts to load them. Private seeders have priority.
|
||||
|
||||
## 6. Plugin ID Contract — Single Source of Truth
|
||||
|
||||
> **See ADR-0002** (`docs/architecture/decisions/adr-0002-seeder-exported-name-as-canonical-plugin-id.md`) for full rationale and alternatives considered.
|
||||
|
||||
**Rule:** Every seeder MUST export a `name` field that exactly matches the corresponding frontend plugin's `id` field (kebab-case).
|
||||
|
||||
```typescript
|
||||
// ✅ Correct — seeder src/index.ts
|
||||
export default {
|
||||
name: "gps-jamming", // MUST equal the frontend plugin id
|
||||
cron: "0 0 * * *",
|
||||
fn: seedGpsJam,
|
||||
};
|
||||
|
||||
// ❌ Wrong — do not use folder names, camelCase, or abbreviations
|
||||
export default {
|
||||
name: "gpsjam", // mismatch — frontend plugin is "gps-jamming"
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
**How the engine uses it:** `seeder-loader.ts` reads each seeder's exported `name` as the canonical plugin ID. This ID is used for:
|
||||
- The `/manifest` endpoint's `plugins` array (what the frontend checks for local routing)
|
||||
- WebSocket data messages (`pluginId` field)
|
||||
- Redis keys (`data:<name>:live`)
|
||||
- Scheduler logs
|
||||
|
||||
**Folder names are organizational only.** The engine warns at startup if `toKebabCase(folderName) !== seeder.name`, but this is cosmetic — the seeder's exported `name` always wins. Folder renames are a future cleanup, not a functional requirement.
|
||||
|
||||
**Frontend side:** `resolveEngineUrl(pluginId)` checks `localEngineHasPlugin(pluginId)` against the manifest. If the names match, the plugin routes to `ws://localhost:5000/stream`. No alias maps or translation layers are needed.
|
||||
|
||||
## 7. WebSocket Payload Format Contract
|
||||
|
||||
When a seeder calls `setLiveSnapshot(pluginId, payload, ttl)`, the engine broadcasts:
|
||||
```json
|
||||
{ "type": "data", "pluginId": "my-plugin", "payload": <whatever you passed> }
|
||||
```
|
||||
|
||||
**`WsClient` payload handling rules (in order):**
|
||||
|
||||
1. Plugin has `mapWebsocketPayload(payload, existingEntities)` → called with raw payload → must return `GeoEntity[]`
|
||||
2. No handler + payload **is** a flat `GeoEntity[]` array → used directly (timestamp normalized)
|
||||
3. No handler + payload is **any other object** → **silently dropped** with a console warning
|
||||
|
||||
This means:
|
||||
|
||||
| Seeder sends | Frontend needs | Notes |
|
||||
|---|---|---|
|
||||
| `[{id, latitude, longitude, ...}]` | Nothing (WsClient handles) | ✅ Simplest for basic point data |
|
||||
| `{ items: [{...}] }` | `mapWebsocketPayload` | Standard engine snapshot format |
|
||||
| `{ satellites: [{...}] }` | `mapWebsocketPayload` | Named-collection format |
|
||||
|
||||
**Recommendation:** If the seeder and frontend plugin are developed together, use a **flat `GeoEntity[]` array** — no `mapWebsocketPayload` needed. Use named objects (e.g. `{ satellites: [...] }`) only when the seeder data has a domain-specific shape worth preserving; in that case you **must** implement `mapWebsocketPayload` on the frontend plugin.
|
||||
|
||||
> [!CAUTION]
|
||||
> The most common silent bug: seeder sends `{ items: [...] }` (an object), frontend plugin omits `mapWebsocketPayload`. Data arrives but WsClient drops it with a console warning. The globe stays empty. Always implement `mapWebsocketPayload` for any plugin whose seeder sends an object payload.
|
||||
@@ -1,3 +1,9 @@
|
||||
---
|
||||
description: Rules for safe Prisma schema changes, defensive migrations, and PostgreSQL DDL operations.
|
||||
paths:
|
||||
- "prisma/**/*"
|
||||
---
|
||||
|
||||
# Database Migrations & Schema Modification Rules
|
||||
|
||||
## 1. Defensive Migrations
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
---
|
||||
description: Docker build patterns, pnpm dev commands, Vitest strategy, Coolify deployment rules, and security headers.
|
||||
paths:
|
||||
- "Dockerfile"
|
||||
- "docker-compose.yml"
|
||||
- ".github/**/*"
|
||||
- "next.config.ts"
|
||||
---
|
||||
|
||||
# Deployment, Testing, and Operations
|
||||
|
||||
## Development Commands
|
||||
@@ -39,6 +48,17 @@ Frontend runs at `http://localhost:3000`.
|
||||
- **Type-Level Contract Testing**: When defining shared TypeScript interfaces/contracts (e.g., in `wwv-plugin-sdk`), you MUST use `expectTypeOf` from `vitest` to assert the actual contract shapes at compile-time instead of writing literal-value identity runtime assertions. You must also enforce `@ts-expect-error` negative type tests to ensure missing or invalid fields trigger compilation errors.
|
||||
- **Key test files**: `rateLimit.test.ts`, `edition.test.ts`, `demoAdmin.test.ts`, `DeclarativePlugin.test.ts`, `cors.test.ts`, `repository.test.ts`, `marketplaceToken.test.ts`
|
||||
|
||||
### E2E Testing (Playwright)
|
||||
|
||||
WorldWideView uses Playwright for End-to-End browser testing to verify the complete UI integration including NextAuth.
|
||||
|
||||
- **Run**: `pnpm run test:e2e` (Ensure your database is running before executing)
|
||||
- **Auth Bypass**: Playwright uses a `global.setup.ts` to directly insert a test user into the database and simulate a UI login to capture a `storageState.json` cookie file. This allows all tests to run pre-authenticated without bypassing production security logic.
|
||||
- **Database Access in Setup**: Because Playwright setup scripts run in a vanilla Node context, importing Next.js backend utilities like `src/lib/db.ts` will crash with `next/headers` resolution errors. You MUST instantiate `PrismaClient` directly using `@prisma/adapter-pg` in any Playwright `setup` or `teardown` scripts.
|
||||
- **Component Synchronization**: Do not use arbitrary timeouts. Tests MUST wait for the application boot sequence to finish by waiting for the `[data-testid="app-ready"]` marker on the `AppShell` to be attached.
|
||||
- **Stable Selectors**: Always use `data-testid` properties (e.g. `data-testid="panel-toggle-left"`) for interacting with UI components in E2E tests rather than fragile CSS classes or dynamic text.
|
||||
- **Worktree Port Conflicts**: If you are testing in a git worktree, configure `playwright.config.ts` to spawn the `webServer` on an alternative port (e.g. `3001`) to avoid colliding with other running worktrees.
|
||||
|
||||
## Security Headers
|
||||
|
||||
Configured in `next.config.ts` `headers()`:
|
||||
@@ -248,6 +268,9 @@ The production Coolify instance runs on a local server at `192.168.68.64`. Direc
|
||||
1. Push to `silvertakana/worldwideview`
|
||||
2. Coolify webhook triggers → automated BuildKit deployment on the host server.
|
||||
|
||||
**GitHub Actions Workflows:**
|
||||
- **Minimal Permissions:** CodeQL and GitHub security best practices dictate that `GITHUB_TOKEN` permissions should always be explicitly constrained. When creating or modifying `.github/workflows/*.yml` files, you MUST always include an explicit `permissions` block (e.g., `permissions: { contents: read }` or similar required scopes) at the top level or job level to adhere to the principle of least privilege.
|
||||
|
||||
**Coolify Deployment Rules & Gotchas (The "Redis 500k" Rule):**
|
||||
- **Coolify Pulls from GitHub:** Coolify does *not* deploy your local workspace files. It strictly clones the repository from GitHub.
|
||||
- **Push Before You Deploy:** If you make a critical infrastructure or optimization fix locally (e.g., swapping a massive `HSET` pipeline for a compressed 5-min throttled `setLiveSnapshot`), you **must** `git commit` and `git push` those changes to the `main` branch before triggering a Coolify deployment.
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
description: Guidelines and architecture for the Playwright End-to-End (E2E) testing infrastructure.
|
||||
paths:
|
||||
- "tests/**"
|
||||
- "public/e2e-fixtures/**"
|
||||
- "playwright.config.ts"
|
||||
---
|
||||
|
||||
# E2E Testing Infrastructure
|
||||
|
||||
The WorldWideView project uses **Playwright** for end-to-end (E2E) testing. This document outlines the boundaries, architectural decisions, and conventions required when authoring or modifying E2E tests.
|
||||
|
||||
## 1. Resource Constraints & Parallelism
|
||||
- **Worker Limits:** The Playwright configuration (`playwright.config.ts`) is strictly limited to a maximum of **2 workers**.
|
||||
- **Reasoning:** Running Next.js compilation alongside a heavy Prisma connection pool inside multiple parallel test workers will lead to database connection exhaustion and resource contention on CI and local environments. Do not increase the worker count beyond 2 without careful consideration of the database pool limits.
|
||||
|
||||
## 2. Test User Lifecycle
|
||||
E2E tests require an authenticated user to access core application features. We manage this test user securely to ensure the environment stays pristine:
|
||||
|
||||
- **Setup (`tests/global.setup.ts`):** Before tests run, the global setup script defensively deletes any existing test user (`[email protected]`) and creates a fresh instance with the `ADMIN` role. It then performs a UI login to capture the authentication state, which is shared across all test files.
|
||||
- **Teardown (`tests/global.teardown.ts`):** After the entire test suite completes (regardless of success or failure), the global teardown script runs and completely purges the test user from the database.
|
||||
- **Safety:** Do not use `[email protected]` for manual testing. It is volatile and intended exclusively for the CI test runner.
|
||||
|
||||
## 3. UI Interaction Conventions
|
||||
- **Strict Selector Usage**: ALWAYS use `data-testid` selectors (e.g., `getByTestId('panel-toggle-left')`) for DOM interactions. **NEVER rely on CSS classes** (like `.layer-item__toggle` or `.dock-btn`) or deep DOM structures, as these are brittle and break during design refactors. If a `data-testid` is missing from an element you need to test, you MUST add it to the React component source code first.
|
||||
- **Dialog Interception:** WorldWideView relies on heavy frontend plugin discovery and dynamic rendering. For example, the `UnverifiedPluginBatchDialog` may unexpectedly appear and block UI interactions in a fresh browser context.
|
||||
- *Mitigation:* Ensure your test suites either explicitly handle these dialogs (e.g., in a `beforeEach` block) or inject mock plugins that bypass the verification flow entirely.
|
||||
|
||||
## 4. Mock Plugins
|
||||
- **Data Interface Strictness**: WorldWideView's `PluginManager` is extremely strict. **ALL mock plugins MUST implement `getPollingInterval`, `fetch`, and `renderEntity`**, even if they are purely UI-focused (like a bottom-panel plugin). Failure to implement these will crash the renderer.
|
||||
- **Capabilities**: If your mock UI plugin needs to be manually activated by the user, ensure its manifest includes the `"ui:sidebar"` capability so it appears in the layer list.
|
||||
- **Injection:** We inject safe, deterministic mock plugins into the database during the `global.setup.ts` phase to test the core rendering pipeline without relying on external APIs. Ensure your mock plugin is registered in the setup and teardown cleanup arrays.
|
||||
- **Location:** Mock plugin configurations and manifests are stored in `public/e2e-fixtures/`. When modifying the rendering engine, ensure you also update the mock plugin (`public/e2e-fixtures/mock-plugin.js`) to reflect any changes in the Plugin SDK capabilities.
|
||||
|
||||
## 5. Security Permissions
|
||||
- When integrating Playwright tests into GitHub Actions (e.g., `.github/workflows/playwright.yml`), you MUST include an explicit permissions block (e.g., `permissions: { contents: read }`) to adhere to CodeQL and least-privilege scoping rules.
|
||||
|
||||
> [!WARNING]
|
||||
> If you encounter flaky tests or `ECONNREFUSED` errors during Playwright runs, check if the local Next.js dev server or the Docker engine stack is competing for ports (e.g., port 5432 or 3000). Ensure `pnpm run dev:backends` is running and stable before launching the test suite.
|
||||
|
||||
## 6. Execution Environment & Tooling Limitations
|
||||
The development environment operates on **Windows PowerShell**. Agents MUST adhere to the following strict execution rules when running commands or interacting with the testing infrastructure:
|
||||
- **No Double Ampersands (`&&`)**: Standard Windows PowerShell (prior to v7) does not support the `&&` operator. Use the semicolon (`;`) to chain commands, or rely on `pnpm` package.json scripts which manage cross-platform execution properly.
|
||||
- **Avoid Non-existent Database CLI Commands**: Do not attempt to use raw `pg` or `psql` commands unless explicitly verified to exist in the path. Instead, use Prisma (`npx prisma studio`, `npx prisma migrate`) or Docker executions (`docker exec -it wwv-db psql ...`) for database interactions.
|
||||
- **Creating Test Plugins**: You will repeatedly need to create mock test plugins for verifying different platform features (e.g. bottom-panel resizing, new UI widgets). When doing so, you MUST review this `e2e-testing.md` file to ensure compliance with the `PluginManager` strict interface rules (implementing `getPollingInterval`, `fetch`, and `renderEntity`).
|
||||
@@ -1,6 +1,8 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: Guidelines for the WorldwideView plugin marketplace, database interactions, and dynamic plugin installation.
|
||||
description: Guidelines for the WorldWideView plugin marketplace, database interactions, PKCE auth flow, and dynamic plugin installation.
|
||||
paths:
|
||||
- "src/lib/marketplace/**/*"
|
||||
- "src/app/api/marketplace/**/*"
|
||||
---
|
||||
|
||||
# Marketplace Architecture
|
||||
@@ -16,6 +18,18 @@ Plugins from the marketplace use the `bundle` format and are imported at runtime
|
||||
- `pluginManager.loadFromManifest()` validates and registers these plugins.
|
||||
- Ensure any schema changes to the marketplace tables follow the `database-migrations.md` rule.
|
||||
|
||||
## 4. Fresh-Install Seeding
|
||||
|
||||
Fresh installs (no rows in `InstalledPlugin`) auto-seed a starter set so the globe isn't empty on day one. The source of truth is the **signed verified registry** (`marketplace.worldwideview.dev/api/registry`, loaded by `registryClient.getVerifiedPluginIds()`).
|
||||
|
||||
- **No hard-coded plugin lists.** Publishing a plugin to the verified registry is what makes it part of the fresh-install starter set.
|
||||
- **Idempotent**: a `defaults_seeded` row in the `Setting` table prevents re-runs. If the registry is unreachable on first attempt, the guard is NOT set — the next request retries.
|
||||
- **Existing instances** with `defaults_seeded=true` are untouched. To pull in newly-verified plugins, users install via the marketplace UI.
|
||||
- **Demo edition** uses an independent path (`NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS` env var, handled in `AppShell.tsx` and `useMarketplaceSync.ts`) — not this seeder.
|
||||
|
||||
> [!CAUTION]
|
||||
> Do not reintroduce a static `DEFAULT_PLUGIN_IDS` constant or any other hard-coded plugin list. That drifted from npm reality, caused 404s for unpublished IDs, and conflated "verified" with "auto-installed."
|
||||
|
||||
## Current Implementation State
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: Strict rules for operating within the pnpm monorepo workspace environment structure across frontend and backend services.
|
||||
globs: ""
|
||||
paths:
|
||||
- "packages/**/*"
|
||||
- "pnpm-workspace.yaml"
|
||||
- "local-plugins/**/*"
|
||||
---
|
||||
|
||||
# Monorepo Workflow Guidelines
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
---
|
||||
trigger: model_decision
|
||||
description: The standard operating procedure for instantiating, modifying, and registering a new data source plugin within the engine.
|
||||
paths:
|
||||
- "src/core/plugins/**/*"
|
||||
- "packages/wwv-plugin-*/src/**/*"
|
||||
- "local-plugins/**/*"
|
||||
- "packages/wwv-plugin-sdk/src/**/*"
|
||||
---
|
||||
|
||||
# Plugin Architecture & Data Flow
|
||||
@@ -17,6 +21,59 @@ A valid plugin class MUST provide:
|
||||
3. `renderEntity(GeoEntity)` to determine visual style.
|
||||
4. `getPollingInterval()` (defaults fallback securely to standard store config).
|
||||
|
||||
## Plugin Data Delivery Types
|
||||
|
||||
Plugins receive entity data in one of three modes. Choose the right mode before writing code — mixing them causes silent data loss.
|
||||
|
||||
| Mode | `getPollingInterval()` | `fetch()` | `mapWebsocketPayload()` | When to use |
|
||||
|---|---|---|---|---|
|
||||
| **REST-only** | `> 0` (ms) | Returns `GeoEntity[]` | Not needed | Static or slow-changing data (< every 30s). No seeder required. |
|
||||
| **WebSocket-only** | `0` | Return `[]` immediately | **Required** if seeder sends object payload | Live-streaming data from a seeder (satellites, AIS, flights) |
|
||||
| **Hybrid** | `> 0` | Returns initial snapshot | **Required** if seeder sends object payload | Needs both immediate data on load AND live updates |
|
||||
|
||||
### WebSocket-Only Pattern (most live-data plugins)
|
||||
|
||||
```typescript
|
||||
getPollingInterval(): number {
|
||||
return 0; // WS-only — do NOT call REST on enable
|
||||
}
|
||||
|
||||
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
return []; // Initial data arrives via mapWebsocketPayload within seconds
|
||||
}
|
||||
|
||||
mapWebsocketPayload(payload: any, _existingEntities: GeoEntity[]): GeoEntity[] {
|
||||
// Transform raw engine payload → GeoEntity[]
|
||||
// payload shape depends on what the seeder calls setLiveSnapshot() with
|
||||
const items = payload?.items ?? (Array.isArray(payload) ? payload : []);
|
||||
return items.map((item: any): GeoEntity => ({
|
||||
id: `my-plugin-${item.id}`,
|
||||
pluginId: "my-plugin",
|
||||
latitude: item.lat,
|
||||
longitude: item.lon,
|
||||
altitude: item.alt ?? 0,
|
||||
timestamp: new Date(),
|
||||
label: item.name,
|
||||
properties: item,
|
||||
}));
|
||||
}
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> If `getPollingInterval()` returns `0` but the seeder sends an object payload, you **MUST** implement `mapWebsocketPayload`. Without it, `WsClient` drops the data silently. See `data-engine-architecture.md §7` for the exact rule.
|
||||
|
||||
### `mapWebsocketPayload` Signature
|
||||
|
||||
```typescript
|
||||
mapWebsocketPayload(payload: any, existingEntities: GeoEntity[]): GeoEntity[]
|
||||
```
|
||||
|
||||
- `payload` — raw value from `setLiveSnapshot()` in the seeder (whatever shape the seeder stores)
|
||||
- `existingEntities` — current entities in the store for this plugin (use for incremental updates)
|
||||
- Must return a **complete replacement** `GeoEntity[]` (not a diff)
|
||||
|
||||
---
|
||||
|
||||
## Plugin Architectures (Manifest Formats)
|
||||
|
||||
Plugins are defined via `PluginManifest` and operate on an **All-Bundle** architecture.
|
||||
@@ -52,6 +109,33 @@ All plugins MUST define their identity and compatibility via a `"worldwideview"`
|
||||
}
|
||||
```
|
||||
|
||||
### `peerDependencies` Rule for npm-Published Plugins
|
||||
|
||||
Plugins published to npm **MUST** declare the following as `peerDependencies`, not `dependencies`:
|
||||
|
||||
```json
|
||||
{
|
||||
"peerDependencies": {
|
||||
"@worldwideview/wwv-plugin-sdk": "*",
|
||||
"react": ">=19",
|
||||
"lucide-react": "*"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Also peer (never bundle): `react-dom`, `cesium`, `resium`, `zustand`.
|
||||
|
||||
Bundling these causes multiple React instances in the host app, breaking hooks (`Invalid hook call` at runtime).
|
||||
|
||||
### File Extension Rule
|
||||
|
||||
- Files containing **JSX** (any `<Component />` syntax, `return (<div>...)`) → must use `.tsx`
|
||||
- Files with no JSX (pure TypeScript, even importing React types) → use `.ts`
|
||||
|
||||
This is enforced by the TypeScript compiler. A `.ts` file with JSX will fail to build.
|
||||
|
||||
---
|
||||
|
||||
## The Registration Pipeline
|
||||
|
||||
> [!NOTE]
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
---
|
||||
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/**/*"
|
||||
paths:
|
||||
- "src/core/state/**/*"
|
||||
- "src/components/**/*"
|
||||
---
|
||||
|
||||
# Zustand State Management
|
||||
|
||||
@@ -38,7 +38,7 @@ Moves a WorldWideView plugin from the old `packages/` monorepo location (or the
|
||||
> ```
|
||||
> Example: `node scripts/migrate-plugin.mjs gps-jamming`
|
||||
>
|
||||
> The script will automatically copy the frontend plugin, inject peerDependencies, refactor `index.tsx` routing, fix the backend seeder's build settings and `SEEDERS_DIR` paths, and register the plugin in `defaultPlugins.ts`.
|
||||
> The script will automatically copy the frontend plugin, inject peerDependencies, refactor `index.tsx` routing, and fix the backend seeder's build settings and `SEEDERS_DIR` paths. (Fresh-install seeding no longer involves a hard-coded list — once published to npm with a valid `worldwideview` block, the plugin is registered via the signed verified registry.)
|
||||
> **You still need to run `pnpm install` and verify the builds manually as described below.**
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
name: playwright-testing
|
||||
description: Use when creating or modifying Playwright end-to-end tests, especially when injecting mock plugins to test platform features.
|
||||
---
|
||||
|
||||
# Playwright E2E Testing & Mock Plugin Guide
|
||||
|
||||
When you are tasked with testing a new feature or plugin in WorldWideView using Playwright, you must use this skill to ensure you follow the strict architecture rules of the platform.
|
||||
|
||||
## 1. Mock Plugin Requirements
|
||||
When creating a mock plugin (e.g., `public/e2e-fixtures/my-mock-plugin.js`) to test a specific UI feature, **you MUST implement the full Data Plugin interface**.
|
||||
|
||||
WorldWideView's `PluginManager` throws fatal runtime errors if a plugin is missing core data fetching methods, even if your plugin only tests a UI component like a bottom panel.
|
||||
|
||||
**Required Methods for EVERY Mock Plugin:**
|
||||
```javascript
|
||||
export default {
|
||||
id: "my-mock-plugin",
|
||||
name: "My Mock Plugin",
|
||||
// ...
|
||||
// MUST BE INCLUDED:
|
||||
fetch: async (timeRange) => { return []; },
|
||||
getPollingInterval: () => { return 60000; },
|
||||
getLayerConfig: () => { return { color: "#FFF", clusterEnabled: false, clusterDistance: 50 }; },
|
||||
renderEntity: (entity) => { return { type: "point", color: "#FFF", size: 5 }; },
|
||||
|
||||
// Your UI testing component (e.g., Sidebar, Bottom Panel)
|
||||
getBottomPanelComponent: () => { ... }
|
||||
}
|
||||
```
|
||||
|
||||
## 2. Mock Plugin Manifest Capabilities
|
||||
If your mock plugin needs to be toggled by the user in the Layers list, you MUST include the `"ui:sidebar"` capability in its `manifest.json`.
|
||||
```json
|
||||
{
|
||||
"capabilities": ["ui:bottom-panel", "ui:sidebar"],
|
||||
"extends": ["sidebar"]
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Database Injection
|
||||
The frontend reads plugins from the database. You MUST inject your mock plugin during `tests/global.setup.ts` using Prisma:
|
||||
|
||||
```typescript
|
||||
const manifestPath = path.join(process.cwd(), 'public', 'e2e-fixtures', 'my-mock-plugin-manifest.json');
|
||||
const manifestStr = fs.readFileSync(manifestPath, 'utf-8');
|
||||
await prisma.installedPlugin.create({
|
||||
data: {
|
||||
pluginId: 'my-mock-plugin',
|
||||
version: '1.0.0',
|
||||
config: manifestStr,
|
||||
enabled: true
|
||||
}
|
||||
});
|
||||
```
|
||||
Make sure to add your new mock plugin ID to the cleanup logic in `global.setup.ts` as well:
|
||||
```typescript
|
||||
await prisma.installedPlugin.deleteMany({
|
||||
where: { pluginId: { in: ['e2e-mock-plugin', 'my-mock-plugin'] } }
|
||||
});
|
||||
```
|
||||
|
||||
## 4. UI Selectors
|
||||
**DO NOT use CSS classes for your locators.** CSS classes change frequently (e.g., `.dock-btn`, `.layer-item__toggle`).
|
||||
You MUST either:
|
||||
1. Add explicit `data-testid` attributes to the React components you are testing.
|
||||
2. Use stable accessibility locators (e.g., `getByRole('button', { name: /Text/ })`).
|
||||
|
||||
## 5. Execution Environment
|
||||
- Ensure `pnpm run dev:backends` is running before you execute tests locally.
|
||||
- Run tests using `pnpm run test:e2e` or `npx playwright test tests/your-test.spec.ts`.
|
||||
- **PowerShell Warning**: Remember you are running in Windows PowerShell. Do NOT chain commands with `&&`. Use `;` instead.
|
||||
@@ -24,20 +24,29 @@ If you create a worktree inside a subdirectory of the current repo (e.g., `.agen
|
||||
Do not use raw `git worktree add`. Always use the `git-wt` alias provided by Worktrunk. It is pre-configured via `.config/wt.toml` to:
|
||||
- Automatically place the worktree in the correct sibling path.
|
||||
- Automatically run `pnpm install`.
|
||||
- Automatically copy `.env` and `.env.local` files so the environment works immediately.
|
||||
- Automatically copy `.env` files so the environment works immediately.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **For AI Agents:** You MUST append the `--yes` flag when creating worktrees to bypass the interactive approval prompt for these hooks, otherwise the command will fail in your non-interactive shell.
|
||||
|
||||
### 3. Database Lifecycle & Port Assignment
|
||||
Each worktree gets a deterministic PostgreSQL port assigned automatically based on its directory hash (to avoid collisions between multiple running worktrees).
|
||||
|
||||
> [!CAUTION]
|
||||
> **Orphaned Volumes:** You MUST use `git-wt remove` to delete worktrees. This triggers a `pre-remove` hook that cleanly tears down the Docker database. If you manually delete the folder (`rm -rf`), the Docker volume is orphaned. If this happens, run `pnpm run db:prune` in the main repository to garbage collect orphaned database volumes.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Action | Command | Details |
|
||||
| :--- | :--- | :--- |
|
||||
| **Create Worktree** | `git-wt switch --create <branch>` | Provisions the sibling directory, branch, env files, and dependencies. |
|
||||
| **Create Worktree** | `git-wt switch --create <branch> --yes` | Provisions the sibling directory, branch, env files, and dependencies. |
|
||||
| **Delete Worktree** | `git-wt remove` | Deletes the worktree and the associated branch cleanly. Run from within the worktree. |
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. Run the create command from the main repository:
|
||||
1. Run the create command from the main repository (always include `--yes`):
|
||||
```bash
|
||||
git-wt switch --create feature/my-new-idea
|
||||
git-wt switch --create feature/my-new-idea --yes
|
||||
```
|
||||
2. **CRITICAL:** Change your working directory to the newly created worktree before editing files. Worktrunk creates it as a sibling.
|
||||
```bash
|
||||
|
||||
@@ -29,20 +29,15 @@ A WorldWideView plugin is a self-contained data source that renders geospatial e
|
||||
|
||||
## Architecture Decision
|
||||
|
||||
```dot
|
||||
digraph plugin_type {
|
||||
rankdir=TB;
|
||||
node [shape=diamond];
|
||||
|
||||
"Does it need live\nexternal API data?" -> "Is polling\nfrequency > 30s?" [label="yes"];
|
||||
"Does it need live\nexternal API data?" -> "Static GeoJSON\n(wwvStaticCompiler)" [label="no"];
|
||||
"Is polling\nfrequency > 30s?" -> "Cron Seeder\n(engine)" [label="yes"];
|
||||
"Is polling\nfrequency > 30s?" -> "Init Seeder\n(engine)" [label="no"];
|
||||
|
||||
"Static GeoJSON\n(wwvStaticCompiler)" [shape=box];
|
||||
"Cron Seeder\n(engine)" [shape=box];
|
||||
"Init Seeder\n(engine)" [shape=box];
|
||||
}
|
||||
```
|
||||
Does it need live external API data?
|
||||
├── NO → Static GeoJSON plugin (wwvStaticCompiler in vite.config.ts)
|
||||
│ No seeder needed. Place data in data/data.json.
|
||||
└── YES → Does it update more often than every 30s?
|
||||
├── NO → Cron Seeder (engine, registerSeeder with cron string)
|
||||
│ getPollingInterval() = 0, mapWebsocketPayload() required
|
||||
└── YES → Init Seeder (engine, registerSeeder with init function)
|
||||
getPollingInterval() = 0, mapWebsocketPayload() required
|
||||
```
|
||||
|
||||
---
|
||||
@@ -146,7 +141,7 @@ export default class WildfiresPlugin implements WorldPlugin {
|
||||
| `getLayerConfig()` | Layer appearance (color, clustering, max entities) |
|
||||
| `renderEntity(entity)` | Per-entity Cesium rendering options |
|
||||
|
||||
**Optional:**
|
||||
**Optional (but `mapWebsocketPayload` is REQUIRED for WS-only plugins with object payloads):**
|
||||
|
||||
| Method | Purpose |
|
||||
|---|---|
|
||||
@@ -158,7 +153,7 @@ export default class WildfiresPlugin implements WorldPlugin {
|
||||
| `getDetailComponent()` | Custom detail panel for selected entity |
|
||||
| `getSettingsComponent()` | Plugin settings UI |
|
||||
| `getGlobeComponent()` | React component injected into globe view |
|
||||
| `mapWebsocketPayload(payload, existing)` | Transform raw WS data into `GeoEntity[]` |
|
||||
| `mapWebsocketPayload(payload, existing)` | **Required if seeder payload is an object** (not a flat array). Transforms raw engine payload → `GeoEntity[]`. Without it, `WsClient` drops object payloads silently. |
|
||||
| `requiresConfiguration(settings)` | Return `true` if plugin needs setup first |
|
||||
|
||||
### 1.3 Package Metadata
|
||||
@@ -518,14 +513,30 @@ export default class IssPlugin implements WorldPlugin {
|
||||
|
||||
destroy(): void {}
|
||||
|
||||
async fetch(timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
return []; // WS-only plugin
|
||||
async fetch(_timeRange: TimeRange): Promise<GeoEntity[]> {
|
||||
return []; // WS-only — data arrives via mapWebsocketPayload
|
||||
}
|
||||
|
||||
getPollingInterval(): number {
|
||||
return 0; // WS-only
|
||||
}
|
||||
|
||||
// REQUIRED: seeder sends { source, fetchedAt, items: [...], totalCount } (an object).
|
||||
// Without this, WsClient drops the payload silently — the globe stays empty.
|
||||
mapWebsocketPayload(payload: any, _existingEntities: GeoEntity[]): GeoEntity[] {
|
||||
const items: any[] = payload?.items ?? (Array.isArray(payload) ? payload : []);
|
||||
return items.map((item: any): GeoEntity => ({
|
||||
id: `iss-${item.id}`,
|
||||
pluginId: "iss",
|
||||
latitude: item.lat,
|
||||
longitude: item.lon,
|
||||
altitude: item.alt ?? 0,
|
||||
timestamp: new Date(),
|
||||
label: "International Space Station",
|
||||
properties: { speed: item.speed },
|
||||
}));
|
||||
}
|
||||
|
||||
getLayerConfig(): LayerConfig {
|
||||
return {
|
||||
color: "#ffffff",
|
||||
@@ -644,7 +655,9 @@ Categories are **lowercase**: `"aviation"` not `"Aviation"`, `"natural-disaster"
|
||||
- [ ] **Engine:** Seeder file in `wwv-seeders/src/seeders/<name>.ts` (or private repo)
|
||||
- [ ] **Engine:** `registerSeeder({ name })` matches frontend plugin `id`
|
||||
- [ ] **Engine:** Calls `setLiveSnapshot()` with correct plugin ID key
|
||||
- [ ] **Engine:** Data shape is an object with `items` array (or plugin implements `mapWebsocketPayload`)
|
||||
- [ ] **Engine:** Seeder payload is either a flat `GeoEntity[]` array OR plugin implements `mapWebsocketPayload` (any other object is silently dropped by WsClient)
|
||||
- [ ] **Frontend (WS-only):** `getPollingInterval()` returns `0` and `fetch()` returns `[]`
|
||||
- [ ] **Frontend (WS-only):** `mapWebsocketPayload(payload, existingEntities)` implemented if seeder sends an object
|
||||
- [ ] **Engine:** SQLite table created in `db.ts` if historical data needed
|
||||
- [ ] **Verification:** `GET localhost:5000/manifest` includes the plugin ID
|
||||
- [ ] **Verification:** `GET localhost:5000/health` shows seeder last-run timestamp
|
||||
|
||||
+10
-1
@@ -2,4 +2,13 @@
|
||||
install_deps = "pnpm install"
|
||||
|
||||
[[pre-start]]
|
||||
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }; if (Test-Path '../worldwideview/.env.local') { Copy-Item '../worldwideview/.env.local' '.env.local' -Force }""""
|
||||
copy_env = """powershell -Command "if (Test-Path '../worldwideview/.env') { Copy-Item '../worldwideview/.env' '.env' -Force }""""
|
||||
|
||||
[[pre-start]]
|
||||
copy_local_plugins = """powershell -Command "if (Test-Path '../worldwideview/local-plugins') { robocopy '../worldwideview/local-plugins' 'local-plugins' /E /XD node_modules dist .next coverage /XF '*.log' /NFL /NDL /NJH /NJS | Out-Null }""""
|
||||
|
||||
[[pre-start]]
|
||||
copy_local_seeders = """powershell -Command "if (Test-Path '../worldwideview/local-seeders') { robocopy '../worldwideview/local-seeders' 'local-seeders' /E /XD .pnpm-store node_modules /NFL /NDL /NJH /NJS | Out-Null }""""
|
||||
|
||||
[[pre-remove]]
|
||||
docker_clean = "docker compose down -v"
|
||||
@@ -55,6 +55,11 @@ NEXT_PUBLIC_DEMO_DEFAULT_PLUGINS=
|
||||
# Edition: "local" | "cloud" | "demo"
|
||||
NEXT_PUBLIC_WWV_EDITION=local
|
||||
|
||||
# Optional Database Teardown
|
||||
# If set to true, terminating 'pnpm run dev' (Ctrl+C) will automatically
|
||||
# stop the local database container (freeing up port 5432).
|
||||
WWV_TEARDOWN_DB_ON_EXIT=false
|
||||
|
||||
# Demo Admin Secret (demo edition only)
|
||||
# Allows operator plugin management on the demo instance via x-wwv-admin-secret header.
|
||||
# Generate any random string. Only set this on the demo deployment.
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Playwright Tests
|
||||
on:
|
||||
push:
|
||||
branches: [ main, master ]
|
||||
pull_request:
|
||||
branches: [ main, master ]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
test:
|
||||
timeout-minutes: 60
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
browser: [chromium, firefox, webkit]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v3
|
||||
with:
|
||||
version: 9.15.4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Install Playwright Browsers
|
||||
run: pnpm exec playwright install --with-deps
|
||||
|
||||
- name: Run Project Setup
|
||||
run: pnpm run setup
|
||||
|
||||
- name: Boot Database
|
||||
run: |
|
||||
docker network create coolify || true
|
||||
pnpm run predev
|
||||
|
||||
- name: Run Playwright tests
|
||||
env:
|
||||
# Prevent Firefox from loading the AT-SPI/MSAA accessibility bridge on
|
||||
# Linux CI — without this, Firefox hangs for ~20 min waiting for a bus
|
||||
# that doesn't exist on ubuntu-latest runners.
|
||||
NO_AT_BRIDGE: ${{ matrix.browser == 'firefox' && '1' || '0' }}
|
||||
run: pnpm test:e2e --project=${{ matrix.browser }}
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ !cancelled() }}
|
||||
with:
|
||||
name: playwright-report-${{ matrix.browser }}
|
||||
path: playwright-report/
|
||||
retention-days: 30
|
||||
@@ -0,0 +1,60 @@
|
||||
name: Test Local Dev Environment
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test-dev:
|
||||
name: Test Local Dev Startup
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
NEXT_PUBLIC_WWV_EDITION: local
|
||||
AUTH_SECRET: ci-placeholder-secret-not-used-in-tests
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- name: Create coolify docker network
|
||||
# Needed because docker-compose.yml references external coolify network
|
||||
run: docker network create coolify || true
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Setup environment
|
||||
run: cp .env.example .env
|
||||
|
||||
- name: Test predev setup
|
||||
# Tests that Docker DB boots, port mappings work, Prisma pushes schema, and plugins sync
|
||||
run: pnpm run predev
|
||||
|
||||
- name: Test dev server startup
|
||||
run: |
|
||||
# Start the dev server in the background
|
||||
pnpm run dev &
|
||||
DEV_PID=$!
|
||||
|
||||
echo "Waiting for Next.js to respond on port 3000..."
|
||||
|
||||
# Wait up to 120 seconds for the dev server to return a response
|
||||
timeout 120 bash -c 'until curl -s http://localhost:3000 > /dev/null; do sleep 5; done'
|
||||
|
||||
# Check if the process is still running
|
||||
if ! kill -0 $DEV_PID 2>/dev/null; then
|
||||
echo "Dev server crashed or failed to start within timeout!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Dev server started successfully!"
|
||||
|
||||
# Graceful shutdown
|
||||
kill $DEV_PID
|
||||
+9
-7
@@ -19,13 +19,8 @@ node_modules/
|
||||
|
||||
# agents
|
||||
/.agents/plans
|
||||
/.agents/context
|
||||
/.agents/research/
|
||||
|
||||
# claude code IDE config
|
||||
/.claude/
|
||||
/.cline/
|
||||
|
||||
# performance
|
||||
/performance/
|
||||
|
||||
@@ -64,7 +59,8 @@ yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
@@ -96,6 +92,7 @@ packages/wwv-data-engine/
|
||||
|
||||
# IDE workspace files
|
||||
*.code-workspace
|
||||
*.vscode
|
||||
|
||||
# Build outputs and generated assets
|
||||
/public/cesium/
|
||||
@@ -127,4 +124,9 @@ skills-lock.json
|
||||
/wwv-seeders/
|
||||
/wwv-seeders-private/
|
||||
/wwv-test/
|
||||
worldwideview.code-workspace
|
||||
worldwideview.code-workspace
|
||||
|
||||
# Playwright
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
/playwright/.auth/
|
||||
@@ -2,11 +2,8 @@
|
||||
|
||||
## 1. Project Identity
|
||||
|
||||
WorldWideView is a **real-time geospatial intelligence engine** that visualizes live global data on an interactive 3D globe. Built with **Next.js 16**, **CesiumJS**, **React 19**, and **Zustand**, it renders everything from live aircraft and maritime vessels to conflict events, satellites, and environmental data — all through a modular plugin architecture.
|
||||
WorldWideView is a **real-time geospatial intelligence engine** visualizing live global data on an interactive 3D globe. Built with **Next.js 16**, **CesiumJS**, **React 19**, and **Zustand**. Design/feature target: `www.worldmonitor.app` ([reference repo](https://github.com/koala73/worldmonitor)).
|
||||
|
||||
### Target Inspiration
|
||||
Our primary design, feature-set, and operational layout goal is to mimic the structure and capabilities of `www.worldmonitor.app`.
|
||||
- **Reference Codebase**: [GitHub - koala73/worldmonitor](https://github.com/koala73/worldmonitor)
|
||||
---
|
||||
|
||||
## 2. Tech Stack
|
||||
@@ -16,486 +13,151 @@ Our primary design, feature-set, and operational layout goal is to mimic the str
|
||||
| Framework | Next.js 16 (App Router, `output: "standalone"`) |
|
||||
| Language | TypeScript 5, strict mode |
|
||||
| 3D Engine | CesiumJS + Resium (Google Photorealistic 3D Tiles) |
|
||||
| State | Zustand (slice-based: globe, layers, timeline, UI, filters, data, config, favorites, geojson) |
|
||||
| State | Zustand (9 slices: globe, layers, timeline, ui, filter, data, config, favorites, geojson) |
|
||||
| Event Bus | Custom typed `DataBus` (pub/sub singleton) |
|
||||
| Styling | Vanilla CSS — **no Tailwind** |
|
||||
| Database | PostgreSQL via Prisma 7 (local and cloud) |
|
||||
| Database | PostgreSQL via Prisma 7 |
|
||||
| Auth | NextAuth v5 beta (Credentials provider, JWT sessions) |
|
||||
| Package Manager | pnpm (monorepo with `pnpm-workspace.yaml`) |
|
||||
| Testing | Vitest + jsdom + React Testing Library |
|
||||
| Deployment | Docker multi-stage build → Coolify |
|
||||
| Analytics | Vercel Analytics / custom `trackEvent` |
|
||||
|
||||
---
|
||||
|
||||
## 3. Directory Structure
|
||||
## 3. Critical Invariants
|
||||
|
||||
> [!NOTE]
|
||||
> See `.agents/rules/directory-structure.md` for the full project directory map and related repositories.
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture Patterns
|
||||
|
||||
> [!NOTE]
|
||||
> See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the human-facing architecture deep-dive — plugin system, state management, data pipeline, data engine & seeders, rendering pipeline, and edition system.
|
||||
|
||||
Key invariants agents MUST respect:
|
||||
Agents MUST respect these at all times:
|
||||
|
||||
- **Plugin source of truth**: `@worldwideview/wwv-plugin-sdk` — never define plugin types locally.
|
||||
- **All-Bundle Model**: every plugin (seeder, CDN-loaded, static-compiled, active-proxied) is dynamically imported via `loadPluginFromManifest` using `import(/* webpackIgnore: true */ entry)`. Legacy `StaticDataPlugin` / `DeclarativePlugin` runtimes are deprecated.
|
||||
- **Agnostic frontend**: the renderer has no concept of a "unified" data engine. Each plugin **MUST declare its own `streamUrl`** in its manifest or config; do not assume one shared pipe.
|
||||
- **Nine Zustand slices** under `src/core/state/`: `globe`, `layers`, `timeline`, `ui`, `filter`, `data`, `config`, `favorites`, `geojson`. Access via `useStore` in React, `useStore.getState()` elsewhere.
|
||||
- **Primitive-based rendering** (not Cesium Entity API). Point/Billboard/Label/Polyline collections only. Never mix `size`/`outlineWidth`/`outlineColor` onto billboard entities — GPU silently clips.
|
||||
- **Three editions** controlled by `NEXT_PUBLIC_WWV_EDITION` (`local` / `cloud` / `demo`); feature flags derived in `src/core/edition.ts`.
|
||||
- **All-Bundle Model**: every plugin is dynamically imported via `loadPluginFromManifest` using `import(/* webpackIgnore: true */ entry)`. Legacy `StaticDataPlugin` / `DeclarativePlugin` runtimes are deprecated.
|
||||
- **Agnostic frontend**: each plugin **MUST declare its own `streamUrl`**; do not assume one shared pipe.
|
||||
- **Nine Zustand slices** under `src/core/state/`: access via `useStore` in React, `useStore.getState()` elsewhere.
|
||||
- **Primitive-based rendering**: Point/Billboard/Label/Polyline collections only. Never mix `size`/`outlineWidth`/`outlineColor` onto billboard entities — GPU silently clips.
|
||||
- **Three editions** via `NEXT_PUBLIC_WWV_EDITION` (`local` / `cloud` / `demo`); feature flags in `src/core/edition.ts`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Critical Conventions
|
||||
## 4. Conventions
|
||||
|
||||
### 5.1 File Size
|
||||
- **File size**: ~300 lines max. Extract helpers, split components, use hooks.
|
||||
- **Import aliases**: `@/*` → `./src/*`; `@worldwideview/wwv-plugin-sdk` → `./packages/wwv-plugin-sdk/src`
|
||||
- **CSS**: Vanilla CSS only. Global: `src/app/globals.css`. Scoped: CSS Modules. HUD: `src/styles/hud-animations.css`.
|
||||
- **Rendering entities**: Points use `type: "point"` + `size`/`outlineColor`/`outlineWidth`. Billboards use `type: "billboard"` + `iconUrl`/`iconScale`. NEVER mix.
|
||||
- **Plugin registration**: Built-ins via `AppShell.tsx` → `PluginRegistry` → `PluginManager`. Marketplace plugins via `InstalledPluginsLoader`.
|
||||
- **Workspace**: Use `"workspace:*"` (not `"*"`) for internal deps. New `packages/` plugins need `transpilePackages` in `next.config.ts`.
|
||||
- **Temp files**: Save debugging scripts/outputs exclusively in `/local-scripts/` — never in root.
|
||||
- **Cleanliness**: Remove dead code, unused imports, debug `console.log` before finalising. Never use `any` or `@ts-ignore`. Never create `.mdc` files.
|
||||
|
||||
**Guideline: ~300 lines per file.** If a file grows excessively large, consider modularizing it. Extract helpers, split components, or use hooks.
|
||||
---
|
||||
|
||||
### 5.2 Import Aliases
|
||||
|
||||
- `@/*` → `./src/*`
|
||||
- `@worldwideview/wwv-plugin-sdk` → `./packages/wwv-plugin-sdk/src`
|
||||
- Plugin modules are dynamically imported and do not require individual `tsconfig.json` aliases
|
||||
|
||||
### 5.3 CSS Rules
|
||||
|
||||
- **Vanilla CSS only** — no Tailwind, no CSS-in-JS
|
||||
- Global styles in `src/app/globals.css`
|
||||
- Component-scoped styles use CSS Modules (`.module.css`) or co-located `.css` files
|
||||
- HUD animations in `src/styles/hud-animations.css`
|
||||
|
||||
### 5.4 Rendering Entity Rules
|
||||
|
||||
When returning `CesiumEntityOptions` from `renderEntity()`:
|
||||
|
||||
- **Points**: Use `type: "point"` with `color`, `size`, `outlineColor`, `outlineWidth`
|
||||
- **Billboards**: Use `type: "billboard"` with `iconUrl`, `color`, `iconScale`
|
||||
- **NEVER mix**: Do not use `size`/`outlineWidth`/`outlineColor` on billboard entities — causes GPU clipping
|
||||
|
||||
### 5.5 Plugin Registration
|
||||
|
||||
Built-in plugins are instantiated in `AppShell.tsx` and registered via `PluginRegistry` → `PluginManager`. Marketplace-installed plugins are loaded from the database via `InstalledPluginsLoader`.
|
||||
|
||||
### 5.6 Workspace Rules
|
||||
|
||||
- Always run `pnpm install` from project root after creating new packages or linking local plugins
|
||||
- Official plugin packages go in `packages/wwv-plugin-<name>/`
|
||||
- Experimental/local plugin sandboxes go in `local-plugins/wwv-plugin-<name>/`
|
||||
- Globs for `packages/*`, `packages/*/backend`, and `local-plugins/*` are mapped in `pnpm-workspace.yaml` and `tsconfig.json` paths
|
||||
- Add new `packages/` plugins to `transpilePackages` in `next.config.ts` if required
|
||||
|
||||
### 5.7 AI Meta-Directives: Antigravity Standard
|
||||
|
||||
> [!NOTE]
|
||||
> This repository is orchestrated via the **Antigravity open standard**. The entry point for the agent framework is `CLAUDE.md` / `AGENTS.md` at the project root.
|
||||
## 5. AI Meta-Directives
|
||||
|
||||
> [!WARNING]
|
||||
> - **Always** use standard `.md` file extensions for rules, skills, and workflows.
|
||||
> - **Never** use proprietary `.mdc` extensions.
|
||||
> - **Never** reference Cursor IDE rules; we use the open `.agents/` standard.
|
||||
> - **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 (Gemini 3.1 Agents)**: If you are a Gemini 3.1 agent, you MUST always be fully transparent. **Whenever you do anything, you must explicitly say what you are going to do in a visible chat message to the user, and ONLY THEN do it.** This ensures the user can actually see and verify what you are doing in real time. Do not jump to destructive actions without stating your intent first. Keep this narration conversational and natural. Avoid stiff, robotic templates. Just explicitly drop a brief, casual note about what you are checking, fixing, or deleting *before* you run the tool.
|
||||
> - **MUST Require Explicit Authorization**: Do NOT execute any state-changing tools (e.g., modifying files, writing code, running scripts, executing git commands) without first obtaining clear, explicit permission from the user to proceed with that specific action, **UNLESS** the action is a simple, straightforward, and safe operation (e.g., no deletion or dangerous operations). For safe operations, you may proceed without explicit permission. Otherwise, inform the user of your proposed plan and WAIT for their approval before acting. **Crucially, if you realize you have violated this rule by taking an unauthorized action, DO NOT automatically revert it. Reverting is itself an action that requires authorization. Just answer the question.**
|
||||
> - **MUST Ask Clarifying Questions**: Never assume anything. If requirements are unclear, if you encounter an unexpected roadblock, or if the user's intent could be interpreted in multiple ways, you MUST pause and ask clarifying questions. Do NOT proceed until the developer has explicitly answered your question or requested you to proceed anyway.
|
||||
|
||||
### 5.8 Workspace Hygiene
|
||||
Whenever agents generate temporary debugging scripts, test REST endpoints via `.mjs`, or dump traces/JSON outputs, they **MUST** save these exclusively inside `/local-scripts/`. The root directory is strictly for production configuration files.
|
||||
|
||||
### 5.9 Rule Adherence & Proactive Updates
|
||||
> [!CAUTION]
|
||||
> **Agents will trust the `.agents/rules/` files unconditionally.**
|
||||
> Whenever you execute a major architectural shift or make a change that invalidates an existing rule, you **MUST** immediately update the corresponding rule file(s) and/or `AGENTS.md` to reflect the new reality. Do not leave rules untouched after a change; operating on outdated information will cause future agents to break the codebase.
|
||||
> - Always use `.md` extensions. Never `.mdc`. Never reference Cursor IDE rules.
|
||||
> - **MUST** bump semver in `package.json` before every commit via `/commit` workflow (`feat:` → Minor, `fix/refactor/perf:` → Patch).
|
||||
> - **MUST** explain complex concepts simply — include an everyday-life analogy.
|
||||
> - **MUST** require explicit user authorization before any state-changing action that isn't simple/safe.
|
||||
> - **MUST** ask clarifying questions rather than assume when requirements are unclear.
|
||||
> - **MUST** update `.agents/rules/` files immediately whenever an architectural shift invalidates them.
|
||||
|
||||
---
|
||||
|
||||
## 6. Environment & Configuration
|
||||
|
||||
> [!NOTE]
|
||||
> See `.agents/rules/environment-config.md` for required environment variables and secrets.
|
||||
See `.agents/context/environment-config.md` for required environment variables and secrets.
|
||||
|
||||
---
|
||||
|
||||
## 7. Development, Deployment & Testing
|
||||
## 7. Development & Deployment
|
||||
|
||||
> [!NOTE]
|
||||
> See `.agents/rules/deployment-and-testing.md` for development commands, Docker architecture, Vitest strategy, and CSP security headers.
|
||||
```bash
|
||||
pnpm dev # Frontend only (auto-runs prisma db push + copy-cesium)
|
||||
pnpm dev:all # Frontend + data engine via Docker Compose
|
||||
pnpm build # Production build
|
||||
pnpm test # Vitest
|
||||
pnpm db:reset # Wipe + re-migrate DB (destructive)
|
||||
```
|
||||
|
||||
See `.agents/context/` → [deployment and testing details in `.agents/rules/deployment-and-testing.md`] for Docker architecture, Coolify rules, and CSP headers.
|
||||
|
||||
---
|
||||
|
||||
## 12. On-Demand Rules
|
||||
## 8. On-Demand Rules (path-scoped, auto-load on file access)
|
||||
|
||||
Read the relevant rule file when working in that domain:
|
||||
These load automatically when you read/edit files matching their paths:
|
||||
|
||||
| Rule | When to use | Path |
|
||||
|---|---|---|
|
||||
| `platform-architecture` | High-level platform goals, product vision, business model, and Edition System | `.agents/rules/platform-architecture.md` |
|
||||
| `application-architecture` | Next.js frontend, Zustand state management, and CesiumJS integration | `.agents/rules/application-architecture.md` |
|
||||
| `plugin-architecture` | Creating/modifying plugins, lifecycle, capability declarations, and seeders (See ADR-0001) | `.agents/rules/plugin-architecture.md` |
|
||||
| `marketplace-architecture` | Dynamic plugin installation, DB sync, CDN loading, and PKCE Auth (See ADR-0001) | `.agents/rules/marketplace-architecture.md` |
|
||||
| `cloud-auth-architecture` | Cloud edition, PostgreSQL RLS, multi-tenancy, and licensing | `.agents/rules/cloud-auth-architecture.md` |
|
||||
| `server-management` | Server development and debugging using SSH and Coolify MCP | `.agents/rules/server-management.md` |
|
||||
| `stakeholders-and-human-centered-design` | Human-centered design principles and stakeholder map | `.agents/rules/stakeholders-and-human-centered-design.md` |
|
||||
| `directory-structure` | Project structure and related repositories | `.agents/rules/directory-structure.md` |
|
||||
| `ecosystem-repositories` | WorldWideView ecosystem repositories and cross-repository workflows | `.agents/rules/ecosystem-repositories.md` |
|
||||
| `deployment-and-testing` | Docker build patterns, testing strategies, security headers | `.agents/rules/deployment-and-testing.md` |
|
||||
| `environment-config` | Secrets and environment variables | `.agents/rules/environment-config.md` |
|
||||
| `monorepo-workflow` | pnpm commands, adding packages, workspace config | `.agents/rules/monorepo-workflow.md` |
|
||||
| `data-engine-architecture` | Data Engine backend seeder loading, pnpm workspace dependencies | `.agents/rules/data-engine-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, 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` |
|
||||
| `troubleshooting-and-debugging` | Resolving plugin latency, namespace collisions, or deployment issues | `.agents/rules/troubleshooting-and-debugging.md` |
|
||||
| Rule | Triggers on |
|
||||
|---|---|
|
||||
| `.agents/rules/cesium-rendering.md` | `src/core/globe/**`, `src/plugins/**`, `packages/wwv-plugin-*/src/**` |
|
||||
| `.agents/rules/state-management.md` | `src/core/state/**`, `src/components/**` |
|
||||
| `.agents/rules/plugin-architecture.md` | `src/core/plugins/**`, `packages/wwv-plugin-*/src/**`, `local-plugins/**` |
|
||||
| `.agents/rules/marketplace-architecture.md` | `src/lib/marketplace/**`, `src/app/api/marketplace/**` |
|
||||
| `.agents/rules/cloud-auth-architecture.md` | `src/lib/auth*`, `src/app/api/auth/**`, `src/core/auth.ts` |
|
||||
| `.agents/rules/database-migrations.md` | `prisma/**` |
|
||||
| `.agents/rules/monorepo-workflow.md` | `packages/**`, `pnpm-workspace.yaml`, `local-plugins/**` |
|
||||
| `.agents/rules/data-engine-architecture.md` | `packages/**`, `local-seeders/**`, `docker-compose.yml` |
|
||||
| `.agents/rules/deployment-and-testing.md` | `Dockerfile`, `docker-compose.yml`, `.github/**`, `next.config.ts` |
|
||||
| `.agents/rules/e2e-testing.md` | `tests/**`, `public/e2e-fixtures/**`, `playwright.config.ts` |
|
||||
|
||||
---
|
||||
|
||||
## 13. Slash Commands / Workflows
|
||||
## 9. On-Demand Context (read explicitly when needed)
|
||||
|
||||
Invoke by name. Read the skill/workflow file and follow its steps.
|
||||
See `.agents/context/INDEX.md` for the full navigation table. Key files:
|
||||
|
||||
| When to read | File |
|
||||
|---|---|
|
||||
| Product vision, business model, Edition system | `.agents/context/platform-architecture.md` |
|
||||
| Finding files, repo layout | `.agents/context/directory-structure.md` |
|
||||
| Routing fix to correct repository | `.agents/context/ecosystem-repositories.md` |
|
||||
| Next.js, data pipeline, Redis, DB schema | `.agents/context/application-architecture.md` |
|
||||
| Debugging plugin data, namespace collisions | `.agents/context/troubleshooting-and-debugging.md` |
|
||||
| SSH, Coolify MCP | `.agents/context/server-management.md` |
|
||||
| Coding principles, Definition of Done | `.agents/context/coding-principles.md` |
|
||||
| `.env` variables and secrets | `.agents/context/environment-config.md` |
|
||||
|
||||
---
|
||||
|
||||
## 10. Slash Commands
|
||||
|
||||
| Command | Description | File |
|
||||
|---|---|---|
|
||||
| `/commit` | **Required before every commit** — bump semver + conventional commit | `.agents/skills/commit/SKILL.md` |
|
||||
| `/remember` | Save a lesson, constraint, or fact into `.agents/` permanent memory | `.agents/skills/remember/SKILL.md` |
|
||||
| `/remember` | Save a lesson or fact into permanent memory | `.agents/skills/remember/SKILL.md` |
|
||||
| `/pr-review` | 6-role comprehensive pull request review | `.agents/skills/pr-review/SKILL.md` |
|
||||
| `/update-context` | Sync `.agents/context/` with current project state | Global skill |
|
||||
| `/local-dev` | Check, start, and troubleshoot local dev environment | `.agents/workflows/local-dev.md` |
|
||||
| `/local-dev` | Check, start, troubleshoot local dev environment | `.agents/workflows/local-dev.md` |
|
||||
| `/data-engine-cli` | Use the wwv-data-engine CLI wrapper | `.agents/workflows/data-engine-cli.md` |
|
||||
| `/debugging-coolify` | Troubleshoot deployed apps on Coolify via MCP/SSH | `.agents/workflows/debugging-coolify.md` |
|
||||
| `/five` | Five Whys root cause analysis | `.agents/workflows/five.md` |
|
||||
| `/stitch-to-nextjs` | Generate UI with Stitch MCP, port into Next.js | `.agents/workflows/stitch-to-nextjs.md` |
|
||||
| `/bing-news-hydration` | Hydrate event attributes with Bing RSS news | `.agents/workflows/bing-news-hydration.md` |
|
||||
| `/generate-user-roadmap` | Generate updated user-facing roadmap | `.agents/workflows/generate-user-roadmap.md` |
|
||||
|
||||
---
|
||||
|
||||
## 14. Agent Skills Reference
|
||||
|
||||
Refer to these skill documents for specialized tasks:
|
||||
|
||||
### Project Skills (`.agents/skills/`)
|
||||
## 11. Agent Skills Reference
|
||||
|
||||
| Skill | When to Use |
|
||||
|---|---|
|
||||
| `worldwideview-plugin-creation` | **Use when creating any plugin** — strict architectural checklist |
|
||||
| `plugin-creation-master-guide.md` | Decision matrix for choosing plugin architecture |
|
||||
| `osm-static-plugin-creation.md` | Creating static GeoJSON plugins from OpenStreetMap |
|
||||
| `microservice-plugin-creation.md` | Legacy guide for standalone Fastify microservices |
|
||||
| `database-operations.md` | Prisma schema changes, migrations, database queries |
|
||||
| `database-incident-recovery-procedures.md` | Authoritative protocol for safely restoring a broken production database |
|
||||
| `index-documentation.md` | Maintaining project documentation index |
|
||||
| `context7` | Fetch up-to-date library docs via Context7 API |
|
||||
| `cesium-context7` | CesiumJS-specific documentation lookup |
|
||||
| `database-incident-recovery-procedures.md` | Safely restoring a broken production database |
|
||||
|
||||
### Global Skills
|
||||
|
||||
52 skills are available across all projects. See `.agents/global-skills-index.md` for the full list and invocation paths.
|
||||
52 global skills available. See `.agents/global-skills-index.md`.
|
||||
|
||||
---
|
||||
|
||||
## 15. Pull Request & Commit Guidelines
|
||||
## 12. 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.
|
||||
- **Git Worktrees**: We use [Worktrunk](https://github.com/max-sixty/worktrunk) to manage parallel branches and avoid relative path breakage in the monorepo. Use `git-wt switch --create <branch>` to provision isolated sibling worktrees automatically configured with `.env` files and `pnpm install`. Use `git-wt remove` to clean up.
|
||||
- **Commit format**: Conventional Commits (`feat:`, `fix:`, `refactor:`, `perf:`). Use `/commit` workflow.
|
||||
- **Required checks**: `pnpm test` and `pnpm build` must pass before merge.
|
||||
- **Review**: Use `/pr-review` for comprehensive multi-role review.
|
||||
- **Worktrees**: Use `git-wt switch --create <branch>` and `git-wt remove` (never `rm -rf` a worktree — orphans the PostgreSQL Docker volume).
|
||||
|
||||
---
|
||||
|
||||
## 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`.
|
||||
|
||||
## 17. Coding Principles
|
||||
|
||||
You are about to write or modify code. **Read this file first.** It exists to prevent the failure mode where every fix makes the next harder — the kind of accumulated coupling and band-aid-on-band-aid that turns a clean codebase into a fragile one over months. This file is the constitution that keeps that from happening.
|
||||
|
||||
### The hard rule
|
||||
## Hard Rule
|
||||
|
||||
> **Always interface-based, extensible, composable, modular. Never band-aids on band-aids.**
|
||||
|
||||
If you find yourself adding a flag, an `if`-check, or a special case to make a problem go away, you are probably band-aiding. Stop and find the seam where the abstraction broke. Fix it there.
|
||||
|
||||
### Core principles
|
||||
|
||||
#### 1. Interfaces before implementations
|
||||
|
||||
Define the contract first. The contract is what other components depend on; the implementation is replaceable. Public functions accept the interface, not the concrete type.
|
||||
|
||||
```ts
|
||||
// Yes
|
||||
function attachSource(source: DataSource) { ... }
|
||||
|
||||
// No
|
||||
function attachPostgresSource(pg: PostgresInstance) { ... }
|
||||
```
|
||||
|
||||
When a pattern repeats across two modules, refactor it into an interface immediately. Don't wait for the third copy to "earn" the abstraction — by then the costs have compounded.
|
||||
|
||||
#### 2. Loose coupling through explicit contracts
|
||||
|
||||
Components communicate through well-defined contracts: typed function signatures, events on a bus, message queues, or capability registries. Pick the form that fits, but pick *one* and make it the only path.
|
||||
|
||||
Components do **not** communicate through:
|
||||
|
||||
- Direct imports of each other's internal modules
|
||||
- Shared mutable state outside the contract
|
||||
- Synchronous request/response when async fits the actual data flow
|
||||
- "Just this once" backdoors that bypass the contract
|
||||
|
||||
If you're tempted to write `import { internalThing } from '../other-module/internal'`, you are doing it wrong. If the symbol you need isn't part of the other module's public contract, either it should be — propose adding it — or you're solving the problem in the wrong place.
|
||||
|
||||
#### 3. Domain boundaries are sacred
|
||||
|
||||
Each domain (module, service, bounded context, plugin) owns its own state and its own surface. Cross-domain access is **explicit, gated, and audited** — never a shortcut.
|
||||
|
||||
Forbidden:
|
||||
- Reading another domain's storage directly
|
||||
- Calling another domain's private functions
|
||||
- Hardcoded `if (tenant === 'X')` or `if (mode === 'special')` branches in shared code
|
||||
|
||||
Allowed:
|
||||
- A documented capability or API on the other domain that you call
|
||||
- A configuration field on the relevant record that drives the strategy
|
||||
- Cross-domain access gated by explicit policy (default **deny**, opt-in per case), with the access itself logged
|
||||
|
||||
The rule of thumb: if removing a domain would require code archaeology in three other domains to figure out what depends on its internals, the boundary has already been violated. Treat that as a bug.
|
||||
|
||||
#### 4. Don't bend your architecture to fit a dependency
|
||||
|
||||
When you bring in a library or framework, use it where it fits cleanly; build natively where it doesn't.
|
||||
|
||||
Let the dependency handle (don't reinvent):
|
||||
- The thing it's specifically good at, in the shape it expects
|
||||
|
||||
Your code owns (the dependency can't represent):
|
||||
- Anything that's specifically your domain
|
||||
- Anything that requires identity, lifecycle, or invariants the dependency doesn't model
|
||||
- The integration seams between the dependency and your domain
|
||||
|
||||
If you find yourself bending your design to fit a library convenience, stop. Either the library has a hook for what you need, or you build it natively. Don't compromise architecture for the convenience of pulling in someone else's defaults.
|
||||
|
||||
#### 5. Data lifetimes are deliberate, not incidental
|
||||
|
||||
Different data has different lifetimes. Get this wrong and you'll either retain garbage forever or delete things users care about. Common categories:
|
||||
|
||||
- **Operational telemetry** (logs, metrics, internal events) — short rolling window. Useful for crash recovery and immediate investigation; not useful enough to keep forever.
|
||||
- **User content** (messages, documents, records the user created or that represent their lived experience with the system) — **permanent unless the user explicitly deletes it.** Never pruned by a sweep, never deleted by a retention policy authored for telemetry.
|
||||
- **Resumable session state** — bounded window appropriate to the use case; archived (state flag flipped) rather than deleted.
|
||||
|
||||
Name each category in your codebase. Write the retention policy for each one separately. Never propose a sweep that crosses categories — "delete events older than 30 days" is fine if events are telemetry; the same policy applied to user content is data loss masquerading as housekeeping. If storage pressure ever becomes real for content, introduce cold-tiered storage, not deletion.
|
||||
|
||||
#### 6. Optional features must be truly removable
|
||||
|
||||
Every optional feature (plugin, extension, integration, side module) declares its surface explicitly and communicates through the same contracts as everything else. No optional feature reaches into another's internals.
|
||||
|
||||
Test for whether something is core vs. optional: **if removing this feature should break the system, it's core. Otherwise it's optional, and it should be removable without leaving residue.**
|
||||
|
||||
If you can't delete an "optional" module's directory and have the system keep running, it isn't optional. Either fix the coupling or move it into core honestly.
|
||||
|
||||
#### 7. Put code where it belongs
|
||||
|
||||
When a feature spans layers (a trigger lives here, the action lives there, the data model lives somewhere else), resist the urge to fold it all into one place "for convenience." The feature lives in three places because each piece belongs to a different domain. Routing across them is the job — not collapsing them.
|
||||
|
||||
The general rule: if a feature needs to read/write durable state, it's a tool/extension on top of the layer that owns that state; if it's "the system should know about this concept," it's a configuration or contract change. Often it's both, with a thin handler that wires them together. That thin handler is fine — it's load-bearing — but it doesn't justify smashing the layers together.
|
||||
|
||||
### Antipatterns to refuse
|
||||
|
||||
These are common failure modes that, repeated over time, calcify a codebase. Refuse them when you catch yourself reaching for them.
|
||||
|
||||
| Antipattern | Better answer |
|
||||
|---|---|
|
||||
| Adding a new flag to an existing function instead of extracting a strategy | Extract the strategy interface; existing call sites pass the default strategy |
|
||||
| Patching around a bug at the call site | Find the seam where the abstraction broke; fix it there |
|
||||
| Direct database access from a feature module | Go through the layer that owns the data; if no surface exists, propose one |
|
||||
| Hardcoded paths, model names, IDs, environment specifics in business logic | Configuration; or look up via registry |
|
||||
| `if (tenant === 'X') { ... }` in shared code | Strategy on the record, or a per-tenant config field |
|
||||
| Inheriting one layer's concerns into another (or vice versa) | Cross the boundary through the documented contract |
|
||||
| "It works for now" — inline coupling between layers | If the layers are real, draw the contract; if they're not, merge them honestly |
|
||||
| Adding a defensive `try/catch` to swallow an error | Find why the error happens; gate cleanly at the right boundary |
|
||||
| Writing a comment to explain what code does | Rename and refactor so the code reads itself |
|
||||
| Copying a snippet from one module into another "to avoid the dependency" | Either it belongs in a shared module, or the duplicate will drift — pick |
|
||||
|
||||
### Debugging discipline
|
||||
|
||||
When something breaks:
|
||||
|
||||
1. **Reproduce it.** Don't trust intuition about what's failing.
|
||||
2. **Find the seam.** Where did the abstraction break? Which contract is being violated, and by whom?
|
||||
3. **Fix at the seam.** Not at the call site. Not at the consumer. At the boundary that's wrong.
|
||||
4. **If you can't find the seam, surface it.** Tell the user explicitly: "this is a design gap; the right fix needs an architectural decision, not a patch." Do not paper over.
|
||||
|
||||
If a fix doesn't work, **don't add another guard on top.** Find the real seam and gate cleanly. Stacked defensive layers are how clean codebases become unmaintainable.
|
||||
|
||||
### Lifecycle invariants and state-changing operations
|
||||
|
||||
Most recurring bugs cluster around the same shape: an operation crosses lifecycle state without checking, and the result is silent corruption, lost data, or orphan rows. The recipe that prevents recurrences:
|
||||
|
||||
1. **Name the invariant.** "Closed sessions don't accept work." "Scoped grants need a scope id." "Subscriptions past retention can't deliver swept events." Write it down before reaching for code.
|
||||
2. **Throw a typed error at the seam.** The single function that crosses the invariant refuses the bad case with a typed, named error — not a boolean return, not a silent skip, not a generic `Error`.
|
||||
3. **Pre-check at every call site that mutates *before* reaching the seam.** If the seam check fires after `store.append()`, you've left an orphan row. The pre-check is hygiene; the seam check is correctness — both are required. When the same pre-check appears at a second call site, extract a helper.
|
||||
4. **Validate, then mutate — never the reverse.** Within a single function, resolve all inputs that could fail (key derivation, lookups, permission checks) before touching durable state. A validation throw should leave nothing half-applied. If you can't separate validation from mutation, the function is doing two jobs.
|
||||
5. **A documented unsafe API is still unsafe.** A docstring that says "don't use this when X" is a foot-gun, not a warranty disclaimer. Either make the API safe in case X (drain, throw, refuse) or remove it.
|
||||
|
||||
If you're tempted to skip step 3 because "the seam check covers it," check whether the call site writes anything before reaching the seam. If yes, you need the pre-check.
|
||||
|
||||
### Definition of done — checklist for adding or updating a function
|
||||
|
||||
Every code change must satisfy the relevant checklist before merge. Refusal triggers below mean **stop and surface to the user** — do not ship a half-met checklist.
|
||||
|
||||
#### Adding a new function
|
||||
|
||||
All must be true:
|
||||
|
||||
- [ ] Belongs in this module (not somewhere else)
|
||||
- [ ] Fulfills an existing interface, OR a new interface is added with it (and reasons documented in a spec doc / ADR)
|
||||
- [ ] Has a doc-comment header (purpose + params + returns + thrown errors if relevant)
|
||||
- [ ] Has at least one test that targets the contract (not implementation details)
|
||||
- [ ] Test passes locally and in CI
|
||||
- [ ] Doesn't introduce direct cross-module imports of internals — communication through public contracts only
|
||||
- [ ] Doesn't touch storage owned by another component — route through that component's surface
|
||||
- [ ] Matches the spec doc's contract for this component (if no spec covers it, update the spec first)
|
||||
- [ ] Name is clear enough that the header comment is a summary, not an explanation
|
||||
|
||||
#### Updating an existing function
|
||||
|
||||
All must be true:
|
||||
|
||||
- [ ] Reason for change is clear (bug fix / new requirement / refactor / spec change)
|
||||
- [ ] Doc-comment still accurate after change (update if not)
|
||||
- [ ] Existing tests cover the new behavior (add new tests if not)
|
||||
- [ ] Build is green (all tests passing)
|
||||
- [ ] If this changes the contract: spec doc updated AND an ADR added if the change is load-bearing
|
||||
- [ ] Fix is at the seam, not at the symptom (no band-aid patches)
|
||||
- [ ] No new flags or special cases added in lieu of strategy extraction
|
||||
|
||||
#### Refusal triggers (any one means stop)
|
||||
|
||||
- Adding `if (tenant === 'X')` to shared code → use per-tenant config instead
|
||||
- Adding a flag to make a problem go away → extract the abstraction the flag implies
|
||||
- Direct DB or filesystem access from a feature module → route through the owning component
|
||||
- `try`/`catch` swallowing an error → find why the error happens, gate cleanly
|
||||
- Test omitted because "it's trivial" → no
|
||||
- Function-header skipped because "it's obvious" → no
|
||||
- "Just add another guard here" when a guard didn't work → find the real seam
|
||||
- Patch shipped to "unblock the build" without root-cause fix → no, surface the design gap
|
||||
|
||||
If any criterion isn't met, stop. Surface to the user as a design question. Don't paper over.
|
||||
|
||||
### Code-style minimums
|
||||
|
||||
#### Comments
|
||||
|
||||
**Every function gets a doc-comment header** in your language's idiomatic format (TSDoc, JSDoc, Python docstrings, Rust `///`, Javadoc, etc.). Not optional. Long-running codebases get re-read after gaps; function-header docs are how re-onboarding stays cheap.
|
||||
|
||||
Required content:
|
||||
|
||||
- One-line summary at a contract level (what the function guarantees, not what the code does line-by-line)
|
||||
- Each parameter and what it represents
|
||||
- Return value
|
||||
- Thrown errors / failure conditions if relevant
|
||||
- Example usage when the call shape is non-obvious
|
||||
|
||||
Apply this to public, internal, exported, and private functions. Apply to methods on classes too.
|
||||
|
||||
**Inline comments inside function bodies** still follow the standard rule: only for non-obvious WHY (hidden constraints, workarounds, surprising behavior, references to bug reports). Don't comment WHAT the code does — well-named identifiers and the function-header doc cover that.
|
||||
|
||||
#### Tests
|
||||
|
||||
**Every function ships with at least one test. Tests passing is a build requirement.**
|
||||
|
||||
- Tests target the contract (function signature + documented behavior + invariants), not implementation details. Refactoring should not break tests; behavior changes should.
|
||||
- A new implementation of an interface must pass the same contract test suite (write tests against the interface, not against a specific implementation).
|
||||
- Test names describe the case being verified, not the function: `it('refuses resume after archival window expires')` not `it('resumeSession')`.
|
||||
- For storage code: tests use a real (temporary) instance of the storage layer, created and torn down per test or per suite. Don't mock the storage engine — you're testing the wrong thing if you do.
|
||||
- For integration code that depends on an external library's hooks: contract tests against that library's surface so a dependency bump catches behavior changes.
|
||||
- Build pipeline (CI or local) runs all tests; non-zero exit = build fails. There is no "build succeeded but tests failed" state.
|
||||
|
||||
#### Logging
|
||||
|
||||
**Every new feature with a non-happy-path ships with a log line at each rare branch.** Use a structured logger with module-scoped child loggers. The log file is where "something's not working" turns into "what actually happened."
|
||||
|
||||
Level guidance:
|
||||
|
||||
- **info** — expected-but-noteworthy edges: a UI race that hits a closed resource, a permission bypass for a privileged principal. Correct behavior an operator might want to confirm fired.
|
||||
- **warn** — should be rare and worth investigating: race past a pre-check, lost events past retention, programmer/operator errors (calling a method after stop, a key that should have resolved didn't).
|
||||
- **error** — actual failures the operator must respond to: handler crashes, dispatch loop crashes, integration failures.
|
||||
- **debug** — high-volume internal state changes; always pair with a `module` field so it can be filtered.
|
||||
|
||||
Pass structured fields, not interpolated strings — fields are what makes a log queryable:
|
||||
|
||||
```ts
|
||||
// Yes
|
||||
logger.warn({ session_id, state }, "rejected append against non-live session");
|
||||
|
||||
// No
|
||||
logger.warn(`session ${session_id} (${state}) rejected append`);
|
||||
```
|
||||
|
||||
If you add a new typed error or a new event topic, also log it. The typed error tells the immediate caller; the event tells subscribers; the log tells the operator. The three are independent surfaces for the same fact, and all three are needed — events don't show up in the log, logs don't show up on the bus, errors don't survive the catch.
|
||||
|
||||
#### Structure
|
||||
|
||||
- Keep modules small. If a file is over ~500 lines, ask whether it has more than one responsibility.
|
||||
- Prefer explicit composition (caller wires things together) over implicit dependency-injection magic.
|
||||
- One public concept per module. If a file exports both `Foo` and `unrelatedHelperUsedNowhereElse`, the helper has the wrong home.
|
||||
|
||||
#### Dependencies
|
||||
|
||||
**Always check the registry for the current version before adding or updating a dependency.** Don't pick versions from memory.
|
||||
|
||||
The simple test: did you actually run `<package-manager> view <pkg> version` (or its equivalent) before pinning? If not, you're guessing — and the guess is almost always behind, sometimes by a major version with active deprecation.
|
||||
|
||||
Why this matters:
|
||||
|
||||
- **Long-running codebases.** Stale dependency anchors compound. A v3 you picked because that's what was on your mind will still be v3 a year later, and the v4 migration gets harder every month it waits.
|
||||
- **Active deprecations are real.** Common libraries are mid-deprecation cycles for older majors. Pinning to a soon-deprecated version on day one means the eventual upgrade is forced rather than chosen.
|
||||
- **"Latest" doesn't mean "use without thinking."** Read the changelog for breaking changes; decide whether to take them now or pin behind explicitly. But the *default* posture should be: pick latest, and justify in writing if pinning behind.
|
||||
|
||||
If you must pin behind latest, leave a comment in the manifest (or a CHANGELOG note) explaining why — a known incompatibility with another dep, an in-progress migration, a tested-and-rejected major bump. *"I haven't checked"* is not an acceptable reason.
|
||||
|
||||
Apply to: adding a new dep, updating an existing one, scaffolding a new package. *Not* required for routine no-op installs that don't touch versions.
|
||||
|
||||
#### Doc-vs-spec discipline
|
||||
|
||||
Specification documents (the deeper ones that describe how a component must behave) are **functional specifications**, not narrative essays. The discipline:
|
||||
|
||||
- **Concrete data structures** — type definitions, schemas, DDL, JSON examples
|
||||
- **Concrete function signatures** — input/output types, error types
|
||||
- **Concrete event/message payloads** — name + schema + example
|
||||
- **Concrete API signatures** — input/output schemas, side effects, permission requirements
|
||||
- **Flow pseudocode** — when orchestration is non-obvious
|
||||
- **Invariants** — explicitly listed: "after X happens, Y is always true"
|
||||
- **Failure modes** — enumerated: "if X fails, the system does Y"
|
||||
- **Acceptance tests** — statements another engineer can implement: "given input X, output Y"
|
||||
|
||||
Avoid in spec docs:
|
||||
- Long prose explaining motivation (that goes in ADRs / decision records)
|
||||
- Discussion of alternatives considered (also ADRs)
|
||||
- Background context (README handles this)
|
||||
- Marketing/aspirational tone
|
||||
|
||||
Spec docs are for implementation. Read one and you should know what to build.
|
||||
|
||||
### When in doubt
|
||||
|
||||
Ask the human user. Specifically:
|
||||
|
||||
- "I don't see a clean seam for this; the options I see are A or B. Which fits the architecture you have in mind?"
|
||||
- "This requires a new contract / capability / interface. Should I draft it before implementing?"
|
||||
- "I'm about to add a special case here; that smells like a missing abstraction. Do you want me to extract the abstraction or note the smell and defer?"
|
||||
|
||||
Don't ship band-aids and ask forgiveness later. The user has explicitly said: prevent that pattern.
|
||||
Read `.agents/context/coding-principles.md` before any non-trivial code change.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Design System: WorldWideView
|
||||
**Project ID:** local-worldwideview-app
|
||||
|
||||
## 1. Visual Theme & Atmosphere
|
||||
The WorldWideView platform employs an **"Airy, High-Tech, and Geospatial-Focused"** aesthetic. The design philosophy centers around "Glassmorphism Pro Max"—keeping the user's primary focus on the rich, underlying 3D globe visualization while providing highly legible, structured, and floating Heads-Up Display (HUD) elements.
|
||||
|
||||
The mood is utilitarian yet premium, heavily relying on dense background blurring, delicate inner borders, and vibrant glowing accent states to establish depth, interactivity, and a sense of "live" intelligence.
|
||||
|
||||
## 2. Color Palette & Roles
|
||||
WorldWideView operates using a multi-theme architecture (Default Dark, Pure Black, Legacy OLED, and Light). The core semantic roles for the **Default Dark Theme** are outlined below:
|
||||
|
||||
* **Obsidian Canvas** (`#171717`) - `--bg-primary`: The foundational layer behind the application shell and globe.
|
||||
* **Translucent Slate Glass** (`rgba(38, 38, 38, 0.85)`) - `--bg-glass`: The primary background for floating HUD panels, sidebars, and dialogs. Provides a frosted glass effect that allows the map to bleed through.
|
||||
* **Frost White** (`#ffffff`) - `--text-primary`: Primary typography for headers, active states, and high-emphasis data.
|
||||
* **Muted Ash** (`#a3a3a3`) - `--text-muted`: Secondary typography used for labels, subtitles, and inactive states to establish visual hierarchy.
|
||||
* **Gossamer Edge** (`rgba(255, 255, 255, 0.15)`) - `--border-subtle`: Defines the subtle, crisp edges of glass panels, dividers, and default button states.
|
||||
* **Starlight Cyan** (`#ffffff` / *Legacy:* `#22d3ee`) - `--accent-cyan`: Used for primary actions, active tabs, timeline scrubbers, and play buttons. Often paired with a diffuse glow (`0 0 24px rgba(255, 255, 255, 0.15)`) for emphasis and technical flair.
|
||||
* **Telemetry Green** (`#22c55e`) - `--accent-green`: Used for live status indicators, pulsing connectivity badges, and positive data deltas.
|
||||
* **Warning Amber** (`#f59e0b`) - `--accent-amber`: Used for warnings, "Alpha" badges, or unavailable data states.
|
||||
|
||||
## 3. Typography Rules
|
||||
The system uses a dual-font strategy to balance clean user interfaces with technical precision.
|
||||
|
||||
* **UI Font (Inter):** Used for all general interface elements, headers, and buttons.
|
||||
* Headers and brand elements use a bold `600/700` weight with tight letter-spacing (`-0.02em`) for a sleek, modern feel.
|
||||
* Section titles, keys, and subtitles use a very small size (`11px`), a medium weight, uppercase transformation, and wide letter-spacing (`0.05em` to `0.1em`) to mimic aerospace or military HUD interfaces.
|
||||
* **Monospace Font (JetBrains Mono):** Used strictly for data values, coordinates, telemetry, and exact timestamps (`11px` to `12px`). Ensures tabular alignment, clear distinction between similar characters (e.g., 0 and O), and technical precision.
|
||||
|
||||
## 4. Component Stylings
|
||||
|
||||
* **Glass Panels (Cards/Containers):**
|
||||
* **Shape:** Generously rounded corners (`16px` / `var(--radius-lg)`).
|
||||
* **Surface:** Dense frosted background blur (`24px`).
|
||||
* **Depth:** Elevated significantly above the map using a dual-layered drop shadow (`0 8px 32px rgba(0, 0, 0, 0.4)` combined with `0 2px 8px rgba(0, 0, 0, 0.2)`). Features a crisp inner border (`inset 0 1px 1px rgba(255, 255, 255, 0.1)`) to simulate physical glass thickness.
|
||||
* **Buttons:**
|
||||
* **Shape:** Subtly rounded corners (`12px` / `var(--radius-md)`) with a standard height of `36px`.
|
||||
* **Surface:** Translucent glass background with a subtle border.
|
||||
* **Behavior:** Smooth, spring-based transitions. On hover, the background brightens, the element scales up/translates slightly (`translateY(-1px)`), and primary buttons emit a vivid neon glow. On click (active), buttons physically depress (`scale(0.97)`).
|
||||
* **Tabs & Selectors:**
|
||||
* **Shape:** Softly rounded (`8px` / `var(--radius-sm)`).
|
||||
* **Surface:** Clean, flat, and transparent by default.
|
||||
* **Behavior:** Transitions to a soft glass hover or active state. Active tabs use a highlighted background (`rgba(var(--accent-rgb), 0.1)`) and bright cyan text with increased font weight.
|
||||
* **Timeline Scrubber:**
|
||||
* **Track:** Slender `4px` tall track with softly rounded edges.
|
||||
* **Handle:** A circular `14px` handle that emits a cyan glow, expanding dynamically on hover (`scale(1.2)`).
|
||||
|
||||
## 5. Layout Principles
|
||||
* **Absolute Overlays:** The UI does not push the map; instead, it floats over a full-screen, `z-index: 0` globe canvas. Elements are anchored to the edges (Header to top, Sidebar to sides, Timeline to bottom).
|
||||
* **Strict 4/8dp Rhythm:** All spacing adheres to an 8-point grid base (`4px`, `8px`, `12px`, `16px`, `24px`, `32px`, `48px`).
|
||||
* **Dynamic Containment:** Sidebars and bottom panels push each other dynamically to prevent overlap and optimize map visibility (e.g., when the bottom panel opens, sidebars slide upward).
|
||||
* **Whitespace & Density:** Panels use a dense `16px` padding globally to maximize the amount of intelligence data visible while maintaining clear breathing room between individual data rows. Scrollable areas hide scrollbars until hovered to maintain the clean glass aesthetic.
|
||||
+4
-2
@@ -42,8 +42,8 @@ services:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
POSTGRES_DB: worldwideview
|
||||
expose:
|
||||
- "5432"
|
||||
ports:
|
||||
- "${WWV_DB_PORT:-5432}:5432"
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
@@ -63,6 +63,8 @@ services:
|
||||
cd /app && node dist/server.js"
|
||||
ports:
|
||||
- "5000:5000"
|
||||
volumes:
|
||||
- ./local-seeders:/app/seeders
|
||||
environment:
|
||||
- PORT=5000
|
||||
- REDIS_URL=redis://wwv-redis:6379
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
# ADR-0002: Source-of-truth for plugin identity and registration
|
||||
|
||||
## Status
|
||||
Accepted
|
||||
|
||||
## Date
|
||||
2026-05-20
|
||||
|
||||
## Context
|
||||
|
||||
Two related problems in the plugin system surfaced in the same period, and both have the same root cause: canonical plugin information was being derived in middleware translation layers (folder names, hard-coded lists) rather than at its proper source. Each problem is fixed by pushing the canonical truth back to its rightful owner and removing the static translation in the middle. Documenting them together makes the shared principle explicit and discourages future regressions of the same shape.
|
||||
|
||||
### Problem 1 — Engine seeder ID derived from folder name
|
||||
|
||||
The WorldWideView local data engine discovers seeders by scanning the filesystem under `/app/seeders`. Historically, the engine assigned each seeder an ID equal to its **folder name** (e.g., the folder `gpsjam/` became plugin ID `"gpsjam"`).
|
||||
|
||||
The frontend, however, identifies plugins by a separate **`id` field** declared in each plugin class (e.g., `"gps-jamming"`). The engine's `/manifest` endpoint listed available plugins using folder-derived IDs, and the frontend's `localEngineHasPlugin(pluginId)` performed an exact string match against that list.
|
||||
|
||||
This created a silent failure mode: six seeders had folder names that did not match their corresponding frontend plugin IDs:
|
||||
|
||||
| Folder name | Frontend plugin `id` |
|
||||
|---|---|
|
||||
| `gpsjam/` | `gps-jamming` |
|
||||
| `sanctions/` | `international-sanctions` |
|
||||
| `wildfires/` | `wildfire` |
|
||||
| `civilUnrest/` | `civil-unrest` |
|
||||
| `conflictEvents/` | `conflict-events` |
|
||||
| `cyberAttacks/` | `cyber-attacks` |
|
||||
|
||||
When `localEngineHasPlugin('gps-jamming')` returned `false` (because the manifest listed `"gpsjam"`), the frontend silently fell through to the production cloud engine, bypassing the local engine entirely. The bug was invisible — no error, just incorrect routing.
|
||||
|
||||
A short-term patch introduced `SEEDER_ID_ALIASES` in `src/core/data/engineManifest.ts` — a frontend translation map from folder names to plugin IDs. This was explicitly a band-aid: it duplicated knowledge in a consumer rather than fixing the contract at the source, and would go stale as new seeders were added.
|
||||
|
||||
The engine's TypeScript source (`seeder-loader.ts`) also had a `toKebabCase()` helper intended to normalize camelCase folder names (e.g., `civilUnrest` → `civil-unrest`), but its compiled `dist/` was stale (the production image had not been rebuilt to include it), and `toKebabCase` alone cannot resolve abbreviation mismatches like `gpsjam` → `gps-jamming`.
|
||||
|
||||
### Problem 2 — Fresh-install plugin set hard-coded
|
||||
|
||||
The marketplace auto-seeder ([src/lib/marketplace/seedDefaultPlugins.ts](../../../src/lib/marketplace/seedDefaultPlugins.ts)) writes a starter set of plugins to the database on first boot so the globe isn't empty on day one. The list of plugins to seed lived in a hard-coded constant `DEFAULT_PLUGIN_IDS` ([src/lib/marketplace/defaultPlugins.ts](../../../src/lib/marketplace/defaultPlugins.ts)).
|
||||
|
||||
Two failure modes followed from the static list:
|
||||
|
||||
1. **Drift**: ten plugins were published to npm under `@worldwideview/*` and verified — surveillance-satellites, military-bases, embassies, seaports, lighthouses, spaceports, iranwarlive, undersea-cables, mineral-mines, nuclear-facilities — but never added to `DEFAULT_PLUGIN_IDS`. Fresh installs missed them silently.
|
||||
2. **Phantom 404s**: two entries in the list (`fortiguard`, `nz-traffic-cameras`) were dev-only sandboxes in `local-plugins/`, never published to npm. Every fresh boot hit `https://marketplace.worldwideview.dev/api/plugins/fortiguard` → 404, logged a warning, and continued. The branch `fix/diagnose-plugins-404` was opened to diagnose those.
|
||||
|
||||
A separate, signed verified-plugins registry already existed at `marketplace.worldwideview.dev/api/registry`, loaded by [registryClient.ts](../../../src/lib/marketplace/registryClient.ts) with Ed25519 verification. It was used for trust-stamping installed plugins but not for selecting which plugins to seed. That registry is the authoritative list of plugins that have been reviewed and verified — exactly the list a starter set should come from.
|
||||
|
||||
### Shared shape
|
||||
|
||||
Both problems wrap the same anti-pattern: a consumer (frontend, seeder) maintains a static translation/list derived from the producer's actual identity (seeder export, npm publication). The translation drifts. The fix in both cases is the same: stop translating in the consumer; let the producer declare the truth and consume it directly.
|
||||
|
||||
## Decisions
|
||||
|
||||
### Decision 1 — The seeder's exported `name` field is the canonical plugin ID
|
||||
|
||||
The engine reads each seeder's `dist/index.mjs` default export's `name` property and uses it as the plugin ID everywhere:
|
||||
|
||||
- `/manifest` endpoint `plugins` array
|
||||
- WebSocket welcome message plugin list
|
||||
- WebSocket data message `pluginId` field
|
||||
- Redis key (`data:<name>:live`)
|
||||
- Scheduler logs
|
||||
|
||||
The folder name is used only as a filesystem fallback if the seeder exports no `name`. The engine logs a warning at startup whenever the kebab-cased folder name differs from the seeder's exported `name`, making drift visible without blocking startup.
|
||||
|
||||
**Contract:** Every seeder MUST export a `name` field that exactly equals the corresponding frontend plugin's `id` field (kebab-case). This is a two-place contract: declare the same ID string in the seeder export and in the frontend plugin class.
|
||||
|
||||
Implementation: `seeder-loader.ts` was updated to set `id = seederConfig.name || toKebabCase(folderName)` instead of `id = toKebabCase(folderName)`. The frontend `SEEDER_ID_ALIASES` map was removed entirely. No translation layer exists between the engine's manifest and the frontend's plugin lookup.
|
||||
|
||||
### Decision 2 — The signed verified registry is the source-of-truth for fresh-install auto-seeding
|
||||
|
||||
The marketplace auto-seeder iterates the set returned by `getVerifiedPluginIds()` (the signed registry) instead of a hard-coded `DEFAULT_PLUGIN_IDS` constant. Publishing a plugin to the verified registry automatically makes it part of the fresh-install starter set on subsequent boots, with no code change.
|
||||
|
||||
The static `DEFAULT_PLUGIN_IDS` list is deleted. There is no fallback list in code — if the registry is unreachable on first attempt, the seeder defers without marking-seeded so the next request retries (the 5-min in-memory cache in `registryClient.ts` bounds the request rate during outages).
|
||||
|
||||
Trust stamping is collapsed: every plugin landed by the seeder is `verified` by definition, so the per-plugin `verified.has(pluginId)` check inside the seeder is dropped — `manifest.trust = "verified"` is set directly.
|
||||
|
||||
**Contract:** A plugin is part of the fresh-install starter set iff it appears in the signed verified-plugins registry. There is no other list to maintain.
|
||||
|
||||
## Shared principle
|
||||
|
||||
> **Canonical plugin truth lives at the source. Reject static translation/lookup layers in the middle.**
|
||||
|
||||
This is the architectural rule both decisions encode. Concrete corollaries for future contributions:
|
||||
|
||||
- Don't introduce a static map in a consumer to compensate for a producer that mis-labels itself. Fix the producer.
|
||||
- Don't introduce a static list in code to enumerate what a registry or filesystem already enumerates. Read from the registry/filesystem.
|
||||
- A translation layer that "just needs an entry added each time we publish a plugin" is a foot-gun — it will silently drift the moment someone forgets.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### For Decision 1
|
||||
|
||||
#### Folder renames (rejected as primary fix)
|
||||
Rename the six mismatched folders to match their frontend plugin IDs (e.g., `gpsjam/` → `gps-jamming/`). This would make the folder name the canonical ID.
|
||||
|
||||
- **Rejected as primary fix** because Windows Docker Desktop holds NTFS volume mount locks on running containers, making renames impossible without a full Docker Desktop shutdown. More importantly, it makes the canonical ID fragile — any accidental folder rename breaks routing silently.
|
||||
- Folder renames remain a cosmetic cleanup option, now that the seeder export is the actual source of truth.
|
||||
|
||||
#### Frontend alias map (`SEEDER_ID_ALIASES`)
|
||||
Maintain a static mapping in `engineManifest.ts` that translates engine-reported IDs to frontend plugin IDs.
|
||||
|
||||
- **Rejected** because it puts translation responsibility on the consumer rather than the producer. Every new seeder with a naming mismatch requires a manual alias entry. The map goes stale silently — no warning if an alias is wrong or missing.
|
||||
|
||||
#### `toKebabCase()` normalization only
|
||||
Apply `toKebabCase()` to folder names in the engine and rely on the convention that folder names encode the plugin ID in camelCase.
|
||||
|
||||
- **Rejected** because `toKebabCase` cannot resolve abbreviation mismatches (`gpsjam` → still `gpsjam`, not `gps-jamming`) or singular/plural differences (`wildfires` → still `wildfires`, not `wildfire`). It only handles camelCase-to-kebab conversion.
|
||||
|
||||
#### Strict validation with engine startup failure
|
||||
Refuse to load any seeder whose folder name doesn't match its exported `name`, blocking startup until inconsistencies are resolved.
|
||||
|
||||
- **Rejected** as too aggressive for a local dev environment. A warning is sufficient — startup continues, mismatches are visible, and the system keeps working.
|
||||
|
||||
### For Decision 2
|
||||
|
||||
#### Add the missing 10 IDs to `DEFAULT_PLUGIN_IDS` (rejected)
|
||||
Extend the static list to include the newly-published plugins.
|
||||
|
||||
- **Rejected** because it ships a fix that resolves the immediate symptom while preserving the underlying drift mechanism. The list would go stale again the next time a plugin is published.
|
||||
|
||||
#### Hybrid: registry as default + static fallback list
|
||||
Read from the registry; fall back to a hard-coded list if the registry is empty/unreachable.
|
||||
|
||||
- **Rejected** because it reintroduces the static list as a permanent shadow source-of-truth. Fallback lists go stale silently. The chosen "defer seeding on empty registry" behavior is safer — fresh installs retry on the next request rather than locking in a stale set.
|
||||
|
||||
#### Delete auto-seeding entirely (rejected)
|
||||
Drop the seeder and let users install everything from the marketplace UI starting from an empty globe.
|
||||
|
||||
- **Rejected** because fresh installs should have something to look at on day one. The user explicitly stated this requirement: "we want the user to have something to get started with."
|
||||
|
||||
## Consequences
|
||||
|
||||
### Easier
|
||||
|
||||
**Decision 1 — engine seeder identity**
|
||||
- Self-documenting identity. Reading any seeder's `src/index.ts` immediately tells you its plugin ID. No external registry to consult.
|
||||
- Filesystem layout is irrelevant. Folders can be named for readability or organized in subdirectories without affecting routing.
|
||||
- No translation layers. The frontend receives the correct ID directly from the manifest; `localEngineHasPlugin()` works with a direct string comparison.
|
||||
- Drift is visible. The engine warns on startup when folder names diverge from exported names, catching mistakes during development rather than silently at runtime.
|
||||
- Adding a new seeder requires only: (1) export `name: '<plugin-id>'` matching the frontend plugin's `id`, (2) no registration step, no alias map entry.
|
||||
|
||||
**Decision 2 — marketplace seeding**
|
||||
- Publishing a plugin to the verified registry is sufficient to add it to the starter set. No code change, no PR to add an ID to a constant.
|
||||
- Phantom 404s are gone. The seeder only queries IDs that exist in the verified registry, which by construction reflects what's actually published.
|
||||
- Trust semantics align. "Verified" and "auto-seeded on fresh install" are now the same condition, not two near-overlapping lists that can drift.
|
||||
- Registry outages no longer brick fresh installs. The deferral semantics ensure the seeder retries instead of marking-seeded with zero rows.
|
||||
|
||||
### Harder
|
||||
|
||||
**Decision 1 — engine seeder identity**
|
||||
- Seeder author bears responsibility. If a seeder exports the wrong `name`, routing fails silently (same failure mode as before, but now localized to the seeder rather than the folder). The startup warning mitigates this.
|
||||
- Contract validation is advisory, not enforced. There is no build-time check that the seeder's `name` matches an actual frontend plugin `id`. A validation script (`scripts/validate-seeder-ids.mjs`) is the recommended mitigation.
|
||||
- Engine image must be kept up to date. The fix lives in `dist/seeder-loader.js` inside the Docker image. If the published `ghcr.io/silvertakana/wwv-data-engine:latest` image is behind the local source, the behavior reverts to folder-name-based IDs. Local changes require `docker cp` injection or an image rebuild until the fix is published.
|
||||
|
||||
**Decision 2 — marketplace seeding**
|
||||
- The verified registry must be kept accurate. A newly-published plugin doesn't auto-seed until it's added to the registry and the registry is re-signed. Operational responsibility shifts from "remember to add the ID to a code constant" to "remember to add the ID to the registry" — a similar discipline, but now at the right layer (the marketplace, not the consumer).
|
||||
- Existing instances are not back-filled. Users whose `Setting` table already has `defaults_seeded=true` will not automatically receive newly-verified plugins; they must install via the marketplace UI. This is by design — re-seeding could reinstall plugins a user explicitly uninstalled.
|
||||
- Dev-only sandboxes (`local-plugins/<name>/`) no longer "tag along" via the default list. `fortiguard` and `nz-traffic-cameras` only reach users once published to npm and added to the verified registry. The local-plugins folder discovery in `/api/marketplace/load` still surfaces them in dev (`NODE_ENV=development` or `WWV_PLUGIN_DEV=true`).
|
||||
+7
-9
@@ -1,7 +1,7 @@
|
||||
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTypeScript from "eslint-config-next/typescript";
|
||||
|
||||
export default [
|
||||
const config = [
|
||||
{
|
||||
ignores: [
|
||||
"node_modules/**",
|
||||
@@ -16,6 +16,8 @@ export default [
|
||||
"local-seeders/**",
|
||||
".agents/**",
|
||||
".claude/**",
|
||||
".gemini/**",
|
||||
"*.cjs",
|
||||
],
|
||||
},
|
||||
...nextCoreWebVitals,
|
||||
@@ -33,20 +35,16 @@ export default [
|
||||
|
||||
// Pre-existing — flagged in the original code review (#96):
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
"no-console": "warn",
|
||||
"no-console": "off",
|
||||
|
||||
// React 19 hook-purity rules from eslint-plugin-react-hooks 7+:
|
||||
"react-hooks/purity": "warn",
|
||||
"react-hooks/refs": "warn",
|
||||
"react-hooks/set-state-in-effect": "warn",
|
||||
"react-hooks/immutability": "warn",
|
||||
"react-hooks/static-components": "warn",
|
||||
|
||||
// (These were previously hallucinated or require extra plugins)
|
||||
// Misc one-offs across the codebase:
|
||||
"react/no-unescaped-entities": "warn",
|
||||
"@typescript-eslint/ban-ts-comment": "warn",
|
||||
"@next/next/no-assign-module-variable": "warn",
|
||||
"prefer-const": "warn",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export default config;
|
||||
@@ -93,6 +93,4 @@ const nextConfig: NextConfig = {
|
||||
},
|
||||
};
|
||||
|
||||
import { withSentryConfig } from "@sentry/nextjs";
|
||||
|
||||
export default nextConfig;
|
||||
+28
-14
@@ -1,14 +1,14 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.11.0",
|
||||
"private": true,
|
||||
"version": "2.16.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
"scripts": {
|
||||
"setup": "node scripts/setup.mjs",
|
||||
"test-worktree": "node scripts/test-worktree.mjs",
|
||||
"clean": "node -e \"const fs=require('fs');fs.rmSync('.next',{recursive:true,force:true})\"",
|
||||
"dev": "concurrently \"pnpm run dev:plugins\" \"next dev\"",
|
||||
"dev": "node scripts/dev.mjs",
|
||||
"dev:all": "concurrently -n \"dev,backends\" -c \"magenta,blue\" \"pnpm dev\" \"pnpm dev:backends\"",
|
||||
"dev:backends": "docker compose --profile engine up wwv-data-engine wwv-redis",
|
||||
"dev:plugins": "node scripts/watch-local-plugins.mjs",
|
||||
@@ -18,9 +18,11 @@
|
||||
"build": "next build --webpack",
|
||||
"start": "next start",
|
||||
"test": "vitest run",
|
||||
"test:e2e": "playwright test",
|
||||
"test:mutate": "stryker run",
|
||||
"lint": "eslint .",
|
||||
"db:reset": "npx prisma migrate reset --force",
|
||||
"db:prune": "node scripts/db-prune.mjs",
|
||||
"generate": "prisma generate"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -29,8 +31,8 @@
|
||||
"@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",
|
||||
"@sentry/nextjs": "^10.53.1",
|
||||
"@supabase/supabase-js": "^2.106.0",
|
||||
"@types/pg": "^8.20.0",
|
||||
"@vercel/analytics": "^1.6.1",
|
||||
"@worldwideview/wwv-plugin-sdk": "workspace:*",
|
||||
@@ -40,25 +42,28 @@
|
||||
"hls.js": "^1.6.16",
|
||||
"insecam-api": "^0.0.3",
|
||||
"jose": "^6.2.3",
|
||||
"lucide-react": "^1.14.0",
|
||||
"lucide-react": "^1.16.0",
|
||||
"next": "16.2.6",
|
||||
"next-auth": "^5.0.0-beta.30",
|
||||
"openid-client": "^6.8.4",
|
||||
"pg": "^8.20.0",
|
||||
"pg": "^8.21.0",
|
||||
"prisma": "^7.8.0",
|
||||
"react": "19.2.6",
|
||||
"react-dom": "19.2.6",
|
||||
"react-player": "^3.4.0",
|
||||
"resium": "1.21.0",
|
||||
"satellite.js": "^7.0.0",
|
||||
"resium": "1.21.1",
|
||||
"satellite.js": "^7.0.1",
|
||||
"stripe": "^22.1.1",
|
||||
"tslib": "^2.8.1",
|
||||
"undici": "^8.2.0",
|
||||
"ws": "^8.14.2",
|
||||
"undici": "^8.3.0",
|
||||
"ws": "^8.20.1",
|
||||
"zod": "^4.4.3",
|
||||
"zustand": "^5.0.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^2.1.0",
|
||||
"@eslint/eslintrc": "^3.3.5",
|
||||
"@playwright/test": "^1.60.0",
|
||||
"@stryker-mutator/core": "^9.6.1",
|
||||
"@stryker-mutator/vitest-runner": "^9.6.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
@@ -69,18 +74,27 @@
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@typescript-eslint/eslint-plugin": "^8.59.4",
|
||||
"@typescript-eslint/parser": "^8.59.4",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "4.1.6",
|
||||
"concurrently": "^9.2.1",
|
||||
"copy-webpack-plugin": "^14.0.0",
|
||||
"eslint": "^9",
|
||||
"eslint-config-airbnb": "^19.0.4",
|
||||
"eslint-config-airbnb-typescript": "^18.0.0",
|
||||
"eslint-config-next": "^16.2.6",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
"eslint-plugin-jsx-a11y": "^6.10.2",
|
||||
"eslint-plugin-react": "^7.37.5",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"fast-check": "^4.8.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tsx": "^4.21.0",
|
||||
"tree-kill": "^1.2.2",
|
||||
"tsx": "^4.22.2",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.12",
|
||||
"vite": "^8.0.13",
|
||||
"vitest": "^4.1.6"
|
||||
},
|
||||
"pnpm": {
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
"clean": "rm -rf dist"
|
||||
},
|
||||
"dependencies": {
|
||||
"commander": "^12.1.0",
|
||||
"commander": "^14.0.3",
|
||||
"prompts": "^2.4.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
"@types/node": "^25.9.1",
|
||||
"@types/prompts": "^2.4.9",
|
||||
"typescript": "^5.0.0"
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
import { Command } from 'commander';
|
||||
import { saveConfig } from '../utils/config.js';
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
import { Command } from 'commander';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
import { Command } from 'commander';
|
||||
import { execSync } from 'child_process';
|
||||
import path from 'path';
|
||||
@@ -50,7 +51,7 @@ export const publishCommand = new Command('publish')
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let originalName = pkgContent.name;
|
||||
const originalName = pkgContent.name;
|
||||
let publishedName = originalName;
|
||||
|
||||
// Determine organization
|
||||
@@ -66,7 +67,7 @@ export const publishCommand = new Command('publish')
|
||||
try {
|
||||
const whoami = execSync('npm whoami', { stdio: 'pipe' }).toString().trim();
|
||||
targetOrg = whoami;
|
||||
} catch (e) {
|
||||
} catch (_e) {
|
||||
// Not logged in or errored, ignore
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-lib-aviation",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.2",
|
||||
"description": "Shared abstract base classes for WorldWideView aviation plugins (commercial, military, specialized)",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -69,7 +69,6 @@ export abstract class BaseAviationPlugin implements WorldPlugin {
|
||||
return {
|
||||
type: "model",
|
||||
iconUrl: this.iconUrl,
|
||||
size: isAirborne ? 8 : 5,
|
||||
modelUrl: this.modelUrl,
|
||||
modelScale: 2.56,
|
||||
modelMinPixelSize: 16,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-lib-incidents",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.2",
|
||||
"description": "Shared abstract base classes for WorldWideView incident plugins (earthquakes, wildfires, conflicts)",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -75,9 +75,7 @@ export abstract class BaseIncidentPlugin implements WorldPlugin {
|
||||
type: "billboard",
|
||||
iconUrl: this.iconUrls[cacheKey],
|
||||
color,
|
||||
size,
|
||||
outlineColor: "#000000",
|
||||
outlineWidth: 1,
|
||||
iconScale: size / 30,
|
||||
labelText: entity.label || undefined,
|
||||
labelFont: "11px JetBrains Mono, monospace" // Adds optional label standard
|
||||
};
|
||||
|
||||
+55
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file index.ts
|
||||
* @description Core SDK for WorldWideView plugin development.
|
||||
* Defines the foundational types, interfaces, and utilities required
|
||||
* to build data seeders, visualizers, and UI extensions.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
import type { ComponentType } from "react";
|
||||
/** Standard SVG icon size (px) used by createSvgIconUrl when no size is given. */
|
||||
export declare const DEFAULT_ICON_SIZE = 32;
|
||||
@@ -24,16 +31,30 @@ export interface TimeRange {
|
||||
end: Date;
|
||||
}
|
||||
export type TimeWindow = "1h" | "6h" | "24h" | "48h" | "7d";
|
||||
/**
|
||||
* @interface GeoEntity
|
||||
* @description The primary data primitive representing a geospatial object.
|
||||
*/
|
||||
export interface GeoEntity {
|
||||
/** Globally unique identifier for this specific entity instance. */
|
||||
id: string;
|
||||
/** The ID of the plugin that owns this entity. */
|
||||
pluginId: string;
|
||||
/** WGS84 Latitude. */
|
||||
latitude: number;
|
||||
/** WGS84 Longitude. */
|
||||
longitude: number;
|
||||
/** Altitude in meters above ellipsoid (optional). */
|
||||
altitude?: number;
|
||||
/** Heading/Rotation in degrees (optional). */
|
||||
heading?: number;
|
||||
/** Speed in knots or meters/sec depending on domain (optional). */
|
||||
speed?: number;
|
||||
/** The moment this data was captured. */
|
||||
timestamp: Date;
|
||||
/** Short display string for labels. */
|
||||
label?: string;
|
||||
/** Arbitrary metadata associated with the entity. */
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
export interface WsStreamPayload {
|
||||
@@ -164,6 +185,11 @@ export type FilterValue = {
|
||||
type: "boolean";
|
||||
value: boolean;
|
||||
};
|
||||
/**
|
||||
* @interface WorldPlugin
|
||||
* @description The core lifecycle interface for all WorldWideView extensions.
|
||||
* Every plugin (built-in or marketplace) must implement this interface.
|
||||
*/
|
||||
export interface WorldPlugin {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -203,6 +229,15 @@ export interface WorldPlugin {
|
||||
viewer: any;
|
||||
enabled: boolean;
|
||||
}>;
|
||||
/**
|
||||
* Returns a React component to be rendered inside the Bottom Panel when this plugin's
|
||||
* dock button is selected. The panel is resizable and can be expanded to fullscreen.
|
||||
* If not provided, the plugin will not appear in the bottom dock.
|
||||
*/
|
||||
getBottomPanelComponent?(): ComponentType<{
|
||||
pluginId: string;
|
||||
enabled: boolean;
|
||||
}>;
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
@@ -213,6 +248,16 @@ export type DataBusEvents = {
|
||||
pluginId: string;
|
||||
defaultInterval: number;
|
||||
};
|
||||
pluginUnregistered: {
|
||||
pluginId: string;
|
||||
};
|
||||
dynamicPluginCreate: {
|
||||
plugin: WorldPlugin;
|
||||
autoEnable?: boolean;
|
||||
};
|
||||
dynamicPluginRemove: {
|
||||
pluginId: string;
|
||||
};
|
||||
dataUpdated: {
|
||||
pluginId: string;
|
||||
entities: GeoEntity[];
|
||||
@@ -244,6 +289,16 @@ export type DataBusEvents = {
|
||||
heading?: number;
|
||||
};
|
||||
globeReady: Record<string, never>;
|
||||
pluginError: {
|
||||
pluginId?: string;
|
||||
message: string;
|
||||
error?: Error;
|
||||
};
|
||||
layerLoadingChanged: {
|
||||
pluginId: string;
|
||||
loading: boolean;
|
||||
};
|
||||
};
|
||||
export * from "./viteGlobals";
|
||||
export * from "./auth-contracts";
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAI3C,kFAAkF;AAClF,eAAO,MAAM,iBAAiB,KAAK,CAAC;AAKpC,MAAM,WAAW,cAAe,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC3D,2BAA2B;IAC3B,KAAK,CAAC,EAAE,MA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AE,MAAM,CAAC;IAGhB,UAAU,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,IAAI,IAAI,CAAC;IAGhB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IAClD,kBAAkB,IAAI,MAAM,CAAC;IAG7B,cAAc,IAAI,WAAW,CAAC;IAC9B,YAAY,CAAC,MAAM,EAAE,SAAS,GAAG,mBAAmB,CAAC;IAGLine truncated
|
||||
+9
-3
@@ -1,7 +1,11 @@
|
||||
"use strict";
|
||||
// ─── WorldWideView Plugin SDK ─────────────────────────────────
|
||||
// The public API for building WorldWideView plugins.
|
||||
// Import from "@worldwideview/wwv-plugin-sdk" in your plugin.
|
||||
/**
|
||||
* @file index.ts
|
||||
* @description Core SDK for WorldWideView plugin development.
|
||||
* Defines the foundational types, interfaces, and utilities required
|
||||
* to build data seeders, visualizers, and UI extensions.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
@@ -61,3 +65,5 @@ function createSvgIconUrl(Icon, opts = {}) {
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(wrappedSvg)}`;
|
||||
}
|
||||
__exportStar(require("./viteGlobals"), exports);
|
||||
// ─── Auth Contracts ──────────────────────────────────────────
|
||||
__exportStar(require("./auth-contracts"), exports);
|
||||
+11
@@ -1,3 +1,10 @@
|
||||
/**
|
||||
* @file manifest.ts
|
||||
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
|
||||
* Defines the contract between the platform and external modules,
|
||||
* covering capabilities, security tiers, and data source configurations.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
import type { PluginCategory } from "./index";
|
||||
export type PluginFormat = "declarative" | "static" | "bundle";
|
||||
export type PluginType = "data-layer" | "extension";
|
||||
@@ -42,6 +49,10 @@ export interface RenderingConfig {
|
||||
minZoomLevel?: number;
|
||||
maxEntities?: number;
|
||||
}
|
||||
/**
|
||||
* @interface PluginManifest
|
||||
* @description The structural definition of a plugin.json file.
|
||||
*/
|
||||
export interface PluginManifest {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,MAAM,YAAY,GAAG,aAAa,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAC/D,MAAM,MAAM,UAAU,GAAG,YAAY,GAAG,WAAW,CAAC;AACpD,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,YAAY,CAAC;AAE/D,MAAM,MAAM,gBAAgB,GACtB,UAAU,GACV,aAAa,MAAM,EAAE,GACrB,iBAAiB,GACjB,YAAY,GACZ,YAAY,GACZ,aAAa,GACb,eAAe,GACf,cAAc,GACd,cAAc,GACd,eAAe,GACf,eAAe,CAAC;AAEtB,MAAM,WAAW,gBAAgB;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,KAAK,CAAC;IACnC,IAAI,CAAC,EAAE;QAAE,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IACxE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/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AW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,UAAU,CAAC;IACjB,MAAM,EAAE,YAAY,CAAC;IACrB,KAAK,EAAE,SAAS,CAAC;IACjB,YAAY,EAAE,gBAAgB,EAAE,CAAC;IACjC,QAAQ,EAAE,cAAc,GAAG,MAAM,CAAC;IAClC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1C,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC;IAClC,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;CACtB"}
|
||||
+7
-3
@@ -1,5 +1,9 @@
|
||||
"use strict";
|
||||
// ─── Plugin Manifest Types ───────────────────────────────────
|
||||
// Schema for plugin.json manifest files.
|
||||
// Three formats: declarative (JSON-only), static (GeoJSON), bundle (JS code).
|
||||
/**
|
||||
* @file manifest.ts
|
||||
* @description Schema and types for the WorldWideView plugin manifest (plugin.json).
|
||||
* Defines the contract between the platform and external modules,
|
||||
* covering capabilities, security tiers, and data source configurations.
|
||||
* @module @worldwideview/wwv-plugin-sdk
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@worldwideview/wwv-plugin-sdk",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.1",
|
||||
"description": "Plugin SDK — types, interfaces, and utilities for building WorldWideView globe plugins",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
import { describe, it, expectTypeOf } from "vitest";
|
||||
import type {
|
||||
TokenExchangeRequest,
|
||||
@@ -21,7 +22,8 @@ describe("Auth Contracts", () => {
|
||||
expectTypeOf<TokenExchangeRequest>().toHaveProperty("audience").toEqualTypeOf<string>();
|
||||
|
||||
// @ts-expect-error - missing required apiKey
|
||||
const badReq: TokenExchangeRequest = { audience: "engine-123" };
|
||||
const _badReq: TokenExchangeRequest = { audience: "engine-123" };
|
||||
void _badReq;
|
||||
});
|
||||
|
||||
it("TokenExchangeResponse has exact required properties", () => {
|
||||
@@ -31,7 +33,8 @@ describe("Auth Contracts", () => {
|
||||
expectTypeOf<TokenExchangeResponse>().toHaveProperty("tier").toEqualTypeOf<Tier | undefined>();
|
||||
|
||||
// @ts-expect-error - missing required token
|
||||
const badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
|
||||
const _badRes: TokenExchangeResponse = { expiresAt: 123456789, kid: "key-1" };
|
||||
void _badRes;
|
||||
});
|
||||
|
||||
it("WebSocketAuthMessage has exact required properties including protocol version", () => {
|
||||
@@ -40,10 +43,12 @@ describe("Auth Contracts", () => {
|
||||
expectTypeOf<WebSocketAuthMessage>().toHaveProperty("token").toEqualTypeOf<SensitiveString>();
|
||||
|
||||
// @ts-expect-error - missing version
|
||||
const badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
|
||||
const _badMsg: WebSocketAuthMessage = { type: "auth", token: "jwt-token-here" as SensitiveString };
|
||||
void _badMsg;
|
||||
|
||||
// @ts-expect-error - wrong version
|
||||
const badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
|
||||
const _badVersion: WebSocketAuthMessage = { type: "auth", v: 2, token: "jwt-token-here" as SensitiveString };
|
||||
void _badVersion;
|
||||
});
|
||||
|
||||
it("WebSocketMessage is a discriminated union correctly containing WebSocketAuthMessage", () => {
|
||||
|
||||
@@ -277,6 +277,12 @@ export interface WorldPlugin {
|
||||
getSettingsComponent?(): ComponentType<{ pluginId: string }>;
|
||||
/** Custom React component injected into the Globe view for rendering primitives/data sources (e.g. GeoJSON). */
|
||||
getGlobeComponent?(): ComponentType<{ viewer: any; enabled: boolean }>;
|
||||
/**
|
||||
* Returns a React component to be rendered inside the Bottom Panel when this plugin's
|
||||
* dock button is selected. The panel is resizable and can be expanded to fullscreen.
|
||||
* If not provided, the plugin will not appear in the bottom dock.
|
||||
*/
|
||||
getBottomPanelComponent?(): ComponentType<{ pluginId: string; enabled: boolean }>;
|
||||
requiresConfiguration?(settings: unknown): boolean;
|
||||
/** Map raw websocket payload into GeoEntity array. Optional existingEntities is provided so plugins can merge state (e.g. historical trails). */
|
||||
mapWebsocketPayload?(payload: any, existingEntities?: GeoEntity[]): GeoEntity[];
|
||||
@@ -288,6 +294,9 @@ export type GlobePlugin = WorldPlugin;
|
||||
// ─── Data Bus Event Types ────────────────────────────────────
|
||||
export type DataBusEvents = {
|
||||
pluginRegistered: { pluginId: string; defaultInterval: number };
|
||||
pluginUnregistered: { pluginId: string };
|
||||
dynamicPluginCreate: { plugin: WorldPlugin; autoEnable?: boolean };
|
||||
dynamicPluginRemove: { pluginId: string };
|
||||
dataUpdated: { pluginId: string; entities: GeoEntity[] };
|
||||
entitySelected: { entity: GeoEntity | null };
|
||||
layerToggled: { pluginId: string; enabled: boolean };
|
||||
@@ -296,6 +305,8 @@ export type DataBusEvents = {
|
||||
cameraFaceTowards: { lat: number; lon: number; alt: number };
|
||||
cameraGoTo: { lat: number; lon: number; alt: number; distance?: number; maxPitch?: number; heading?: number };
|
||||
globeReady: Record<string, never>;
|
||||
pluginError: { pluginId?: string; message: string; error?: Error };
|
||||
layerLoadingChanged: { pluginId: string; loading: boolean };
|
||||
};
|
||||
|
||||
export * from "./viteGlobals";
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
timeout: 60000,
|
||||
expect: {
|
||||
timeout: 10000,
|
||||
},
|
||||
globalSetup: './tests/global.setup.ts',
|
||||
globalTeardown: './tests/global.teardown.ts',
|
||||
testDir: './tests',
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. Restrict to 2 locally to prevent Next.js compilation overload. */
|
||||
workers: process.env.CI ? 1 : 2,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: 'html',
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||
baseURL: 'http://localhost:3001',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
storageState: 'playwright/.auth/user.json'
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'firefox',
|
||||
use: {
|
||||
...devices['Desktop Firefox'],
|
||||
storageState: 'playwright/.auth/user.json',
|
||||
launchOptions: {
|
||||
firefoxUserPrefs: {
|
||||
// Disable MSAA/AT-SPI accessibility layer — causes hangs on Linux CI
|
||||
'accessibility.force_disabled': 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'webkit',
|
||||
use: {
|
||||
...devices['Desktop Safari'],
|
||||
storageState: 'playwright/.auth/user.json'
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
webServer: {
|
||||
command: 'pnpm dev',
|
||||
env: { PORT: '3001' },
|
||||
url: 'http://localhost:3001',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120 * 1000,
|
||||
},
|
||||
});
|
||||
Generated
+1069
-667
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"id": "e2e-mock-bottom-panel",
|
||||
"name": "E2E Bottom Panel Mock",
|
||||
"version": "1.0.0",
|
||||
"description": "A static mock plugin used for Playwright E2E tests focusing on the bottom panel.",
|
||||
"author": "WorldWideView Automated Tests",
|
||||
"type": "extension",
|
||||
"format": "bundle",
|
||||
"trust": "unverified",
|
||||
"entry": "/e2e-fixtures/e2e-mock-bottom-panel.js",
|
||||
"capabilities": ["ui:bottom-panel", "ui:sidebar"],
|
||||
"extends": ["bottom-panel", "sidebar"],
|
||||
"category": "utility"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// This file is loaded by the plugin manager in the E2E test environment.
|
||||
// It bypasses the build step and directly uses the host's injected React instance.
|
||||
|
||||
export default {
|
||||
id: "e2e-mock-bottom-panel",
|
||||
name: "E2E Bottom Panel Mock",
|
||||
description: "A mock plugin for Bottom Panel E2E testing.",
|
||||
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
|
||||
category: "custom",
|
||||
version: "1.0.0",
|
||||
|
||||
// Lifecycle
|
||||
initialize: async (ctx) => {
|
||||
console.log("[e2e-mock-bottom-panel] Initialized");
|
||||
},
|
||||
destroy: () => {
|
||||
console.log("[e2e-mock-bottom-panel] Destroyed");
|
||||
},
|
||||
|
||||
// Data
|
||||
fetch: async (timeRange) => {
|
||||
return []; // No entities for this mock
|
||||
},
|
||||
getPollingInterval: () => {
|
||||
return 60000;
|
||||
},
|
||||
|
||||
// Rendering
|
||||
getLayerConfig: () => {
|
||||
return {
|
||||
color: "#0000FF",
|
||||
clusterEnabled: false,
|
||||
clusterDistance: 50
|
||||
};
|
||||
},
|
||||
renderEntity: (entity) => {
|
||||
return {
|
||||
type: "point",
|
||||
color: "#0000FF",
|
||||
size: 5
|
||||
};
|
||||
},
|
||||
|
||||
// Provide a bottom panel UI component using the host's React instance
|
||||
getBottomPanelComponent: () => {
|
||||
// Access React from the global host object injected by WorldWideView
|
||||
const React = globalThis.__WWV_HOST__.React;
|
||||
|
||||
if (!React) {
|
||||
console.error("[e2e-mock-bottom-panel] Failed to resolve React from __WWV_HOST__");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Return a component function
|
||||
return function MockBottomPanel() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{
|
||||
"data-testid": "e2e-bottom-panel-content",
|
||||
style: {
|
||||
padding: "16px",
|
||||
background: "rgba(0, 0, 255, 0.1)",
|
||||
border: "1px solid blue",
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center"
|
||||
}
|
||||
},
|
||||
"Mock Bottom Panel Active"
|
||||
);
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"id": "e2e-mock-plugin",
|
||||
"name": "E2E Mock Plugin",
|
||||
"version": "1.0.0",
|
||||
"description": "A static mock plugin used for Playwright E2E tests.",
|
||||
"author": "WorldWideView Automated Tests",
|
||||
"type": "extension",
|
||||
"format": "bundle",
|
||||
"trust": "unverified",
|
||||
"entry": "/e2e-fixtures/mock-plugin.js",
|
||||
"capabilities": ["ui:sidebar"],
|
||||
"category": "utility",
|
||||
"extends": ["sidebar"]
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// This file is loaded by the plugin manager in the E2E test environment.
|
||||
// It bypasses the build step and directly uses the host's injected React instance.
|
||||
|
||||
export default {
|
||||
// Basic plugin metadata required by WorldPlugin interface
|
||||
id: "e2e-mock-plugin",
|
||||
name: "E2E Mock Plugin",
|
||||
description: "A mock plugin for E2E testing.",
|
||||
icon: "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=", // Empty SVG as fallback
|
||||
category: "custom",
|
||||
version: "1.0.0",
|
||||
|
||||
// Lifecycle
|
||||
initialize: async (ctx) => {
|
||||
console.log("[e2e-mock-plugin] Initialized");
|
||||
},
|
||||
destroy: () => {
|
||||
console.log("[e2e-mock-plugin] Destroyed");
|
||||
},
|
||||
|
||||
// Data
|
||||
fetch: async (timeRange) => {
|
||||
return []; // No entities for this mock
|
||||
},
|
||||
getPollingInterval: () => {
|
||||
return 60000;
|
||||
},
|
||||
|
||||
// Rendering
|
||||
getLayerConfig: () => {
|
||||
return {
|
||||
color: "#00FF00",
|
||||
clusterEnabled: false,
|
||||
clusterDistance: 50
|
||||
};
|
||||
},
|
||||
renderEntity: (entity) => {
|
||||
return {
|
||||
type: "point",
|
||||
color: "#00FF00",
|
||||
size: 5
|
||||
};
|
||||
},
|
||||
|
||||
// Provide a UI component using the host's React instance
|
||||
getSidebarComponent: () => {
|
||||
// Access React from the global host object injected by WorldWideView
|
||||
const React = globalThis.__WWV_HOST__.React;
|
||||
|
||||
if (!React) {
|
||||
console.error("[e2e-mock-plugin] Failed to resolve React from __WWV_HOST__");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Return a component function, not just an element
|
||||
return function MockSidebar() {
|
||||
return React.createElement(
|
||||
"div",
|
||||
{ "data-testid": "e2e-mock-panel", style: { padding: "16px", background: "rgba(0, 255, 0, 0.1)", border: "1px solid green" } },
|
||||
"Mock Panel (E2E Test)"
|
||||
);
|
||||
};
|
||||
}
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
@@ -9,6 +9,7 @@
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
// Load environment variables manually since dotenv might not be installed globally
|
||||
/**
|
||||
@@ -46,6 +47,83 @@ if (skipLocalDb) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Deterministic Port Assignment
|
||||
const cwd = process.cwd();
|
||||
const folderName = path.basename(cwd);
|
||||
let port = 5432; // Default for main repo
|
||||
|
||||
if (folderName !== 'worldwideview') {
|
||||
const hash = crypto.createHash('sha256').update(cwd).digest('hex');
|
||||
const portOffset = parseInt(hash.substring(0, 4), 16) % 1000;
|
||||
port = 5433 + portOffset;
|
||||
}
|
||||
|
||||
process.env.WWV_DB_PORT = port.toString();
|
||||
console.log(`🔌 Assigned deterministic database port: ${port}`);
|
||||
|
||||
// Robust rewrite of DATABASE_URL in .env
|
||||
const envPath = path.resolve(cwd, '.env');
|
||||
if (fs.existsSync(envPath)) {
|
||||
const envContent = fs.readFileSync(envPath, 'utf8');
|
||||
const lines = envContent.split(/\r?\n/);
|
||||
|
||||
const targetUrl = `DATABASE_URL="postgresql://postgres:[email protected]:${port}/worldwideview?schema=public"`;
|
||||
let foundTargetActive = false;
|
||||
let linesModified = false;
|
||||
|
||||
const newLines = lines.map(line => {
|
||||
// Check if line is an active DATABASE_URL
|
||||
if (/^\s*DATABASE_URL\s*=/.test(line)) {
|
||||
if (line.trim() === targetUrl) {
|
||||
foundTargetActive = true;
|
||||
return line;
|
||||
} else {
|
||||
console.warn(`⚠️ [Telemetry] Commenting out conflicting DATABASE_URL: ${line.trim()}`);
|
||||
linesModified = true;
|
||||
return `# ${line}`;
|
||||
}
|
||||
}
|
||||
return line;
|
||||
});
|
||||
|
||||
if (!foundTargetActive) {
|
||||
console.log(`🔌 [Telemetry] Injecting correct local DATABASE_URL for port ${port}.`);
|
||||
newLines.push(``);
|
||||
newLines.push(`# Dynamically injected by boot-db.mjs for worktree`);
|
||||
newLines.push(targetUrl);
|
||||
linesModified = true;
|
||||
}
|
||||
|
||||
if (linesModified) {
|
||||
const newContent = newLines.join('\n');
|
||||
|
||||
// File write with retries and telemetry
|
||||
const maxRetries = 3;
|
||||
let attempt = 0;
|
||||
while (attempt < maxRetries) {
|
||||
try {
|
||||
fs.writeFileSync(envPath, newContent, 'utf8');
|
||||
break; // Success
|
||||
} catch (err) {
|
||||
attempt++;
|
||||
if (err.code === 'EBUSY' || err.code === 'EPERM' || err.message.includes('os error 32')) {
|
||||
console.warn(`⚠️ [Telemetry] File lock encountered on .env (attempt ${attempt}/${maxRetries}). Retrying in 100ms...`);
|
||||
if (attempt >= maxRetries) {
|
||||
console.error('❌ Failed to write .env after multiple attempts due to file locks.');
|
||||
throw err;
|
||||
}
|
||||
// Synchronous sleep since boot-db.mjs isn't currently inside an async IIFE
|
||||
const start = Date.now();
|
||||
while (Date.now() - start < 100) {}
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
console.log('🚀 Checking local PostgreSQL database...');
|
||||
|
||||
try {
|
||||
|
||||
@@ -15,7 +15,7 @@ function copyDir(src, dest) {
|
||||
}
|
||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||
|
||||
for (let entry of entries) {
|
||||
for (const entry of entries) {
|
||||
const srcPath = path.join(src, entry.name);
|
||||
const destPath = path.join(dest, entry.name);
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* @file db-prune.mjs
|
||||
* @description Garbage collects orphaned Docker volumes from deleted git worktrees.
|
||||
* Resolves the issue where manually deleting a worktree folder (rm -rf) leaves
|
||||
* behind persistent database and data volumes.
|
||||
*/
|
||||
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
console.log('🧹 Starting Garbage Collection for orphaned WorldWideView Docker volumes...');
|
||||
|
||||
try {
|
||||
// Get all docker volumes
|
||||
const volumesOutput = execSync('docker volume ls --format "{{.Name}}"').toString();
|
||||
const volumes = volumesOutput.split('\n').map(v => v.trim()).filter(Boolean);
|
||||
|
||||
// Identify WorldWideView volumes
|
||||
const wwvVolumes = volumes.filter(v =>
|
||||
(v.startsWith('worldwideview') && v.endsWith('_postgres-data')) ||
|
||||
(v.startsWith('worldwideview') && v.endsWith('_wwv-data'))
|
||||
);
|
||||
|
||||
if (wwvVolumes.length === 0) {
|
||||
console.log('✅ No WorldWideView volumes found.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Get active worktree folders in the parent directory
|
||||
const parentDir = path.resolve(process.cwd(), '..');
|
||||
const folders = fs.readdirSync(parentDir, { withFileTypes: true })
|
||||
.filter(dirent => dirent.isDirectory() && dirent.name.startsWith('worldwideview'))
|
||||
.map(dirent => dirent.name);
|
||||
|
||||
// Compute their expected Docker project names (lowercase, alphanumeric only)
|
||||
// Docker Compose defaults to this sanitization for project names based on directories
|
||||
const activeProjectNames = new Set(
|
||||
folders.map(folder => folder.replace(/[^a-zA-Z0-9]/g, '').toLowerCase())
|
||||
);
|
||||
|
||||
let orphanedCount = 0;
|
||||
|
||||
for (const volume of wwvVolumes) {
|
||||
let projectName = '';
|
||||
if (volume.endsWith('_postgres-data')) {
|
||||
projectName = volume.slice(0, -'_postgres-data'.length);
|
||||
} else if (volume.endsWith('_wwv-data')) {
|
||||
projectName = volume.slice(0, -'_wwv-data'.length);
|
||||
}
|
||||
|
||||
if (!activeProjectNames.has(projectName)) {
|
||||
console.log(`🗑️ Deleting orphaned volume: ${volume}`);
|
||||
try {
|
||||
execSync(`docker volume rm ${volume}`, { stdio: 'inherit' });
|
||||
orphanedCount++;
|
||||
} catch (rmError) {
|
||||
console.warn(`⚠️ Could not remove volume ${volume}. It may still be in use.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (orphanedCount === 0) {
|
||||
console.log('✅ All existing volumes belong to active worktrees. Nothing to prune.');
|
||||
} else {
|
||||
console.log(`✅ Successfully pruned ${orphanedCount} orphaned volume(s).`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to prune volumes:', error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* @file dev.mjs
|
||||
* @description Orchestrator for the local development environment.
|
||||
* Replaces direct usage of 'concurrently' via CLI to allow for optional,
|
||||
* cross-platform graceful teardown of the Docker database on exit.
|
||||
* @module scripts
|
||||
*/
|
||||
|
||||
import concurrently from 'concurrently';
|
||||
import kill from 'tree-kill/index.js';
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
import process from 'process';
|
||||
|
||||
// Manually parse .env to avoid external dependencies early in the boot process
|
||||
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] || '';
|
||||
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');
|
||||
|
||||
const teardownDbOnExit = process.env.WWV_TEARDOWN_DB_ON_EXIT === 'true' || process.env.WWV_TEARDOWN_DB_ON_EXIT === '1';
|
||||
|
||||
const { result, commands } = concurrently(
|
||||
[
|
||||
{ command: 'pnpm run dev:plugins', name: 'plugins', prefixColor: 'magenta' },
|
||||
{ command: 'pnpm exec next dev', name: 'next', prefixColor: 'blue' }
|
||||
],
|
||||
{
|
||||
prefix: 'name',
|
||||
killOthers: ['failure', 'success']
|
||||
}
|
||||
);
|
||||
|
||||
let isShuttingDown = false;
|
||||
|
||||
const shutdown = () => {
|
||||
if (isShuttingDown) return;
|
||||
isShuttingDown = true;
|
||||
|
||||
console.log('\n🛑 Shutting down dev servers...');
|
||||
|
||||
// Forcefully kill the process tree of each command cross-platform
|
||||
commands.forEach(cmd => {
|
||||
if (cmd.pid) {
|
||||
kill(cmd.pid, 'SIGKILL');
|
||||
}
|
||||
});
|
||||
|
||||
if (teardownDbOnExit) {
|
||||
console.log('📦 Tearing down local PostgreSQL database...');
|
||||
try {
|
||||
execSync('docker compose stop db', { stdio: 'inherit' });
|
||||
console.log('✅ Local database stopped.');
|
||||
} catch (e) {
|
||||
console.error('⚠️ Failed to stop database container.');
|
||||
}
|
||||
}
|
||||
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
// Listen for termination signals
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
|
||||
result.then(
|
||||
() => process.exit(0),
|
||||
() => process.exit(1)
|
||||
);
|
||||
@@ -1,6 +1,13 @@
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
const dbUrl = process.env.DATABASE_URL || '';
|
||||
|
||||
if (!dbUrl) {
|
||||
console.error("❌ ERROR: DATABASE_URL is missing.");
|
||||
console.error(" Did you forget to run 'pnpm run setup' to generate your .env file?");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const isLocal = dbUrl.includes('localhost') || dbUrl.includes('127.0.0.1') || dbUrl.includes('host.docker.internal') || dbUrl.includes('postgres:postgres@db:5432');
|
||||
|
||||
if (!isLocal) {
|
||||
|
||||
+220
-24
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { build } from "vite";
|
||||
import { fileURLToPath } from "url";
|
||||
@@ -26,9 +27,72 @@ const EXTERNAL_GLOBALS = {
|
||||
"resium": "globalThis.__WWV_HOST__.Resium",
|
||||
};
|
||||
|
||||
/**
|
||||
* Synthetic host-module exports for `@/` imports that plugins use to access
|
||||
* the host application's runtime objects (store, plugin manager, components).
|
||||
*
|
||||
* When a plugin sub-component does `import { useStore } from "@/core/state/store"`,
|
||||
* the tsconfig `@/*` alias (inherited from the main app root tsconfig) would normally
|
||||
* resolve that to the actual `src/core/state/store.ts` file — pulling the entire Zustand
|
||||
* store (and its transitive deps like `src/core/edition.ts`) into the bundle.
|
||||
* This plugin intercepts those imports at the resolveId stage, before Vite touches
|
||||
* the filesystem, and substitutes a synthetic module that reads from the host globals
|
||||
* injected at runtime by `hostGlobals.ts`.
|
||||
*/
|
||||
const HOST_MODULE_SYNTHETICS = {
|
||||
"@/core/state/store": `export const useStore = globalThis.__WWV_HOST__.useStore;`,
|
||||
"@/core/plugins/PluginManager": `export const pluginManager = globalThis.__WWV_HOST__.pluginManager;`,
|
||||
"@/components/video/CameraStream": `export const CameraStream = globalThis.__WWV_HOST__.CameraStream;`,
|
||||
"zustand": `
|
||||
const zustand = globalThis.__WWV_HOST__.zustand || {};
|
||||
export default zustand;
|
||||
export const { create, createStore } = zustand;
|
||||
`,
|
||||
};
|
||||
|
||||
/**
|
||||
* @function wwvHostRedirectPlugin
|
||||
* @description Vite plugin that intercepts host-app module imports (`@/core/...`,
|
||||
* `@/components/...`) in local plugin builds and redirects them to the runtime
|
||||
* host globals instead of bundling the full app source tree.
|
||||
*
|
||||
* @returns {import('vite').Plugin}
|
||||
*/
|
||||
function wwvHostRedirectPlugin() {
|
||||
return {
|
||||
name: "wwv-host-redirect",
|
||||
enforce: "pre",
|
||||
resolveId(id) {
|
||||
if (id in HOST_MODULE_SYNTHETICS) return `\0${id}`;
|
||||
return null;
|
||||
},
|
||||
load(id) {
|
||||
if (!id.startsWith("\0")) return null;
|
||||
const originalId = id.slice(1);
|
||||
return HOST_MODULE_SYNTHETICS[originalId] ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @function readJsonFile
|
||||
* @description Reads a UTF-8 JSON file, tolerating a leading BOM (U+FEFF).
|
||||
* Node's `fs.readFileSync(p, 'utf-8')` preserves the BOM byte, which `JSON.parse`
|
||||
* then rejects with "Unexpected token". Scaffolders and editors on Windows
|
||||
* occasionally emit BOMs into `package.json`; pnpm/npm strip them silently,
|
||||
* so we match that behavior here to avoid breaking dev on otherwise-valid files.
|
||||
* @param {string} filePath
|
||||
* @returns {any}
|
||||
*/
|
||||
function readJsonFile(filePath) {
|
||||
let text = fs.readFileSync(filePath, "utf-8");
|
||||
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @function discoverLocalPlugins
|
||||
* @description Finds all directories in `local-plugins/` that contain a valid
|
||||
* @description Finds all directories in `local-plugins/` that contain a valid
|
||||
* `package.json` with a `worldwideview` manifest block.
|
||||
* @returns {Array<{dir: string, manifest: any, pluginDir: string}>}
|
||||
*/
|
||||
@@ -40,43 +104,141 @@ export function discoverLocalPlugins() {
|
||||
if (dir.startsWith(".")) return false;
|
||||
const pkgPath = path.join(LOCAL_PLUGINS_DIR, dir, "package.json");
|
||||
if (!fs.existsSync(pkgPath)) return false;
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
||||
const pkg = readJsonFile(pkgPath);
|
||||
return !!pkg.worldwideview;
|
||||
})
|
||||
.map(dir => {
|
||||
const pkgPath = path.join(LOCAL_PLUGINS_DIR, dir, "package.json");
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
||||
const pkg = readJsonFile(pkgPath);
|
||||
const manifest = pkg.worldwideview;
|
||||
manifest.version = pkg.version;
|
||||
manifest.name = pkg.name;
|
||||
manifest.description = pkg.description;
|
||||
return { dir, manifest, pluginDir: path.join(LOCAL_PLUGINS_DIR, dir) };
|
||||
return { dir, manifest, pkg, pluginDir: path.join(LOCAL_PLUGINS_DIR, dir) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @function buildPlugin
|
||||
* @description Invokes the Vite build engine to compile a plugin's source
|
||||
* into a single ES module, externalizing shared host dependencies.
|
||||
* @function resolvePluginEntry
|
||||
* @description Resolves the TypeScript source entry file for a plugin.
|
||||
*
|
||||
* Resolution order:
|
||||
* 1. `worldwideview.dev_entry` — explicit override in the manifest block
|
||||
* 2. `pkg.types` — if it points to a .ts/.tsx source file (not a .d.ts declaration)
|
||||
* 3. `pkg.source` — explicit source field (less common, but valid)
|
||||
* 4. Heuristic fallback: src/index.ts → src/index.tsx → index.ts → index.tsx
|
||||
*
|
||||
* @param {string} pluginDir - Absolute path to the plugin directory.
|
||||
* @param {any} manifest - The parsed `worldwideview` manifest block.
|
||||
* @param {any} pkg - The full parsed package.json object.
|
||||
* @returns {string|null} Absolute path to the entry file, or null if not found.
|
||||
*/
|
||||
export async function buildPlugin({ dir, manifest, pluginDir }) {
|
||||
const devEntry = manifest.dev_entry || "src/index.ts";
|
||||
let entryFile = path.join(pluginDir, devEntry);
|
||||
function resolvePluginEntry(pluginDir, manifest, pkg) {
|
||||
const candidates = [];
|
||||
|
||||
// Fallback: check for .tsx
|
||||
if (!fs.existsSync(entryFile)) {
|
||||
const tsxEntry = devEntry.replace(".ts", ".tsx");
|
||||
entryFile = path.join(pluginDir, tsxEntry);
|
||||
if (!fs.existsSync(entryFile)) {
|
||||
console.warn(`[sync] ⚠ No entry file found for ${dir}, skipping`);
|
||||
return false;
|
||||
if (manifest.dev_entry) {
|
||||
candidates.push(path.join(pluginDir, manifest.dev_entry));
|
||||
}
|
||||
|
||||
// pkg.types points to the TS source in all WWV plugins (e.g. "src/index.ts")
|
||||
if (pkg.types && !pkg.types.endsWith(".d.ts")) {
|
||||
candidates.push(path.join(pluginDir, pkg.types));
|
||||
}
|
||||
|
||||
if (pkg.source) {
|
||||
candidates.push(path.join(pluginDir, pkg.source));
|
||||
}
|
||||
|
||||
// Heuristic fallbacks
|
||||
for (const rel of ["src/index.ts", "src/index.tsx", "index.ts", "index.tsx"]) {
|
||||
candidates.push(path.join(pluginDir, rel));
|
||||
}
|
||||
|
||||
return candidates.find(f => fs.existsSync(f)) ?? null;
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(["dist", "node_modules", ".git", ".turbo", ".vite"]);
|
||||
|
||||
/**
|
||||
* @function latestSourceMtime
|
||||
* @description Walks a plugin directory and returns the newest mtime (ms) across
|
||||
* source files. Used to decide whether a cached `dist/frontend.mjs` is still valid.
|
||||
* Skips build/output dirs so this is fast even on cold disks.
|
||||
* @param {string} rootDir
|
||||
* @returns {number} newest mtime in ms, or 0 if no files found
|
||||
*/
|
||||
function latestSourceMtime(rootDir) {
|
||||
let newest = 0;
|
||||
/** @param {string} dir */
|
||||
function walk(dir) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (entry.name.startsWith(".") && entry.name !== ".env") continue;
|
||||
if (SKIP_DIRS.has(entry.name)) continue;
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
walk(full);
|
||||
} else if (entry.isFile()) {
|
||||
const m = fs.statSync(full).mtimeMs;
|
||||
if (m > newest) newest = m;
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(rootDir);
|
||||
return newest;
|
||||
}
|
||||
|
||||
/**
|
||||
* @function isBuildFresh
|
||||
* @description Returns true if the plugin's existing `dist/frontend.mjs` is newer
|
||||
* than every source file under its directory — meaning Vite would produce a
|
||||
* byte-identical bundle and the build can be skipped.
|
||||
* @param {string} pluginDir
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isBuildFresh(pluginDir) {
|
||||
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
|
||||
if (!fs.existsSync(distFile)) return false;
|
||||
const distMtime = fs.statSync(distFile).mtimeMs;
|
||||
const sourceMtime = latestSourceMtime(pluginDir);
|
||||
return distMtime >= sourceMtime;
|
||||
}
|
||||
|
||||
/**
|
||||
* @function buildPlugin
|
||||
* @description Invokes the Vite build engine to compile a plugin's source
|
||||
* into a single ES module, externalizing shared host dependencies.
|
||||
*
|
||||
* Returns `"fresh"` if an up-to-date `dist/frontend.mjs` already exists (no build run),
|
||||
* `true` if Vite produced a new bundle, or `false` on failure.
|
||||
*/
|
||||
export async function buildPlugin({ dir, manifest, pkg, pluginDir }) {
|
||||
if (isBuildFresh(pluginDir)) {
|
||||
return "fresh";
|
||||
}
|
||||
|
||||
const entryFile = resolvePluginEntry(pluginDir, manifest, pkg ?? {});
|
||||
|
||||
if (!entryFile) {
|
||||
console.warn(`[sync] ⚠ No entry file found for ${dir}, skipping`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await build({
|
||||
root: pluginDir,
|
||||
// Disable auto-loading the plugin's own vite.config.ts — the local
|
||||
// plugins' node_modules may be symlinked to a different repo's SDK
|
||||
// build (worktree scenario), which breaks config loading. The sync
|
||||
// script provides all necessary config inline.
|
||||
configFile: false,
|
||||
logLevel: "warn",
|
||||
plugins: [wwvHostRedirectPlugin()],
|
||||
build: {
|
||||
lib: {
|
||||
entry: entryFile,
|
||||
@@ -114,7 +276,7 @@ export async function buildPlugin({ dir, manifest, pluginDir }) {
|
||||
}
|
||||
}
|
||||
|
||||
export function syncToPublic({ dir, manifest, pluginDir }) {
|
||||
export function syncToPublic({ dir, manifest, pluginDir }, { quiet = false } = {}) {
|
||||
const publicName = manifest.id || dir.replace("wwv-plugin-", "");
|
||||
const targetDir = path.join(OUTPUT_DIR, publicName);
|
||||
const distFile = path.join(pluginDir, "dist", "frontend.mjs");
|
||||
@@ -151,7 +313,7 @@ export function syncToPublic({ dir, manifest, pluginDir }) {
|
||||
JSON.stringify(pluginJson, null, 2)
|
||||
);
|
||||
|
||||
console.log(`[sync] ✅ ${publicName} → public/plugins-local/${publicName}/`);
|
||||
if (!quiet) console.log(`[sync] ✅ ${publicName} → public/plugins-local/${publicName}/`);
|
||||
}
|
||||
|
||||
// Clean stale plugins from public/plugins-local/ that no longer exist in local-plugins/
|
||||
@@ -166,6 +328,32 @@ function cleanStale(activeIds) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @function runWithConcurrency
|
||||
* @description Runs an async worker over `items` with a fixed concurrency cap.
|
||||
* Vite builds are CPU-bound; running all ~30 in parallel thrashes the scheduler
|
||||
* and balloons RSS. A cap around half the logical cores keeps wall-clock low
|
||||
* without starving the rest of the dev environment (Next.js, the data engine).
|
||||
* @template T, R
|
||||
* @param {T[]} items
|
||||
* @param {number} concurrency
|
||||
* @param {(item: T) => Promise<R>} worker
|
||||
* @returns {Promise<R[]>}
|
||||
*/
|
||||
async function runWithConcurrency(items, concurrency, worker) {
|
||||
const results = new Array(items.length);
|
||||
let cursor = 0;
|
||||
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
|
||||
while (true) {
|
||||
const i = cursor++;
|
||||
if (i >= items.length) return;
|
||||
results[i] = await worker(items[i]);
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return results;
|
||||
}
|
||||
|
||||
export async function syncAll() {
|
||||
const plugins = discoverLocalPlugins();
|
||||
|
||||
@@ -175,12 +363,20 @@ export async function syncAll() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[sync] Found ${plugins.length} local plugin(s): ${plugins.map(p => p.dir).join(", ")}`);
|
||||
const concurrency = Math.max(2, Math.min(plugins.length, Math.ceil(os.cpus().length / 2)));
|
||||
console.log(`[sync] Found ${plugins.length} local plugin(s); building with concurrency=${concurrency}`);
|
||||
const started = Date.now();
|
||||
|
||||
for (const plugin of plugins) {
|
||||
const ok = await buildPlugin(plugin);
|
||||
if (ok) syncToPublic(plugin);
|
||||
}
|
||||
let freshCount = 0;
|
||||
let builtCount = 0;
|
||||
await runWithConcurrency(plugins, concurrency, async (plugin) => {
|
||||
const result = await buildPlugin(plugin);
|
||||
if (result === "fresh") freshCount++;
|
||||
else if (result) builtCount++;
|
||||
if (result) syncToPublic(plugin, { quiet: result === "fresh" });
|
||||
});
|
||||
|
||||
console.log(`[sync] Done in ${((Date.now() - started) / 1000).toFixed(1)}s (${builtCount} built, ${freshCount} cached)`);
|
||||
|
||||
const activeIds = plugins.map(p => p.manifest.id || p.dir.replace("wwv-plugin-", ""));
|
||||
cleanStale(activeIds);
|
||||
|
||||
@@ -13,29 +13,84 @@ if (!fs.existsSync(LOCAL_PLUGINS_DIR)) {
|
||||
}
|
||||
|
||||
let debounceTimeout = null;
|
||||
let isSyncing = false;
|
||||
let pendingSync = false;
|
||||
/** Files changed since last sync completed — collected during the debounce window */
|
||||
const pendingChanges = new Set();
|
||||
|
||||
function handleFileChange(eventType, filename) {
|
||||
if (filename && (filename.includes("dist") || filename.includes("node_modules") || filename.endsWith(".map"))) return; // ignore build artifacts
|
||||
|
||||
if (!filename) return;
|
||||
if (
|
||||
filename.includes("dist") ||
|
||||
filename.includes("node_modules") ||
|
||||
filename.endsWith(".map") ||
|
||||
filename.includes(".git")
|
||||
) return; // ignore build artifacts and git internals
|
||||
|
||||
pendingChanges.add(filename);
|
||||
|
||||
if (debounceTimeout) {
|
||||
clearTimeout(debounceTimeout);
|
||||
}
|
||||
|
||||
|
||||
debounceTimeout = setTimeout(async () => {
|
||||
console.log(`\n[watch] Change detected in local plugins (file: ${filename}). Syncing...`);
|
||||
try {
|
||||
await syncAll();
|
||||
} catch (err) {
|
||||
console.error(`[watch] Sync failed:`, err);
|
||||
if (isSyncing) {
|
||||
pendingSync = true;
|
||||
return;
|
||||
}
|
||||
await runSync();
|
||||
}, 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pulls plugin slugs out of changed file paths so we can name what triggered the rebuild.
|
||||
* fs.watch on `local-plugins/` emits paths like `aviation/src/index.ts` (POSIX or Windows).
|
||||
*/
|
||||
function summarizeChangedPlugins(files) {
|
||||
const slugs = new Set();
|
||||
for (const f of files) {
|
||||
const head = f.split(/[\\/]/)[0];
|
||||
if (head) slugs.add(head);
|
||||
}
|
||||
return [...slugs];
|
||||
}
|
||||
|
||||
async function runSync() {
|
||||
isSyncing = true;
|
||||
const changed = summarizeChangedPlugins(pendingChanges);
|
||||
pendingChanges.clear();
|
||||
const label = changed.length === 0
|
||||
? "pending changes"
|
||||
: changed.length <= 3
|
||||
? changed.join(", ")
|
||||
: `${changed.slice(0, 3).join(", ")} (+${changed.length - 3} more)`;
|
||||
console.log(`\n[watch] 🔄 Change detected in: ${label}`);
|
||||
try {
|
||||
await syncAll();
|
||||
console.log(`[watch] ✨ Hot-reload ready`);
|
||||
} catch (err) {
|
||||
console.error(`[watch] Sync failed:`, err);
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
if (pendingSync) {
|
||||
pendingSync = false;
|
||||
await runSync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Initial sync
|
||||
console.log(`[watch] Starting initial sync...`);
|
||||
isSyncing = true;
|
||||
syncAll().then(() => {
|
||||
isSyncing = false;
|
||||
if (pendingSync) {
|
||||
pendingSync = false;
|
||||
runSync("pending changes").catch(console.error);
|
||||
}
|
||||
console.log(`[watch] Watching ${LOCAL_PLUGINS_DIR} for changes...`);
|
||||
fs.watch(LOCAL_PLUGINS_DIR, { recursive: true }, handleFileChange);
|
||||
}).catch(err => {
|
||||
isSyncing = false;
|
||||
console.error(`[watch] Initial sync failed:`, err);
|
||||
});
|
||||
@@ -50,11 +50,11 @@ function isAgentAction(v: unknown): v is AgentAction {
|
||||
if (!v || typeof v !== "object") return false;
|
||||
const a = (v as { action?: unknown }).action;
|
||||
return (
|
||||
a === "fly_to" ||
|
||||
a === "face_towards" ||
|
||||
a === "layer_toggle" ||
|
||||
a === "highlight_layer" ||
|
||||
a === "select_entity" ||
|
||||
a === "ping"
|
||||
a === "fly_to"
|
||||
|| a === "face_towards"
|
||||
|| a === "layer_toggle"
|
||||
|| a === "highlight_layer"
|
||||
|| a === "select_entity"
|
||||
|| a === "ping"
|
||||
);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ export async function GET() {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"Connection": "keep-alive",
|
||||
Connection: "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -22,14 +22,12 @@ function readMaybe(p: string): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
const BUILD_ID =
|
||||
process.env.NEXT_PUBLIC_WWV_BUILD_ID ??
|
||||
readMaybe(path.join(process.cwd(), ".build-id")) ??
|
||||
"dev";
|
||||
const BUILD_AT =
|
||||
process.env.NEXT_PUBLIC_WWV_BUILD_AT ??
|
||||
readMaybe(path.join(process.cwd(), ".build-at")) ??
|
||||
null;
|
||||
const BUILD_ID = process.env.NEXT_PUBLIC_WWV_BUILD_ID
|
||||
?? readMaybe(path.join(process.cwd(), ".build-id"))
|
||||
?? "dev";
|
||||
const BUILD_AT = process.env.NEXT_PUBLIC_WWV_BUILD_AT
|
||||
?? readMaybe(path.join(process.cwd(), ".build-at"))
|
||||
?? null;
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
|
||||
@@ -14,8 +14,7 @@
|
||||
import type { CameraAdapter, CameraFeature } from "./types";
|
||||
|
||||
const BULK_URL = "https://eapps.ncdot.gov/services/traffic-prod/v1/cameras";
|
||||
const DETAIL_URL = (id: number) =>
|
||||
`https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
|
||||
const DETAIL_URL = (id: number) => `https://eapps.ncdot.gov/services/traffic-prod/v1/cameras/${id}`;
|
||||
|
||||
const CONCURRENCY = 20;
|
||||
|
||||
@@ -64,7 +63,8 @@ async function mapWithConcurrency<T, R>(
|
||||
let next = 0;
|
||||
async function run() {
|
||||
while (next < items.length) {
|
||||
const i = next++;
|
||||
const i = next;
|
||||
next += 1;
|
||||
results[i] = await worker(items[i]);
|
||||
}
|
||||
}
|
||||
@@ -113,9 +113,7 @@ export const ncdotAdapter: CameraAdapter = {
|
||||
const bulk = (await bulkRes.json()) as BulkRecord[];
|
||||
if (!Array.isArray(bulk)) return [];
|
||||
|
||||
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) =>
|
||||
fetchDetail(b.id),
|
||||
);
|
||||
const details = await mapWithConcurrency(bulk, CONCURRENCY, (b) => fetchDetail(b.id),);
|
||||
|
||||
const features: CameraFeature[] = [];
|
||||
for (const d of details) {
|
||||
|
||||
@@ -55,8 +55,7 @@ export const osmSurveillanceAdapter: CameraAdapter = {
|
||||
if (!res.ok) throw new Error(`overpass ${res.status}`);
|
||||
const data = (await res.json()) as { elements?: OverpassNode[] };
|
||||
const nodes = (data.elements ?? []).filter(
|
||||
(e): e is OverpassNode =>
|
||||
e.type === "node" && typeof e.lat === "number",
|
||||
(e): e is OverpassNode => e.type === "node" && typeof e.lat === "number",
|
||||
);
|
||||
|
||||
return nodes.map<CameraFeature>((n) => {
|
||||
|
||||
@@ -113,12 +113,10 @@ export async function fetchAdapter(adapter: CameraAdapter): Promise<CameraFeatur
|
||||
try {
|
||||
const data = await Promise.race([
|
||||
adapter.fetch(),
|
||||
new Promise<CameraFeature[]>((_resolve, reject) =>
|
||||
setTimeout(
|
||||
new Promise<CameraFeature[]>((_resolve, reject) => setTimeout(
|
||||
() => reject(new Error(`Adapter ${adapter.id} timed out after ${ADAPTER_FETCH_TIMEOUT_MS}ms`)),
|
||||
ADAPTER_FETCH_TIMEOUT_MS,
|
||||
),
|
||||
),
|
||||
),),
|
||||
]);
|
||||
cache.set(adapter.id, {
|
||||
data,
|
||||
|
||||
@@ -29,7 +29,7 @@ export async function GET(req: NextRequest) {
|
||||
const ajaxRes = await fetch(ajaxUrl, {
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Referer": targetUrl
|
||||
Referer: targetUrl
|
||||
}
|
||||
});
|
||||
const ajaxHtml = await ajaxRes.text();
|
||||
@@ -37,9 +37,8 @@ export async function GET(req: NextRequest) {
|
||||
const streamMatch = ajaxHtml.match(/src:\s*'([^']+m3u8[^']+)'/);
|
||||
if (streamMatch && streamMatch[1]) {
|
||||
return NextResponse.json({ streamUrl: streamMatch[1] });
|
||||
} else {
|
||||
return NextResponse.json({ error: "Could not find m3u8 stream on balticlivecam backend" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ error: "Could not find m3u8 stream on balticlivecam backend" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "Unsupported extractor platform" }, { status: 400 });
|
||||
|
||||
@@ -5,9 +5,8 @@
|
||||
* until all features are retrieved.
|
||||
*/
|
||||
|
||||
const GDOT_BASE =
|
||||
"https://services1.arcgis.com/2iUE8l8JKrP2tygQ/arcgis/rest/services" +
|
||||
"/GDOT_Live_Traffic_Cameras/FeatureServer/0/query";
|
||||
const GDOT_BASE = "https://services1.arcgis.com/2iUE8l8JKrP2tygQ/arcgis/rest/services"
|
||||
+ "/GDOT_Live_Traffic_Cameras/FeatureServer/0/query";
|
||||
|
||||
const PAGE_SIZE = 2000;
|
||||
|
||||
|
||||
@@ -29,9 +29,9 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
try {
|
||||
const upstream = await fetch(targetUrl, {
|
||||
headers: {
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
|
||||
"Accept-Language": "en-US,en;q=0.5",
|
||||
},
|
||||
signal: AbortSignal.timeout(MAX_IFRAME_DURATION_MS),
|
||||
@@ -45,7 +45,7 @@ export async function GET(req: NextRequest) {
|
||||
}
|
||||
|
||||
const contentType = upstream.headers.get("content-type") || "text/html";
|
||||
|
||||
|
||||
// If it's not HTML, just proxy the stream directly (fallback)
|
||||
if (!contentType.includes("text/html")) {
|
||||
return new Response(upstream.body as ReadableStream, {
|
||||
|
||||
@@ -27,7 +27,7 @@ export async function GET(req: NextRequest) {
|
||||
const response = await safeFetch(targetUrl, {
|
||||
headers: {
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
Accept: "application/json, text/plain, */*",
|
||||
},
|
||||
maxSize: 5 * 1024 * 1024, // 5MB
|
||||
timeout: 10000 // 10s
|
||||
|
||||
@@ -48,8 +48,7 @@ export async function GET(req: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const contentType =
|
||||
upstream.headers.get("content-type") || "application/octet-stream";
|
||||
const contentType = upstream.headers.get("content-type") || "application/octet-stream";
|
||||
|
||||
return new Response(upstream.body as ReadableStream, {
|
||||
status: 200,
|
||||
|
||||
@@ -8,7 +8,7 @@ function isPrivateUrl(urlStr: string): boolean {
|
||||
const parsed = new URL(urlStr);
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return true;
|
||||
const host = parsed.hostname;
|
||||
|
||||
|
||||
// If developer overrides local restrictions, bypass checks
|
||||
if (process.env.WWV_PROXY_ALLOW_LOCAL === "true") return false;
|
||||
|
||||
@@ -47,18 +47,19 @@ export async function GET(req: NextRequest) {
|
||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS)
|
||||
});
|
||||
} catch (headError: any) {
|
||||
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
|
||||
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
|
||||
} catch (headError: unknown) {
|
||||
const err = headError as Error & { cause?: { code?: string } };
|
||||
// Primitive IP camera servers (like Insecam sources) often aggressively drop the TCP connection
|
||||
// instead of returning 405 when they see an unsupported HTTP method like HEAD.
|
||||
// If the socket was closed unexpectedly, retry with GET.
|
||||
if (headError.cause?.code === 'UND_ERR_SOCKET' || headError.message?.includes('fetch failed')) {
|
||||
if (err.cause?.code === 'UND_ERR_SOCKET' || err.message?.includes('fetch failed')) {
|
||||
response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: { "User-Agent": "WorldWideView/1.0" },
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS)
|
||||
});
|
||||
} else {
|
||||
throw headError;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,13 +82,14 @@ export async function GET(req: NextRequest) {
|
||||
contentType: response.headers.get("content-type"),
|
||||
latencyMs: Date.now() - startTime
|
||||
});
|
||||
} catch (error: any) {
|
||||
const realError = error.cause || error;
|
||||
const code = realError?.code || error?.code || realError?.name || error?.name;
|
||||
} catch (error: unknown) {
|
||||
const err = error as Error & { cause?: { code?: string, message?: string, name?: string }, code?: string };
|
||||
const realError = err.cause || err;
|
||||
const code = realError?.code || err?.code || realError?.name || err?.name;
|
||||
|
||||
let displayError = error?.message || "Unknown error";
|
||||
let displayError = err?.message || "Unknown error";
|
||||
if (code && code !== 'TypeError' && code !== 'Error') {
|
||||
displayError = `[${code}] ${realError?.message || error?.message || ""}`;
|
||||
displayError = `[${code}] ${realError?.message || err?.message || ""}`;
|
||||
}
|
||||
|
||||
// Make sure we don't accidentally categorize a malformed HTTP response as a timeout
|
||||
@@ -95,7 +97,7 @@ export async function GET(req: NextRequest) {
|
||||
return NextResponse.json({ status: "error", error: displayError, latencyMs: Date.now() - startTime });
|
||||
}
|
||||
|
||||
if (error?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
|
||||
if (err?.name === "TimeoutError" || displayError.includes("timeout") || code === "UND_ERR_CONNECT_TIMEOUT") {
|
||||
return NextResponse.json({ status: "timeout", error: "Connection timed out", latencyMs: Date.now() - startTime });
|
||||
}
|
||||
|
||||
|
||||
@@ -13,8 +13,7 @@
|
||||
|
||||
import type { GdotCameraFeature } from "../gdot/gdotFetcher";
|
||||
|
||||
const WSDOT_BASE =
|
||||
"https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
|
||||
const WSDOT_BASE = "https://wsdot.wa.gov/Traffic/api/HighwayCameras/HighwayCamerasREST.svc/GetCamerasAsJson";
|
||||
|
||||
interface WsdotCamera {
|
||||
CameraID: number;
|
||||
@@ -78,8 +77,8 @@ export async function fetchWsdotCameras(): Promise<GdotCameraFeature[]> {
|
||||
if (!key) {
|
||||
if (!warnedMissingKey) {
|
||||
console.warn(
|
||||
"[WSDOT] WSDOT_API_KEY not set — skipping. " +
|
||||
"Get a free key at https://wsdot.wa.gov/traffic/api/",
|
||||
"[WSDOT] WSDOT_API_KEY not set — skipping. "
|
||||
+ "Get a free key at https://wsdot.wa.gov/traffic/api/",
|
||||
);
|
||||
warnedMissingKey = true;
|
||||
}
|
||||
|
||||
@@ -30,10 +30,10 @@ export async function POST(request: Request) {
|
||||
|
||||
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";
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ export async function GET(
|
||||
|
||||
// Await params as required in Next.js 15+
|
||||
const resolvedParams = await params;
|
||||
const subdomain = resolvedParams.subdomain;
|
||||
const {subdomain} = resolvedParams;
|
||||
|
||||
try {
|
||||
const workspace = await prisma.workspace.findUnique({
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const revalidate = 60;
|
||||
|
||||
const WTIA_POSITIONS_URL = "https://api.wheretheiss.at/v1/satellites/25544/positions";
|
||||
const MAX_TIMESTAMPS = 10;
|
||||
|
||||
function isValidPosition(item: any): boolean {
|
||||
return (
|
||||
item != null
|
||||
&& typeof item === "object"
|
||||
&& Number.isFinite(item.latitude)
|
||||
&& Number.isFinite(item.longitude)
|
||||
&& Number.isFinite(item.altitude)
|
||||
&& Number.isFinite(item.velocity)
|
||||
&& Number.isFinite(item.timestamp)
|
||||
);
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const timestampsParam = searchParams.get("timestamps");
|
||||
|
||||
if (!timestampsParam) {
|
||||
return NextResponse.json(
|
||||
{ error: "Missing required 'timestamps' query parameter" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const timestamps = timestampsParam
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter((t) => /^\d+$/.test(t));
|
||||
|
||||
if (timestamps.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "No valid timestamps provided" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
if (timestamps.length > MAX_TIMESTAMPS) {
|
||||
return NextResponse.json(
|
||||
{ error: `Maximum ${MAX_TIMESTAMPS} timestamps allowed per request` },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const url = `${WTIA_POSITIONS_URL}?timestamps=${timestamps.join(",")}&units=kilometers`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
},
|
||||
next: { revalidate },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ISS positions" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const positions = (Array.isArray(data) ? data : [])
|
||||
.filter(isValidPosition)
|
||||
.map((p) => ({
|
||||
latitude: p.latitude,
|
||||
longitude: p.longitude,
|
||||
altitude: p.altitude,
|
||||
velocity: p.velocity,
|
||||
visibility: p.visibility,
|
||||
timestamp: p.timestamp,
|
||||
}));
|
||||
|
||||
return NextResponse.json({ positions });
|
||||
} catch (error) {
|
||||
console.error("[IssPositionsRoute] Error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ISS positions" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const revalidate = 10;
|
||||
|
||||
const WTIA_URL = "https://api.wheretheiss.at/v1/satellites/25544";
|
||||
|
||||
function isValidResponse(data: any): boolean {
|
||||
return (
|
||||
data != null
|
||||
&& typeof data === "object"
|
||||
&& Number.isFinite(data.latitude)
|
||||
&& Number.isFinite(data.longitude)
|
||||
&& Number.isFinite(data.altitude)
|
||||
&& Number.isFinite(data.velocity)
|
||||
&& Number.isFinite(data.timestamp)
|
||||
);
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const response = await fetch(WTIA_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
},
|
||||
next: { revalidate },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ISS position" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!isValidResponse(data)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid ISS position data" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
id: data.id,
|
||||
name: data.name,
|
||||
latitude: data.latitude,
|
||||
longitude: data.longitude,
|
||||
altitude: data.altitude,
|
||||
velocity: data.velocity,
|
||||
visibility: data.visibility,
|
||||
footprint: data.footprint,
|
||||
timestamp: data.timestamp,
|
||||
units: data.units,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[IssRoute] Error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ISS position" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const revalidate = 3600;
|
||||
|
||||
const WTIA_TLE_URL = "https://api.wheretheiss.at/v1/satellites/25544/tles/latest";
|
||||
|
||||
function isValidTle(data: any): boolean {
|
||||
return (
|
||||
data != null
|
||||
&& typeof data === "object"
|
||||
&& typeof data.line1 === "string"
|
||||
&& typeof data.line2 === "string"
|
||||
&& data.line1.length > 0
|
||||
&& data.line2.length > 0
|
||||
&& Number.isFinite(data.tle_timestamp)
|
||||
);
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const response = await fetch(WTIA_TLE_URL, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "WorldWideView/1.0",
|
||||
},
|
||||
next: { revalidate },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ISS TLE data" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!isValidTle(data)) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid ISS TLE data" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
id: data.id,
|
||||
name: data.name,
|
||||
header: data.header,
|
||||
line1: data.line1,
|
||||
line2: data.line2,
|
||||
tleTimestamp: data.tle_timestamp,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[IssTleRoute] Error:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch ISS TLE data" },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,24 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import * as client from "openid-client";
|
||||
import { encryptCredential } from "@/lib/auth/encryption";
|
||||
import db from "@/lib/db";
|
||||
import { prisma as db } from "@/lib/db";
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const isHttps = req.nextUrl.protocol === "https:";
|
||||
const cookiePrefix = isHttps ? "__Host-" : "";
|
||||
|
||||
|
||||
const stateCookie = req.cookies.get(`${cookiePrefix}pkce_state`)?.value;
|
||||
const verifierCookie = req.cookies.get(`${cookiePrefix}pkce_verifier`)?.value;
|
||||
const urlState = req.nextUrl.searchParams.get("state");
|
||||
|
||||
|
||||
if (!stateCookie || urlState !== stateCookie) {
|
||||
return NextResponse.json({ error: "State mismatch" }, { status: 400 });
|
||||
}
|
||||
|
||||
|
||||
if (!verifierCookie) {
|
||||
return NextResponse.json({ error: "Missing code_verifier" }, { status: 400 });
|
||||
}
|
||||
|
||||
|
||||
const marketplaceUrl = process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL || "https://app.worldwideview.dev";
|
||||
const issuer = new URL(marketplaceUrl);
|
||||
const server = {
|
||||
@@ -25,16 +26,15 @@ export async function GET(req: NextRequest) {
|
||||
authorization_endpoint: new URL("/oauth/authorize", issuer).toString(),
|
||||
token_endpoint: new URL("/api/tickets/exchange", issuer).toString(),
|
||||
};
|
||||
const config = { client_id: "local-app" };
|
||||
const config = { server, clientId: "local-app" };
|
||||
|
||||
try {
|
||||
const tokens = await client.processAuthCodeResponse(
|
||||
server,
|
||||
config,
|
||||
const tokens = await client.authorizationCodeGrant(
|
||||
config as any,
|
||||
new URL(req.url),
|
||||
{ expectedState: stateCookie, pkceCodeVerifier: verifierCookie }
|
||||
);
|
||||
|
||||
|
||||
if (tokens.access_token) {
|
||||
const encrypted = await encryptCredential(tokens.access_token);
|
||||
await db.marketplaceCredential.upsert({
|
||||
@@ -58,9 +58,9 @@ export async function GET(req: NextRequest) {
|
||||
console.error("[PKCE] Exchange failed:", err.message);
|
||||
return NextResponse.json({ error: "Failed to exchange authorization code" }, { status: 500 });
|
||||
}
|
||||
|
||||
|
||||
const res = NextResponse.redirect(new URL("/", req.nextUrl.origin), 302);
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_state`, "", {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -68,7 +68,7 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 0
|
||||
});
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_verifier`, "", {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -76,6 +76,6 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 0
|
||||
});
|
||||
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export async function GET(request: Request) {
|
||||
try {
|
||||
// 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: any) => p.version !== "built-in");
|
||||
|
||||
@@ -24,13 +24,13 @@ export async function GET(request: Request) {
|
||||
const res = await fetch(`${MARKETPLACE_URL}/api/plugins`, {
|
||||
next: { revalidate: 60 } // Cache for 60 seconds
|
||||
});
|
||||
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Marketplace returned ${res.status}`);
|
||||
}
|
||||
|
||||
const marketplacePlugins = await res.json();
|
||||
|
||||
|
||||
// Build a lookup map of Market versions
|
||||
const marketVersions = new Map();
|
||||
for (const p of marketplacePlugins) {
|
||||
@@ -42,7 +42,7 @@ export async function GET(request: Request) {
|
||||
// Compare and flag updates
|
||||
for (const localPlugin of updatablePlugins) {
|
||||
const marketVersion = marketVersions.get(localPlugin.pluginId);
|
||||
|
||||
|
||||
// Only suggest an update if marketplace version exists and differs
|
||||
if (marketVersion && marketVersion !== "0.0.0" && marketVersion !== localPlugin.version) {
|
||||
updates[localPlugin.pluginId] = marketVersion;
|
||||
|
||||
@@ -5,9 +5,9 @@ export async function GET(req: NextRequest) {
|
||||
const state = client.randomState();
|
||||
const code_verifier = client.randomPKCECodeVerifier();
|
||||
const code_challenge = await client.calculatePKCECodeChallenge(code_verifier);
|
||||
|
||||
|
||||
const marketplaceUrl = process.env.NEXT_PUBLIC_WWV_MARKETPLACE_URL || "https://app.worldwideview.dev";
|
||||
|
||||
|
||||
const url = new URL("/oauth/authorize", marketplaceUrl);
|
||||
url.searchParams.set("client_id", "local-app");
|
||||
url.searchParams.set("response_type", "code");
|
||||
@@ -16,12 +16,12 @@ export async function GET(req: NextRequest) {
|
||||
url.searchParams.set("state", state);
|
||||
url.searchParams.set("redirect_uri", `${req.nextUrl.origin}/api/marketplace/callback`);
|
||||
url.searchParams.set("scope", "plugins:read");
|
||||
|
||||
|
||||
const res = NextResponse.redirect(url.toString(), 302);
|
||||
|
||||
|
||||
const isHttps = req.nextUrl.protocol === "https:";
|
||||
const cookiePrefix = isHttps ? "__Host-" : "";
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_state`, state, {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -29,7 +29,7 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 60 * 10 // 10 minutes
|
||||
});
|
||||
|
||||
|
||||
res.cookies.set(`${cookiePrefix}pkce_verifier`, code_verifier, {
|
||||
httpOnly: true,
|
||||
secure: isHttps,
|
||||
@@ -37,6 +37,6 @@ export async function GET(req: NextRequest) {
|
||||
path: "/api/marketplace/callback",
|
||||
maxAge: 60 * 10 // 10 minutes
|
||||
});
|
||||
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -17,8 +17,8 @@ function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return (
|
||||
ALLOWED_REDIRECT_HOSTS.has(parsed.hostname) ||
|
||||
parsed.hostname.endsWith(".worldwideview.dev")
|
||||
ALLOWED_REDIRECT_HOSTS.has(parsed.hostname)
|
||||
|| parsed.hostname.endsWith(".worldwideview.dev")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
@@ -53,7 +53,7 @@ export async function GET(request: NextRequest) {
|
||||
if (!session?.user) {
|
||||
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
|
||||
const callbackPath = request.nextUrl.pathname + request.nextUrl.search;
|
||||
loginUrl.searchParams.set("callbackUrl", callbackPath);
|
||||
|
||||
@@ -24,7 +24,7 @@ if (process.env.ALLOWED_DEV_ORIGIN) {
|
||||
function isSafeRedirect(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
const hostname = parsed.hostname;
|
||||
const {hostname} = parsed;
|
||||
return ALLOWED_REDIRECT_HOSTS.has(hostname) || hostname.endsWith(".worldwideview.dev");
|
||||
} catch {
|
||||
return false;
|
||||
@@ -126,7 +126,6 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
// Token in fragment — never sent to server in logs/referer
|
||||
return NextResponse.redirect(`${successUrl.toString()}#token=${token}`);
|
||||
|
||||
} catch (err) {
|
||||
// Top-level catch: log and redirect to marketplace with error, don't expose raw 500
|
||||
console.error("[install-redirect] Unexpected error:", err);
|
||||
|
||||
@@ -21,8 +21,6 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
|
||||
if (rateLimited) return withCors(rateLimited, request);
|
||||
|
||||
@@ -53,9 +51,9 @@ export async function POST(request: Request) {
|
||||
if (res.ok) {
|
||||
const card = await res.json();
|
||||
finalManifest = { ...card };
|
||||
|
||||
|
||||
// Reconstruct entry URL for plugins that are distributed via NPM.
|
||||
// We also forcefully coerce format to "bundle" here because
|
||||
// We also forcefully coerce format to "bundle" here because
|
||||
// the marketplace cache might still return "static" for plugins we recently converted.
|
||||
if (finalManifest.npmPackage) {
|
||||
const targetVersion = version || finalManifest.version || "1.0.0";
|
||||
@@ -73,9 +71,9 @@ export async function POST(request: Request) {
|
||||
const validation = validateManifest(finalManifest);
|
||||
if (!validation.valid) {
|
||||
console.error(
|
||||
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n` +
|
||||
`Errors: ${validation.errors.join(", ")}\n` +
|
||||
`Evaluated Payload:\n${JSON.stringify(finalManifest, null, 2)}`
|
||||
`[Marketplace Install Route] ❌ MANIFEST VALIDATION FAILED for ${pluginId}\n`
|
||||
+ `Errors: ${validation.errors.join(", ")}\n`
|
||||
+ `Evaluated Payload:\n${JSON.stringify(finalManifest, null, 2)}`
|
||||
);
|
||||
return withCors(
|
||||
NextResponse.json(
|
||||
|
||||
@@ -65,9 +65,7 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
const allRecords = [...records, ...localPlugins];
|
||||
|
||||
|
||||
|
||||
const manifests = allRecords
|
||||
.map((r: any): PluginManifest | null => {
|
||||
try {
|
||||
@@ -92,10 +90,10 @@ export async function GET(request: Request) {
|
||||
// Skip bundle plugins whose entry is a bare module specifier
|
||||
// (e.g. "camera") — cannot be dynamically imported in the browser.
|
||||
if (
|
||||
m.format === "bundle" &&
|
||||
!m.entry.startsWith("/") &&
|
||||
!m.entry.startsWith("./") &&
|
||||
!m.entry.startsWith("http")
|
||||
m.format === "bundle"
|
||||
&& !m.entry.startsWith("/")
|
||||
&& !m.entry.startsWith("./")
|
||||
&& !m.entry.startsWith("http")
|
||||
) return false;
|
||||
|
||||
// For anything that looks like a real manifest, validate it and log if it fails
|
||||
@@ -103,7 +101,7 @@ export async function GET(request: Request) {
|
||||
if (!validation.valid) {
|
||||
const errorMessage = `Manifest validation failed for ${m.id}`;
|
||||
console.error(`[Marketplace API] ${errorMessage}:`, validation.errors);
|
||||
|
||||
|
||||
// Capture in Sentry so we have visibility into malformed third-party plugins
|
||||
Sentry.captureMessage(errorMessage, {
|
||||
level: "error",
|
||||
@@ -131,7 +129,7 @@ export async function GET(request: Request) {
|
||||
if (m.format === "declarative" && m.dataSource) {
|
||||
// Only omit headers and potentially sensitive auth params.
|
||||
// The URL might be needed by the client for polling, but headers like Bearer tokens shouldn't leak.
|
||||
// If the audit explicitly asks to strip URL, maybe just replace it entirely if it's sensitive,
|
||||
// If the audit explicitly asks to strip URL, maybe just replace it entirely if it's sensitive,
|
||||
// but usually headers are the sensitive part. We strip headers.
|
||||
if (m.dataSource.headers) {
|
||||
m.dataSource.headers = {};
|
||||
@@ -146,4 +144,3 @@ export async function GET(request: Request) {
|
||||
return withCors(NextResponse.json({ manifests: [] }), request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
describe, it, expect, vi, beforeEach
|
||||
} from "vitest";
|
||||
import { NextRequest } from "next/server";
|
||||
import { GET as connectRoute } from "./connect/route";
|
||||
import { GET as callbackRoute } from "./callback/route";
|
||||
@@ -10,7 +12,24 @@ vi.mock("openid-client", () => ({
|
||||
discoveryRequest: vi.fn(),
|
||||
processAuthorizationResponse: vi.fn(),
|
||||
validateAuthResponse: vi.fn(),
|
||||
processAuthCodeResponse: vi.fn()
|
||||
authorizationCodeGrant: vi.fn().mockResolvedValue({ access_token: "mock-token" })
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/encryption", () => ({
|
||||
encryptCredential: vi.fn().mockResolvedValue({
|
||||
version: 1,
|
||||
salt: "mock-salt",
|
||||
nonce: "mock-nonce",
|
||||
ciphertext: "mock-ciphertext"
|
||||
})
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
marketplaceCredential: {
|
||||
upsert: vi.fn().mockResolvedValue({})
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
describe("PKCE Flow", () => {
|
||||
@@ -22,14 +41,14 @@ describe("PKCE Flow", () => {
|
||||
it("should generate PKCE parameters and redirect with secure cookies", async () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/connect");
|
||||
const res = await connectRoute(req);
|
||||
|
||||
|
||||
expect(res.status).toBe(302);
|
||||
|
||||
|
||||
// Check redirect URL
|
||||
const location = res.headers.get("Location");
|
||||
expect(location).toContain("response_type=code");
|
||||
expect(location).toContain("code_challenge_method=S256");
|
||||
|
||||
|
||||
// Check cookie flags
|
||||
const cookies = res.headers.get("Set-Cookie");
|
||||
expect(cookies).toBeDefined();
|
||||
@@ -46,7 +65,7 @@ describe("PKCE Flow", () => {
|
||||
it("should reject if state does not match", async () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=wrong-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "State mismatch" });
|
||||
@@ -56,7 +75,7 @@ describe("PKCE Flow", () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
// code_verifier cookie is intentionally omitted
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.json()).toEqual({ error: "Missing code_verifier" });
|
||||
@@ -66,19 +85,19 @@ describe("PKCE Flow", () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
req.cookies.set("__Host-pkce_verifier", "mock-verifier");
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
|
||||
|
||||
const cookies = res.headers.get("Set-Cookie");
|
||||
expect(cookies).toContain("__Host-pkce_state=;");
|
||||
expect(cookies).toContain("Max-Age=0");
|
||||
});
|
||||
|
||||
|
||||
it("should perform openid-client exchange and save encrypted token", async () => {
|
||||
const req = new NextRequest("https://localhost:3000/api/marketplace/callback?state=correct-state&code=test-code");
|
||||
req.cookies.set("__Host-pkce_state", "correct-state");
|
||||
req.cookies.set("__Host-pkce_verifier", "mock-verifier");
|
||||
|
||||
|
||||
const res = await callbackRoute(req);
|
||||
expect(res.status).toBe(302); // Redirect back to marketplace or app
|
||||
});
|
||||
|
||||
@@ -44,8 +44,7 @@ export async function GET(request: Request) {
|
||||
const authError = await validateMarketplaceAuth(request);
|
||||
canManagePlugins = authError === null;
|
||||
}
|
||||
|
||||
|
||||
return withCors(NextResponse.json({ plugins: [], canManagePlugins }), request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,6 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
const rateLimited = marketplaceApiLimiter.check(getClientIp(request));
|
||||
if (rateLimited) return withCors(rateLimited, request);
|
||||
|
||||
@@ -59,4 +57,3 @@ export async function POST(request: Request) {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user