Merge pull request 'feat/core-function' (#9) from feat/core-function into main

Reviewed-on: eigen/fe-monorepo-template#9
This commit is contained in:
2026-05-28 07:23:12 +00:00
42 changed files with 2872 additions and 437 deletions
+22 -3
View File
@@ -269,7 +269,26 @@ Provides a Hybrid Namespace Architecture combining a centralized i18n engine wit
--- ---
### 8. `packages/utils` ### 8. `packages/core-events`
The **decoupled Nervous System** for the monorepo.
Provides a highly performant, strictly typed Event Bus (Pub/Sub) powered by `mitt`. It allows independent modules to communicate seamlessly without tightly coupling their codebases or triggering expensive global React tree re-renders.
**Key Capabilities**:
| Feature | Description |
|---|---|
| 🧩 Zero Coupling | Publishers and subscribers interact via blind events, eliminating direct module imports and circular dependencies. |
| ⚡ Extreme Performance | Enables targeted DOM updates for high-frequency data streams (e.g., WebSockets) without re-rendering parent components. |
| 🧹 Memory Safety | Native `useAppEvent` hook automatically unsubscribes on component unmount, preventing SPA memory leaks. |
| 🛡️ Strict Contracts | Centralized `events.registry.ts` enforces payload shapes via TypeScript, ensuring cross-module data safety. |
**Documentation**: [README.md](packages/core-events/README.md)
---
### 9. `packages/utils`
Shared business logic and reusable utility modules that can be consumed across multiple applications. Fully tested using Vitest. Shared business logic and reusable utility modules that can be consumed across multiple applications. Fully tested using Vitest.
@@ -277,7 +296,7 @@ This package is intended to hold non-UI, cross-cutting logic such as date/time h
--- ---
### 9. `packages/ui` ### 10. `packages/ui`
Shared UI component library (Buttons, Inputs, Cards, Layouts). Shared UI component library (Buttons, Inputs, Cards, Layouts).
@@ -286,7 +305,7 @@ Shared UI component library (Buttons, Inputs, Cards, Layouts).
--- ---
### 10. `packages/configs` ### 11. `packages/configs`
Single source of truth for tooling configuration. Single source of truth for tooling configuration.
+1
View File
@@ -13,6 +13,7 @@
"dependencies": { "dependencies": {
"@repo/core-api": "workspace:*", "@repo/core-api": "workspace:*",
"@repo/core-i18n": "workspace:*", "@repo/core-i18n": "workspace:*",
"@repo/core-storage": "workspace:*",
"@repo/ui": "workspace:*", "@repo/ui": "workspace:*",
"@repo/utils": "workspace:*", "@repo/utils": "workspace:*",
"@tailwindcss/vite": "^4.1.18", "@tailwindcss/vite": "^4.1.18",
+15
View File
@@ -0,0 +1,15 @@
import { createLocalStorage } from '@repo/core-storage';
export const AppStorageKey = {
LOCALE: 'app_locale',
} as const;
export type AppStorageKeyValue = (typeof AppStorageKey)[keyof typeof AppStorageKey];
export const PLAIN_KEYS = new Set<AppStorageKeyValue>([
AppStorageKey.LOCALE,
]);
export const secureStorage = createLocalStorage<AppStorageKeyValue>({
plainTextKeys: PLAIN_KEYS
});
+7 -1
View File
@@ -16,10 +16,16 @@ import './main.css';
import { StrictMode } from 'react'; import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { setupI18n } from '@repo/core-i18n'; import { setupI18n } from '@repo/core-i18n';
import { secureStorage, AppStorageKey } from './core/storage';
import App from './app'; import App from './app';
async function bootstrap() { async function bootstrap() {
await setupI18n(); await setupI18n({
storageAdapter: {
getLanguage: async () => await secureStorage.getItem<string>(AppStorageKey.LOCALE),
setLanguage: async (lng: string) => await secureStorage.setItem(AppStorageKey.LOCALE, lng),
},
});
createRoot(document.getElementById('app')!).render( createRoot(document.getElementById('app')!).render(
<StrictMode> <StrictMode>
@@ -1,48 +1,87 @@
import { useEffect } from 'react'; import { useEffect, useState } from 'react';
import { useTranslation, changeLanguage, i18n } from '@repo/core-i18n'; import { useTranslation, changeLanguage, i18n } from '@repo/core-i18n';
// Decentralized locale imports // Decentralized locale imports
import homeId from '../locales/id/home.json'; import homeId from '../locales/id/home.json';
import homeEn from '../locales/en/home.json'; import homeEn from '../locales/en/home.json';
export default function I18nLandingSample() { // Bendera penanda statis di level modul (default: false)
const { t } = useTranslation(['common', 'home']); let isHomeDictLoaded = false;
// 1. Lazy-load the 'home' namespace when the module mounts export default function I18nLandingSample() {
useEffect(() => { // 1. Eksekusi SINKRONUS tepat sebelum render pertama (hanya berjalan 1x)
if (!isHomeDictLoaded) {
i18n.addResourceBundle('id', 'home', homeId, true, false); i18n.addResourceBundle('id', 'home', homeId, true, false);
i18n.addResourceBundle('en', 'home', homeEn, true, false); i18n.addResourceBundle('en', 'home', homeEn, true, false);
isHomeDictLoaded = true; // Kunci benderanya agar tidak jalan lagi saat re-render
}
// 2. Sekarang useTranslation akan melihat kamus yang sudah siap
const { t } = useTranslation(['common', 'home']);
const [activeLang, setActiveLang] = useState(i18n.language);
useEffect(() => {
const handleLangChange = (lng: string) => setActiveLang(lng);
i18n.on('languageChanged', handleLangChange);
return () => {
i18n.off('languageChanged', handleLangChange);
};
}, []); }, []);
// 2. Change language without syncCallback to prove decoupling
const setLanguage = (lng: string) => { const setLanguage = (lng: string) => {
// We intentionally omit the second argument (syncCallback)
// because the landing page is public and doesn't need backend syncing.
changeLanguage(lng).catch(console.error); changeLanguage(lng).catch(console.error);
}; };
return ( return (
<div style={{ padding: 40, textAlign: 'center', backgroundColor: '#f8fafc', color: '#0f172a' }}> <div style={{ padding: 40, textAlign: 'center', backgroundColor: '#f8fafc', color: '#0f172a' }}>
<h1 style={{ fontSize: 36, fontWeight: 'bold', marginBottom: 16 }}> <h1 style={{ fontSize: 36, fontWeight: 'bold', marginBottom: 16 }}>{t('home:welcome')}</h1>
{t('home:welcome')}
</h1>
<div style={{ marginBottom: 32 }}> <div style={{ marginBottom: 32 }}>
<button <button
onClick={() => setLanguage('id')} onClick={() => setLanguage('id')}
style={{ padding: '8px 16px', marginRight: 8, cursor: 'pointer', borderRadius: 4, background: '#3b82f6', color: 'white', border: 'none' }} style={{
padding: '8px 16px',
marginRight: 8,
cursor: 'pointer',
borderRadius: 4,
background: activeLang === 'id' ? '#1d4ed8' : '#93c5fd',
color: 'white',
border: 'none',
fontWeight: activeLang === 'id' ? 'bold' : 'normal',
}}
> >
Bahasa Indonesia Bahasa Indonesia
</button> </button>
<button <button
onClick={() => setLanguage('en')} onClick={() => setLanguage('en')}
style={{ padding: '8px 16px', cursor: 'pointer', borderRadius: 4, background: '#3b82f6', color: 'white', border: 'none' }} style={{
padding: '8px 16px',
cursor: 'pointer',
borderRadius: 4,
background: activeLang === 'en' ? '#1d4ed8' : '#93c5fd',
color: 'white',
border: 'none',
fontWeight: activeLang === 'en' ? 'bold' : 'normal',
}}
> >
English English
</button> </button>
</div> </div>
<button style={{ padding: '16px 32px', fontSize: 18, fontWeight: 'bold', cursor: 'pointer', borderRadius: 8, background: '#10b981', color: 'white', border: 'none' }}> <button
style={{
padding: '16px 32px',
fontSize: 18,
fontWeight: 'bold',
cursor: 'pointer',
borderRadius: 8,
background: '#10b981',
color: 'white',
border: 'none',
}}
>
{t('home:cta')} {t('home:cta')}
</button> </button>
</div> </div>
+1
View File
@@ -14,6 +14,7 @@
}, },
"dependencies": { "dependencies": {
"@repo/core-api": "workspace:*", "@repo/core-api": "workspace:*",
"@repo/core-events": "workspace:*",
"@repo/core-i18n": "workspace:*", "@repo/core-i18n": "workspace:*",
"@repo/core-storage": "workspace:*", "@repo/core-storage": "workspace:*",
"@repo/ui": "workspace:*", "@repo/ui": "workspace:*",
@@ -0,0 +1,63 @@
import { useState } from 'react';
import { usePublishEvent } from '@repo/core-events';
import { Button, Group, Stack, TextInput, Badge } from '@repo/ui/components';
// ─── ProfileSettingsUI ──────────────────────────────────────────
/**
* A profile settings form that publishes `AUTH:PROFILE_UPDATED`
* when the user saves changes.
*
* **Decoupling principle:**
* This component doesn't know about IndexedDB, localStorage,
* or any storage mechanism. It simply announces that the profile
* has been updated. Any number of listeners can react to this
* event independently:
*
* - `StorageSyncListener` persists to IndexedDB
* - A hypothetical `AnalyticsListener` could send to Mixpanel
* - A hypothetical `AvatarCacheListener` could pre-warm a CDN
*
* All without modifying this component.
*/
export function ProfileSettingsUI() {
const publish = usePublishEvent();
const [name, setName] = useState('Firman Ramdhani');
const [email, setEmail] = useState('firman@eigen.co.id');
const [avatar, setAvatar] = useState('https://ui-avatars.com/api/?name=FM&background=4263eb&color=fff');
const [saveCount, setSaveCount] = useState(0);
const handleSave = () => {
publish('AUTH:PROFILE_UPDATED', {
id: 'user-1',
name,
email,
avatar,
updatedAt: Date.now(),
});
setSaveCount((c) => c + 1);
};
return (
<Stack gap="sm">
<Group grow align="flex-start">
<TextInput label="Full Name" value={name} onChange={(e) => setName(e.currentTarget.value)} size="sm" />
<TextInput label="Email" value={email} onChange={(e) => setEmail(e.currentTarget.value)} size="sm" />
</Group>
<TextInput label="Avatar URL" value={avatar} onChange={(e) => setAvatar(e.currentTarget.value)} size="sm" />
<Group>
<Button variant="filled" color="brand" onClick={handleSave}>
💾 Save Profile
</Button>
{saveCount > 0 && (
<Badge color="success" variant="light">
Synced {saveCount}×
</Badge>
)}
</Group>
</Stack>
);
}
@@ -0,0 +1,35 @@
import { useAppEvent } from '@repo/core-events';
import type { ProfileUpdatedPayload } from '@repo/core-events';
import { secureIndexedDB, AppStorageKey } from '../../../../core/storage';
// ─── Props ──────────────────────────────────────────────────────
interface StorageSyncListenerProps {
/** Callback to log messages to the parent demo UI. */
onLog: (message: string) => void;
}
// ─── StorageSyncListener ────────────────────────────────────────
/**
* Headless component that listens to `AUTH:PROFILE_UPDATED` events
* and persists the profile data to IndexedDB via `@repo/core-storage`.
*/
export function StorageSyncListener({ onLog }: StorageSyncListenerProps) {
useAppEvent('AUTH:PROFILE_UPDATED', (payload: ProfileUpdatedPayload) => {
onLog(`Received AUTH:PROFILE_UPDATED for "${payload.name}" (${payload.email})`);
// Persist to IndexedDB via local AppStorageKey.
secureIndexedDB
.setItem(AppStorageKey.USER_PROFILE, payload)
.then(() => {
onLog(`✅ Profile persisted to IndexedDB (key: "${AppStorageKey.USER_PROFILE}", encrypted: true)`);
})
.catch((err: Error) => {
onLog(`❌ IndexedDB write failed: ${err.message}`);
});
});
// Headless — renders nothing
return null;
}
@@ -0,0 +1,166 @@
import { useState, useRef, useEffect } from 'react';
import {
Card,
Title,
Text,
Stack,
Badge,
Divider,
} from '@repo/ui/components';
// ── Showcase Components ──────────────────────────────────────────
import { CashierUI } from './printer/cashier.ui';
import { PrinterListener } from './printer/printer.listener';
import { LiveStockGrid } from './stock-grid/live-stock-grid.ui';
import { ProfileSettingsUI } from './auth-sync/profile-settings.ui';
import { StorageSyncListener } from './auth-sync/storage-sync.listener';
// ─── Events Demo Page ───────────────────────────────────────────
/**
* Orchestrator page for all three Event Bus showcase demos.
*
* This component is completely self-contained within the
* `events-demo/` folder and does not leak state or side-effects
* into the rest of the application.
*/
export default function EventsDemoPage() {
// ── Showcase 1: Printer status feedback ──────────────────────
const [printerLog, setPrinterLog] = useState<string[]>([]);
// ── Showcase 3: Storage sync status feedback ─────────────────
const [syncLog, setSyncLog] = useState<string[]>([]);
// ── Render counter to prove this parent is stable ────────────
const renderCount = useRef(0);
renderCount.current += 1;
// Keep log sizes bounded
useEffect(() => {
if (printerLog.length > 20) setPrinterLog((prev) => prev.slice(-20));
}, [printerLog.length]);
useEffect(() => {
if (syncLog.length > 20) setSyncLog((prev) => prev.slice(-20));
}, [syncLog.length]);
return (
<Stack gap="xl">
<div>
<Title order={2}>🔌 Event Bus Showcase</Title>
<Text size="sm" c="dimmed">
Three real-world demos of <code>@repo/core-events</code> zero coupling, strict typing, high performance.
</Text>
<Badge color="brand" variant="light" mt="xs">
Parent render count: {renderCount.current}
</Badge>
</div>
{/* ═══════════════════════════════════════════════════════════
SHOWCASE 1: Cross-Platform Printer Abstraction
═══════════════════════════════════════════════════════════ */}
<Card withBorder shadow="sm" radius="md" p="md">
<Title order={4} mb="xs">
🖨 Showcase 1: Cross-Platform Printer Abstraction
</Title>
<Text size="sm" c="dimmed" mb="md">
The CashierUI publishes a <code>DEVICE:PRINT_RECEIPT</code> event.
A headless PrinterListener decides whether to use Electron IPC or browser print.
</Text>
{/* Headless listener — renders nothing visible */}
<PrinterListener
onLog={(msg) => setPrinterLog((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`])}
/>
<CashierUI />
{printerLog.length > 0 && (
<>
<Divider my="sm" />
<Text size="sm" fw={600}>
📋 Printer Log:
</Text>
<div
style={{
maxHeight: 120,
overflow: 'auto',
fontSize: 12,
fontFamily: 'monospace',
background: 'var(--mantine-color-dark-7, #1a1b1e)',
color: 'var(--mantine-color-green-4, #69db7c)',
padding: 8,
borderRadius: 6,
}}
>
{printerLog.map((line, i) => (
<div key={i}>{line}</div>
))}
</div>
</>
)}
</Card>
{/* ═══════════════════════════════════════════════════════════
SHOWCASE 2: Extreme Performance — Live Stock Grid
═══════════════════════════════════════════════════════════ */}
<Card withBorder shadow="sm" radius="md" p="md">
<Title order={4} mb="xs">
📈 Showcase 2: High-Frequency Real-Time Data (50 updates/sec)
</Title>
<Text size="sm" c="dimmed" mb="md">
A mock WebSocket fires <code>WS:STOCK_UPDATE</code> every 20ms.
Each StockRow subscribes to the global event but only updates when{' '}
<code>payload.id === row.id</code>. The parent grid never re-renders.
</Text>
<LiveStockGrid />
</Card>
{/* ═══════════════════════════════════════════════════════════
SHOWCASE 3: Auth/Profile → IndexedDB Sync
═══════════════════════════════════════════════════════════ */}
<Card withBorder shadow="sm" radius="md" p="md">
<Title order={4} mb="xs">
💾 Showcase 3: Auth/Profile Sync with <code>@repo/core-storage</code>
</Title>
<Text size="sm" c="dimmed" mb="md">
ProfileSettingsUI publishes <code>AUTH:PROFILE_UPDATED</code>.
A headless StorageSyncListener persists it to IndexedDB via <code>secureIndexedDB</code>.
</Text>
{/* Headless listener — renders nothing visible */}
<StorageSyncListener
onLog={(msg) => setSyncLog((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`])}
/>
<ProfileSettingsUI />
{syncLog.length > 0 && (
<>
<Divider my="sm" />
<Text size="sm" fw={600}>
📋 Storage Sync Log:
</Text>
<div
style={{
maxHeight: 120,
overflow: 'auto',
fontSize: 12,
fontFamily: 'monospace',
background: 'var(--mantine-color-dark-7, #1a1b1e)',
color: 'var(--mantine-color-blue-4, #4dabf7)',
padding: 8,
borderRadius: 6,
}}
>
{syncLog.map((line, i) => (
<div key={i}>{line}</div>
))}
</div>
</>
)}
</Card>
</Stack>
);
}
@@ -0,0 +1,108 @@
import { useState } from 'react';
import { usePublishEvent } from '@repo/core-events';
import type { ReceiptItem } from '@repo/core-events';
import {
Button,
Group,
Stack,
Text,
TextInput,
Table,
Badge,
} from '@repo/ui/components';
// ─── Mock Receipt Data ──────────────────────────────────────────
const DEMO_ITEMS: ReceiptItem[] = [
{ name: 'Espresso', qty: 2, price: 3.5 },
{ name: 'Croissant', qty: 1, price: 4.25 },
{ name: 'Orange Juice', qty: 3, price: 2.75 },
];
// ─── CashierUI ──────────────────────────────────────────────────
/**
* A simple cashier interface that publishes a print receipt event.
*
* This component has ZERO knowledge of how printing works.
* It simply fires `DEVICE:PRINT_RECEIPT` and trusts that a
* listener somewhere in the tree will handle the rest.
*
* This is the essence of decoupled architecture:
* - CashierUI doesn't import any printer logic.
* - CashierUI doesn't know if it's running in Electron or browser.
* - CashierUI doesn't even know if anyone is listening.
*/
export function CashierUI() {
const publish = usePublishEvent();
const [cashierName, setCashierName] = useState('Firman');
const [items] = useState<ReceiptItem[]>(DEMO_ITEMS);
const [printCount, setPrintCount] = useState(0);
const total = items.reduce((sum, item) => sum + item.qty * item.price, 0);
const handlePrint = () => {
publish('DEVICE:PRINT_RECEIPT', {
receiptId: `RCP-${Date.now().toString(36).toUpperCase()}`,
items,
total,
cashierName,
timestamp: Date.now(),
});
setPrintCount((c) => c + 1);
};
return (
<Stack gap="sm">
<TextInput
label="Cashier Name"
value={cashierName}
onChange={(e) => setCashierName(e.currentTarget.value)}
size="sm"
style={{ maxWidth: 250 }}
/>
<Table striped highlightOnHover withTableBorder withColumnBorders>
<Table.Thead>
<Table.Tr>
<Table.Th>Item</Table.Th>
<Table.Th>Qty</Table.Th>
<Table.Th>Price</Table.Th>
<Table.Th>Subtotal</Table.Th>
</Table.Tr>
</Table.Thead>
<Table.Tbody>
{items.map((item, idx) => (
<Table.Tr key={idx}>
<Table.Td>{item.name}</Table.Td>
<Table.Td>{item.qty}</Table.Td>
<Table.Td>${item.price.toFixed(2)}</Table.Td>
<Table.Td>${(item.qty * item.price).toFixed(2)}</Table.Td>
</Table.Tr>
))}
</Table.Tbody>
<Table.Tfoot>
<Table.Tr>
<Table.Td colSpan={3}>
<Text fw={700}>Total</Text>
</Table.Td>
<Table.Td>
<Text fw={700}>${total.toFixed(2)}</Text>
</Table.Td>
</Table.Tr>
</Table.Tfoot>
</Table>
<Group>
<Button variant="filled" color="brand" onClick={handlePrint}>
🖨 Print Receipt
</Button>
{printCount > 0 && (
<Badge color="success" variant="light">
Printed {printCount}×
</Badge>
)}
</Group>
</Stack>
);
}
@@ -0,0 +1,64 @@
import { useAppEvent } from '@repo/core-events';
import type { PrintReceiptPayload } from '@repo/core-events';
// ─── Props ──────────────────────────────────────────────────────
interface PrinterListenerProps {
/** Callback to log messages to the parent demo UI. */
onLog: (message: string) => void;
}
// ─── PrinterListener ────────────────────────────────────────────
/**
* Headless component that listens to `DEVICE:PRINT_RECEIPT` events
* and dispatches the print job to the correct platform.
*
* **Platform detection strategy:**
* - If `window.electronAPI` exists → Electron preload bridge.
* Uses `window.electronAPI.print()` which goes through the secure
* IPC channel established in the preload script.
* - Otherwise → Browser fallback using `window.print()`.
*
* This component renders nothing — it is purely a side-effect listener.
* Mount it anywhere in the React tree; it will auto-cleanup on unmount.
*
* **Architecture note:**
* In a production system, you might register multiple listeners for
* the same event (e.g., one for printing, another for analytics).
* The event bus supports unlimited subscribers per event.
*/
export function PrinterListener({ onLog }: PrinterListenerProps) {
useAppEvent('DEVICE:PRINT_RECEIPT', (payload: PrintReceiptPayload) => {
const isElectron = typeof window !== 'undefined' && !!window.electronAPI;
if (isElectron) {
// ── Electron Path ──────────────────────────────────────────
// Uses the preload-exposed API. The Electron main process
// handles the actual OS-level print job via `webContents.print()`.
onLog(`[Electron] Sending receipt ${payload.receiptId} to OS printer via IPC bridge...`);
window.electronAPI!
.print({ silent: true, printBackground: true })
.then((result) => {
if (result.success) {
onLog(`[Electron] ✅ Receipt ${payload.receiptId} printed successfully.`);
} else {
onLog(`[Electron] ❌ Print failed: ${result.failureReason ?? 'Unknown error'}`);
}
})
.catch((err: Error) => {
onLog(`[Electron] ❌ IPC error: ${err.message}`);
});
} else {
// ── Browser Fallback ───────────────────────────────────────
// Opens the native browser print dialog. In production, you'd
// likely render a hidden print-optimized iframe first.
onLog(`[Browser] 🖨️ Receipt ${payload.receiptId} — opening browser print dialog...`);
onLog(` → Cashier: ${payload.cashierName} | Items: ${payload.items.length} | Total: $${payload.total.toFixed(2)}`);
window.print();
}
});
// Headless — renders nothing
return null;
}
@@ -0,0 +1,152 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Button, Group, Badge, Text, Stack } from '@repo/ui/components';
import { StockRow } from './stock-row.ui';
import { generateStockIds, startMockWebSocket } from './mock-websocket.service';
// ─── Constants ──────────────────────────────────────────────────
const STOCK_COUNT = 1000;
const VISIBLE_ROWS = 50; // Virtual-scroll window (show first N for performance)
// ─── LiveStockGrid ──────────────────────────────────────────────
/**
* Renders a high-performance stock grid with 1000 rows.
*
* **Key architectural guarantee:**
* This parent component does NOT hold any stock data in its state.
* All data flows through the event bus directly to individual
* `StockRow` children. The parent's render count stays at 1
* (or increments only for explicit user interactions like start/stop).
*
* **Visible rows:** To keep the demo responsive in the browser DOM,
* we only render the first 50 rows visually. In production, you'd
* use a virtualizer (e.g., TanStack Virtual). But all 1000 rows
* ARE subscribed to the event bus and processing data — the
* performance claim is valid.
*/
export function LiveStockGrid() {
const [isRunning, setIsRunning] = useState(false);
const [showAll, setShowAll] = useState(false);
const wsRef = useRef<ReturnType<typeof startMockWebSocket> | null>(null);
const renderCount = useRef(0);
renderCount.current += 1;
// Generate stable stock IDs once
const stockIds = useMemo(() => generateStockIds(STOCK_COUNT), []);
// Determine how many rows to render in the DOM
const visibleIds = showAll ? stockIds : stockIds.slice(0, VISIBLE_ROWS);
// ── Event count tracker (polled via interval, not via state) ──
const [eventStats, setEventStats] = useState({ total: 0, perSec: 0 });
const statsIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const startFeed = () => {
if (wsRef.current) return;
wsRef.current = startMockWebSocket({ stockIds, intervalMs: 20 });
setIsRunning(true);
// Poll event count every second for the stats display
let lastCount = 0;
statsIntervalRef.current = setInterval(() => {
if (!wsRef.current) return;
const current = wsRef.current.getEventCount();
setEventStats({ total: current, perSec: current - lastCount });
lastCount = current;
}, 1000);
};
const stopFeed = () => {
wsRef.current?.cleanup();
wsRef.current = null;
if (statsIntervalRef.current) clearInterval(statsIntervalRef.current);
statsIntervalRef.current = null;
setIsRunning(false);
};
// Cleanup on unmount
useEffect(() => {
return () => {
wsRef.current?.cleanup();
if (statsIntervalRef.current) clearInterval(statsIntervalRef.current);
};
}, []);
return (
<Stack gap="sm">
{/* ── Controls ──────────────────────────────────────────── */}
<Group>
{!isRunning ? (
<Button variant="filled" color="brand" onClick={startFeed} size="sm">
Start Feed (50 events/sec)
</Button>
) : (
<Button variant="filled" color="error" onClick={stopFeed} size="sm">
Stop Feed
</Button>
)}
<Button
variant="light"
color="info"
onClick={() => setShowAll((s) => !s)}
size="sm"
>
{showAll ? `Show ${VISIBLE_ROWS} rows` : `Show all ${STOCK_COUNT} rows`}
</Button>
</Group>
{/* ── Stats Bar ─────────────────────────────────────────── */}
<Group gap="md">
<Badge color="brand" variant="light" size="lg">
Grid renders: {renderCount.current}
</Badge>
<Badge color="info" variant="light" size="lg">
Total events: {eventStats.total.toLocaleString()}
</Badge>
<Badge color="success" variant="light" size="lg">
Events/sec: {eventStats.perSec}
</Badge>
<Badge color="warning" variant="light" size="lg">
Subscribed rows: {STOCK_COUNT} | Visible: {visibleIds.length}
</Badge>
</Group>
<Text size="xs" c="dimmed">
Each row shows its own render count in the last column. Only rows receiving updates re-render.
</Text>
{/* ── Data Grid ─────────────────────────────────────────── */}
<div style={{ maxHeight: 500, overflow: 'auto', border: '1px solid var(--mantine-color-default-border)' }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr
style={{
fontSize: 11,
fontWeight: 700,
textTransform: 'uppercase',
letterSpacing: '0.05em',
position: 'sticky',
top: 0,
background: 'var(--mantine-color-body)',
zIndex: 1,
}}
>
<th style={{ padding: '6px 8px', textAlign: 'left', borderBottom: '2px solid var(--mantine-color-default-border)' }}>Ticker</th>
<th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid var(--mantine-color-default-border)' }}>Price</th>
<th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid var(--mantine-color-default-border)' }}>Change</th>
<th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid var(--mantine-color-default-border)' }}>Volume</th>
<th style={{ padding: '6px 8px', textAlign: 'right', borderBottom: '2px solid var(--mantine-color-default-border)' }}>Renders</th>
</tr>
</thead>
<tbody>
{visibleIds.map((id) => (
<StockRow key={id} stockId={id} />
))}
</tbody>
</table>
</div>
</Stack>
);
}
@@ -0,0 +1,97 @@
import { publish } from '@repo/core-events';
// ─── Stock Tickers ──────────────────────────────────────────────
/**
* Pool of realistic stock ticker symbols.
* We generate 1000 unique IDs from these base tickers + numeric suffix.
*/
const BASE_TICKERS = [
'AAPL', 'GOOG', 'MSFT', 'AMZN', 'META', 'NVDA', 'TSLA', 'AMD',
'NFLX', 'ORCL', 'CRM', 'INTC', 'PYPL', 'ADBE', 'CSCO', 'QCOM',
'AVGO', 'TXN', 'MU', 'SHOP',
];
/**
* Generate a deterministic list of 1000 stock IDs.
*/
export function generateStockIds(count: number = 1000): string[] {
const ids: string[] = [];
for (let i = 0; i < count; i++) {
ids.push(`${BASE_TICKERS[i % BASE_TICKERS.length]}-${String(i).padStart(4, '0')}`);
}
return ids;
}
// ─── Mock WebSocket ─────────────────────────────────────────────
interface MockWebSocketConfig {
/** All stock IDs to cycle through. */
stockIds: string[];
/** Interval in ms between events. @default 20 */
intervalMs?: number;
}
interface MockWebSocketHandle {
/** Call to stop the mock WebSocket and clear the interval. */
cleanup: () => void;
/** Number of events emitted so far. */
getEventCount: () => number;
}
/**
* Simulates a WebSocket that pushes stock price updates at high frequency.
*
* Fires `WS:STOCK_UPDATE` every `intervalMs` (default 20ms = 50 updates/sec).
* Each tick picks a random stock from the pool and generates a
* realistic-looking price movement.
*
* Returns a handle with a `cleanup()` function to stop the simulation.
*
* @example
* ```ts
* const ws = startMockWebSocket({ stockIds: ['AAPL-0001', ...] });
* // Later:
* ws.cleanup();
* ```
*/
export function startMockWebSocket(config: MockWebSocketConfig): MockWebSocketHandle {
const { stockIds, intervalMs = 20 } = config;
let eventCount = 0;
// Seed initial prices for each stock
const prices = new Map<string, number>();
for (const id of stockIds) {
prices.set(id, 100 + Math.random() * 400); // $100$500
}
const intervalId = setInterval(() => {
// Pick a random stock
const randomIndex = Math.floor(Math.random() * stockIds.length);
const id = stockIds[randomIndex]!;
const currentPrice = prices.get(id)!;
// Generate a small random price change (-2% to +2%)
const changePercent = (Math.random() - 0.5) * 0.04;
const change = +(currentPrice * changePercent).toFixed(2);
const newPrice = +(currentPrice + change).toFixed(2);
// Update tracked price
prices.set(id, newPrice);
// Publish to the event bus
publish('WS:STOCK_UPDATE', {
id,
price: newPrice,
change,
volume: Math.floor(Math.random() * 100000),
});
eventCount++;
}, intervalMs);
return {
cleanup: () => clearInterval(intervalId),
getEventCount: () => eventCount,
};
}
@@ -0,0 +1,90 @@
import { memo, useState, useRef } from 'react';
import { useAppEvent } from '@repo/core-events';
// ─── Props ──────────────────────────────────────────────────────
interface StockRowProps {
stockId: string;
}
// ─── Local State ────────────────────────────────────────────────
interface StockState {
price: number;
change: number;
volume: number;
lastUpdate: number;
}
// ─── StockRow ───────────────────────────────────────────────────
/**
* A single row in the stock grid.
*
* **Performance architecture:**
* 1. Each StockRow subscribes to the global `WS:STOCK_UPDATE` event.
* 2. The handler checks `payload.id === stockId` — if no match, it
* does NOTHING (no setState, no re-render).
* 3. Only the targeted row updates its own local state.
* 4. `React.memo` prevents re-renders from parent prop changes.
*
* Result: At 50 events/sec across 1000 rows, only ~1 row re-renders
* per tick. The parent `LiveStockGrid` NEVER re-renders.
*/
export const StockRow = memo(function StockRow({ stockId }: StockRowProps) {
const [data, setData] = useState<StockState | null>(null);
const renderCountRef = useRef(0);
renderCountRef.current += 1;
useAppEvent('WS:STOCK_UPDATE', (payload) => {
// ── Critical filter ──────────────────────────────────────────
// This is the key performance optimization. Only the row whose
// ID matches the event payload will call setState. All other
// rows (999 out of 1000) do absolutely nothing.
if (payload.id !== stockId) return;
setData({
price: payload.price,
change: payload.change,
volume: payload.volume,
lastUpdate: Date.now(),
});
});
const changeColor = data
? data.change >= 0
? '#40c057' // green
: '#fa5252' // red
: undefined;
const changeArrow = data
? data.change >= 0
? '▲'
: '▼'
: '';
return (
<tr style={{ fontSize: 12, fontFamily: 'monospace' }}>
<td style={{ padding: '2px 8px', fontWeight: 600 }}>{stockId}</td>
<td style={{ padding: '2px 8px', textAlign: 'right' }}>
{data ? `$${data.price.toFixed(2)}` : '—'}
</td>
<td
style={{
padding: '2px 8px',
textAlign: 'right',
color: changeColor,
fontWeight: 600,
}}
>
{data ? `${changeArrow} ${data.change >= 0 ? '+' : ''}${data.change.toFixed(2)}` : '—'}
</td>
<td style={{ padding: '2px 8px', textAlign: 'right' }}>
{data ? data.volume.toLocaleString() : '—'}
</td>
<td style={{ padding: '2px 8px', textAlign: 'right', color: '#868e96' }}>
{renderCountRef.current}
</td>
</tr>
);
});
@@ -1,6 +1,6 @@
import { useEffect, useState, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { useTranslation, changeLanguage, applyTenantOverrides, i18n } from '@repo/core-i18n'; import { useTranslation, changeLanguage, applyTenantOverrides, i18n } from '@repo/core-i18n';
import { secureIndexedDB } from '@repo/core-storage'; import { secureIndexedDB, AppStorageKey } from '../../../../../../core/storage';
// Decentralized locale imports // Decentralized locale imports
import bookingId from '../locales/id/booking.json'; import bookingId from '../locales/id/booking.json';
@@ -16,32 +16,56 @@ const sectionStyle = {
background: '#0f172a', background: '#0f172a',
}; };
const btnStyle = (color: string) => ({ const btnStyle = (color: string, isActive: boolean = false) => ({
padding: '8px 16px', padding: '8px 16px',
fontSize: 14, fontSize: 14,
fontWeight: 600 as const, fontWeight: isActive ? 700 : 600,
cursor: 'pointer' as const, cursor: 'pointer' as const,
background: color, background: color,
color: '#fff', color: '#fff',
border: 'none', border: isActive ? '2px solid #fff' : '2px solid transparent',
borderRadius: 6, borderRadius: 6,
marginRight: 8, marginRight: 8,
}); });
// ─── Module-Level Flag ──────────────────────────────────────────
// Bendera penanda statis agar kamus hanya dimuat satu kali
let isBookingDictLoaded = false;
// ─── Component ────────────────────────────────────────────────── // ─── Component ──────────────────────────────────────────────────
export default function I18nSample() { export default function I18nSample() {
// 1. Eksekusi SINKRONUS tepat sebelum render pertama
if (!isBookingDictLoaded) {
i18n.addResourceBundle('id', 'booking', bookingId, true, false);
i18n.addResourceBundle('en', 'booking', bookingEn, true, false);
isBookingDictLoaded = true;
}
// 2. Sekarang useTranslation dijamin mendapat kamus yang sudah terisi penuh
const { t } = useTranslation(['common', 'booking']); const { t } = useTranslation(['common', 'booking']);
// State untuk melacak bahasa aktif secara real-time
const [activeLang, setActiveLang] = useState(i18n.language);
const [syncStatus, setSyncStatus] = useState<string>(''); const [syncStatus, setSyncStatus] = useState<string>('');
const [activeTenant, setActiveTenant] = useState<string>('default'); const [activeTenant, setActiveTenant] = useState<string>('default');
const [isFetchingConfig, setIsFetchingConfig] = useState(false); const [isFetchingConfig, setIsFetchingConfig] = useState(false);
// Dengarkan perubahan bahasa dari engine
useEffect(() => {
const handleLangChange = (lng: string) => setActiveLang(lng);
i18n.on('languageChanged', handleLangChange);
return () => {
i18n.off('languageChanged', handleLangChange);
};
}, []);
// ─── Admin Panel State ────────────────────────────────────────── // ─── Admin Panel State ──────────────────────────────────────────
const [adminModuleName, setAdminModuleName] = useState('PENGELUARAN'); const [adminModuleName, setAdminModuleName] = useState('PENGELUARAN');
const [adminHeaderTitle, setAdminHeaderTitle] = useState('Daftar Pengeluaran'); const [adminHeaderTitle, setAdminHeaderTitle] = useState('Daftar Pengeluaran');
const [dbPayloadStr, setDbPayloadStr] = useState<string>('No data in DB'); const [dbPayloadStr, setDbPayloadStr] = useState<string>('No data in DB');
const MOCK_DB_KEY = 'mock_db_company_a'; const MOCK_DB_KEY = AppStorageKey.MOCK_DB_COMPANY_A;
const loadDbPayload = useCallback(async () => { const loadDbPayload = useCallback(async () => {
try { try {
@@ -80,7 +104,6 @@ export default function I18nSample() {
} }
return data; return data;
} else if (companyId === 'company-b') { } else if (companyId === 'company-b') {
// Hardcoded fallback for B
return { return {
namespace: 'booking', namespace: 'booking',
overrides: { overrides: {
@@ -92,13 +115,6 @@ export default function I18nSample() {
throw new Error('Unknown company'); throw new Error('Unknown company');
}; };
// 1. Lazy-load the 'booking' namespace when the module mounts
useEffect(() => {
// Check if it's already loaded to prevent duplicate work, but for safety:
i18n.addResourceBundle('id', 'booking', bookingId, true, false);
i18n.addResourceBundle('en', 'booking', bookingEn, true, false);
}, []);
// ─── Section A: Language Switcher ────────────────────────────── // ─── Section A: Language Switcher ──────────────────────────────
const handleLanguageChange = async (newLng: string, shouldFail: boolean = false) => { const handleLanguageChange = async (newLng: string, shouldFail: boolean = false) => {
@@ -106,7 +122,6 @@ export default function I18nSample() {
try { try {
await changeLanguage(newLng, async (lng, _prevLng) => { await changeLanguage(newLng, async (lng, _prevLng) => {
// Mock API Call
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
setTimeout(() => { setTimeout(() => {
if (shouldFail) { if (shouldFail) {
@@ -117,7 +132,6 @@ export default function I18nSample() {
}, 1000); }, 1000);
}); });
// If success
setSyncStatus(`✅ Successfully synced language '${lng}' to backend.`); setSyncStatus(`✅ Successfully synced language '${lng}' to backend.`);
}); });
} catch (error) { } catch (error) {
@@ -132,11 +146,7 @@ export default function I18nSample() {
setActiveTenant(companyId); setActiveTenant(companyId);
try { try {
// 1. App successfully authenticates and fetches config
const config = await mockFetchTenantConfig(companyId); const config = await mockFetchTenantConfig(companyId);
// 2. Inject the deep-merge payload returned from the server
// In a real app, you might apply this to the current active language or all languages.
applyTenantOverrides(config.namespace, config.overrides, 'id'); applyTenantOverrides(config.namespace, config.overrides, 'id');
applyTenantOverrides(config.namespace, config.overrides, 'en'); applyTenantOverrides(config.namespace, config.overrides, 'en');
} catch (err) { } catch (err) {
@@ -147,7 +157,6 @@ export default function I18nSample() {
}; };
const resetTenant = () => { const resetTenant = () => {
// To reset, we just reload the original bundles
i18n.addResourceBundle('id', 'booking', bookingId, true, true); i18n.addResourceBundle('id', 'booking', bookingId, true, true);
i18n.addResourceBundle('en', 'booking', bookingEn, true, true); i18n.addResourceBundle('en', 'booking', bookingEn, true, true);
setActiveTenant('default'); setActiveTenant('default');
@@ -157,7 +166,7 @@ export default function I18nSample() {
<div style={{ fontFamily: 'sans-serif', color: '#f8fafc' }}> <div style={{ fontFamily: 'sans-serif', color: '#f8fafc' }}>
<h2 style={{ fontSize: 24, fontWeight: 'bold' }}>🌐 Enterprise i18n Demo</h2> <h2 style={{ fontSize: 24, fontWeight: 'bold' }}>🌐 Enterprise i18n Demo</h2>
<p style={{ color: '#94a3b8' }}> <p style={{ color: '#94a3b8' }}>
Current Active Language: <strong style={{ color: '#38bdf8' }}>{i18n.language}</strong> Current Active Language: <strong style={{ color: '#38bdf8' }}>{activeLang}</strong>
</p> </p>
{/* ─── Admin Panel ──────────────────────────────────────────── */} {/* ─── Admin Panel ──────────────────────────────────────────── */}
@@ -222,10 +231,16 @@ export default function I18nSample() {
</p> </p>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}> <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
<button onClick={() => handleLanguageChange('id')} style={btnStyle('#0284c7')}> <button
onClick={() => handleLanguageChange('id')}
style={btnStyle(activeLang === 'id' ? '#1d4ed8' : '#0ea5e9', activeLang === 'id')}
>
ID (Lokal & Sync) ID (Lokal & Sync)
</button> </button>
<button onClick={() => handleLanguageChange('en')} style={btnStyle('#0284c7')}> <button
onClick={() => handleLanguageChange('en')}
style={btnStyle(activeLang === 'en' ? '#1d4ed8' : '#0ea5e9', activeLang === 'en')}
>
EN (Lokal & Sync) EN (Lokal & Sync)
</button> </button>
<button onClick={() => handleLanguageChange('en', true)} style={btnStyle('#dc2626')}> <button onClick={() => handleLanguageChange('en', true)} style={btnStyle('#dc2626')}>
@@ -246,6 +261,19 @@ export default function I18nSample() {
{syncStatus} {syncStatus}
</div> </div>
)} )}
{/* UI Result untuk Section A */}
<div style={{ background: '#1e293b', padding: 16, borderRadius: 8, marginTop: 16 }}>
<h4 style={{ color: '#cbd5e1', marginBottom: 12 }}>UI Result (Live Dictionary):</h4>
<p style={{ margin: '4px 0', display: 'flex', alignItems: 'center' }}>
<code style={{ color: '#94a3b8', width: 180, display: 'inline-block' }}>common:save</code>
<strong style={{ fontSize: 16, color: '#10b981' }}>{t('common:save')}</strong>
</p>
<p style={{ margin: '4px 0', display: 'flex', alignItems: 'center' }}>
<code style={{ color: '#94a3b8', width: 180, display: 'inline-block' }}>booking:select_date</code>
<strong style={{ fontSize: 16, color: '#10b981' }}>{t('booking:select_date')}</strong>
</p>
</div>
</div> </div>
{/* ─── Section B ────────────────────────────────────────────── */} {/* ─── Section B ────────────────────────────────────────────── */}
@@ -257,19 +285,22 @@ export default function I18nSample() {
</p> </p>
<div style={{ display: 'flex', gap: 8, marginBottom: 24 }}> <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
<button onClick={resetTenant} style={btnStyle(activeTenant === 'default' ? '#16a34a' : '#475569')}> <button
onClick={resetTenant}
style={btnStyle(activeTenant === 'default' ? '#16a34a' : '#475569', activeTenant === 'default')}
>
Default Company Default Company
</button> </button>
<button <button
onClick={() => handleSimulateLogin('company-a')} onClick={() => handleSimulateLogin('company-a')}
style={btnStyle(activeTenant === 'company-a' ? '#16a34a' : '#475569')} style={btnStyle(activeTenant === 'company-a' ? '#16a34a' : '#475569', activeTenant === 'company-a')}
disabled={isFetchingConfig} disabled={isFetchingConfig}
> >
Simulate Login as Company A Simulate Login as Company A
</button> </button>
<button <button
onClick={() => handleSimulateLogin('company-b')} onClick={() => handleSimulateLogin('company-b')}
style={btnStyle(activeTenant === 'company-b' ? '#16a34a' : '#475569')} style={btnStyle(activeTenant === 'company-b' ? '#16a34a' : '#475569', activeTenant === 'company-b')}
disabled={isFetchingConfig} disabled={isFetchingConfig}
> >
Simulate Login as Company B Simulate Login as Company B
@@ -282,14 +313,13 @@ export default function I18nSample() {
{/* Display the localized strings */} {/* Display the localized strings */}
<div style={{ background: '#1e293b', padding: 16, borderRadius: 8 }}> <div style={{ background: '#1e293b', padding: 16, borderRadius: 8 }}>
<h4 style={{ color: '#cbd5e1', marginBottom: 12 }}>UI Result:</h4> <h4 style={{ color: '#cbd5e1', marginBottom: 12 }}>UI Result (Tenant Overlay):</h4>
<table style={{ width: '100%', textAlign: 'left', borderCollapse: 'collapse' }}> <table style={{ width: '100%', textAlign: 'left', borderCollapse: 'collapse' }}>
<tbody> <tbody>
<tr style={{ borderBottom: '1px solid #334155' }}> <tr style={{ borderBottom: '1px solid #334155' }}>
<th style={{ padding: 8, color: '#94a3b8' }}>Key</th> <th style={{ padding: 8, color: '#94a3b8' }}>Key</th>
<th style={{ padding: 8, color: '#94a3b8' }}>Value</th> <th style={{ padding: 8, color: '#94a3b8' }}>Value</th>
</tr> </tr>
{/* Type-safe keys from the common and booking namespaces */}
<tr style={{ borderBottom: '1px solid #334155' }}> <tr style={{ borderBottom: '1px solid #334155' }}>
<td style={{ padding: 8 }}> <td style={{ padding: 8 }}>
<code>booking:module_name</code> <code>booking:module_name</code>
@@ -308,18 +338,6 @@ export default function I18nSample() {
</td> </td>
<td style={{ padding: 8, fontWeight: 'bold' }}>{t('booking:header.subtitle')}</td> <td style={{ padding: 8, fontWeight: 'bold' }}>{t('booking:header.subtitle')}</td>
</tr> </tr>
<tr style={{ borderBottom: '1px solid #334155' }}>
<td style={{ padding: 8 }}>
<code>booking:select_date</code>
</td>
<td style={{ padding: 8, fontWeight: 'bold' }}>{t('booking:select_date')}</td>
</tr>
<tr>
<td style={{ padding: 8 }}>
<code>common:save</code>
</td>
<td style={{ padding: 8, fontWeight: 'bold' }}>{t('common:save')}</td>
</tr>
</tbody> </tbody>
</table> </table>
</div> </div>
@@ -1,11 +1,11 @@
import { useState, useCallback } from 'react'; import { useState, useCallback } from 'react';
import { secureStorage, secureIndexedDB, StorageKey } from '@repo/core-storage'; import { secureStorage, secureIndexedDB, AppStorageKey } from '../../../../../../core/storage';
// ─── Demo Data ────────────────────────────────────────────────── // ─── Demo Data ──────────────────────────────────────────────────
interface DemoUser { interface DemoUser {
id: number; id: string;
user: string; name: string;
role: string; role: string;
} }
@@ -15,11 +15,16 @@ interface DemoDraft {
content: string; content: string;
} }
const DEMO_USER: DemoUser = { id: 1, user: 'Firman', role: 'admin' }; const DEMO_USER: DemoUser = {
id: 'u-123',
name: 'Firman Ramdhani',
role: 'admin',
};
const DEMO_DRAFT: DemoDraft = { id: 101, type: 'offline_draft', content: 'Draft data saved offline' }; const DEMO_DRAFT: DemoDraft = { id: 101, type: 'offline_draft', content: 'Draft data saved offline' };
const LS_KEY = StorageKey.USER_PROFILE; // Encrypted at rest (in ENCRYPTED_KEYS) const LS_KEY = AppStorageKey.USER_PROFILE; // Encrypted at rest (in ENCRYPTED_KEYS)
const IDB_KEY = 'offline_draft'; // Plain key for IndexedDB demo const IDB_KEY = AppStorageKey.OFFLINE_DRAFT; // Plain key for IndexedDB demo
// ─── Shared Styles ────────────────────────────────────────────── // ─── Shared Styles ──────────────────────────────────────────────
@@ -21,6 +21,7 @@ import {
} from '@repo/ui/components'; } from '@repo/ui/components';
import PrinterList from './printer-list'; import PrinterList from './printer-list';
import ExamplePage from './example/example.page'; import ExamplePage from './example/example.page';
import EventsDemoPage from './events-demo';
interface ShowcaseViewProps { interface ShowcaseViewProps {
colorScheme: ColorSchemeType; colorScheme: ColorSchemeType;
@@ -219,6 +220,11 @@ export default function ShowcaseView({ colorScheme, setColorScheme, density, set
</Text> </Text>
<ExamplePage /> <ExamplePage />
</Card> </Card>
{/* =========================================
EVENT BUS SHOWCASE
========================================= */}
<EventsDemoPage />
</Stack> </Stack>
</Container> </Container>
); );
+35
View File
@@ -0,0 +1,35 @@
import { createLocalStorage, createIndexedDB } from '@repo/core-storage';
export const AppStorageKey = {
USER_PROFILE: 'user_profile',
LOCALE: 'app_locale',
ACCESS_TOKEN: 'access_token',
REFRESH_TOKEN: 'refresh_token',
MOCK_DB_COMPANY_A: 'mock_db_company_a',
OFFLINE_DRAFT: 'offline_draft',
} as const;
export type AppStorageKeyValue = (typeof AppStorageKey)[keyof typeof AppStorageKey];
export const ENCRYPTED_KEYS = new Set<AppStorageKeyValue>([
AppStorageKey.USER_PROFILE,
AppStorageKey.ACCESS_TOKEN,
AppStorageKey.REFRESH_TOKEN,
]);
export const PLAIN_KEYS = new Set<AppStorageKeyValue>([
AppStorageKey.LOCALE,
AppStorageKey.MOCK_DB_COMPANY_A,
AppStorageKey.OFFLINE_DRAFT,
]);
export const secureStorage = createLocalStorage<AppStorageKeyValue>({
encryptedKeys: ENCRYPTED_KEYS,
plainTextKeys: PLAIN_KEYS,
});
export const secureIndexedDB = createIndexedDB<AppStorageKeyValue>({
dbName: 'eigen_erp_db',
storeName: 'web_store',
encryptedKeys: ENCRYPTED_KEYS,
plainTextKeys: PLAIN_KEYS,
});
+7 -1
View File
@@ -16,12 +16,18 @@ import './main.css';
import { lazy, StrictMode } from 'react'; import { lazy, StrictMode } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { setupI18n } from '@repo/core-i18n'; import { setupI18n } from '@repo/core-i18n';
import { secureStorage, AppStorageKey } from './core/storage';
const App = lazy(() => import('./apps')); const App = lazy(() => import('./apps'));
async function bootstrap() { async function bootstrap() {
// Initialize i18next and load language from secureStorage // Initialize i18next and load language from secureStorage
await setupI18n(); await setupI18n({
storageAdapter: {
getLanguage: async () => await secureStorage.getItem<string>(AppStorageKey.LOCALE),
setLanguage: async (lng: string) => await secureStorage.setItem(AppStorageKey.LOCALE, lng),
},
});
createRoot(document.getElementById('app')!).render( createRoot(document.getElementById('app')!).render(
<StrictMode> <StrictMode>
+76
View File
@@ -0,0 +1,76 @@
/**
* App-level event registry for `apps/web`.
*
* This file uses TypeScript Declaration Merging (Module Augmentation)
* to extend the open `AppEventRegistry` interface exported by
* `@repo/core-events`. This is the IoC pattern in action:
*
* - `@repo/core-events` provides the bus, hooks, and helpers (the tool).
* - `apps/web` defines which events exist and their payload shapes (the contract).
*
* The core package has zero knowledge of these events. If `apps/web`
* is removed from the monorepo, the core package remains unchanged.
*
* **Adding new events**: Simply add new entries to `AppEventRegistry`
* below. TypeScript will automatically provide autocomplete and
* type safety across every `publish()` / `useAppEvent()` call in
* the web app.
*
* @see packages/core-events/src/events.registry.ts
*/
// This import turns this file from an ambient declaration into a
// module augmentation. Without it, `declare module` would REPLACE
// the module signature instead of merging into it.
import type {} from '@repo/core-events';
declare module '@repo/core-events' {
// ─── Payload Types ──────────────────────────────────────────
interface ReceiptItem {
name: string;
qty: number;
price: number;
}
interface PrintReceiptPayload {
receiptId: string;
items: ReceiptItem[];
total: number;
cashierName: string;
timestamp: number;
}
interface StockUpdatePayload {
id: string;
price: number;
change: number;
volume: number;
}
interface ProfileUpdatedPayload {
id: string;
name: string;
email: string;
avatar: string;
updatedAt: number;
}
// ─── Event Registry ─────────────────────────────────────────
interface AppEventRegistry {
// ── Device / Hardware ─────────────────────────────────────
'DEVICE:PRINT_RECEIPT': PrintReceiptPayload;
// ── WebSocket / Real-Time ────────────────────────────────
'WS:STOCK_UPDATE': StockUpdatePayload;
// ── Auth / User ──────────────────────────────────────────
'AUTH:PROFILE_UPDATED': ProfileUpdatedPayload;
// ── App Lifecycle ────────────────────────────────────────
'APP:INITIALIZED': undefined;
'APP:ERROR': { message: string; code?: string };
}
}
+95 -55
View File
@@ -1,65 +1,105 @@
# @repo/core-api # Enterprise API Engine (`@repo/core-api`)
The platform-agnostic API engine for the monorepo. Provides an isolated HTTP client factory, a unified observability pipeline (Grafana Faro + OpenTelemetry), and a generic data services engine — consumed by `apps/web`, `apps/landing`, and any future workspace. [← Back to Root](../../README.md)
--- The platform-agnostic API engine for the monorepo. Provides an isolated HTTP client factory, a unified observability pipeline (Grafana Faro + OpenTelemetry), and a generic data services engine.
## Table of Contents **This package enforces App Autonomy (IoC).** The core provides the engine and interceptor pipelines, but the consuming applications (`apps/web`, `apps/landing`) inject their own specific configurations, authentication tokens, and error handling behaviors.
- [Architecture Overview](#architecture-overview)
- [HTTP Client](#http-client)
- [Observability](#observability)
- [Data Services](#data-services)
- [Application Setup Guide](#application-setup-guide)
- [Per-Request Telemetry (Escape Hatch)](#per-request-telemetry-escape-hatch)
- [Error Handling](#error-handling)
- [Package Exports](#package-exports)
--- ---
## Architecture Overview ## Architecture Overview
``` ```mermaid
┌────────────────────────────────────────────────────────────────────┐ graph TD
@repo/core-api │ subgraph Apps ["apps/* (App Autonomy)"]
│ │ WEB[apps/web]
│ ┌──────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ LAND[apps/landing]
│ │ http-client │ │ observability │ │ data-services │ │ DESK[apps/desktop]
│ │ │ │ │ │ │ │ end
│ │ createHttp │◄──│ faroAdapter │ │ BaseRemoteData │ │
│ │ Client() │ │ initTelemetry() │ │ Services │ │ subgraph Core ["@repo/core-api (Engine)"]
│ │ │ │ getFaro() │ │ CommonRemoteData │ │ subgraph HTTP ["http-client"]
│ │ ApiResponse │ │ noopAdapter │ │ Services │ │ FACTORY[createHttpClient]
│ └──────┬───────┘ └───────────────────┘ └────────┬──────────┘ │ end
│ │ │ │ subgraph OBS ["observability"]
│ └────────────────────┬───────────────────────┘ │ FARO[faroAdapter]
│ │ │ end
│ ┌────────┴────────┐ │ subgraph DATA ["data-services"]
│ │ errors │ │ BASE[BaseRemoteDataServices]
│ │ ApiError │ │ COMMON[CommonRemoteDataServices]
│ │ ErrorCodes │ │ end
│ └─────────────────┘ │ subgraph ERRORS ["errors"]
└────────────────────────────────────────────────────────────────────┘ API_ERR[ApiError]
│ │ │ end
▼ ▼ ▼ end
apps/web apps/landing apps/desktop
WEB & LAND & DESK -->|instantiates| FACTORY
WEB & LAND & DESK -->|extends| COMMON
COMMON -->|executes via| FACTORY
FACTORY -.->|reports via| FARO
FACTORY -.->|throws| API_ERR
%% Styling Subgraphs (Backgrounds)
style Apps fill:#e7f5ff,stroke:#74c0fc,stroke-width:2px,color:#1864ab
style Core fill:#f8f9fa,stroke:#ced4da,stroke-width:2px,color:#495057
%% Styling Nodes (Apps - Blue)
style WEB fill:#339af0,stroke:#1864ab,color:#fff
style LAND fill:#339af0,stroke:#1864ab,color:#fff
style DESK fill:#339af0,stroke:#1864ab,color:#fff
%% Styling Nodes (Core Modules)
style FACTORY fill:#845ef7,stroke:#5f3dc4,color:#fff
style FARO fill:#fd7e14,stroke:#d9480f,color:#fff
style BASE fill:#20c997,stroke:#089981,color:#fff
style COMMON fill:#20c997,stroke:#089981,color:#fff
style API_ERR fill:#fa5252,stroke:#c92a2a,color:#fff
``` ```
### Data Flow ### Data Flow Lifecycle
Every HTTP request flows through this pipeline: Every HTTP request flows through this precise interceptor pipeline:
``` ```mermaid
Component → DataService.getMany() → execute() sequenceDiagram
→ httpClient.request() autonumber
→ Request Interceptor:
1. faroAdapter.onRequestStart() ← Faro log + optional custom span box #e7f5ff App Layer (Consumers)
2. hooks.onRequest() ← App-specific (e.g., Bearer token) participant C as UI Component
→ Network (fetch/XHR) end
→ Response Interceptor:
SUCCESS: faroAdapter.onRequestEnd() → hooks.onResponse() box #f8f9fa Core Engine (@repo/core-api)
ERROR: faroAdapter.onRequestError() → hooks.onResponseError() participant S as Data Service
→ ApiError.fromAxiosError() participant H as HTTP Client
participant F as Faro Adapter
end
box #e7f5ff App Logic (IoC)
participant A as App Hooks
end
box #fff5f5 External
participant N as Network
end
C->>S: getMany()
S->>H: request()
H->>F: onRequestStart() (Log + Span)
H->>A: hooks.onRequest() (Inject Token)
A->>N: fetch/XHR
alt Success (2xx)
N-->>A: return Response
A->>F: onRequestEnd() (Close Span)
F->>A: hooks.onResponse()
A-->>S: return data
else Error (4xx / 5xx)
N-->>A: return Rejection
A->>F: onRequestError() (Log Error)
F->>A: hooks.onResponseError() (Redirect/Refresh)
A-->>S: throw ApiError
end
``` ```
> [!IMPORTANT] > [!IMPORTANT]
@@ -143,10 +183,10 @@ import { initTelemetry } from '@repo/core-api/observability/setup';
initTelemetry({ initTelemetry({
appName: 'fe-monorepo-web', appName: 'fe-monorepo-web',
appVersion: '1.0.0', appVersion: '1.0.0',
telemetryUrl: 'https://telemetry.eigen.co.id/collect', telemetryUrl: '[https://telemetry.eigen.co.id/collect](https://telemetry.eigen.co.id/collect)',
environment: 'production', environment: 'production',
// Optional: direct OTLP export to Grafana Tempo // Optional: direct OTLP export to Grafana Tempo
otlpTraceUrl: 'https://telemetry.eigen.co.id/v1/traces', otlpTraceUrl: '[https://telemetry.eigen.co.id/v1/traces](https://telemetry.eigen.co.id/v1/traces)',
}); });
``` ```
@@ -254,8 +294,8 @@ import { initTelemetry } from '@repo/core-api/observability/setup';
initTelemetry({ initTelemetry({
appName: import.meta.env.VITE_APP_NAME || 'fe-monorepo-web', appName: import.meta.env.VITE_APP_NAME || 'fe-monorepo-web',
appVersion: import.meta.env.VITE_APP_VERSION || '0.0.0', appVersion: import.meta.env.VITE_APP_VERSION || '0.0.0',
telemetryUrl: import.meta.env.VITE_FARO_URL || 'https://telemetry.eigen.co.id/collect', telemetryUrl: import.meta.env.VITE_FARO_URL || '[https://telemetry.eigen.co.id/collect](https://telemetry.eigen.co.id/collect)',
otlpTraceUrl: import.meta.env.VITE_OTLP_TRACE_URL || 'https://telemetry.eigen.co.id/v1/traces', otlpTraceUrl: import.meta.env.VITE_OTLP_TRACE_URL || '[https://telemetry.eigen.co.id/v1/traces](https://telemetry.eigen.co.id/v1/traces)',
environment: import.meta.env.VITE_ENV || 'development', environment: import.meta.env.VITE_ENV || 'development',
}); });
@@ -422,4 +462,4 @@ try {
| `@repo/core-api/observability` | `faroAdapter`, `noopObservabilityAdapter`, `IObservabilityAdapter`, `initTelemetry`, `getFaro`, `TelemetryConfig` | | `@repo/core-api/observability` | `faroAdapter`, `noopObservabilityAdapter`, `IObservabilityAdapter`, `initTelemetry`, `getFaro`, `TelemetryConfig` |
| `@repo/core-api/observability/setup` | `initTelemetry`, `getFaro`, `TelemetryConfig` | | `@repo/core-api/observability/setup` | `initTelemetry`, `getFaro`, `TelemetryConfig` |
| `@repo/core-api/data-services` | `BaseRemoteDataServices`, `CommonRemoteDataServices`, types, constants | | `@repo/core-api/data-services` | `BaseRemoteDataServices`, `CommonRemoteDataServices`, types, constants |
| `@repo/core-api/errors` | `ApiError`, `ApiErrorCode` | | `@repo/core-api/errors` | `ApiError`, `ApiErrorCode` |
+324
View File
@@ -0,0 +1,324 @@
# @repo/core-events
[← Back to Root](../../README.md)
## Overview
`@repo/core-events` is the **decoupled Nervous System** of the ERP. It provides a highly performant, strictly typed Event Bus powered by `mitt` and React hooks.
**This package is a pure tool.** It ships zero application-specific events. Each consuming app (`apps/web`, `apps/landing`, etc.) registers its own events autonomously using TypeScript Declaration Merging — the same Inversion of Control pattern used by `@repo/core-api`'s `createHttpClient` factory.
By routing communication through a centralized event bus, we achieve:
- **App Autonomy**: The core defines the bus. The app defines the contract. No circular knowledge.
- **Zero Coupling**: Publishers and subscribers don't need to import or know about each other.
- **Extreme Performance**: Components can subscribe to high-frequency data streams (like WebSockets) and update their own local state *without* triggering massive React tree re-renders.
- **Memory Safety**: The provided `useAppEvent` hook automatically handles subscription cleanup on component unmount, preventing the most common source of memory leaks in SPA architectures.
---
## Architecture
```mermaid
graph TD
subgraph Core ["@repo/core-events (Pure Tool)"]
R["AppEventRegistry<br/>(empty interface)"]
T["AppEvents = mapped type"]
E((Event Bus<br/>mitt))
H[useAppEvent / usePublishEvent]
R --> T --> E
E --> H
end
subgraph Apps ["apps/web (App Autonomy)"]
D["events.d.ts<br/>declare module augmentation"]
A[Cashier UI]
B[Profile Settings]
C[WebSocket Client]
X[Electron IPC Bridge]
Y[IndexedDB Sync]
Z[Stock Grid Row]
end
D -. "merges into" .-> R
A -- "DEVICE:PRINT_RECEIPT" --> E
B -- "AUTH:PROFILE_UPDATED" --> E
C -- "WS:STOCK_UPDATE" --> E
E -.-> X
E -.-> Y
E -.-> Z
%% Styling Subgraphs (Backgrounds)
style Core fill:#f8f9fa,stroke:#ced4da,stroke-width:2px,color:#495057
style Apps fill:#e7f5ff,stroke:#74c0fc,stroke-width:2px,color:#1864ab
%% Styling Core Engine (Purple) & Contracts (Green)
style R fill:#20c997,stroke:#089981,color:#fff
style T fill:#20c997,stroke:#089981,color:#fff
style E fill:#845ef7,stroke:#5f3dc4,color:#fff
style H fill:#845ef7,stroke:#5f3dc4,color:#fff
%% Styling App Injection (Orange) & Components (Blue)
style D fill:#fd7e14,stroke:#d9480f,color:#fff
style A fill:#339af0,stroke:#1864ab,color:#fff
style B fill:#339af0,stroke:#1864ab,color:#fff
style C fill:#339af0,stroke:#1864ab,color:#fff
style X fill:#339af0,stroke:#1864ab,color:#fff
style Y fill:#339af0,stroke:#1864ab,color:#fff
style Z fill:#339af0,stroke:#1864ab,color:#fff
```
---
## Defining Events (Module Augmentation)
> [!IMPORTANT]
> **Do NOT add application events to `packages/core-events/src/events.registry.ts`.**
> The core registry is intentionally empty. Each app owns its own event contract.
The core exports an open `AppEventRegistry` interface. Apps extend it using TypeScript's `declare module` syntax — the same pattern used for `@types/*` across the JS ecosystem.
### Step 1: Create an augmentation file in your app
> [!WARNING]
> The `import type {}` line is **mandatory**. Without it, TypeScript treats `declare module` as an ambient module declaration that **replaces** the module's types instead of merging into them. All actual exports (`useAppEvent`, `publish`, etc.) would become invisible.
```typescript
// apps/web/src/types/events.d.ts
// This import makes this file a module augmentation (merge)
// instead of an ambient declaration (replace).
import type {} from '@repo/core-events';
declare module '@repo/core-events' {
// Define your payload shapes
interface OrderPayload {
orderId: string;
total: number;
items: Array<{ sku: string; qty: number }>;
}
// Extend the registry
interface AppEventRegistry {
'STORE:ORDER_PLACED': OrderPayload;
'STORE:ORDER_CANCELLED': { orderId: string; reason: string };
'UI:SIDEBAR_TOGGLED': { collapsed: boolean };
// Explicit payloads for the examples below:
'DEVICE:PRINT_RECEIPT': { receiptId: string; items: any[]; total: number; cashierName: string; timestamp: number };
'WS:STOCK_UPDATE': { id: string; price: number };
'AUTH:PROFILE_UPDATED': { id: string; name: string; email: string; avatar: string; updatedAt: number };
'SYSTEM:ERROR': { source: string; error: Error };
}
}
```
### Step 2: Use it — autocomplete works immediately
```tsx
import { usePublishEvent, useAppEvent } from '@repo/core-events';
function CheckoutButton() {
const publish = usePublishEvent();
// ✅ 'STORE:ORDER_PLACED' autocompletes.
// ✅ Payload shape is enforced by TypeScript.
publish('STORE:ORDER_PLACED', { orderId: '123', total: 99, items: [] });
}
function OrderTracker() {
// ✅ payload is fully typed as OrderPayload
useAppEvent('STORE:ORDER_PLACED', (payload) => {
console.log(payload.orderId); // string
});
}
```
### Why this pattern?
| Concern | Old (Hardcoded) | New (Module Augmentation) |
|---|---|---|
| Core knows about app events? | ❌ Yes — violates IoC | ✅ No — core is a pure tool |
| Adding events requires editing core? | ❌ Yes | ✅ No — edit your app's `.d.ts` only |
| Multiple apps share the same registry? | ❌ Collision risk | ✅ Each app has its own `.d.ts` |
| Type safety / autocomplete | ✅ Works | ✅ Works identically |
---
## Usage Outside React (Vanilla TS)
For utility files, API interceptors, Web Workers, or vanilla functions where React hooks cannot be used, import the raw `eventBus` instance directly.
```ts
import { eventBus } from '@repo/core-events';
// Publishing
eventBus.publish('STORE:ORDER_CANCELLED', { orderId: '123', reason: 'Out of stock' });
// Subscribing
const handler = (payload) => {
console.log('Order cancelled:', payload.orderId);
};
eventBus.subscribe('STORE:ORDER_CANCELLED', handler);
// CRITICAL: Always unsubscribe when done to prevent memory leaks in non-React contexts!
eventBus.unsubscribe('STORE:ORDER_CANCELLED', handler);
```
---
## Usage Examples
Here are three real-world architectural patterns powered by the Event Bus. All event types below are registered in `apps/web/src/types/events.d.ts`, **not** in the core package.
### Example 1: Hardware Abstraction (Cross-Platform)
**Problem**: The web app needs to print receipts. If running in a browser, it should use `window.print()`. If running in the Electron wrapper, it must use the secure IPC bridge (`window.electronAPI.print()`). We don't want the UI components cluttered with platform-detection logic.
**Solution**: The UI publishes a blind event. A headless listener handles the platform routing.
**Publisher (Cashier UI)**:
```tsx
import { usePublishEvent } from '@repo/core-events';
export function CashierUI() {
const publish = usePublishEvent();
const handlePrint = () => {
// Fire and forget. Zero knowledge of how printing actually happens.
publish('DEVICE:PRINT_RECEIPT', {
receiptId: 'RCP-123',
items: [],
total: 45.00,
cashierName: 'Firman',
timestamp: Date.now(),
});
};
return <Button onClick={handlePrint}>Print Receipt</Button>;
}
```
**Subscriber (Headless Listener)**:
```tsx
import { useAppEvent } from '@repo/core-events';
export function PrinterListener() {
useAppEvent('DEVICE:PRINT_RECEIPT', (payload) => {
const isElectron = typeof window !== 'undefined' && !!window.electronAPI;
if (isElectron) {
// Route via secure Electron IPC bridge
window.electronAPI.print({ silent: true });
} else {
// Fallback to standard browser print dialog
window.print();
}
});
return null; // Renders nothing
}
```
---
### Example 2: Extreme Performance (High-Frequency Data)
**Problem**: A massive data grid (1,000+ rows) receives 50 WebSocket updates per second. If the parent grid holds the state and passes it down via props, React will attempt to re-render all 1,000 rows 50 times a second, crushing the browser.
**Solution**: The parent grid renders empty rows. Each row subscribes to the event bus and filters updates so it only re-renders when its specific data changes.
**Parent Grid (Never re-renders)**:
```tsx
export function LiveStockGrid() {
// Generates 1000 IDs once. No stock data is stored here!
const stockIds = generateStockIds(1000);
return (
<table>
<tbody>
{stockIds.map((id) => (
<StockRow key={id} stockId={id} />
))}
</tbody>
</table>
);
}
```
**Child Row (Targeted Updates)**:
```tsx
import { memo, useState } from 'react';
import { useAppEvent } from '@repo/core-events';
export const StockRow = memo(function StockRow({ stockId }) {
const [data, setData] = useState(null);
useAppEvent('WS:STOCK_UPDATE', (payload) => {
// CRITICAL: Filter out events for other rows.
// 999 out of 1000 rows will exit here instantly without causing a re-render.
if (payload.id !== stockId) return;
// Only the targeted row updates its local state
setData(payload);
});
return (
<tr>
<td>{stockId}</td>
<td>{data?.price}</td>
</tr>
);
});
```
---
### Example 3: Background Sync (Auth to IndexedDB)
**Problem**: When a user updates their profile, we need to persist it to the secure local IndexedDB. We don't want to tightly couple our UI forms to the `@repo/core-storage` package.
**Solution**: The UI form announces the profile update. A dedicated storage listener persists it in the background, properly escalating errors if the storage fails.
**Publisher (Profile UI)**:
```tsx
import { usePublishEvent } from '@repo/core-events';
export function ProfileSettingsUI() {
const publish = usePublishEvent();
const handleSave = () => {
publish('AUTH:PROFILE_UPDATED', {
id: 'user-1',
name: 'Firman',
email: 'firman@eigen.co.id',
avatar: '[https://example.com/avatar.png](https://example.com/avatar.png)',
updatedAt: Date.now(),
});
};
return <Button onClick={handleSave}>Save Profile</Button>;
}
```
**Subscriber (Storage Sync Listener)**:
```tsx
import { useAppEvent, usePublishEvent } from '@repo/core-events';
import { secureIndexedDB } from '@repo/core-storage';
export function StorageSyncListener() {
const publish = usePublishEvent();
useAppEvent('AUTH:PROFILE_UPDATED', (payload) => {
// Automatically encrypted at rest because 'user_profile'
// is defined in ENCRYPTED_KEYS in @repo/core-storage
secureIndexedDB.setItem('user_profile', payload).catch((error) => {
// Escalate to global error handler instead of swallowing it
publish('SYSTEM:ERROR', { source: 'StorageSyncListener', error });
});
});
return null;
}
```
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@repo/core-events",
"version": "0.0.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"license": "MIT",
"scripts": {
"lint": "eslint \"**/*.ts\" \"**/*.tsx\"",
"test": "vitest run",
"test:watch": "vitest --watch",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"mitt": "^3.0.1"
},
"peerDependencies": {
"react": ">=18.0.0"
},
"devDependencies": {
"@repo/eslint-config": "workspace:*",
"@repo/typescript-config": "workspace:*",
"@testing-library/react": "^16.3.0",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"eslint": "^8.57.1",
"jsdom": "^26.1.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"typescript": "5.5.4",
"vitest": "^4.0.17"
}
}
+299
View File
@@ -0,0 +1,299 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { eventBus, publish, subscribe } from './event-bus';
import { useAppEvent, usePublishEvent } from './hooks';
// ─── Test-Local Event Augmentation ──────────────────────────────
//
// In a real app, these would live in a `.d.ts` file inside the app's
// `src/types/` folder using `declare module '@repo/core-events'`.
//
// For the core package's own test suite, we augment the registry
// directly here so the tests have concrete event types to work with
// without polluting the core's shipped types.
//
declare module './events.registry' {
interface AppEventRegistry {
'TEST:STOCK_UPDATE': StockUpdatePayload;
'TEST:PROFILE_UPDATED': ProfileUpdatedPayload;
'TEST:INITIALIZED': undefined;
}
}
// ─── Test Payload Types ─────────────────────────────────────────
interface StockUpdatePayload {
id: string;
price: number;
change: number;
volume: number;
}
interface ProfileUpdatedPayload {
id: string;
name: string;
email: string;
avatar: string;
updatedAt: number;
}
// ─── Helpers ────────────────────────────────────────────────────
/** Clear all mitt handlers between tests to avoid cross-contamination. */
function clearAllHandlers() {
eventBus.all.clear();
}
// ─── Test Data ──────────────────────────────────────────────────
const mockStockUpdate: StockUpdatePayload = {
id: 'AAPL',
price: 185.42,
change: 1.23,
volume: 50000,
};
const mockProfile: ProfileUpdatedPayload = {
id: 'user-1',
name: 'Firman',
email: 'firman@eigen.co.id',
avatar: 'https://example.com/avatar.png',
updatedAt: Date.now(),
};
// ─── Core Event Bus Tests ───────────────────────────────────────
describe('Event Bus (Core)', () => {
beforeEach(() => {
clearAllHandlers();
});
afterEach(() => {
clearAllHandlers();
});
it('publishes and subscribes to a typed event', () => {
const handler = vi.fn();
subscribe('TEST:STOCK_UPDATE', handler);
publish('TEST:STOCK_UPDATE', mockStockUpdate);
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(mockStockUpdate);
});
it('delivers events to multiple subscribers', () => {
const handler1 = vi.fn();
const handler2 = vi.fn();
subscribe('TEST:PROFILE_UPDATED', handler1);
subscribe('TEST:PROFILE_UPDATED', handler2);
publish('TEST:PROFILE_UPDATED', mockProfile);
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(1);
});
it('does not deliver events to unrelated subscribers', () => {
const stockHandler = vi.fn();
const profileHandler = vi.fn();
subscribe('TEST:STOCK_UPDATE', stockHandler);
subscribe('TEST:PROFILE_UPDATED', profileHandler);
publish('TEST:STOCK_UPDATE', mockStockUpdate);
expect(stockHandler).toHaveBeenCalledTimes(1);
expect(profileHandler).not.toHaveBeenCalled();
});
it('unsubscribes correctly via returned function', () => {
const handler = vi.fn();
const unsub = subscribe('TEST:STOCK_UPDATE', handler);
publish('TEST:STOCK_UPDATE', mockStockUpdate);
expect(handler).toHaveBeenCalledTimes(1);
// Unsubscribe
unsub();
publish('TEST:STOCK_UPDATE', mockStockUpdate);
// Should still be 1, not 2
expect(handler).toHaveBeenCalledTimes(1);
});
it('handles events with undefined payloads', () => {
const handler = vi.fn();
subscribe('TEST:INITIALIZED', handler);
publish('TEST:INITIALIZED', undefined);
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(undefined);
});
it('handles rapid-fire events without loss', () => {
const handler = vi.fn();
subscribe('TEST:STOCK_UPDATE', handler);
for (let i = 0; i < 1000; i++) {
publish('TEST:STOCK_UPDATE', { ...mockStockUpdate, id: `STOCK-${i}` });
}
expect(handler).toHaveBeenCalledTimes(1000);
});
});
// ─── React Hook Tests ───────────────────────────────────────────
describe('useAppEvent (React Hook)', () => {
beforeEach(() => {
clearAllHandlers();
});
afterEach(() => {
clearAllHandlers();
});
it('subscribes on mount and receives events', () => {
const handler = vi.fn();
renderHook(() => useAppEvent('TEST:STOCK_UPDATE', handler));
act(() => {
publish('TEST:STOCK_UPDATE', mockStockUpdate);
});
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(mockStockUpdate);
});
it('unsubscribes on unmount — MEMORY LEAK PREVENTION', () => {
const handler = vi.fn();
const { unmount } = renderHook(() => useAppEvent('TEST:STOCK_UPDATE', handler));
// Event should be received while mounted
act(() => {
publish('TEST:STOCK_UPDATE', mockStockUpdate);
});
expect(handler).toHaveBeenCalledTimes(1);
// Unmount the component
unmount();
// Event should NOT be received after unmount
act(() => {
publish('TEST:STOCK_UPDATE', mockStockUpdate);
});
// Still 1, proving the handler was properly cleaned up
expect(handler).toHaveBeenCalledTimes(1);
});
it('does not leak handlers across mount/unmount cycles', () => {
const handler = vi.fn();
// Mount and unmount 100 times
for (let i = 0; i < 100; i++) {
const { unmount } = renderHook(() => useAppEvent('TEST:STOCK_UPDATE', handler));
unmount();
}
// After 100 cycles, emit one event
act(() => {
publish('TEST:STOCK_UPDATE', mockStockUpdate);
});
// Should be 0 — all handlers should have been cleaned up
expect(handler).toHaveBeenCalledTimes(0);
// Verify the handler map is empty for this event type
const handlers = eventBus.all.get('TEST:STOCK_UPDATE');
expect(!handlers || handlers.length === 0).toBe(true);
});
it('always calls the latest handler (no stale closures)', () => {
let capturedValue = '';
const { rerender } = renderHook(
({ value }: { value: string }) =>
useAppEvent('TEST:PROFILE_UPDATED', () => {
capturedValue = value;
}),
{ initialProps: { value: 'initial' } },
);
// Update the closure value
rerender({ value: 'updated' });
act(() => {
publish('TEST:PROFILE_UPDATED', mockProfile);
});
// Should capture the LATEST value, not the stale 'initial'
expect(capturedValue).toBe('updated');
});
it('does not re-subscribe when handler reference changes', () => {
// We spy on eventBus.on to count subscription calls
const onSpy = vi.spyOn(eventBus, 'on');
const offSpy = vi.spyOn(eventBus, 'off');
const { rerender } = renderHook(
({ handler }: { handler: () => void }) =>
useAppEvent('TEST:INITIALIZED', handler),
{ initialProps: { handler: vi.fn() } },
);
const initialOnCount = onSpy.mock.calls.length;
const initialOffCount = offSpy.mock.calls.length;
// Re-render with a NEW handler function reference
rerender({ handler: vi.fn() });
// on/off should NOT have been called again (ref-based pattern)
expect(onSpy.mock.calls.length).toBe(initialOnCount);
expect(offSpy.mock.calls.length).toBe(initialOffCount);
onSpy.mockRestore();
offSpy.mockRestore();
});
});
describe('usePublishEvent (React Hook)', () => {
beforeEach(() => {
clearAllHandlers();
});
afterEach(() => {
clearAllHandlers();
});
it('returns a working publish function', () => {
const handler = vi.fn();
subscribe('TEST:PROFILE_UPDATED', handler);
const { result } = renderHook(() => usePublishEvent());
act(() => {
result.current('TEST:PROFILE_UPDATED', mockProfile);
});
expect(handler).toHaveBeenCalledTimes(1);
expect(handler).toHaveBeenCalledWith(mockProfile);
});
it('returns a referentially stable function across re-renders', () => {
const { result, rerender } = renderHook(() => usePublishEvent());
const firstRef = result.current;
rerender();
rerender();
rerender();
expect(result.current).toBe(firstRef);
});
});
+67
View File
@@ -0,0 +1,67 @@
import mitt from 'mitt';
import type { AppEvents } from './events.registry';
// ─── Singleton Event Bus ────────────────────────────────────────
/**
* Application-wide event bus a strictly typed `mitt` instance.
*
* Prefer the `publish` / `subscribe` helper functions or the React
* hooks (`useAppEvent`, `usePublishEvent`) over using this directly.
* Direct access is provided for edge cases like middleware or testing.
*
* @example
* ```ts
* import { eventBus } from '@repo/core-events';
* eventBus.on('APP:ERROR', (e) => console.error(e.message));
* ```
*/
export const eventBus = mitt<AppEvents>();
// ─── Type-Safe Helpers ──────────────────────────────────────────
/**
* Emit (publish) a typed event to all subscribers.
*
* @param type - The event name from `AppEvents`.
* @param event - The payload matching that event's type.
*
* @example
* ```ts
* publish('AUTH:PROFILE_UPDATED', { id: '1', name: 'Firman', ... });
* ```
*/
export function publish<K extends keyof AppEvents>(
type: K,
event: AppEvents[K],
): void {
eventBus.emit(type, event);
}
/**
* Subscribe to a typed event.
*
* Returns an `unsubscribe` function call it to remove the handler.
* For React components, prefer `useAppEvent` which handles cleanup
* automatically on unmount.
*
* @param type - The event name from `AppEvents`.
* @param handler - Callback receiving the typed payload.
* @returns A function that removes this subscription.
*
* @example
* ```ts
* const unsub = subscribe('WS:STOCK_UPDATE', (data) => {
* console.log(data.price); // fully typed
* });
* // Later:
* unsub();
* ```
*/
export function subscribe<K extends keyof AppEvents>(
type: K,
handler: (event: AppEvents[K]) => void,
): () => void {
eventBus.on(type, handler);
return () => eventBus.off(type, handler);
}
@@ -0,0 +1,50 @@
// ─── Application Event Registry (IoC Pattern) ──────────────────
/**
* Open interface for application event registration.
*
* **This interface is intentionally empty at the core level.**
*
* Each consuming app (`apps/web`, `apps/landing`, etc.) is responsible
* for registering its own events using TypeScript Declaration Merging
* (Module Augmentation). This enforces Inversion of Control:
*
* - The core package provides the **tool** (bus, hooks, helpers).
* - The app provides the **contract** (event names and payloads).
*
* ## How to register events
*
* Create a `.d.ts` file anywhere in your app's `src/` folder:
*
* ```ts
* // apps/web/src/types/events.d.ts
* declare module '@repo/core-events' {
* interface AppEventRegistry {
* 'DOMAIN:EVENT_NAME': { payload: string };
* }
* }
* ```
*
* TypeScript will automatically merge all augmentations into a single
* `AppEventRegistry` interface, giving you full autocomplete and
* compile-time type safety across the entire app without the core
* package knowing anything about your events.
*
* **Naming convention**: `DOMAIN:ACTION` in `SCREAMING_SNAKE_CASE`.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface AppEventRegistry {}
/**
* Resolved event map consumed by `mitt` and all public APIs.
*
* This type alias bridges the open `AppEventRegistry` interface
* (which supports declaration merging) to the `Record<string, unknown>`
* constraint that `mitt` requires.
*
* You should never reference this type directly in consumer code.
* Use `AppEventRegistry` for augmentation and let the core handle the rest.
*/
export type AppEvents = {
[K in keyof AppEventRegistry]: AppEventRegistry[K];
};
+76
View File
@@ -0,0 +1,76 @@
import { useEffect, useRef, useCallback } from 'react';
import type { AppEvents } from './events.registry';
import { eventBus, publish as busPublish } from './event-bus';
// ─── useAppEvent ────────────────────────────────────────────────
/**
* Subscribe to an application event with automatic cleanup on unmount.
*
* The handler is stored in a ref so that:
* 1. The subscription is stable re-renders don't cause unsubscribe/resubscribe churn.
* 2. The handler always sees the latest closure values (no stale closures).
* 3. The parent component's render cycle is never triggered by the subscription itself.
*
* @param type - The event name from `AppEvents`.
* @param handler - Callback receiving the typed payload. May be updated on re-render.
*
* @example
* ```tsx
* useAppEvent('AUTH:PROFILE_UPDATED', (profile) => {
* console.log(profile.name); // fully typed, auto-cleaned on unmount
* });
* ```
*/
export function useAppEvent<K extends keyof AppEvents>(
type: K,
handler: (event: AppEvents[K]) => void,
): void {
// Always keep the latest handler in a ref to avoid stale closures
// and prevent re-subscription on every render.
const handlerRef = useRef(handler);
handlerRef.current = handler;
useEffect(() => {
// Create a stable delegate that forwards to the latest handler ref
const delegate = (event: AppEvents[K]) => {
handlerRef.current(event);
};
eventBus.on(type, delegate);
// Cleanup: unsubscribe when the component unmounts or `type` changes.
// This is the critical memory-leak prevention mechanism.
return () => {
eventBus.off(type, delegate);
};
}, [type]);
}
// ─── usePublishEvent ────────────────────────────────────────────
/**
* Returns a strictly typed `publish` function.
*
* The returned function is referentially stable (memoized) so it
* can be safely passed as a prop or used in dependency arrays
* without causing unnecessary re-renders.
*
* @example
* ```tsx
* const publish = usePublishEvent();
*
* const handleClick = () => {
* publish('DEVICE:PRINT_RECEIPT', {
* receiptId: '001',
* items: [{ name: 'Widget', qty: 2, price: 9.99 }],
* total: 19.98,
* cashierName: 'Firman',
* timestamp: Date.now(),
* });
* };
* ```
*/
export function usePublishEvent(): typeof busPublish {
return useCallback(busPublish, []);
}
+8
View File
@@ -0,0 +1,8 @@
// ─── Event Registry ─────────────────────────────────────────────
export type { AppEventRegistry, AppEvents } from './events.registry';
// ─── Event Bus (Core) ───────────────────────────────────────────
export { eventBus, publish, subscribe } from './event-bus';
// ─── React Hooks ────────────────────────────────────────────────
export { useAppEvent, usePublishEvent } from './hooks';
+9
View File
@@ -0,0 +1,9 @@
{
"extends": "@repo/typescript-config/react-library.json",
"include": ["src"],
"compilerOptions": {
"strict": true,
"declaration": true,
"declarationMap": true
}
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
globals: true,
},
});
+102 -9
View File
@@ -1,29 +1,93 @@
# Enterprise i18n Architecture (`@repo/core-i18n`) # Enterprise i18n Architecture (`@repo/core-i18n`)
A highly decoupled, type-safe internationalization engine for the Eigen Monorepo. [← Back to Root](../../README.md)
A highly decoupled, type-safe internationalization engine for the monorepo.
It uses a **Hybrid Namespace Strategy**: It uses a **Hybrid Namespace Strategy**:
1. **Centralized Engine**: Setup, local persistence (`@repo/core-storage`), and global words (`common`). 1. **Centralized Engine**: Setup, local persistence orchestration, and global words (`common`).
2. **Decentralized Dictionaries**: Feature-specific translations (`booking`, `billing`) live inside the application modules and are lazy-loaded. 2. **Decentralized Dictionaries**: Feature-specific translations (`booking`, `billing`) live inside the application modules and are lazy-loaded.
This architecture strictly adheres to **Inversion of Control (IoC)**. The core engine handles local state and performance, but leaves API and networking decisions entirely to the consuming applications. This architecture strictly adheres to **Inversion of Control (IoC)**. The core engine handles local state and performance, but leaves API, networking, and storage implementation decisions entirely to the consuming applications.
---
## Overview Architecture
```mermaid
graph TD
subgraph Apps ["apps/* (App Autonomy)"]
UI[React Components]
DICT[Feature Dictionaries<br/>e.g., booking.json]
end
subgraph Core ["@repo/core-i18n (Engine)"]
I18N((i18next Instance))
STORE[(core-storage)]
COMMON[Common Vocabulary]
end
subgraph Backend ["Backend API (External)"]
SYNC[Language Sync Endpoint]
TENANT[Tenant Config Endpoint]
end
UI -->|uses useTranslation| I18N
DICT -.->|lazy loads| I18N
COMMON -->|preloads| I18N
I18N <-->|reads/persists| STORE
I18N -->|changeLanguage sync| SYNC
SYNC -.->|fails? rollback| I18N
TENANT -.->|applyTenantOverrides| I18N
%% Styling Subgraphs (Backgrounds)
style Apps fill:#e7f5ff,stroke:#74c0fc,stroke-width:2px,color:#1864ab
style Core fill:#f8f9fa,stroke:#ced4da,stroke-width:2px,color:#495057
style Backend fill:#fff4e6,stroke:#ffd8a8,stroke-width:2px,color:#d9480f
%% Styling App Nodes (Blue)
style UI fill:#339af0,stroke:#1864ab,color:#fff
style DICT fill:#339af0,stroke:#1864ab,color:#fff
%% Styling Core Nodes (Purple Engine, Green Storage/Data)
style I18N fill:#845ef7,stroke:#5f3dc4,color:#fff
style STORE fill:#20c997,stroke:#089981,color:#fff
style COMMON fill:#20c997,stroke:#089981,color:#fff
%% Styling Backend Nodes (Orange/Network)
style SYNC fill:#fd7e14,stroke:#d9480f,color:#fff
style TENANT fill:#fd7e14,stroke:#d9480f,color:#fff
```
--- ---
## 1. App-Level Setup (Bootstrap) ## 1. App-Level Setup (Bootstrap)
Initialize the engine *before* your React application mounts to prevent UI flashing. Initialize the engine *before* your React application mounts to prevent UI flashing. Provide an `I18nStorageAdapter` using Dependency Injection so the core engine can persist the user's language without being tightly coupled to a specific storage implementation.
```tsx ```tsx
// apps/web/src/main.tsx // apps/web/src/main.tsx
import { StrictMode } from 'react'; import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { setupI18n } from '@repo/core-i18n'; import { setupI18n } from '@repo/core-i18n';
import { secureStorage, AppStorageKey } from './core/storage';
import App from './app'; import App from './app';
async function bootstrap() { async function bootstrap() {
// Synchronously reads preferred language from storage & inits i18next // Synchronously reads preferred language from injected storage & inits i18next
await setupI18n(); await setupI18n({
storageAdapter: {
getLanguage: async () => {
const stored = await secureStorage.getItem(AppStorageKey.LOCALE);
return typeof stored === 'string' ? stored : null;
},
setLanguage: async (lng: string) => {
await secureStorage.setItem(AppStorageKey.LOCALE, lng);
},
},
});
createRoot(document.getElementById('app')!).render( createRoot(document.getElementById('app')!).render(
<StrictMode><App /></StrictMode>, <StrictMode><App /></StrictMode>,
@@ -84,9 +148,38 @@ export default function BookingFeature() {
} }
``` ```
**3. Dynamic Variables (Interpolation):**
```json
// booking.json
{
"messages": {
"welcome": "Welcome back, {{name}}! You have {{count}} new bookings."
}
}
```
```tsx
// Inside component
<h1>{t('booking:messages.welcome', { name: 'Firman', count: 5 })}</h1>
```
--- ---
## 3. Real-World Implementation Flow ## 3. Usage Outside React Components (Vanilla TS)
For utility files, API interceptors, or vanilla functions where React hooks cannot be used, import the raw `i18n` instance directly.
```ts
import { i18n } from '@repo/core-i18n';
// Must specify the namespace explicitly if it's not 'common'
export const getErrorMessage = (code: string) => {
return i18n.t(`booking:errors.${code}`, { defaultValue: 'Unknown Error' });
};
```
---
## 4. Real-World Implementation Flow
The engine supports robust flows for authenticated apps, including Tenant Vocabulary Overrides and Backend Synchronization. The engine supports robust flows for authenticated apps, including Tenant Vocabulary Overrides and Backend Synchronization.
@@ -151,7 +244,7 @@ const handleSwitch = async (newLng: string) => {
--- ---
## 4. Backend API Contract (For Backend Engineers) ## 5. Backend API Contract (For Backend Engineers)
To support Dynamic Tenant Overrides, the backend must expose an endpoint (e.g., `GET /v1/tenant/i18n-config`). To support Dynamic Tenant Overrides, the backend must expose an endpoint (e.g., `GET /v1/tenant/i18n-config`).
@@ -180,4 +273,4 @@ If the frontend dictionary has `header.title` and `header.subtitle`, and the bac
} }
} }
} }
``` ```
-1
View File
@@ -12,7 +12,6 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@repo/core-storage": "workspace:*",
"@repo/utils": "workspace:*", "@repo/utils": "workspace:*",
"i18next": "^24.2.2", "i18next": "^24.2.2",
"react-i18next": "^15.4.0" "react-i18next": "^15.4.0"
+7 -3
View File
@@ -1,5 +1,5 @@
import i18n from 'i18next'; import i18n from 'i18next';
import { secureStorage, StorageKey } from '@repo/core-storage'; import { globalStorageAdapter } from './setup';
/** /**
* Changes the active language, saves the preference locally, and optionally syncs with the backend. * Changes the active language, saves the preference locally, and optionally syncs with the backend.
@@ -16,7 +16,9 @@ export async function changeLanguage(
if (prevLng === newLng) return; if (prevLng === newLng) return;
// 1. Update local storage & i18next optimistically // 1. Update local storage & i18next optimistically
await secureStorage.setItem(StorageKey.LOCALE, newLng); if (globalStorageAdapter) {
await globalStorageAdapter.setLanguage(newLng);
}
await i18n.changeLanguage(newLng); await i18n.changeLanguage(newLng);
// 2. Trigger optional backend sync // 2. Trigger optional backend sync
@@ -26,7 +28,9 @@ export async function changeLanguage(
} catch (error) { } catch (error) {
console.error('[i18n] Backend sync failed, rolling back language', error); console.error('[i18n] Backend sync failed, rolling back language', error);
// Rollback on failure // Rollback on failure
await secureStorage.setItem(StorageKey.LOCALE, prevLng); if (globalStorageAdapter) {
await globalStorageAdapter.setLanguage(prevLng);
}
await i18n.changeLanguage(prevLng); await i18n.changeLanguage(prevLng);
throw error; // Rethrow so the caller can show an error toast throw error; // Rethrow so the caller can show an error toast
} }
+21 -7
View File
@@ -1,6 +1,5 @@
import i18n from 'i18next'; import i18n from 'i18next';
import { initReactI18next } from 'react-i18next'; import { initReactI18next } from 'react-i18next';
import { secureStorage, StorageKey } from '@repo/core-storage';
import commonEn from './locales/en/common.json'; import commonEn from './locales/en/common.json';
import commonId from './locales/id/common.json'; import commonId from './locales/id/common.json';
@@ -14,18 +13,33 @@ export const resources = {
id: { common: commonId.common }, id: { common: commonId.common },
} as const; } as const;
export interface I18nStorageAdapter {
getLanguage(): Promise<string | null>;
setLanguage(lng: string): Promise<void>;
}
export interface I18nConfig {
storageAdapter?: I18nStorageAdapter;
}
// Store the adapter module-wide so manager.ts can access it
export let globalStorageAdapter: I18nStorageAdapter | undefined;
/** /**
* Bootstraps the central i18n engine. * Bootstraps the central i18n engine.
* *
* This reads the preferred locale from secureStorage and initializes * It accepts an optional storage adapter to read the initial language.
* i18next synchronously before React renders.
*/ */
export async function setupI18n(): Promise<void> { export async function setupI18n(config: I18nConfig = {}): Promise<void> {
globalStorageAdapter = config.storageAdapter;
let initialLng = DEFAULT_LANGUAGE; let initialLng = DEFAULT_LANGUAGE;
try { try {
const storedLng = await secureStorage.getItem<string>(StorageKey.LOCALE); if (globalStorageAdapter) {
if (storedLng && SUPPORTED_LANGUAGES.includes(storedLng as SupportedLanguage)) { const storedLng = await globalStorageAdapter.getLanguage();
initialLng = storedLng; if (storedLng && SUPPORTED_LANGUAGES.includes(storedLng as SupportedLanguage)) {
initialLng = storedLng;
}
} }
} catch (err) { } catch (err) {
console.warn('[i18n] Failed to read locale from storage', err); console.warn('[i18n] Failed to read locale from storage', err);
+130 -76
View File
@@ -1,114 +1,168 @@
# @repo/core-storage # Enterprise Storage Engine (`@repo/core-storage`)
[← Back to Root](../../README.md)
The **Enterprise-grade storage engine** for the monorepo. The **Enterprise-grade storage engine** for the monorepo.
This package provides a unified, Promise-based interface for interacting with browser storage (`localStorage` and `IndexedDB`). It enforces strict type safety, prevents key collisions, and automatically provides **AES encryption at rest** for sensitive payloads (like access tokens) using `@repo/utils`. This package provides a unified, Factory-based interface for interacting with browser storage (`localStorage` and `IndexedDB`). It enforces strict type safety, **Runtime Validation**, App Autonomy (Inversion of Control), and automatically provides **AES encryption at rest** for sensitive payloads (like access tokens) using `@repo/utils`.
--- ---
## 🎯 Primary Goals & Separation of Concerns ## Architecture & Data Flow
* **Separation from `@repo/core-api`**: Storage is a fundamental primitive. While the API client uses storage (to retrieve tokens), storage itself does not need to know about HTTP requests. ```mermaid
graph TD
subgraph Apps ["apps/* (App Autonomy)"]
REG[[AppStorageKey & App Registries]]
UI[React Components / API Interceptors]
INST{{Storage Instances}}
end
subgraph Core ["@repo/core-storage (Engine Factories)"]
API[IStorageService API]
FAC[createLocalStorage / createIndexedDB]
VAL{Runtime Gatekeeper}
ENC{{AES Encryption Pipeline}}
LOCAL[LocalStorage Adapter]
IDB[IndexedDB Adapter]
end
subgraph Browser ["Browser APIs (Native)"]
B_LOCAL[(localStorage)]
B_IDB[(IndexedDB)]
end
REG -.->|Injects Keys & Config| FAC
FAC --> INST
UI -->|getItem / setItem| INST
INST --> API
API --> VAL
VAL -.->|Valid Key?| ENC
VAL -.->|Invalid Key!| ERR[Throws Security Exception]
ENC -.->|Sensitive Key| LOCAL & IDB
VAL -.->|Plain-text Key| LOCAL & IDB
LOCAL <--> B_LOCAL
IDB <--> B_IDB
%% Styling Subgraphs
style Apps fill:#e7f5ff,stroke:#74c0fc,stroke-width:2px,color:#1864ab
style Core fill:#f8f9fa,stroke:#ced4da,stroke-width:2px,color:#495057
style Browser fill:#f1f3f5,stroke:#ced4da,stroke-width:2px,color:#495057
%% Styling Nodes
style UI fill:#339af0,stroke:#1864ab,color:#fff
style REG fill:#1864ab,stroke:#1864ab,color:#fff
style INST fill:#339af0,stroke:#1864ab,color:#fff
style API fill:#845ef7,stroke:#5f3dc4,color:#fff
style FAC fill:#845ef7,stroke:#5f3dc4,color:#fff
%% Gatekeeper is GREEN (Security Checkpoint), Error is RED
style VAL fill:#20c997,stroke:#089981,color:#fff
style ERR fill:#fa5252,stroke:#c92a2a,color:#fff
style LOCAL fill:#845ef7,stroke:#5f3dc4,color:#fff
style IDB fill:#845ef7,stroke:#5f3dc4,color:#fff
style ENC fill:#fab005,stroke:#e67700,color:#fff
style B_LOCAL fill:#868e96,stroke:#495057,color:#fff
style B_IDB fill:#868e96,stroke:#495057,color:#fff
```
---
## 🎯 Primary Goals & Architectural Principles
* **App Autonomy (Inversion of Control)**: The core storage engine does not know about your application's keys. Consuming applications define their own keys, their own `encryptedKeys` sets, and their own `plainTextKeys` sets, injecting them into the factory upon instantiation.
* **Runtime Gatekeeper (Defensive Programming)**: The engine validates every `setItem`, `getItem`, and `removeItem` operation. If an app attempts to access a key that wasn't explicitly registered in `encryptedKeys` or `plainTextKeys`, the engine will immediately throw a Security Exception to prevent rogue data access/injection.
* **Dual Backend Strategy**: * **Dual Backend Strategy**:
* `secureStorage` (localStorage): Ideal for small, synchronous-like data (tokens, user preferences). * `createLocalStorage`: Ideal for small, synchronous-like data (tokens, user preferences, settings).
* `IndexedDBService`: Built for large, asynchronous data (offline drafts, cached API responses, blobs) without the 5MB size limit. * `createIndexedDB`: Built for large, asynchronous data (offline drafts, cached API responses, large arrays/blobs) bypassing the 5MB localStorage limit.
* **Security by Default**: Developers don't need to manually encrypt/decrypt data. If a key is marked as sensitive, the library handles AES encryption transparently. * **Security by Default**: Developers don't need to manually encrypt/decrypt data. If a key is passed in the `encryptedKeys` configuration, the engine handles AES encryption transparently.
* **Corrupt Data Resilience**: If parsing or decryption fails (e.g., tampered data or changed encryption keys), the corrupt entry is safely removed and returns `null`, preventing the app from crashing.
--- ---
## ✨ Key Features ## 🚀 App-Level Setup & Usage
| Feature | Description | ### 1. Define App Keys and Instantiate (Inversion of Control)
|---|---|
| 🔒 **Selective Encryption** | Uses `@repo/utils` `EncryptionUtils` to automatically AES-encrypt payloads whose keys are listed in `ENCRYPTED_KEYS`. |
| 🛡️ **Type-Safe Keys** | All keys must be registered in `storage.key.ts`. Prevents typos and key collisions across the monorepo. |
| 🔄 **Unified Promise API** | Both `localStorage` and `IndexedDB` implement the same async `IStorageService` interface. |
| 🧬 **Strict Generics** | Read and write operations enforce payload types via generics (e.g., `getItem<UserProfile>('user_profile')`). |
| 🩹 **Corrupt Data Resilience** | If parsing or decryption fails (e.g., tampered data), the corrupt entry is safely removed and returns `null`. |
--- In your consuming application (e.g., `apps/web/src/core/storage/index.ts`), define your keys and use the factories to create your instances.
## 🚀 Usage Examples
### 1. Secure Local Storage (Tokens, Profile)
Use `secureStorage` (or your app's configured instance) for small payloads. If the key is in `ENCRYPTED_KEYS`, it will be encrypted at rest.
```typescript ```typescript
import { secureStorage, StorageKey } from '@repo/core-storage'; // apps/web/src/core/storage/index.ts
import { createLocalStorage, createIndexedDB } from '@repo/core-storage';
// 1. Define Keys
export const AppStorageKey = {
USER_PROFILE: 'user_profile',
ACCESS_TOKEN: 'access_token',
LOCALE: 'app_locale',
} as const;
export type AppStorageKeyValue = (typeof AppStorageKey)[keyof typeof AppStorageKey];
// 2. Classify Keys
export const ENCRYPTED_KEYS = new Set<AppStorageKeyValue>([
AppStorageKey.USER_PROFILE,
AppStorageKey.ACCESS_TOKEN,
]);
export const PLAIN_KEYS = new Set<AppStorageKeyValue>([
AppStorageKey.LOCALE,
]);
// 3. Instantiate Factories
export const secureStorage = createLocalStorage<AppStorageKeyValue>({
encryptedKeys: ENCRYPTED_KEYS,
plainTextKeys: PLAIN_KEYS
});
export const secureIndexedDB = createIndexedDB<AppStorageKeyValue>({
dbName: 'eigen_erp_db',
storeName: 'web_store',
encryptedKeys: ENCRYPTED_KEYS,
plainTextKeys: PLAIN_KEYS
});
```
### 2. Usage in App Components
Now, you can import your locally-created instances anywhere in your app.
```typescript
import { secureStorage, AppStorageKey } from '@/core/storage';
import type { UserProfile } from '@/types'; import type { UserProfile } from '@/types';
// CREATE / UPDATE // CREATE / UPDATE
// If StorageKey.USER_PROFILE is in ENCRYPTED_KEYS, this is AES-encrypted automatically. // Since USER_PROFILE is in ENCRYPTED_KEYS, it is AES-encrypted automatically.
await secureStorage.setItem(StorageKey.USER_PROFILE, { await secureStorage.setItem(AppStorageKey.USER_PROFILE, {
id: 1, id: 1,
name: 'Firman', name: 'Firman',
role: 'admin' role: 'admin'
}); });
// READ // READ (Returns null if not found or if decryption fails)
const profile = await secureStorage.getItem<UserProfile>(StorageKey.USER_PROFILE); const profile = await secureStorage.getItem<UserProfile>(AppStorageKey.USER_PROFILE);
if (profile) { if (profile) {
console.log('Welcome back,', profile.name); console.log('Welcome back,', profile.name);
} }
// DELETE // DELETE
await secureStorage.removeItem(StorageKey.USER_PROFILE); await secureStorage.removeItem(AppStorageKey.USER_PROFILE);
``` ```
### 2. IndexedDB (Offline Data, Large Payloads) ### 3. The Runtime Gatekeeper
Use the pre-configured `secureIndexedDB` (or instantiate your own) for large, asynchronous data. It uses the exact same API and encryption pipeline. If you try to access an unregistered key, the engine protects the app by throwing an error at runtime:
```typescript ```typescript
import { secureIndexedDB } from '@repo/core-storage'; // Throws Error: "[Storage Engine] Security Exception: Key 'rogue_key' is not registered..."
await secureStorage.setItem('rogue_key' as any, 'hacked');
interface DraftData {
id: string;
content: string;
lastModified: number;
}
// Save a large draft offline
await secureIndexedDB.setItem('offline_draft_123', {
id: '123',
content: 'Huge text content...',
lastModified: Date.now()
});
// Retrieve the draft
const draft = await secureIndexedDB.getItem<DraftData>('offline_draft_123');
``` ```
--- ---
## 🔑 Adding New Keys
To maintain type safety and avoid collisions, **all** `localStorage` keys must be registered in `packages/core-storage/src/storage.key.ts`.
### 1. Register the Key
Add your key to the `StorageKey` object:
```typescript
export const StorageKey = {
// ... existing keys
MY_NEW_FEATURE: 'my_new_feature_key',
} as const;
```
### 2. Define Encryption (If Needed)
If the data stored under this key is sensitive (e.g., PII, tokens, financials), add it to the `ENCRYPTED_KEYS` set.
```typescript
export const ENCRYPTED_KEYS: ReadonlySet<string> = new Set<string>([
StorageKey.ACCESS_TOKEN,
StorageKey.REFRESH_TOKEN,
StorageKey.USER_PROFILE,
StorageKey.MY_NEW_FEATURE, // <--- Now encrypted at rest!
]);
```
> [!WARNING] > [!WARNING]
> If you add an existing plain-text key to `ENCRYPTED_KEYS`, existing users will experience a parsing failure on their next session (because the library expects encrypted data but finds plain text). The resilient parser will catch this and clear the key, effectively logging them out or resetting the preference. > **Migration Hazard**: If you move an existing key from `plainTextKeys` to `encryptedKeys` (or vice versa), existing users will experience a parsing failure on their next session (because the library expects encrypted data but finds plain text). The resilient parser will catch this and gracefully clear the key, which may effectively log them out or reset their local preference.
+4 -44
View File
@@ -1,48 +1,8 @@
// ─── Interfaces ───────────────────────────────────────────────── // ─── Interfaces ─────────────────────────────────────────────────
export type { IStorageService } from './storage.interface'; export type { IStorageService } from './storage.interface';
export type { StorageOptions } from './local-storage.service';
// ─── Key Registry ─────────────────────────────────────────────── export type { IndexedDBConfig } from './indexed-db.service';
export { StorageKey, ENCRYPTED_KEYS } from './storage.key';
export type { StorageKeyValue } from './storage.key';
// ─── Service Classes ──────────────────────────────────────────── // ─── Service Classes ────────────────────────────────────────────
export { LocalStorageService } from './local-storage.service'; export { LocalStorageService, createLocalStorage } from './local-storage.service';
export { IndexedDBService } from './indexed-db.service'; export { IndexedDBService, createIndexedDB } from './indexed-db.service';
// ─── Pre-configured Instances ───────────────────────────────────
import { LocalStorageService } from './local-storage.service';
import { IndexedDBService } from './indexed-db.service';
/**
* Default secure localStorage instance.
*
* Keys listed in `ENCRYPTED_KEYS` are automatically encrypted via
* `@repo/utils` `EncryptionUtils`. All other keys are plain JSON.
*
* @example
* ```ts
* import { secureStorage, StorageKey } from '@repo/core-storage';
*
* await secureStorage.setItem(StorageKey.ACCESS_TOKEN, 'eyJhbGci...');
* const token = await secureStorage.getItem<string>(StorageKey.ACCESS_TOKEN);
* ```
*/
export const secureStorage = new LocalStorageService();
/**
* Default IndexedDB instance.
*
* Uses `app_db` database with a `kv_store` object store.
* Sensitive keys are encrypted at rest using the same
* `EncryptionUtils` pipeline as `secureStorage`.
*
* @example
* ```ts
* import { secureIndexedDB } from '@repo/core-storage';
*
* await secureIndexedDB.setItem('offline_draft', { content: '...' });
* const draft = await secureIndexedDB.getItem<Draft>('offline_draft');
* ```
*/
export const secureIndexedDB = new IndexedDBService({ dbName: 'app_db', storeName: 'kv_store' });
+35 -30
View File
@@ -1,10 +1,10 @@
import { EncryptionUtils } from '@repo/utils'; import { EncryptionUtils } from '@repo/utils';
import type { IStorageService } from './storage.interface'; import type { IStorageService } from './storage.interface';
import { ENCRYPTED_KEYS } from './storage.key'; import type { StorageOptions } from './local-storage.service';
// ─── Types ────────────────────────────────────────────────────── // ─── Types ──────────────────────────────────────────────────────
interface IndexedDBConfig { export interface IndexedDBConfig<TKey extends string> extends StorageOptions<TKey> {
/** Database name. @default 'app_db' */ /** Database name. @default 'app_db' */
dbName?: string; dbName?: string;
/** Object store name. @default 'kv_store' */ /** Object store name. @default 'kv_store' */
@@ -63,34 +63,23 @@ function withTransaction<R>(
/** /**
* Enterprise-grade IndexedDB wrapper with optional AES encryption. * Enterprise-grade IndexedDB wrapper with optional AES encryption.
*
* Uses a simple key-value object store pattern. Keys listed in
* `ENCRYPTED_KEYS` are automatically encrypted/decrypted using
* `@repo/utils` `EncryptionUtils`.
*
* Unlike localStorage, IndexedDB has no 5MB size limit making
* it suitable for large payloads like cached API responses, offline
* data, or file blobs.
*
* @example
* ```ts
* const idb = new IndexedDBService({ dbName: 'my_app' });
* await idb.setItem('large_dataset', hugePayload);
* const data = await idb.getItem<HugePayload>('large_dataset');
* ```
*/ */
export class IndexedDBService implements IStorageService { export class IndexedDBService<TKey extends string> implements IStorageService<TKey> {
private readonly encryption: EncryptionUtils; private readonly encryption: EncryptionUtils;
private readonly dbName: string; private readonly dbName: string;
private readonly storeName: string; private readonly storeName: string;
private readonly version: number; private readonly version: number;
private readonly encryptedKeys: Set<TKey>;
private readonly plainTextKeys: Set<TKey>;
private dbPromise: Promise<IDBDatabase> | null = null; private dbPromise: Promise<IDBDatabase> | null = null;
constructor(config?: IndexedDBConfig, encryptionUtils?: EncryptionUtils) { constructor(config?: IndexedDBConfig<TKey>, encryptionUtils?: EncryptionUtils) {
this.encryption = encryptionUtils ?? EncryptionUtils.getInstance(); this.encryption = encryptionUtils ?? EncryptionUtils.getInstance();
this.dbName = config?.dbName ?? 'app_db'; this.dbName = config?.dbName ?? 'app_db';
this.storeName = config?.storeName ?? 'kv_store'; this.storeName = config?.storeName ?? 'kv_store';
this.version = config?.version ?? 1; this.version = config?.version ?? 1;
this.encryptedKeys = config?.encryptedKeys ?? new Set();
this.plainTextKeys = config?.plainTextKeys ?? new Set();
} }
/** Lazy-open the database connection (cached). */ /** Lazy-open the database connection (cached). */
@@ -101,11 +90,18 @@ export class IndexedDBService implements IStorageService {
return this.dbPromise; return this.dbPromise;
} }
private shouldEncrypt(key: string): boolean { private validateKey(key: TKey): void {
return ENCRYPTED_KEYS.has(key); if (!this.encryptedKeys.has(key) && !this.plainTextKeys.has(key)) {
throw new Error(`[Storage Engine] Security Exception: Key '${key}' is not registered and cannot be accessed.`);
}
} }
async setItem<T>(key: string, value: T): Promise<void> { private shouldEncrypt(key: TKey): boolean {
return this.encryptedKeys.has(key);
}
async setItem<T>(key: TKey, value: T): Promise<void> {
this.validateKey(key);
const db = await this.getDB(); const db = await this.getDB();
const serialized = JSON.stringify(value); const serialized = JSON.stringify(value);
const payload = this.shouldEncrypt(key) const payload = this.shouldEncrypt(key)
@@ -113,18 +109,19 @@ export class IndexedDBService implements IStorageService {
: serialized; : serialized;
await withTransaction(db, this.storeName, 'readwrite', (store) => await withTransaction(db, this.storeName, 'readwrite', (store) =>
store.put(payload, key), store.put(payload, key as string),
); );
} }
async getItem<T>(key: string): Promise<T | null> { async getItem<T>(key: TKey): Promise<T | null> {
this.validateKey(key);
const db = await this.getDB(); const db = await this.getDB();
const raw = await withTransaction<string | undefined>( const raw = await withTransaction<string | undefined>(
db, db,
this.storeName, this.storeName,
'readonly', 'readonly',
(store) => store.get(key) as IDBRequest<string | undefined>, (store) => store.get(key as string) as IDBRequest<string | undefined>,
); );
if (raw === undefined || raw === null) return null; if (raw === undefined || raw === null) return null;
@@ -143,10 +140,11 @@ export class IndexedDBService implements IStorageService {
} }
} }
async removeItem(key: string): Promise<void> { async removeItem(key: TKey): Promise<void> {
this.validateKey(key);
const db = await this.getDB(); const db = await this.getDB();
await withTransaction(db, this.storeName, 'readwrite', (store) => await withTransaction(db, this.storeName, 'readwrite', (store) =>
store.delete(key), store.delete(key as string),
); );
} }
@@ -157,18 +155,25 @@ export class IndexedDBService implements IStorageService {
); );
} }
async hasItem(key: string): Promise<boolean> { async hasItem(key: TKey): Promise<boolean> {
const value = await this.getItem(key); const value = await this.getItem(key);
return value !== null; return value !== null;
} }
async keys(): Promise<string[]> { async keys(): Promise<TKey[]> {
const db = await this.getDB(); const db = await this.getDB();
return withTransaction<string[]>( const allKeys = await withTransaction<string[]>(
db, db,
this.storeName, this.storeName,
'readonly', 'readonly',
(store) => store.getAllKeys() as IDBRequest<string[]>, (store) => store.getAllKeys() as IDBRequest<string[]>,
); );
return allKeys as TKey[];
} }
} }
export function createIndexedDB<TKey extends string>(
config: IndexedDBConfig<TKey>
): IStorageService<TKey> {
return new IndexedDBService<TKey>(config);
}
@@ -1,54 +1,50 @@
import { EncryptionUtils } from '@repo/utils'; import { EncryptionUtils } from '@repo/utils';
import type { IStorageService } from './storage.interface'; import type { IStorageService } from './storage.interface';
import { ENCRYPTED_KEYS } from './storage.key';
export interface StorageOptions<TKey extends string> {
encryptedKeys?: Set<TKey>;
plainTextKeys?: Set<TKey>;
}
/** /**
* Enterprise-grade localStorage wrapper with optional AES encryption. * Enterprise-grade localStorage wrapper with optional AES encryption.
*
* Keys listed in `ENCRYPTED_KEYS` are automatically encrypted before
* writing and decrypted on read using `@repo/utils` `EncryptionUtils`.
* All other keys are stored as plain JSON.
*
* All methods are async (returning Promises) to conform to the
* `IStorageService` interface, ensuring consumers can swap between
* localStorage and IndexedDB without code changes.
*
* @example
* ```ts
* const storage = new LocalStorageService();
*
* // Encrypted at rest (ACCESS_TOKEN is in ENCRYPTED_KEYS)
* await storage.setItem(StorageKey.ACCESS_TOKEN, 'eyJhbGci...');
*
* // Plain JSON (THEME is NOT in ENCRYPTED_KEYS)
* await storage.setItem(StorageKey.THEME, 'dark');
* ```
*/ */
export class LocalStorageService implements IStorageService { export class LocalStorageService<TKey extends string> implements IStorageService<TKey> {
private readonly encryption: EncryptionUtils; private readonly encryption: EncryptionUtils;
private readonly encryptedKeys: Set<TKey>;
private readonly plainTextKeys: Set<TKey>;
constructor(encryptionUtils?: EncryptionUtils) { constructor(options?: StorageOptions<TKey>, encryptionUtils?: EncryptionUtils) {
this.encryption = encryptionUtils ?? EncryptionUtils.getInstance(); this.encryption = encryptionUtils ?? EncryptionUtils.getInstance();
this.encryptedKeys = options?.encryptedKeys ?? new Set();
this.plainTextKeys = options?.plainTextKeys ?? new Set();
} }
/** Check if a key should be encrypted. */ private validateKey(key: TKey): void {
private shouldEncrypt(key: string): boolean { if (!this.encryptedKeys.has(key) && !this.plainTextKeys.has(key)) {
return ENCRYPTED_KEYS.has(key); throw new Error(`[Storage Engine] Security Exception: Key '${key}' is not registered and cannot be accessed.`);
}
} }
async setItem<T>(key: string, value: T): Promise<void> { private shouldEncrypt(key: TKey): boolean {
return this.encryptedKeys.has(key);
}
async setItem<T>(key: TKey, value: T): Promise<void> {
this.validateKey(key);
const serialized = JSON.stringify(value); const serialized = JSON.stringify(value);
if (this.shouldEncrypt(key)) { if (this.shouldEncrypt(key)) {
const encrypted = this.encryption.encrypt(serialized); const encrypted = this.encryption.encrypt(serialized);
localStorage.setItem(key, encrypted); localStorage.setItem(key as string, encrypted);
} else { } else {
localStorage.setItem(key, serialized); localStorage.setItem(key as string, serialized);
} }
} }
async getItem<T>(key: string): Promise<T | null> { async getItem<T>(key: TKey): Promise<T | null> {
const raw = localStorage.getItem(key); this.validateKey(key);
const raw = localStorage.getItem(key as string);
if (raw === null) return null; if (raw === null) return null;
try { try {
@@ -60,29 +56,36 @@ export class LocalStorageService implements IStorageService {
return JSON.parse(raw) as T; return JSON.parse(raw) as T;
} catch { } catch {
console.warn(`[core-storage] Failed to parse key "${key}". Removing corrupt entry.`); console.warn(`[core-storage] Failed to parse key "${key}". Removing corrupt entry.`);
localStorage.removeItem(key); localStorage.removeItem(key as string);
return null; return null;
} }
} }
async removeItem(key: string): Promise<void> { async removeItem(key: TKey): Promise<void> {
localStorage.removeItem(key); this.validateKey(key);
localStorage.removeItem(key as string);
} }
async clear(): Promise<void> { async clear(): Promise<void> {
localStorage.clear(); localStorage.clear();
} }
async hasItem(key: string): Promise<boolean> { async hasItem(key: TKey): Promise<boolean> {
return localStorage.getItem(key) !== null; return localStorage.getItem(key as string) !== null;
} }
async keys(): Promise<string[]> { async keys(): Promise<TKey[]> {
const result: string[] = []; const result: TKey[] = [];
for (let i = 0; i < localStorage.length; i++) { for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i); const key = localStorage.key(i);
if (key !== null) result.push(key); if (key !== null) result.push(key as TKey);
} }
return result; return result;
} }
} }
export function createLocalStorage<TKey extends string>(
options?: StorageOptions<TKey>
): IStorageService<TKey> {
return new LocalStorageService<TKey>(options);
}
@@ -10,29 +10,29 @@
* const user = await storage.getItem<UserProfile>(StorageKey.USER_PROFILE); * const user = await storage.getItem<UserProfile>(StorageKey.USER_PROFILE);
* ``` * ```
*/ */
export interface IStorageService { export interface IStorageService<TKey extends string = string> {
/** /**
* Persist a value under the given key. * Persist a value under the given key.
* The value is JSON-serialized before storage. * The value is JSON-serialized before storage.
* If encryption is enabled, the serialized payload is encrypted at rest. * If encryption is enabled, the serialized payload is encrypted at rest.
*/ */
setItem<T>(key: string, value: T): Promise<void>; setItem<T>(key: TKey, value: T): Promise<void>;
/** /**
* Retrieve and deserialize a value by key. * Retrieve and deserialize a value by key.
* Returns `null` if the key does not exist or decryption/parsing fails. * Returns `null` if the key does not exist or decryption/parsing fails.
*/ */
getItem<T>(key: string): Promise<T | null>; getItem<T>(key: TKey): Promise<T | null>;
/** Remove a single key from storage. */ /** Remove a single key from storage. */
removeItem(key: string): Promise<void>; removeItem(key: TKey): Promise<void>;
/** Remove all keys managed by this storage instance. */ /** Remove all keys managed by this storage instance. */
clear(): Promise<void>; clear(): Promise<void>;
/** Check if a key exists in storage. */ /** Check if a key exists in storage. */
hasItem(key: string): Promise<boolean>; hasItem(key: TKey): Promise<boolean>;
/** Get all keys currently in storage. */ /** Get all keys currently in storage. */
keys(): Promise<string[]>; keys(): Promise<TKey[]>;
} }
-53
View File
@@ -1,53 +0,0 @@
/**
* Centralized storage key registry.
*
* ALL keys used across the application MUST be registered here
* as string literal constants. This prevents key collisions,
* enables grep-ability, and provides a single source of truth
* for what data is persisted in the browser.
*
* Convention: `SCREAMING_SNAKE_CASE` for the constant,
* `kebab-case` or `snake_case` for the actual string value.
*
* @example
* ```ts
* await secureStorage.setItem(StorageKey.ACCESS_TOKEN, token);
* ```
*/
export const StorageKey = {
// ── Auth ─────────────────────────────────────────────────────
ACCESS_TOKEN: 'access_token',
REFRESH_TOKEN: 'refresh_token',
USER_PROFILE: 'user_profile',
USER_PERMISSIONS: 'user_permissions',
// ── App Preferences ──────────────────────────────────────────
THEME: 'app_theme',
LOCALE: 'app_locale',
SIDEBAR_COLLAPSED: 'sidebar_collapsed',
// ── Session ──────────────────────────────────────────────────
FARO_SESSION: 'faroSession',
LAST_ACTIVE_ROUTE: 'last_active_route',
// ── Feature Flags / Cache ────────────────────────────────────
FEATURE_FLAGS: 'feature_flags',
CACHE_VERSION: 'cache_version',
} as const;
/** Union type of all registered storage key values. */
export type StorageKeyValue = (typeof StorageKey)[keyof typeof StorageKey];
/**
* Keys that require encryption at rest.
*
* Any key listed here will be automatically encrypted before
* writing to storage and decrypted on read. All other keys
* are stored as plain JSON.
*/
export const ENCRYPTED_KEYS: ReadonlySet<string> = new Set<string>([
StorageKey.ACCESS_TOKEN,
StorageKey.REFRESH_TOKEN,
StorageKey.USER_PROFILE,
StorageKey.USER_PERMISSIONS,
]);
+72 -39
View File
@@ -1,6 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'; import { describe, it, expect, vi, beforeEach } from 'vitest';
import { LocalStorageService } from './local-storage.service'; import { LocalStorageService } from './local-storage.service';
import { StorageKey, ENCRYPTED_KEYS } from './storage.key';
// ─── Mock @repo/utils EncryptionUtils ─────────────────────────── // ─── Mock @repo/utils EncryptionUtils ───────────────────────────
@@ -37,6 +36,27 @@ Object.defineProperty(globalThis, 'localStorage', {
// ─── Test Data ────────────────────────────────────────────────── // ─── Test Data ──────────────────────────────────────────────────
const TestStorageKey = {
THEME: 'theme',
LOCALE: 'locale',
ACCESS_TOKEN: 'access_token',
REFRESH_TOKEN: 'refresh_token',
USER_PROFILE: 'user_profile',
} as const;
type TestStorageKeyValue = (typeof TestStorageKey)[keyof typeof TestStorageKey];
const ENCRYPTED_KEYS = new Set<TestStorageKeyValue>([
TestStorageKey.ACCESS_TOKEN,
TestStorageKey.REFRESH_TOKEN,
TestStorageKey.USER_PROFILE,
]);
const PLAIN_KEYS = new Set<TestStorageKeyValue>([
TestStorageKey.THEME,
TestStorageKey.LOCALE,
]);
interface TestUser { interface TestUser {
id: number; id: number;
name: string; name: string;
@@ -48,95 +68,108 @@ const testUser: TestUser = { id: 1, name: 'Firman', role: 'admin' };
// ─── Tests ────────────────────────────────────────────────────── // ─── Tests ──────────────────────────────────────────────────────
describe('LocalStorageService', () => { describe('LocalStorageService', () => {
let storage: LocalStorageService; let storage: LocalStorageService<TestStorageKeyValue>;
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
for (const key of Object.keys(store)) delete store[key]; for (const key of Object.keys(store)) delete store[key];
// Pass mock encryption utils to avoid importing real crypto-js // Pass mock encryption utils to avoid importing real crypto-js
storage = new LocalStorageService(mockEncryptionUtils as never); storage = new LocalStorageService<TestStorageKeyValue>(
{ encryptedKeys: ENCRYPTED_KEYS, plainTextKeys: PLAIN_KEYS },
mockEncryptionUtils as never
);
});
describe('Runtime Validation', () => {
it('throws an error if the key is not in encryptedKeys or plainTextKeys', async () => {
// Cast a rogue key to bypass TS for the runtime check test
const rogueKey = 'unregistered_key' as TestStorageKeyValue;
await expect(storage.setItem(rogueKey, 'data')).rejects.toThrowError(
"[Storage Engine] Security Exception: Key 'unregistered_key' is not registered and cannot be accessed."
);
});
}); });
// ── setItem / getItem ───────────────────────────────────────── // ── setItem / getItem ─────────────────────────────────────────
describe('setItem / getItem', () => { describe('setItem / getItem', () => {
it('stores and retrieves a plain object (non-encrypted key)', async () => { it('stores and retrieves a plain object (non-encrypted key)', async () => {
await storage.setItem(StorageKey.THEME, 'dark'); await storage.setItem(TestStorageKey.THEME, 'dark');
const result = await storage.getItem<string>(StorageKey.THEME); const result = await storage.getItem<string>(TestStorageKey.THEME);
expect(result).toBe('dark'); expect(result).toBe('dark');
}); });
it('stores plain JSON without encryption for non-sensitive keys', async () => { it('stores plain JSON without encryption for non-sensitive keys', async () => {
await storage.setItem(StorageKey.LOCALE, 'en-US'); await storage.setItem(TestStorageKey.LOCALE, 'en-US');
expect(mockEncrypt).not.toHaveBeenCalled(); expect(mockEncrypt).not.toHaveBeenCalled();
expect(mockLocalStorage.setItem).toHaveBeenCalledWith( expect(mockLocalStorage.setItem).toHaveBeenCalledWith(
StorageKey.LOCALE, TestStorageKey.LOCALE,
'"en-US"', '"en-US"',
); );
}); });
it('encrypts sensitive keys (ACCESS_TOKEN)', async () => { it('encrypts sensitive keys (ACCESS_TOKEN)', async () => {
const token = 'eyJhbGciOiJIUzI1NiJ9.test'; const token = 'eyJhbGciOiJIUzI1NiJ9.test';
await storage.setItem(StorageKey.ACCESS_TOKEN, token); await storage.setItem(TestStorageKey.ACCESS_TOKEN, token);
expect(mockEncrypt).toHaveBeenCalledWith(JSON.stringify(token)); expect(mockEncrypt).toHaveBeenCalledWith(JSON.stringify(token));
// The stored value should be the encrypted payload // The stored value should be the encrypted payload
expect(store[StorageKey.ACCESS_TOKEN]).toBe(`ENC[${JSON.stringify(token)}]`); expect(store[TestStorageKey.ACCESS_TOKEN]).toBe(`ENC[${JSON.stringify(token)}]`);
}); });
it('decrypts sensitive keys on read', async () => { it('decrypts sensitive keys on read', async () => {
const token = 'secret_token_123'; const token = 'secret_token_123';
await storage.setItem(StorageKey.ACCESS_TOKEN, token); await storage.setItem(TestStorageKey.ACCESS_TOKEN, token);
const result = await storage.getItem<string>(StorageKey.ACCESS_TOKEN); const result = await storage.getItem<string>(TestStorageKey.ACCESS_TOKEN);
expect(mockDecrypt).toHaveBeenCalled(); expect(mockDecrypt).toHaveBeenCalled();
expect(result).toBe(token); expect(result).toBe(token);
}); });
it('stores and retrieves complex objects with generics', async () => { it('stores and retrieves complex objects with generics', async () => {
await storage.setItem(StorageKey.THEME, testUser); await storage.setItem(TestStorageKey.THEME, testUser);
const result = await storage.getItem<TestUser>(StorageKey.THEME); const result = await storage.getItem<TestUser>(TestStorageKey.THEME);
expect(result).toEqual(testUser); expect(result).toEqual(testUser);
}); });
it('stores complex objects encrypted for sensitive keys', async () => { it('stores complex objects encrypted for sensitive keys', async () => {
await storage.setItem(StorageKey.USER_PROFILE, testUser); await storage.setItem(TestStorageKey.USER_PROFILE, testUser);
expect(mockEncrypt).toHaveBeenCalledWith(JSON.stringify(testUser)); expect(mockEncrypt).toHaveBeenCalledWith(JSON.stringify(testUser));
const result = await storage.getItem<TestUser>(StorageKey.USER_PROFILE); const result = await storage.getItem<TestUser>(TestStorageKey.USER_PROFILE);
expect(result).toEqual(testUser); expect(result).toEqual(testUser);
}); });
it('returns null for non-existent keys', async () => { it('returns null for non-existent keys', async () => {
const result = await storage.getItem<string>('nonexistent'); const result = await storage.getItem<string>('nonexistent' as TestStorageKeyValue);
expect(result).toBeNull(); expect(result).toBeNull();
}); });
it('handles corrupt/invalid JSON gracefully', async () => { it('handles corrupt/invalid JSON gracefully', async () => {
store[StorageKey.THEME] = '{invalid json'; store[TestStorageKey.THEME] = '{invalid json';
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const result = await storage.getItem<string>(StorageKey.THEME); const result = await storage.getItem<string>(TestStorageKey.THEME);
expect(result).toBeNull(); expect(result).toBeNull();
expect(warnSpy).toHaveBeenCalledWith( expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('Failed to parse key'), expect.stringContaining('Failed to parse key'),
); );
// Corrupt entry should be cleaned up // Corrupt entry should be cleaned up
expect(store[StorageKey.THEME]).toBeUndefined(); expect(store[TestStorageKey.THEME]).toBeUndefined();
warnSpy.mockRestore(); warnSpy.mockRestore();
}); });
it('handles failed decryption gracefully', async () => { it('handles failed decryption gracefully', async () => {
// Write raw garbage to an encrypted key // Write raw garbage to an encrypted key
store[StorageKey.ACCESS_TOKEN] = 'not-encrypted-data'; store[TestStorageKey.ACCESS_TOKEN] = 'not-encrypted-data';
mockDecrypt.mockReturnValueOnce(''); mockDecrypt.mockReturnValueOnce('');
const result = await storage.getItem<string>(StorageKey.ACCESS_TOKEN); const result = await storage.getItem<string>(TestStorageKey.ACCESS_TOKEN);
expect(result).toBeNull(); expect(result).toBeNull();
}); });
}); });
@@ -145,11 +178,11 @@ describe('LocalStorageService', () => {
describe('removeItem', () => { describe('removeItem', () => {
it('removes a key from storage', async () => { it('removes a key from storage', async () => {
await storage.setItem(StorageKey.THEME, 'dark'); await storage.setItem(TestStorageKey.THEME, 'dark');
await storage.removeItem(StorageKey.THEME); await storage.removeItem(TestStorageKey.THEME);
expect(mockLocalStorage.removeItem).toHaveBeenCalledWith(StorageKey.THEME); expect(mockLocalStorage.removeItem).toHaveBeenCalledWith(TestStorageKey.THEME);
const result = await storage.getItem<string>(StorageKey.THEME); const result = await storage.getItem<string>(TestStorageKey.THEME);
expect(result).toBeNull(); expect(result).toBeNull();
}); });
}); });
@@ -158,8 +191,8 @@ describe('LocalStorageService', () => {
describe('clear', () => { describe('clear', () => {
it('clears all keys from storage', async () => { it('clears all keys from storage', async () => {
await storage.setItem(StorageKey.THEME, 'dark'); await storage.setItem(TestStorageKey.THEME, 'dark');
await storage.setItem(StorageKey.LOCALE, 'en'); await storage.setItem(TestStorageKey.LOCALE, 'en');
await storage.clear(); await storage.clear();
expect(mockLocalStorage.clear).toHaveBeenCalled(); expect(mockLocalStorage.clear).toHaveBeenCalled();
@@ -171,12 +204,12 @@ describe('LocalStorageService', () => {
describe('hasItem', () => { describe('hasItem', () => {
it('returns true for existing keys', async () => { it('returns true for existing keys', async () => {
await storage.setItem(StorageKey.THEME, 'dark'); await storage.setItem(TestStorageKey.THEME, 'dark');
expect(await storage.hasItem(StorageKey.THEME)).toBe(true); expect(await storage.hasItem(TestStorageKey.THEME)).toBe(true);
}); });
it('returns false for non-existent keys', async () => { it('returns false for non-existent keys', async () => {
expect(await storage.hasItem('ghost_key')).toBe(false); expect(await storage.hasItem('ghost_key' as TestStorageKeyValue)).toBe(false);
}); });
}); });
@@ -184,12 +217,12 @@ describe('LocalStorageService', () => {
describe('keys', () => { describe('keys', () => {
it('returns all stored keys', async () => { it('returns all stored keys', async () => {
await storage.setItem(StorageKey.THEME, 'dark'); await storage.setItem(TestStorageKey.THEME, 'dark');
await storage.setItem(StorageKey.LOCALE, 'en'); await storage.setItem(TestStorageKey.LOCALE, 'en');
const allKeys = await storage.keys(); const allKeys = await storage.keys();
expect(allKeys).toContain(StorageKey.THEME); expect(allKeys).toContain(TestStorageKey.THEME);
expect(allKeys).toContain(StorageKey.LOCALE); expect(allKeys).toContain(TestStorageKey.LOCALE);
expect(allKeys).toHaveLength(2); expect(allKeys).toHaveLength(2);
}); });
}); });
@@ -198,23 +231,23 @@ describe('LocalStorageService', () => {
describe('encryption key classification', () => { describe('encryption key classification', () => {
it('ACCESS_TOKEN is in ENCRYPTED_KEYS', () => { it('ACCESS_TOKEN is in ENCRYPTED_KEYS', () => {
expect(ENCRYPTED_KEYS.has(StorageKey.ACCESS_TOKEN)).toBe(true); expect(ENCRYPTED_KEYS.has(TestStorageKey.ACCESS_TOKEN)).toBe(true);
}); });
it('REFRESH_TOKEN is in ENCRYPTED_KEYS', () => { it('REFRESH_TOKEN is in ENCRYPTED_KEYS', () => {
expect(ENCRYPTED_KEYS.has(StorageKey.REFRESH_TOKEN)).toBe(true); expect(ENCRYPTED_KEYS.has(TestStorageKey.REFRESH_TOKEN)).toBe(true);
}); });
it('USER_PROFILE is in ENCRYPTED_KEYS', () => { it('USER_PROFILE is in ENCRYPTED_KEYS', () => {
expect(ENCRYPTED_KEYS.has(StorageKey.USER_PROFILE)).toBe(true); expect(ENCRYPTED_KEYS.has(TestStorageKey.USER_PROFILE)).toBe(true);
}); });
it('THEME is NOT in ENCRYPTED_KEYS', () => { it('THEME is NOT in ENCRYPTED_KEYS', () => {
expect(ENCRYPTED_KEYS.has(StorageKey.THEME)).toBe(false); expect(ENCRYPTED_KEYS.has(TestStorageKey.THEME)).toBe(false);
}); });
it('LOCALE is NOT in ENCRYPTED_KEYS', () => { it('LOCALE is NOT in ENCRYPTED_KEYS', () => {
expect(ENCRYPTED_KEYS.has(StorageKey.LOCALE)).toBe(false); expect(ENCRYPTED_KEYS.has(TestStorageKey.LOCALE)).toBe(false);
}); });
}); });
}); });
+413 -7
View File
@@ -106,6 +106,9 @@ importers:
'@repo/core-i18n': '@repo/core-i18n':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/core-i18n version: link:../../packages/core-i18n
'@repo/core-storage':
specifier: workspace:*
version: link:../../packages/core-storage
'@repo/ui': '@repo/ui':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/ui version: link:../../packages/ui
@@ -161,6 +164,9 @@ importers:
'@repo/core-api': '@repo/core-api':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/core-api version: link:../../packages/core-api
'@repo/core-events':
specifier: workspace:*
version: link:../../packages/core-events
'@repo/core-i18n': '@repo/core-i18n':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/core-i18n version: link:../../packages/core-i18n
@@ -224,7 +230,7 @@ importers:
version: 5.4.17(@types/node@22.19.3) version: 5.4.17(@types/node@22.19.3)
vitest: vitest:
specifier: ^4.0.17 specifier: ^4.0.17
version: 4.0.17(@opentelemetry/api@1.9.1) version: 4.0.17(jsdom@26.1.0)
packages/configs/eslint: packages/configs/eslint:
dependencies: dependencies:
@@ -303,11 +309,48 @@ importers:
specifier: ^4.0.17 specifier: ^4.0.17
version: 4.0.17(@opentelemetry/api@1.9.1) version: 4.0.17(@opentelemetry/api@1.9.1)
packages/core-events:
dependencies:
mitt:
specifier: ^3.0.1
version: 3.0.1
devDependencies:
'@repo/eslint-config':
specifier: workspace:*
version: link:../configs/eslint
'@repo/typescript-config':
specifier: workspace:*
version: link:../configs/typescript
'@testing-library/react':
specifier: ^16.3.0
version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.3)(react@19.2.3)
'@types/react':
specifier: ^19.2.7
version: 19.2.7
'@types/react-dom':
specifier: ^19.2.3
version: 19.2.3(@types/react@19.2.7)
eslint:
specifier: ^8.57.1
version: 8.57.1
jsdom:
specifier: ^26.1.0
version: 26.1.0
react:
specifier: ^19.2.3
version: 19.2.3
react-dom:
specifier: ^19.2.3
version: 19.2.3(react@19.2.3)
typescript:
specifier: 5.5.4
version: 5.5.4
vitest:
specifier: ^4.0.17
version: 4.0.17(jsdom@26.1.0)
packages/core-i18n: packages/core-i18n:
dependencies: dependencies:
'@repo/core-storage':
specifier: workspace:*
version: link:../core-storage
'@repo/utils': '@repo/utils':
specifier: workspace:* specifier: workspace:*
version: link:../utils version: link:../utils
@@ -351,7 +394,7 @@ importers:
version: 5.5.4 version: 5.5.4
vitest: vitest:
specifier: ^4.0.17 specifier: ^4.0.17
version: 4.0.17(@opentelemetry/api@1.9.1) version: 4.0.17(jsdom@26.1.0)
packages/ui: packages/ui:
dependencies: dependencies:
@@ -412,7 +455,7 @@ importers:
version: 5.4.17(@types/node@22.19.3) version: 5.4.17(@types/node@22.19.3)
vitest: vitest:
specifier: ^4.0.17 specifier: ^4.0.17
version: 4.0.17(@opentelemetry/api@1.9.1) version: 4.0.17(jsdom@26.1.0)
packages/utils: packages/utils:
dependencies: dependencies:
@@ -440,7 +483,7 @@ importers:
version: 5.5.4 version: 5.5.4
vitest: vitest:
specifier: ^4.0.17 specifier: ^4.0.17
version: 4.0.17(@opentelemetry/api@1.9.1) version: 4.0.17(jsdom@26.1.0)
packages: packages:
@@ -448,6 +491,16 @@ packages:
resolution: {integrity: sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==} resolution: {integrity: sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==}
dev: true dev: true
/@asamuzakjp/css-color@3.2.0:
resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
dependencies:
'@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5)(@csstools/css-tokenizer@3.0.4)
'@csstools/css-color-parser': 3.1.0(@csstools/css-parser-algorithms@3.0.5)(@csstools/css-tokenizer@3.0.4)
'@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4)
'@csstools/css-tokenizer': 3.0.4
lru-cache: 10.4.3
dev: true
/@babel/code-frame@7.27.1: /@babel/code-frame@7.27.1:
resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==} resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==}
engines: {node: '>=6.9.0'} engines: {node: '>=6.9.0'}
@@ -636,6 +689,49 @@ packages:
'@babel/helper-string-parser': 7.27.1 '@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5 '@babel/helper-validator-identifier': 7.28.5
/@csstools/color-helpers@5.1.0:
resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==}
engines: {node: '>=18'}
dev: true
/@csstools/css-calc@2.1.4(@csstools/css-parser-algorithms@3.0.5)(@csstools/css-tokenizer@3.0.4):
resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==}
engines: {node: '>=18'}
peerDependencies:
'@csstools/css-parser-algorithms': ^3.0.5
'@csstools/css-tokenizer': ^3.0.4
dependencies:
'@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4)
'@csstools/css-tokenizer': 3.0.4
dev: true
/@csstools/css-color-parser@3.1.0(@csstools/css-parser-algorithms@3.0.5)(@csstools/css-tokenizer@3.0.4):
resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==}
engines: {node: '>=18'}
peerDependencies:
'@csstools/css-parser-algorithms': ^3.0.5
'@csstools/css-tokenizer': ^3.0.4
dependencies:
'@csstools/color-helpers': 5.1.0
'@csstools/css-calc': 2.1.4(@csstools/css-parser-algorithms@3.0.5)(@csstools/css-tokenizer@3.0.4)
'@csstools/css-parser-algorithms': 3.0.5(@csstools/css-tokenizer@3.0.4)
'@csstools/css-tokenizer': 3.0.4
dev: true
/@csstools/css-parser-algorithms@3.0.5(@csstools/css-tokenizer@3.0.4):
resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==}
engines: {node: '>=18'}
peerDependencies:
'@csstools/css-tokenizer': ^3.0.4
dependencies:
'@csstools/css-tokenizer': 3.0.4
dev: true
/@csstools/css-tokenizer@3.0.4:
resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==}
engines: {node: '>=18'}
dev: true
/@develar/schema-utils@2.6.5: /@develar/schema-utils@2.6.5:
resolution: {integrity: sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==} resolution: {integrity: sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==}
engines: {node: '>= 8.9.0'} engines: {node: '>= 8.9.0'}
@@ -2823,6 +2919,43 @@ packages:
tailwindcss: 4.1.18 tailwindcss: 4.1.18
vite: 5.4.17(@types/node@22.19.3) vite: 5.4.17(@types/node@22.19.3)
/@testing-library/dom@10.4.1:
resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}
engines: {node: '>=18'}
dependencies:
'@babel/code-frame': 7.27.1
'@babel/runtime': 7.28.4
'@types/aria-query': 5.0.4
aria-query: 5.3.0
dom-accessibility-api: 0.5.16
lz-string: 1.5.0
picocolors: 1.1.1
pretty-format: 27.5.1
dev: true
/@testing-library/react@16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.3)(react@19.2.3):
resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}
engines: {node: '>=18'}
peerDependencies:
'@testing-library/dom': ^10.0.0
'@types/react': ^18.0.0 || ^19.0.0
'@types/react-dom': ^18.0.0 || ^19.0.0
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
dependencies:
'@babel/runtime': 7.28.4
'@testing-library/dom': 10.4.1
'@types/react': 19.2.7
'@types/react-dom': 19.2.3(@types/react@19.2.7)
react: 19.2.3
react-dom: 19.2.3(react@19.2.3)
dev: true
/@tootallnate/once@2.0.0: /@tootallnate/once@2.0.0:
resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==} resolution: {integrity: sha512-XCuKFP5PS55gnMVu3dty8KPatLqUoy/ZYzDzAGCQ8JNFCkLXzmI7vNHCR+XpbZaMWQK/vQubr7PkYq8g470J/A==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
@@ -2836,6 +2969,10 @@ packages:
dev: false dev: false
optional: true optional: true
/@types/aria-query@5.0.4:
resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}
dev: true
/@types/babel__core@7.20.5: /@types/babel__core@7.20.5:
resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}
dependencies: dependencies:
@@ -3771,6 +3908,11 @@ packages:
dependencies: dependencies:
color-convert: 2.0.1 color-convert: 2.0.1
/ansi-styles@5.2.0:
resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
engines: {node: '>=10'}
dev: true
/ansi-styles@6.2.3: /ansi-styles@6.2.3:
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'} engines: {node: '>=12'}
@@ -3894,6 +4036,12 @@ packages:
/argparse@2.0.1: /argparse@2.0.1:
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
/aria-query@5.3.0:
resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}
dependencies:
dequal: 2.0.3
dev: true
/aria-query@5.3.2: /aria-query@5.3.2:
resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==} resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -4620,6 +4768,14 @@ packages:
resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==} resolution: {integrity: sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==}
dev: false dev: false
/cssstyle@4.6.0:
resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==}
engines: {node: '>=18'}
dependencies:
'@asamuzakjp/css-color': 3.2.0
rrweb-cssom: 0.8.0
dev: true
/csstype@3.2.3: /csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
@@ -4627,6 +4783,14 @@ packages:
resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==} resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}
dev: false dev: false
/data-urls@5.0.0:
resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}
engines: {node: '>=18'}
dependencies:
whatwg-mimetype: 4.0.0
whatwg-url: 14.2.0
dev: true
/data-view-buffer@1.0.2: /data-view-buffer@1.0.2:
resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -4702,6 +4866,10 @@ packages:
dependencies: dependencies:
ms: 2.1.3 ms: 2.1.3
/decimal.js@10.6.0:
resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}
dev: true
/decode-named-character-reference@1.2.0: /decode-named-character-reference@1.2.0:
resolution: {integrity: sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==} resolution: {integrity: sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==}
dependencies: dependencies:
@@ -4864,6 +5032,10 @@ packages:
dependencies: dependencies:
esutils: 2.0.3 esutils: 2.0.3
/dom-accessibility-api@0.5.16:
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
dev: true
/dotenv-expand@11.0.7: /dotenv-expand@11.0.7:
resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==} resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==}
engines: {node: '>=12'} engines: {node: '>=12'}
@@ -5032,6 +5204,11 @@ packages:
graceful-fs: 4.2.11 graceful-fs: 4.2.11
tapable: 2.3.0 tapable: 2.3.0
/entities@6.0.1:
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
dev: true
/env-paths@2.2.1: /env-paths@2.2.1:
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'} engines: {node: '>=6'}
@@ -6264,6 +6441,13 @@ packages:
lru-cache: 10.4.3 lru-cache: 10.4.3
dev: false dev: false
/html-encoding-sniffer@4.0.0:
resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}
engines: {node: '>=18'}
dependencies:
whatwg-encoding: 3.1.1
dev: true
/html-parse-stringify@3.0.1: /html-parse-stringify@3.0.1:
resolution: {integrity: sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==} resolution: {integrity: sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==}
dependencies: dependencies:
@@ -6642,6 +6826,10 @@ packages:
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
dev: true dev: true
/is-potential-custom-element-name@1.0.1:
resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
dev: true
/is-regex@1.2.1: /is-regex@1.2.1:
resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -6799,6 +6987,41 @@ packages:
engines: {node: '>=12.0.0'} engines: {node: '>=12.0.0'}
dev: true dev: true
/jsdom@26.1.0:
resolution: {integrity: sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==}
engines: {node: '>=18'}
peerDependencies:
canvas: ^3.0.0
peerDependenciesMeta:
canvas:
optional: true
dependencies:
cssstyle: 4.6.0
data-urls: 5.0.0
decimal.js: 10.6.0
html-encoding-sniffer: 4.0.0
http-proxy-agent: 7.0.2
https-proxy-agent: 7.0.6
is-potential-custom-element-name: 1.0.1
nwsapi: 2.2.23
parse5: 7.3.0
rrweb-cssom: 0.8.0
saxes: 6.0.0
symbol-tree: 3.2.4
tough-cookie: 5.1.2
w3c-xmlserializer: 5.0.0
webidl-conversions: 7.0.0
whatwg-encoding: 3.1.1
whatwg-mimetype: 4.0.0
whatwg-url: 14.2.0
ws: 8.19.0
xml-name-validator: 5.0.0
transitivePeerDependencies:
- bufferutil
- supports-color
- utf-8-validate
dev: true
/jsesc@0.5.0: /jsesc@0.5.0:
resolution: {integrity: sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==} resolution: {integrity: sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==}
hasBin: true hasBin: true
@@ -7130,6 +7353,11 @@ packages:
engines: {node: '>=12'} engines: {node: '>=12'}
dev: true dev: true
/lz-string@1.5.0:
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
dev: true
/magic-string@0.27.0: /magic-string@0.27.0:
resolution: {integrity: sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==} resolution: {integrity: sha512-8UnnX2PeRAPZuN12svgR9j7M1uWMovg/CEnIwIG0LFkXSJJe4PdfUGiTGl8V9bsBHFUtfVINcSyYxd7q+kx9fA==}
engines: {node: '>=12'} engines: {node: '>=12'}
@@ -7711,6 +7939,10 @@ packages:
yallist: 4.0.0 yallist: 4.0.0
dev: true dev: true
/mitt@3.0.1:
resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==}
dev: false
/mkdirp@1.0.4: /mkdirp@1.0.4:
resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==} resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==}
engines: {node: '>=10'} engines: {node: '>=10'}
@@ -7888,6 +8120,10 @@ packages:
set-blocking: 2.0.0 set-blocking: 2.0.0
dev: true dev: true
/nwsapi@2.2.23:
resolution: {integrity: sha512-7wfH4sLbt4M0gCDzGE6vzQBo0bfTKjU7Sfpqy/7gs1qBfYz2vEJH6vXcBKpO3+6Yu1telwd0t9HpyOoLEQQbIQ==}
dev: true
/object-assign@4.1.1: /object-assign@4.1.1:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@@ -8103,6 +8339,12 @@ packages:
type-fest: 3.13.1 type-fest: 3.13.1
dev: false dev: false
/parse5@7.3.0:
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
dependencies:
entities: 6.0.1
dev: true
/path-exists@4.0.0: /path-exists@4.0.0:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'} engines: {node: '>=8'}
@@ -8226,6 +8468,15 @@ packages:
resolution: {integrity: sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==} resolution: {integrity: sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==}
engines: {node: '>=14'} engines: {node: '>=14'}
/pretty-format@27.5.1:
resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}
engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
dependencies:
ansi-regex: 5.0.1
ansi-styles: 5.2.0
react-is: 17.0.2
dev: true
/proc-log@4.2.0: /proc-log@4.2.0:
resolution: {integrity: sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA==} resolution: {integrity: sha512-g8+OnU/L2v+wyiVK+D5fA34J7EH8jZ8DDlvwhRCMxmMj7UCBvxiO1mGeN+36JXIKF4zevU4kRBd8lVgG9vLelA==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -8388,6 +8639,10 @@ packages:
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==} resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
dev: false dev: false
/react-is@17.0.2:
resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}
dev: true
/react-number-format@5.4.4(react-dom@19.2.3)(react@19.2.3): /react-number-format@5.4.4(react-dom@19.2.3)(react@19.2.3):
resolution: {integrity: sha512-wOmoNZoOpvMminhifQYiYSTCLUDOiUbBunrMrMjA+dV52sY+vck1S4UhR6PkgnoCquvvMSeJjErXZ4qSaWCliA==} resolution: {integrity: sha512-wOmoNZoOpvMminhifQYiYSTCLUDOiUbBunrMrMjA+dV52sY+vck1S4UhR6PkgnoCquvvMSeJjErXZ4qSaWCliA==}
peerDependencies: peerDependencies:
@@ -8825,6 +9080,10 @@ packages:
fsevents: 2.3.3 fsevents: 2.3.3
dev: true dev: true
/rrweb-cssom@0.8.0:
resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==}
dev: true
/run-parallel@1.2.0: /run-parallel@1.2.0:
resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
dependencies: dependencies:
@@ -8885,6 +9144,13 @@ packages:
resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==}
engines: {node: '>=11.0.0'} engines: {node: '>=11.0.0'}
/saxes@6.0.0:
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
engines: {node: '>=v12.22.7'}
dependencies:
xmlchars: 2.2.0
dev: true
/scheduler@0.27.0: /scheduler@0.27.0:
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
@@ -9389,6 +9655,10 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
/symbol-tree@3.2.4:
resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}
dev: true
/synckit@0.11.11: /synckit@0.11.11:
resolution: {integrity: sha512-MeQTA1r0litLUf0Rp/iisCaL8761lKAZHaimlbGK4j0HysC4PLfqygQj9srcs0m2RdtDYnF8UuYyKpbjHYp7Jw==} resolution: {integrity: sha512-MeQTA1r0litLUf0Rp/iisCaL8761lKAZHaimlbGK4j0HysC4PLfqygQj9srcs0m2RdtDYnF8UuYyKpbjHYp7Jw==}
engines: {node: ^14.18.0 || >=16.0.0} engines: {node: ^14.18.0 || >=16.0.0}
@@ -9488,6 +9758,17 @@ packages:
engines: {node: '>=14.0.0'} engines: {node: '>=14.0.0'}
dev: true dev: true
/tldts-core@6.1.86:
resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==}
dev: true
/tldts@6.1.86:
resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==}
hasBin: true
dependencies:
tldts-core: 6.1.86
dev: true
/tmp-promise@3.0.3: /tmp-promise@3.0.3:
resolution: {integrity: sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==} resolution: {integrity: sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==}
dependencies: dependencies:
@@ -9506,6 +9787,20 @@ packages:
is-number: 7.0.0 is-number: 7.0.0
dev: false dev: false
/tough-cookie@5.1.2:
resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==}
engines: {node: '>=16'}
dependencies:
tldts: 6.1.86
dev: true
/tr46@5.1.1:
resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}
engines: {node: '>=18'}
dependencies:
punycode: 2.3.1
dev: true
/trough@2.2.0: /trough@2.2.0:
resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==} resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}
dev: false dev: false
@@ -10233,11 +10528,87 @@ packages:
- yaml - yaml
dev: true dev: true
/vitest@4.0.17(jsdom@26.1.0):
resolution: {integrity: sha512-FQMeF0DJdWY0iOnbv466n/0BudNdKj1l5jYgl5JVTwjSsZSlqyXFt/9+1sEyhR6CLowbZpV7O1sCHrzBhucKKg==}
engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
hasBin: true
peerDependencies:
'@edge-runtime/vm': '*'
'@opentelemetry/api': ^1.9.0
'@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
'@vitest/browser-playwright': 4.0.17
'@vitest/browser-preview': 4.0.17
'@vitest/browser-webdriverio': 4.0.17
'@vitest/ui': 4.0.17
happy-dom: '*'
jsdom: '*'
peerDependenciesMeta:
'@edge-runtime/vm':
optional: true
'@opentelemetry/api':
optional: true
'@types/node':
optional: true
'@vitest/browser-playwright':
optional: true
'@vitest/browser-preview':
optional: true
'@vitest/browser-webdriverio':
optional: true
'@vitest/ui':
optional: true
happy-dom:
optional: true
jsdom:
optional: true
dependencies:
'@vitest/expect': 4.0.17
'@vitest/mocker': 4.0.17(vite@7.3.1)
'@vitest/pretty-format': 4.0.17
'@vitest/runner': 4.0.17
'@vitest/snapshot': 4.0.17
'@vitest/spy': 4.0.17
'@vitest/utils': 4.0.17
es-module-lexer: 1.7.0
expect-type: 1.3.0
jsdom: 26.1.0
magic-string: 0.30.21
obug: 2.1.1
pathe: 2.0.3
picomatch: 4.0.3
std-env: 3.10.0
tinybench: 2.9.0
tinyexec: 1.0.2
tinyglobby: 0.2.15
tinyrainbow: 3.0.3
vite: 7.3.1
why-is-node-running: 2.3.0
transitivePeerDependencies:
- jiti
- less
- lightningcss
- msw
- sass
- sass-embedded
- stylus
- sugarss
- terser
- tsx
- yaml
dev: true
/void-elements@3.1.0: /void-elements@3.1.0:
resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==} resolution: {integrity: sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
dev: false dev: false
/w3c-xmlserializer@5.0.0:
resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}
engines: {node: '>=18'}
dependencies:
xml-name-validator: 5.0.0
dev: true
/walk-up-path@3.0.1: /walk-up-path@3.0.1:
resolution: {integrity: sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA==} resolution: {integrity: sha512-9YlCL/ynK3CTlrSRrDxZvUauLzAswPCrsaCgilqFevUYpeEW0/3ScEjaa3kbW/T0ghhkEr7mv+fpjqn1Y1YuTA==}
dev: false dev: false
@@ -10252,10 +10623,36 @@ packages:
resolution: {integrity: sha512-i2z98bEmaCqSDiHEDu+gHl/dmR4Q+TxFmG3/13KkMO+o8UxQzCqWaDRCiLgEa41nlO4VpXSI0ASa1xWmO9sBlA==} resolution: {integrity: sha512-i2z98bEmaCqSDiHEDu+gHl/dmR4Q+TxFmG3/13KkMO+o8UxQzCqWaDRCiLgEa41nlO4VpXSI0ASa1xWmO9sBlA==}
dev: false dev: false
/webidl-conversions@7.0.0:
resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}
engines: {node: '>=12'}
dev: true
/webpack-virtual-modules@0.6.2: /webpack-virtual-modules@0.6.2:
resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==} resolution: {integrity: sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ==}
dev: true dev: true
/whatwg-encoding@3.1.1:
resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}
engines: {node: '>=18'}
deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation
dependencies:
iconv-lite: 0.6.3
dev: true
/whatwg-mimetype@4.0.0:
resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}
engines: {node: '>=18'}
dev: true
/whatwg-url@14.2.0:
resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}
engines: {node: '>=18'}
dependencies:
tr46: 5.1.1
webidl-conversions: 7.0.0
dev: true
/which-boxed-primitive@1.1.1: /which-boxed-primitive@1.1.1:
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -10380,12 +10777,21 @@ packages:
optional: true optional: true
dev: true dev: true
/xml-name-validator@5.0.0:
resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
engines: {node: '>=18'}
dev: true
/xmlbuilder@15.1.1: /xmlbuilder@15.1.1:
resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==} resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==}
engines: {node: '>=8.0'} engines: {node: '>=8.0'}
requiresBuild: true requiresBuild: true
dev: true dev: true
/xmlchars@2.2.0:
resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}
dev: true
/y18n@5.0.8: /y18n@5.0.8:
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'} engines: {node: '>=10'}