Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94b58069e0 | ||
|
|
28e4e67043 | ||
|
|
594f85afb2 | ||
|
|
b29133fca0 | ||
|
|
ac0092c8a8 | ||
|
|
f0daefd53d |
No files matched your search
@@ -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
|
||||
|
||||
+4
-1
@@ -2,4 +2,7 @@
|
||||
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-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,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
|
||||
@@ -208,7 +208,9 @@ Refer to these skill documents for specialized tasks:
|
||||
- **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.
|
||||
- **Git Worktrees & Database Lifecycle**: We use [Worktrunk](https://github.com/max-sixty/worktrunk) to manage parallel branches and avoid relative path breakage. `git-wt switch --create <branch>` provisions isolated sibling worktrees configured with `.env` files and `pnpm install`. The database port is assigned deterministically based on the directory hash.
|
||||
> [!CAUTION]
|
||||
> You MUST use `git-wt remove` to clean up worktrees. Manually deleting a worktree folder (`rm -rf`) will orphan the associated PostgreSQL Docker volume. If this happens, you must manually run `pnpm run db:prune` in the main repository to reclaim disk space.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-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:
|
||||
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "worldwideview",
|
||||
"version": "2.11.0",
|
||||
"version": "2.14.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -8,7 +8,7 @@
|
||||
"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",
|
||||
@@ -21,6 +21,7 @@
|
||||
"test:mutate": "stryker run",
|
||||
"lint": "eslint .",
|
||||
"db:reset": "npx prisma migrate reset --force",
|
||||
"db:prune": "node scripts/db-prune.mjs",
|
||||
"generate": "prisma generate"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -78,6 +79,7 @@
|
||||
"fast-check": "^4.8.0",
|
||||
"jsdom": "^28.1.0",
|
||||
"rollup-plugin-external-globals": "^0.13.0",
|
||||
"tree-kill": "^1.2.2",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5",
|
||||
"vite": "^8.0.12",
|
||||
|
||||
@@ -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 }>;
|
||||
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[];
|
||||
|
||||
Generated
+3
-956
File diff suppressed because it is too large.
Load diff
@@ -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 {
|
||||
|
||||
@@ -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';
|
||||
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: '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)
|
||||
);
|
||||
@@ -13,29 +13,58 @@ if (!fs.existsSync(LOCAL_PLUGINS_DIR)) {
|
||||
}
|
||||
|
||||
let debounceTimeout = null;
|
||||
let isSyncing = false;
|
||||
let pendingSync = false;
|
||||
|
||||
function handleFileChange(eventType, filename) {
|
||||
if (filename && (filename.includes("dist") || filename.includes("node_modules") || filename.endsWith(".map"))) return; // ignore build artifacts
|
||||
if (filename && (
|
||||
filename.includes("dist") ||
|
||||
filename.includes("node_modules") ||
|
||||
filename.endsWith(".map") ||
|
||||
filename.includes(".git")
|
||||
)) return; // ignore build artifacts and git internals
|
||||
|
||||
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(filename);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
async function runSync(filename) {
|
||||
isSyncing = true;
|
||||
console.log(`\n[watch] Change detected in local plugins (file: ${filename}). Syncing...`);
|
||||
try {
|
||||
await syncAll();
|
||||
} catch (err) {
|
||||
console.error(`[watch] Sync failed:`, err);
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
if (pendingSync) {
|
||||
pendingSync = false;
|
||||
await runSync("pending changes");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
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-" : "";
|
||||
@@ -25,12 +25,11 @@ 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 }
|
||||
);
|
||||
|
||||
@@ -10,7 +10,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", () => {
|
||||
|
||||
@@ -33,13 +33,6 @@ export default function SetupPage() {
|
||||
<h1 className={styles.title}>Welcome to WorldWideView</h1>
|
||||
<p className={styles.subtitle}>Create your admin account to get started</p>
|
||||
|
||||
{/* Legacy Data Detection Banner */}
|
||||
<div className={styles.legacyNotice}>
|
||||
<strong>💡 Upgrading from an older version?</strong>
|
||||
<p>We've detected legacy SQLite data. Once your new Postgres database is connected, you can import your favorites by running the migration command in your terminal.</p>
|
||||
<code>docker compose exec wwv node scripts/migrate-legacy.mjs</code>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className={styles.form}>
|
||||
<label className={styles.label} htmlFor="name">
|
||||
Display Name
|
||||
|
||||
@@ -103,27 +103,3 @@
|
||||
.button:hover { opacity: 0.9; }
|
||||
.button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
.legacyNotice {
|
||||
margin: 1.5rem 0;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 191, 0, 0.05);
|
||||
border: 1px solid rgba(255, 191, 0, 0.3);
|
||||
text-align: left;
|
||||
font-size: 0.8rem;
|
||||
color: #ffbf00;
|
||||
}
|
||||
|
||||
.legacyNotice strong {
|
||||
display: block;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.legacyNotice code {
|
||||
display: block;
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem;
|
||||
background: #000;
|
||||
color: #0f0;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { LayerPanel } from "@/components/panels/LayerPanel";
|
||||
import { EntityInfoCard } from "@/components/panels/EntityInfoCard";
|
||||
import { DataConfigPanel } from "@/components/panels/DataConfig";
|
||||
import CameraStatsPanel from "@/components/panels/CameraStatsPanel";
|
||||
import { Timeline } from "@/components/timeline/Timeline";
|
||||
import { BottomPanelManager } from "@/components/layout/BottomPanelManager";
|
||||
import { TimelineSync } from "@/core/globe/TimelineSync";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { pluginRegistry } from "@/core/plugins/PluginRegistry";
|
||||
@@ -156,7 +156,7 @@ export function AppShell() {
|
||||
trackEvent("platform-boot", { duration });
|
||||
}
|
||||
}, [boot.phase]);
|
||||
const timelineOpen = useStore((s) => s.timelineOpen);
|
||||
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
|
||||
|
||||
const rootClasses = [
|
||||
"app-shell",
|
||||
@@ -165,7 +165,7 @@ export function AppShell() {
|
||||
isBooting && boot.timelineReady ? "boot-timeline" : "",
|
||||
isBooting && boot.controlsReady ? "boot-controls" : "",
|
||||
!isBooting ? "boot-done" : "",
|
||||
!timelineOpen ? "timeline-closed" : "",
|
||||
!activeBottomPanel ? "timeline-closed" : "",
|
||||
].filter(Boolean).join(" ");
|
||||
|
||||
return (
|
||||
@@ -188,7 +188,7 @@ export function AppShell() {
|
||||
<DataConfigPanel />
|
||||
{!isMobile && <CameraStatsPanel />}
|
||||
<EntityInfoCard />
|
||||
<Timeline />
|
||||
<BottomPanelManager />
|
||||
<FloatingVideoManager />
|
||||
{needsReload && <ReloadToast />}
|
||||
<ErrorToast />
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
.bottom-panel-system {
|
||||
position: absolute;
|
||||
bottom: 20px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
width: calc(100% - 40px);
|
||||
max-width: 1200px;
|
||||
}
|
||||
|
||||
.bottom-panel-dock {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
pointer-events: auto;
|
||||
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.dock-btn {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.dock-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.dock-btn.active {
|
||||
background: rgba(43, 115, 255, 0.2);
|
||||
border-color: rgba(43, 115, 255, 0.5);
|
||||
color: #4b8df8;
|
||||
box-shadow: 0 0 15px rgba(43, 115, 255, 0.3);
|
||||
}
|
||||
|
||||
.bottom-panel {
|
||||
width: 100%;
|
||||
border-radius: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
pointer-events: auto;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
/* Transition applied to height in style, but we can animate opacity/transform too */
|
||||
transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.bottom-panel.closed {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.bottom-panel.open {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.bottom-panel-resize-handle {
|
||||
height: 12px;
|
||||
width: 100%;
|
||||
cursor: ns-resize;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
background: transparent;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.bottom-panel-resize-handle:hover .resize-grip {
|
||||
background: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.resize-grip {
|
||||
width: 40px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.bottom-panel-close-btn {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
cursor: pointer;
|
||||
padding: 4px;
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.bottom-panel-close-btn:hover {
|
||||
color: white;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.bottom-panel-content {
|
||||
padding: 24px;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
/* Ensure the content sits below the resize handle */
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Timeline adjustments inside the new panel */
|
||||
.timeline__content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
height: 100%;
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import React, { useRef, useState, useEffect } from "react";
|
||||
import { useStore } from "@/core/state/store";
|
||||
import { pluginManager } from "@/core/plugins/PluginManager";
|
||||
import { Timeline } from "@/components/timeline/Timeline";
|
||||
import "./BottomPanelManager.css";
|
||||
|
||||
export function BottomPanelManager() {
|
||||
const activeBottomPanel = useStore((s) => s.activeBottomPanel);
|
||||
const setActiveBottomPanel = useStore((s) => s.setActiveBottomPanel);
|
||||
const bottomPanelHeight = useStore((s) => s.bottomPanelHeight);
|
||||
const setBottomPanelHeight = useStore((s) => s.setBottomPanelHeight);
|
||||
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const resizeRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Get all registered plugins that provide a bottom panel component
|
||||
const plugins = pluginManager.getAllPlugins().map((p) => p.plugin);
|
||||
const dockablePlugins = plugins.filter((p) => p.getBottomPanelComponent !== undefined);
|
||||
|
||||
// Handle mouse drag for resizing the panel
|
||||
useEffect(() => {
|
||||
if (!isDragging) return;
|
||||
|
||||
const handleMouseMove = (e: MouseEvent) => {
|
||||
// Calculate new height based on distance from bottom of window
|
||||
const newHeight = window.innerHeight - e.clientY;
|
||||
// Clamp between min 200px and max window height - 100px
|
||||
const clampedHeight = Math.max(200, Math.min(newHeight, window.innerHeight - 100));
|
||||
setBottomPanelHeight(clampedHeight);
|
||||
};
|
||||
|
||||
const handleMouseUp = () => {
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
window.addEventListener("mousemove", handleMouseMove);
|
||||
window.addEventListener("mouseup", handleMouseUp);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("mousemove", handleMouseMove);
|
||||
window.removeEventListener("mouseup", handleMouseUp);
|
||||
};
|
||||
}, [isDragging, setBottomPanelHeight]);
|
||||
|
||||
// Handle mobile auto-close on load (legacy behavior from Timeline)
|
||||
useEffect(() => {
|
||||
if (window.innerWidth < 768 && activeBottomPanel !== null) {
|
||||
setActiveBottomPanel(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Render active panel content
|
||||
const renderActivePanelContent = () => {
|
||||
if (activeBottomPanel === "timeline") {
|
||||
return <Timeline />;
|
||||
}
|
||||
|
||||
const activePlugin = dockablePlugins.find(p => p.id === activeBottomPanel);
|
||||
if (activePlugin && activePlugin.getBottomPanelComponent) {
|
||||
const Component = activePlugin.getBottomPanelComponent();
|
||||
return <Component pluginId={activePlugin.id} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bottom-panel-system">
|
||||
{/* Dock: Always visible above the panel */}
|
||||
<div className="bottom-panel-dock">
|
||||
<button
|
||||
className={`dock-btn glass-panel ${activeBottomPanel === "timeline" ? "active" : ""}`}
|
||||
onClick={() => setActiveBottomPanel(activeBottomPanel === "timeline" ? null : "timeline")}
|
||||
title="Timeline"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<polyline points="12 6 12 12 16 14" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{dockablePlugins.map((plugin) => (
|
||||
<button
|
||||
key={plugin.id}
|
||||
className={`dock-btn glass-panel ${activeBottomPanel === plugin.id ? "active" : ""}`}
|
||||
onClick={() => setActiveBottomPanel(activeBottomPanel === plugin.id ? null : plugin.id)}
|
||||
title={plugin.name || plugin.id}
|
||||
>
|
||||
{/* Placeholder icon, a real implementation might use an icon provided by the plugin metadata */}
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
|
||||
<path d="M3 9h18" />
|
||||
</svg>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Active Panel Shell */}
|
||||
<div
|
||||
className={`bottom-panel glass-panel ${activeBottomPanel ? "open" : "closed"}`}
|
||||
style={{ height: activeBottomPanel ? `${bottomPanelHeight}px` : "0px" }}
|
||||
>
|
||||
{activeBottomPanel && (
|
||||
<>
|
||||
<div
|
||||
className="bottom-panel-resize-handle"
|
||||
ref={resizeRef}
|
||||
onMouseDown={() => setIsDragging(true)}
|
||||
>
|
||||
<div className="resize-grip" />
|
||||
</div>
|
||||
<button
|
||||
className="bottom-panel-close-btn"
|
||||
onClick={() => setActiveBottomPanel(null)}
|
||||
title="Close Panel"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M18 6 6 18" />
|
||||
<path d="m6 6 12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="bottom-panel-content">
|
||||
{renderActivePanelContent()}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -30,17 +30,12 @@ export function Timeline() {
|
||||
const setPlaybackSpeed = useStore((s) => s.setPlaybackSpeed);
|
||||
const setPlaybackMode = useStore((s) => s.setPlaybackMode);
|
||||
const timeRange = useStore((s) => s.timeRange);
|
||||
const timelineOpen = useStore((s) => s.timelineOpen);
|
||||
const setTimelineOpen = useStore((s) => s.setTimelineOpen);
|
||||
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [isDemoAdmin, setIsDemoAdmin] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
if (window.innerWidth < 768) {
|
||||
setTimelineOpen(false);
|
||||
}
|
||||
if (!isDemo) return;
|
||||
fetch("/api/auth/session")
|
||||
.then((r) => r.json())
|
||||
@@ -65,31 +60,10 @@ export function Timeline() {
|
||||
const formatTime = (date: Date) =>
|
||||
mounted ? `${date.toLocaleTimeString()} — ${date.toLocaleDateString()}` : "...";
|
||||
|
||||
if (!timelineOpen) {
|
||||
return (
|
||||
<div className="timeline-toggle-wrapper">
|
||||
<button
|
||||
className="timeline-toggle-btn glass-panel"
|
||||
onClick={() => setTimelineOpen(true)}
|
||||
title="Open Timeline"
|
||||
>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<circle cx="12" cy="12" r="10"/>
|
||||
<polyline points="12 6 12 12 16 14"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<div className="timeline glass-panel">
|
||||
<button className="timeline-close-btn" onClick={() => setTimelineOpen(false)} title="Hide Timeline">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M18 6 6 18"/>
|
||||
<path d="m6 6 12 12"/>
|
||||
</svg>
|
||||
</button>
|
||||
<div className="timeline__content">
|
||||
|
||||
{/* Row 1: Controls */}
|
||||
<div className="timeline__controls-row">
|
||||
|
||||
@@ -31,7 +31,8 @@ describe('uiSlice', () => {
|
||||
expect(state.selectedEntity).toBeNull();
|
||||
expect(state.floatingStreams).toEqual([]);
|
||||
expect(state.activeConfigTab).toBe('filters');
|
||||
expect(state.timelineOpen).toBe(true);
|
||||
expect(state.activeBottomPanel).toBeNull();
|
||||
expect(state.bottomPanelHeight).toBe(220);
|
||||
});
|
||||
|
||||
it('toggles simple boolean states', () => {
|
||||
@@ -47,8 +48,11 @@ describe('uiSlice', () => {
|
||||
store.getState().toggleFilterPanel();
|
||||
expect(store.getState().filterPanelOpen).toBe(true);
|
||||
|
||||
store.getState().setTimelineOpen(false);
|
||||
expect(store.getState().timelineOpen).toBe(false);
|
||||
store.getState().setActiveBottomPanel('timeline');
|
||||
expect(store.getState().activeBottomPanel).toBe('timeline');
|
||||
|
||||
store.getState().setBottomPanelHeight(300);
|
||||
expect(store.getState().bottomPanelHeight).toBe(300);
|
||||
|
||||
store.getState().setFeedbackDialogOpen(true);
|
||||
expect(store.getState().feedbackDialogOpen).toBe(true);
|
||||
|
||||
@@ -105,10 +105,17 @@ export interface UISlice {
|
||||
showErrorToast: (message: string) => void;
|
||||
/** Dismisses the active error toast. */
|
||||
clearErrorToast: () => void;
|
||||
/** Visibility of the temporal timeline controller. */
|
||||
timelineOpen: boolean;
|
||||
/** Sets the timeline visibility. */
|
||||
setTimelineOpen: (open: boolean) => void;
|
||||
/**
|
||||
* The ID of the currently active bottom panel, or null when the dock is shown without
|
||||
* an active panel. The built-in timeline uses the reserved ID "timeline".
|
||||
*/
|
||||
activeBottomPanel: string | null;
|
||||
/** Opens a specific bottom panel by ID, or closes all panels if null is passed. */
|
||||
setActiveBottomPanel: (id: string | null) => void;
|
||||
/** Height of the bottom panel in pixels. Clamped between 200 and window height. */
|
||||
bottomPanelHeight: number;
|
||||
/** Sets the bottom panel height (used by the resize drag handle). */
|
||||
setBottomPanelHeight: (height: number) => void;
|
||||
}
|
||||
|
||||
export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => ({
|
||||
@@ -127,7 +134,8 @@ export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => (
|
||||
openMobilePanel: null,
|
||||
mobileRightPanelGlow: false,
|
||||
feedbackDialogOpen: false,
|
||||
timelineOpen: true,
|
||||
activeBottomPanel: null,
|
||||
bottomPanelHeight: 220,
|
||||
toggleTheme: () => set((state) => {
|
||||
const nextTheme = {
|
||||
"dark": "black",
|
||||
@@ -207,6 +215,7 @@ export const createUISlice: StateCreator<AppStore, [], [], UISlice> = (set) => (
|
||||
errorToastMessage: null,
|
||||
showErrorToast: (message) => set({ errorToastMessage: message }),
|
||||
clearErrorToast: () => set({ errorToastMessage: null }),
|
||||
setTimelineOpen: (open) => set({ timelineOpen: open }),
|
||||
setActiveBottomPanel: (id) => set({ activeBottomPanel: id }),
|
||||
setBottomPanelHeight: (height) => set({ bottomPanelHeight: height }),
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user