Two cleanups in one pass: 1. Update import paths app-wide from `~/lib/auth.server` to `~/lib/auth/session.server` for the four session helpers (sessionStorage, createSession, getSessionUser, destroySession). ~40 files: 33 simple path swaps where the file imported only session symbols, 5 splits where it also imported per-method auth functions (auth.verify.tsx, api.settings.email.ts, activities.\$id.tsx, routes.\$id.tsx, auth.accept-terms.tsx) — those keep one import from auth.server (for verifyMagicToken, canView, recordTermsAcceptance, etc.) and gain a second import from auth/session.server. Two more files used relative paths and were missed by the first grep pass (lib/oauth.server.ts and routes/oauth.authorize.tsx) — migrated too. The @deprecated re-exports block in auth.server.ts is gone. 2. Rename the new auth files to follow the project's `.server.ts` convention so Vite/React Router treat them as server-only (they read process.env.SESSION_SECRET, hit the DB, etc. — must NOT enter the client bundle): - auth/session.ts → auth/session.server.ts - auth/completion.ts → auth/completion.server.ts - auth/completion.test.ts → auth/completion.server.test.ts Done with `git mv` so blame is preserved. Verified: typecheck + lint green; 126 unit tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
92 lines
3.1 KiB
TypeScript
92 lines
3.1 KiB
TypeScript
import type { Route } from "./+types/api.events";
|
|
import { getSessionUser } from "~/lib/auth/session.server";
|
|
import { register } from "~/lib/events.server";
|
|
import { countUnread } from "~/lib/notifications.server";
|
|
|
|
const HEARTBEAT_INTERVAL_MS = 25_000;
|
|
// Server-suggested EventSource reconnect delay. Browser default is ~3s;
|
|
// 5s + small jitter spreads deploy-storm reconnects without making
|
|
// transient blips feel sluggish.
|
|
const RECONNECT_RETRY_MS = 5_000;
|
|
|
|
/**
|
|
* GET /api/events — Server-Sent Events stream. Session-bound; anonymous
|
|
* visitors get 401. Emits `notifications.unread` events when the
|
|
* user's unread count changes (badge live-update).
|
|
*
|
|
* Initial event on connect carries the current count so the client
|
|
* doesn't have to wait for a state change to render.
|
|
*/
|
|
export async function loader({ request }: Route.LoaderArgs) {
|
|
const user = await getSessionUser(request);
|
|
if (!user) {
|
|
return new Response("Unauthorized", { status: 401 });
|
|
}
|
|
|
|
const userId = user.id;
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
async start(controller) {
|
|
const encoder = new TextEncoder();
|
|
let closed = false;
|
|
|
|
const writeRaw = (chunk: string) => {
|
|
if (closed) return;
|
|
try {
|
|
controller.enqueue(encoder.encode(chunk));
|
|
} catch {
|
|
closed = true;
|
|
}
|
|
};
|
|
|
|
const send = (event: string, data: unknown) => {
|
|
// Per the EventSource spec, multi-line `data:` lines are joined
|
|
// with newlines; JSON-stringifying single-line is enough here.
|
|
writeRaw(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
};
|
|
|
|
const close = () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
try { controller.close(); } catch { /* ignore */ }
|
|
};
|
|
|
|
// Server-suggested reconnect backoff + small jitter so deploy
|
|
// storms don't reconnect everyone simultaneously.
|
|
const jitter = Math.floor(Math.random() * 2000);
|
|
writeRaw(`retry: ${RECONNECT_RETRY_MS + jitter}\n\n`);
|
|
|
|
const unregister = register(userId, { send, close });
|
|
|
|
// Initial state: current unread count, so the client renders
|
|
// correctly without waiting for the first live event.
|
|
const initial = await countUnread(userId);
|
|
send("notifications.unread", { count: initial });
|
|
|
|
// Heartbeat keeps intermediate proxies from killing the idle
|
|
// connection. SSE comments are ignored by the client but keep
|
|
// the bytes flowing.
|
|
const heartbeat = setInterval(() => {
|
|
writeRaw(`: ping\n\n`);
|
|
}, HEARTBEAT_INTERVAL_MS);
|
|
|
|
// Client disconnect → request.signal aborts → close + clean up.
|
|
request.signal.addEventListener("abort", () => {
|
|
clearInterval(heartbeat);
|
|
unregister();
|
|
close();
|
|
});
|
|
},
|
|
});
|
|
|
|
return new Response(stream, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "text/event-stream; charset=utf-8",
|
|
"Cache-Control": "no-cache, no-transform",
|
|
"Connection": "keep-alive",
|
|
// Some intermediate proxies buffer text/event-stream by default
|
|
// unless told otherwise; this is the de-facto opt-out hint.
|
|
"X-Accel-Buffering": "no",
|
|
},
|
|
});
|
|
}
|