Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14aaf64934 |
@@ -202,7 +202,7 @@ jobs:
|
||||
- name: Install frontend dependencies
|
||||
run: cd frontend && npm ci
|
||||
- name: Type-check frontend
|
||||
run: cd frontend && npm run prep && npm run typecheck:all
|
||||
run: cd frontend && npm run prebuild && npm run typecheck:all
|
||||
- name: Lint frontend
|
||||
run: cd frontend && npm run lint
|
||||
- name: Build frontend
|
||||
|
||||
@@ -158,7 +158,6 @@ __pycache__/
|
||||
|
||||
# Virtual environments
|
||||
.env*
|
||||
!.env*.example
|
||||
.venv*
|
||||
env*/
|
||||
venv*/
|
||||
|
||||
@@ -1,347 +0,0 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to AI Agents when working with code in this repository.
|
||||
|
||||
## Common Development Commands
|
||||
|
||||
### Build and Test
|
||||
- **Build project**: `./gradlew clean build`
|
||||
- **Run locally**: `./gradlew bootRun`
|
||||
- **Full test suite**: `./test.sh` (builds all Docker variants and runs comprehensive tests)
|
||||
- **Code formatting**: `./gradlew spotlessApply` (runs automatically before compilation)
|
||||
|
||||
### Docker Development
|
||||
- **Build ultra-lite**: `docker build -t stirlingtools/stirling-pdf:latest-ultra-lite -f ./Dockerfile.ultra-lite .`
|
||||
- **Build standard**: `docker build -t stirlingtools/stirling-pdf:latest -f ./Dockerfile .`
|
||||
- **Build fat version**: `docker build -t stirlingtools/stirling-pdf:latest-fat -f ./Dockerfile.fat .`
|
||||
- **Example compose files**: Located in `exampleYmlFiles/` directory
|
||||
|
||||
### Security Mode Development
|
||||
Set `DOCKER_ENABLE_SECURITY=true` environment variable to enable security features during development. This is required for testing the full version locally.
|
||||
|
||||
### Frontend Development
|
||||
- **Frontend dev server**: `cd frontend && npm run dev` (requires backend on localhost:8080)
|
||||
- **Tech Stack**: Vite + React + TypeScript + Mantine UI + TailwindCSS
|
||||
- **Proxy Configuration**: Vite proxies `/api/*` calls to backend (localhost:8080)
|
||||
- **Build Process**: DO NOT run build scripts manually - builds are handled by CI/CD pipelines
|
||||
- **Package Installation**: DO NOT run npm install commands - package management handled separately
|
||||
- **Deployment Options**:
|
||||
- **Desktop App**: `npm run tauri-build` (native desktop application)
|
||||
- **Web Server**: `npm run build` then serve dist/ folder
|
||||
- **Development**: `npm run tauri-dev` for desktop dev mode
|
||||
|
||||
#### Environment Variables
|
||||
- All `VITE_*` variables must be declared in the appropriate example file:
|
||||
- `frontend/config/.env.example` — core, proprietary, and shared vars
|
||||
- `frontend/config/.env.saas.example` — SaaS-only vars
|
||||
- `frontend/config/.env.desktop.example` — desktop (Tauri)-only vars
|
||||
- Never use `|| 'hardcoded-fallback'` inline — put defaults in the example files
|
||||
- `npm run prep` / `prep:saas` / `prep:desktop` auto-create the env files from examples on first run, and error if any required keys are missing
|
||||
- These prep scripts run automatically at the start of all `dev*`, `build*`, and `tauri*` commands
|
||||
- See `frontend/README.md#environment-variables` for full documentation
|
||||
|
||||
#### Import Paths - CRITICAL
|
||||
**ALWAYS use `@app/*` for imports.** Do not use `@core/*` or `@proprietary/*` unless explicitly wrapping/extending a lower layer implementation.
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT - Use @app/* for all imports
|
||||
import { AppLayout } from "@app/components/AppLayout";
|
||||
import { useFileContext } from "@app/contexts/FileContext";
|
||||
import { FileContext } from "@app/contexts/FileContext";
|
||||
|
||||
// ❌ WRONG - Do not use @core/* or @proprietary/* in normal code
|
||||
import { AppLayout } from "@core/components/AppLayout";
|
||||
import { useFileContext } from "@proprietary/contexts/FileContext";
|
||||
```
|
||||
|
||||
**Only use explicit aliases when:**
|
||||
- Building layer-specific override that wraps a lower layer's component
|
||||
- Example: `import { AppProviders as CoreAppProviders } from "@core/components/AppProviders"` when creating proprietary/AppProviders.tsx that extends the core version
|
||||
|
||||
The `@app/*` alias automatically resolves to the correct layer based on build target (core/proprietary/desktop) and handles the fallback cascade.
|
||||
|
||||
#### Component Override Pattern (Stub/Shadow)
|
||||
Use this pattern for desktop-specific or proprietary-specific features WITHOUT runtime checks or conditionals.
|
||||
|
||||
**How it works:**
|
||||
1. Core defines stub component (returns null or no-op)
|
||||
2. Desktop/proprietary overrides with same path/name
|
||||
3. Core imports via `@app/*` - higher layer "shadows" core in those builds
|
||||
4. No `@ts-ignore`, no `isTauri()` checks, no runtime conditionals!
|
||||
|
||||
**Example - Desktop-specific footer:**
|
||||
|
||||
```typescript
|
||||
// core/components/rightRail/RightRailFooterExtensions.tsx (stub)
|
||||
interface RightRailFooterExtensionsProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RightRailFooterExtensions(_props: RightRailFooterExtensionsProps) {
|
||||
return null; // Stub - does nothing in web builds
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// desktop/components/rightRail/RightRailFooterExtensions.tsx (real implementation)
|
||||
import { Box } from '@mantine/core';
|
||||
import { BackendHealthIndicator } from '@app/components/BackendHealthIndicator';
|
||||
|
||||
interface RightRailFooterExtensionsProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RightRailFooterExtensions({ className }: RightRailFooterExtensionsProps) {
|
||||
return (
|
||||
<Box className={className}>
|
||||
<BackendHealthIndicator />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// core/components/shared/RightRail.tsx (usage - works in ALL builds)
|
||||
import { RightRailFooterExtensions } from '@app/components/rightRail/RightRailFooterExtensions';
|
||||
|
||||
export function RightRail() {
|
||||
return (
|
||||
<div>
|
||||
{/* In web builds: renders nothing (stub returns null) */}
|
||||
{/* In desktop builds: renders BackendHealthIndicator */}
|
||||
<RightRailFooterExtensions className="right-rail-footer" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Build resolution:**
|
||||
- **Core build**: `@app/*` → `core/*` → Gets stub (returns null)
|
||||
- **Desktop build**: `@app/*` → `desktop/*` → Gets real implementation (shadows core)
|
||||
|
||||
**Benefits:**
|
||||
- No runtime checks or feature flags
|
||||
- Type-safe across all builds
|
||||
- Clean, readable code
|
||||
- Build-time optimization (dead code elimination)
|
||||
|
||||
#### Multi-Tool Workflow Architecture
|
||||
Frontend designed for **stateful document processing**:
|
||||
- Users upload PDFs once, then chain tools (split → merge → compress → view)
|
||||
- File state and processing results persist across tool switches
|
||||
- No file reloading between tools - performance critical for large PDFs (up to 100GB+)
|
||||
|
||||
#### FileContext - Central State Management
|
||||
**Location**: `frontend/src/core/contexts/FileContext.tsx`
|
||||
- **Active files**: Currently loaded PDFs and their variants
|
||||
- **Tool navigation**: Current mode (viewer/pageEditor/fileEditor/toolName)
|
||||
- **Memory management**: PDF document cleanup, blob URL lifecycle, Web Worker management
|
||||
- **IndexedDB persistence**: File storage with thumbnail caching
|
||||
- **Preview system**: Tools can preview results (e.g., Split → Viewer → back to Split) without context pollution
|
||||
|
||||
**Critical**: All file operations go through FileContext. Don't bypass with direct file handling.
|
||||
|
||||
#### Processing Services
|
||||
- **enhancedPDFProcessingService**: Background PDF parsing and manipulation
|
||||
- **thumbnailGenerationService**: Web Worker-based with main-thread fallback
|
||||
- **fileStorage**: IndexedDB with LRU cache management
|
||||
|
||||
#### Memory Management Strategy
|
||||
**Why manual cleanup exists**: Large PDFs (up to 100GB+) through multiple tools accumulate:
|
||||
- PDF.js documents that need explicit .destroy() calls
|
||||
- Blob URLs from tool outputs that need revocation
|
||||
- Web Workers that need termination
|
||||
Without cleanup: browser crashes with memory leaks.
|
||||
|
||||
#### Tool Development
|
||||
|
||||
**Architecture**: Modular hook-based system with clear separation of concerns:
|
||||
|
||||
- **useToolOperation** (`frontend/src/core/hooks/tools/shared/useToolOperation.ts`): Main orchestrator hook
|
||||
- Coordinates all tool operations with consistent interface
|
||||
- Integrates with FileContext for operation tracking
|
||||
- Handles validation, error handling, and UI state management
|
||||
|
||||
- **Supporting Hooks**:
|
||||
- **useToolState**: UI state management (loading, progress, error, files)
|
||||
- **useToolApiCalls**: HTTP requests and file processing
|
||||
- **useToolResources**: Blob URLs, thumbnails, ZIP downloads
|
||||
|
||||
- **Utilities**:
|
||||
- **toolErrorHandler**: Standardized error extraction and i18n support
|
||||
- **toolResponseProcessor**: API response handling (single/zip/custom)
|
||||
- **toolOperationTracker**: FileContext integration utilities
|
||||
|
||||
**Three Tool Patterns**:
|
||||
|
||||
**Pattern 1: Single-File Tools** (Individual processing)
|
||||
- Backend processes one file per API call
|
||||
- Set `multiFileEndpoint: false`
|
||||
- Examples: Compress, Rotate
|
||||
```typescript
|
||||
return useToolOperation({
|
||||
operationType: 'compress',
|
||||
endpoint: '/api/v1/misc/compress-pdf',
|
||||
buildFormData: (params, file: File) => { /* single file */ },
|
||||
multiFileEndpoint: false,
|
||||
});
|
||||
```
|
||||
|
||||
**Pattern 2: Multi-File Tools** (Batch processing)
|
||||
- Backend accepts `MultipartFile[]` arrays in single API call
|
||||
- Set `multiFileEndpoint: true`
|
||||
- Examples: Split, Merge, Overlay
|
||||
```typescript
|
||||
return useToolOperation({
|
||||
operationType: 'split',
|
||||
endpoint: '/api/v1/general/split-pages',
|
||||
buildFormData: (params, files: File[]) => { /* all files */ },
|
||||
multiFileEndpoint: true,
|
||||
filePrefix: 'split_',
|
||||
});
|
||||
```
|
||||
|
||||
**Pattern 3: Complex Tools** (Custom processing)
|
||||
- Tools with complex routing logic or non-standard processing
|
||||
- Provide `customProcessor` for full control
|
||||
- Examples: Convert, OCR
|
||||
```typescript
|
||||
return useToolOperation({
|
||||
operationType: 'convert',
|
||||
customProcessor: async (params, files) => { /* custom logic */ },
|
||||
});
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **No Timeouts**: Operations run until completion (supports 100GB+ files)
|
||||
- **Consistent**: All tools follow same pattern and interface
|
||||
- **Maintainable**: Single responsibility hooks, easy to test and modify
|
||||
- **i18n Ready**: Built-in internationalization support
|
||||
- **Type Safe**: Full TypeScript support with generic interfaces
|
||||
- **Memory Safe**: Automatic resource cleanup and blob URL management
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### Project Structure
|
||||
- **Backend**: Spring Boot application
|
||||
- **Frontend**: React-based SPA in `/frontend` directory
|
||||
- **File Storage**: IndexedDB for client-side file persistence and thumbnails
|
||||
- **Internationalization**: JSON-based translations (converted from backend .properties)
|
||||
- **PDF Processing**: PDFBox for core PDF operations, LibreOffice for conversions, PDF.js for client-side rendering
|
||||
- **Security**: Spring Security with optional authentication (controlled by `DOCKER_ENABLE_SECURITY`)
|
||||
- **Configuration**: YAML-based configuration with environment variable overrides
|
||||
|
||||
### Controller Architecture
|
||||
- **API Controllers** (`src/main/java/.../controller/api/`): REST endpoints for PDF operations
|
||||
- Organized by function: converters, security, misc, pipeline
|
||||
- Follow pattern: `@RestController` + `@RequestMapping("/api/v1/...")`
|
||||
|
||||
### Key Components
|
||||
- **SPDFApplication.java**: Main application class with desktop UI and browser launching logic
|
||||
- **ConfigInitializer**: Handles runtime configuration and settings files
|
||||
- **Pipeline System**: Automated PDF processing workflows via `PipelineController`
|
||||
- **Security Layer**: Authentication, authorization, and user management (when enabled)
|
||||
|
||||
### Frontend Directory Structure
|
||||
The frontend is organized with a clear separation of concerns:
|
||||
|
||||
- **`frontend/src/core/`**: Main application code (shared, production-ready components)
|
||||
- **`core/components/`**: React components organized by feature
|
||||
- `core/components/tools/`: Individual PDF tool implementations
|
||||
- `core/components/viewer/`: PDF viewer components
|
||||
- `core/components/pageEditor/`: Page manipulation UI
|
||||
- `core/components/tooltips/`: Help tooltips for tools
|
||||
- `core/components/shared/`: Reusable UI components
|
||||
- **`core/contexts/`**: React Context providers
|
||||
- `FileContext.tsx`: Central file state management
|
||||
- `file/`: File reducer and selectors
|
||||
- `toolWorkflow/`: Tool workflow state
|
||||
- **`core/hooks/`**: Custom React hooks
|
||||
- `hooks/tools/`: Tool-specific operation hooks (one directory per tool)
|
||||
- `hooks/tools/shared/`: Shared hook utilities (useToolOperation, etc.)
|
||||
- **`core/constants/`**: Application constants and configuration
|
||||
- **`core/data/`**: Static data (tool taxonomy, etc.)
|
||||
- **`core/services/`**: Business logic services (PDF processing, storage, etc.)
|
||||
|
||||
- **`frontend/src/desktop/`**: Desktop-specific (Tauri) code
|
||||
- **`frontend/src/proprietary/`**: Proprietary/licensed features
|
||||
- **`frontend/src-tauri/`**: Tauri (Rust) native desktop application code
|
||||
- **`frontend/public/`**: Static assets served directly
|
||||
- `public/locales/`: Translation JSON files
|
||||
|
||||
### Component Architecture
|
||||
- **Static Assets**: CSS, JS, and resources in `src/main/resources/static/` (legacy) + `frontend/public/` (modern)
|
||||
- **Internationalization**:
|
||||
- Backend: `messages_*.properties` files
|
||||
- Frontend: JSON files in `frontend/public/locales/` (converted from .properties)
|
||||
- Conversion Script: `scripts/convert_properties_to_json.py`
|
||||
|
||||
### Configuration Modes
|
||||
- **Ultra-lite**: Basic PDF operations only
|
||||
- **Standard**: Full feature set
|
||||
- **Fat**: Pre-downloaded dependencies for air-gapped environments
|
||||
- **Security Mode**: Adds authentication, user management, and enterprise features
|
||||
|
||||
### Testing Strategy
|
||||
- **Integration Tests**: Cucumber tests in `testing/cucumber/`
|
||||
- **Docker Testing**: `test.sh` validates all Docker variants
|
||||
- **Manual Testing**: No unit tests currently - relies on UI and API testing
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. **Local Development**:
|
||||
- Backend: `./gradlew bootRun` (runs on localhost:8080)
|
||||
- Frontend: `cd frontend && npm run dev` (runs on localhost:5173, proxies to backend)
|
||||
2. **Docker Testing**: Use `./test.sh` before submitting PRs
|
||||
3. **Code Style**: Spotless enforces Google Java Format automatically
|
||||
4. **Translations**:
|
||||
- Backend: Use helper scripts in `/scripts` for multi-language updates
|
||||
- Frontend: Update JSON files in `frontend/public/locales/` or use conversion script
|
||||
5. **Documentation**: API docs auto-generated and available at `/swagger-ui/index.html`
|
||||
|
||||
## Frontend Architecture Status
|
||||
|
||||
- **Core Status**: React SPA architecture complete with multi-tool workflow support
|
||||
- **State Management**: FileContext handles all file operations and tool navigation
|
||||
- **File Processing**: Production-ready with memory management for large PDF workflows (up to 100GB+)
|
||||
- **Tool Integration**: Modular hook architecture with `useToolOperation` orchestrator
|
||||
- Individual hooks: `useToolState`, `useToolApiCalls`, `useToolResources`
|
||||
- Utilities: `toolErrorHandler`, `toolResponseProcessor`, `toolOperationTracker`
|
||||
- Pattern: Each tool creates focused operation hook, UI consumes state/actions
|
||||
- **Preview System**: Tool results can be previewed without polluting file context (Split tool example)
|
||||
- **Performance**: Web Worker thumbnails, IndexedDB persistence, background processing
|
||||
|
||||
## Translation Rules
|
||||
|
||||
- **CRITICAL**: Always update translations in `en-GB` only, never `en-US`
|
||||
- Translation files are located in `frontend/public/locales/`
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Java Version**: Minimum JDK 21, supports and recommends JDK 25
|
||||
- **Lombok**: Used extensively - ensure IDE plugin is installed
|
||||
- **File Persistence**:
|
||||
- **Backend**: Designed to be stateless - files are processed in memory/temp locations only
|
||||
- **Frontend**: Uses IndexedDB for client-side file storage and caching (with thumbnails)
|
||||
- **Security**: When `DOCKER_ENABLE_SECURITY=false`, security-related classes are excluded from compilation
|
||||
- **Import Paths**: ALWAYS use `@app/*` for imports - never use `@core/*` or `@proprietary/*` unless explicitly wrapping/extending a lower layer
|
||||
- **FileContext**: All file operations MUST go through FileContext - never bypass with direct File handling
|
||||
- **Memory Management**: Manual cleanup required for PDF.js documents and blob URLs - don't remove cleanup code
|
||||
- **Tool Development**: New tools should follow `useToolOperation` hook pattern (see `useCompressOperation.ts`)
|
||||
- **Performance Target**: Must handle PDFs up to 100GB+ without browser crashes
|
||||
- **Preview System**: Tools can preview results without polluting main file context (see Split tool implementation)
|
||||
- **Adding Tools**: See `ADDING_TOOLS.md` for complete guide to creating new PDF tools
|
||||
|
||||
## Communication Style
|
||||
- Be direct and to the point
|
||||
- No apologies or conversational filler
|
||||
- Answer questions directly without preamble
|
||||
- Explain reasoning concisely when asked
|
||||
- Avoid unnecessary elaboration
|
||||
|
||||
## Decision Making
|
||||
- Ask clarifying questions before making assumptions
|
||||
- Stop and ask when uncertain about project-specific details
|
||||
- Confirm approach before making structural changes
|
||||
- Request guidance on preferences (cross-platform vs specific tools, etc.)
|
||||
- Verify understanding of requirements before proceeding
|
||||
@@ -0,0 +1,337 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Common Development Commands
|
||||
|
||||
### Build and Test
|
||||
- **Build project**: `./gradlew clean build`
|
||||
- **Run locally**: `./gradlew bootRun`
|
||||
- **Full test suite**: `./test.sh` (builds all Docker variants and runs comprehensive tests)
|
||||
- **Code formatting**: `./gradlew spotlessApply` (runs automatically before compilation)
|
||||
|
||||
### Docker Development
|
||||
- **Build ultra-lite**: `docker build -t stirlingtools/stirling-pdf:latest-ultra-lite -f ./Dockerfile.ultra-lite .`
|
||||
- **Build standard**: `docker build -t stirlingtools/stirling-pdf:latest -f ./Dockerfile .`
|
||||
- **Build fat version**: `docker build -t stirlingtools/stirling-pdf:latest-fat -f ./Dockerfile.fat .`
|
||||
- **Example compose files**: Located in `exampleYmlFiles/` directory
|
||||
|
||||
### Security Mode Development
|
||||
Set `DOCKER_ENABLE_SECURITY=true` environment variable to enable security features during development. This is required for testing the full version locally.
|
||||
|
||||
### Frontend Development
|
||||
- **Frontend dev server**: `cd frontend && npm run dev` (requires backend on localhost:8080)
|
||||
- **Tech Stack**: Vite + React + TypeScript + Mantine UI + TailwindCSS
|
||||
- **Proxy Configuration**: Vite proxies `/api/*` calls to backend (localhost:8080)
|
||||
- **Build Process**: DO NOT run build scripts manually - builds are handled by CI/CD pipelines
|
||||
- **Package Installation**: DO NOT run npm install commands - package management handled separately
|
||||
- **Deployment Options**:
|
||||
- **Desktop App**: `npm run tauri-build` (native desktop application)
|
||||
- **Web Server**: `npm run build` then serve dist/ folder
|
||||
- **Development**: `npm run tauri-dev` for desktop dev mode
|
||||
|
||||
#### Import Paths - CRITICAL
|
||||
**ALWAYS use `@app/*` for imports.** Do not use `@core/*` or `@proprietary/*` unless explicitly wrapping/extending a lower layer implementation.
|
||||
|
||||
```typescript
|
||||
// ✅ CORRECT - Use @app/* for all imports
|
||||
import { AppLayout } from "@app/components/AppLayout";
|
||||
import { useFileContext } from "@app/contexts/FileContext";
|
||||
import { FileContext } from "@app/contexts/FileContext";
|
||||
|
||||
// ❌ WRONG - Do not use @core/* or @proprietary/* in normal code
|
||||
import { AppLayout } from "@core/components/AppLayout";
|
||||
import { useFileContext } from "@proprietary/contexts/FileContext";
|
||||
```
|
||||
|
||||
**Only use explicit aliases when:**
|
||||
- Building layer-specific override that wraps a lower layer's component
|
||||
- Example: `import { AppProviders as CoreAppProviders } from "@core/components/AppProviders"` when creating proprietary/AppProviders.tsx that extends the core version
|
||||
|
||||
The `@app/*` alias automatically resolves to the correct layer based on build target (core/proprietary/desktop) and handles the fallback cascade.
|
||||
|
||||
#### Component Override Pattern (Stub/Shadow)
|
||||
Use this pattern for desktop-specific or proprietary-specific features WITHOUT runtime checks or conditionals.
|
||||
|
||||
**How it works:**
|
||||
1. Core defines stub component (returns null or no-op)
|
||||
2. Desktop/proprietary overrides with same path/name
|
||||
3. Core imports via `@app/*` - higher layer "shadows" core in those builds
|
||||
4. No `@ts-ignore`, no `isTauri()` checks, no runtime conditionals!
|
||||
|
||||
**Example - Desktop-specific footer:**
|
||||
|
||||
```typescript
|
||||
// core/components/rightRail/RightRailFooterExtensions.tsx (stub)
|
||||
interface RightRailFooterExtensionsProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RightRailFooterExtensions(_props: RightRailFooterExtensionsProps) {
|
||||
return null; // Stub - does nothing in web builds
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// desktop/components/rightRail/RightRailFooterExtensions.tsx (real implementation)
|
||||
import { Box } from '@mantine/core';
|
||||
import { BackendHealthIndicator } from '@app/components/BackendHealthIndicator';
|
||||
|
||||
interface RightRailFooterExtensionsProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RightRailFooterExtensions({ className }: RightRailFooterExtensionsProps) {
|
||||
return (
|
||||
<Box className={className}>
|
||||
<BackendHealthIndicator />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
// core/components/shared/RightRail.tsx (usage - works in ALL builds)
|
||||
import { RightRailFooterExtensions } from '@app/components/rightRail/RightRailFooterExtensions';
|
||||
|
||||
export function RightRail() {
|
||||
return (
|
||||
<div>
|
||||
{/* In web builds: renders nothing (stub returns null) */}
|
||||
{/* In desktop builds: renders BackendHealthIndicator */}
|
||||
<RightRailFooterExtensions className="right-rail-footer" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Build resolution:**
|
||||
- **Core build**: `@app/*` → `core/*` → Gets stub (returns null)
|
||||
- **Desktop build**: `@app/*` → `desktop/*` → Gets real implementation (shadows core)
|
||||
|
||||
**Benefits:**
|
||||
- No runtime checks or feature flags
|
||||
- Type-safe across all builds
|
||||
- Clean, readable code
|
||||
- Build-time optimization (dead code elimination)
|
||||
|
||||
#### Multi-Tool Workflow Architecture
|
||||
Frontend designed for **stateful document processing**:
|
||||
- Users upload PDFs once, then chain tools (split → merge → compress → view)
|
||||
- File state and processing results persist across tool switches
|
||||
- No file reloading between tools - performance critical for large PDFs (up to 100GB+)
|
||||
|
||||
#### FileContext - Central State Management
|
||||
**Location**: `frontend/src/core/contexts/FileContext.tsx`
|
||||
- **Active files**: Currently loaded PDFs and their variants
|
||||
- **Tool navigation**: Current mode (viewer/pageEditor/fileEditor/toolName)
|
||||
- **Memory management**: PDF document cleanup, blob URL lifecycle, Web Worker management
|
||||
- **IndexedDB persistence**: File storage with thumbnail caching
|
||||
- **Preview system**: Tools can preview results (e.g., Split → Viewer → back to Split) without context pollution
|
||||
|
||||
**Critical**: All file operations go through FileContext. Don't bypass with direct file handling.
|
||||
|
||||
#### Processing Services
|
||||
- **enhancedPDFProcessingService**: Background PDF parsing and manipulation
|
||||
- **thumbnailGenerationService**: Web Worker-based with main-thread fallback
|
||||
- **fileStorage**: IndexedDB with LRU cache management
|
||||
|
||||
#### Memory Management Strategy
|
||||
**Why manual cleanup exists**: Large PDFs (up to 100GB+) through multiple tools accumulate:
|
||||
- PDF.js documents that need explicit .destroy() calls
|
||||
- Blob URLs from tool outputs that need revocation
|
||||
- Web Workers that need termination
|
||||
Without cleanup: browser crashes with memory leaks.
|
||||
|
||||
#### Tool Development
|
||||
|
||||
**Architecture**: Modular hook-based system with clear separation of concerns:
|
||||
|
||||
- **useToolOperation** (`frontend/src/core/hooks/tools/shared/useToolOperation.ts`): Main orchestrator hook
|
||||
- Coordinates all tool operations with consistent interface
|
||||
- Integrates with FileContext for operation tracking
|
||||
- Handles validation, error handling, and UI state management
|
||||
|
||||
- **Supporting Hooks**:
|
||||
- **useToolState**: UI state management (loading, progress, error, files)
|
||||
- **useToolApiCalls**: HTTP requests and file processing
|
||||
- **useToolResources**: Blob URLs, thumbnails, ZIP downloads
|
||||
|
||||
- **Utilities**:
|
||||
- **toolErrorHandler**: Standardized error extraction and i18n support
|
||||
- **toolResponseProcessor**: API response handling (single/zip/custom)
|
||||
- **toolOperationTracker**: FileContext integration utilities
|
||||
|
||||
**Three Tool Patterns**:
|
||||
|
||||
**Pattern 1: Single-File Tools** (Individual processing)
|
||||
- Backend processes one file per API call
|
||||
- Set `multiFileEndpoint: false`
|
||||
- Examples: Compress, Rotate
|
||||
```typescript
|
||||
return useToolOperation({
|
||||
operationType: 'compress',
|
||||
endpoint: '/api/v1/misc/compress-pdf',
|
||||
buildFormData: (params, file: File) => { /* single file */ },
|
||||
multiFileEndpoint: false,
|
||||
});
|
||||
```
|
||||
|
||||
**Pattern 2: Multi-File Tools** (Batch processing)
|
||||
- Backend accepts `MultipartFile[]` arrays in single API call
|
||||
- Set `multiFileEndpoint: true`
|
||||
- Examples: Split, Merge, Overlay
|
||||
```typescript
|
||||
return useToolOperation({
|
||||
operationType: 'split',
|
||||
endpoint: '/api/v1/general/split-pages',
|
||||
buildFormData: (params, files: File[]) => { /* all files */ },
|
||||
multiFileEndpoint: true,
|
||||
filePrefix: 'split_',
|
||||
});
|
||||
```
|
||||
|
||||
**Pattern 3: Complex Tools** (Custom processing)
|
||||
- Tools with complex routing logic or non-standard processing
|
||||
- Provide `customProcessor` for full control
|
||||
- Examples: Convert, OCR
|
||||
```typescript
|
||||
return useToolOperation({
|
||||
operationType: 'convert',
|
||||
customProcessor: async (params, files) => { /* custom logic */ },
|
||||
});
|
||||
```
|
||||
|
||||
**Benefits**:
|
||||
- **No Timeouts**: Operations run until completion (supports 100GB+ files)
|
||||
- **Consistent**: All tools follow same pattern and interface
|
||||
- **Maintainable**: Single responsibility hooks, easy to test and modify
|
||||
- **i18n Ready**: Built-in internationalization support
|
||||
- **Type Safe**: Full TypeScript support with generic interfaces
|
||||
- **Memory Safe**: Automatic resource cleanup and blob URL management
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
### Project Structure
|
||||
- **Backend**: Spring Boot application
|
||||
- **Frontend**: React-based SPA in `/frontend` directory
|
||||
- **File Storage**: IndexedDB for client-side file persistence and thumbnails
|
||||
- **Internationalization**: JSON-based translations (converted from backend .properties)
|
||||
- **PDF Processing**: PDFBox for core PDF operations, LibreOffice for conversions, PDF.js for client-side rendering
|
||||
- **Security**: Spring Security with optional authentication (controlled by `DOCKER_ENABLE_SECURITY`)
|
||||
- **Configuration**: YAML-based configuration with environment variable overrides
|
||||
|
||||
### Controller Architecture
|
||||
- **API Controllers** (`src/main/java/.../controller/api/`): REST endpoints for PDF operations
|
||||
- Organized by function: converters, security, misc, pipeline
|
||||
- Follow pattern: `@RestController` + `@RequestMapping("/api/v1/...")`
|
||||
|
||||
### Key Components
|
||||
- **SPDFApplication.java**: Main application class with desktop UI and browser launching logic
|
||||
- **ConfigInitializer**: Handles runtime configuration and settings files
|
||||
- **Pipeline System**: Automated PDF processing workflows via `PipelineController`
|
||||
- **Security Layer**: Authentication, authorization, and user management (when enabled)
|
||||
|
||||
### Frontend Directory Structure
|
||||
The frontend is organized with a clear separation of concerns:
|
||||
|
||||
- **`frontend/src/core/`**: Main application code (shared, production-ready components)
|
||||
- **`core/components/`**: React components organized by feature
|
||||
- `core/components/tools/`: Individual PDF tool implementations
|
||||
- `core/components/viewer/`: PDF viewer components
|
||||
- `core/components/pageEditor/`: Page manipulation UI
|
||||
- `core/components/tooltips/`: Help tooltips for tools
|
||||
- `core/components/shared/`: Reusable UI components
|
||||
- **`core/contexts/`**: React Context providers
|
||||
- `FileContext.tsx`: Central file state management
|
||||
- `file/`: File reducer and selectors
|
||||
- `toolWorkflow/`: Tool workflow state
|
||||
- **`core/hooks/`**: Custom React hooks
|
||||
- `hooks/tools/`: Tool-specific operation hooks (one directory per tool)
|
||||
- `hooks/tools/shared/`: Shared hook utilities (useToolOperation, etc.)
|
||||
- **`core/constants/`**: Application constants and configuration
|
||||
- **`core/data/`**: Static data (tool taxonomy, etc.)
|
||||
- **`core/services/`**: Business logic services (PDF processing, storage, etc.)
|
||||
|
||||
- **`frontend/src/desktop/`**: Desktop-specific (Tauri) code
|
||||
- **`frontend/src/proprietary/`**: Proprietary/licensed features
|
||||
- **`frontend/src-tauri/`**: Tauri (Rust) native desktop application code
|
||||
- **`frontend/public/`**: Static assets served directly
|
||||
- `public/locales/`: Translation JSON files
|
||||
|
||||
### Component Architecture
|
||||
- **Static Assets**: CSS, JS, and resources in `src/main/resources/static/` (legacy) + `frontend/public/` (modern)
|
||||
- **Internationalization**:
|
||||
- Backend: `messages_*.properties` files
|
||||
- Frontend: JSON files in `frontend/public/locales/` (converted from .properties)
|
||||
- Conversion Script: `scripts/convert_properties_to_json.py`
|
||||
|
||||
### Configuration Modes
|
||||
- **Ultra-lite**: Basic PDF operations only
|
||||
- **Standard**: Full feature set
|
||||
- **Fat**: Pre-downloaded dependencies for air-gapped environments
|
||||
- **Security Mode**: Adds authentication, user management, and enterprise features
|
||||
|
||||
### Testing Strategy
|
||||
- **Integration Tests**: Cucumber tests in `testing/cucumber/`
|
||||
- **Docker Testing**: `test.sh` validates all Docker variants
|
||||
- **Manual Testing**: No unit tests currently - relies on UI and API testing
|
||||
|
||||
## Development Workflow
|
||||
|
||||
1. **Local Development**:
|
||||
- Backend: `./gradlew bootRun` (runs on localhost:8080)
|
||||
- Frontend: `cd frontend && npm run dev` (runs on localhost:5173, proxies to backend)
|
||||
2. **Docker Testing**: Use `./test.sh` before submitting PRs
|
||||
3. **Code Style**: Spotless enforces Google Java Format automatically
|
||||
4. **Translations**:
|
||||
- Backend: Use helper scripts in `/scripts` for multi-language updates
|
||||
- Frontend: Update JSON files in `frontend/public/locales/` or use conversion script
|
||||
5. **Documentation**: API docs auto-generated and available at `/swagger-ui/index.html`
|
||||
|
||||
## Frontend Architecture Status
|
||||
|
||||
- **Core Status**: React SPA architecture complete with multi-tool workflow support
|
||||
- **State Management**: FileContext handles all file operations and tool navigation
|
||||
- **File Processing**: Production-ready with memory management for large PDF workflows (up to 100GB+)
|
||||
- **Tool Integration**: Modular hook architecture with `useToolOperation` orchestrator
|
||||
- Individual hooks: `useToolState`, `useToolApiCalls`, `useToolResources`
|
||||
- Utilities: `toolErrorHandler`, `toolResponseProcessor`, `toolOperationTracker`
|
||||
- Pattern: Each tool creates focused operation hook, UI consumes state/actions
|
||||
- **Preview System**: Tool results can be previewed without polluting file context (Split tool example)
|
||||
- **Performance**: Web Worker thumbnails, IndexedDB persistence, background processing
|
||||
|
||||
## Translation Rules
|
||||
|
||||
- **CRITICAL**: Always update translations in `en-GB` only, never `en-US`
|
||||
- Translation files are located in `frontend/public/locales/`
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Java Version**: Minimum JDK 21, supports and recommends JDK 25
|
||||
- **Lombok**: Used extensively - ensure IDE plugin is installed
|
||||
- **File Persistence**:
|
||||
- **Backend**: Designed to be stateless - files are processed in memory/temp locations only
|
||||
- **Frontend**: Uses IndexedDB for client-side file storage and caching (with thumbnails)
|
||||
- **Security**: When `DOCKER_ENABLE_SECURITY=false`, security-related classes are excluded from compilation
|
||||
- **Import Paths**: ALWAYS use `@app/*` for imports - never use `@core/*` or `@proprietary/*` unless explicitly wrapping/extending a lower layer
|
||||
- **FileContext**: All file operations MUST go through FileContext - never bypass with direct File handling
|
||||
- **Memory Management**: Manual cleanup required for PDF.js documents and blob URLs - don't remove cleanup code
|
||||
- **Tool Development**: New tools should follow `useToolOperation` hook pattern (see `useCompressOperation.ts`)
|
||||
- **Performance Target**: Must handle PDFs up to 100GB+ without browser crashes
|
||||
- **Preview System**: Tools can preview results without polluting main file context (see Split tool implementation)
|
||||
- **Adding Tools**: See `ADDING_TOOLS.md` for complete guide to creating new PDF tools
|
||||
|
||||
## Communication Style
|
||||
- Be direct and to the point
|
||||
- No apologies or conversational filler
|
||||
- Answer questions directly without preamble
|
||||
- Explain reasoning concisely when asked
|
||||
- Avoid unnecessary elaboration
|
||||
|
||||
## Decision Making
|
||||
- Ask clarifying questions before making assumptions
|
||||
- Stop and ask when uncertain about project-specific details
|
||||
- Confirm approach before making structural changes
|
||||
- Request guidance on preferences (cross-platform vs specific tools, etc.)
|
||||
- Verify understanding of requirements before proceeding
|
||||
@@ -10,8 +10,6 @@ if that directory exists, is licensed under the license defined in "app/propriet
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/proprietary/LICENSE".
|
||||
* All content that resides under the "frontend/src/desktop/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/desktop/LICENSE".
|
||||
* All content that resides under the "frontend/src/saas/" directory of this repository,
|
||||
if that directory exists, is licensed under the license defined in "frontend/src/saas/LICENSE".
|
||||
* Content outside of the above mentioned directories or restrictions above is
|
||||
available under the MIT License as defined below.
|
||||
|
||||
|
||||
@@ -341,8 +341,7 @@ public class EmlProcessingUtils {
|
||||
}
|
||||
|
||||
private String getFallbackStyles() {
|
||||
return
|
||||
"""
|
||||
return """
|
||||
/* Minimal fallback - main CSS resource failed to load */
|
||||
body {
|
||||
font-family: var(--font-family, Helvetica, sans-serif);
|
||||
|
||||
+2
-4
@@ -178,8 +178,7 @@ public class ReactRoutingController {
|
||||
String escapedBaseUrlJs = JavaScriptUtils.javaScriptEscape(baseUrl);
|
||||
|
||||
String serverUrl = "(window.location.origin + '" + escapedBaseUrlJs + "')";
|
||||
return
|
||||
"""
|
||||
return """
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -238,8 +237,7 @@ public class ReactRoutingController {
|
||||
String escapedBaseUrlJs = JavaScriptUtils.javaScriptEscape(baseUrl);
|
||||
|
||||
String serverUrl = "(window.location.origin + '" + escapedBaseUrlJs + "')";
|
||||
return
|
||||
"""
|
||||
return """
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
|
||||
+3
-4
@@ -581,10 +581,9 @@ public class PdfJsonFallbackFontService {
|
||||
|
||||
Character.UnicodeScript script = Character.UnicodeScript.of(codePoint);
|
||||
return switch (script) {
|
||||
// HAN script is used by both Simplified and Traditional Chinese
|
||||
// Default to Simplified (mainland China, 1.4B speakers) as it's more common
|
||||
// Traditional Chinese PDFs are detected via font name aliases (MingLiU, PMingLiU,
|
||||
// etc.)
|
||||
// HAN script is used by both Simplified and Traditional Chinese
|
||||
// Default to Simplified (mainland China, 1.4B speakers) as it's more common
|
||||
// Traditional Chinese PDFs are detected via font name aliases (MingLiU, PMingLiU, etc.)
|
||||
case HAN -> FALLBACK_FONT_CJK_ID;
|
||||
case HIRAGANA, KATAKANA -> FALLBACK_FONT_JP_ID;
|
||||
case HANGUL -> FALLBACK_FONT_KR_ID;
|
||||
|
||||
@@ -21,7 +21,8 @@ class ApiEndpointTest {
|
||||
return postNodeWithParams(description, true, names);
|
||||
}
|
||||
|
||||
private JsonNode postNodeWithParams(String description, boolean required, String... names) {
|
||||
private JsonNode postNodeWithParams(
|
||||
String description, boolean required, String... names) {
|
||||
ObjectNode post = mapper.createObjectNode();
|
||||
post.put("description", description);
|
||||
ArrayNode params = mapper.createArrayNode();
|
||||
|
||||
@@ -103,9 +103,7 @@ class LanguageServiceBasicTest {
|
||||
// Verify filtering by restrictions
|
||||
assertTrue(supportedLanguages.contains("en_US"), "Allowed language should be included");
|
||||
assertTrue(supportedLanguages.contains("fr_FR"), "Allowed language should be included");
|
||||
assertFalse(
|
||||
supportedLanguages.contains("en_GB"),
|
||||
"en_GB should NOT be included when not in whitelist");
|
||||
assertFalse(supportedLanguages.contains("en_GB"), "en_GB should NOT be included when not in whitelist");
|
||||
assertFalse(supportedLanguages.contains("de_DE"), "Restricted language should be excluded");
|
||||
}
|
||||
|
||||
|
||||
@@ -84,13 +84,11 @@ class LanguageServiceTest {
|
||||
|
||||
// Verify
|
||||
assertEquals(
|
||||
allowedLanguages, supportedLanguages, "Should return only whitelisted languages");
|
||||
assertFalse(
|
||||
supportedLanguages.contains("en_GB"),
|
||||
"en_GB should NOT be included when not in whitelist");
|
||||
assertFalse(
|
||||
supportedLanguages.contains("de_DE"),
|
||||
"de_DE should NOT be included when not in whitelist");
|
||||
allowedLanguages,
|
||||
supportedLanguages,
|
||||
"Should return only whitelisted languages");
|
||||
assertFalse(supportedLanguages.contains("en_GB"), "en_GB should NOT be included when not in whitelist");
|
||||
assertFalse(supportedLanguages.contains("de_DE"), "de_DE should NOT be included when not in whitelist");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+4
-5
@@ -161,7 +161,7 @@ public class EmailService {
|
||||
String subject = "Welcome to Stirling PDF";
|
||||
|
||||
String body =
|
||||
"""
|
||||
"""
|
||||
<html><body style="margin: 0; padding: 0;">
|
||||
<div style="font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;">
|
||||
<div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
|
||||
@@ -220,7 +220,7 @@ public class EmailService {
|
||||
String subject = "You've been invited to Stirling PDF";
|
||||
|
||||
String body =
|
||||
"""
|
||||
"""
|
||||
<html><body style="margin: 0; padding: 0;">
|
||||
<div style="font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;">
|
||||
<div style="max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
|
||||
@@ -269,8 +269,7 @@ public class EmailService {
|
||||
String passwordSection =
|
||||
newPassword == null
|
||||
? ""
|
||||
:
|
||||
"""
|
||||
: """
|
||||
<div style=\"background-color: #f8f9fa; border-left: 4px solid #007bff; padding: 15px; margin: 20px 0; border-radius: 4px;\">
|
||||
<p style=\"margin: 0;\"><strong>Temporary Password:</strong> %s</p>
|
||||
</div>
|
||||
@@ -278,7 +277,7 @@ public class EmailService {
|
||||
.formatted(newPassword);
|
||||
|
||||
String body =
|
||||
"""
|
||||
"""
|
||||
<html><body style=\"margin: 0; padding: 0;\">
|
||||
<div style=\"font-family: Arial, sans-serif; background-color: #f8f9fa; padding: 20px;\">
|
||||
<div style=\"max-width: 600px; margin: auto; background-color: #ffffff; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;\">
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ springBoot {
|
||||
|
||||
allprojects {
|
||||
group = 'stirling.software'
|
||||
version = '2.7.1'
|
||||
version = '2.7.0'
|
||||
|
||||
configurations.configureEach {
|
||||
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Codex Contribution Guidelines for Stirling-PDF
|
||||
|
||||
This file provides high-level instructions for Codex when modifying any files within this repository. Follow these rules to ensure changes remain consistent with the existing project structure.
|
||||
|
||||
## 1. Code Style and Formatting
|
||||
- Respect the `.editorconfig` settings located in the repository root. Java files use 4 spaces; HTML, JS, and Python generally use 2 spaces. Lines should end with `LF`.
|
||||
- Format Java code with `./gradlew spotlessApply` before committing.
|
||||
- Review `DeveloperGuide.md` for project structure and design details before making significant changes.
|
||||
|
||||
## 2. Testing
|
||||
- Run `./gradlew build` before committing changes to ensure the project compiles.
|
||||
- If the build cannot complete due to environment restrictions, DO NOT COMMIT THE CHANGE
|
||||
|
||||
## 3. Commits
|
||||
- Keep commits focused. Group related changes together and provide concise commit messages.
|
||||
- Ensure the working tree is clean (`git status`) before concluding your work.
|
||||
|
||||
## 4. Pull Requests
|
||||
- Summarize what was changed and why. Include build results from `./gradlew build` in the PR description.
|
||||
- Note that the code was generated with the assistance of AI.
|
||||
|
||||
## 5. Translations
|
||||
- Only modify `messages_en_GB.properties` when adding or updating translations.
|
||||
|
||||
@@ -14,14 +14,10 @@
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env
|
||||
.env.saas
|
||||
.env.desktop
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
!.env*.example
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
|
||||
+2
-17
@@ -1,11 +1,6 @@
|
||||
# Frontend
|
||||
## Environment Variables
|
||||
# Getting Started with Create React App
|
||||
|
||||
The frontend requires environment variables to be set before running. `npm run dev` will create a `.env` file for you automatically on first run using the defaults from `config/.env.example` - for most development work this is all you need.
|
||||
|
||||
If you need to configure specific services (Google Drive, Supabase, Stripe, PostHog), edit your local `.env` file. The values in `config/.env.example` show what each variable does and provides sensible defaults where applicable.
|
||||
|
||||
For desktop (Tauri) development, `npm run tauri-dev` will additionally create a `.env.desktop` file from `config/.env.desktop.example`.
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Docker Setup
|
||||
|
||||
@@ -125,11 +120,6 @@ npm run tauri-dev
|
||||
|
||||
This will run the gradle runboot command and the tauri dev command concurrently, starting the app once both are stable.
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> Desktop builds require additional environment variables. See [Environment Variables](#environment-variables)
|
||||
> above - `npm run tauri-dev` will set these up automatically from `config/.env.desktop.example` on first run.
|
||||
|
||||
### Build
|
||||
To build a deployment of the Tauri app. Use this command in the `frontend` folder:
|
||||
|
||||
@@ -138,8 +128,3 @@ npm run tauri-build
|
||||
```
|
||||
|
||||
This will bundle the backend and frontend into one executable for each target. Targets can be set within the `tauri.conf.json` file.
|
||||
|
||||
> [!NOTE]
|
||||
>
|
||||
> Desktop builds require additional environment variables. See [Environment Variables](#environment-variables)
|
||||
> above - `npm run tauri-build` will set these up automatically from `config/.env.desktop.example` on first run.
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# Frontend environment variables for desktop (Tauri) builds.
|
||||
# Layered on top of .env when running in desktop mode.
|
||||
|
||||
# Desktop backend endpoint — leave blank to use VITE_API_BASE_URL from .env
|
||||
VITE_DESKTOP_BACKEND_URL=
|
||||
|
||||
# Desktop auth integration
|
||||
VITE_SAAS_SERVER_URL=https://auth.stirling.com
|
||||
VITE_SAAS_BACKEND_API_URL=https://api2.stirling.com
|
||||
VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=sb_publishable_UHz2SVRF5mvdrPHWkRteyA_yNlZTkYb
|
||||
VITE_SUPABASE_URL=https://rficokptxxxxtyzcvgmx.supabase.co
|
||||
@@ -1,20 +0,0 @@
|
||||
# Frontend environment variables for core and proprietary builds.
|
||||
|
||||
# API base URL — use / for same-origin (default for web builds)
|
||||
VITE_API_BASE_URL=/
|
||||
|
||||
# Google Drive integration
|
||||
VITE_GOOGLE_DRIVE_CLIENT_ID=
|
||||
VITE_GOOGLE_DRIVE_API_KEY=
|
||||
VITE_GOOGLE_DRIVE_APP_ID=
|
||||
|
||||
# Supabase configuration
|
||||
VITE_SUPABASE_URL=https://rficokptxxxxtyzcvgmx.supabase.co
|
||||
VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY=sb_publishable_UHz2SVRF5mvdrPHWkRteyA_yNlZTkYb
|
||||
|
||||
# Stripe checkout
|
||||
VITE_STRIPE_PUBLISHABLE_KEY=pk_live_51Q56W2P9mY5IAnSnp3kcxG50uyFMLuhM4fFs774DAP3t88KmlwUrUo31CecpnAZ9FHsNp8xJyOnYNYNVVP6z4oi500q5sFYPEp
|
||||
|
||||
# PostHog analytics
|
||||
VITE_PUBLIC_POSTHOG_KEY=phc_VOdeYnlevc2T63m3myFGjeBlRcIusRgmhfx6XL5a1iz
|
||||
VITE_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com
|
||||
@@ -1,11 +0,0 @@
|
||||
# Frontend environment variables for SaaS builds.
|
||||
# Layered on top of .env when running in SaaS mode.
|
||||
|
||||
# Userback feedback widget — leave blank to disable
|
||||
VITE_USERBACK_TOKEN=
|
||||
|
||||
# URL subpath prefix for SaaS deployments (e.g. "app" if serving at /app/) — leave blank for root
|
||||
VITE_RUN_SUBPATH=
|
||||
|
||||
# Development-only auth bypass — allows unauthenticated access on localhost in dev mode
|
||||
VITE_DEV_BYPASS_AUTH=false
|
||||
Generated
+1
-658
@@ -44,7 +44,6 @@
|
||||
"@mantine/hooks": "^8.3.1",
|
||||
"@mui/icons-material": "^7.3.2",
|
||||
"@mui/material": "^7.3.2",
|
||||
"@posthog/react": "^1.8.2",
|
||||
"@reactour/tour": "^3.8.0",
|
||||
"@stripe/react-stripe-js": "^4.0.2",
|
||||
"@stripe/stripe-js": "^7.9.0",
|
||||
@@ -57,10 +56,8 @@
|
||||
"@tauri-apps/plugin-http": "^2.5.7",
|
||||
"@tauri-apps/plugin-notification": "^2.3.3",
|
||||
"@tauri-apps/plugin-shell": "^2.3.5",
|
||||
"@userback/widget": "^0.3.12",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"axios": "^1.13.2",
|
||||
"d3": "^7.9.0",
|
||||
"globals": "^17.1.0",
|
||||
"i18next": "^25.5.2",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
@@ -72,7 +69,6 @@
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-easy-crop": "^5.5.6",
|
||||
"react-i18next": "^15.7.3",
|
||||
"react-rnd": "^10.5.2",
|
||||
"react-router-dom": "^7.9.1",
|
||||
@@ -92,7 +88,6 @@
|
||||
"@testing-library/jest-dom": "^6.8.0",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/gapi": "^0.0.47",
|
||||
"@types/gapi.client.drive-v3": "^0.0.5",
|
||||
"@types/google.accounts": "^0.0.18",
|
||||
@@ -104,7 +99,6 @@
|
||||
"@typescript-eslint/parser": "^8.44.1",
|
||||
"@vitejs/plugin-react-swc": "^4.1.0",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"dotenv": "^16.4.7",
|
||||
"dpdm": "^3.14.0",
|
||||
"eslint": "^10.0.2",
|
||||
"jsdom": "^27.0.0",
|
||||
@@ -115,7 +109,6 @@
|
||||
"postcss-preset-mantine": "^1.18.0",
|
||||
"postcss-simple-vars": "^7.0.1",
|
||||
"puppeteer": "^24.25.0",
|
||||
"tsx": "^4.19.4",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
@@ -2878,22 +2871,6 @@
|
||||
"cross-spawn": "^7.0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/@posthog/react": {
|
||||
"version": "1.8.2",
|
||||
"resolved": "https://registry.npmjs.org/@posthog/react/-/react-1.8.2.tgz",
|
||||
"integrity": "sha512-KzUuXIcAR8fAjU7IeDq+XfEcUTNvzgEGB381WRrFUUsu7jFTcKZZ6crx/ukHRCzTnoEuy5EJDkL7b7sJecPlCg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8.0",
|
||||
"posthog-js": ">=1.257.2",
|
||||
"react": ">=16.8.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@posthog/types": {
|
||||
"version": "1.354.0",
|
||||
"resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.354.0.tgz",
|
||||
@@ -4567,173 +4544,24 @@
|
||||
"assertion-error": "^2.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3": {
|
||||
"version": "7.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz",
|
||||
"integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-array": "*",
|
||||
"@types/d3-axis": "*",
|
||||
"@types/d3-brush": "*",
|
||||
"@types/d3-chord": "*",
|
||||
"@types/d3-color": "*",
|
||||
"@types/d3-contour": "*",
|
||||
"@types/d3-delaunay": "*",
|
||||
"@types/d3-dispatch": "*",
|
||||
"@types/d3-drag": "*",
|
||||
"@types/d3-dsv": "*",
|
||||
"@types/d3-ease": "*",
|
||||
"@types/d3-fetch": "*",
|
||||
"@types/d3-force": "*",
|
||||
"@types/d3-format": "*",
|
||||
"@types/d3-geo": "*",
|
||||
"@types/d3-hierarchy": "*",
|
||||
"@types/d3-interpolate": "*",
|
||||
"@types/d3-path": "*",
|
||||
"@types/d3-polygon": "*",
|
||||
"@types/d3-quadtree": "*",
|
||||
"@types/d3-random": "*",
|
||||
"@types/d3-scale": "*",
|
||||
"@types/d3-scale-chromatic": "*",
|
||||
"@types/d3-selection": "*",
|
||||
"@types/d3-shape": "*",
|
||||
"@types/d3-time": "*",
|
||||
"@types/d3-time-format": "*",
|
||||
"@types/d3-timer": "*",
|
||||
"@types/d3-transition": "*",
|
||||
"@types/d3-zoom": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-array": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz",
|
||||
"integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-axis": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz",
|
||||
"integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-brush": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz",
|
||||
"integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-chord": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz",
|
||||
"integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-color": {
|
||||
"version": "3.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz",
|
||||
"integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-contour": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz",
|
||||
"integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-array": "*",
|
||||
"@types/geojson": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-delaunay": {
|
||||
"version": "6.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
|
||||
"integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-dispatch": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz",
|
||||
"integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-drag": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz",
|
||||
"integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-dsv": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz",
|
||||
"integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-ease": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz",
|
||||
"integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-fetch": {
|
||||
"version": "3.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz",
|
||||
"integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-dsv": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-force": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz",
|
||||
"integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-format": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz",
|
||||
"integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-geo": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.0.tgz",
|
||||
"integrity": "sha512-856sckF0oP/diXtS4jNsiQw/UuK5fQG8l/a9VVLeSouf1/PPbBE1i1W852zVwKwYCBkFJJB7nCFTbk6UMEXBOQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/geojson": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-hierarchy": {
|
||||
"version": "3.1.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz",
|
||||
"integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-interpolate": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz",
|
||||
@@ -4749,27 +4577,6 @@
|
||||
"integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-polygon": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz",
|
||||
"integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-quadtree": {
|
||||
"version": "3.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz",
|
||||
"integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-random": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.3.tgz",
|
||||
"integrity": "sha512-Imagg1vJ3y76Y2ea0871wpabqp613+8/r0mCLEBfdtqC7xMSfj9idOnmBYyMoULfHePJyxMAw3nWhJxzc+LFwQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-scale": {
|
||||
"version": "4.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
|
||||
@@ -4779,20 +4586,6 @@
|
||||
"@types/d3-time": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-scale-chromatic": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
|
||||
"integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-selection": {
|
||||
"version": "3.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.11.tgz",
|
||||
"integrity": "sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-shape": {
|
||||
"version": "3.1.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
|
||||
@@ -4808,40 +4601,12 @@
|
||||
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-time-format": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz",
|
||||
"integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-timer": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz",
|
||||
"integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/d3-transition": {
|
||||
"version": "3.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz",
|
||||
"integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-zoom": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.8.tgz",
|
||||
"integrity": "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/d3-interpolate": "*",
|
||||
"@types/d3-selection": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
@@ -4896,13 +4661,6 @@
|
||||
"@maxim_mazurok/gapi.client.drive-v3": "latest"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/geojson": {
|
||||
"version": "7946.0.16",
|
||||
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
|
||||
"integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/google.accounts": {
|
||||
"version": "0.0.18",
|
||||
"resolved": "https://registry.npmjs.org/@types/google.accounts/-/google.accounts-0.0.18.tgz",
|
||||
@@ -5250,12 +5008,6 @@
|
||||
"url": "https://opencollective.com/eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@userback/widget": {
|
||||
"version": "0.3.12",
|
||||
"resolved": "https://registry.npmjs.org/@userback/widget/-/widget-0.3.12.tgz",
|
||||
"integrity": "sha512-68YihQblx1+4kFpd7e4nDBSV6ljSY0+hzIHHgbxgbJPJIhNgN4lyvOjcDbCrEb9qh6yXx5W6HBLKTMJD4hLXGg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react-swc": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react-swc/-/plugin-react-swc-4.2.3.tgz",
|
||||
@@ -6531,6 +6283,7 @@
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
|
||||
"integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
@@ -6694,47 +6447,6 @@
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/d3": {
|
||||
"version": "7.9.0",
|
||||
"resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
|
||||
"integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "3",
|
||||
"d3-axis": "3",
|
||||
"d3-brush": "3",
|
||||
"d3-chord": "3",
|
||||
"d3-color": "3",
|
||||
"d3-contour": "4",
|
||||
"d3-delaunay": "6",
|
||||
"d3-dispatch": "3",
|
||||
"d3-drag": "3",
|
||||
"d3-dsv": "3",
|
||||
"d3-ease": "3",
|
||||
"d3-fetch": "3",
|
||||
"d3-force": "3",
|
||||
"d3-format": "3",
|
||||
"d3-geo": "3",
|
||||
"d3-hierarchy": "3",
|
||||
"d3-interpolate": "3",
|
||||
"d3-path": "3",
|
||||
"d3-polygon": "3",
|
||||
"d3-quadtree": "3",
|
||||
"d3-random": "3",
|
||||
"d3-scale": "4",
|
||||
"d3-scale-chromatic": "3",
|
||||
"d3-selection": "3",
|
||||
"d3-shape": "3",
|
||||
"d3-time": "3",
|
||||
"d3-time-format": "4",
|
||||
"d3-timer": "3",
|
||||
"d3-transition": "3",
|
||||
"d3-zoom": "3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-array": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
|
||||
@@ -6747,43 +6459,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-axis": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",
|
||||
"integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-brush": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",
|
||||
"integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-drag": "2 - 3",
|
||||
"d3-interpolate": "1 - 3",
|
||||
"d3-selection": "3",
|
||||
"d3-transition": "3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-chord": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",
|
||||
"integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-path": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-color": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
|
||||
@@ -6793,77 +6468,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-contour": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",
|
||||
"integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "^3.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-delaunay": {
|
||||
"version": "6.0.4",
|
||||
"resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
|
||||
"integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"delaunator": "5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-dispatch": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
|
||||
"integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-drag": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
|
||||
"integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-selection": "3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-dsv": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
|
||||
"integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"commander": "7",
|
||||
"iconv-lite": "0.6",
|
||||
"rw": "1"
|
||||
},
|
||||
"bin": {
|
||||
"csv2json": "bin/dsv2json.js",
|
||||
"csv2tsv": "bin/dsv2dsv.js",
|
||||
"dsv2dsv": "bin/dsv2dsv.js",
|
||||
"dsv2json": "bin/dsv2json.js",
|
||||
"json2csv": "bin/json2dsv.js",
|
||||
"json2dsv": "bin/json2dsv.js",
|
||||
"json2tsv": "bin/json2dsv.js",
|
||||
"tsv2csv": "bin/dsv2dsv.js",
|
||||
"tsv2json": "bin/dsv2json.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-ease": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
|
||||
@@ -6873,32 +6477,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-fetch": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",
|
||||
"integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-dsv": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-force": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
|
||||
"integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-quadtree": "1 - 3",
|
||||
"d3-timer": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-format": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.2.tgz",
|
||||
@@ -6908,27 +6486,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-geo": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",
|
||||
"integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-array": "2.5.0 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-hierarchy": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
|
||||
"integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-interpolate": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
|
||||
@@ -6950,33 +6507,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-polygon": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",
|
||||
"integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-quadtree": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
|
||||
"integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-random": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
|
||||
"integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-scale": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
|
||||
@@ -6993,28 +6523,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-scale-chromatic": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
|
||||
"integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-color": "1 - 3",
|
||||
"d3-interpolate": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-selection": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
|
||||
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-shape": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
|
||||
@@ -7060,41 +6568,6 @@
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-transition": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
|
||||
"integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-color": "1 - 3",
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-ease": "1 - 3",
|
||||
"d3-interpolate": "1 - 3",
|
||||
"d3-timer": "1 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"d3-selection": "2 - 3"
|
||||
}
|
||||
},
|
||||
"node_modules/d3-zoom": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
|
||||
"integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"d3-dispatch": "1 - 3",
|
||||
"d3-drag": "2 - 3",
|
||||
"d3-interpolate": "1 - 3",
|
||||
"d3-selection": "2 - 3",
|
||||
"d3-transition": "2 - 3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/data-uri-to-buffer": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
|
||||
@@ -7246,15 +6719,6 @@
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/delaunator": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz",
|
||||
"integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"robust-predicates": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
@@ -7520,19 +6984,6 @@
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "16.6.1",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
|
||||
"integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://dotenvx.com"
|
||||
}
|
||||
},
|
||||
"node_modules/dpdm": {
|
||||
"version": "3.15.1",
|
||||
"resolved": "https://registry.npmjs.org/dpdm/-/dpdm-3.15.1.tgz",
|
||||
@@ -8555,19 +8006,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/get-tsconfig": {
|
||||
"version": "4.13.6",
|
||||
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz",
|
||||
"integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"resolve-pkg-maps": "^1.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/get-uri": {
|
||||
"version": "6.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz",
|
||||
@@ -8896,18 +8334,6 @@
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
@@ -10369,12 +9795,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/normalize-wheel": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/normalize-wheel/-/normalize-wheel-1.0.1.tgz",
|
||||
"integrity": "sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/npm-normalize-package-bin": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz",
|
||||
@@ -11615,20 +11035,6 @@
|
||||
"react": ">= 16.8 || 18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-easy-crop": {
|
||||
"version": "5.5.6",
|
||||
"resolved": "https://registry.npmjs.org/react-easy-crop/-/react-easy-crop-5.5.6.tgz",
|
||||
"integrity": "sha512-Jw3/ozs8uXj3NpL511Suc4AHY+mLRO23rUgipXvNYKqezcFSYHxe4QXibBymkOoY6oOtLVMPO2HNPRHYvMPyTw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"normalize-wheel": "^1.0.1",
|
||||
"tslib": "^2.0.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.4.0",
|
||||
"react-dom": ">=16.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-i18next": {
|
||||
"version": "15.7.4",
|
||||
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-15.7.4.tgz",
|
||||
@@ -12173,16 +11579,6 @@
|
||||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/resolve-pkg-maps": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
|
||||
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/responselike": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/responselike/-/responselike-4.0.2.tgz",
|
||||
@@ -12219,12 +11615,6 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/robust-predicates": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz",
|
||||
"integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==",
|
||||
"license": "Unlicense"
|
||||
},
|
||||
"node_modules/rollup": {
|
||||
"version": "4.59.0",
|
||||
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.59.0.tgz",
|
||||
@@ -12270,24 +11660,12 @@
|
||||
"fsevents": "~2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/rw": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
|
||||
"integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
|
||||
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/sass-lookup": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/sass-lookup/-/sass-lookup-6.1.0.tgz",
|
||||
@@ -13422,41 +12800,6 @@
|
||||
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
|
||||
"license": "0BSD"
|
||||
},
|
||||
"node_modules/tsx": {
|
||||
"version": "4.21.0",
|
||||
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.21.0.tgz",
|
||||
"integrity": "sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"esbuild": "~0.27.0",
|
||||
"get-tsconfig": "^4.7.5"
|
||||
},
|
||||
"bin": {
|
||||
"tsx": "dist/cli.mjs"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "~2.3.3"
|
||||
}
|
||||
},
|
||||
"node_modules/tsx/node_modules/fsevents": {
|
||||
"version": "2.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
|
||||
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/type-check": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
|
||||
|
||||
+15
-33
@@ -52,10 +52,8 @@
|
||||
"@tauri-apps/plugin-http": "^2.5.7",
|
||||
"@tauri-apps/plugin-notification": "^2.3.3",
|
||||
"@tauri-apps/plugin-shell": "^2.3.5",
|
||||
"@userback/widget": "^0.3.12",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"axios": "^1.13.2",
|
||||
"d3": "^7.9.0",
|
||||
"globals": "^17.1.0",
|
||||
"i18next": "^25.5.2",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
@@ -68,7 +66,6 @@
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-easy-crop": "^5.5.6",
|
||||
"react-i18next": "^15.7.3",
|
||||
"react-rnd": "^10.5.2",
|
||||
"react-router-dom": "^7.9.1",
|
||||
@@ -79,39 +76,27 @@
|
||||
"web-vitals": "^5.1.0"
|
||||
},
|
||||
"scripts": {
|
||||
"prep": "tsx scripts/setup-env.ts && npm run generate-icons",
|
||||
"prep:saas": "tsx scripts/setup-env.ts --saas && npm run generate-icons",
|
||||
"prep:desktop": "tsx scripts/setup-env.ts --desktop && npm run generate-icons",
|
||||
"prep:desktop-build": "node scripts/build-provisioner.mjs && npm run prep:desktop",
|
||||
"dev": "npm run prep && vite",
|
||||
"dev:core": "npm run prep && vite --mode core",
|
||||
"dev:proprietary": "npm run prep && vite --mode proprietary",
|
||||
"dev:saas": "npm run prep:saas && vite --mode saas",
|
||||
"dev:desktop": "npm run prep:desktop && vite --mode desktop",
|
||||
"pretauri-build": "node scripts/build-provisioner.mjs",
|
||||
"predev": "npm run generate-icons",
|
||||
"dev": "vite",
|
||||
"prebuild": "npm run generate-icons",
|
||||
"lint": "npm run lint:eslint && npm run lint:cycles",
|
||||
"lint:eslint": "eslint --max-warnings=0",
|
||||
"lint:cycles": "dpdm src --circular --no-warning --no-tree --exit-code circular:1",
|
||||
"build": "npm run prep && vite build",
|
||||
"build:core": "npm run prep && vite build --mode core",
|
||||
"build:proprietary": "npm run prep && vite build --mode proprietary",
|
||||
"build:saas": "npm run prep:saas && vite build --mode saas",
|
||||
"build:desktop": "npm run prep:desktop && vite build --mode desktop",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri-dev": "npm run prep:desktop && tauri dev --no-watch",
|
||||
"tauri-build": "npm run prep:desktop-build && tauri build",
|
||||
"_tauri-build-dev": "npm run prep:desktop && tauri build",
|
||||
"tauri-build-dev": "npm run _tauri-build-dev -- --no-bundle",
|
||||
"tauri-build-dev-mac": "npm run _tauri-build-dev -- --bundles app",
|
||||
"tauri-build-dev-windows": "npm run _tauri-build-dev -- --bundles nsis",
|
||||
"tauri-build-dev-linux": "npm run _tauri-build-dev -- --bundles appimage",
|
||||
"tauri-dev": "tauri dev --no-watch",
|
||||
"tauri-build": "tauri build",
|
||||
"tauri-build-dev": "tauri build --no-bundle",
|
||||
"tauri-build-dev-mac": "tauri build --bundles app",
|
||||
"tauri-build-dev-windows": "tauri build --bundles nsis",
|
||||
"tauri-build-dev-linux": "tauri build --bundles appimage",
|
||||
"tauri-clean": "cd src-tauri && cargo clean && cd .. && rm -rf dist build",
|
||||
"typecheck": "npm run typecheck:proprietary",
|
||||
"typecheck:core": "tsc --noEmit --project src/core/tsconfig.json",
|
||||
"typecheck:proprietary": "tsc --noEmit --project src/proprietary/tsconfig.json",
|
||||
"typecheck:saas": "tsc --noEmit --project src/saas/tsconfig.json",
|
||||
"typecheck:desktop": "tsc --noEmit --project src/desktop/tsconfig.json",
|
||||
"typecheck:scripts": "tsc --noEmit --project scripts/tsconfig.json",
|
||||
"typecheck:all": "npm run typecheck:core && npm run typecheck:proprietary && npm run typecheck:saas && npm run typecheck:desktop && npm run typecheck:scripts",
|
||||
"typecheck:core": "tsc --noEmit --project tsconfig.core.json",
|
||||
"typecheck:proprietary": "tsc --noEmit --project tsconfig.proprietary.json",
|
||||
"typecheck:desktop": "tsc --noEmit --project tsconfig.desktop.json",
|
||||
"typecheck:all": "npm run typecheck:core && npm run typecheck:proprietary && npm run typecheck:desktop",
|
||||
"check": "npm run typecheck && npm run lint && npm run test:run",
|
||||
"generate-licenses": "node scripts/generate-licenses.js",
|
||||
"generate-icons": "node scripts/generate-icons.js",
|
||||
@@ -151,7 +136,6 @@
|
||||
"@testing-library/jest-dom": "^6.8.0",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/gapi": "^0.0.47",
|
||||
"@types/gapi.client.drive-v3": "^0.0.5",
|
||||
"@types/google.accounts": "^0.0.18",
|
||||
@@ -163,7 +147,6 @@
|
||||
"@typescript-eslint/parser": "^8.44.1",
|
||||
"@vitejs/plugin-react-swc": "^4.1.0",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"dotenv": "^16.4.7",
|
||||
"dpdm": "^3.14.0",
|
||||
"eslint": "^10.0.2",
|
||||
"jsdom": "^27.0.0",
|
||||
@@ -175,7 +158,6 @@
|
||||
"postcss-simple-vars": "^7.0.1",
|
||||
"puppeteer": "^24.25.0",
|
||||
"typescript": "^5.9.2",
|
||||
"tsx": "^4.19.4",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
"vite-plugin-static-copy": "^3.1.4",
|
||||
|
||||
@@ -142,10 +142,6 @@ welcome = "Welcome"
|
||||
white = "White"
|
||||
WorkInProgess = "Work in progress, May not work or be buggy, Please report any problems!"
|
||||
yes = "Yes"
|
||||
insufficientCredits = "Insufficient credits. Required: {{requiredCredits}}, Available: {{currentBalance}}, Shortfall: {{shortfall}}"
|
||||
loadingCredits = "Checking credits..."
|
||||
loadingProStatus = "Checking subscription status..."
|
||||
noticeTopUpOrPlan = "Not enough credits, please top up or upgrade to a plan"
|
||||
|
||||
[account]
|
||||
accountSettings = "Account Settings"
|
||||
@@ -2567,45 +2563,10 @@ title = "Quality Adjustment"
|
||||
tags = "squish,small,tiny"
|
||||
|
||||
[config.account.overview]
|
||||
confirmDelete = "Delete My Account"
|
||||
deleteAccount = "Delete Account"
|
||||
deleteAccountTitle = "Delete Account"
|
||||
deleteFailed = "Failed to delete account."
|
||||
deleteFailedTitle = "Unable to delete account"
|
||||
deleteWarning = "This action is permanent and cannot be undone. All your data will be deleted."
|
||||
enterEmailConfirm = "To confirm deletion, please type your email address ({{email}}) below:"
|
||||
guestDescription = "You are signed in as a guest. Consider upgrading your account above."
|
||||
label = "Overview"
|
||||
manageAccountPreferences = "Manage your account preferences"
|
||||
signedInAs = "Signed in as"
|
||||
title = "Account Settings"
|
||||
|
||||
[config.account.profilePicture]
|
||||
description = "Upload an image to personalize your account."
|
||||
help = "PNG, JPG, or WebP up to 2MB."
|
||||
remove = "Remove"
|
||||
sizeError = "Please select an image smaller than 2MB."
|
||||
switchedToCustom = "Switched to custom picture. You can now upload your own."
|
||||
title = "Profile picture"
|
||||
upload = "Upload"
|
||||
useCustom = "Use custom picture"
|
||||
usingProvider = "Using {{provider}} profile picture"
|
||||
|
||||
[config.account.profilePicture.cropper]
|
||||
cropError = "Failed to crop image. Please try again."
|
||||
invalidImage = "Invalid image file. Please select a valid PNG, JPG, or WebP file."
|
||||
processing = "Processing crop..."
|
||||
save = "Save Cropped Image"
|
||||
sizeErrorAfterCrop = "Cropped image is too large. Please zoom out or crop a smaller area."
|
||||
title = "Crop Profile Picture"
|
||||
zoom = "Zoom"
|
||||
|
||||
[config.account.security]
|
||||
changePassword = "Change password"
|
||||
description = "Manage your password and security settings."
|
||||
title = "Passwords & Security"
|
||||
update = "Update password"
|
||||
|
||||
[config.account.upgrade]
|
||||
description = "Link your account to preserve your history and access more features!"
|
||||
email = "Email"
|
||||
@@ -2619,13 +2580,9 @@ socialLogin = "Upgrade with Social Account"
|
||||
title = "Upgrade Guest Account"
|
||||
upgradeButton = "Upgrade Account"
|
||||
|
||||
[config]
|
||||
plan = "Plan"
|
||||
|
||||
[config.apiKeys]
|
||||
chartAriaLabel = "Credits usage: included {{includedUsed}} of {{includedTotal}}, purchased {{purchasedUsed}} of {{purchasedTotal}}"
|
||||
copyKeyAriaLabel = "Copy API key"
|
||||
creditsRemaining = "Credits Remaining"
|
||||
description = "Your API key for accessing Stirling's suite of PDF tools. Copy it to your project or refresh to generate a new one."
|
||||
docsDescription = "Learn more about integrating with Stirling PDF:"
|
||||
docsLink = "API Documentation"
|
||||
@@ -2759,15 +2716,6 @@ webOptions = "Web to PDF Options"
|
||||
wordDoc = "Word Document"
|
||||
wordDocExt = "Word Document (.docx)"
|
||||
zoomLevel = "Zoom Level"
|
||||
cbrToPdf = "CBR → PDF"
|
||||
cbzToPdf = "CBZ → PDF"
|
||||
ebookToPdf = "eBook → PDF"
|
||||
emlToPdf = "Email → PDF"
|
||||
fileToPdf = "Office/Document → PDF"
|
||||
pdfToCbr = "PDF → CBR"
|
||||
pdfToCbz = "PDF → CBZ"
|
||||
pdfToEpub = "PDF → EPUB"
|
||||
svgToPdf = "SVG → PDF"
|
||||
|
||||
[convert.ebookOptions]
|
||||
ebookOptions = "eBook to PDF Options"
|
||||
@@ -3894,7 +3842,6 @@ version = "Version"
|
||||
accountCreatedSuccess = "Account created successfully! You can now sign in."
|
||||
alreadyLoggedIn = "You are already logged in to"
|
||||
alreadyLoggedIn2 = "devices. Please log out of the devices and try again."
|
||||
backToSignIn = "Back to sign in"
|
||||
cancel = "Cancel"
|
||||
changePasswordWarning = "Please change your password after logging in for the first time"
|
||||
credentialsUpdated = "Your credentials have been updated. Please sign in again."
|
||||
@@ -3936,21 +3883,16 @@ or = "Or"
|
||||
password = "Password"
|
||||
passwordChangedSuccess = "Password changed successfully! Please sign in with your new password."
|
||||
passwordResetSent = "Password reset link sent to {{email}}! Check your email and follow the instructions."
|
||||
passwordUpdatedSuccess = "Your password has been updated successfully."
|
||||
pleaseEnterBoth = "Please enter both email and password"
|
||||
pleaseEnterEmail = "Please enter your email address"
|
||||
relyingPartyRegistrationNotFound = "No relying party registration found"
|
||||
rememberme = "Remember me"
|
||||
resetHelp = "Enter your email to receive a secure link to reset your password. If the link has expired, please request a new one."
|
||||
resetYourPassword = "Reset your password"
|
||||
saml2RequiresLicense = "SAML login requires an Enterprise license. Please contact the administrator to upgrade your plan."
|
||||
sending = "Sending…"
|
||||
sendMagicLink = "Send Magic Link"
|
||||
sendResetLink = "Send reset link"
|
||||
sessionExpired = "Your session has expired. Please sign in again."
|
||||
signin = "Sign in"
|
||||
signInAnonymously = "Sign Up as a Guest"
|
||||
subtitle = "Sign back in to Stirling PDF"
|
||||
signingIn = "Signing in..."
|
||||
signinTitle = "Please sign in"
|
||||
signInWith = "Sign in with"
|
||||
@@ -3959,7 +3901,6 @@ ssoSignIn = "Login via Single Sign-on"
|
||||
title = "Sign in"
|
||||
toManySessions = "You have too many active sessions"
|
||||
unexpectedError = "Unexpected error: {{message}}"
|
||||
updatePassword = "Update password"
|
||||
useEmailInstead = "Login with email"
|
||||
useMagicLink = "Use magic link instead"
|
||||
userIsDisabled = "User is deactivated, login is currently blocked with this username. Please contact the administrator."
|
||||
@@ -4269,15 +4210,6 @@ viewSwitcher = "Use these controls to select how you want to view your PDFs."
|
||||
workbench = "This is the <strong>Workbench</strong> - the main area where you view and edit your PDFs."
|
||||
wrapUp = "You're all set! You've learnt about the main areas of the app and how to use them. Click the <strong>Help</strong> button whenever you like to see this tour again."
|
||||
|
||||
[onboarding.freeTrial]
|
||||
afterTrialWithoutPayment = "After your trial ends, you'll continue with our free tier. Add a payment method to keep Pro access."
|
||||
afterTrialWithPayment = "Your Pro subscription will start automatically when the trial ends."
|
||||
body = "You have full access to Stirling PDF Pro features during your trial. Enjoy unlimited conversions, larger file sizes, and priority processing."
|
||||
daysRemaining = "{{days}} days remaining"
|
||||
daysRemainingSingular = "{{days}} day remaining"
|
||||
title = "Your 30-Day Pro Trial"
|
||||
trialEnds = "Trial ends {{date}}"
|
||||
|
||||
[onboarding.buttons]
|
||||
back = "Back"
|
||||
download = "Download →"
|
||||
@@ -5015,10 +4947,7 @@ perMonth = "/month"
|
||||
perSeat = "/seat"
|
||||
popular = "Popular"
|
||||
selectPlan = "Select Plan"
|
||||
selectCredits = "Select Credit Amount"
|
||||
showComparison = "Compare All Features"
|
||||
purchase = "Purchase"
|
||||
totalCost = "Total Cost"
|
||||
upgrade = "Upgrade"
|
||||
withServer = "+ Server Plan"
|
||||
|
||||
@@ -5110,30 +5039,6 @@ successMessage = "Your license has been successfully activated. You can now clos
|
||||
name = "Team"
|
||||
siteLicense = "Site License"
|
||||
|
||||
[plan.api]
|
||||
large = "5,000 Credits"
|
||||
medium = "1,000 Credits"
|
||||
small = "500 Credits"
|
||||
xsmall = "100 Credits"
|
||||
|
||||
[plan.apiPackages]
|
||||
subtitle = "Purchase API credits for your applications"
|
||||
title = "API Credit Packages"
|
||||
|
||||
[plan.trial]
|
||||
badge = "Trial"
|
||||
continueWithFree = "Continue with Free"
|
||||
daysRemaining = "Your trial ends in {{days}} days"
|
||||
endDate = "Expires: {{date}}"
|
||||
expired = "Your Trial Has Ended"
|
||||
expiredMessage = "Your 30-day Pro trial has expired. Subscribe to Pro to continue accessing premium features, or continue with our free tier."
|
||||
freeTierLimitations = "Free tier includes basic PDF tools with usage limits."
|
||||
message = ""
|
||||
subscribe = "Subscribe to Pro"
|
||||
subscribeToPro = "Subscribe to Pro"
|
||||
subscriptionScheduled = "Subscription scheduled - starts {{date}}"
|
||||
title = "Free Trial Active"
|
||||
|
||||
[credits]
|
||||
enableOverageBilling = "Enable Overage Billing"
|
||||
maybeLater = "Maybe later"
|
||||
@@ -5821,16 +5726,6 @@ placeholder = "Enter search term..."
|
||||
searching = "Searching..."
|
||||
title = "Search PDF"
|
||||
|
||||
[selfHosted]
|
||||
|
||||
[selfHosted.offline]
|
||||
hideTools = "Hide unavailable tools ▴"
|
||||
messageNoFallback = "Tools are unavailable until your server comes back online."
|
||||
messageWithFallback = "Some tools require a server connection."
|
||||
showTools = "View unavailable tools ▾"
|
||||
title = "Your Stirling-PDF server is unreachable"
|
||||
toolNotAvailableLocally = "Your Stirling-PDF server is offline and \"{{endpoint}}\" is not available on the local backend."
|
||||
|
||||
[session]
|
||||
expired = "Your session has expired. Please refresh the page and try again."
|
||||
refreshPage = "Refresh Page"
|
||||
@@ -6636,7 +6531,6 @@ favorites = "Favourites"
|
||||
heading = "All tools (fullscreen view)"
|
||||
noResults = "Try adjusting your search or toggle descriptions to find what you need."
|
||||
recommended = "Recommended"
|
||||
selfHostedOffline = "Requires your Stirling-PDF server (currently offline):"
|
||||
showDetails = "Show Details"
|
||||
unavailable = "Disabled by server administrator:"
|
||||
unavailableDependency = "Unavailable - required tool missing on server:"
|
||||
|
||||
@@ -1670,7 +1670,7 @@ documentName = "Documento"
|
||||
endDate = "Data di fine"
|
||||
error = "Errore nel caricamento degli eventi"
|
||||
eventDetails = "Dettagli evento"
|
||||
failure = "Non riuscito"
|
||||
failure = "Fallimento"
|
||||
fileHash = "Hash del file"
|
||||
filterByType = "Filtra per tipo"
|
||||
filterByUser = "Filtra per utente"
|
||||
@@ -1680,7 +1680,7 @@ outcome = "Stato"
|
||||
sortAsc = "Ordina crescente"
|
||||
sortDesc = "Ordina decrescente"
|
||||
startDate = "Data di inizio"
|
||||
success = "Avvenuto con uccesso"
|
||||
success = "Successo"
|
||||
timestamp = "Timestamp"
|
||||
title = "Eventi di audit"
|
||||
type = "Tipo"
|
||||
@@ -1689,12 +1689,12 @@ viewDetails = "Visualizza dettagli"
|
||||
|
||||
[audit.filters]
|
||||
allOutcomes = "Tutti"
|
||||
failureOnly = "Solo non riusciti"
|
||||
failureOnly = "Solo fallimenti"
|
||||
last7Days = "Ultimi 7 giorni"
|
||||
last30Days = "Ultimi 30 giorni"
|
||||
outcomeFilter = "Esito"
|
||||
quickPresets = "Filtri rapidi"
|
||||
successOnly = "Solo avvenuti con successo"
|
||||
successOnly = "Solo successi"
|
||||
thisMonth = "Questo mese"
|
||||
today = "Oggi"
|
||||
|
||||
@@ -1717,7 +1717,7 @@ enterCode = "Codice di conferma"
|
||||
enterCodeBelow = "Inserisci il codice esattamente come mostrato sopra (maiuscole/minuscole rilevanti)"
|
||||
initiateDelete = "Elimina tutti i dati"
|
||||
irreversible = "IRREVERSIBILE"
|
||||
success = "Avvenuto con successo"
|
||||
success = "Successo"
|
||||
successMessage = "Tutti i dati di audit sono stati cancellati con successo"
|
||||
warning1 = "Questa azione non può essere annullata"
|
||||
warning2 = "L'eliminazione dei dati di audit rimuoverà definitivamente tutti i log storici, inclusi eventi di sicurezza, attività degli utenti e operazioni sui file dal database."
|
||||
@@ -5088,7 +5088,7 @@ dedicatedSupportSlas = "Supporto dedicato e SLA"
|
||||
enterpriseSubscription = "Enterprise"
|
||||
everythingInCredits = "Tutto in Crediti, più:"
|
||||
everythingInFree = "Tutto in Free, più:"
|
||||
fasterThroughput = "Capacità di elaborazione 10x più veloce"
|
||||
fasterThroughput = "Throughput 10x più veloce"
|
||||
forRegularWork = "Per un uso PDF regolare:"
|
||||
freeTier = "Piano Free"
|
||||
fullyPrivateFiles = "File completamente privati"
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Copies missing env files from their .example templates, and warns about
|
||||
* any keys present in the example but not set in the environment.
|
||||
* Also warns about any VITE_ vars set in the environment that aren't listed
|
||||
* in any example file.
|
||||
*
|
||||
* Usage:
|
||||
* tsx scripts/setup-env.ts # checks .env
|
||||
* tsx scripts/setup-env.ts --desktop # also checks .env.desktop
|
||||
* tsx scripts/setup-env.ts --saas # also checks .env.saas
|
||||
*/
|
||||
|
||||
import { existsSync, copyFileSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { config, parse } from 'dotenv';
|
||||
|
||||
// npm scripts run from the directory containing package.json (frontend/)
|
||||
const root = process.cwd();
|
||||
const args = process.argv.slice(2);
|
||||
const isDesktop = args.includes('--desktop');
|
||||
const isSaas = args.includes('--saas');
|
||||
|
||||
console.log('setup-env: see frontend/README.md#environment-variables for documentation');
|
||||
|
||||
function getExampleKeys(exampleFile: string): string[] {
|
||||
const examplePath = join(root, exampleFile);
|
||||
if (!existsSync(examplePath)) return [];
|
||||
return Object.keys(parse(readFileSync(examplePath, 'utf-8')));
|
||||
}
|
||||
|
||||
function ensureEnvFile(envFile: string, exampleFile: string): boolean {
|
||||
const envPath = join(root, envFile);
|
||||
const examplePath = join(root, exampleFile);
|
||||
|
||||
if (!existsSync(examplePath)) {
|
||||
console.warn(`setup-env: ${exampleFile} not found, skipping ${envFile}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!existsSync(envPath)) {
|
||||
copyFileSync(examplePath, envPath);
|
||||
console.log(`setup-env: created ${envFile} from ${exampleFile}`);
|
||||
}
|
||||
|
||||
config({ path: envPath });
|
||||
|
||||
const missing = getExampleKeys(exampleFile).filter(k => !(k in process.env));
|
||||
|
||||
if (missing.length > 0) {
|
||||
console.error(
|
||||
`setup-env: ${envFile} is missing keys from ${exampleFile}:\n` +
|
||||
missing.map(k => ` ${k}`).join('\n') +
|
||||
'\n Add them manually or delete your local file to re-copy from the example.'
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
let failed = false;
|
||||
failed = ensureEnvFile('.env', 'config/.env.example') || failed;
|
||||
|
||||
if (isDesktop) {
|
||||
failed = ensureEnvFile('.env.desktop', 'config/.env.desktop.example') || failed;
|
||||
}
|
||||
|
||||
if (isSaas) {
|
||||
failed = ensureEnvFile('.env.saas', 'config/.env.saas.example') || failed;
|
||||
}
|
||||
|
||||
// Warn about any VITE_ vars set in the environment that aren't listed in any example file.
|
||||
const allExampleKeys = new Set([
|
||||
...getExampleKeys('config/.env.example'),
|
||||
...getExampleKeys('config/.env.desktop.example'),
|
||||
...getExampleKeys('config/.env.saas.example'),
|
||||
]);
|
||||
const unknownViteVars = Object.keys(process.env)
|
||||
.filter(k => k.startsWith('VITE_') && !allExampleKeys.has(k));
|
||||
if (unknownViteVars.length > 0) {
|
||||
console.warn(
|
||||
'setup-env: the following VITE_ vars are set but not listed in any example file:\n' +
|
||||
unknownViteVars.map(k => ` ${k}`).join('\n') +
|
||||
'\n Add them to the appropriate config/.env.*.example file if they are required.'
|
||||
);
|
||||
}
|
||||
|
||||
if (failed) process.exit(1);
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"module": "node16",
|
||||
"moduleResolution": "node16",
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["./**/*.ts"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "Stirling-PDF",
|
||||
"version": "2.7.1",
|
||||
"version": "2.6.0",
|
||||
"identifier": "stirling.pdf.dev",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
@@ -50,6 +50,7 @@
|
||||
"pdf"
|
||||
],
|
||||
"name": "PDF Document",
|
||||
"description": "Open PDF files with Stirling-PDF",
|
||||
"role": "Editor",
|
||||
"mimeType": "application/pdf"
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* Core stub for HomePage extensions.
|
||||
*/
|
||||
|
||||
export function HomePageExtensions() {
|
||||
return null;
|
||||
}
|
||||
@@ -9,62 +9,44 @@ export abstract class DOMCommand {
|
||||
}
|
||||
|
||||
export class RotatePageCommand extends DOMCommand {
|
||||
private originalRotation: number | null = null;
|
||||
|
||||
constructor(
|
||||
private pageId: string,
|
||||
private degrees: number,
|
||||
private getCurrentDocument: () => PDFDocument | null,
|
||||
private setDocument: (doc: PDFDocument) => void
|
||||
private degrees: number
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
const currentDoc = this.getCurrentDocument();
|
||||
if (!currentDoc) return;
|
||||
|
||||
const page = currentDoc.pages.find(p => p.id === this.pageId);
|
||||
if (!page) return;
|
||||
|
||||
if (this.originalRotation === null) {
|
||||
this.originalRotation = page.rotation;
|
||||
}
|
||||
|
||||
const newRotation = ((page.rotation + this.degrees) % 360 + 360) % 360;
|
||||
|
||||
this.setDocument({
|
||||
...currentDoc,
|
||||
pages: currentDoc.pages.map(p =>
|
||||
p.id === this.pageId ? { ...p, rotation: newRotation } : p
|
||||
),
|
||||
});
|
||||
|
||||
// Also update DOM immediately for CSS animation on currently-mounted pages
|
||||
const pageElement = document.querySelector(`[data-page-id="${this.pageId}"]`);
|
||||
if (pageElement) {
|
||||
const img = pageElement.querySelector('img');
|
||||
if (img) img.style.transform = `rotate(${newRotation}deg)`;
|
||||
if (img) {
|
||||
const currentTransform = img.style.transform || '';
|
||||
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
||||
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
||||
let newRotation = currentRotation + this.degrees;
|
||||
|
||||
newRotation = ((newRotation % 360) + 360) % 360;
|
||||
|
||||
img.style.transform = `rotate(${newRotation}deg)`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
if (this.originalRotation === null) return;
|
||||
|
||||
const currentDoc = this.getCurrentDocument();
|
||||
if (!currentDoc) return;
|
||||
|
||||
this.setDocument({
|
||||
...currentDoc,
|
||||
pages: currentDoc.pages.map(p =>
|
||||
p.id === this.pageId ? { ...p, rotation: this.originalRotation! } : p
|
||||
),
|
||||
});
|
||||
|
||||
const pageElement = document.querySelector(`[data-page-id="${this.pageId}"]`);
|
||||
if (pageElement) {
|
||||
const img = pageElement.querySelector('img');
|
||||
if (img) img.style.transform = `rotate(${this.originalRotation}deg)`;
|
||||
if (img) {
|
||||
const currentTransform = img.style.transform || '';
|
||||
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
||||
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
||||
let previousRotation = currentRotation - this.degrees;
|
||||
|
||||
previousRotation = ((previousRotation % 360) + 360) % 360;
|
||||
|
||||
img.style.transform = `rotate(${previousRotation}deg)`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -329,67 +311,38 @@ export class BulkRotateCommand extends DOMCommand {
|
||||
|
||||
constructor(
|
||||
private pageIds: string[],
|
||||
private degrees: number,
|
||||
private getCurrentDocument: () => PDFDocument | null,
|
||||
private setDocument: (doc: PDFDocument) => void
|
||||
private degrees: number
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
const currentDoc = this.getCurrentDocument();
|
||||
if (!currentDoc) return;
|
||||
|
||||
const pageIdSet = new Set(this.pageIds);
|
||||
|
||||
// Store original rotations from state for reliable undo (only on first execution)
|
||||
if (this.originalRotations.size === 0) {
|
||||
for (const page of currentDoc.pages) {
|
||||
if (pageIdSet.has(page.id)) {
|
||||
this.originalRotations.set(page.id, page.rotation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update state so rotation survives virtualizer unmount/remount
|
||||
// Build a map of id → new rotation for O(1) DOM lookups below
|
||||
const newRotationById = new Map<string, number>();
|
||||
const updatedPages = currentDoc.pages.map(page => {
|
||||
if (pageIdSet.has(page.id)) {
|
||||
const newRotation = ((page.rotation + this.degrees) % 360 + 360) % 360;
|
||||
newRotationById.set(page.id, newRotation);
|
||||
return { ...page, rotation: newRotation };
|
||||
}
|
||||
return page;
|
||||
});
|
||||
|
||||
this.setDocument({ ...currentDoc, pages: updatedPages });
|
||||
|
||||
// Mirror to DOM immediately for CSS animation on currently-mounted pages
|
||||
for (const pageId of this.pageIds) {
|
||||
this.pageIds.forEach(pageId => {
|
||||
const pageElement = document.querySelector(`[data-page-id="${pageId}"]`);
|
||||
if (pageElement) {
|
||||
const img = pageElement.querySelector('img');
|
||||
if (img) img.style.transform = `rotate(${newRotationById.get(pageId)}deg)`;
|
||||
if (img) {
|
||||
// Store original rotation for undo (only on first execution)
|
||||
if (!this.originalRotations.has(pageId)) {
|
||||
const currentTransform = img.style.transform || '';
|
||||
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
||||
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
||||
this.originalRotations.set(pageId, currentRotation);
|
||||
}
|
||||
|
||||
// Apply rotation using transform to trigger CSS animation
|
||||
const currentTransform = img.style.transform || '';
|
||||
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
||||
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
||||
const newRotation = currentRotation + this.degrees;
|
||||
img.style.transform = `rotate(${newRotation}deg)`;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
const currentDoc = this.getCurrentDocument();
|
||||
if (!currentDoc) return;
|
||||
|
||||
// Restore original rotations in state
|
||||
const updatedPages = currentDoc.pages.map(page =>
|
||||
this.originalRotations.has(page.id)
|
||||
? { ...page, rotation: this.originalRotations.get(page.id)! }
|
||||
: page
|
||||
);
|
||||
|
||||
this.setDocument({ ...currentDoc, pages: updatedPages });
|
||||
|
||||
// Mirror to DOM immediately for CSS animation on currently-mounted pages
|
||||
for (const pageId of this.pageIds) {
|
||||
this.pageIds.forEach(pageId => {
|
||||
const pageElement = document.querySelector(`[data-page-id="${pageId}"]`);
|
||||
if (pageElement) {
|
||||
const img = pageElement.querySelector('img');
|
||||
@@ -397,7 +350,7 @@ export class BulkRotateCommand extends DOMCommand {
|
||||
img.style.transform = `rotate(${this.originalRotations.get(pageId)}deg)`;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
get description(): string {
|
||||
|
||||
@@ -66,20 +66,20 @@ export const usePageEditorCommands = ({
|
||||
|
||||
const handleRotatePages = useCallback(
|
||||
(pageIds: string[], rotation: number) => {
|
||||
const bulkRotateCommand = new BulkRotateCommand(pageIds, rotation, getEditedDocument, setEditedDocument);
|
||||
const bulkRotateCommand = new BulkRotateCommand(pageIds, rotation);
|
||||
executeCommandWithTracking(bulkRotateCommand);
|
||||
},
|
||||
[executeCommandWithTracking, getEditedDocument, setEditedDocument]
|
||||
[executeCommandWithTracking]
|
||||
);
|
||||
|
||||
const createRotateCommand = useCallback(
|
||||
(pageIds: string[], rotation: number) => ({
|
||||
execute: () => {
|
||||
const bulkRotateCommand = new BulkRotateCommand(pageIds, rotation, getEditedDocument, setEditedDocument);
|
||||
const bulkRotateCommand = new BulkRotateCommand(pageIds, rotation);
|
||||
executeCommandWithTracking(bulkRotateCommand);
|
||||
},
|
||||
}),
|
||||
[executeCommandWithTracking, getEditedDocument, setEditedDocument]
|
||||
[executeCommandWithTracking]
|
||||
);
|
||||
|
||||
const createDeleteCommand = useCallback(
|
||||
|
||||
@@ -28,7 +28,6 @@ import {
|
||||
} from '@app/components/shared/quickAccessBar/QuickAccessBar';
|
||||
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '@app/styles/zIndex';
|
||||
import { QuickAccessBarFooterExtensions } from '@app/components/quickAccessBar/QuickAccessBarFooterExtensions';
|
||||
import { useConfigButtonIcon } from '@app/hooks/useConfigButtonIcon';
|
||||
|
||||
const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -45,8 +44,6 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
const [configModalOpen, setConfigModalOpen] = useState(false);
|
||||
const [activeButton, setActiveButton] = useState<string>('tools');
|
||||
const scrollableRef = useRef<HTMLDivElement>(null);
|
||||
const configButtonIcon = useConfigButtonIcon();
|
||||
|
||||
const {
|
||||
tooltipOpen,
|
||||
manualCloseOnly,
|
||||
@@ -205,7 +202,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
...(shouldHideSettingsButton ? [] : [{
|
||||
id: 'config',
|
||||
name: t("quickAccess.settings", "Settings"),
|
||||
icon: configButtonIcon ?? <LocalIcon icon="settings-rounded" width="1.25rem" height="1.25rem" />,
|
||||
icon: <LocalIcon icon="settings-rounded" width="1.25rem" height="1.25rem" />,
|
||||
size: 'md' as const,
|
||||
type: 'modal' as const,
|
||||
onClick: () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { NavKey, VALID_NAV_KEYS } from '@app/components/shared/config/types';
|
||||
import { Z_INDEX_OVER_CONFIG_MODAL } from '@app/styles/zIndex';
|
||||
import type { ConfigNavSection, ConfigNavItem } from '@app/components/shared/config/configNavSections';
|
||||
import type { ConfigNavSection, ConfigNavItem } from '@core/components/shared/config/configNavSections';
|
||||
|
||||
interface SettingsSearchBarProps {
|
||||
configNavSections: ConfigNavSection[];
|
||||
|
||||
@@ -30,11 +30,9 @@ const BANNER_DISMISSED_KEY = "stirlingpdf_features_banner_dismissed";
|
||||
|
||||
interface GeneralSectionProps {
|
||||
hideTitle?: boolean;
|
||||
hideUpdateSection?: boolean;
|
||||
hideAdminBanner?: boolean;
|
||||
}
|
||||
|
||||
const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hideUpdateSection = false, hideAdminBanner = false }) => {
|
||||
const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false }) => {
|
||||
const { t } = useTranslation();
|
||||
const { preferences, updatePreference } = usePreferences();
|
||||
const { config } = useAppConfig();
|
||||
@@ -158,7 +156,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!hideAdminBanner && loginDisabled && !bannerDismissed && (
|
||||
{loginDisabled && !bannerDismissed && (
|
||||
<Paper withBorder p="md" radius="md" style={{ background: "var(--mantine-color-blue-0)", position: "relative" }}>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
@@ -217,7 +215,7 @@ const GeneralSection: React.FC<GeneralSectionProps> = ({ hideTitle = false, hide
|
||||
)}
|
||||
|
||||
{/* Update Check Section */}
|
||||
{!hideUpdateSection && config?.appVersion && (
|
||||
{config?.appVersion && (
|
||||
<Paper withBorder p="md" radius="md">
|
||||
<Stack gap="md">
|
||||
<div>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { Stack, Text, NumberInput, Select, Divider, Checkbox, Slider, SegmentedControl, Tooltip, Box } from "@mantine/core";
|
||||
import { useState, useEffect } from "react";
|
||||
import { Stack, Text, NumberInput, Select, Divider, Checkbox, Slider, SegmentedControl } from "@mantine/core";
|
||||
import SliderWithInput from '@app/components/shared/sliderWithInput/SliderWithInput';
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CompressParameters } from "@app/hooks/tools/compress/useCompressParameters";
|
||||
import ButtonSelector from "@app/components/shared/ButtonSelector";
|
||||
import { useGroupEnabled } from "@app/hooks/useGroupEnabled";
|
||||
import apiClient from "@app/services/apiClient";
|
||||
import { Z_INDEX_AUTOMATE_DROPDOWN } from "@app/styles/zIndex";
|
||||
|
||||
interface CompressSettingsProps {
|
||||
@@ -14,7 +15,20 @@ interface CompressSettingsProps {
|
||||
|
||||
const CompressSettings = ({ parameters, onParameterChange, disabled = false }: CompressSettingsProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { enabled: imageMagickAvailable, unavailableReason: imageMagickReason } = useGroupEnabled('ImageMagick');
|
||||
const [imageMagickAvailable, setImageMagickAvailable] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const checkImageMagick = async () => {
|
||||
try {
|
||||
const response = await apiClient.get<boolean>('/api/v1/config/group-enabled?group=ImageMagick');
|
||||
setImageMagickAvailable(response.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to check ImageMagick availability:', error);
|
||||
setImageMagickAvailable(true); // Optimistic fallback
|
||||
}
|
||||
};
|
||||
checkImageMagick();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
@@ -108,27 +122,17 @@ const CompressSettings = ({ parameters, onParameterChange, disabled = false }: C
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Tooltip
|
||||
label={imageMagickReason ?? t("compress.lineArt.unavailable", "ImageMagick is not installed or enabled on this server")}
|
||||
disabled={imageMagickAvailable !== false}
|
||||
multiline
|
||||
maw={280}
|
||||
>
|
||||
<Box style={{ cursor: imageMagickAvailable === false ? 'not-allowed' : undefined }}>
|
||||
<Checkbox
|
||||
checked={parameters.lineArt}
|
||||
onChange={(event) => onParameterChange('lineArt', event.currentTarget.checked)}
|
||||
disabled={disabled || imageMagickAvailable === false}
|
||||
label={t("compress.lineArt.label", "Convert images to line art (bilevel)")}
|
||||
description={
|
||||
imageMagickAvailable !== false
|
||||
? t("compress.lineArt.description", "Uses ImageMagick to reduce pages to high-contrast black and white for maximum size reduction.")
|
||||
: undefined
|
||||
}
|
||||
style={{ pointerEvents: imageMagickAvailable === false ? 'none' : undefined }}
|
||||
/>
|
||||
</Box>
|
||||
</Tooltip>
|
||||
<Checkbox
|
||||
checked={parameters.lineArt}
|
||||
onChange={(event) => onParameterChange('lineArt', event.currentTarget.checked)}
|
||||
disabled={disabled || imageMagickAvailable === false}
|
||||
label={t("compress.lineArt.label", "Convert images to line art (bilevel)")}
|
||||
description={
|
||||
imageMagickAvailable === false
|
||||
? t("compress.lineArt.unavailable", "ImageMagick is not installed or enabled on this server")
|
||||
: t("compress.lineArt.description", "Uses ImageMagick to reduce pages to high-contrast black and white for maximum size reduction.")
|
||||
}
|
||||
/>
|
||||
{parameters.lineArt && (
|
||||
<Stack gap="xs" style={{ opacity: (disabled || imageMagickAvailable === false) ? 0.6 : 1 }}>
|
||||
<Text size="sm" fw={600}>{t('compress.lineArt.detailLevel', 'Detail level')}</Text>
|
||||
|
||||
@@ -24,7 +24,7 @@ export const getIconStyle = (): Record<string, string> => {
|
||||
return {};
|
||||
};
|
||||
|
||||
export type ToolDisabledReason = 'comingSoon' | 'disabledByAdmin' | 'missingDependency' | 'unknownUnavailable' | 'requiresPremium' | 'selfHostedOffline' | null;
|
||||
export type ToolDisabledReason = 'comingSoon' | 'disabledByAdmin' | 'missingDependency' | 'unknownUnavailable' | 'requiresPremium' | null;
|
||||
|
||||
export const getToolDisabledReason = (
|
||||
id: string,
|
||||
@@ -43,9 +43,6 @@ export const getToolDisabledReason = (
|
||||
|
||||
const availabilityInfo = toolAvailability?.[id as ToolId];
|
||||
if (availabilityInfo && availabilityInfo.available === false) {
|
||||
if (availabilityInfo.reason === 'selfHostedOffline') {
|
||||
return 'selfHostedOffline';
|
||||
}
|
||||
if (availabilityInfo.reason === 'missingDependency') {
|
||||
return 'missingDependency';
|
||||
}
|
||||
@@ -67,12 +64,6 @@ export const getDisabledLabel = (
|
||||
fallback: 'Premium feature:'
|
||||
};
|
||||
}
|
||||
if (disabledReason === 'selfHostedOffline') {
|
||||
return {
|
||||
key: 'toolPanel.fullscreen.selfHostedOffline',
|
||||
fallback: 'Requires your Stirling-PDF server (currently offline):'
|
||||
};
|
||||
}
|
||||
if (disabledReason === 'missingDependency') {
|
||||
return {
|
||||
key: 'toolPanel.fullscreen.unavailableDependency',
|
||||
|
||||
@@ -36,8 +36,8 @@ const OperationButton = ({
|
||||
'data-tour': dataTour
|
||||
}: OperationButtonProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { isOnline, message: backendMessage } = useBackendHealth();
|
||||
const blockedByBackend = !isOnline;
|
||||
const { isHealthy, message: backendMessage } = useBackendHealth();
|
||||
const blockedByBackend = !isHealthy;
|
||||
const combinedDisabled = disabled || blockedByBackend;
|
||||
const tooltipLabel = blockedByBackend
|
||||
? (backendMessage ?? t('backendHealth.checking', 'Checking backend status...'))
|
||||
|
||||
@@ -71,31 +71,6 @@ export const ENDPOINT_NAMES = {
|
||||
'text-editor-pdf': 'text-editor-to-pdf'
|
||||
} as const;
|
||||
|
||||
/** Maps conversion endpoint → [i18n key, English fallback] for display names */
|
||||
export const ENDPOINT_I18N: Record<string, [string, string]> = {
|
||||
'img-to-pdf': ['imageToPDF.header', 'Image → PDF'],
|
||||
'html-to-pdf': ['HTMLToPDF.header', 'HTML → PDF'],
|
||||
'markdown-to-pdf': ['MarkdownToPDF.header', 'Markdown → PDF'],
|
||||
'pdf-to-img': ['pdfToImage.title', 'PDF → Image'],
|
||||
'pdf-to-word': ['PDFToWord.header', 'PDF → Word'],
|
||||
'pdf-to-presentation': ['PDFToPresentation.header', 'PDF → Presentation'],
|
||||
'pdf-to-text': ['PDFToText.header', 'PDF → Text'],
|
||||
'pdf-to-csv': ['PDFToCSV.header', 'PDF → CSV'],
|
||||
'pdf-to-xlsx': ['PDFToXLSX.header', 'PDF → Excel'],
|
||||
'pdf-to-markdown': ['PDFToMarkdown.header', 'PDF → Markdown'],
|
||||
'pdf-to-html': ['PDFToHTML.header', 'PDF → HTML'],
|
||||
'pdf-to-xml': ['PDFToXML.header', 'PDF → XML'],
|
||||
'pdf-to-pdfa': ['pdfToPDFA.header', 'PDF → PDF/A'],
|
||||
'file-to-pdf': ['convert.fileToPdf', 'Office/Document → PDF'],
|
||||
'cbr-to-pdf': ['convert.cbrToPdf', 'CBR → PDF'],
|
||||
'cbz-to-pdf': ['convert.cbzToPdf', 'CBZ → PDF'],
|
||||
'eml-to-pdf': ['convert.emlToPdf', 'Email → PDF'],
|
||||
'ebook-to-pdf': ['convert.ebookToPdf', 'eBook → PDF'],
|
||||
'svg-to-pdf': ['convert.svgToPdf', 'SVG → PDF'],
|
||||
'pdf-to-cbr': ['convert.pdfToCbr', 'PDF → CBR'],
|
||||
'pdf-to-cbz': ['convert.pdfToCbz', 'PDF → CBZ'],
|
||||
'pdf-to-epub': ['convert.pdfToEpub', 'PDF → EPUB'],
|
||||
};
|
||||
|
||||
// Grouped file extensions for dropdowns
|
||||
export const FROM_FORMAT_OPTIONS = [
|
||||
|
||||
@@ -2,7 +2,6 @@ import React, { createContext, useContext, useState, useEffect, ReactNode, useCa
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import { getSimulatedAppConfig } from '@app/testing/serverExperienceSimulations';
|
||||
import type { AppConfig, AppConfigBootstrapMode } from '@app/types/appConfig';
|
||||
import { useJwtConfigSync } from '@app/hooks/useJwtConfigSync';
|
||||
|
||||
/**
|
||||
* Sleep utility for delays
|
||||
@@ -42,7 +41,6 @@ export interface AppConfigProviderProps {
|
||||
initialConfig?: AppConfig | null;
|
||||
bootstrapMode?: AppConfigBootstrapMode;
|
||||
autoFetch?: boolean;
|
||||
onConfigLoaded?: (config: AppConfig) => void;
|
||||
}
|
||||
|
||||
export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
@@ -51,7 +49,6 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
initialConfig = null,
|
||||
bootstrapMode = 'blocking',
|
||||
autoFetch = true,
|
||||
onConfigLoaded,
|
||||
}) => {
|
||||
const isBlockingMode = bootstrapMode === 'blocking';
|
||||
const [config, setConfig] = useState<AppConfig | null>(initialConfig);
|
||||
@@ -61,9 +58,6 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
const [hasResolvedConfig, setHasResolvedConfig] = useState(Boolean(initialConfig) && !isBlockingMode);
|
||||
const [loading, setLoading] = useState(!hasResolvedConfig);
|
||||
|
||||
const onConfigLoadedRef = React.useRef(onConfigLoaded);
|
||||
onConfigLoadedRef.current = onConfigLoaded;
|
||||
|
||||
const maxRetries = retryOptions?.maxRetries ?? 0;
|
||||
const initialDelay = retryOptions?.initialDelay ?? 1000;
|
||||
|
||||
@@ -119,7 +113,6 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
setConfig(data);
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
onConfigLoadedRef.current?.(data);
|
||||
return; // Success - exit function
|
||||
} catch (err: any) {
|
||||
const status = err?.response?.status;
|
||||
@@ -158,21 +151,42 @@ export const AppConfigProvider: React.FC<AppConfigProviderProps> = ({
|
||||
setLoading(false);
|
||||
}, [hasResolvedConfig, isBlockingMode, maxRetries, initialDelay]);
|
||||
|
||||
const { isAuthPage } = useJwtConfigSync(fetchConfig);
|
||||
|
||||
useEffect(() => {
|
||||
// Skip config fetch on auth pages (/login, /signup, /auth/callback, /invite/*)
|
||||
// Config will be fetched after successful authentication via jwt-available event
|
||||
const currentPath = window.location.pathname;
|
||||
const isAuthPage = currentPath.includes('/login') ||
|
||||
currentPath.includes('/signup') ||
|
||||
currentPath.includes('/auth/callback') ||
|
||||
currentPath.includes('/invite/');
|
||||
|
||||
// On auth pages, always skip the config fetch
|
||||
// The config will be fetched after authentication via jwt-available event
|
||||
if (isAuthPage) {
|
||||
console.debug('[AppConfig] On auth page - using default config, skipping fetch', { path: window.location.pathname });
|
||||
console.debug('[AppConfig] On auth page - using default config, skipping fetch', { path: currentPath });
|
||||
setConfig({ enableLogin: true });
|
||||
setHasResolvedConfig(true);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// On non-auth pages, fetch config (will validate JWT if present)
|
||||
if (autoFetch) {
|
||||
fetchConfig();
|
||||
}
|
||||
}, [autoFetch, fetchConfig, isAuthPage]);
|
||||
}, [autoFetch, fetchConfig]);
|
||||
|
||||
// Listen for JWT availability (triggered on login/signup)
|
||||
useEffect(() => {
|
||||
const handleJwtAvailable = () => {
|
||||
console.debug('[AppConfig] JWT available event - refetching config');
|
||||
// Force refetch with JWT
|
||||
fetchConfig(true);
|
||||
};
|
||||
|
||||
window.addEventListener('jwt-available', handleJwtAvailable);
|
||||
return () => window.removeEventListener('jwt-available', handleJwtAvailable);
|
||||
}, [fetchConfig]);
|
||||
|
||||
const refetch = useCallback(() => fetchConfig(true), [fetchConfig]);
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { readFileSync, readdirSync, statSync } from 'fs';
|
||||
import { join, extname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
// frontend/ root — this file lives at src/core/env.test.ts
|
||||
const frontendRoot = join(fileURLToPath(import.meta.url), '../../..');
|
||||
|
||||
function parseEnvKeys(content: string): Set<string> {
|
||||
const keys = new Set<string>();
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (trimmed && !trimmed.startsWith('#')) {
|
||||
const match = trimmed.match(/^([A-Z_][A-Z0-9_]*)=/);
|
||||
if (match) keys.add(match[1]);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
function collectSourceFiles(dir: string): string[] {
|
||||
const files: string[] = [];
|
||||
for (const entry of readdirSync(dir)) {
|
||||
const fullPath = join(dir, entry);
|
||||
const stat = statSync(fullPath);
|
||||
if (stat.isDirectory() && entry !== 'node_modules' && entry !== 'assets') {
|
||||
files.push(...collectSourceFiles(fullPath));
|
||||
} else if (stat.isFile() && (extname(entry) === '.ts' || extname(entry) === '.tsx') && !entry.endsWith('.d.ts')) {
|
||||
files.push(fullPath);
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function findViteEnvVars(srcDir: string): Set<string> {
|
||||
const vars = new Set<string>();
|
||||
for (const file of collectSourceFiles(srcDir)) {
|
||||
const content = readFileSync(file, 'utf-8');
|
||||
for (const match of content.matchAll(/import\.meta\.env\.(VITE_\w+)/g)) {
|
||||
vars.add(match[1]);
|
||||
}
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
describe('env vars', () => {
|
||||
it('every VITE_ var used in source is present in an example env file', () => {
|
||||
const baseEnv = readFileSync(join(frontendRoot, 'config/.env.example'), 'utf-8');
|
||||
const desktopEnv = readFileSync(join(frontendRoot, 'config/.env.desktop.example'), 'utf-8');
|
||||
const saasEnv = readFileSync(join(frontendRoot, 'config/.env.saas.example'), 'utf-8');
|
||||
|
||||
const exampleKeys = new Set([...parseEnvKeys(baseEnv), ...parseEnvKeys(desktopEnv), ...parseEnvKeys(saasEnv)]);
|
||||
const sourceVars = findViteEnvVars(join(frontendRoot, 'src'));
|
||||
|
||||
const missing = [...sourceVars].filter(v => !exampleKeys.has(v));
|
||||
expect(missing, `Missing from 'frontend/config/.env.example' files: ${missing.join(', ')}`).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -121,11 +121,13 @@ export const useToolOperation = <TParams>(
|
||||
? config.endpoint(params)
|
||||
: config.endpoint;
|
||||
|
||||
// Credit check — no-op in core builds, real check in desktop/SaaS versions
|
||||
const creditError = await checkCredits();
|
||||
if (creditError !== null) {
|
||||
actions.setError(creditError);
|
||||
return;
|
||||
// Credit check for cloud operations (desktop SaaS mode only, no-op in web builds)
|
||||
if (willUseCloud && endpoint) {
|
||||
const creditError = await checkCredits();
|
||||
if (creditError !== null) {
|
||||
actions.setError(creditError);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Backend readiness check (will skip for SaaS-routed endpoints)
|
||||
|
||||
@@ -5,6 +5,6 @@ export function useBackendHealth(): BackendHealthState {
|
||||
status: 'healthy',
|
||||
message: null,
|
||||
error: null,
|
||||
isOnline: true,
|
||||
isHealthy: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
/**
|
||||
* Core stub — config button uses the default settings icon.
|
||||
*/
|
||||
export function useConfigButtonIcon(): React.ReactNode {
|
||||
return null;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import type { GroupEnabledResult } from '@app/types/groupEnabled';
|
||||
|
||||
export type { GroupEnabledResult };
|
||||
|
||||
/**
|
||||
* Checks whether a named feature group is enabled on the backend.
|
||||
* Returns { enabled: null } while loading, then true/false with an optional reason.
|
||||
*/
|
||||
export function useGroupEnabled(group: string): GroupEnabledResult {
|
||||
const [result, setResult] = useState<GroupEnabledResult>({ enabled: null, unavailableReason: null });
|
||||
const isMountedRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
isMountedRef.current = true;
|
||||
return () => { isMountedRef.current = false; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
apiClient
|
||||
.get<boolean>(`/api/v1/config/group-enabled?group=${encodeURIComponent(group)}`)
|
||||
.then(res => { if (isMountedRef.current) setResult({ enabled: res.data, unavailableReason: null }); })
|
||||
.catch(() => { if (isMountedRef.current) setResult({ enabled: false, unavailableReason: null }); });
|
||||
}, [group]);
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Core implementation: sets up the jwt-available event listener for OSS JWT auth,
|
||||
* and detects auth pages where config fetch should be skipped.
|
||||
*/
|
||||
export function useJwtConfigSync(fetchConfig: (force?: boolean) => void): { isAuthPage: boolean } {
|
||||
const currentPath = window.location.pathname;
|
||||
const isAuthPage =
|
||||
currentPath.includes('/login') ||
|
||||
currentPath.includes('/signup') ||
|
||||
currentPath.includes('/auth/callback') ||
|
||||
currentPath.includes('/invite/');
|
||||
|
||||
useEffect(() => {
|
||||
const handleJwtAvailable = () => {
|
||||
console.debug('[AppConfig] JWT available event - refetching config');
|
||||
fetchConfig(true);
|
||||
};
|
||||
|
||||
window.addEventListener('jwt-available', handleJwtAvailable);
|
||||
return () => window.removeEventListener('jwt-available', handleJwtAvailable);
|
||||
}, [fetchConfig]);
|
||||
|
||||
return { isAuthPage };
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
/**
|
||||
* Stub implementation for web builds.
|
||||
* In desktop builds this is shadowed by desktop/hooks/useSaaSMode.ts which
|
||||
* returns whether the app is currently in SaaS connection mode (vs self-hosted).
|
||||
*/
|
||||
export function useSaaSMode(): boolean {
|
||||
return false;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/**
|
||||
* Stub implementation for web / SaaS builds.
|
||||
* In self-hosted desktop mode this is shadowed by the desktop override which
|
||||
* returns the set of tool IDs that are unavailable when the self-hosted server
|
||||
* is offline (i.e. tools whose endpoints the local bundled backend does not support).
|
||||
*/
|
||||
export function useSelfHostedToolAvailability(
|
||||
_tools: Array<{ id: string; endpoints?: string[] }>
|
||||
): Set<string> {
|
||||
return new Set<string>();
|
||||
}
|
||||
@@ -3,13 +3,11 @@ import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
|
||||
import { usePreferences } from '@app/contexts/PreferencesContext';
|
||||
import { getAllEndpoints, type ToolRegistryEntry, type ToolRegistry } from "@app/data/toolsTaxonomy";
|
||||
import { useMultipleEndpointsEnabled } from "@app/hooks/useEndpointConfig";
|
||||
import { useSelfHostedToolAvailability } from "@app/hooks/useSelfHostedToolAvailability";
|
||||
import { useSaaSMode } from "@app/hooks/useSaaSMode";
|
||||
import { FileId } from '@app/types/file';
|
||||
import { ToolId } from "@app/types/toolId";
|
||||
import type { EndpointDisableReason } from '@app/types/endpointAvailability';
|
||||
|
||||
export type ToolDisableCause = 'disabledByAdmin' | 'missingDependency' | 'unknown' | 'selfHostedOffline';
|
||||
export type ToolDisableCause = 'disabledByAdmin' | 'missingDependency' | 'unknown';
|
||||
|
||||
export interface ToolAvailabilityInfo {
|
||||
available: boolean;
|
||||
@@ -30,59 +28,30 @@ interface ToolManagementResult {
|
||||
export const useToolManagement = (): ToolManagementResult => {
|
||||
const [toolSelectedFileIds, setToolSelectedFileIds] = useState<FileId[]>([]);
|
||||
|
||||
// Build endpoints list from registry entries with fallback to legacy mapping
|
||||
const { allTools } = useToolRegistry();
|
||||
const baseRegistry = allTools;
|
||||
const { preferences } = usePreferences();
|
||||
const isSaaSMode = useSaaSMode();
|
||||
|
||||
const allEndpoints = useMemo(() => getAllEndpoints(baseRegistry), [baseRegistry]);
|
||||
const { endpointStatus, endpointDetails, loading: endpointsLoading } = useMultipleEndpointsEnabled(allEndpoints);
|
||||
|
||||
const toolEndpointList = useMemo(
|
||||
() => (Object.keys(baseRegistry) as ToolId[])
|
||||
// Exclude coming-soon tools (no component and no link) — they are already
|
||||
// unavailable regardless of server state and should not appear in the
|
||||
// self-hosted offline banner.
|
||||
.filter(id => {
|
||||
const tool = baseRegistry[id];
|
||||
return !!(tool?.component ?? tool?.link);
|
||||
})
|
||||
.map(id => ({
|
||||
id,
|
||||
endpoints: baseRegistry[id]?.endpoints ?? [],
|
||||
})),
|
||||
[baseRegistry]
|
||||
);
|
||||
const selfHostedOfflineIds = useSelfHostedToolAvailability(toolEndpointList);
|
||||
|
||||
const isToolAvailable = useCallback((toolKey: string): boolean => {
|
||||
// Self-hosted offline check must come before the loading gate:
|
||||
// in self-hosted offline mode endpointsLoading stays true indefinitely
|
||||
// (health check never resolves), so checking it first would wrongly
|
||||
// keep all tools enabled.
|
||||
if (selfHostedOfflineIds.has(toolKey)) return false;
|
||||
|
||||
// Keep tools enabled while endpoint status is loading (optimistic UX)
|
||||
// Keep tools enabled during loading (optimistic UX)
|
||||
if (endpointsLoading) return true;
|
||||
|
||||
const tool = baseRegistry[toolKey as ToolId];
|
||||
const endpoints = tool?.endpoints || [];
|
||||
|
||||
// Tools without endpoints are always available
|
||||
if (endpoints.length === 0) return true;
|
||||
|
||||
const hasLocalSupport = endpoints.some((endpoint: string) => endpointStatus[endpoint] !== false);
|
||||
|
||||
// In SaaS mode tools without local support can route to the cloud backend
|
||||
if (!hasLocalSupport && isSaaSMode) return true;
|
||||
|
||||
return hasLocalSupport;
|
||||
}, [endpointsLoading, endpointStatus, baseRegistry, isSaaSMode, selfHostedOfflineIds]);
|
||||
// Check if at least one endpoint is enabled
|
||||
// If endpoint is not in status map, assume enabled (optimistic fallback)
|
||||
return endpoints.some((endpoint: string) => endpointStatus[endpoint] !== false);
|
||||
}, [endpointsLoading, endpointStatus, baseRegistry]);
|
||||
|
||||
const deriveToolDisableReason = useCallback((toolKey: ToolId): ToolDisableCause => {
|
||||
if (selfHostedOfflineIds.has(toolKey)) {
|
||||
return 'selfHostedOffline';
|
||||
}
|
||||
|
||||
const tool = baseRegistry[toolKey];
|
||||
if (!tool) {
|
||||
return 'unknown';
|
||||
@@ -102,13 +71,10 @@ export const useToolManagement = (): ToolManagementResult => {
|
||||
return 'unknown';
|
||||
}
|
||||
return 'unknown';
|
||||
}, [baseRegistry, endpointDetails, endpointStatus, selfHostedOfflineIds]);
|
||||
}, [baseRegistry, endpointDetails, endpointStatus]);
|
||||
|
||||
const toolAvailability = useMemo(() => {
|
||||
// Skip computation during loading UNLESS some tools are already known offline.
|
||||
// In self-hosted offline mode endpointsLoading never clears, so we must still
|
||||
// compute the map to surface the selfHostedOfflineIds set.
|
||||
if (endpointsLoading && selfHostedOfflineIds.size === 0) {
|
||||
if (endpointsLoading) {
|
||||
return {};
|
||||
}
|
||||
const availability: ToolAvailabilityMap = {};
|
||||
@@ -119,7 +85,7 @@ export const useToolManagement = (): ToolManagementResult => {
|
||||
: { available: false, reason: deriveToolDisableReason(toolKey) };
|
||||
});
|
||||
return availability;
|
||||
}, [baseRegistry, deriveToolDisableReason, endpointsLoading, isToolAvailable, selfHostedOfflineIds]);
|
||||
}, [baseRegistry, deriveToolDisableReason, endpointsLoading, isToolAvailable]);
|
||||
|
||||
const toolRegistry: Partial<ToolRegistry> = useMemo(() => {
|
||||
const availableToolRegistry: Partial<ToolRegistry> = {};
|
||||
@@ -149,7 +115,7 @@ export const useToolManagement = (): ToolManagementResult => {
|
||||
}, [toolRegistry]);
|
||||
|
||||
return {
|
||||
selectedTool: getSelectedTool(null),
|
||||
selectedTool: getSelectedTool(null), // This will be unused, kept for compatibility
|
||||
toolSelectedFileIds,
|
||||
toolRegistry,
|
||||
setToolSelectedFileIds,
|
||||
|
||||
@@ -23,7 +23,6 @@ import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
import { useFilesModalContext } from "@app/contexts/FilesModalContext";
|
||||
import AppConfigModal from "@app/components/shared/AppConfigModal";
|
||||
import { getStartupNavigationAction } from "@app/utils/homePageNavigation";
|
||||
import { HomePageExtensions } from "@app/components/home/HomePageExtensions";
|
||||
|
||||
import "@app/pages/HomePage.css";
|
||||
|
||||
@@ -205,7 +204,6 @@ export default function HomePage() {
|
||||
|
||||
return (
|
||||
<div className="h-screen overflow-hidden">
|
||||
<HomePageExtensions />
|
||||
{isMobile ? (
|
||||
<div className="mobile-layout">
|
||||
<div className="mobile-toggle">
|
||||
|
||||
@@ -15,5 +15,5 @@ export function getApiBaseUrl(): string {
|
||||
return (window as any).STIRLING_PDF_API_BASE_URL;
|
||||
}
|
||||
|
||||
return import.meta.env.VITE_API_BASE_URL;
|
||||
return import.meta.env.VITE_API_BASE_URL || '/';
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createClient, SupabaseClient } from '@supabase/supabase-js';
|
||||
|
||||
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
|
||||
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY;
|
||||
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL || 'https://rficokptxxxxtyzcvgmx.supabase.co';
|
||||
const supabaseAnonKey = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY || 'sb_publishable_UHz2SVRF5mvdrPHWkRteyA_yNlZTkYb';
|
||||
|
||||
// Check if Supabase is configured
|
||||
export const isSupabaseConfigured = !!(supabaseUrl && supabaseAnonKey);
|
||||
|
||||
@@ -13,13 +13,3 @@
|
||||
@layer utilities {
|
||||
@tailwind utilities;
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
.no-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.no-scrollbar {
|
||||
-ms-overflow-style: none; /* IE and Edge */
|
||||
scrollbar-width: none; /* Firefox */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
|
||||
|
||||
const BASE_NO_LOGIN_CONFIG: AppConfig = {
|
||||
enableAnalytics: true,
|
||||
appVersion: '2.7.1',
|
||||
appVersion: '2.6.0',
|
||||
serverCertificateEnabled: false,
|
||||
enableAlphaFunctionality: false,
|
||||
serverPort: 8080,
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "../../",
|
||||
"paths": {
|
||||
"@app/*": [
|
||||
"src/core/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"../global.d.ts",
|
||||
"../*.js",
|
||||
"../*.ts",
|
||||
"../*.tsx",
|
||||
"."
|
||||
]
|
||||
}
|
||||
@@ -4,5 +4,5 @@ export interface BackendHealthState {
|
||||
status: BackendStatus;
|
||||
message?: string | null;
|
||||
error: string | null;
|
||||
isOnline: boolean;
|
||||
isHealthy: boolean;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export type EndpointDisableReason = 'CONFIG' | 'DEPENDENCY' | 'UNKNOWN' | 'NOT_SUPPORTED_LOCALLY' | null;
|
||||
export type EndpointDisableReason = 'CONFIG' | 'DEPENDENCY' | 'UNKNOWN' | null;
|
||||
|
||||
export interface EndpointAvailabilityDetails {
|
||||
enabled: boolean;
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
export interface GroupEnabledResult {
|
||||
enabled: boolean | null;
|
||||
/** Human-readable reason shown when the feature is unavailable. Null while loading or when enabled. */
|
||||
unavailableReason: string | null;
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
Stirling PDF User License
|
||||
|
||||
Copyright (c) 2025 Stirling PDF Inc.
|
||||
|
||||
License Scope & Usage Rights
|
||||
|
||||
Production use of the Stirling PDF Software is only permitted with a valid Stirling PDF User License.
|
||||
|
||||
For purposes of this license, “the Software” refers to the Stirling PDF application and any associated documentation files
|
||||
provided by Stirling PDF Inc. You or your organization may not use the Software in production, at scale, or for business-critical
|
||||
processes unless you have agreed to, and remain in compliance with, the Stirling PDF Subscription Terms of Service
|
||||
(https://www.stirlingpdf.com/terms) or another valid agreement with Stirling PDF, and hold an active User License subscription
|
||||
covering the appropriate number of licensed users.
|
||||
|
||||
Trial and Minimal Use
|
||||
|
||||
You may use the Software without a paid subscription for the sole purposes of internal trial, evaluation, or minimal use, provided that:
|
||||
* Use is limited to the capabilities and restrictions defined by the Software itself;
|
||||
* You do not copy, distribute, sublicense, reverse-engineer, or use the Software in client-facing or commercial contexts.
|
||||
|
||||
Continued use beyond this scope requires a valid Stirling PDF User License.
|
||||
|
||||
Modifications and Derivative Works
|
||||
|
||||
You may modify the Software only for development or internal testing purposes. Any such modifications or derivative works:
|
||||
|
||||
* May not be deployed in production environments without a valid User License;
|
||||
* May not be distributed or sublicensed;
|
||||
* Remain the intellectual property of Stirling PDF and/or its licensors;
|
||||
* May only be used, copied, or exploited in accordance with the terms of a valid Stirling PDF User License subscription.
|
||||
|
||||
Prohibited Actions
|
||||
|
||||
Unless explicitly permitted by a paid license or separate agreement, you may not:
|
||||
|
||||
* Use the Software in production environments;
|
||||
* Copy, merge, distribute, sublicense, or sell the Software;
|
||||
* Remove or alter any licensing or copyright notices;
|
||||
* Circumvent access restrictions or licensing requirements.
|
||||
|
||||
Third-Party Components
|
||||
|
||||
The Stirling PDF Software may include components subject to separate open source licenses. Such components remain governed by
|
||||
their original license terms as provided by their respective owners.
|
||||
|
||||
Disclaimer
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -9,7 +9,6 @@ import { useBackendInitializer } from '@app/hooks/useBackendInitializer';
|
||||
import { DESKTOP_DEFAULT_APP_CONFIG } from '@app/config/defaultAppConfig';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import { authService } from '@app/services/authService';
|
||||
import { endpointAvailabilityService } from '@app/services/endpointAvailabilityService';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
@@ -65,17 +64,7 @@ export function AppProviders({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
if (setupComplete && !isFirstLaunch && connectionMode === 'selfhosted') {
|
||||
void tauriBackendService.initializeExternalBackend();
|
||||
// Also start the self-hosted server monitor so the operation router and UI
|
||||
// can detect when the remote server goes offline and fall back to local backend.
|
||||
connectionModeService.getServerConfig().then(cfg => {
|
||||
if (cfg?.url) {
|
||||
selfHostedServerMonitor.start(cfg.url);
|
||||
}
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
selfHostedServerMonitor.stop();
|
||||
};
|
||||
}, [setupComplete, isFirstLaunch, connectionMode]);
|
||||
|
||||
// Initialize monitoring for bundled backend (already started in Rust)
|
||||
@@ -83,31 +72,38 @@ export function AppProviders({ children }: { children: ReactNode }) {
|
||||
const shouldMonitorBackend = setupComplete && !isFirstLaunch && connectionMode === 'saas';
|
||||
useBackendInitializer(shouldMonitorBackend);
|
||||
|
||||
// Preload endpoint availability for the local bundled backend.
|
||||
// SaaS mode: triggers when the bundled backend reports healthy.
|
||||
// Self-hosted mode: triggers when the local bundled backend port is discovered
|
||||
// (so useSelfHostedToolAvailability can use the cache instead of making
|
||||
// individual requests per-tool when the remote server goes offline).
|
||||
const shouldPreloadLocalEndpoints =
|
||||
(setupComplete && !isFirstLaunch && connectionMode === 'saas') ||
|
||||
(setupComplete && !isFirstLaunch && connectionMode === 'selfhosted');
|
||||
// Preload endpoint availability after backend is healthy
|
||||
useEffect(() => {
|
||||
if (!shouldPreloadLocalEndpoints) return;
|
||||
if (!shouldMonitorBackend) {
|
||||
return; // Only preload in SaaS mode with bundled backend
|
||||
}
|
||||
|
||||
const tryPreload = () => {
|
||||
const backendUrl = tauriBackendService.getBackendUrl();
|
||||
if (!backendUrl) return;
|
||||
// tauriBackendService.isOnline now always reflects the local backend.
|
||||
// Wait for it to be healthy before preloading in both modes.
|
||||
if (!tauriBackendService.isOnline) return;
|
||||
console.debug('[AppProviders] Preloading common tool endpoints for local backend');
|
||||
void endpointAvailabilityService.preloadEndpoints(COMMON_TOOL_ENDPOINTS, backendUrl);
|
||||
const preloadEndpoints = async () => {
|
||||
const backendHealthy = tauriBackendService.isBackendHealthy();
|
||||
if (backendHealthy) {
|
||||
console.debug('[AppProviders] Preloading common tool endpoints');
|
||||
await endpointAvailabilityService.preloadEndpoints(
|
||||
COMMON_TOOL_ENDPOINTS,
|
||||
tauriBackendService.getBackendUrl()
|
||||
);
|
||||
console.debug('[AppProviders] Endpoint preloading complete');
|
||||
}
|
||||
};
|
||||
|
||||
const unsubscribe = tauriBackendService.subscribeToStatus(() => tryPreload());
|
||||
tryPreload();
|
||||
// Subscribe to backend status changes
|
||||
const unsubscribe = tauriBackendService.subscribeToStatus((status) => {
|
||||
if (status === 'healthy') {
|
||||
preloadEndpoints();
|
||||
}
|
||||
});
|
||||
|
||||
// Also check immediately in case backend is already healthy
|
||||
if (tauriBackendService.isBackendHealthy()) {
|
||||
preloadEndpoints();
|
||||
}
|
||||
|
||||
return unsubscribe;
|
||||
}, [shouldPreloadLocalEndpoints, connectionMode]);
|
||||
}, [shouldMonitorBackend]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authChecked) {
|
||||
|
||||
@@ -13,29 +13,29 @@ export const BackendHealthIndicator: React.FC<BackendHealthIndicatorProps> = ({
|
||||
const { t } = useTranslation();
|
||||
const theme = useMantineTheme();
|
||||
const colorScheme = useComputedColorScheme('light');
|
||||
const { status, isOnline, checkHealth } = useBackendHealth();
|
||||
const { status, isHealthy, checkHealth } = useBackendHealth();
|
||||
|
||||
const label = useMemo(() => {
|
||||
if (status === 'starting') {
|
||||
return t('backendHealth.checking', 'Checking backend status...');
|
||||
}
|
||||
|
||||
if (isOnline) {
|
||||
if (isHealthy) {
|
||||
return t('backendHealth.online', 'Backend Online');
|
||||
}
|
||||
|
||||
return t('backendHealth.offline', 'Backend Offline');
|
||||
}, [status, isOnline, t]);
|
||||
}, [status, isHealthy, t]);
|
||||
|
||||
const dotColor = useMemo(() => {
|
||||
if (status === 'starting') {
|
||||
return theme.colors.yellow?.[5] ?? '#fcc419';
|
||||
}
|
||||
if (isOnline) {
|
||||
if (isHealthy) {
|
||||
return theme.colors.green?.[5] ?? '#37b24d';
|
||||
}
|
||||
return theme.colors.red?.[6] ?? '#e03131';
|
||||
}, [status, isOnline, theme.colors.green, theme.colors.red, theme.colors.yellow]);
|
||||
}, [status, isHealthy, theme.colors.green, theme.colors.red, theme.colors.yellow]);
|
||||
|
||||
const handleKeyDown = useCallback((event: React.KeyboardEvent<HTMLSpanElement>) => {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useBanner } from '@app/contexts/BannerContext';
|
||||
import { DefaultAppBanner } from '@app/components/shared/DefaultAppBanner';
|
||||
import UpgradeBanner from '@app/components/shared/UpgradeBanner';
|
||||
import { TeamInvitationBanner } from '@app/components/shared/TeamInvitationBanner';
|
||||
import { SelfHostedOfflineBanner } from '@app/components/shared/SelfHostedOfflineBanner';
|
||||
|
||||
export function DesktopBannerInitializer() {
|
||||
const { setBanner } = useBanner();
|
||||
@@ -11,7 +10,6 @@ export function DesktopBannerInitializer() {
|
||||
useEffect(() => {
|
||||
setBanner(
|
||||
<>
|
||||
<SelfHostedOfflineBanner />
|
||||
<TeamInvitationBanner />
|
||||
<UpgradeBanner />
|
||||
<DefaultAppBanner />
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Box, Text, Stack } from '@mantine/core';
|
||||
import { useSaaSBilling } from '@app/contexts/SaasBillingContext';
|
||||
import { BILLING_CONFIG } from '@app/config/billing';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { authService } from '@app/services/authService';
|
||||
import { CREDIT_EVENTS } from '@app/constants/creditEvents';
|
||||
@@ -50,7 +49,7 @@ export function QuickAccessBarFooterExtensions({ className }: QuickAccessBarFoot
|
||||
// - Still loading billing data
|
||||
// - User is a managed team member (unlimited credits)
|
||||
// - Credits >= 20 (only show when low)
|
||||
if (!isSaasMode || !isAuthenticated || loading || isManagedTeamMember || creditBalance >= BILLING_CONFIG.PLAN_PRICING_PRELOAD_THRESHOLD) {
|
||||
if (!isSaasMode || !isAuthenticated || loading || isManagedTeamMember || creditBalance >= 20) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,229 +0,0 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { Paper, Group, Text, ActionIcon, UnstyledButton, Popover, List, ScrollArea } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { useToolWorkflow } from '@app/contexts/ToolWorkflowContext';
|
||||
import { useConversionCloudStatus } from '@app/hooks/useConversionCloudStatus';
|
||||
import { selfHostedServerMonitor, type SelfHostedServerState } from '@app/services/selfHostedServerMonitor';
|
||||
import { connectionModeService, type ConnectionMode } from '@app/services/connectionModeService';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { endpointAvailabilityService } from '@app/services/endpointAvailabilityService';
|
||||
import { EXTENSION_TO_ENDPOINT, ENDPOINT_I18N } from '@app/constants/convertConstants';
|
||||
import { ENDPOINTS as SPLIT_ENDPOINTS } from '@app/constants/splitConstants';
|
||||
import type { ToolId } from '@app/types/toolId';
|
||||
|
||||
const BANNER_BG = 'var(--mantine-color-gray-1)';
|
||||
const BANNER_BORDER = 'var(--mantine-color-gray-3)';
|
||||
const BANNER_TEXT = 'var(--mantine-color-gray-7)';
|
||||
const BANNER_ICON = 'var(--mantine-color-gray-5)';
|
||||
const BANNER_LINK = 'var(--mantine-color-gray-6)';
|
||||
|
||||
/** Maps split endpoint → [i18n key, English fallback] for the method name */
|
||||
const SPLIT_ENDPOINT_I18N: Record<string, [string, string]> = {
|
||||
'split-pages': ['split.methods.byPages.name', 'Pages'],
|
||||
'split-pdf-by-sections': ['split.methods.bySections.name', 'Sections'],
|
||||
'split-by-size-or-count': ['split.methods.bySize.name', 'File Size'],
|
||||
'split-pdf-by-chapters': ['split.methods.byChapters.name', 'Chapters'],
|
||||
'auto-split-pdf': ['split.methods.byPageDivider.name', 'Page Divider'],
|
||||
'split-for-poster-print': ['split.methods.byPoster.name', 'Printable Chunks'],
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Desktop-only banner shown when the user is in self-hosted mode and the
|
||||
* configured Stirling-PDF server is unreachable.
|
||||
*
|
||||
* - Warns the user their server is offline
|
||||
* - Explains whether local fallback is active
|
||||
* - Shows an expandable list of tools that are unavailable locally
|
||||
* - Session-dismissable (reappears on next launch if server still offline)
|
||||
*/
|
||||
export function SelfHostedOfflineBanner() {
|
||||
const { t } = useTranslation();
|
||||
const [connectionMode, setConnectionMode] = useState<ConnectionMode | null>(null);
|
||||
const [serverState, setServerState] = useState<SelfHostedServerState>(
|
||||
() => selfHostedServerMonitor.getSnapshot()
|
||||
);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [localBackendReady, setLocalBackendReady] = useState(
|
||||
() => !!tauriBackendService.getBackendUrl()
|
||||
);
|
||||
|
||||
// Load connection mode once on mount
|
||||
useEffect(() => {
|
||||
void connectionModeService.getCurrentMode().then(setConnectionMode);
|
||||
}, []);
|
||||
|
||||
// Subscribe to self-hosted server status changes
|
||||
useEffect(() => {
|
||||
const unsub = selfHostedServerMonitor.subscribe(state => {
|
||||
setServerState(state);
|
||||
// Auto-collapse tool list when server comes back online
|
||||
if (state.isOnline) setExpanded(false);
|
||||
});
|
||||
return unsub;
|
||||
}, []);
|
||||
|
||||
// React to local backend port being discovered
|
||||
useEffect(() => {
|
||||
return tauriBackendService.subscribeToStatus(() => {
|
||||
setLocalBackendReady(!!tauriBackendService.getBackendUrl());
|
||||
});
|
||||
}, []);
|
||||
|
||||
// Re-use the toolAvailability already computed by useToolManagement —
|
||||
// tools with reason 'selfHostedOffline' are the ones unavailable locally.
|
||||
const { toolAvailability, toolRegistry } = useToolWorkflow();
|
||||
|
||||
// Re-use conversion availability already computed by useConversionCloudStatus.
|
||||
const { availability: conversionAvailability } = useConversionCloudStatus();
|
||||
|
||||
const [splitAvailability, setSplitAvailability] = useState<Record<string, boolean>>({});
|
||||
useEffect(() => {
|
||||
if (serverState.status !== 'offline') {
|
||||
setSplitAvailability({});
|
||||
return;
|
||||
}
|
||||
const localUrl = tauriBackendService.getBackendUrl();
|
||||
if (!localUrl) {
|
||||
setSplitAvailability({});
|
||||
return;
|
||||
}
|
||||
const uniqueEndpoints = [...new Set(Object.values(SPLIT_ENDPOINTS))] as string[];
|
||||
void Promise.all(
|
||||
uniqueEndpoints.map(async ep => ({
|
||||
ep,
|
||||
supported: await endpointAvailabilityService.isEndpointSupportedLocally(ep, localUrl).catch(() => false),
|
||||
}))
|
||||
).then(results => {
|
||||
const map: Record<string, boolean> = {};
|
||||
for (const { ep, supported } of results) map[ep] = supported;
|
||||
setSplitAvailability(map);
|
||||
});
|
||||
}, [serverState.status]);
|
||||
|
||||
const allUnavailableNames = useMemo(() => {
|
||||
// Top-level tools unavailable in self-hosted offline mode
|
||||
const toolNames = (Object.keys(toolAvailability) as ToolId[])
|
||||
.filter(id => toolAvailability[id]?.available === false && toolAvailability[id]?.reason === 'selfHostedOffline')
|
||||
.map(id => toolRegistry[id]?.name ?? id)
|
||||
.filter(Boolean) as string[];
|
||||
|
||||
// Use translated tool names from the registry as prefixes
|
||||
const convertPrefix = toolRegistry['convert' as ToolId]?.name ?? 'Convert';
|
||||
const splitPrefix = toolRegistry['split' as ToolId]?.name ?? 'Split';
|
||||
|
||||
// Conversion types unavailable locally — deduplicated by endpoint
|
||||
const unavailableEndpoints = new Set<string>();
|
||||
for (const [key, available] of Object.entries(conversionAvailability)) {
|
||||
if (!available) {
|
||||
const dashIdx = key.indexOf('-');
|
||||
const fromExt = key.slice(0, dashIdx);
|
||||
const toExt = key.slice(dashIdx + 1);
|
||||
const endpoint = EXTENSION_TO_ENDPOINT[fromExt]?.[toExt];
|
||||
if (endpoint) unavailableEndpoints.add(endpoint);
|
||||
}
|
||||
}
|
||||
const conversionNames = [...unavailableEndpoints]
|
||||
.map(ep => {
|
||||
const i18n = ENDPOINT_I18N[ep];
|
||||
const suffix = i18n
|
||||
? (i18n[0] ? t(i18n[0], i18n[1]) : i18n[1])
|
||||
: ep;
|
||||
return `${convertPrefix}: ${suffix}`;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
// Split methods unavailable locally
|
||||
const unavailableSplitNames = Object.entries(splitAvailability)
|
||||
.filter(([, available]) => !available)
|
||||
.map(([ep]) => {
|
||||
const i18n = SPLIT_ENDPOINT_I18N[ep];
|
||||
const suffix = i18n ? t(i18n[0], i18n[1]) : ep;
|
||||
return `${splitPrefix}: ${suffix}`;
|
||||
})
|
||||
.filter(Boolean);
|
||||
|
||||
return [...toolNames, ...conversionNames, ...unavailableSplitNames].sort();
|
||||
}, [toolAvailability, toolRegistry, conversionAvailability, splitAvailability, t]);
|
||||
|
||||
// Only show when in self-hosted mode, server confirmed offline, and not dismissed
|
||||
const show =
|
||||
!dismissed &&
|
||||
connectionMode === 'selfhosted' &&
|
||||
serverState.status === 'offline';
|
||||
|
||||
if (!show) return null;
|
||||
|
||||
const messageText = localBackendReady
|
||||
? t('selfHosted.offline.messageWithFallback', 'Some tools require a server connection.')
|
||||
: t('selfHosted.offline.messageNoFallback', 'Tools are unavailable until your server comes back online.');
|
||||
|
||||
return (
|
||||
<Paper
|
||||
radius={0}
|
||||
style={{
|
||||
background: BANNER_BG,
|
||||
borderBottom: `1px solid ${BANNER_BORDER}`,
|
||||
}}
|
||||
>
|
||||
<Group gap="xs" align="center" wrap="nowrap" justify="space-between" px="sm" py={6}>
|
||||
<Group gap="xs" align="center" wrap="nowrap" style={{ minWidth: 0, flex: 1 }}>
|
||||
<LocalIcon
|
||||
icon="warning-rounded"
|
||||
width="1rem"
|
||||
height="1rem"
|
||||
style={{ color: BANNER_ICON, flexShrink: 0 }}
|
||||
/>
|
||||
<Text size="xs" fw={600} style={{ color: BANNER_TEXT, flexShrink: 0 }}>
|
||||
{t('selfHosted.offline.title', 'Server unreachable')}
|
||||
</Text>
|
||||
<Text size="xs" style={{ color: BANNER_TEXT, opacity: 0.8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{messageText}
|
||||
</Text>
|
||||
</Group>
|
||||
{allUnavailableNames.length > 0 && (
|
||||
<Popover
|
||||
opened={expanded}
|
||||
onClose={() => setExpanded(false)}
|
||||
position="bottom-end"
|
||||
withinPortal
|
||||
shadow="md"
|
||||
width={260}
|
||||
>
|
||||
<Popover.Target>
|
||||
<UnstyledButton
|
||||
onClick={() => setExpanded(e => !e)}
|
||||
style={{ color: BANNER_LINK, fontSize: 'var(--mantine-font-size-xs)', fontWeight: 500, flexShrink: 0, whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{expanded
|
||||
? t('selfHosted.offline.hideTools', 'Hide unavailable tools ▴')
|
||||
: t('selfHosted.offline.showTools', 'View unavailable tools ▾')}
|
||||
</UnstyledButton>
|
||||
</Popover.Target>
|
||||
<Popover.Dropdown p="xs">
|
||||
<ScrollArea.Autosize mah={300}>
|
||||
<List size="xs" spacing={2}>
|
||||
{allUnavailableNames.map(name => (
|
||||
<List.Item key={name}>{name}</List.Item>
|
||||
))}
|
||||
</List>
|
||||
</ScrollArea.Autosize>
|
||||
</Popover.Dropdown>
|
||||
</Popover>
|
||||
)}
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
onClick={() => setDismissed(true)}
|
||||
aria-label={t('close', 'Close')}
|
||||
style={{ color: BANNER_TEXT }}
|
||||
>
|
||||
<LocalIcon icon="close-rounded" width="0.8rem" height="0.8rem" />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -8,8 +8,6 @@ import { SaaSTeamsSection } from '@app/components/shared/config/configSections/S
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { authService } from '@app/services/authService';
|
||||
|
||||
export type { ConfigNavSection, ConfigNavItem } from '@core/components/shared/config/configNavSections';
|
||||
|
||||
/**
|
||||
* Hook version of desktop config nav sections with proper i18n support
|
||||
*/
|
||||
|
||||
@@ -42,7 +42,7 @@ export function SaasPlanSection() {
|
||||
const { currentTeam, isTeamLeader, isPersonalTeam } = useSaaSTeam();
|
||||
|
||||
// Plans data
|
||||
const { plans, loading: plansLoading, error: plansError } = useSaaSPlans();
|
||||
const { plans, loading: plansLoading, error: plansError } = useSaaSPlans('usd');
|
||||
|
||||
// Check connection mode on mount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSaaSBilling } from '@app/contexts/SaasBillingContext';
|
||||
import { BILLING_CONFIG } from '@app/config/billing';
|
||||
import { CreditExhaustedModal } from '@app/components/shared/modals/CreditExhaustedModal';
|
||||
import { InsufficientCreditsModal } from '@app/components/shared/modals/InsufficientCreditsModal';
|
||||
import { useCreditEvents } from '@app/hooks/useCreditEvents';
|
||||
@@ -19,16 +18,7 @@ export function CreditModalBootstrap() {
|
||||
requiredCredits?: number;
|
||||
}>({});
|
||||
|
||||
const { creditBalance, isManagedTeamMember, lastFetchTime, plansLastFetchTime, refreshPlans } = useSaaSBilling();
|
||||
|
||||
// Preload plan pricing when billing confirms credits are low.
|
||||
// Fires once: only when billing has loaded (lastFetchTime set) and plans haven't been
|
||||
// fetched yet (plansLastFetchTime null). This way the modal shows real prices instantly.
|
||||
useEffect(() => {
|
||||
if (lastFetchTime !== null && plansLastFetchTime === null && creditBalance < BILLING_CONFIG.PLAN_PRICING_PRELOAD_THRESHOLD && !isManagedTeamMember) {
|
||||
refreshPlans();
|
||||
}
|
||||
}, [lastFetchTime, plansLastFetchTime, creditBalance, isManagedTeamMember, refreshPlans]);
|
||||
const { creditBalance, isManagedTeamMember } = useSaaSBilling();
|
||||
|
||||
// Monitor credit balance and dispatch events
|
||||
useCreditEvents();
|
||||
|
||||
@@ -13,13 +13,9 @@ export const BILLING_CONFIG = {
|
||||
// Overage pricing (per credit) - also fetched dynamically from Stripe
|
||||
OVERAGE_PRICE_PER_CREDIT: 0.05,
|
||||
|
||||
// Credit warning threshold (shows low-balance indicator)
|
||||
// Credit warning threshold
|
||||
LOW_CREDIT_THRESHOLD: 10,
|
||||
|
||||
// Threshold at which plan pricing is preloaded (higher than LOW_CREDIT_THRESHOLD
|
||||
// so prices are ready before the warning UI appears)
|
||||
PLAN_PRICING_PRELOAD_THRESHOLD: 20,
|
||||
|
||||
// Stripe lookup keys
|
||||
PRO_PLAN_LOOKUP_KEY: 'plan:pro',
|
||||
METER_LOOKUP_KEY: 'meter:overage',
|
||||
|
||||
@@ -2,14 +2,22 @@
|
||||
* Connection-related constants for desktop app
|
||||
*/
|
||||
|
||||
// SaaS authentication server URL
|
||||
export const STIRLING_SAAS_URL: string = import.meta.env.VITE_SAAS_SERVER_URL;
|
||||
// SaaS server URL from environment variable
|
||||
// The SaaS authentication server (Supabase)
|
||||
export const STIRLING_SAAS_URL: string = import.meta.env.VITE_SAAS_SERVER_URL || '';
|
||||
|
||||
// Stirling SaaS backend API server (for team endpoints, etc.)
|
||||
export const STIRLING_SAAS_BACKEND_API_URL: string = import.meta.env.VITE_SAAS_BACKEND_API_URL;
|
||||
// SaaS backend API URL from environment variable
|
||||
// The Stirling SaaS backend API server (for team endpoints, etc.)
|
||||
export const STIRLING_SAAS_BACKEND_API_URL: string = import.meta.env.VITE_SAAS_BACKEND_API_URL || '';
|
||||
|
||||
// Supabase publishable key — used for SaaS authentication
|
||||
export const SUPABASE_KEY: string = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY;
|
||||
// Supabase publishable key from environment variable
|
||||
// Used for SaaS authentication
|
||||
export const SUPABASE_KEY: string = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY || 'sb_publishable_UHz2SVRF5mvdrPHWkRteyA_yNlZTkYb';
|
||||
|
||||
// Desktop deep link callback for Supabase email confirmations
|
||||
export const DESKTOP_DEEP_LINK_CALLBACK = 'stirlingpdf://auth/callback';
|
||||
|
||||
// Validation warnings
|
||||
if (!STIRLING_SAAS_BACKEND_API_URL) {
|
||||
console.warn('[Desktop Connection] VITE_SAAS_BACKEND_API_URL not configured - SaaS backend APIs (teams, etc.) will not work');
|
||||
}
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { createContext, useContext, useEffect, useState, ReactNode, useCallback, useRef, useMemo } from 'react';
|
||||
import { createContext, useContext, useEffect, useState, ReactNode, useCallback } from 'react';
|
||||
import { saasBillingService, BillingStatus, PlanPrice } from '@app/services/saasBillingService';
|
||||
import { authService } from '@app/services/authService';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { useSaaSTeam } from '@app/contexts/SaaSTeamContext';
|
||||
import type { TierLevel } from '@app/types/billing';
|
||||
|
||||
// How long plan pricing is considered fresh. Lives at module level so both the
|
||||
// provider and usePlanPricing (the consumer hook) can reference it.
|
||||
const PLANS_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
/**
|
||||
* Desktop implementation of SaaS Billing Context
|
||||
* Provides billing and plan management for users connected to SaaS backend
|
||||
@@ -38,7 +34,6 @@ interface SaasBillingContextType {
|
||||
plans: Map<string, PlanPrice>;
|
||||
plansLoading: boolean;
|
||||
plansError: string | null;
|
||||
plansLastFetchTime: number | null;
|
||||
|
||||
// Derived State
|
||||
isManagedTeamMember: boolean;
|
||||
@@ -68,7 +63,6 @@ const SaasBillingContext = createContext<SaasBillingContextType>({
|
||||
plans: new Map(),
|
||||
plansLoading: false,
|
||||
plansError: null,
|
||||
plansLastFetchTime: null,
|
||||
isManagedTeamMember: false,
|
||||
loading: false,
|
||||
error: null,
|
||||
@@ -86,19 +80,7 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
const [plansError, setPlansError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false); // Start false (lazy load)
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// lastFetchTimeRef is the source of truth for cache logic (always current, no stale closure).
|
||||
// lastFetchTimeValue mirrors it as state purely to drive re-renders and expose through context.
|
||||
const lastFetchTimeRef = useRef<number | null>(null);
|
||||
const [lastFetchTimeValue, setLastFetchTimeValue] = useState<number | null>(null);
|
||||
// billingStatusRef mirrors billingStatus so fetchBillingData can read the current value
|
||||
// without needing billingStatus in its useCallback dep array.
|
||||
const billingStatusRef = useRef<BillingStatus | null>(null);
|
||||
// plansLastFetchTimeRef is the source of truth for timing; plansLastFetchTimeValue
|
||||
// is the state mirror exposed via context so consumers can react to it.
|
||||
const plansLastFetchTimeRef = useRef<number | null>(null);
|
||||
const [plansLastFetchTimeValue, setPlansLastFetchTimeValue] = useState<number | null>(null);
|
||||
// In-flight deduplication — prevents concurrent duplicate network requests.
|
||||
const plansFetchInProgressRef = useRef(false);
|
||||
const [lastFetchTime, setLastFetchTime] = useState<number | null>(null);
|
||||
const [isSaasMode, setIsSaasMode] = useState(false);
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
|
||||
@@ -151,21 +133,19 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
// Cache check: Skip if fresh data exists (<5 min old)
|
||||
const now = Date.now();
|
||||
if (billingStatusRef.current && lastFetchTimeRef.current && (now - lastFetchTimeRef.current) < 300000) {
|
||||
if (billingStatus && lastFetchTime && (now - lastFetchTime) < 300000) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only set loading if no existing data (prevents flicker on refresh)
|
||||
if (!billingStatusRef.current) {
|
||||
if (!billingStatus) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await saasBillingService.getBillingStatus();
|
||||
billingStatusRef.current = status;
|
||||
setBillingStatus(status);
|
||||
lastFetchTimeRef.current = now;
|
||||
setLastFetchTimeValue(now);
|
||||
setBillingStatus(status); // Atomic update
|
||||
setLastFetchTime(now);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
console.error('[SaasBillingContext] Failed to fetch billing:', err);
|
||||
@@ -174,34 +154,26 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [isSaasMode, isAuthenticated, isManagedTeamMember, teamLoading]);
|
||||
}, [isSaasMode, isAuthenticated, isManagedTeamMember, billingStatus, lastFetchTime, teamLoading]);
|
||||
|
||||
// Raw plan fetch — auth guard + in-flight deduplication only.
|
||||
// TTL cache logic lives in usePlanPricing so the consumer hook controls staleness policy.
|
||||
// Fetch available plans
|
||||
const fetchPlansData = useCallback(async () => {
|
||||
// Guard: Skip if not in SaaS mode or not authenticated
|
||||
if (!isSaasMode || !isAuthenticated) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (plansFetchInProgressRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
plansFetchInProgressRef.current = true;
|
||||
setPlansLoading(true);
|
||||
setPlansError(null);
|
||||
|
||||
try {
|
||||
const priceMap = await saasBillingService.getAvailablePlans('usd');
|
||||
setPlans(priceMap);
|
||||
const now = Date.now();
|
||||
plansLastFetchTimeRef.current = now;
|
||||
setPlansLastFetchTimeValue(now);
|
||||
} catch (err) {
|
||||
console.error('[SaasBillingContext] Failed to fetch plans:', err);
|
||||
setPlansError(err instanceof Error ? err.message : 'Failed to fetch plans');
|
||||
// Non-blocking: continue with empty plans
|
||||
} finally {
|
||||
plansFetchInProgressRef.current = false;
|
||||
setPlansLoading(false);
|
||||
}
|
||||
}, [isSaasMode, isAuthenticated]);
|
||||
@@ -210,14 +182,9 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
if (!isSaasMode || !isAuthenticated) {
|
||||
// Clear state when not in SaaS mode or not authenticated
|
||||
billingStatusRef.current = null;
|
||||
setBillingStatus(null);
|
||||
setPlans(new Map());
|
||||
lastFetchTimeRef.current = null;
|
||||
setLastFetchTimeValue(null);
|
||||
plansLastFetchTimeRef.current = null;
|
||||
setPlansLastFetchTimeValue(null);
|
||||
plansFetchInProgressRef.current = false;
|
||||
setLastFetchTime(null);
|
||||
setLoading(false);
|
||||
setError(null);
|
||||
setPlansError(null);
|
||||
@@ -232,12 +199,12 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
isAuthenticated &&
|
||||
!teamLoading &&
|
||||
!isManagedTeamMember &&
|
||||
billingStatusRef.current === null &&
|
||||
lastFetchTimeRef.current === null
|
||||
billingStatus === null &&
|
||||
lastFetchTime === null
|
||||
) {
|
||||
fetchBillingData();
|
||||
}
|
||||
}, [isSaasMode, isAuthenticated, teamLoading, isManagedTeamMember, fetchBillingData]);
|
||||
}, [isSaasMode, isAuthenticated, teamLoading, isManagedTeamMember, billingStatus, lastFetchTime, fetchBillingData]);
|
||||
|
||||
// Public refresh methods
|
||||
const refreshBilling = useCallback(async () => {
|
||||
@@ -245,12 +212,11 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Force cache invalidation — write to ref synchronously so fetchBillingData
|
||||
// reads null immediately (not a stale closure value from the previous render).
|
||||
lastFetchTimeRef.current = null;
|
||||
setLastFetchTimeValue(null);
|
||||
// Force cache invalidation
|
||||
setLastFetchTime(null);
|
||||
await fetchBillingData();
|
||||
}, [isSaasMode, isAuthenticated, fetchBillingData]);
|
||||
await fetchPlansData();
|
||||
}, [isSaasMode, isAuthenticated, fetchBillingData, fetchPlansData]);
|
||||
|
||||
const refreshPlans = useCallback(async () => {
|
||||
await fetchPlansData();
|
||||
@@ -274,9 +240,10 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
if (typeof newBalance === 'number' && billingStatus) {
|
||||
// Update credit balance in billing status without full refresh
|
||||
const updated = { ...billingStatus, creditBalance: newBalance };
|
||||
billingStatusRef.current = updated;
|
||||
setBillingStatus(updated);
|
||||
setBillingStatus({
|
||||
...billingStatus,
|
||||
creditBalance: newBalance,
|
||||
});
|
||||
|
||||
// Dispatch exhausted event if credits hit 0
|
||||
if (newBalance <= 0 && (billingStatus.creditBalance ?? 0) > 0) {
|
||||
@@ -293,36 +260,29 @@ export function SaasBillingProvider({ children }: { children: ReactNode }) {
|
||||
};
|
||||
}, [billingStatus]);
|
||||
|
||||
const contextValue = useMemo(() => ({
|
||||
billingStatus,
|
||||
tier: isManagedTeamMember ? 'team' : (billingStatus?.tier ?? 'free'),
|
||||
subscription: billingStatus?.subscription ?? null,
|
||||
usage: billingStatus?.meterUsage ?? null,
|
||||
isTrialing: billingStatus?.isTrialing ?? false,
|
||||
trialDaysRemaining: billingStatus?.trialDaysRemaining,
|
||||
price: plans.get('team')?.price,
|
||||
currency: plans.get('team')?.currency,
|
||||
creditBalance: billingStatus?.creditBalance ?? 0,
|
||||
plans,
|
||||
plansLoading,
|
||||
plansError,
|
||||
plansLastFetchTime: plansLastFetchTimeValue,
|
||||
isManagedTeamMember,
|
||||
loading: loading || teamLoading,
|
||||
error,
|
||||
lastFetchTime: lastFetchTimeValue,
|
||||
refreshBilling,
|
||||
refreshCredits: refreshBilling,
|
||||
refreshPlans,
|
||||
openBillingPortal,
|
||||
}), [
|
||||
billingStatus, isManagedTeamMember, plans, plansLoading, plansError,
|
||||
plansLastFetchTimeValue, loading, teamLoading, error, lastFetchTimeValue,
|
||||
refreshBilling, refreshPlans, openBillingPortal,
|
||||
]);
|
||||
|
||||
return (
|
||||
<SaasBillingContext.Provider value={contextValue}>
|
||||
<SaasBillingContext.Provider value={{
|
||||
billingStatus,
|
||||
tier: isManagedTeamMember ? 'team' : (billingStatus?.tier ?? 'free'),
|
||||
subscription: billingStatus?.subscription ?? null,
|
||||
usage: billingStatus?.meterUsage ?? null,
|
||||
isTrialing: billingStatus?.isTrialing ?? false,
|
||||
trialDaysRemaining: billingStatus?.trialDaysRemaining,
|
||||
price: billingStatus?.price,
|
||||
currency: billingStatus?.currency,
|
||||
creditBalance: billingStatus?.creditBalance ?? 0,
|
||||
plans,
|
||||
plansLoading,
|
||||
plansError,
|
||||
isManagedTeamMember,
|
||||
loading: loading || teamLoading,
|
||||
error,
|
||||
lastFetchTime,
|
||||
refreshBilling,
|
||||
refreshCredits: refreshBilling, // Alias for clarity
|
||||
refreshPlans,
|
||||
openBillingPortal,
|
||||
}}>
|
||||
{children}
|
||||
</SaasBillingContext.Provider>
|
||||
);
|
||||
@@ -351,26 +311,5 @@ export function useSaaSBilling() {
|
||||
return context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for components that display plan pricing data.
|
||||
* Fetches on first use; re-fetches only after PLANS_CACHE_TTL_MS (1 hour).
|
||||
* Safe to call from multiple components — in-flight deduplication is handled by fetchPlansData.
|
||||
*/
|
||||
export function usePlanPricing() {
|
||||
const { plans, plansLoading, plansError, plansLastFetchTime, refreshPlans } = useContext(SaasBillingContext);
|
||||
|
||||
useEffect(() => {
|
||||
const isFresh =
|
||||
plansLastFetchTime !== null &&
|
||||
Date.now() - plansLastFetchTime < PLANS_CACHE_TTL_MS;
|
||||
|
||||
if (!isFresh) {
|
||||
refreshPlans();
|
||||
}
|
||||
}, [plansLastFetchTime, refreshPlans]);
|
||||
|
||||
return { plans, plansLoading, plansError };
|
||||
}
|
||||
|
||||
export { SaasBillingContext };
|
||||
export type { SaasBillingContextType };
|
||||
|
||||
@@ -1,63 +1,24 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { backendHealthMonitor } from '@app/services/backendHealthMonitor';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import type { BackendHealthState } from '@app/types/backendHealth';
|
||||
|
||||
/**
|
||||
* Hook to read backend health state for UI (Run button, BackendHealthIndicator).
|
||||
*
|
||||
* backendHealthMonitor tracks the local bundled backend.
|
||||
* selfHostedServerMonitor tracks the remote server in self-hosted mode.
|
||||
*
|
||||
* isOnline logic:
|
||||
* - SaaS mode: true when local backend is healthy
|
||||
* - Self-hosted mode (server online): true (remote is up)
|
||||
* - Self-hosted mode (server offline, local port known): true so the Run button
|
||||
* stays enabled — operationRouter routes supported tools to local
|
||||
* - Self-hosted mode (server offline, local port unknown): false
|
||||
* Hook to read the shared backend health monitor state.
|
||||
* All consumers subscribe to a single poller managed by backendHealthMonitor.
|
||||
*/
|
||||
export function useBackendHealth() {
|
||||
const [health, setHealth] = useState<BackendHealthState>(() => backendHealthMonitor.getSnapshot());
|
||||
const [serverStatus, setServerStatus] = useState(
|
||||
() => selfHostedServerMonitor.getSnapshot().status
|
||||
);
|
||||
const [localUrl, setLocalUrl] = useState<string | null>(
|
||||
() => tauriBackendService.getBackendUrl()
|
||||
);
|
||||
const [connectionMode, setConnectionMode] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
void connectionModeService.getCurrentMode().then(setConnectionMode);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return backendHealthMonitor.subscribe(setHealth);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return selfHostedServerMonitor.subscribe(state => setServerStatus(state.status));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return tauriBackendService.subscribeToStatus(() => {
|
||||
setLocalUrl(tauriBackendService.getBackendUrl());
|
||||
});
|
||||
}, []);
|
||||
|
||||
const checkHealth = useCallback(async () => {
|
||||
return backendHealthMonitor.checkNow();
|
||||
}, []);
|
||||
|
||||
const isOnline =
|
||||
connectionMode === 'selfhosted'
|
||||
? serverStatus !== 'offline' || !!localUrl
|
||||
: health.isOnline;
|
||||
|
||||
return {
|
||||
...health,
|
||||
isOnline,
|
||||
checkHealth,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useState, useEffect } from 'react';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { endpointAvailabilityService } from '@app/services/endpointAvailabilityService';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import { EXTENSION_TO_ENDPOINT } from '@app/constants/convertConstants';
|
||||
import { getEndpointName } from '@app/utils/convertUtils';
|
||||
|
||||
@@ -29,56 +28,16 @@ export function useConversionCloudStatus(): ConversionStatus {
|
||||
|
||||
useEffect(() => {
|
||||
const checkConversions = async () => {
|
||||
// Don't check until backend is healthy
|
||||
// This prevents showing incorrect status during startup
|
||||
if (!tauriBackendService.isBackendHealthy()) {
|
||||
setStatus({ availability: {}, cloudStatus: {}, localOnly: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
const mode = await connectionModeService.getCurrentMode();
|
||||
|
||||
// Self-hosted offline path: server is down but local backend is available.
|
||||
// Check each conversion against the local backend only (no cloud routing).
|
||||
if (mode === 'selfhosted') {
|
||||
const { status } = selfHostedServerMonitor.getSnapshot();
|
||||
const localUrl = tauriBackendService.getBackendUrl();
|
||||
if (status === 'offline' && localUrl) {
|
||||
const pairs: [string, string, string][] = [];
|
||||
for (const fromExt of Object.keys(EXTENSION_TO_ENDPOINT)) {
|
||||
for (const toExt of Object.keys(EXTENSION_TO_ENDPOINT[fromExt] || {})) {
|
||||
const endpointName = getEndpointName(fromExt, toExt);
|
||||
if (endpointName) pairs.push([fromExt, toExt, endpointName]);
|
||||
}
|
||||
}
|
||||
const availability: Record<string, boolean> = {};
|
||||
const cloudStatus: Record<string, boolean> = {};
|
||||
const localOnly: Record<string, boolean> = {};
|
||||
const results = await Promise.all(
|
||||
pairs.map(async ([fromExt, toExt, endpointName]) => {
|
||||
const key = `${fromExt}-${toExt}`;
|
||||
try {
|
||||
const supported = await endpointAvailabilityService.isEndpointSupportedLocally(endpointName, localUrl);
|
||||
return { key, supported };
|
||||
} catch {
|
||||
return { key, supported: false };
|
||||
}
|
||||
})
|
||||
);
|
||||
for (const { key, supported } of results) {
|
||||
availability[key] = supported;
|
||||
cloudStatus[key] = false;
|
||||
localOnly[key] = supported;
|
||||
}
|
||||
setStatus({ availability, cloudStatus, localOnly });
|
||||
return;
|
||||
}
|
||||
// Server online or local not ready: let normal endpoint checking handle it
|
||||
setStatus({ availability: {}, cloudStatus: {}, localOnly: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't check until backend is healthy (SaaS startup guard)
|
||||
if (!tauriBackendService.isOnline) {
|
||||
setStatus({ availability: {}, cloudStatus: {}, localOnly: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode !== 'saas') {
|
||||
// Non-SaaS, non-self-hosted: local endpoint checking handles everything
|
||||
// In non-SaaS modes, local endpoint checking handles everything
|
||||
setStatus({ availability: {}, cloudStatus: {}, localOnly: {} });
|
||||
return;
|
||||
}
|
||||
@@ -124,29 +83,14 @@ export function useConversionCloudStatus(): ConversionStatus {
|
||||
// Initial check
|
||||
checkConversions();
|
||||
|
||||
// Re-check when SaaS local backend becomes healthy
|
||||
const unsubLocal = tauriBackendService.subscribeToStatus((status) => {
|
||||
// Subscribe to backend status changes to re-check when backend becomes healthy
|
||||
const unsubscribe = tauriBackendService.subscribeToStatus((status) => {
|
||||
if (status === 'healthy') {
|
||||
checkConversions();
|
||||
}
|
||||
});
|
||||
|
||||
// Re-check when self-hosted server goes offline or comes back online.
|
||||
// By the time the server is confirmed offline, the local port is already
|
||||
// discovered (waitForPort completes in ~500ms vs the 8s server poll timeout).
|
||||
// selfHostedServerMonitor.subscribe immediately invokes the listener with the
|
||||
// current state, which would cause a duplicate check alongside the one above.
|
||||
// Skip the first invocation since checkConversions() was already called above.
|
||||
let skipFirst = true;
|
||||
const unsubServer = selfHostedServerMonitor.subscribe(() => {
|
||||
if (skipFirst) { skipFirst = false; return; }
|
||||
void checkConversions();
|
||||
});
|
||||
|
||||
return () => {
|
||||
unsubLocal();
|
||||
unsubServer();
|
||||
};
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
|
||||
return status;
|
||||
|
||||
@@ -3,8 +3,6 @@ import { isAxiosError } from 'axios';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import { endpointAvailabilityService } from '@app/services/endpointAvailabilityService';
|
||||
import { isBackendNotReadyError } from '@app/constants/backendErrors';
|
||||
import type { EndpointAvailabilityDetails } from '@app/types/endpointAvailability';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
@@ -17,13 +15,6 @@ interface EndpointConfig {
|
||||
|
||||
const RETRY_DELAY_MS = 2500;
|
||||
|
||||
function isSelfHostedOffline(): boolean {
|
||||
return (
|
||||
selfHostedServerMonitor.getSnapshot().status === 'offline' &&
|
||||
!!tauriBackendService.getBackendUrl()
|
||||
);
|
||||
}
|
||||
|
||||
function getErrorMessage(err: unknown): string {
|
||||
if (isAxiosError(err)) {
|
||||
const data = err.response?.data as { message?: string } | undefined;
|
||||
@@ -155,21 +146,7 @@ export function useEndpointEnabled(endpoint: string): {
|
||||
return;
|
||||
}
|
||||
|
||||
// In self-hosted offline mode, enable optimistically when the local backend is ready.
|
||||
// ConvertSettings already filters unsupported endpoints from the dropdown,
|
||||
// so by the time the user has a valid endpoint selected it is supported locally.
|
||||
if (isSelfHostedOffline()) {
|
||||
setEnabled(true);
|
||||
setLoading(false);
|
||||
// Re-evaluate if the server comes back online
|
||||
return selfHostedServerMonitor.subscribe(() => {
|
||||
if (!isSelfHostedOffline() && tauriBackendService.isOnline) {
|
||||
fetchEndpointStatus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (tauriBackendService.isOnline) {
|
||||
if (tauriBackendService.isBackendHealthy()) {
|
||||
fetchEndpointStatus();
|
||||
}
|
||||
|
||||
@@ -230,34 +207,6 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
|
||||
return;
|
||||
}
|
||||
|
||||
// Self-hosted offline: check each endpoint against the local backend directly.
|
||||
// checkDependenciesReady() would fail here since it hits the offline remote server.
|
||||
const { status: serverStatus } = selfHostedServerMonitor.getSnapshot();
|
||||
const localUrl = tauriBackendService.getBackendUrl();
|
||||
if (serverStatus === 'offline' && localUrl) {
|
||||
const results = await Promise.all(
|
||||
[...new Set(endpoints)].map(async (ep) => {
|
||||
try {
|
||||
const supported = await endpointAvailabilityService.isEndpointSupportedLocally(ep, localUrl);
|
||||
return { ep, supported };
|
||||
} catch {
|
||||
return { ep, supported: false };
|
||||
}
|
||||
})
|
||||
);
|
||||
if (!isMountedRef.current) return;
|
||||
const statusMap: Record<string, boolean> = {};
|
||||
const details: Record<string, EndpointAvailabilityDetails> = {};
|
||||
for (const { ep, supported } of results) {
|
||||
statusMap[ep] = supported;
|
||||
details[ep] = { enabled: supported, reason: supported ? null : 'NOT_SUPPORTED_LOCALLY' };
|
||||
}
|
||||
setEndpointDetails(prev => ({ ...prev, ...details }));
|
||||
setEndpointStatus(prev => ({ ...prev, ...statusMap }));
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const dependenciesReady = await checkDependenciesReady();
|
||||
if (!dependenciesReady) {
|
||||
return; // Health monitor will trigger retry when truly ready
|
||||
@@ -364,17 +313,7 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSelfHostedOffline()) {
|
||||
fetchAllEndpointStatuses();
|
||||
const unsubServer = selfHostedServerMonitor.subscribe(() => {
|
||||
if (!isSelfHostedOffline() && tauriBackendService.isOnline) {
|
||||
fetchAllEndpointStatuses();
|
||||
}
|
||||
});
|
||||
return unsubServer;
|
||||
}
|
||||
|
||||
if (tauriBackendService.isOnline) {
|
||||
if (tauriBackendService.isBackendHealthy()) {
|
||||
fetchAllEndpointStatuses();
|
||||
}
|
||||
|
||||
@@ -401,7 +340,8 @@ export function useMultipleEndpointsEnabled(endpoints: string[]): {
|
||||
// Default backend URL from environment variables
|
||||
const DEFAULT_BACKEND_URL =
|
||||
import.meta.env.VITE_DESKTOP_BACKEND_URL
|
||||
|| import.meta.env.VITE_API_BASE_URL;
|
||||
|| import.meta.env.VITE_API_BASE_URL
|
||||
|| '';
|
||||
|
||||
/**
|
||||
* Desktop override exposing the backend URL based on connection mode.
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import apiClient from '@app/services/apiClient';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import type { GroupEnabledResult } from '@app/types/groupEnabled';
|
||||
|
||||
const OFFLINE_REASON_FALLBACK = 'Requires your Stirling-PDF server (currently offline)';
|
||||
|
||||
/**
|
||||
* Desktop override: skips the network request entirely when the self-hosted
|
||||
* server is confirmed offline, returning a reason string matching the tool panel.
|
||||
*/
|
||||
export function useGroupEnabled(group: string): GroupEnabledResult {
|
||||
const { t } = useTranslation();
|
||||
// Initialise synchronously so the first render already reflects offline state —
|
||||
// avoids a flash where the option appears enabled before the effect runs.
|
||||
// Use OFFLINE_REASON_FALLBACK directly so unavailableReason is non-null from
|
||||
// the very first render when offline (t() is not available in useState initialiser).
|
||||
const [result, setResult] = useState<GroupEnabledResult>(() => {
|
||||
const { status } = selfHostedServerMonitor.getSnapshot();
|
||||
if (status === 'offline') {
|
||||
return { enabled: false, unavailableReason: OFFLINE_REASON_FALLBACK };
|
||||
}
|
||||
return { enabled: null, unavailableReason: null };
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const { status } = selfHostedServerMonitor.getSnapshot();
|
||||
if (status === 'offline') {
|
||||
setResult({
|
||||
enabled: false,
|
||||
unavailableReason: t('toolPanel.fullscreen.selfHostedOffline', OFFLINE_REASON_FALLBACK),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
apiClient
|
||||
.get<boolean>(`/api/v1/config/group-enabled?group=${encodeURIComponent(group)}`)
|
||||
.then(res => setResult({ enabled: res.data, unavailableReason: null }))
|
||||
.catch(() => setResult({ enabled: false, unavailableReason: null }));
|
||||
}, [group, t]);
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
|
||||
/**
|
||||
* Returns whether the app is currently in SaaS connection mode.
|
||||
* Starts optimistically true (most common for desktop) to avoid tools
|
||||
* being incorrectly marked unavailable during initial load.
|
||||
*/
|
||||
export function useSaaSMode(): boolean {
|
||||
const [isSaaSMode, setIsSaaSMode] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
void connectionModeService.getCurrentMode().then(mode => setIsSaaSMode(mode === 'saas'));
|
||||
return connectionModeService.subscribeToModeChanges(cfg => setIsSaaSMode(cfg.mode === 'saas'));
|
||||
}, []);
|
||||
|
||||
return isSaaSMode;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSaaSBilling, usePlanPricing } from '@app/contexts/SaasBillingContext';
|
||||
import { saasBillingService } from '@app/services/saasBillingService';
|
||||
import { FREE_PLAN_FEATURES, TEAM_PLAN_FEATURES, ENTERPRISE_PLAN_FEATURES } from '@app/config/planFeatures';
|
||||
import type { TierLevel } from '@app/types/billing';
|
||||
|
||||
@@ -22,13 +22,34 @@ export interface PlanTier {
|
||||
overagePrice?: number;
|
||||
}
|
||||
|
||||
export const useSaaSPlans = () => {
|
||||
export const useSaaSPlans = (currency: string = 'usd') => {
|
||||
const { t } = useTranslation();
|
||||
const { refreshPlans } = useSaaSBilling();
|
||||
const { plans, plansLoading, plansError } = usePlanPricing();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [dynamicPrices, setDynamicPrices] = useState<Map<string, { price: number; currency: string; overagePrice?: number }>>(new Map());
|
||||
|
||||
const computedPlans = useMemo<PlanTier[]>(() => {
|
||||
const teamPlan = plans.get('team');
|
||||
const fetchPlans = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const priceMap = await saasBillingService.getAvailablePlans(currency);
|
||||
setDynamicPrices(priceMap);
|
||||
} catch (err) {
|
||||
console.error('Error fetching plans:', err);
|
||||
setError(err instanceof Error ? err.message : 'Failed to fetch plans');
|
||||
// Continue with default prices if fetch fails
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchPlans();
|
||||
}, [currency]);
|
||||
|
||||
const plans = useMemo<PlanTier[]>(() => {
|
||||
const teamPlan = dynamicPrices.get('team');
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -83,12 +104,12 @@ export const useSaaSPlans = () => {
|
||||
]
|
||||
}
|
||||
];
|
||||
}, [t, plans]);
|
||||
}, [t, dynamicPrices]);
|
||||
|
||||
return {
|
||||
plans: computedPlans,
|
||||
loading: plansLoading,
|
||||
error: plansError,
|
||||
refetch: refreshPlans,
|
||||
plans,
|
||||
loading,
|
||||
error,
|
||||
refetch: fetchPlans,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import { endpointAvailabilityService } from '@app/services/endpointAvailabilityService';
|
||||
|
||||
/**
|
||||
* Desktop implementation of useSelfHostedToolAvailability.
|
||||
* Returns the set of tool IDs that are unavailable when the self-hosted server
|
||||
* is offline (tools whose endpoints are not supported by the local bundled backend).
|
||||
*
|
||||
* Returns an empty set when:
|
||||
* - Not in self-hosted mode
|
||||
* - Self-hosted server is online
|
||||
* - Local backend port is not yet known
|
||||
*/
|
||||
export function useSelfHostedToolAvailability(
|
||||
tools: Array<{ id: string; endpoints?: string[] }>
|
||||
): Set<string> {
|
||||
const [unavailableIds, setUnavailableIds] = useState<Set<string>>(new Set());
|
||||
// Keep a stable ref to the latest tools list to avoid unnecessary re-subscriptions
|
||||
const toolsRef = useRef(tools);
|
||||
toolsRef.current = tools;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const computeUnavailableTools = async () => {
|
||||
const mode = await connectionModeService.getCurrentMode();
|
||||
if (mode !== 'selfhosted') {
|
||||
setUnavailableIds(new Set());
|
||||
return;
|
||||
}
|
||||
|
||||
const { status } = selfHostedServerMonitor.getSnapshot();
|
||||
if (status !== 'offline') {
|
||||
// Idle or checking — not yet confirmed offline; don't mark anything unavailable
|
||||
if (!cancelled) setUnavailableIds(new Set());
|
||||
return;
|
||||
}
|
||||
|
||||
const localUrl = tauriBackendService.getBackendUrl();
|
||||
if (!localUrl) {
|
||||
// Local backend port not yet known; can't determine unavailable tools yet
|
||||
if (!cancelled) setUnavailableIds(new Set());
|
||||
return;
|
||||
}
|
||||
|
||||
// For each tool, check whether at least one of its endpoints is supported locally
|
||||
const unavailable = new Set<string>();
|
||||
await Promise.all(
|
||||
toolsRef.current.map(async tool => {
|
||||
const endpoints = tool.endpoints ?? [];
|
||||
if (endpoints.length === 0) return; // No endpoints → always available
|
||||
|
||||
const locallySupported = await Promise.all(
|
||||
endpoints.map(ep =>
|
||||
endpointAvailabilityService.isEndpointSupportedLocally(ep, localUrl)
|
||||
)
|
||||
);
|
||||
|
||||
if (!locallySupported.some(Boolean)) {
|
||||
unavailable.add(tool.id);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
if (!cancelled) setUnavailableIds(unavailable);
|
||||
};
|
||||
|
||||
// Re-compute when server status changes
|
||||
const unsubServer = selfHostedServerMonitor.subscribe(() => {
|
||||
void computeUnavailableTools();
|
||||
});
|
||||
|
||||
// Re-compute when local backend becomes healthy (port discovered)
|
||||
const unsubBackend = tauriBackendService.subscribeToStatus(() => {
|
||||
void computeUnavailableTools();
|
||||
});
|
||||
|
||||
// Initial computation
|
||||
void computeUnavailableTools();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubServer();
|
||||
unsubBackend();
|
||||
};
|
||||
}, []); // tools intentionally omitted — accessed via ref to avoid churn
|
||||
|
||||
return unavailableIds;
|
||||
}
|
||||
@@ -21,7 +21,7 @@ export function useToolCloudStatus(endpointName?: string): boolean {
|
||||
try {
|
||||
// Don't show cloud badges until backend is healthy
|
||||
// This prevents showing incorrect cloud status during startup
|
||||
if (!tauriBackendService.isOnline) {
|
||||
if (!tauriBackendService.isBackendHealthy()) {
|
||||
setUsesCloud(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react';
|
||||
import { useToolRegistry } from "@app/contexts/ToolRegistryContext";
|
||||
import { usePreferences } from '@app/contexts/PreferencesContext';
|
||||
import { getAllEndpoints, type ToolRegistryEntry, type ToolRegistry } from "@app/data/toolsTaxonomy";
|
||||
import { useMultipleEndpointsEnabled } from "@app/hooks/useEndpointConfig";
|
||||
import { FileId } from '@app/types/file';
|
||||
import { ToolId } from "@app/types/toolId";
|
||||
import type { EndpointDisableReason } from '@app/types/endpointAvailability';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
|
||||
export type ToolDisableCause = 'disabledByAdmin' | 'missingDependency' | 'unknown';
|
||||
|
||||
export interface ToolAvailabilityInfo {
|
||||
available: boolean;
|
||||
reason?: ToolDisableCause;
|
||||
}
|
||||
|
||||
export type ToolAvailabilityMap = Partial<Record<ToolId, ToolAvailabilityInfo>>;
|
||||
|
||||
interface ToolManagementResult {
|
||||
selectedTool: ToolRegistryEntry | null;
|
||||
toolSelectedFileIds: FileId[];
|
||||
toolRegistry: Partial<ToolRegistry>;
|
||||
setToolSelectedFileIds: (fileIds: FileId[]) => void;
|
||||
getSelectedTool: (toolKey: ToolId | null) => ToolRegistryEntry | null;
|
||||
toolAvailability: ToolAvailabilityMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop override of useToolManagement
|
||||
* Enhances tool availability logic to consider SaaS backend routing
|
||||
* - Tools not supported locally but available on SaaS are marked as available
|
||||
* - In SaaS mode, tools can route to cloud backend
|
||||
*/
|
||||
export const useToolManagement = (): ToolManagementResult => {
|
||||
const [toolSelectedFileIds, setToolSelectedFileIds] = useState<FileId[]>([]);
|
||||
// Start optimistically assuming SaaS mode (most common for desktop)
|
||||
// This prevents tools from being incorrectly marked unavailable during initial load
|
||||
const [isSaaSMode, setIsSaaSMode] = useState(true);
|
||||
|
||||
// Log that desktop version is being used
|
||||
useEffect(() => {
|
||||
console.debug('[useToolManagement] DESKTOP VERSION loaded - SaaS routing enabled');
|
||||
}, []);
|
||||
|
||||
// Check connection mode
|
||||
useEffect(() => {
|
||||
connectionModeService.getCurrentMode().then(mode => {
|
||||
setIsSaaSMode(mode === 'saas');
|
||||
console.debug('[useToolManagement] Connection mode loaded:', mode);
|
||||
});
|
||||
|
||||
// Subscribe to mode changes
|
||||
const unsubscribe = connectionModeService.subscribeToModeChanges(config => {
|
||||
setIsSaaSMode(config.mode === 'saas');
|
||||
console.debug('[useToolManagement] Connection mode changed:', config.mode);
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, []);
|
||||
|
||||
// Build endpoints list from registry entries with fallback to legacy mapping
|
||||
const { allTools } = useToolRegistry();
|
||||
const baseRegistry = allTools;
|
||||
const { preferences } = usePreferences();
|
||||
|
||||
const allEndpoints = useMemo(() => getAllEndpoints(baseRegistry), [baseRegistry]);
|
||||
const { endpointStatus, endpointDetails, loading: endpointsLoading } = useMultipleEndpointsEnabled(allEndpoints);
|
||||
|
||||
const isToolAvailable = useCallback((toolKey: string): boolean => {
|
||||
// Keep tools enabled during loading (optimistic UX)
|
||||
if (endpointsLoading) return true;
|
||||
|
||||
const tool = baseRegistry[toolKey as ToolId];
|
||||
const endpoints = tool?.endpoints || [];
|
||||
|
||||
// Tools without endpoints are always available
|
||||
if (endpoints.length === 0) return true;
|
||||
|
||||
// Check if at least one endpoint is enabled locally
|
||||
const hasLocalSupport = endpoints.some((endpoint: string) => endpointStatus[endpoint] !== false);
|
||||
|
||||
// DESKTOP ENHANCEMENT: In SaaS mode, tools are available even if not supported locally
|
||||
// They will route to the SaaS backend instead
|
||||
if (!hasLocalSupport && isSaaSMode) {
|
||||
console.debug(`[useToolManagement] Tool ${toolKey} not supported locally but available via SaaS routing`);
|
||||
// In SaaS mode, assume tools can route to cloud if not available locally
|
||||
// The operation router will handle the actual routing decision
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!hasLocalSupport) {
|
||||
console.debug(`[useToolManagement] Tool ${toolKey} not available - no local support and not in SaaS mode`, {
|
||||
isSaaSMode,
|
||||
endpoints,
|
||||
endpointStatus: endpoints.map(e => ({ [e]: endpointStatus[e] }))
|
||||
});
|
||||
}
|
||||
|
||||
return hasLocalSupport;
|
||||
}, [endpointsLoading, endpointStatus, baseRegistry, isSaaSMode]);
|
||||
|
||||
const deriveToolDisableReason = useCallback((toolKey: ToolId): ToolDisableCause => {
|
||||
const tool = baseRegistry[toolKey];
|
||||
if (!tool) {
|
||||
return 'unknown';
|
||||
}
|
||||
const endpoints = tool.endpoints || [];
|
||||
const disabledReasons: EndpointDisableReason[] = endpoints
|
||||
.filter(endpoint => endpointStatus[endpoint] === false)
|
||||
.map(endpoint => endpointDetails[endpoint]?.reason ?? 'CONFIG');
|
||||
|
||||
if (disabledReasons.some(reason => reason === 'DEPENDENCY')) {
|
||||
return 'missingDependency';
|
||||
}
|
||||
if (disabledReasons.some(reason => reason === 'CONFIG')) {
|
||||
return 'disabledByAdmin';
|
||||
}
|
||||
if (disabledReasons.length > 0) {
|
||||
return 'unknown';
|
||||
}
|
||||
return 'unknown';
|
||||
}, [baseRegistry, endpointDetails, endpointStatus]);
|
||||
|
||||
const toolAvailability = useMemo(() => {
|
||||
if (endpointsLoading) {
|
||||
return {};
|
||||
}
|
||||
const availability: ToolAvailabilityMap = {};
|
||||
(Object.keys(baseRegistry) as ToolId[]).forEach(toolKey => {
|
||||
const available = isToolAvailable(toolKey);
|
||||
availability[toolKey] = available
|
||||
? { available: true }
|
||||
: { available: false, reason: deriveToolDisableReason(toolKey) };
|
||||
});
|
||||
return availability;
|
||||
}, [baseRegistry, deriveToolDisableReason, endpointsLoading, isToolAvailable]);
|
||||
|
||||
const toolRegistry: Partial<ToolRegistry> = useMemo(() => {
|
||||
const availableToolRegistry: Partial<ToolRegistry> = {};
|
||||
(Object.keys(baseRegistry) as ToolId[]).forEach(toolKey => {
|
||||
const baseTool = baseRegistry[toolKey];
|
||||
if (!baseTool) return;
|
||||
const availabilityInfo = toolAvailability[toolKey];
|
||||
const isAvailable = availabilityInfo ? availabilityInfo.available !== false : true;
|
||||
|
||||
// Check if tool is "coming soon" (has no component and no link)
|
||||
const isComingSoon = !baseTool.component && !baseTool.link && toolKey !== 'read' && toolKey !== 'multiTool';
|
||||
|
||||
if (preferences.hideUnavailableTools && (!isAvailable || isComingSoon)) {
|
||||
return;
|
||||
}
|
||||
availableToolRegistry[toolKey] = {
|
||||
...baseTool,
|
||||
name: baseTool.name,
|
||||
description: baseTool.description,
|
||||
};
|
||||
});
|
||||
return availableToolRegistry;
|
||||
}, [baseRegistry, preferences.hideUnavailableTools, toolAvailability]);
|
||||
|
||||
const getSelectedTool = useCallback((toolKey: ToolId | null): ToolRegistryEntry | null => {
|
||||
return toolKey ? toolRegistry[toolKey] || null : null;
|
||||
}, [toolRegistry]);
|
||||
|
||||
return {
|
||||
selectedTool: getSelectedTool(null), // This will be unused, kept for compatibility
|
||||
toolSelectedFileIds,
|
||||
toolRegistry,
|
||||
setToolSelectedFileIds,
|
||||
getSelectedTool,
|
||||
toolAvailability,
|
||||
};
|
||||
};
|
||||
@@ -19,7 +19,7 @@ export function useWillUseCloud(endpoint?: string): boolean {
|
||||
|
||||
// Don't show cloud badges until backend is healthy
|
||||
// This prevents showing incorrect cloud status during startup
|
||||
if (!tauriBackendService.isOnline) {
|
||||
if (!tauriBackendService.isBackendHealthy()) {
|
||||
setWillUseCloud(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export function getApiBaseUrl(): string {
|
||||
return (window as any).STIRLING_PDF_API_BASE_URL;
|
||||
}
|
||||
|
||||
return import.meta.env.VITE_API_BASE_URL;
|
||||
return import.meta.env.VITE_API_BASE_URL || '/';
|
||||
}
|
||||
|
||||
// In Tauri mode, return empty string as placeholder
|
||||
|
||||
@@ -96,7 +96,7 @@ export function setupApiInterceptors(client: AxiosInstance): void {
|
||||
|
||||
// Backend readiness check (for local backend)
|
||||
const isSaaS = await operationRouter.isSaaSMode();
|
||||
const backendHealthy = tauriBackendService.isOnline;
|
||||
const backendHealthy = tauriBackendService.isBackendHealthy();
|
||||
const backendStatus = tauriBackendService.getBackendStatus();
|
||||
const backendPort = tauriBackendService.getBackendPort();
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ class BackendHealthMonitor {
|
||||
private state: BackendHealthState = {
|
||||
status: tauriBackendService.getBackendStatus(),
|
||||
error: null,
|
||||
isOnline: tauriBackendService.getBackendStatus() === 'healthy',
|
||||
isHealthy: tauriBackendService.getBackendStatus() === 'healthy',
|
||||
};
|
||||
|
||||
constructor(pollingInterval = 5000) {
|
||||
@@ -35,7 +35,7 @@ class BackendHealthMonitor {
|
||||
...this.state,
|
||||
...partial,
|
||||
status: nextStatus,
|
||||
isOnline: nextStatus === 'healthy',
|
||||
isHealthy: nextStatus === 'healthy',
|
||||
};
|
||||
|
||||
// Only notify listeners if meaningful state changed
|
||||
|
||||
@@ -2,22 +2,14 @@ import i18n from '@app/i18n';
|
||||
import { alert } from '@app/components/toast';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { operationRouter } from '@app/services/operationRouter';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
|
||||
const BACKEND_TOAST_COOLDOWN_MS = 4000;
|
||||
let lastBackendToast = 0;
|
||||
|
||||
/**
|
||||
* Desktop-specific guard that ensures the relevant backend is ready before
|
||||
* tools attempt to call any API endpoints.
|
||||
*
|
||||
* - SaaS mode: checks the local bundled backend via tauriBackendService.isOnline
|
||||
* - Self-hosted mode (server online/checking): allows through — the operation
|
||||
* targets the remote server and will surface network errors naturally
|
||||
* - Self-hosted mode (server confirmed offline): allows through if local port is
|
||||
* known (operationRouter falls back to local); suppresses toast since
|
||||
* SelfHostedOfflineBanner already communicates the outage
|
||||
* Desktop-specific guard that ensures the embedded backend is healthy
|
||||
* before tools attempt to call any API endpoints.
|
||||
* Enhanced to skip checks for endpoints routed to SaaS backend.
|
||||
*
|
||||
* @param endpoint - Optional endpoint path to check if it needs local backend
|
||||
* @returns true if backend is ready OR endpoint will be routed to SaaS
|
||||
@@ -32,40 +24,14 @@ export async function ensureBackendReady(endpoint?: string): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
const mode = await connectionModeService.getCurrentMode();
|
||||
if (mode === 'selfhosted') {
|
||||
let { status } = selfHostedServerMonitor.getSnapshot();
|
||||
|
||||
// 'checking' means the first poll hasn't returned yet. Wait briefly (up to
|
||||
// 1.5 s) for it to resolve so we don't surface raw network errors during the
|
||||
// first few seconds after launch. If it doesn't resolve in time we fall
|
||||
// through and allow the operation — the HTTP layer will handle any error.
|
||||
if (status === 'checking') {
|
||||
await Promise.race([
|
||||
selfHostedServerMonitor.checkNow(),
|
||||
new Promise<void>(resolve => setTimeout(resolve, 1500)),
|
||||
]);
|
||||
status = selfHostedServerMonitor.getSnapshot().status;
|
||||
}
|
||||
|
||||
if (status === 'offline') {
|
||||
// Server offline: allow through if local backend port is known.
|
||||
// operationRouter will route to local for supported endpoints.
|
||||
// Suppress the toast — SelfHostedOfflineBanner communicates the outage.
|
||||
return !!tauriBackendService.getBackendUrl();
|
||||
}
|
||||
// Server online: allow through — the operation targets the remote server.
|
||||
// Check local backend health
|
||||
if (tauriBackendService.isBackendHealthy()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// SaaS mode: check local bundled backend
|
||||
if (tauriBackendService.isOnline) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Trigger a fresh check so we get the latest status
|
||||
// Trigger a health check so we get the freshest status
|
||||
await tauriBackendService.checkBackendHealth();
|
||||
if (tauriBackendService.isOnline) {
|
||||
if (tauriBackendService.isBackendHealthy()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import i18n from '@app/i18n';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { tauriBackendService } from '@app/services/tauriBackendService';
|
||||
import { endpointAvailabilityService } from '@app/services/endpointAvailabilityService';
|
||||
import { selfHostedServerMonitor } from '@app/services/selfHostedServerMonitor';
|
||||
import { STIRLING_SAAS_BACKEND_API_URL } from '@app/constants/connection';
|
||||
import { CONVERSION_ENDPOINTS, ENDPOINT_NAMES } from '@app/constants/convertConstants';
|
||||
|
||||
@@ -183,35 +181,6 @@ export class OperationRouter {
|
||||
console.debug(`[operationRouter] Routing ${operation} to local backend (supported locally)`);
|
||||
}
|
||||
|
||||
// Self-hosted fallback: when the remote server is offline, route tool endpoints
|
||||
// to the local bundled backend if it supports them.
|
||||
if (mode === 'selfhosted' && operation && this.isToolEndpoint(operation)) {
|
||||
const { status } = selfHostedServerMonitor.getSnapshot();
|
||||
if (status === 'offline') {
|
||||
const endpointName = this.extractEndpointName(operation);
|
||||
const localUrl = tauriBackendService.getBackendUrl();
|
||||
if (localUrl) {
|
||||
const supportedLocally = await endpointAvailabilityService.isEndpointSupportedLocally(
|
||||
endpointName,
|
||||
localUrl
|
||||
);
|
||||
if (supportedLocally) {
|
||||
console.debug(
|
||||
`[operationRouter] Self-hosted server offline, routing ${operation} to local backend`
|
||||
);
|
||||
return localUrl.replace(/\/$/, '');
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
i18n.t(
|
||||
'selfHosted.offline.toolNotAvailableLocally',
|
||||
'Your Stirling-PDF server is offline and "{{endpoint}}" is not available on the local backend.',
|
||||
{ endpoint: endpointName }
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Existing logic for local/remote routing
|
||||
const target = await this.getExecutionTarget(operation);
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ export interface BillingStatus {
|
||||
tier: TierLevel;
|
||||
isTrialing: boolean;
|
||||
trialDaysRemaining?: number;
|
||||
price?: number; // Monthly price (in dollars)
|
||||
currency?: string; // Currency symbol (e.g., '$', '£')
|
||||
creditBalance?: number; // Real-time remaining credits
|
||||
}
|
||||
|
||||
@@ -71,6 +73,51 @@ export class SaasBillingService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch Pro plan price from Stripe
|
||||
* Calls stripe-price-lookup edge function to get current pricing
|
||||
*/
|
||||
private async fetchPlanPrice(
|
||||
token: string,
|
||||
currencyCode: string = 'usd'
|
||||
): Promise<{ price: number; currency: string }> {
|
||||
try {
|
||||
const { data, error } = await supabase.functions.invoke<{
|
||||
prices: Record<string, { unit_amount: number; currency: string }>;
|
||||
missing: string[];
|
||||
}>('stripe-price-lookup', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: {
|
||||
lookup_keys: ['plan:pro'],
|
||||
currency: currencyCode,
|
||||
},
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw new Error(error.message || 'Failed to fetch plan price');
|
||||
}
|
||||
|
||||
if (!data || !data.prices) {
|
||||
throw new Error('No pricing data returned');
|
||||
}
|
||||
|
||||
const proPrice = data.prices['plan:pro'];
|
||||
if (proPrice) {
|
||||
const price = proPrice.unit_amount / 100; // Convert cents to dollars
|
||||
const currency = getCurrencySymbol(proPrice.currency);
|
||||
return { price, currency };
|
||||
}
|
||||
|
||||
// Fallback if price not found
|
||||
throw new Error('Pro plan price not found');
|
||||
} catch (error) {
|
||||
console.error('[Desktop Billing] Error fetching plan price:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch billing status from Supabase edge function
|
||||
* Calls get-usage-billing which returns subscription + meter usage data
|
||||
@@ -126,6 +173,8 @@ export class SaasBillingService {
|
||||
let meterUsage: BillingStatus['meterUsage'] = null;
|
||||
let isTrialing = false;
|
||||
let trialDaysRemaining: number | undefined;
|
||||
let price: number | undefined;
|
||||
let currency: string | undefined;
|
||||
|
||||
if (isPro) {
|
||||
// Fetch usage details
|
||||
@@ -155,6 +204,17 @@ export class SaasBillingService {
|
||||
console.warn('[Desktop Billing] Failed to fetch usage data:', usageError);
|
||||
}
|
||||
|
||||
// Fetch the current Pro plan price from Stripe
|
||||
try {
|
||||
const priceData = await this.fetchPlanPrice(token, 'usd');
|
||||
price = priceData.price;
|
||||
currency = priceData.currency;
|
||||
} catch (error) {
|
||||
console.warn('[Desktop Billing] Failed to fetch plan price, using default:', error);
|
||||
// Fallback to default pricing
|
||||
price = 10;
|
||||
currency = '$';
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch credit balance for all authenticated users (both Pro and Free)
|
||||
@@ -190,6 +250,8 @@ export class SaasBillingService {
|
||||
tier,
|
||||
isTrialing,
|
||||
trialDaysRemaining,
|
||||
price,
|
||||
currency,
|
||||
creditBalance,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
import { fetch } from '@tauri-apps/plugin-http';
|
||||
|
||||
export interface SelfHostedServerState {
|
||||
status: 'idle' | 'checking' | 'online' | 'offline';
|
||||
isOnline: boolean;
|
||||
serverUrl: string | null;
|
||||
}
|
||||
|
||||
type Listener = (state: SelfHostedServerState) => void;
|
||||
|
||||
const POLL_INTERVAL_MS = 15_000;
|
||||
const REQUEST_TIMEOUT_MS = 8_000;
|
||||
|
||||
/**
|
||||
* Singleton service that independently monitors the health of the self-hosted
|
||||
* Stirling-PDF server. Used in self-hosted connection mode to detect when the
|
||||
* remote server goes offline so that the operation router can fall back to the
|
||||
* local bundled backend for supported tools.
|
||||
*
|
||||
* This is separate from tauriBackendService / backendHealthMonitor so that the
|
||||
* local-backend health indicator (BackendHealthIndicator) and the self-hosted
|
||||
* server status can be tracked independently.
|
||||
*/
|
||||
class SelfHostedServerMonitor {
|
||||
private static instance: SelfHostedServerMonitor;
|
||||
|
||||
private state: SelfHostedServerState = {
|
||||
status: 'idle',
|
||||
isOnline: false,
|
||||
serverUrl: null,
|
||||
};
|
||||
|
||||
private listeners = new Set<Listener>();
|
||||
private intervalId: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
static getInstance(): SelfHostedServerMonitor {
|
||||
if (!SelfHostedServerMonitor.instance) {
|
||||
SelfHostedServerMonitor.instance = new SelfHostedServerMonitor();
|
||||
}
|
||||
return SelfHostedServerMonitor.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start polling the given server URL for health.
|
||||
* Safe to call multiple times; only starts one polling loop at a time.
|
||||
* Call stop() before calling start() again with a different URL.
|
||||
*/
|
||||
start(serverUrl: string): void {
|
||||
if (this.intervalId !== null && this.state.serverUrl === serverUrl) {
|
||||
// Already polling this URL
|
||||
return;
|
||||
}
|
||||
|
||||
this.stop();
|
||||
|
||||
this.updateState({ serverUrl, status: 'checking', isOnline: false });
|
||||
|
||||
void this.pollOnce(serverUrl);
|
||||
this.intervalId = setInterval(() => {
|
||||
void this.pollOnce(serverUrl);
|
||||
}, POLL_INTERVAL_MS);
|
||||
}
|
||||
|
||||
/** Stop polling. */
|
||||
stop(): void {
|
||||
if (this.intervalId !== null) {
|
||||
clearInterval(this.intervalId);
|
||||
this.intervalId = null;
|
||||
}
|
||||
this.updateState({ status: 'idle', isOnline: false, serverUrl: null });
|
||||
}
|
||||
|
||||
get isOnline(): boolean {
|
||||
return this.state.isOnline;
|
||||
}
|
||||
|
||||
getSnapshot(): SelfHostedServerState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/** Subscribe to state changes. Returns an unsubscribe function. */
|
||||
subscribe(listener: Listener): () => void {
|
||||
this.listeners.add(listener);
|
||||
// Emit current state immediately so subscribers are always initialised
|
||||
listener(this.state);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** Trigger an immediate health check outside of the scheduled interval. */
|
||||
async checkNow(): Promise<void> {
|
||||
if (this.state.serverUrl) {
|
||||
await this.pollOnce(this.state.serverUrl);
|
||||
}
|
||||
}
|
||||
|
||||
private async pollOnce(serverUrl: string): Promise<void> {
|
||||
const healthUrl = `${serverUrl.replace(/\/$/, '')}/api/v1/info/status`;
|
||||
|
||||
try {
|
||||
const response = await fetch(healthUrl, {
|
||||
method: 'GET',
|
||||
connectTimeout: REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
this.updateState({ status: 'online', isOnline: true });
|
||||
} else {
|
||||
this.updateState({ status: 'offline', isOnline: false });
|
||||
}
|
||||
} catch {
|
||||
this.updateState({ status: 'offline', isOnline: false });
|
||||
}
|
||||
}
|
||||
|
||||
private updateState(partial: Partial<SelfHostedServerState>): void {
|
||||
const next = { ...this.state, ...partial };
|
||||
|
||||
const changed =
|
||||
next.status !== this.state.status ||
|
||||
next.isOnline !== this.state.isOnline ||
|
||||
next.serverUrl !== this.state.serverUrl;
|
||||
|
||||
this.state = next;
|
||||
|
||||
if (changed) {
|
||||
this.listeners.forEach(listener => listener(this.state));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const selfHostedServerMonitor = SelfHostedServerMonitor.getInstance();
|
||||
@@ -1,5 +1,7 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { fetch } from '@tauri-apps/plugin-http';
|
||||
import { connectionModeService } from '@app/services/connectionModeService';
|
||||
import { getAuthTokenFromAnySource } from '@app/services/authTokenStore';
|
||||
|
||||
export type BackendStatus = 'stopped' | 'starting' | 'healthy' | 'unhealthy';
|
||||
|
||||
@@ -27,7 +29,7 @@ export class TauriBackendService {
|
||||
return this.backendStatus;
|
||||
}
|
||||
|
||||
get isOnline(): boolean {
|
||||
isBackendHealthy(): boolean {
|
||||
return this.backendStatus === 'healthy';
|
||||
}
|
||||
|
||||
@@ -56,9 +58,7 @@ export class TauriBackendService {
|
||||
|
||||
/**
|
||||
* Initialize health monitoring for an external server (server mode)
|
||||
* Does not start bundled backend, but enables health checks.
|
||||
* Also discovers the local bundled backend port so it can be used as a fallback
|
||||
* when the self-hosted server is offline.
|
||||
* Does not start bundled backend, but enables health checks
|
||||
*/
|
||||
async initializeExternalBackend(): Promise<void> {
|
||||
if (this.backendStarted) {
|
||||
@@ -68,11 +68,6 @@ export class TauriBackendService {
|
||||
this.backendStarted = true; // Mark as active for health checks
|
||||
this.setStatus('starting');
|
||||
this.beginHealthMonitoring();
|
||||
|
||||
// Discover the local bundled backend port in the background.
|
||||
// The Rust side always starts the local backend, so we can poll for its port
|
||||
// even in self-hosted mode. This allows local fallback when the server is offline.
|
||||
void this.waitForPort();
|
||||
}
|
||||
|
||||
async startBackend(backendUrl?: string): Promise<void> {
|
||||
@@ -113,8 +108,6 @@ export class TauriBackendService {
|
||||
const port = await invoke<number | null>('get_backend_port');
|
||||
if (port) {
|
||||
this.backendPort = port;
|
||||
// Notify status listeners so hooks reading getBackendUrl() re-evaluate
|
||||
this.statusListeners.forEach(listener => listener(this.backendStatus));
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -124,6 +117,19 @@ export class TauriBackendService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get auth token with expiry validation
|
||||
* Delegates to authService which handles caching and expiry checking
|
||||
*/
|
||||
private async getAuthToken(): Promise<string | null> {
|
||||
try {
|
||||
return await getAuthTokenFromAnySource();
|
||||
} catch (error) {
|
||||
console.debug('[TauriBackendService] Failed to get auth token:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private beginHealthMonitoring() {
|
||||
if (this.healthMonitor) {
|
||||
return;
|
||||
@@ -137,31 +143,67 @@ export class TauriBackendService {
|
||||
});
|
||||
}
|
||||
|
||||
/** Always checks the local bundled backend at localhost:{port}. */
|
||||
async checkBackendHealth(): Promise<boolean> {
|
||||
if (!this.backendStarted) {
|
||||
console.debug('[TauriBackendService] Health check: backend not started');
|
||||
this.setStatus('stopped');
|
||||
return false;
|
||||
}
|
||||
if (!this.backendPort) {
|
||||
console.debug('[TauriBackendService] Health check: backend port not available');
|
||||
return false;
|
||||
const mode = await connectionModeService.getCurrentMode();
|
||||
|
||||
// Determine base URL based on mode
|
||||
let baseUrl: string;
|
||||
if (mode === 'selfhosted') {
|
||||
const serverConfig = await connectionModeService.getServerConfig();
|
||||
if (!serverConfig) {
|
||||
console.error('[TauriBackendService] Self-hosted mode but no server URL configured');
|
||||
this.setStatus('unhealthy');
|
||||
return false;
|
||||
}
|
||||
baseUrl = serverConfig.url.replace(/\/$/, '');
|
||||
} else {
|
||||
// SaaS mode - check bundled local backend
|
||||
if (!this.backendStarted) {
|
||||
console.debug('[TauriBackendService] Health check: backend not started');
|
||||
this.setStatus('stopped');
|
||||
return false;
|
||||
}
|
||||
if (!this.backendPort) {
|
||||
console.debug('[TauriBackendService] Health check: backend port not available');
|
||||
return false;
|
||||
}
|
||||
baseUrl = `http://localhost:${this.backendPort}`;
|
||||
}
|
||||
|
||||
const configUrl = `http://localhost:${this.backendPort}/api/v1/config/app-config`;
|
||||
console.debug(`[TauriBackendService] Checking local backend health at: ${configUrl}`);
|
||||
|
||||
// Check if backend is ready (dependencies checked)
|
||||
try {
|
||||
const response = await fetch(configUrl, { method: 'GET', connectTimeout: 5000 });
|
||||
const configUrl = `${baseUrl}/api/v1/config/app-config`;
|
||||
console.debug(`[TauriBackendService] Checking backend health at: ${configUrl}`);
|
||||
|
||||
// For self-hosted mode, include auth token if available
|
||||
const headers: Record<string, string> = {};
|
||||
if (mode === 'selfhosted') {
|
||||
const token = await this.getAuthToken();
|
||||
if (token) {
|
||||
headers['Authorization'] = `Bearer ${token}`;
|
||||
console.debug(`[TauriBackendService] Adding auth token to health check`);
|
||||
} else {
|
||||
console.debug(`[TauriBackendService] No auth token available for health check`);
|
||||
}
|
||||
}
|
||||
|
||||
const response = await fetch(configUrl, {
|
||||
method: 'GET',
|
||||
connectTimeout: 5000,
|
||||
headers,
|
||||
});
|
||||
|
||||
console.debug(`[TauriBackendService] Health check response: status=${response.status}, ok=${response.ok}`);
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`[TauriBackendService] Health check failed: ${response.status}`);
|
||||
console.warn(`[TauriBackendService] Health check failed: response not ok (status ${response.status})`);
|
||||
this.setStatus('unhealthy');
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.debug(`[TauriBackendService] Health check data:`, data);
|
||||
|
||||
const dependenciesReady = data.dependenciesReady === true;
|
||||
console.debug(`[TauriBackendService] dependenciesReady=${dependenciesReady}`);
|
||||
|
||||
|
||||
@@ -12,25 +12,24 @@ import posthog from 'posthog-js';
|
||||
import { PostHogProvider } from '@posthog/react';
|
||||
import { BASE_PATH } from '@app/constants/app';
|
||||
|
||||
posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
|
||||
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
|
||||
posthog.init('phc_VOdeYnlevc2T63m3myFGjeBlRcIusRgmhfx6XL5a1iz', {
|
||||
api_host: 'https://eu.i.posthog.com',
|
||||
defaults: '2025-05-24',
|
||||
capture_exceptions: true, // This enables capturing exceptions using Error Tracking, set to false if you don't want this
|
||||
debug: false,
|
||||
opt_out_capturing_by_default: true, // Opt-out by default, controlled by cookie consent
|
||||
persistence: 'memory', // No cookies/localStorage written until user opts in
|
||||
cross_subdomain_cookie: false,
|
||||
});
|
||||
|
||||
function updatePosthogConsent() {
|
||||
if (!posthog.__loaded) return;
|
||||
function updatePosthogConsent(){
|
||||
if(typeof(posthog) == "undefined" || !posthog.__loaded) {
|
||||
return;
|
||||
}
|
||||
const optIn = (window.CookieConsent as any)?.acceptedService?.('posthog', 'analytics') || false;
|
||||
if (optIn) {
|
||||
posthog.set_config({ persistence: 'localStorage+cookie' });
|
||||
posthog.opt_in_capturing();
|
||||
} else {
|
||||
posthog.opt_out_capturing();
|
||||
posthog.set_config({ persistence: 'memory' });
|
||||
}
|
||||
console.log("Updated PostHog consent: ", optIn ? "opted in" : "opted out");
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import { SuccessStage } from '@app/components/shared/stripeCheckout/stages/Succe
|
||||
import { ErrorStage } from '@app/components/shared/stripeCheckout/stages/ErrorStage';
|
||||
|
||||
// Validate Stripe key (static validation, no dynamic imports)
|
||||
const STRIPE_KEY = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY;
|
||||
const STRIPE_KEY = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_live_51Q56W2P9mY5IAnSnp3kcxG50uyFMLuhM4fFs774DAP3t88KmlwUrUo31CecpnAZ9FHsNp8xJyOnYNYNVVP6z4oi500q5sFYPEp';
|
||||
|
||||
if (!STRIPE_KEY) {
|
||||
console.error(
|
||||
|
||||
@@ -6,7 +6,7 @@ import { EmbeddedCheckoutProvider, EmbeddedCheckout } from '@stripe/react-stripe
|
||||
import { PlanTier } from '@app/services/licenseService';
|
||||
|
||||
// Load Stripe once
|
||||
const STRIPE_KEY = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY;
|
||||
const STRIPE_KEY = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_live_51Q56W2P9mY5IAnSnp3kcxG50uyFMLuhM4fFs774DAP3t88KmlwUrUo31CecpnAZ9FHsNp8xJyOnYNYNVVP6z4oi500q5sFYPEp';
|
||||
const stripePromise = STRIPE_KEY ? loadStripe(STRIPE_KEY) : null;
|
||||
|
||||
interface PaymentStageProps {
|
||||
|
||||
@@ -48,7 +48,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
|
||||
|
||||
const BASE_NO_LOGIN_CONFIG: AppConfig = {
|
||||
enableAnalytics: true,
|
||||
appVersion: '2.7.1',
|
||||
appVersion: '2.6.0',
|
||||
serverCertificateEnabled: false,
|
||||
enableAlphaFunctionality: false,
|
||||
enableDesktopInstallSlide: true,
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "../../",
|
||||
"paths": {
|
||||
"@app/*": [
|
||||
"src/proprietary/*",
|
||||
"src/core/*"
|
||||
],
|
||||
"@core/*": [
|
||||
"src/core/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"../global.d.ts",
|
||||
"../*.js",
|
||||
"../*.ts",
|
||||
"../*.tsx",
|
||||
"../core/setupTests.ts",
|
||||
"."
|
||||
]
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
* @returns true if key exists and has valid format
|
||||
*/
|
||||
export function isStripeConfigured(): boolean {
|
||||
const stripeKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY;
|
||||
const stripeKey = import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || 'pk_live_51Q56W2P9mY5IAnSnp3kcxG50uyFMLuhM4fFs774DAP3t88KmlwUrUo31CecpnAZ9FHsNp8xJyOnYNYNVVP6z4oi500q5sFYPEp';
|
||||
return !!stripeKey && stripeKey.startsWith('pk_');
|
||||
}
|
||||
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { Suspense } from 'react';
|
||||
import { Routes, Route } from 'react-router-dom';
|
||||
import { AppProviders } from '@app/components/AppProviders';
|
||||
import { setBaseUrl } from '@app/constants/app';
|
||||
import type { AppConfig } from '@app/contexts/AppConfigContext';
|
||||
import { AppLayout } from '@app/components/AppLayout';
|
||||
import { LoadingFallback } from '@app/components/shared/LoadingFallback';
|
||||
import OnboardingTour from '@app/components/onboarding/OnboardingTour';
|
||||
import Landing from '@app/routes/Landing';
|
||||
import Login from '@app/routes/Login';
|
||||
import Signup from '@app/routes/Signup';
|
||||
import AuthCallback from '@app/routes/AuthCallback';
|
||||
import ResetPassword from '@app/routes/ResetPassword';
|
||||
import OnboardingBootstrap from '@app/components/OnboardingBootstrap';
|
||||
import TrialExpiredBootstrap from '@app/components/TrialExpiredBootstrap';
|
||||
|
||||
// Import global styles
|
||||
import '@app/styles/tailwind.css';
|
||||
import '@app/styles/saas-theme.css';
|
||||
import '@app/styles/cookieconsent.css';
|
||||
import '@app/styles/index.css';
|
||||
|
||||
// Import file ID debugging helpers (development only)
|
||||
import '@app/utils/fileIdSafety';
|
||||
|
||||
function handleConfigLoaded(config: AppConfig) {
|
||||
if (config.baseUrl) setBaseUrl(config.baseUrl);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Suspense fallback={<LoadingFallback />}>
|
||||
<AppProviders appConfigProviderProps={{ onConfigLoaded: handleConfigLoaded }}>
|
||||
<AppLayout>
|
||||
<OnboardingBootstrap />
|
||||
<TrialExpiredBootstrap />
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/signup" element={<Signup />} />
|
||||
<Route path="/auth/callback" element={<AuthCallback />} />
|
||||
<Route path="/auth/reset" element={<ResetPassword />} />
|
||||
<Route path="/*" element={<Landing />} />
|
||||
</Routes>
|
||||
<OnboardingTour />
|
||||
</AppLayout>
|
||||
</AppProviders>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
Stirling PDF User License
|
||||
|
||||
Copyright (c) 2025 Stirling PDF Inc.
|
||||
|
||||
License Scope & Usage Rights
|
||||
|
||||
Production use of the Stirling PDF Software is only permitted with a valid Stirling PDF User License.
|
||||
|
||||
For purposes of this license, “the Software” refers to the Stirling PDF application and any associated documentation files
|
||||
provided by Stirling PDF Inc. You or your organization may not use the Software in production, at scale, or for business-critical
|
||||
processes unless you have agreed to, and remain in compliance with, the Stirling PDF Subscription Terms of Service
|
||||
(https://www.stirlingpdf.com/terms) or another valid agreement with Stirling PDF, and hold an active User License subscription
|
||||
covering the appropriate number of licensed users.
|
||||
|
||||
Trial and Minimal Use
|
||||
|
||||
You may use the Software without a paid subscription for the sole purposes of internal trial, evaluation, or minimal use, provided that:
|
||||
* Use is limited to the capabilities and restrictions defined by the Software itself;
|
||||
* You do not copy, distribute, sublicense, reverse-engineer, or use the Software in client-facing or commercial contexts.
|
||||
|
||||
Continued use beyond this scope requires a valid Stirling PDF User License.
|
||||
|
||||
Modifications and Derivative Works
|
||||
|
||||
You may modify the Software only for development or internal testing purposes. Any such modifications or derivative works:
|
||||
|
||||
* May not be deployed in production environments without a valid User License;
|
||||
* May not be distributed or sublicensed;
|
||||
* Remain the intellectual property of Stirling PDF and/or its licensors;
|
||||
* May only be used, copied, or exploited in accordance with the terms of a valid Stirling PDF User License subscription.
|
||||
|
||||
Prohibited Actions
|
||||
|
||||
Unless explicitly permitted by a paid license or separate agreement, you may not:
|
||||
|
||||
* Use the Software in production environments;
|
||||
* Copy, merge, distribute, sublicense, or sell the Software;
|
||||
* Remove or alter any licensing or copyright notices;
|
||||
* Circumvent access restrictions or licensing requirements.
|
||||
|
||||
Third-Party Components
|
||||
|
||||
The Stirling PDF Software may include components subject to separate open source licenses. Such components remain governed by
|
||||
their original license terms as provided by their respective owners.
|
||||
|
||||
Disclaimer
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -1,583 +0,0 @@
|
||||
import { createContext, useContext, useEffect, useState, ReactNode, useCallback } from 'react'
|
||||
import { supabase } from '@app/auth/supabase'
|
||||
import type { Session, User as SupabaseUser, AuthError } from '@supabase/supabase-js'
|
||||
import { CreditSummary, SubscriptionInfo, CreditCheckResult, ApiCredits } from '@app/types/credits'
|
||||
import apiClient, { setGlobalCreditUpdateCallback } from '@app/services/apiClient'
|
||||
import { synchronizeUserUpgrade } from '@app/services/userService'
|
||||
import { syncOAuthAvatar, getProfilePictureMetadata, type ProfilePictureMetadata } from '@app/services/avatarSyncService'
|
||||
|
||||
// Extend Supabase User to include optional username for compatibility
|
||||
export type User = SupabaseUser & { username?: string };
|
||||
|
||||
export interface TrialStatus {
|
||||
isTrialing: boolean
|
||||
trialEnd: string
|
||||
daysRemaining: number
|
||||
hasPaymentMethod: boolean
|
||||
hasScheduledSub: boolean
|
||||
status: string
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
session: Session | null
|
||||
user: User | null
|
||||
loading: boolean
|
||||
error: AuthError | null
|
||||
creditBalance: number | null
|
||||
subscription: SubscriptionInfo | null
|
||||
creditSummary: CreditSummary | null
|
||||
isPro: boolean | null
|
||||
trialStatus: TrialStatus | null
|
||||
profilePictureUrl: string | null
|
||||
profilePictureMetadata: ProfilePictureMetadata | null
|
||||
signOut: () => Promise<void>
|
||||
refreshSession: () => Promise<void>
|
||||
hasSufficientCredits: (requiredCredits: number) => CreditCheckResult
|
||||
updateCredits: (newBalance: number) => void
|
||||
refreshCredits: () => Promise<void>
|
||||
refreshProStatus: () => Promise<void>
|
||||
refreshTrialStatus: () => Promise<void>
|
||||
refreshProfilePicture: () => Promise<void>
|
||||
refreshProfilePictureMetadata: () => Promise<void>
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType>({
|
||||
session: null,
|
||||
user: null,
|
||||
loading: true,
|
||||
error: null,
|
||||
creditBalance: null,
|
||||
subscription: null,
|
||||
creditSummary: null,
|
||||
isPro: null,
|
||||
trialStatus: null,
|
||||
profilePictureUrl: null,
|
||||
profilePictureMetadata: null,
|
||||
signOut: async () => {},
|
||||
refreshSession: async () => {},
|
||||
hasSufficientCredits: () => ({ hasSufficientCredits: false, currentBalance: 0, requiredCredits: 0 }),
|
||||
updateCredits: () => {},
|
||||
refreshCredits: async () => {},
|
||||
refreshProStatus: async () => {},
|
||||
refreshTrialStatus: async () => {},
|
||||
refreshProfilePicture: async () => {},
|
||||
refreshProfilePictureMetadata: async () => {}
|
||||
})
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [session, setSession] = useState<Session | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<AuthError | null>(null)
|
||||
const [creditBalance, setCreditBalance] = useState<number | null>(null)
|
||||
const [subscription, setSubscription] = useState<SubscriptionInfo | null>(null)
|
||||
const [creditSummary, setCreditSummary] = useState<CreditSummary | null>(null)
|
||||
const [isPro, setIsPro] = useState<boolean | null>(null)
|
||||
const [trialStatus, setTrialStatus] = useState<TrialStatus | null>(null)
|
||||
const [profilePictureUrl, setProfilePictureUrl] = useState<string | null>(null)
|
||||
const [profilePictureMetadata, setProfilePictureMetadata] = useState<ProfilePictureMetadata | null>(null)
|
||||
|
||||
const fetchCredits = useCallback(async (sessionToUse?: Session | null) => {
|
||||
const currentSession = sessionToUse ?? session
|
||||
|
||||
if (!currentSession?.user) {
|
||||
console.debug('[Auth Debug] No user session, skipping credit fetch')
|
||||
setCreditBalance(null)
|
||||
setCreditSummary(null)
|
||||
setSubscription(null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
console.debug('[Auth Debug] Fetching credits for user:', currentSession.user.id)
|
||||
const response = await apiClient.get<ApiCredits>('/api/v1/credits')
|
||||
const apiCredits = response.data
|
||||
|
||||
// Map server payload to app CreditSummary
|
||||
const credits: CreditSummary = {
|
||||
currentCredits: apiCredits.totalAvailableCredits,
|
||||
maxCredits: apiCredits.weeklyCreditsAllocated + apiCredits.totalBoughtCredits,
|
||||
creditsUsed: (apiCredits.weeklyCreditsAllocated - apiCredits.weeklyCreditsRemaining) + (apiCredits.totalBoughtCredits - apiCredits.boughtCreditsRemaining),
|
||||
creditsRemaining: apiCredits.totalAvailableCredits,
|
||||
resetDate: apiCredits.weeklyResetDate,
|
||||
weeklyAllowance: apiCredits.weeklyCreditsAllocated
|
||||
}
|
||||
|
||||
setCreditSummary(credits)
|
||||
setCreditBalance(credits.creditsRemaining)
|
||||
|
||||
const subscriptionInfo: SubscriptionInfo = {
|
||||
status: 'active',
|
||||
tier: (credits.weeklyAllowance || 0) > 100 ? 'premium' : 'free',
|
||||
creditsPerWeek: credits.weeklyAllowance,
|
||||
maxCredits: credits.maxCredits
|
||||
}
|
||||
setSubscription(subscriptionInfo)
|
||||
|
||||
console.debug('[Auth Debug] Credits fetched successfully:', credits)
|
||||
} catch (error: any) {
|
||||
console.debug('[Auth Debug] Failed to fetch credits:', error)
|
||||
// Don't set error state for credit fetching failures to avoid disrupting auth flow
|
||||
// Credits might not be available in all deployments
|
||||
setCreditBalance(null)
|
||||
setCreditSummary(null)
|
||||
setSubscription(null)
|
||||
}
|
||||
}, [session])
|
||||
|
||||
const refreshCredits = useCallback(async () => {
|
||||
await fetchCredits()
|
||||
}, [fetchCredits])
|
||||
|
||||
const fetchProStatus = useCallback(async (sessionToUse?: Session | null) => {
|
||||
const currentSession = sessionToUse ?? session
|
||||
|
||||
if (!currentSession?.user) {
|
||||
console.debug('[Auth Debug] No user session, skipping pro status fetch')
|
||||
setIsPro(null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
console.debug('[Auth Debug] Fetching pro status for user:', currentSession.user.id)
|
||||
const { data: proStatus, error } = await supabase.rpc('is_pro')
|
||||
|
||||
if (error) {
|
||||
console.error('[Auth Debug] Error checking Pro status:', error)
|
||||
setIsPro(false) // Default to false if there's an error
|
||||
} else {
|
||||
const isProUser = Boolean(proStatus)
|
||||
setIsPro(isProUser)
|
||||
console.debug('[Auth Debug] Pro status fetched:', isProUser)
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('[Auth Debug] Failed to fetch pro status:', error)
|
||||
setIsPro(false) // Default to false if there's an error
|
||||
}
|
||||
}, [session])
|
||||
|
||||
const refreshProStatus = useCallback(async () => {
|
||||
await fetchProStatus()
|
||||
}, [fetchProStatus])
|
||||
|
||||
const fetchTrialStatus = useCallback(async (sessionToUse?: Session | null) => {
|
||||
const currentSession = sessionToUse ?? session
|
||||
|
||||
if (!currentSession?.user) {
|
||||
console.debug('[Auth Debug] No user session, skipping trial status fetch')
|
||||
setTrialStatus(null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
console.debug('[Auth Debug] Fetching trial status for user:', currentSession.user.id)
|
||||
const { data, error } = await supabase
|
||||
.from('billing_subscriptions')
|
||||
.select('status, trial_end, has_payment_method, scheduled_subscription_id')
|
||||
.in('status', ['trialing', 'incomplete_expired', 'canceled'])
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (error) {
|
||||
console.error('[Auth Debug] Error fetching trial status:', error)
|
||||
setTrialStatus(null)
|
||||
return
|
||||
}
|
||||
|
||||
if (data?.trial_end) {
|
||||
const trialEnd = new Date(data.trial_end)
|
||||
const now = new Date()
|
||||
const daysRemaining = Math.ceil((trialEnd.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
|
||||
|
||||
setTrialStatus({
|
||||
isTrialing: data.status === 'trialing' && daysRemaining > 0,
|
||||
trialEnd: data.trial_end,
|
||||
daysRemaining: Math.max(0, daysRemaining),
|
||||
hasPaymentMethod: data.has_payment_method || false,
|
||||
hasScheduledSub: !!data.scheduled_subscription_id,
|
||||
status: data.status
|
||||
})
|
||||
console.debug('[Auth Debug] Trial status fetched:', {
|
||||
status: data.status,
|
||||
daysRemaining: Math.max(0, daysRemaining),
|
||||
hasPaymentMethod: data.has_payment_method,
|
||||
isTrialing: data.status === 'trialing' && daysRemaining > 0
|
||||
})
|
||||
} else {
|
||||
setTrialStatus(null)
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('[Auth Debug] Failed to fetch trial status:', error)
|
||||
setTrialStatus(null)
|
||||
}
|
||||
}, [session])
|
||||
|
||||
const refreshTrialStatus = useCallback(async () => {
|
||||
await fetchTrialStatus()
|
||||
}, [fetchTrialStatus])
|
||||
|
||||
const fetchProfilePicture = useCallback(async (sessionToUse?: Session | null) => {
|
||||
const currentSession = sessionToUse ?? session
|
||||
|
||||
if (!currentSession?.user) {
|
||||
console.debug('[Auth Debug] No user session, skipping profile picture fetch')
|
||||
setProfilePictureUrl(null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const PROFILE_BUCKET = 'profile-pictures'
|
||||
const profilePath = `${currentSession.user.id}/avatar`
|
||||
|
||||
console.debug('[Auth Debug] Fetching profile picture for user:', currentSession.user.id)
|
||||
const { data, error } = await supabase
|
||||
.storage
|
||||
.from(PROFILE_BUCKET)
|
||||
.createSignedUrl(profilePath, 60 * 60)
|
||||
|
||||
if (error) {
|
||||
// Profile picture not found is expected for users without uploads
|
||||
console.debug('[Auth Debug] Profile picture not available:', error.message)
|
||||
setProfilePictureUrl(null)
|
||||
} else {
|
||||
setProfilePictureUrl(data.signedUrl)
|
||||
console.debug('[Auth Debug] Profile picture URL fetched successfully')
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.debug('[Auth Debug] Failed to fetch profile picture:', error)
|
||||
setProfilePictureUrl(null)
|
||||
}
|
||||
}, [session])
|
||||
|
||||
const refreshProfilePicture = useCallback(async () => {
|
||||
await fetchProfilePicture()
|
||||
}, [fetchProfilePicture])
|
||||
|
||||
const fetchProfilePictureMetadata = useCallback(async (sessionToUse?: Session | null) => {
|
||||
const currentSession = sessionToUse ?? session
|
||||
|
||||
if (!currentSession?.user) {
|
||||
console.debug('[Auth Debug] No user session, skipping profile picture metadata fetch')
|
||||
setProfilePictureMetadata(null)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
console.debug('[Auth Debug] Fetching profile picture metadata for user:', currentSession.user.id)
|
||||
const metadata = await getProfilePictureMetadata(currentSession.user.id)
|
||||
setProfilePictureMetadata(metadata)
|
||||
console.debug('[Auth Debug] Profile picture metadata fetched:', metadata)
|
||||
} catch (error: any) {
|
||||
console.debug('[Auth Debug] Failed to fetch profile picture metadata:', error)
|
||||
setProfilePictureMetadata(null)
|
||||
}
|
||||
}, [session])
|
||||
|
||||
const refreshProfilePictureMetadata = useCallback(async () => {
|
||||
await fetchProfilePictureMetadata()
|
||||
}, [fetchProfilePictureMetadata])
|
||||
|
||||
const updateCredits = useCallback((newBalance: number) => {
|
||||
console.debug('[Auth Debug] Updating credit balance:', { from: creditBalance, to: newBalance })
|
||||
setCreditBalance(newBalance)
|
||||
// Also update the creditSummary if it exists
|
||||
if (creditSummary) {
|
||||
const updatedSummary: CreditSummary = {
|
||||
...creditSummary,
|
||||
creditsRemaining: newBalance,
|
||||
currentCredits: newBalance
|
||||
}
|
||||
setCreditSummary(updatedSummary)
|
||||
}
|
||||
}, [creditSummary])
|
||||
|
||||
const hasSufficientCredits = useCallback((requiredCredits: number): CreditCheckResult => {
|
||||
const currentBalance = creditBalance ?? 0
|
||||
const hasSufficient = currentBalance >= requiredCredits
|
||||
console.debug('[Auth Debug] Credit check:', { requiredCredits, currentBalance, hasSufficient })
|
||||
|
||||
return {
|
||||
hasSufficientCredits: hasSufficient,
|
||||
currentBalance,
|
||||
requiredCredits,
|
||||
shortfall: hasSufficient ? undefined : requiredCredits - currentBalance
|
||||
}
|
||||
}, [creditBalance])
|
||||
|
||||
const refreshSession = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
const { data, error } = await supabase.auth.refreshSession()
|
||||
|
||||
if (error) {
|
||||
console.error('[Auth Debug] Session refresh error:', error)
|
||||
setError(error)
|
||||
setSession(null)
|
||||
} else {
|
||||
console.debug('[Auth Debug] Session refreshed successfully')
|
||||
setSession(data.session)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Auth Debug] Unexpected error during session refresh:', err)
|
||||
setError(err as AuthError)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const signOut = async () => {
|
||||
try {
|
||||
setError(null)
|
||||
const { error } = await supabase.auth.signOut()
|
||||
|
||||
if (error) {
|
||||
console.error('[Auth Debug] Sign out error:', error)
|
||||
setError(error)
|
||||
} else {
|
||||
console.debug('[Auth Debug] Signed out successfully')
|
||||
setSession(null)
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Auth Debug] Unexpected error during sign out:', err)
|
||||
setError(err as AuthError)
|
||||
}
|
||||
}
|
||||
|
||||
// Set up global credit update callback
|
||||
useEffect(() => {
|
||||
setGlobalCreditUpdateCallback(updateCredits)
|
||||
}, [updateCredits])
|
||||
|
||||
useEffect(() => {
|
||||
let mounted = true
|
||||
|
||||
// Load current session on first mount
|
||||
const initializeAuth = async () => {
|
||||
try {
|
||||
console.debug('[Auth Debug] Initializing auth...')
|
||||
const { data, error } = await supabase.auth.getSession()
|
||||
|
||||
if (!mounted) return
|
||||
|
||||
if (error) {
|
||||
console.error('[Auth Debug] Initial session error:', error)
|
||||
setError(error)
|
||||
} else {
|
||||
console.debug('[Auth Debug] Initial session loaded:', {
|
||||
hasSession: !!data.session,
|
||||
userId: data.session?.user?.id,
|
||||
email: data.session?.user?.email
|
||||
})
|
||||
setSession(data.session)
|
||||
|
||||
// Fetch credits, pro status, trial status, profile picture metadata, and profile picture using the session from the response
|
||||
if (data.session?.user) {
|
||||
// Sync OAuth avatar in background
|
||||
syncOAuthAvatar(data.session.user).catch((err) => {
|
||||
console.debug('[Auth Debug] Failed to sync OAuth avatar on init:', err)
|
||||
})
|
||||
|
||||
await fetchCredits(data.session)
|
||||
await fetchProStatus(data.session)
|
||||
await fetchTrialStatus(data.session)
|
||||
await fetchProfilePictureMetadata(data.session)
|
||||
|
||||
// Small delay to allow avatar sync to complete if quick
|
||||
setTimeout(() => {
|
||||
fetchProfilePicture(data.session)
|
||||
}, 500)
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[Auth Debug] Unexpected error during auth initialization:', err)
|
||||
if (mounted) {
|
||||
setError(err as AuthError)
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
initializeAuth()
|
||||
|
||||
// Subscribe to auth state changes
|
||||
const { data: { subscription } } = supabase.auth.onAuthStateChange(
|
||||
async (event, newSession) => {
|
||||
if (!mounted) return
|
||||
|
||||
console.debug('[Auth Debug] Auth state change:', {
|
||||
event,
|
||||
hasSession: !!newSession,
|
||||
userId: newSession?.user?.id,
|
||||
email: newSession?.user?.email,
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
|
||||
// Don't run supabase calls inside this callback; schedule them
|
||||
setTimeout(() => {
|
||||
if (mounted) {
|
||||
setSession(newSession)
|
||||
setError(null)
|
||||
|
||||
// Additional handling for specific events
|
||||
if (event === 'SIGNED_OUT') {
|
||||
console.debug('[Auth Debug] User signed out, clearing session')
|
||||
// Clear credit data, pro status, trial status, profile picture, and metadata on sign out
|
||||
setCreditBalance(null)
|
||||
setCreditSummary(null)
|
||||
setSubscription(null)
|
||||
setIsPro(null)
|
||||
setTrialStatus(null)
|
||||
setProfilePictureUrl(null)
|
||||
setProfilePictureMetadata(null)
|
||||
} else if (event === 'SIGNED_IN') {
|
||||
console.debug('[Auth Debug] User signed in successfully')
|
||||
if (newSession?.user) {
|
||||
setLoading(true)
|
||||
|
||||
// Sync OAuth avatar in background (don't block other fetches)
|
||||
syncOAuthAvatar(newSession.user).catch((err) => {
|
||||
console.debug('[Auth Debug] Failed to sync OAuth avatar:', err)
|
||||
})
|
||||
|
||||
// Fetch user data in parallel
|
||||
Promise.all([
|
||||
fetchCredits(newSession),
|
||||
fetchProStatus(newSession),
|
||||
fetchTrialStatus(newSession),
|
||||
fetchProfilePictureMetadata(newSession),
|
||||
]).then(() => {
|
||||
// Fetch profile picture AFTER sync has had time to complete
|
||||
// Use a small delay to allow avatar sync to finish if it's quick
|
||||
setTimeout(() => {
|
||||
fetchProfilePicture(newSession).finally(() => {
|
||||
setLoading(false)
|
||||
console.debug('[Auth Debug] User data fully loaded after sign in')
|
||||
})
|
||||
}, 500)
|
||||
})
|
||||
}
|
||||
} else if (event === 'TOKEN_REFRESHED') {
|
||||
console.debug('[Auth Debug] Token refreshed')
|
||||
// Optionally refresh credits, pro status, trial status, profile picture metadata, and profile picture on token refresh
|
||||
if (newSession?.user) {
|
||||
Promise.all([
|
||||
fetchCredits(newSession),
|
||||
fetchProStatus(newSession),
|
||||
fetchTrialStatus(newSession),
|
||||
fetchProfilePictureMetadata(newSession),
|
||||
fetchProfilePicture(newSession)
|
||||
]).then(() => {
|
||||
console.debug('[Auth Debug] User data refreshed after token refresh')
|
||||
})
|
||||
}
|
||||
} else if (event === 'USER_UPDATED') {
|
||||
console.debug('[Auth Debug] User updated')
|
||||
|
||||
// Check if this is a pending OAuth upgrade completion
|
||||
const pendingUpgrade = sessionStorage.getItem('pendingUpgrade')
|
||||
const upgradeProvider = sessionStorage.getItem('upgradeProvider')
|
||||
|
||||
if (pendingUpgrade && newSession?.user && newSession.user.is_anonymous === false) {
|
||||
console.debug('[Auth Debug] Processing pending OAuth upgrade:', upgradeProvider)
|
||||
|
||||
// Clear the flags first to prevent loops
|
||||
sessionStorage.removeItem('pendingUpgrade')
|
||||
sessionStorage.removeItem('upgradeProvider')
|
||||
|
||||
// Synchronize with backend
|
||||
synchronizeUserUpgrade(upgradeProvider || undefined)
|
||||
.then(() => {
|
||||
console.debug('[Auth Debug] User upgrade synchronized successfully')
|
||||
|
||||
// Refresh credits, pro status, trial status, profile picture metadata, and profile picture after upgrade
|
||||
if (newSession?.user) {
|
||||
return Promise.all([
|
||||
fetchCredits(newSession),
|
||||
fetchProStatus(newSession),
|
||||
fetchTrialStatus(newSession),
|
||||
fetchProfilePictureMetadata(newSession),
|
||||
fetchProfilePicture(newSession)
|
||||
])
|
||||
}
|
||||
})
|
||||
.then(() => {
|
||||
console.debug('[Auth Debug] User data refreshed after upgrade')
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('[Auth Debug] Failed to synchronize user upgrade:', err)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 0)
|
||||
}
|
||||
)
|
||||
|
||||
return () => {
|
||||
mounted = false
|
||||
subscription.unsubscribe()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const value: AuthContextType = {
|
||||
session,
|
||||
user: session?.user ?? null,
|
||||
loading,
|
||||
error,
|
||||
creditBalance,
|
||||
subscription,
|
||||
creditSummary,
|
||||
isPro,
|
||||
trialStatus,
|
||||
profilePictureUrl,
|
||||
profilePictureMetadata,
|
||||
signOut,
|
||||
refreshSession,
|
||||
hasSufficientCredits,
|
||||
updateCredits,
|
||||
refreshCredits,
|
||||
refreshProStatus,
|
||||
refreshTrialStatus,
|
||||
refreshProfilePicture,
|
||||
refreshProfilePictureMetadata
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={value}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext)
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider')
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
// Debug hook to expose auth state for debugging
|
||||
export function useAuthDebug() {
|
||||
const auth = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
console.debug('[Auth Debug] Current auth state:', {
|
||||
hasSession: !!auth.session,
|
||||
hasUser: !!auth.user,
|
||||
loading: auth.loading,
|
||||
hasError: !!auth.error,
|
||||
userId: auth.user?.id,
|
||||
email: auth.user?.email,
|
||||
provider: auth.user?.app_metadata?.provider
|
||||
})
|
||||
}, [auth.session, auth.user, auth.loading, auth.error])
|
||||
|
||||
return auth
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
// Debug helper to log Supabase configuration
|
||||
const debugConfig = () => {
|
||||
const url = import.meta.env.VITE_SUPABASE_URL
|
||||
const key = import.meta.env.VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY
|
||||
|
||||
console.log('[Supabase Debug] Configuration:', {
|
||||
url: url ? '✓ URL configured' : '✗ URL missing',
|
||||
key: key ? '✓ Key configured' : '✗ Key missing',
|
||||
urlValue: url || 'undefined',
|
||||
keyValue: key ? `${key.substring(0, 20)}...` : 'undefined'
|
||||
})
|
||||
|
||||
return { url, key }
|
||||
}
|
||||
|
||||
const config = debugConfig()
|
||||
|
||||
if (!config.url) {
|
||||
throw new Error('Missing VITE_SUPABASE_URL environment variable')
|
||||
}
|
||||
|
||||
if (!config.key) {
|
||||
throw new Error('Missing VITE_SUPABASE_PUBLISHABLE_DEFAULT_KEY environment variable')
|
||||
}
|
||||
|
||||
export const supabase = createClient(
|
||||
config.url,
|
||||
config.key,
|
||||
{
|
||||
auth: {
|
||||
persistSession: true, // keep session in localStorage
|
||||
autoRefreshToken: true,
|
||||
detectSessionInUrl: true, // helpful on first load after redirect
|
||||
// debug: import.meta.env.DEV, // Enable debug logs in development
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// Debug helper for auth events
|
||||
export const debugAuthEvents = () => {
|
||||
supabase.auth.onAuthStateChange((event, session) => {
|
||||
console.log('[Supabase Debug] Auth state change:', {
|
||||
event,
|
||||
hasSession: !!session,
|
||||
userId: session?.user?.id,
|
||||
email: session?.user?.email,
|
||||
provider: session?.user?.app_metadata?.provider,
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Debug auth events can be manually enabled by calling debugAuthEvents()
|
||||
// Commented out to prevent excessive logging on every page load
|
||||
// if (import.meta.env.DEV) {
|
||||
// debugAuthEvents()
|
||||
// }
|
||||
|
||||
// Anonymous authentication functions
|
||||
export const signInAnonymously = async () => {
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signInAnonymously()
|
||||
|
||||
if (error) {
|
||||
console.error('[Supabase] Anonymous sign-in error:', error)
|
||||
throw error
|
||||
}
|
||||
|
||||
console.log('[Supabase] Anonymous sign-in successful:', {
|
||||
userId: data.user?.id,
|
||||
isAnonymous: data.user?.is_anonymous
|
||||
})
|
||||
|
||||
return { data, error }
|
||||
} catch (error) {
|
||||
console.error('[Supabase] Anonymous sign-in failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Account linking functions
|
||||
export const linkEmailIdentity = async (email: string, password?: string) => {
|
||||
try {
|
||||
const updateData: any = { email }
|
||||
if (password) {
|
||||
updateData.password = password
|
||||
}
|
||||
|
||||
const { data, error } = await supabase.auth.updateUser(updateData)
|
||||
|
||||
if (error) {
|
||||
console.error('[Supabase] Email linking error:', error)
|
||||
throw error
|
||||
}
|
||||
|
||||
// Refresh session to get updated token with new user metadata
|
||||
const { error: refreshError } = await supabase.auth.refreshSession()
|
||||
|
||||
if (refreshError) {
|
||||
console.warn('[Supabase] Session refresh after email linking failed:', refreshError)
|
||||
// Don't throw - linking was successful, refresh is just for consistency
|
||||
} else {
|
||||
console.log('[Supabase] Session refreshed after email linking')
|
||||
}
|
||||
|
||||
console.log('[Supabase] Email linked successfully:', {
|
||||
email,
|
||||
userId: data.user?.id
|
||||
})
|
||||
|
||||
return { data, error }
|
||||
} catch (error) {
|
||||
console.error('[Supabase] Email linking failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export const linkOAuthIdentity = async (provider: 'google' | 'github' | 'apple' | 'azure', redirectTo?: string) => {
|
||||
try {
|
||||
const { data, error } = await supabase.auth.linkIdentity({
|
||||
provider: provider,
|
||||
options: redirectTo ? { redirectTo } : undefined
|
||||
})
|
||||
|
||||
if (error) {
|
||||
console.error('[Supabase] OAuth linking error:', error)
|
||||
throw error
|
||||
}
|
||||
|
||||
console.log('[Supabase] OAuth identity linked successfully:', {
|
||||
provider,
|
||||
redirectTo,
|
||||
url: data.url
|
||||
})
|
||||
|
||||
return { data, error }
|
||||
} catch (error) {
|
||||
console.error('[Supabase] OAuth linking failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to check if user is anonymous
|
||||
export const isUserAnonymous = (user: any) => {
|
||||
return user?.is_anonymous === true
|
||||
}
|
||||
|
||||
// Get current user session
|
||||
export const getCurrentUser = async () => {
|
||||
try {
|
||||
const { data: { user }, error } = await supabase.auth.getUser()
|
||||
|
||||
if (error) {
|
||||
console.error('[Supabase] Get user error:', error)
|
||||
throw error
|
||||
}
|
||||
|
||||
return user
|
||||
} catch (error) {
|
||||
console.error('[Supabase] Get user failed:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { usePreferences } from '@app/contexts/PreferencesContext';
|
||||
import { useOnboarding } from '@app/contexts/OnboardingContext';
|
||||
import { useAuth } from '@app/auth/UseSession';
|
||||
import SaasOnboardingModal from '@app/components/onboarding/SaasOnboardingModal';
|
||||
|
||||
const STORAGE_KEY = 'saas_onboarding_seen';
|
||||
const ONBOARDING_SESSION_BLOCK_KEY = 'stirling-onboarding-session-active';
|
||||
|
||||
/**
|
||||
* SaaS-only bootstrap to clear deferred tour requests, mark tool panel prompt as completed,
|
||||
* and show SaaS-specific onboarding on first login.
|
||||
*/
|
||||
export default function OnboardingBootstrap() {
|
||||
const { preferences, updatePreference } = usePreferences();
|
||||
const { clearPendingTourRequest, setStartAfterToolModeSelection } = useOnboarding();
|
||||
const { user, loading, trialStatus, isPro, refreshTrialStatus } = useAuth();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [isPolling, setIsPolling] = useState(false);
|
||||
const [pollAttempts, setPollAttempts] = useState(0);
|
||||
|
||||
// Start polling when user logs in
|
||||
useEffect(() => {
|
||||
const hasSeenOnboarding = localStorage.getItem(STORAGE_KEY) === 'true';
|
||||
|
||||
if (user && !hasSeenOnboarding && !loading && !isPolling && !showModal) {
|
||||
console.debug('[Onboarding] Starting poll for trial data');
|
||||
setIsPolling(true);
|
||||
setPollAttempts(0);
|
||||
}
|
||||
}, [user, loading, isPolling, showModal]);
|
||||
|
||||
// Poll for trial data
|
||||
useEffect(() => {
|
||||
if (!isPolling) return;
|
||||
|
||||
const pollInterval = 500; // Check every 500ms
|
||||
|
||||
const timer = setTimeout(async () => {
|
||||
const newAttempts = pollAttempts + 1;
|
||||
console.debug('[Onboarding] Polling for trial data, attempt:', newAttempts);
|
||||
|
||||
await refreshTrialStatus();
|
||||
setPollAttempts(newAttempts);
|
||||
|
||||
// Check will happen in the next effect
|
||||
}, pollInterval);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [isPolling, pollAttempts, refreshTrialStatus]);
|
||||
|
||||
// Stop polling when data arrives or timeout
|
||||
useEffect(() => {
|
||||
if (!isPolling) return;
|
||||
|
||||
const hasData = trialStatus !== undefined && trialStatus !== null;
|
||||
const hasProStatus = isPro !== null;
|
||||
const maxAttempts = 10;
|
||||
|
||||
if (hasData || pollAttempts >= maxAttempts) {
|
||||
console.debug('[Onboarding] Trial data ready or timeout, showing modal', {
|
||||
hasData,
|
||||
hasProStatus,
|
||||
attempts: pollAttempts,
|
||||
trialStatus,
|
||||
isPro
|
||||
});
|
||||
setIsPolling(false);
|
||||
setShowModal(true);
|
||||
}
|
||||
}, [isPolling, trialStatus, isPro, pollAttempts]);
|
||||
|
||||
const handleClose = () => {
|
||||
localStorage.setItem(STORAGE_KEY, 'true');
|
||||
setShowModal(false);
|
||||
};
|
||||
|
||||
// Keep existing logic to disable core onboarding flags
|
||||
useEffect(() => {
|
||||
// Ensure tool panel preference is set so tours are never deferred.
|
||||
if (!preferences.toolPanelModePromptSeen || !preferences.hasSelectedToolPanelMode) {
|
||||
updatePreference('toolPanelModePromptSeen', true);
|
||||
updatePreference('hasSelectedToolPanelMode', true);
|
||||
}
|
||||
|
||||
// Clear any lingering deferred tour requests.
|
||||
clearPendingTourRequest();
|
||||
setStartAfterToolModeSelection(false);
|
||||
|
||||
// In SaaS, skip the core intro onboarding entirely.
|
||||
if (!preferences.hasSeenIntroOnboarding) {
|
||||
updatePreference('hasSeenIntroOnboarding', true);
|
||||
}
|
||||
// Also mark completed to avoid follow-up banners/modals.
|
||||
if (!preferences.hasCompletedOnboarding) {
|
||||
updatePreference('hasCompletedOnboarding', true);
|
||||
}
|
||||
|
||||
// Also clear any session flag that might mark onboarding as active.
|
||||
if (typeof window !== 'undefined') {
|
||||
window.sessionStorage.removeItem(ONBOARDING_SESSION_BLOCK_KEY);
|
||||
}
|
||||
}, [
|
||||
preferences.hasSelectedToolPanelMode,
|
||||
preferences.toolPanelModePromptSeen,
|
||||
preferences.hasSeenIntroOnboarding,
|
||||
preferences.hasCompletedOnboarding,
|
||||
updatePreference,
|
||||
clearPendingTourRequest,
|
||||
setStartAfterToolModeSelection,
|
||||
]);
|
||||
|
||||
// Only render modal when it should be shown to avoid running hooks unnecessarily
|
||||
return showModal ? <SaasOnboardingModal opened={showModal} onClose={handleClose} /> : null;
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAuth } from '@app/auth/UseSession';
|
||||
import { TrialExpiredModal } from '@app/components/shared/TrialExpiredModal';
|
||||
import StripeCheckout from '@app/components/shared/StripeCheckoutSaas';
|
||||
|
||||
/**
|
||||
* Bootstrap component that shows the trial expired modal when a user's trial has ended
|
||||
* and they haven't added a payment method. Shows once per user per expired trial.
|
||||
*/
|
||||
export default function TrialExpiredBootstrap() {
|
||||
const { user, trialStatus, isPro } = useAuth();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [checkoutOpened, setCheckoutOpened] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Close modal if user logs out or session expires
|
||||
if (!user) {
|
||||
if (showModal) {
|
||||
console.debug('[TrialExpired] User logged out, closing modal');
|
||||
setShowModal(false);
|
||||
}
|
||||
if (checkoutOpened) {
|
||||
setCheckoutOpened(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Only check conditions when auth is fully loaded
|
||||
if (trialStatus === null || isPro === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Build localStorage key unique to this user
|
||||
const storageKey = `trialExpiredModalShown_${user.id}`;
|
||||
const hasSeenModal = localStorage.getItem(storageKey) === 'true';
|
||||
|
||||
// If user is currently trialing, clear any previous "seen" flag
|
||||
// This handles the edge case where a user might re-enter a trial
|
||||
if (trialStatus.isTrialing) {
|
||||
if (hasSeenModal) {
|
||||
console.debug('[TrialExpired] User is trialing, clearing seen flag');
|
||||
localStorage.removeItem(storageKey);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if all conditions are met to show the modal
|
||||
const isExpired =
|
||||
trialStatus.status === 'incomplete_expired' || trialStatus.status === 'canceled';
|
||||
const hasNoPayment = !trialStatus.hasPaymentMethod && !trialStatus.hasScheduledSub;
|
||||
const wasDowngraded = !isPro;
|
||||
const trialEndedRecently = trialStatus.daysRemaining === 0;
|
||||
|
||||
const shouldShowModal =
|
||||
isExpired && hasNoPayment && wasDowngraded && trialEndedRecently && !hasSeenModal;
|
||||
|
||||
if (shouldShowModal) {
|
||||
console.debug('[TrialExpired] Showing trial expired modal', {
|
||||
status: trialStatus.status,
|
||||
daysRemaining: trialStatus.daysRemaining,
|
||||
hasPaymentMethod: trialStatus.hasPaymentMethod,
|
||||
hasScheduledSub: trialStatus.hasScheduledSub,
|
||||
isPro,
|
||||
});
|
||||
setShowModal(true);
|
||||
}
|
||||
}, [user, trialStatus, isPro, showModal, checkoutOpened]);
|
||||
|
||||
const handleClose = () => {
|
||||
if (user) {
|
||||
const storageKey = `trialExpiredModalShown_${user.id}`;
|
||||
localStorage.setItem(storageKey, 'true');
|
||||
console.debug('[TrialExpired] Modal dismissed, marking as seen');
|
||||
}
|
||||
setShowModal(false);
|
||||
};
|
||||
|
||||
const handleSubscribe = () => {
|
||||
console.debug('[TrialExpired] User clicked Subscribe to Pro');
|
||||
setCheckoutOpened(true);
|
||||
};
|
||||
|
||||
const handleCheckoutSuccess = () => {
|
||||
console.debug('[TrialExpired] Subscription successful, refreshing page');
|
||||
// Close modal and refresh to update subscription status
|
||||
handleClose();
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const handleCheckoutClose = () => {
|
||||
console.debug('[TrialExpired] Checkout closed');
|
||||
setCheckoutOpened(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<TrialExpiredModal
|
||||
opened={showModal && !checkoutOpened}
|
||||
onClose={handleClose}
|
||||
onSubscribe={handleSubscribe}
|
||||
/>
|
||||
|
||||
{user && (
|
||||
<StripeCheckout
|
||||
opened={checkoutOpened}
|
||||
onClose={handleCheckoutClose}
|
||||
purchaseType="subscription"
|
||||
planId="pro"
|
||||
creditsPack={null}
|
||||
planName="Pro"
|
||||
onSuccess={handleCheckoutSuccess}
|
||||
onError={(error) => console.error('[TrialExpired] Checkout error:', error)}
|
||||
isTrialConversion={false} // Trial already ended, so this is not a conversion
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
.guest-banner {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
right: 4.5rem;
|
||||
z-index: 1000;
|
||||
background: var(--modal-content-bg, #111418);
|
||||
border: 1px solid var(--api-keys-card-border, rgba(255,255,255,0.08));
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 6px 24px rgba(0,0,0,0.35);
|
||||
padding: 12px 16px;
|
||||
max-width: 30rem;
|
||||
width: 30rem;
|
||||
color: var(--mantine-color-text);
|
||||
}
|
||||
|
||||
.guest-banner-content {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.guest-banner-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.guest-banner-title {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--mantine-color-text);
|
||||
margin-bottom: 4px;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.guest-banner-message {
|
||||
font-size: 12px;
|
||||
color: var(--mantine-color-dimmed);
|
||||
line-height: 1.4;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.guest-banner-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.guest-banner-dismiss {
|
||||
padding: 6px;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--mantine-color-dimmed);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.guest-banner-dismiss:hover {
|
||||
background: var(--mantine-color-gray-1, rgba(255,255,255,0.05));
|
||||
}
|
||||
|
||||
.guest-banner-signup {
|
||||
white-space: nowrap;
|
||||
padding: 6px 12px;
|
||||
border-radius: 8px;
|
||||
background: var(--blue-6, #2563eb);
|
||||
color: #fff;
|
||||
border: none;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.guest-banner-signup:hover {
|
||||
background: var(--blue-7, #1d4ed8);
|
||||
}
|
||||
|
||||
.guest-banner-icon {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
.guest-banner-signup-icon {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import CloseIcon from '@mui/icons-material/Close'
|
||||
import PersonAddIcon from '@mui/icons-material/PersonAdd'
|
||||
import { useAuth } from '@app/auth/UseSession'
|
||||
import { isUserAnonymous } from '@app/auth/supabase'
|
||||
import { withBasePath } from '@app/constants/app'
|
||||
import '@app/components/auth/GuestUserBanner.css'
|
||||
|
||||
interface GuestUserBannerProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
// Ensure the toast only appears once per full page load, not on re-hydration
|
||||
let hasShownThisLoad = false
|
||||
|
||||
/**
|
||||
* Guest user toast encouraging account creation.
|
||||
* Appears 2s after load, top-right of the viewport, offset by right rail.
|
||||
*/
|
||||
export function GuestUserBanner({ className = '' }: GuestUserBannerProps) {
|
||||
const { t } = useTranslation()
|
||||
const { session } = useAuth()
|
||||
const [isDismissed, setIsDismissed] = useState(false)
|
||||
const [visible, setVisible] = useState(false)
|
||||
|
||||
const isAnon = Boolean(session?.user && isUserAnonymous(session.user))
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAnon || hasShownThisLoad) return
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
setVisible(true)
|
||||
hasShownThisLoad = true
|
||||
}, 2000)
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}, [isAnon])
|
||||
|
||||
if (!isAnon || isDismissed || !visible) {
|
||||
return null
|
||||
}
|
||||
|
||||
const handleSignUp = () => {
|
||||
window.location.href = withBasePath('/signup')
|
||||
}
|
||||
|
||||
const handleDismiss = () => {
|
||||
setIsDismissed(true)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`guest-banner ${className || ''}`}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className="guest-banner-content">
|
||||
<div className="guest-banner-text">
|
||||
<div className="guest-banner-title">
|
||||
{t('guestBanner.title', "You're using Stirling PDF as a guest!")}
|
||||
</div>
|
||||
<div className="guest-banner-message">
|
||||
{t('guestBanner.message', 'Create a free account to save your work, access more features, and support the project.')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="guest-banner-actions">
|
||||
<button
|
||||
onClick={handleDismiss}
|
||||
aria-label={t('guestBanner.dismiss', 'Dismiss banner')}
|
||||
className="guest-banner-dismiss"
|
||||
>
|
||||
<CloseIcon className="guest-banner-icon" />
|
||||
</button>
|
||||
<button
|
||||
onClick={handleSignUp}
|
||||
className="guest-banner-signup"
|
||||
>
|
||||
<PersonAddIcon className="guest-banner-signup-icon" />
|
||||
{t('guestBanner.signUp', 'Sign Up Free')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default GuestUserBanner
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user