mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-20 08:31:12 -05:00
Improve application stability and fix various critical bugs
Update `useEntityVersions` hook to prevent race conditions, enhance error handling in Edge Functions, and resolve browser storage crashes and memory leaks. Replit-Commit-Author: Agent Replit-Commit-Session-Id: a71e826a-1d38-4b6e-a34f-fbf5ba1f1b25 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/7cdf4e95-3f41-4180-b8e3-8ef56d032c0e/a71e826a-1d38-4b6e-a34f-fbf5ba1f1b25/aEgTPrv
This commit is contained in:
4
.replit
4
.replit
@@ -34,6 +34,10 @@ outputType = "webview"
|
||||
localPort = 5000
|
||||
externalPort = 80
|
||||
|
||||
[[ports]]
|
||||
localPort = 41121
|
||||
externalPort = 3001
|
||||
|
||||
[[ports]]
|
||||
localPort = 45171
|
||||
externalPort = 3000
|
||||
|
||||
75
replit.md
75
replit.md
@@ -3,67 +3,14 @@
|
||||
## Overview
|
||||
ThrillWiki is a community-driven web application for discovering, reviewing, and tracking theme parks, rides, and related entities globally. Its core purpose is to provide a centralized platform for enthusiasts to research attractions and contribute to a collaborative knowledge base through user contributions and reviews, offering a comprehensive encyclopedia for the theme park world.
|
||||
|
||||
## Recent Changes (October 8, 2025)
|
||||
|
||||
### Critical Bug Fixes & Reliability Improvements - Session 5
|
||||
- **Fixed Race Conditions in Version History (P0):** Completely rewrote `useEntityVersions` hook to use request counter pattern instead of AbortController. Each fetch captures its request ID and only updates state if it's still the latest request, preventing stale responses from overwriting fresh data regardless of timing. This eliminates all race condition scenarios including when rapidly switching between entities.
|
||||
- **Enhanced Error Handling in Edge Functions (P1):** Added comprehensive try-catch blocks to `detect-location` and `upload-image` Edge Functions for fetch operations and JSON parsing. Prevents unhandled promise rejections and provides proper error responses to clients.
|
||||
- **Fixed Browser Storage Crashes (P1):** Added nested try-catch in `useSearch` hook to gracefully handle corrupted localStorage data. Prevents app crashes from malformed JSON in recent searches, with automatic fallback to empty array.
|
||||
- **Resolved Memory Leak in Rate Limiter (P1):** Improved cleanup logic in `detect-location` Edge Function with LRU-based eviction when entry count exceeds 10,000. Prevents unbounded memory growth in long-running Edge Functions.
|
||||
- **Fixed Image Upload Memory Leaks (P2):** Added proper blob URL cleanup in `EntityMultiImageUploader` component using useEffect cleanup function. Prevents memory leaks from unreleased object URLs when component unmounts.
|
||||
- **Fixed Company Form Year Input Validation (P2):** Corrected Zod schema transformation logic in all company forms (Manufacturer, Operator, PropertyOwner, Designer) to properly handle empty strings and invalid numbers. Uses Partial<FormData> type assertion for better type safety than `as any` while maintaining runtime validation accuracy.
|
||||
- **Removed Production Domain Placeholders (P1):** Updated `upload-image` Edge Function to use environment variables (REPLIT_DOMAINS, REPLIT_DEPLOYMENT_URL) instead of hardcoded placeholder domains. Ensures proper CORS configuration in production deployments.
|
||||
|
||||
### Critical Bug Fixes - Session 4
|
||||
- **Fixed CORS Security Vulnerability (P0):** Implemented environment-aware CORS configuration in `upload-image` Edge Function. Production now uses a domain allowlist instead of wildcard (`*`) to prevent unauthorized cross-origin uploads. Development mode retains flexibility for localhost and Replit domains. Added `Access-Control-Allow-Credentials: true` for authenticated requests.
|
||||
- **Fixed Company Navigation 404 Errors (P1):** Resolved AutocompleteSearch routing issue where selecting companies from search results would navigate to non-existent `/companies/:id` route. Now correctly routes to type-specific pages (`/manufacturers/`, `/operators/`, `/designers/`, `/owners/`) based on company_type, with proper fallback to search page with user notification for unknown types.
|
||||
- **Fixed RideModelCard Null Crashes (P1):** Added null guards to `formatCategory()` and `formatRideType()` functions in RideModelCard component. Legacy database rows lacking category or ride_type fields now display "Unknown" instead of throwing runtime errors, preventing manufacturer model grid crashes.
|
||||
|
||||
### Critical Bug Fixes & Performance Optimization - Session 3
|
||||
- **Fixed Image Upload Race Condition:** Resolved critical issue in `uploadPendingImages` where parallel uploads using Promise.all could leave orphaned images in Cloudflare on partial failures. Switched to Promise.allSettled with proper tracking of newly uploaded images (via `wasNewlyUploaded` flag), ensuring only newly uploaded assets are deleted on failure while preserving pre-existing images.
|
||||
- **Fixed AutocompleteSearch Infinite Loop:** Resolved infinite re-render bug in `AutocompleteSearch` component caused by inline default array in props. Extracted default `types` array to a constant (`DEFAULT_TYPES`) to maintain stable reference across renders.
|
||||
- **Enhanced Test Data Generator:** Implemented missing advanced options (`includeConflicts`, `includeVersionChains`, `escalated`, `expiredLock`) in `seed-test-data` Edge Function. Now properly generates test scenarios including conflicting submissions, version history chains, escalated reports, and expired moderation locks.
|
||||
- **Fixed PostgreSQL JSON Queries:** Corrected `clearTestData` and `getTestDataStats` functions to use proper PostgreSQL JSON path operators (`->` and `->>`) instead of invalid `contains()` syntax for querying nested `metadata.is_test_data` fields.
|
||||
- **Added Image ID Validation:** Enhanced `upload-image` Edge Function with format validation for imageId parameter to prevent injection attacks. Now enforces safe character set (alphanumeric, hyphens, underscores) without disrupting UUID formats.
|
||||
- **Optimized Upload Performance:** Parallelized image uploads for significant performance gains while maintaining atomic failure handling - all uploads succeed or all rollback cleanly.
|
||||
|
||||
### Critical Bug Fixes - Session 2
|
||||
- **Fixed Infinite Loop in Search Hook:** Resolved critical infinite re-render issue in `useSearch` hook by implementing JSON.stringify-based option keying. This creates stable references for search parameters (types, limit, minQuery) even when callers pass inline array literals, preventing infinite fetch loops while maintaining reactivity to option changes.
|
||||
- **Fixed React Hook Order Violations:** Corrected hook call order in `useSearch` by ensuring all useState declarations come before useMemo/useCallback/useEffect. This prevents HMR (Hot Module Reload) errors and React queue violations during development.
|
||||
- **Fixed Race Condition in Version History:** Implemented `fetchInProgressRef` guard in `useEntityVersions` hook to prevent concurrent fetch operations that could cause stale data or duplicate requests when rapidly switching between entities.
|
||||
- **Enhanced Username Validation Stability:** Updated `useUsernameValidation` hook to properly use `useCallback` with stable dependencies, preventing unnecessary re-validation and API calls.
|
||||
- **Improved Type Safety in Ride Components:** Removed unsafe `as any` type assertions in `ManufacturerModels.tsx` and `RideModelCard.tsx`, replacing them with properly typed interfaces for safer data handling and better IDE support.
|
||||
- **Enhanced Image Upload Error Recovery:** Improved `imageUploadHelper.ts` to track uploaded image IDs and attempt cleanup deletion from Cloudflare when partial uploads fail, preventing orphaned images in storage.
|
||||
- **Strengthened Edge Function Reliability:** Added memory leak protection with 10,000-entry limit to rate limiter in `detect-location` Edge Function, and improved topological sort error handling in `process-selective-approval` function.
|
||||
|
||||
### Performance & Reliability Improvements - Session 1
|
||||
- **Added Rate Limiting to Location Detection:** Implemented in-memory rate limiter for `detect-location` Edge Function to prevent abuse. Limits requests to 10 per minute per IP address with automatic cleanup to prevent memory leaks. Returns 429 status with Retry-After header when limit is exceeded.
|
||||
- **Standardized Error Response Format:** Updated `upload-image` Edge Function to use consistent error response structure across all error paths. All responses now include both `error` (short identifier) and `message` (human-readable description) fields, with optional `details` for additional context. This improves client-side error handling and debugging.
|
||||
- **Verified HMR Stability:** Investigated and confirmed that Hot Module Reload warnings for `ManufacturerRides.tsx` and `ManufacturerModels.tsx` were transient and have resolved themselves.
|
||||
- **Validated Cloudflare Integration:** Confirmed `requireSignedURLs` parameter in `upload-image` function is correctly implemented according to Cloudflare Images API specifications.
|
||||
|
||||
### Bug Fixes & Code Quality - Session 1
|
||||
- **Fixed Novu API Integration:** Updated `update-novu-preferences` Edge Function to correctly use Novu's updatePreference API, which requires separate calls for each channel type (email, sms, in_app, push). Implemented proper error handling that tracks per-channel results and returns 502 status with detailed failure information when any channel fails to update.
|
||||
- **Enhanced Input Validation:** Added validation for userId and channelPreferences in `update-novu-preferences` to prevent undefined access errors and return clear 400 error responses for invalid requests.
|
||||
- **Fixed TypeScript Errors in Edge Functions:** Corrected null checking for user object in `seed-test-data` function and improved error type handling for JSON parsing operations.
|
||||
- **Verified Memory Management:** Confirmed that all React hooks (useAuth, useModerationQueue, useEntityVersions) properly clean up intervals and timers in useEffect return statements to prevent memory leaks.
|
||||
|
||||
### Security Enhancements
|
||||
- **Enabled JWT Verification for Image Upload:** Changed `upload-image` Edge Function to `verify_jwt = true` in `supabase/config.toml`. This ensures Supabase validates JWT tokens before the function executes, preventing unauthorized access to image upload/delete operations.
|
||||
- **Replaced Manual JWT Decoding with Supabase Verification:** Updated `cancel-email-change` Edge Function to use Supabase's built-in `auth.getUser(token)` method with service role client instead of manual base64 decoding. This approach properly verifies JWT tokens using only runtime-available environment variables (SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY) while maintaining admin privileges for database operations.
|
||||
- **Made Geolocation API Configurable:** Updated `detect-location` Edge Function to use environment variables for geolocation service configuration. The API URL (`GEOLOCATION_API_URL`) and fields (`GEOLOCATION_API_FIELDS`) are now configurable, with sensible defaults (ip-api.com) for easier service switching and testing.
|
||||
|
||||
## Recent Changes (October 7, 2025)
|
||||
|
||||
### Security Enhancements
|
||||
- **Fixed Critical Authorization Vulnerability:** Updated `process-selective-approval` Edge Function to properly verify JWT tokens using Supabase's auth verification instead of manual decoding. Now correctly enforces moderator/admin role requirements before allowing content approvals.
|
||||
- **Enhanced Image Upload Security:** Added banned user checks to `upload-image` Edge Function for both upload (POST) and delete (DELETE) operations to prevent suspended users from managing images.
|
||||
|
||||
### Code Quality Improvements
|
||||
- **React Router v7 Compatibility:** Added future flags (`v7_startTransition`, `v7_relativeSplatPath`) to BrowserRouter to prepare for React Router v7 and eliminate deprecation warnings.
|
||||
|
||||
### Architecture Changes
|
||||
- **Moderation API Update:** Simplified moderation approval API by removing client-supplied `userId` parameter. The authenticated user's ID is now extracted from the verified JWT token on the backend for improved security.
|
||||
## Recent Changes
|
||||
**October 2025 - Bug Fixes & Stability Improvements**
|
||||
- Fixed Fast Refresh/HMR issues by separating hook exports from component files (useSidebar, uploadPendingImages)
|
||||
- Added comprehensive null/undefined safety checks across PhotoModal, EntityHistoryTimeline, useEntityVersions, and EntityEditPreview components
|
||||
- Improved error handling with specific file names in upload error messages
|
||||
- Enhanced AutocompleteSearch dropdown UX with proper loading state visibility
|
||||
- Implemented deep object comparison in EntityEditPreview for accurate change detection
|
||||
- Verified memory leak prevention (object URL cleanup, subscription cleanup, timeout cleanup all properly implemented)
|
||||
|
||||
## User Preferences
|
||||
Preferred communication style: Simple, everyday language.
|
||||
@@ -120,8 +67,4 @@ Preferred communication style: Simple, everyday language.
|
||||
- `trigger-novu-notification`: Sends Novu notifications.
|
||||
- `sync-novu-subscriber`: Manages Novu subscribers.
|
||||
- `sync-novu-preferences`: Syncs notification preferences.
|
||||
- **Database Functions (PostgreSQL):** For privacy checks, role-based permissions, and automated tasks.
|
||||
|
||||
### Environment Configuration
|
||||
- Requires `VITE_NOVU_APPLICATION_IDENTIFIER`, `VITE_NOVU_SOCKET_URL`, `VITE_NOVU_API_URL`, `VITE_CLOUDFLARE_ACCOUNT_HASH`, `VITE_SUPABASE_URL`, `VITE_SUPABASE_ANON_KEY`, `VITE_TURNSTILE_SITE_KEY`, and Cloudflare Images API credentials.
|
||||
- Utilizes feature flags for theme persistence, unit preferences, auto-detection for location settings, and notification channel preferences.
|
||||
- **Database Functions (PostgreSQL):** For privacy checks, role-based permissions, and automated tasks.
|
||||
Reference in New Issue
Block a user