feat: warm-up deps — ts-reset, web-vitals, RHF devtool, query-broadcast
Four low-risk adds before the Zod 4 / drizzle-zod headliner: - @total-typescript/ts-reset: tightens TS stdlib types globally (JSON.parse → unknown, fetch().json() → unknown, .filter(Boolean) narrows, Set literals respect typed Set targets). Caught 179 latent type errors; fixed all production sites (8 files) and added `any` cast escape hatch in test files (ESLint exemption scoped to tests/). - web-vitals + /api/v1/internal/vitals endpoint + WebVitalsReporter client component: establishes Core Web Vitals baseline (LCP/INP/CLS/ FCP/TTFB) via navigator.sendBeacon. Required before optimisation work. - @hookform/devtools + FormDevtool wrapper: dev-only RHF state inspector, lazy-loaded via next/dynamic so the chunk is excluded from prod bundles entirely. - @tanstack/query-broadcast-client-experimental: cross-tab cache sync via BroadcastChannel — wired in query-provider.tsx, 1-liner. Audit doc updated with sections 35 + 36 (PDF stack overhaul + comprehensive second-pass package sweep) covering ~20 package adoption candidates and 4-5 deprecation candidates. Verified: tsc clean, vitest 1293/1293 pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -56,7 +56,10 @@ function SetPasswordInner() {
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({}));
|
||||
const body = (await response.json().catch(() => ({}))) as {
|
||||
message?: string;
|
||||
error?: string;
|
||||
};
|
||||
toast.error(body.message ?? body.error ?? 'Failed to set password. Please try again.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Sidebar } from '@/components/layout/sidebar';
|
||||
import { Topbar } from '@/components/layout/topbar';
|
||||
import { MobileLayout } from '@/components/layout/mobile/mobile-layout';
|
||||
import { RealtimeToasts } from '@/components/shared/realtime-toasts';
|
||||
import { WebVitalsReporter } from '@/components/shared/web-vitals-reporter';
|
||||
|
||||
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
@@ -40,6 +41,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
|
||||
<PermissionsProvider>
|
||||
<SocketProvider>
|
||||
<RealtimeToasts />
|
||||
<WebVitalsReporter />
|
||||
{/* Desktop shell - hidden by CSS on mobile */}
|
||||
<div data-shell="desktop" className="flex h-screen overflow-hidden bg-background">
|
||||
<Sidebar
|
||||
|
||||
54
src/app/api/v1/internal/vitals/route.ts
Normal file
54
src/app/api/v1/internal/vitals/route.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
import { logger } from '@/lib/logger';
|
||||
|
||||
/**
|
||||
* Ingest Core Web Vitals from the client. Called via `navigator.sendBeacon`
|
||||
* from `WebVitalsReporter` so it survives page unload. Body shape matches
|
||||
* the `Metric` type from `web-vitals` v4.
|
||||
*
|
||||
* For now we log structured to pino — once we have a perf-tracking table
|
||||
* (or external aggregator) wired, this can persist instead. The key value
|
||||
* today is establishing the baseline before optimisation work.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'invalid json' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!body || typeof body !== 'object') {
|
||||
return NextResponse.json({ error: 'invalid body' }, { status: 400 });
|
||||
}
|
||||
|
||||
const m = body as {
|
||||
name?: string;
|
||||
value?: number;
|
||||
rating?: 'good' | 'needs-improvement' | 'poor';
|
||||
id?: string;
|
||||
delta?: number;
|
||||
navigationType?: string;
|
||||
path?: string;
|
||||
};
|
||||
|
||||
if (typeof m.name !== 'string' || typeof m.value !== 'number') {
|
||||
return NextResponse.json({ error: 'missing name/value' }, { status: 400 });
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
vital: m.name,
|
||||
value: m.value,
|
||||
rating: m.rating ?? null,
|
||||
id: m.id ?? null,
|
||||
delta: m.delta ?? null,
|
||||
navigationType: m.navigationType ?? null,
|
||||
path: m.path ?? null,
|
||||
},
|
||||
'web-vital',
|
||||
);
|
||||
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
@@ -48,7 +48,9 @@ export function ExternalEoiUploadDialog({ open, onOpenChange, interestId, onSucc
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: 'Upload failed' }));
|
||||
const err = (await res.json().catch(() => ({ error: 'Upload failed' }))) as {
|
||||
error?: string;
|
||||
};
|
||||
throw new Error(err.error ?? 'Upload failed');
|
||||
}
|
||||
return res.json();
|
||||
|
||||
@@ -233,10 +233,12 @@ function FilterField({
|
||||
id={`${definition.key}-${opt.value}`}
|
||||
checked={selected}
|
||||
onCheckedChange={(checked) => {
|
||||
const current = Array.isArray(value) ? value : [];
|
||||
const current: string[] = Array.isArray(value)
|
||||
? value.filter((v): v is string => typeof v === 'string')
|
||||
: [];
|
||||
const next = checked
|
||||
? [...current, opt.value]
|
||||
: current.filter((v: string) => v !== opt.value);
|
||||
: current.filter((v) => v !== opt.value);
|
||||
onChange(next.length > 0 ? next : undefined);
|
||||
}}
|
||||
/>
|
||||
|
||||
32
src/components/shared/form-devtool.tsx
Normal file
32
src/components/shared/form-devtool.tsx
Normal file
@@ -0,0 +1,32 @@
|
||||
'use client';
|
||||
|
||||
import dynamic from 'next/dynamic';
|
||||
import type { Control, FieldValues } from 'react-hook-form';
|
||||
|
||||
// Lazy-load @hookform/devtools only when actually rendered. The
|
||||
// `process.env.NODE_ENV` guard below ensures we never hit this path in
|
||||
// production, so Next.js' code splitter keeps the devtools chunk out of
|
||||
// the prod bundle entirely.
|
||||
const DevTool = dynamic(() => import('@hookform/devtools').then((m) => ({ default: m.DevTool })), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* Floating react-hook-form state inspector. Shows live values, errors,
|
||||
* touched/dirty state. Rendered only in development.
|
||||
*
|
||||
* Usage in any form component:
|
||||
*
|
||||
* const form = useForm({ resolver: zodResolver(schema) });
|
||||
* ...
|
||||
* <form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
* <FormDevtool control={form.control} />
|
||||
* {fields}
|
||||
* </form>
|
||||
*/
|
||||
export function FormDevtool<T extends FieldValues>({ control }: { control: Control<T> }) {
|
||||
if (process.env.NODE_ENV !== 'development') return null;
|
||||
// Cast: @hookform/devtools types Control as the v6 shape; ours is v7+.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return <DevTool control={control as any} placement="bottom-right" />;
|
||||
}
|
||||
@@ -56,7 +56,7 @@ const SELF_SOURCE: Record<NotesEntityType, NoteSource | null> = {
|
||||
residential_interests: null,
|
||||
};
|
||||
|
||||
const AGGREGATABLE: ReadonlySet<NotesEntityType> = new Set([
|
||||
const AGGREGATABLE: ReadonlySet<NotesEntityType> = new Set<NotesEntityType>([
|
||||
'clients',
|
||||
'yachts',
|
||||
'companies',
|
||||
|
||||
56
src/components/shared/web-vitals-reporter.tsx
Normal file
56
src/components/shared/web-vitals-reporter.tsx
Normal file
@@ -0,0 +1,56 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals';
|
||||
|
||||
const VITALS_ENDPOINT = '/api/v1/internal/vitals';
|
||||
|
||||
/**
|
||||
* Reports Core Web Vitals to the backend so we have a baseline before
|
||||
* any perf-optimisation work. Sends via `sendBeacon` (survives unload)
|
||||
* with a `fetch` fallback for browsers that don't support beacon.
|
||||
*
|
||||
* Mounted in the dashboard layout — fires once per page lifecycle for
|
||||
* each metric. Vitals are reported when stable (LCP locked in, INP after
|
||||
* meaningful interaction, etc.), not on every render.
|
||||
*/
|
||||
export function WebVitalsReporter() {
|
||||
useEffect(() => {
|
||||
function report(metric: Metric) {
|
||||
const path = typeof window !== 'undefined' ? window.location.pathname : null;
|
||||
|
||||
const body = JSON.stringify({
|
||||
name: metric.name,
|
||||
value: metric.value,
|
||||
rating: metric.rating,
|
||||
id: metric.id,
|
||||
delta: metric.delta,
|
||||
navigationType: metric.navigationType,
|
||||
path,
|
||||
});
|
||||
|
||||
if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
|
||||
navigator.sendBeacon(VITALS_ENDPOINT, new Blob([body], { type: 'application/json' }));
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback for browsers without sendBeacon.
|
||||
fetch(VITALS_ENDPOINT, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
keepalive: true,
|
||||
}).catch(() => {
|
||||
// Swallow — vitals are best-effort.
|
||||
});
|
||||
}
|
||||
|
||||
onLCP(report);
|
||||
onINP(report);
|
||||
onCLS(report);
|
||||
onFCP(report);
|
||||
onTTFB(report);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -73,7 +73,14 @@ export async function apiFetch<T = unknown>(url: string, opts: ApiFetchOptions =
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ error: res.statusText }));
|
||||
const error = (await res.json().catch(() => ({ error: res.statusText }))) as {
|
||||
error?: string;
|
||||
message?: string;
|
||||
code?: string;
|
||||
details?: unknown;
|
||||
requestId?: string;
|
||||
retryAfter?: number;
|
||||
};
|
||||
// Surface the request id so toasts can display "Error ID: …" and
|
||||
// the user can copy it to a support ticket. Server-side wrappers
|
||||
// always set X-Request-Id, even on early-return 401/403 paths.
|
||||
|
||||
@@ -33,7 +33,7 @@ import type { PipelineStage } from '@/lib/constants';
|
||||
* bulk-archive UI prompts the operator to confirm individually + supply
|
||||
* a reason for these clients.
|
||||
*/
|
||||
export const HIGH_STAKES_STAGES: ReadonlySet<PipelineStage> = new Set([
|
||||
export const HIGH_STAKES_STAGES: ReadonlySet<PipelineStage> = new Set<PipelineStage>([
|
||||
'deposit_10pct',
|
||||
'contract_sent',
|
||||
'contract_signed',
|
||||
|
||||
@@ -30,8 +30,8 @@ export async function refreshRates(): Promise<void> {
|
||||
throw new CodedError('INTERNAL', {
|
||||
internalMessage: `Frankfurter API error: ${res.status}`,
|
||||
});
|
||||
const data = await res.json();
|
||||
const rates = data.rates as Record<string, number>;
|
||||
const data = (await res.json()) as { rates: Record<string, number> };
|
||||
const rates = data.rates;
|
||||
|
||||
for (const [currency, rate] of Object.entries(rates)) {
|
||||
await db
|
||||
|
||||
@@ -105,7 +105,7 @@ export async function sendInquiryNotifications(params: InquiryNotificationParams
|
||||
try {
|
||||
const recipientsSetting = await getSetting('inquiry_notification_recipients', portId);
|
||||
const externalEmails: string[] = Array.isArray(recipientsSetting?.value)
|
||||
? recipientsSetting.value
|
||||
? recipientsSetting.value.filter((v): v is string => typeof v === 'string')
|
||||
: [];
|
||||
|
||||
if (externalEmails.length > 0) {
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { broadcastQueryClient } from '@tanstack/query-broadcast-client-experimental';
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
|
||||
export function QueryProvider({ children }: { children: ReactNode }) {
|
||||
const [queryClient] = useState(
|
||||
@@ -23,6 +24,14 @@ export function QueryProvider({ children }: { children: ReactNode }) {
|
||||
}),
|
||||
);
|
||||
|
||||
// Sync cache across tabs via BroadcastChannel. When a rep updates a
|
||||
// client in tab A, tab B's cached query invalidates instantly without
|
||||
// a server roundtrip. Runs in browser only.
|
||||
useEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
broadcastQueryClient({ queryClient, broadcastChannel: 'pn-crm' });
|
||||
}, [queryClient]);
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
{children}
|
||||
|
||||
4
src/types/ts-reset.d.ts
vendored
Normal file
4
src/types/ts-reset.d.ts
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
// Activates @total-typescript/ts-reset — tightens TypeScript stdlib types
|
||||
// across the project (JSON.parse, Array.isArray, .filter(Boolean), etc.)
|
||||
// without changing runtime behavior.
|
||||
import '@total-typescript/ts-reset';
|
||||
Reference in New Issue
Block a user