singularity-core 0.6.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  # singularity-core
2
2
 
3
- Shared non-UI code for Singularity TanStack Start apps: cookie-based auth
4
- sessions against the Singularity API, openapi-fetch middleware, API error
5
- helpers, paging and theme preference.
3
+ Shared non-UI code for the Singularity TanStack Start apps (filion blog,
4
+ admin, tools, games): cookie-based auth sessions against the Singularity API,
5
+ openapi-fetch middleware and API error helpers, API schema helpers, paging,
6
+ route static data, image URLs, formatting, HTTP helpers, theme preference,
7
+ the cookie notice, SEO, security headers and CSP, and telemetry.
6
8
 
7
9
  ```ts
8
10
  // src/utils/auth/auth.server.ts
@@ -14,3 +16,72 @@ export const { login, logout, getValidSession, hasUserPermission } =
14
16
  ```
15
17
 
16
18
  See [AGENTS.md](./AGENTS.md) for the subpaths and the rules for adding code.
19
+
20
+ ## TODO
21
+
22
+ Fix on `main` and release as 0.9.0 (the `feature/fragments` tarballs already use
23
+ up to 0.8.7), then rebase `feature/fragments`.
24
+
25
+ ### High value
26
+
27
+ - [x] Logout can end the user's sessions on every device. `endApiSession`
28
+ (`src/auth/server.ts:156`) sends `refreshToken: null` when the refresh cookie
29
+ is missing, and `?? refreshToken` (`:241`) keeps an `EMPTY_GUID` from a
30
+ refresh. Treat `EMPTY_GUID` as no token everywhere and skip the API logout
31
+ when there is no real refresh token.
32
+ - [x] Temporary API errors sign users out. A refresh that returns 429 or 5xx
33
+ clears the cookies (`src/auth/server.ts:232-235`), and the `catch` (`:243`)
34
+ returns null even while the access token is still valid. Clear only on
35
+ 400/401/403 and keep the current token while `secondsUntilExpiry > 0`. Add
36
+ tests for both.
37
+ - [x] Cookie roles are decoded, not verified (`src/auth/server.ts:70-93`). Keep it
38
+ decode-only, but document here and in `docs/projects/core.md` that roles are
39
+ a UI hint and the API is the real gate. Audit that every admin and blog
40
+ server function behind `requirePermission` calls the API with the bearer
41
+ token.
42
+ - [x] CSP (`src/security/index.ts:59-76`) lacks `base-uri 'self'`,
43
+ `object-src 'none'` and `form-action 'self'`. Widen `CspDirective` to allow
44
+ `frame-src` and `worker-src`. In the dev policy, browsers ignore
45
+ `'unsafe-inline'` next to a nonce or `'strict-dynamic'`.
46
+ - [x] `useListSearch` (`src/paging/react.ts:14-26`) reapplies the old text after
47
+ Back or a link clears the search. Re-sync `text` when `current` changes from
48
+ outside (track the last applied value in a ref).
49
+ - [x] `build` doesn't clean `dist/`, so `dist/fragments` from the other branch
50
+ would ship in the next pack. Delete `dist` before `tsc`.
51
+ - [x] `formatDate` (`src/format/index.ts:1-14`) uses local getters, so server
52
+ (UTC) and browser (Stockholm) disagree near midnight, and invalid input gives
53
+ `NaN-NaN-NaN`. Use `Intl.DateTimeFormat` with a `timeZone` and return `""`
54
+ for invalid dates.
55
+
56
+ ### Nice to have
57
+
58
+ - [x] `formatTimeSpan` drops days (`src/format/index.ts:32-34`), and the "days
59
+ included" test expects the wrong value.
60
+ - [x] The theme client hint `Sec-CH-Prefers-Color-Scheme` (`src/theme/server.ts:22`)
61
+ is never requested with `Accept-CH`. The server renders "system" as light
62
+ while `ThemeProvider` treats it as dark before mount
63
+ (`src/theme/react.tsx:89`). Make the two defaults agree.
64
+ - [x] `ThemeProvider` reads and writes `localStorage` without a guard
65
+ (`src/theme/react.tsx:98,128`). `buildThemeBootstrapScript`
66
+ (`src/theme/index.ts:63`) puts keys into a JS string and a RegExp unescaped;
67
+ use `JSON.stringify` and escape the regex.
68
+ - [x] `proxyEventStream` (`src/api/server.ts:89-94`) doesn't catch a failed fetch.
69
+ Return 502 with `failureMessage`.
70
+ - [x] Small fixes: `pageSearchSchema` throws on `?page=abc` (add
71
+ `.catch(undefined)`); `parsePage` accepts `take: 0` (use
72
+ `.int().positive()`); `na` returns one shared fallback array; `IMAGE_WIDTHS`
73
+ is mutable; `new URL(src)` throws on relative `/i/` URLs
74
+ (`src/images/index.ts:57,82`); `slugify` drops ø/æ/ß/ł.
75
+ - [x] `getValidSession` isn't cached per request, so beforeLoad, middleware and a
76
+ loader can each refresh. Make cookie `secure` an option instead of reading
77
+ `NODE_ENV`.
78
+ - [x] `engines` pins Node 25, which reached end of life in June 2026. Allow 24 LTS
79
+ and 26.
80
+ - [x] Add `.gitattributes` (`* text=auto eol=lf`). CRLF in `package.json` is why
81
+ `biome check` fails.
82
+ - [x] Add a `check` script that only reports and a `verify` script (typecheck,
83
+ check, test). Add `"./package.json"` to `exports`.
84
+ - [x] No tests for `http` or `router/react`.
85
+ - [x] Docs drift: `AGENTS.md` mentions `pnpm openapi-types`, which isn't in
86
+ `package.json`; it describes both tarballs and publishing without saying
87
+ which is current. This README names 5 of the 13 areas.
@@ -14,7 +14,7 @@ export declare const forwardVisitorIpMiddleware: Middleware;
14
14
  * Forwards a browser POST to an API event-stream endpoint and streams the
15
15
  * answer back, so the API key stays on the server. Passes the visitor's IP,
16
16
  * since the API rate limits per visitor, and aborts upstream when the browser
17
- * disconnects.
17
+ * disconnects. An API that cannot be reached is a 502 with `failureMessage`.
18
18
  */
19
19
  export declare function proxyEventStream({ request, url, apiKey, failureMessage, }: {
20
20
  request: Request;
@@ -56,7 +56,7 @@ const eventStreamHeaders = {
56
56
  * Forwards a browser POST to an API event-stream endpoint and streams the
57
57
  * answer back, so the API key stays on the server. Passes the visitor's IP,
58
58
  * since the API rate limits per visitor, and aborts upstream when the browser
59
- * disconnects.
59
+ * disconnects. An API that cannot be reached is a 502 with `failureMessage`.
60
60
  */
61
61
  export async function proxyEventStream({ request, url, apiKey, failureMessage = "Request failed. Try again.", }) {
62
62
  const headers = {
@@ -68,12 +68,19 @@ export async function proxyEventStream({ request, url, apiKey, failureMessage =
68
68
  if (visitorIp) {
69
69
  headers["X-Forwarded-For"] = visitorIp;
70
70
  }
71
- const upstream = await fetch(url, {
72
- method: "POST",
73
- headers,
74
- body: await request.text(),
75
- signal: request.signal,
76
- });
71
+ let upstream;
72
+ try {
73
+ upstream = await fetch(url, {
74
+ method: "POST",
75
+ headers,
76
+ body: await request.text(),
77
+ signal: request.signal,
78
+ });
79
+ }
80
+ catch {
81
+ // API down, DNS or TLS failure, or the browser went away mid-request.
82
+ return new Response(failureMessage, { status: 502 });
83
+ }
77
84
  if (!upstream.ok || !upstream.body) {
78
85
  const error = await upstream.text().catch(() => "");
79
86
  return new Response(error || failureMessage, {
@@ -25,6 +25,12 @@ export type CookieSessionOptions = {
25
25
  loginRoles?: UserRoles;
26
26
  /** Error message for a login without `loginRoles`. */
27
27
  loginRolesError?: string;
28
+ /**
29
+ * Marks the cookies `Secure`, so browsers send them over HTTPS only.
30
+ * Defaults to true; Chrome and Firefox also keep them on http://localhost.
31
+ * Pass false only for a plain-HTTP setup on another host.
32
+ */
33
+ secure?: boolean;
28
34
  };
29
35
  /** The session plus the refresh token it was read or rotated with (server only). */
30
36
  export type ServerSession = Session & {
@@ -35,7 +41,7 @@ export type ServerSession = Session & {
35
41
  * API itself, so no client code needs the tokens. Call only from server code
36
42
  * (server functions, middleware, loaders' server side).
37
43
  */
38
- export declare function createCookieSession({ client, cookiePrefix, cookiePath, loginRoles, loginRolesError, }: CookieSessionOptions): {
44
+ export declare function createCookieSession({ client, cookiePrefix, cookiePath, loginRoles, loginRolesError, secure, }: CookieSessionOptions): {
39
45
  login: (username: string, password: string) => Promise<import("./index.js").PublicSession | null>;
40
46
  logout: () => Promise<{
41
47
  success: boolean;
@@ -1,4 +1,4 @@
1
- import { getCookie, setCookie } from "@tanstack/react-start/server";
1
+ import { getCookie, getRequest, setCookie } from "@tanstack/react-start/server";
2
2
  import { decodeJwt } from "jose";
3
3
  import createFetchClient from "openapi-fetch";
4
4
  import { getApiErrorMessage } from "../api/index.js";
@@ -18,7 +18,19 @@ export function createAuthClient(options) {
18
18
  const REFRESH_TOKEN_MAX_AGE = 60 * 60 * 24 * 30;
19
19
  /** Refresh when the access token has less than this many seconds left. */
20
20
  const REFRESH_MARGIN_SECONDS = 300;
21
+ /**
22
+ * Refresh answers that mean the API refused the token itself. Anything else
23
+ * (429, 5xx) is temporary and keeps the session.
24
+ */
25
+ const REFRESH_REJECTED_STATUSES = new Set([400, 401, 403]);
21
26
  const EMPTY_GUID = "00000000-0000-0000-0000-000000000000";
27
+ /**
28
+ * A refresh token the API issued, or null. The API sends the empty GUID when
29
+ * there is none, and a logout without a token ends every session of the user.
30
+ */
31
+ function issuedRefreshToken(token) {
32
+ return token && token !== EMPTY_GUID ? token : null;
33
+ }
22
34
  /** Seconds until the JWT expires, so the cookie never outlives the token. */
23
35
  function secondsUntilExpiry(token) {
24
36
  try {
@@ -29,6 +41,14 @@ function secondsUntilExpiry(token) {
29
41
  return 0;
30
42
  }
31
43
  }
44
+ /**
45
+ * Reads the session from the access token without verifying it: the apps do
46
+ * not hold the API's signing key. Its roles are a hint for the UI and for
47
+ * skipping calls that would fail, not a gate, since an edited cookie passes
48
+ * them. The API verifies the token and reads the user's roles from its own
49
+ * database on every call, so anything a role protects must happen in the API,
50
+ * called with this token as the bearer.
51
+ */
32
52
  function toSession(accessToken, userId, refreshToken) {
33
53
  try {
34
54
  const decoded = decodeJwt(accessToken);
@@ -37,7 +57,7 @@ function toSession(accessToken, userId, refreshToken) {
37
57
  return null;
38
58
  return {
39
59
  accessToken,
40
- refreshToken: refreshToken ?? null,
60
+ refreshToken: issuedRefreshToken(refreshToken),
41
61
  id,
42
62
  roles: extractJwtRoles(decoded),
43
63
  username: decoded.unique_name ||
@@ -54,24 +74,48 @@ function toSession(accessToken, userId, refreshToken) {
54
74
  * API itself, so no client code needs the tokens. Call only from server code
55
75
  * (server functions, middleware, loaders' server side).
56
76
  */
57
- export function createCookieSession({ client, cookiePrefix, cookiePath = "/", loginRoles = [], loginRolesError = "Access denied", }) {
77
+ export function createCookieSession({ client, cookiePrefix, cookiePath = "/", loginRoles = [], loginRolesError = "Access denied", secure = true, }) {
58
78
  const accessTokenCookie = `${cookiePrefix}_access_token`;
59
79
  const refreshTokenCookie = `${cookiePrefix}_refresh_token`;
60
80
  const userIdCookie = `${cookiePrefix}_user_id`;
61
81
  function cookieOptions(maxAge) {
62
82
  return {
63
83
  httpOnly: true,
64
- secure: process.env.NODE_ENV === "production",
84
+ secure,
65
85
  sameSite: "lax",
66
86
  path: cookiePath,
67
87
  maxAge,
68
88
  };
69
89
  }
70
- function storeTokens({ accessToken, refreshToken, id }) {
90
+ /**
91
+ * Each request's session, so beforeLoad, middleware and loaders share one
92
+ * read and at most one refresh. The request's cookies still hold the old
93
+ * tokens after a refresh, so reading them again would refresh again.
94
+ */
95
+ const sessions = new WeakMap();
96
+ function currentRequest() {
97
+ try {
98
+ return getRequest();
99
+ }
100
+ catch {
101
+ // Outside a request: nothing to share.
102
+ return undefined;
103
+ }
104
+ }
105
+ /** Makes `session` this request's answer, after a login or logout. */
106
+ function rememberSession(session) {
107
+ const request = currentRequest();
108
+ if (request) {
109
+ sessions.set(request, Promise.resolve(session));
110
+ }
111
+ }
112
+ function storeTokens(tokens) {
113
+ const { accessToken, id } = tokens;
71
114
  if (accessToken) {
72
115
  setCookie(accessTokenCookie, accessToken, cookieOptions(secondsUntilExpiry(accessToken)));
73
116
  }
74
- if (refreshToken && refreshToken !== EMPTY_GUID) {
117
+ const refreshToken = issuedRefreshToken(tokens.refreshToken);
118
+ if (refreshToken) {
75
119
  setCookie(refreshTokenCookie, refreshToken, cookieOptions(REFRESH_TOKEN_MAX_AGE));
76
120
  }
77
121
  if (id) {
@@ -84,10 +128,17 @@ export function createCookieSession({ client, cookiePrefix, cookiePath = "/", lo
84
128
  setCookie(name, "", cookieOptions(0));
85
129
  }
86
130
  }
87
- async function endApiSession(accessToken, refreshToken) {
131
+ /**
132
+ * Ends the API session of this refresh token. Without one there is nothing
133
+ * to end: the API would take a logout without a token as "every device".
134
+ */
135
+ async function endApiSession(accessToken, token) {
136
+ const refreshToken = issuedRefreshToken(token);
137
+ if (!refreshToken)
138
+ return;
88
139
  try {
89
140
  await client.POST("/api/v1/auth/logout", {
90
- body: { refreshToken: refreshToken ?? null },
141
+ body: { refreshToken },
91
142
  headers: { Authorization: `Bearer ${accessToken}` },
92
143
  });
93
144
  }
@@ -109,6 +160,7 @@ export function createCookieSession({ client, cookiePrefix, cookiePath = "/", lo
109
160
  throw new Error(session ? loginRolesError : "Failed to login");
110
161
  }
111
162
  storeTokens(response.data);
163
+ rememberSession(session);
112
164
  return toPublicSession(session);
113
165
  }
114
166
  /** Ends this device's session on the API, then clears the cookies. */
@@ -118,25 +170,43 @@ export function createCookieSession({ client, cookiePrefix, cookiePath = "/", lo
118
170
  await endApiSession(session.accessToken, session.refreshToken);
119
171
  }
120
172
  clearTokens();
173
+ rememberSession(null);
121
174
  return { success: true };
122
175
  }
123
176
  /**
124
177
  * The signed-in session, refreshing the access token when it is close to
125
- * expiring. The API tolerates concurrent refreshes with the same token, so
126
- * parallel SSR requests do not sign the user out.
178
+ * expiring. Read once per request: later calls in the same request, and
179
+ * calls made while the first is refreshing, get the same answer. The API
180
+ * tolerates concurrent refreshes with the same token, so parallel requests
181
+ * do not sign the user out. A refresh that fails for a temporary reason
182
+ * keeps the cookies and the current token while it lasts.
127
183
  */
128
- async function getValidSession() {
184
+ function getValidSession() {
185
+ const request = currentRequest();
186
+ if (!request) {
187
+ return readSession();
188
+ }
189
+ let session = sessions.get(request);
190
+ if (!session) {
191
+ session = readSession();
192
+ sessions.set(request, session);
193
+ }
194
+ return session;
195
+ }
196
+ /** Reads the cookies and refreshes when needed; see `getValidSession`. */
197
+ async function readSession() {
129
198
  const accessToken = getCookie(accessTokenCookie);
130
- const refreshToken = getCookie(refreshTokenCookie) ?? null;
199
+ const refreshToken = issuedRefreshToken(getCookie(refreshTokenCookie));
131
200
  const userId = getCookie(userIdCookie);
132
201
  if (accessToken &&
133
202
  secondsUntilExpiry(accessToken) >= REFRESH_MARGIN_SECONDS) {
134
203
  return toSession(accessToken, userId, refreshToken);
135
204
  }
205
+ const currentSession = () => accessToken && secondsUntilExpiry(accessToken) > 0
206
+ ? toSession(accessToken, userId, refreshToken)
207
+ : null;
136
208
  if (!refreshToken || !userId) {
137
- return accessToken && secondsUntilExpiry(accessToken) > 0
138
- ? toSession(accessToken, userId, refreshToken)
139
- : null;
209
+ return currentSession();
140
210
  }
141
211
  try {
142
212
  const response = await client.POST("/api/v1/auth/refresh", {
@@ -144,15 +214,19 @@ export function createCookieSession({ client, cookiePrefix, cookiePath = "/", lo
144
214
  cache: "no-store",
145
215
  });
146
216
  if (response.error || !response.data?.accessToken) {
147
- clearTokens();
148
- return null;
217
+ if (REFRESH_REJECTED_STATUSES.has(response.response.status)) {
218
+ clearTokens();
219
+ return null;
220
+ }
221
+ // Rate limited or failing: try again on the next request.
222
+ return currentSession();
149
223
  }
150
224
  storeTokens(response.data);
151
- return toSession(response.data.accessToken, userId, response.data.refreshToken ?? refreshToken);
225
+ return toSession(response.data.accessToken, userId, issuedRefreshToken(response.data.refreshToken) ?? refreshToken);
152
226
  }
153
227
  catch {
154
228
  // API unreachable: keep the cookies and try again on the next request.
155
- return null;
229
+ return currentSession();
156
230
  }
157
231
  }
158
232
  async function hasUserPermission(requiredRoles = []) {
@@ -164,6 +238,9 @@ export function createCookieSession({ client, cookiePrefix, cookiePath = "/", lo
164
238
  /**
165
239
  * Throws `Unauthorized` unless the user is signed in with one of
166
240
  * `requiredRoles` (any account when empty). For server function middleware.
241
+ * The roles come from the cookie unverified (see `toSession`), so this only
242
+ * turns away calls early: the handler must still do its work through the
243
+ * API with the session's token, which is the real check.
167
244
  */
168
245
  async function requirePermission(requiredRoles = []) {
169
246
  if (!(await hasUserPermission(requiredRoles))) {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Whether the visitor has dismissed the cookie notice, read from the
3
+ * `cookieName` cookie. The app shows the notice while this is false.
4
+ */
5
+ export declare function isCookieNoticeDismissed(cookieName: string): boolean;
6
+ /**
7
+ * Remembers for a year that the visitor dismissed the cookie notice, on
8
+ * every path of the host so apps sharing it (`/blog`, `/games`, …) show it
9
+ * once. Rename the cookie to show a changed notice to everyone again.
10
+ */
11
+ export declare function dismissCookieNotice(cookieName: string): void;
@@ -0,0 +1,21 @@
1
+ import { getCookie, setCookie } from "@tanstack/react-start/server";
2
+ const DISMISSED = "dismissed";
3
+ /**
4
+ * Whether the visitor has dismissed the cookie notice, read from the
5
+ * `cookieName` cookie. The app shows the notice while this is false.
6
+ */
7
+ export function isCookieNoticeDismissed(cookieName) {
8
+ return getCookie(cookieName) === DISMISSED;
9
+ }
10
+ /**
11
+ * Remembers for a year that the visitor dismissed the cookie notice, on
12
+ * every path of the host so apps sharing it (`/blog`, `/games`, …) show it
13
+ * once. Rename the cookie to show a changed notice to everyone again.
14
+ */
15
+ export function dismissCookieNotice(cookieName) {
16
+ setCookie(cookieName, DISMISSED, {
17
+ path: "/",
18
+ maxAge: 60 * 60 * 24 * 365,
19
+ sameSite: "lax",
20
+ });
21
+ }
@@ -1,8 +1,15 @@
1
- /** `YYYY-MM-DD` in local time, or "" without a date. */
2
- export declare function formatDate(dateInput: string | Date | null | undefined): string;
3
1
  /**
4
- * Minutes in a .NET `TimeSpan` string (`d.hh:mm:ss` or `hh:mm:ss`), e.g.
5
- * "7 min", or "< 1 min" for less than a minute.
2
+ * `YYYY-MM-DD` of the day in `timeZone` (Stockholm unless given), so the
3
+ * server and the browser agree whatever zone each runs in. "" without a
4
+ * valid date.
5
+ */
6
+ export declare function formatDate(dateInput: string | Date | null | undefined, { timeZone }?: {
7
+ timeZone?: string;
8
+ }): string;
9
+ /**
10
+ * Whole minutes in a .NET `TimeSpan` string (`d.hh:mm:ss` or `hh:mm:ss`),
11
+ * days included, e.g. "7 min", or "< 1 min" for less than a minute. "" when
12
+ * the string is not a `TimeSpan`.
6
13
  */
7
14
  export declare function formatTimeSpan(timeSpan: string | undefined | null): string;
8
15
  /** File size for people: "1.2 MB", "340 KB". */
@@ -1,40 +1,52 @@
1
- /** `YYYY-MM-DD` in local time, or "" without a date. */
2
- export function formatDate(dateInput) {
1
+ /** filion.se is a Swedish site, so its days start at midnight in Stockholm. */
2
+ const DEFAULT_TIME_ZONE = "Europe/Stockholm";
3
+ const dayFormats = new Map();
4
+ /** One formatter per time zone; building them is slow. */
5
+ function dayFormat(timeZone) {
6
+ let format = dayFormats.get(timeZone);
7
+ if (!format) {
8
+ format = new Intl.DateTimeFormat("en-US", {
9
+ timeZone,
10
+ year: "numeric",
11
+ month: "2-digit",
12
+ day: "2-digit",
13
+ });
14
+ dayFormats.set(timeZone, format);
15
+ }
16
+ return format;
17
+ }
18
+ /**
19
+ * `YYYY-MM-DD` of the day in `timeZone` (Stockholm unless given), so the
20
+ * server and the browser agree whatever zone each runs in. "" without a
21
+ * valid date.
22
+ */
23
+ export function formatDate(dateInput, { timeZone = DEFAULT_TIME_ZONE } = {}) {
3
24
  if (!dateInput) {
4
25
  return "";
5
26
  }
6
27
  const date = new Date(dateInput);
7
- const year = date.getFullYear();
8
- const month = String(date.getMonth() + 1).padStart(2, "0");
9
- const day = String(date.getDate()).padStart(2, "0");
10
- return `${year}-${month}-${day}`;
28
+ if (Number.isNaN(date.getTime())) {
29
+ return "";
30
+ }
31
+ const parts = Object.fromEntries(dayFormat(timeZone)
32
+ .formatToParts(date)
33
+ .map(({ type, value }) => [type, value]));
34
+ return `${parts.year}-${parts.month}-${parts.day}`;
11
35
  }
36
+ /** .NET's `TimeSpan` text: `[d.]hh:mm[:ss[.fffffff]]`. */
37
+ const TIME_SPAN = /^(?:(\d+)\.)?(\d+):(\d+)(?::\d+(?:\.\d+)?)?$/;
12
38
  /**
13
- * Minutes in a .NET `TimeSpan` string (`d.hh:mm:ss` or `hh:mm:ss`), e.g.
14
- * "7 min", or "< 1 min" for less than a minute.
39
+ * Whole minutes in a .NET `TimeSpan` string (`d.hh:mm:ss` or `hh:mm:ss`),
40
+ * days included, e.g. "7 min", or "< 1 min" for less than a minute. "" when
41
+ * the string is not a `TimeSpan`.
15
42
  */
16
43
  export function formatTimeSpan(timeSpan) {
17
- if (!timeSpan)
18
- return "";
19
- const parts = timeSpan.split(":");
20
- if (parts.length < 2)
21
- return "";
22
- const firstPart = parts[0];
23
- const secondPart = parts[1];
24
- if (!firstPart || !secondPart)
25
- return "";
26
- // Handle days if present (d.hh)
27
- const hoursPart = firstPart.includes(".")
28
- ? firstPart.split(".")[1]
29
- : firstPart;
30
- if (!hoursPart)
44
+ const match = timeSpan ? TIME_SPAN.exec(timeSpan) : null;
45
+ if (!match)
31
46
  return "";
32
- const minutes = parseInt(secondPart, 10);
33
- const hours = parseInt(hoursPart, 10);
34
- const totalMinutes = hours * 60 + minutes;
35
- if (totalMinutes === 0)
36
- return "< 1 min";
37
- return `${totalMinutes} min`;
47
+ const [, days = "0", hours, minutes] = match;
48
+ const totalMinutes = (Number(days) * 24 + Number(hours)) * 60 + Number(minutes);
49
+ return totalMinutes === 0 ? "< 1 min" : `${totalMinutes} min`;
38
50
  }
39
51
  /** File size for people: "1.2 MB", "340 KB". */
40
52
  export function formatFileSize(bytes) {
@@ -42,6 +54,17 @@ export function formatFileSize(bytes) {
42
54
  return `${(bytes / 1_000_000).toFixed(1)} MB`;
43
55
  return `${Math.max(1, Math.round(bytes / 1000))} KB`;
44
56
  }
57
+ /** Letters with no accent for NFD to strip, spelled as they usually are in Latin. */
58
+ const SLUG_LETTERS = {
59
+ ø: "o",
60
+ æ: "ae",
61
+ œ: "oe",
62
+ ß: "ss",
63
+ ł: "l",
64
+ đ: "d",
65
+ ð: "d",
66
+ þ: "th",
67
+ };
45
68
  /** URL slug for a display name: accents dropped, lowercase, dashes. */
46
69
  export function slugify(name) {
47
70
  return name
@@ -49,6 +72,7 @@ export function slugify(name) {
49
72
  .replace(/\p{M}/gu, "")
50
73
  .trim()
51
74
  .toLowerCase()
75
+ .replace(/[øæœßłđðþ]/g, (letter) => SLUG_LETTERS[letter] ?? "")
52
76
  .replace(/[^a-z0-9]+/g, "-")
53
77
  .replace(/^-+|-+$/g, "");
54
78
  }
@@ -4,16 +4,17 @@
4
4
  * step with `ImageTransformOptions` in the webapi.
5
5
  */
6
6
  /** Widths the image endpoint renders. */
7
- export declare const IMAGE_WIDTHS: number[];
7
+ export declare const IMAGE_WIDTHS: readonly number[];
8
8
  /** True for a versioned Filion image URL that can be resized. */
9
9
  export declare function isFilionImage(src: string | URL | undefined): boolean;
10
10
  /**
11
11
  * Returns `src` asking for `width` × `height`. Both are optional; without a
12
12
  * height the image keeps its own aspect ratio. Sizes snap to what the API
13
- * renders, so any width and a near-allowed ratio still load.
13
+ * renders, so any width and a near-allowed ratio still load. A relative `src`
14
+ * gives a relative URL back.
14
15
  */
15
16
  export declare function withImageSize(src: string | URL, width?: number, height?: number, format?: "webp" | "jpg"): string;
16
- /** The `w` and `h` already in a Filion image URL. */
17
+ /** The `w` and `h` already in a Filion image URL, absolute or relative. */
17
18
  export declare function getImageUrlSize(src: string): {
18
19
  width?: number;
19
20
  height?: number;
@@ -4,19 +4,34 @@
4
4
  * step with `ImageTransformOptions` in the webapi.
5
5
  */
6
6
  /** Widths the image endpoint renders. */
7
- export const IMAGE_WIDTHS = [
7
+ export const IMAGE_WIDTHS = Object.freeze([
8
8
  320, 480, 640, 800, 960, 1200, 1280, 1600, 1920, 2560,
9
- ];
9
+ ]);
10
10
  /** Width / height ratios the image endpoint crops to. */
11
11
  const IMAGE_ASPECTS = [16 / 9, 16 / 10, 4 / 3, 3 / 2, 1, 1200 / 630];
12
12
  // Production serves /i/…, the API itself /api/public/i/… (local dev).
13
13
  const FILION_IMAGE_PATH = /\/(?:api\/public\/)?i\/\d+\.(?:webp|jpg)$/;
14
+ const RELATIVE_BASE = "http://relative.invalid";
15
+ /** Parses an absolute URL, or a relative one such as `/i/42.webp?v=…`. */
16
+ function parseImageUrl(src) {
17
+ const text = src.toString();
18
+ try {
19
+ return { url: new URL(text), relative: false };
20
+ }
21
+ catch {
22
+ return { url: new URL(text, RELATIVE_BASE), relative: true };
23
+ }
24
+ }
25
+ /** `url` written the way it came in: absolute, or from the path on. */
26
+ function formatImageUrl(url, relative) {
27
+ return relative ? `${url.pathname}${url.search}${url.hash}` : url.toString();
28
+ }
14
29
  /** True for a versioned Filion image URL that can be resized. */
15
30
  export function isFilionImage(src) {
16
31
  if (!src)
17
32
  return false;
18
33
  try {
19
- const url = new URL(src.toString());
34
+ const { url } = parseImageUrl(src);
20
35
  return FILION_IMAGE_PATH.test(url.pathname) && url.searchParams.has("v");
21
36
  }
22
37
  catch {
@@ -35,28 +50,29 @@ function snapAspect(ratio) {
35
50
  /**
36
51
  * Returns `src` asking for `width` × `height`. Both are optional; without a
37
52
  * height the image keeps its own aspect ratio. Sizes snap to what the API
38
- * renders, so any width and a near-allowed ratio still load.
53
+ * renders, so any width and a near-allowed ratio still load. A relative `src`
54
+ * gives a relative URL back.
39
55
  */
40
56
  export function withImageSize(src, width, height, format) {
41
- const url = new URL(src.toString());
57
+ const { url, relative } = parseImageUrl(src);
42
58
  url.searchParams.delete("w");
43
59
  url.searchParams.delete("h");
44
60
  if (format) {
45
61
  url.pathname = url.pathname.replace(/\.(?:webp|jpg)$/, `.${format}`);
46
62
  }
47
63
  if (!width)
48
- return url.toString();
64
+ return formatImageUrl(url, relative);
49
65
  const snappedWidth = snapWidth(width);
50
66
  url.searchParams.set("w", String(snappedWidth));
51
67
  if (height) {
52
68
  const ratio = snapAspect(width / height);
53
69
  url.searchParams.set("h", String(Math.round(snappedWidth / ratio)));
54
70
  }
55
- return url.toString();
71
+ return formatImageUrl(url, relative);
56
72
  }
57
- /** The `w` and `h` already in a Filion image URL. */
73
+ /** The `w` and `h` already in a Filion image URL, absolute or relative. */
58
74
  export function getImageUrlSize(src) {
59
- const url = new URL(src);
75
+ const { url } = parseImageUrl(src);
60
76
  const width = Number(url.searchParams.get("w")) || undefined;
61
77
  const height = Number(url.searchParams.get("h")) || undefined;
62
78
  return { width, height };
@@ -74,7 +90,7 @@ export function filionTransformer(src, operations) {
74
90
  */
75
91
  export function getImageBreakpoints(width, layout) {
76
92
  if (layout === "fullWidth" || !width)
77
- return IMAGE_WIDTHS;
93
+ return [...IMAGE_WIDTHS];
78
94
  const max = snapWidth(width * 2);
79
95
  return IMAGE_WIDTHS.filter((candidate) => candidate <= max);
80
96
  }
@@ -30,9 +30,11 @@ export declare function toListParams(query: ListQuery): {
30
30
  };
31
31
  /**
32
32
  * `?page=&search=` for server-paged lists. `page` is zero-based and omitted on
33
- * the first page; `search` filters the whole list on the API.
33
+ * the first page; `search` filters the whole list on the API. A value that
34
+ * does not fit (`?page=abc`, a hand-typed `?search=2026`, which the router
35
+ * reads as a number) is dropped instead of failing the route.
34
36
  */
35
37
  export declare const pageSearchSchema: z.ZodObject<{
36
- page: z.ZodOptional<z.ZodNumber>;
37
- search: z.ZodOptional<z.ZodString>;
38
+ page: z.ZodCatch<z.ZodOptional<z.ZodNumber>>;
39
+ search: z.ZodCatch<z.ZodOptional<z.ZodString>>;
38
40
  }, z.core.$strip>;
@@ -8,9 +8,10 @@ export function parsePage(label, schema, data) {
8
8
  const parsed = z
9
9
  .object({
10
10
  items: z.array(schema),
11
- total: z.number(),
12
- page: z.number(),
13
- take: z.number(),
11
+ total: z.number().int().min(0),
12
+ page: z.number().int().min(0),
13
+ // pageCount divides by it.
14
+ take: z.number().int().positive(),
14
15
  })
15
16
  .safeParse(data);
16
17
  if (!parsed.success) {
@@ -34,9 +35,11 @@ export function toListParams(query) {
34
35
  }
35
36
  /**
36
37
  * `?page=&search=` for server-paged lists. `page` is zero-based and omitted on
37
- * the first page; `search` filters the whole list on the API.
38
+ * the first page; `search` filters the whole list on the API. A value that
39
+ * does not fit (`?page=abc`, a hand-typed `?search=2026`, which the router
40
+ * reads as a number) is dropped instead of failing the route.
38
41
  */
39
42
  export const pageSearchSchema = z.object({
40
- page: z.number().int().min(0).optional(),
41
- search: z.string().optional(),
43
+ page: z.number().int().min(0).optional().catch(undefined),
44
+ search: z.string().optional().catch(undefined),
42
45
  });
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Search box state for a server-searched list (see `pageSearchSchema`). Returns the text being typed and
3
3
  * its setter; once typing pauses, `apply` gets the trimmed text (undefined when
4
- * empty) so the route can put it in the URL and reload from the API.
4
+ * empty) so the route can put it in the URL and reload from the API. When
5
+ * `current` changes from outside (Back, a link that clears the search), the
6
+ * text follows it instead of being applied again.
5
7
  */
6
8
  export declare function useListSearch(current: string | undefined, apply: (search: string | undefined) => void): readonly [string, import("react").Dispatch<import("react").SetStateAction<string>>];
@@ -3,17 +3,30 @@ const SEARCH_DEBOUNCE_MS = 300;
3
3
  /**
4
4
  * Search box state for a server-searched list (see `pageSearchSchema`). Returns the text being typed and
5
5
  * its setter; once typing pauses, `apply` gets the trimmed text (undefined when
6
- * empty) so the route can put it in the URL and reload from the API.
6
+ * empty) so the route can put it in the URL and reload from the API. When
7
+ * `current` changes from outside (Back, a link that clears the search), the
8
+ * text follows it instead of being applied again.
7
9
  */
8
10
  export function useListSearch(current, apply) {
9
11
  const [text, setText] = useState(current ?? "");
10
12
  const applyRef = useRef(apply);
11
13
  applyRef.current = apply;
14
+ // The search this hook last applied, or last took from `current`.
15
+ const appliedRef = useRef(current);
16
+ useEffect(() => {
17
+ if (current === appliedRef.current)
18
+ return;
19
+ appliedRef.current = current;
20
+ setText(current ?? "");
21
+ }, [current]);
12
22
  useEffect(() => {
13
23
  const trimmed = text.trim() || undefined;
14
24
  if (trimmed === current)
15
25
  return;
16
- const timer = setTimeout(() => applyRef.current(trimmed), SEARCH_DEBOUNCE_MS);
26
+ const timer = setTimeout(() => {
27
+ appliedRef.current = trimmed;
28
+ applyRef.current(trimmed);
29
+ }, SEARCH_DEBOUNCE_MS);
17
30
  return () => clearTimeout(timer);
18
31
  }, [text, current]);
19
32
  return [text, setText];
@@ -18,7 +18,8 @@ export const nb = (fallback = false) => z
18
18
  export const na = (item, fallback = []) => z
19
19
  .array(item)
20
20
  .nullish()
21
- .transform((val) => val ?? fallback);
21
+ // A copy per parse, so no two results share (and mutate) one array.
22
+ .transform((val) => val ?? [...fallback]);
22
23
  export function buildSchema(fields) {
23
24
  return z.object(fields);
24
25
  }
@@ -9,18 +9,23 @@ export type SecurityTxtOptions = {
9
9
  };
10
10
  /** Plain-text security contact file per RFC 9116. Serve with `plainTextResponse`. */
11
11
  export declare function buildSecurityTxt({ contact, expires, canonical, preferredLanguages, }: SecurityTxtOptions): string;
12
- type CspDirective = "default-src" | "script-src" | "style-src" | "img-src" | "font-src" | "media-src" | "connect-src" | "frame-ancestors";
12
+ /** Directives an app can add sources to. */
13
+ type CspDirective = "default-src" | "script-src" | "style-src" | "img-src" | "font-src" | "media-src" | "connect-src" | "frame-src" | "worker-src" | "frame-ancestors";
13
14
  export type ContentSecurityPolicyOptions = {
14
15
  /** Per-request nonce; inline scripts must carry it. */
15
16
  nonce: string;
16
- /** Dev servers need inline and eval scripts for HMR. */
17
+ /**
18
+ * Dev servers need eval for HMR. Inline scripts still need the nonce there:
19
+ * browsers ignore `'unsafe-inline'` next to a nonce or `'strict-dynamic'`.
20
+ */
17
21
  dev: boolean;
18
22
  /** Sources added after the defaults, e.g. a font host for `font-src`. */
19
23
  extraSources?: Partial<Record<CspDirective, string[]>>;
20
24
  };
21
25
  /**
22
- * Content-Security-Policy header value. Production uses the nonce with
23
- * `strict-dynamic` (no unsafe-inline / unsafe-eval in script-src).
26
+ * Content-Security-Policy header value. Scripts need the nonce, or a nonced
27
+ * script that loads them (`strict-dynamic`); dev only adds `unsafe-eval`.
28
+ * Frames and workers come from this origin unless the app adds a source.
24
29
  */
25
30
  export declare function buildContentSecurityPolicy({ nonce, dev, extraSources, }: ContentSecurityPolicyOptions): string;
26
31
  /**
@@ -12,31 +12,43 @@ export function buildSecurityTxt({ contact, expires, canonical, preferredLanguag
12
12
  ].join("\n");
13
13
  }
14
14
  /**
15
- * Content-Security-Policy header value. Production uses the nonce with
16
- * `strict-dynamic` (no unsafe-inline / unsafe-eval in script-src).
15
+ * Directives no app extends: no `<base>` pointing relative URLs elsewhere, no
16
+ * plugins, and forms post only to this origin.
17
+ */
18
+ const FIXED_DIRECTIVES = [
19
+ "base-uri 'self'",
20
+ "object-src 'none'",
21
+ "form-action 'self'",
22
+ ];
23
+ /**
24
+ * Content-Security-Policy header value. Scripts need the nonce, or a nonced
25
+ * script that loads them (`strict-dynamic`); dev only adds `unsafe-eval`.
26
+ * Frames and workers come from this origin unless the app adds a source.
17
27
  */
18
28
  export function buildContentSecurityPolicy({ nonce, dev, extraSources = {}, }) {
19
29
  const directives = {
20
30
  "default-src": ["'self'"],
21
- "script-src": dev
22
- ? [
23
- "'self'",
24
- "'unsafe-inline'",
25
- "'unsafe-eval'",
26
- "'strict-dynamic'",
27
- `'nonce-${nonce}'`,
28
- ]
29
- : ["'self'", "'strict-dynamic'", `'nonce-${nonce}'`],
31
+ "script-src": [
32
+ "'self'",
33
+ ...(dev ? ["'unsafe-eval'"] : []),
34
+ "'strict-dynamic'",
35
+ `'nonce-${nonce}'`,
36
+ ],
30
37
  "style-src": ["'self'", "'unsafe-inline'"],
31
38
  "img-src": ["'self'", "data:", "blob:", "https:"],
32
39
  "font-src": ["'self'", "data:"],
33
40
  "media-src": ["'self'"],
34
41
  "connect-src": ["'self'", "https:"],
42
+ "frame-src": ["'self'"],
43
+ // Set, so workers do not fall back to script-src and its
44
+ // 'strict-dynamic' rules: this origin, plus what the app adds.
45
+ "worker-src": ["'self'"],
35
46
  "frame-ancestors": ["'self'"],
36
47
  };
37
- return Object.entries(directives)
38
- .map(([name, sources]) => [name, ...sources, ...(extraSources[name] ?? [])].join(" "))
39
- .join("; ");
48
+ return [
49
+ ...Object.entries(directives).map(([name, sources]) => [name, ...sources, ...(extraSources[name] ?? [])].join(" ")),
50
+ ...FIXED_DIRECTIVES,
51
+ ].join("; ");
40
52
  }
41
53
  /**
42
54
  * Response headers every page should send: HSTS, framing, sniffing, referrer
@@ -10,6 +10,21 @@ export type ThemeContext = {
10
10
  theme: Theme;
11
11
  isDark: boolean;
12
12
  };
13
+ /**
14
+ * Whether a `system` preference shows dark while the OS preference is
15
+ * unknown: on the server without the client hint, and in `ThemeProvider`
16
+ * before mount. One value for both, so the server's markup and the first
17
+ * client render agree. The bootstrap script corrects the page before paint.
18
+ */
19
+ export declare const SYSTEM_DARK_WHEN_UNKNOWN = false;
20
+ /**
21
+ * Response headers asking the browser to send `Sec-CH-Prefers-Color-Scheme`
22
+ * on later requests, so `getThemeContext` can render a `system` preference
23
+ * on the server. Chromium browsers send it; others, and every first visit
24
+ * (no `Critical-CH`, which would cost a retried request), fall back to
25
+ * `SYSTEM_DARK_WHEN_UNKNOWN`. Spread into the root route's `headers`.
26
+ */
27
+ export declare function themeClientHintHeaders(): Record<string, string>;
13
28
  /**
14
29
  * Resolves whether dark mode should be active for a preference and OS hint.
15
30
  */
@@ -29,6 +44,8 @@ export declare function applyDarkClass(isDark: boolean): void;
29
44
  /**
30
45
  * Inline script for first paint when preference is `system` (or legacy localStorage-only).
31
46
  * `storageKey` is both the localStorage key and the cookie name unless
32
- * `cookieKey` is given. Logic must stay aligned with {@link resolveIsDark}.
47
+ * `cookieKey` is given. Any text works as a key: both are quoted, and the
48
+ * cookie name is matched literally. Blocked storage falls back to the cookie.
49
+ * Logic must stay aligned with {@link resolveIsDark}.
33
50
  */
34
51
  export declare function buildThemeBootstrapScript(storageKey: string, cookieKey?: string): string;
@@ -1,5 +1,23 @@
1
1
  import { z } from "zod";
2
2
  export const ThemeSchema = z.enum(["dark", "light", "system"]);
3
+ /**
4
+ * Whether a `system` preference shows dark while the OS preference is
5
+ * unknown: on the server without the client hint, and in `ThemeProvider`
6
+ * before mount. One value for both, so the server's markup and the first
7
+ * client render agree. The bootstrap script corrects the page before paint.
8
+ */
9
+ export const SYSTEM_DARK_WHEN_UNKNOWN = false;
10
+ const COLOR_SCHEME_HINT = "Sec-CH-Prefers-Color-Scheme";
11
+ /**
12
+ * Response headers asking the browser to send `Sec-CH-Prefers-Color-Scheme`
13
+ * on later requests, so `getThemeContext` can render a `system` preference
14
+ * on the server. Chromium browsers send it; others, and every first visit
15
+ * (no `Critical-CH`, which would cost a retried request), fall back to
16
+ * `SYSTEM_DARK_WHEN_UNKNOWN`. Spread into the root route's `headers`.
17
+ */
18
+ export function themeClientHintHeaders() {
19
+ return { "Accept-CH": COLOR_SCHEME_HINT, Vary: COLOR_SCHEME_HINT };
20
+ }
3
21
  /**
4
22
  * Resolves whether dark mode should be active for a preference and OS hint.
5
23
  */
@@ -36,11 +54,26 @@ export function applyDarkClass(isDark) {
36
54
  root.classList.remove("dark");
37
55
  }
38
56
  }
57
+ /**
58
+ * A JS string literal for an inline `<script>`: JSON-quoted, with `<`
59
+ * escaped so the text can never close the script tag.
60
+ */
61
+ function scriptString(text) {
62
+ return JSON.stringify(text).replaceAll("<", "\\u003c");
63
+ }
64
+ /** `text` matched literally inside a RegExp. */
65
+ function escapeRegExp(text) {
66
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
67
+ }
39
68
  /**
40
69
  * Inline script for first paint when preference is `system` (or legacy localStorage-only).
41
70
  * `storageKey` is both the localStorage key and the cookie name unless
42
- * `cookieKey` is given. Logic must stay aligned with {@link resolveIsDark}.
71
+ * `cookieKey` is given. Any text works as a key: both are quoted, and the
72
+ * cookie name is matched literally. Blocked storage falls back to the cookie.
73
+ * Logic must stay aligned with {@link resolveIsDark}.
43
74
  */
44
75
  export function buildThemeBootstrapScript(storageKey, cookieKey = storageKey) {
45
- return `(function(){try{var k='${storageKey}',c='${cookieKey}';var t=localStorage.getItem(k);if(!t){var m=document.cookie.match(new RegExp('(?:^|; )'+c+'=([^;]*)'));t=m?decodeURIComponent(m[1]):null}var p=(!t||t==='system')&&window.matchMedia('(prefers-color-scheme: dark)').matches;var d=t==='dark'||p;if(d)document.documentElement.classList.add('dark');else document.documentElement.classList.remove('dark')}catch(e){}})();`;
76
+ const k = scriptString(storageKey);
77
+ const cookiePattern = scriptString(`(?:^|; )${escapeRegExp(cookieKey)}=([^;]*)`);
78
+ return `(function(){try{var t=null;try{t=localStorage.getItem(${k})}catch(e){}if(!t){var m=document.cookie.match(new RegExp(${cookiePattern}));t=m?decodeURIComponent(m[1]):null}var p=(!t||t==='system')&&window.matchMedia('(prefers-color-scheme: dark)').matches;var d=t==='dark'||p;if(d)document.documentElement.classList.add('dark');else document.documentElement.classList.remove('dark')}catch(e){}})();`;
46
79
  }
@@ -3,6 +3,12 @@ import { type Theme } from "./index.js";
3
3
  type ThemeProviderProps = {
4
4
  children: React.ReactNode;
5
5
  initialTheme: Theme;
6
+ /**
7
+ * What the server showed (`ThemeContext.isDark`), kept until mount so the
8
+ * first client render matches it. Defaults to `SYSTEM_DARK_WHEN_UNKNOWN`
9
+ * for a `system` preference, the server's own guess without the hint.
10
+ */
11
+ initialIsDark?: boolean;
6
12
  /** localStorage key; use the same name as the theme cookie. */
7
13
  storageKey: string;
8
14
  /** Saves the preference for SSR, normally a server function setting the cookie. */
@@ -10,15 +16,27 @@ type ThemeProviderProps = {
10
16
  onResolvedIsDarkChange?: (isDark: boolean) => void;
11
17
  };
12
18
  type ThemeProviderState = {
19
+ /** The preference: light, dark or system. */
13
20
  theme: Theme;
21
+ /** Saves a preference (localStorage + `persistTheme`) and applies it. */
14
22
  setTheme: (theme: Theme) => void;
23
+ /** Switches to the opposite of what is shown, saved as an explicit preference. */
24
+ toggleTheme: () => void;
25
+ /**
26
+ * What is shown. Before mount a `system` preference reads as the server
27
+ * showed it (`initialIsDark`), since only the browser knows the OS
28
+ * preference.
29
+ */
30
+ resolvedTheme: "light" | "dark";
31
+ /** False on the server and the first client render, so their markup matches. */
32
+ mounted: boolean;
15
33
  };
16
34
  /**
17
35
  * Manages theme preference (localStorage + cookie) and syncs the `dark` class on `<html>`.
18
36
  */
19
- export declare function ThemeProvider({ children, initialTheme, storageKey, persistTheme, onResolvedIsDarkChange, }: ThemeProviderProps): React.JSX.Element;
37
+ export declare function ThemeProvider({ children, initialTheme, initialIsDark, storageKey, persistTheme, onResolvedIsDarkChange, }: ThemeProviderProps): React.JSX.Element;
20
38
  /**
21
- * Hook to access the current theme and setTheme function.
39
+ * Hook to access the theme preference, the theme shown, and the setters.
22
40
  */
23
41
  export declare const useTheme: () => ThemeProviderState;
24
42
  export {};
@@ -1,24 +1,70 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import * as React from "react";
3
- import { applyDarkClass, resolveIsDark, ThemeSchema, } from "./index.js";
3
+ import { applyDarkClass, resolveIsDark, SYSTEM_DARK_WHEN_UNKNOWN, ThemeSchema, } from "./index.js";
4
4
  const initialState = {
5
5
  theme: "system",
6
6
  setTheme: () => null,
7
+ toggleTheme: () => null,
8
+ resolvedTheme: SYSTEM_DARK_WHEN_UNKNOWN ? "dark" : "light",
9
+ mounted: false,
7
10
  };
8
- const ThemeProviderContext = React.createContext(initialState);
11
+ /**
12
+ * One context for every copy of this module. TanStack Start bundles this
13
+ * package into the app's server code (it peers on `@tanstack/react-start`)
14
+ * but bundles `singularity-components`, whose header reads this context,
15
+ * separately with its own copy of this file. A context per copy would leave
16
+ * the server-rendered header outside the app's `ThemeProvider`.
17
+ */
18
+ function sharedThemeContext() {
19
+ const key = Symbol.for("singularity-core/theme/react");
20
+ const registry = globalThis;
21
+ const existing = registry[key];
22
+ if (existing) {
23
+ return existing;
24
+ }
25
+ const context = React.createContext(initialState);
26
+ registry[key] = context;
27
+ return context;
28
+ }
29
+ const ThemeProviderContext = sharedThemeContext();
30
+ const PREFERS_DARK_QUERY = "(prefers-color-scheme: dark)";
9
31
  function getSystemPrefersDark() {
10
- return window.matchMedia("(prefers-color-scheme: dark)").matches;
32
+ return window.matchMedia(PREFERS_DARK_QUERY).matches;
33
+ }
34
+ /** The stored preference, or null when storage is empty or blocked (private mode, disabled site data). */
35
+ function readStoredTheme(storageKey) {
36
+ try {
37
+ return localStorage.getItem(storageKey);
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ /** Stores the preference when storage allows; the cookie from `persistTheme` carries it either way. */
44
+ function storeTheme(storageKey, theme) {
45
+ try {
46
+ localStorage.setItem(storageKey, theme);
47
+ }
48
+ catch {
49
+ // Blocked or full.
50
+ }
11
51
  }
12
52
  /**
13
53
  * Manages theme preference (localStorage + cookie) and syncs the `dark` class on `<html>`.
14
54
  */
15
- export function ThemeProvider({ children, initialTheme, storageKey, persistTheme, onResolvedIsDarkChange, }) {
55
+ export function ThemeProvider({ children, initialTheme, initialIsDark = SYSTEM_DARK_WHEN_UNKNOWN, storageKey, persistTheme, onResolvedIsDarkChange, }) {
16
56
  const [theme, setThemeState] = React.useState(initialTheme);
17
- // Latest callback without re-running the effects below when it changes.
57
+ // The OS preference; undefined until mounted.
58
+ const [systemPrefersDark, setSystemPrefersDark] = React.useState(undefined);
59
+ const mounted = systemPrefersDark !== undefined;
60
+ const isDark = resolveIsDark(theme, systemPrefersDark ?? initialIsDark);
61
+ // Latest callbacks without re-running the effects below when they change.
18
62
  const persistRef = React.useRef(persistTheme);
19
63
  persistRef.current = persistTheme;
64
+ const onResolvedIsDarkChangeRef = React.useRef(onResolvedIsDarkChange);
65
+ onResolvedIsDarkChangeRef.current = onResolvedIsDarkChange;
20
66
  React.useEffect(() => {
21
- const storedTheme = localStorage.getItem(storageKey);
67
+ const storedTheme = readStoredTheme(storageKey);
22
68
  if (!storedTheme) {
23
69
  return;
24
70
  }
@@ -28,34 +74,39 @@ export function ThemeProvider({ children, initialTheme, storageKey, persistTheme
28
74
  void persistRef.current(parsed.data);
29
75
  }
30
76
  }, [storageKey, initialTheme]);
31
- const applyResolvedTheme = React.useCallback((nextTheme) => {
32
- const isDark = resolveIsDark(nextTheme, getSystemPrefersDark());
33
- applyDarkClass(isDark);
34
- onResolvedIsDarkChange?.(isDark);
35
- }, [onResolvedIsDarkChange]);
36
77
  React.useEffect(() => {
37
- applyResolvedTheme(theme);
38
- }, [theme, applyResolvedTheme]);
78
+ const media = window.matchMedia(PREFERS_DARK_QUERY);
79
+ const onChange = () => setSystemPrefersDark(media.matches);
80
+ onChange();
81
+ media.addEventListener("change", onChange);
82
+ return () => media.removeEventListener("change", onChange);
83
+ }, []);
84
+ // Until mount, the class is the one the server or the bootstrap script set.
39
85
  React.useEffect(() => {
40
- if (theme !== "system") {
86
+ if (!mounted) {
41
87
  return;
42
88
  }
43
- const media = window.matchMedia("(prefers-color-scheme: dark)");
44
- const onChange = () => applyResolvedTheme("system");
45
- media.addEventListener("change", onChange);
46
- return () => media.removeEventListener("change", onChange);
47
- }, [theme, applyResolvedTheme]);
48
- const value = React.useMemo(() => ({
49
- theme,
50
- setTheme: (newTheme) => {
51
- localStorage.setItem(storageKey, newTheme);
89
+ applyDarkClass(isDark);
90
+ onResolvedIsDarkChangeRef.current?.(isDark);
91
+ }, [mounted, isDark]);
92
+ const value = React.useMemo(() => {
93
+ const setTheme = (newTheme) => {
94
+ storeTheme(storageKey, newTheme);
52
95
  void persistRef.current(newTheme);
53
96
  setThemeState(newTheme);
54
- },
55
- }), [theme, storageKey]);
97
+ };
98
+ return {
99
+ theme,
100
+ setTheme,
101
+ // Reads the OS preference now, in case it is clicked before mount.
102
+ toggleTheme: () => setTheme(resolveIsDark(theme, getSystemPrefersDark()) ? "light" : "dark"),
103
+ resolvedTheme: isDark ? "dark" : "light",
104
+ mounted,
105
+ };
106
+ }, [theme, storageKey, isDark, mounted]);
56
107
  return (_jsx(ThemeProviderContext.Provider, { value: value, children: children }));
57
108
  }
58
109
  /**
59
- * Hook to access the current theme and setTheme function.
110
+ * Hook to access the theme preference, the theme shown, and the setters.
60
111
  */
61
112
  export const useTheme = () => React.useContext(ThemeProviderContext);
@@ -1,7 +1,9 @@
1
1
  import { type Theme, type ThemeContext } from "./index.js";
2
2
  /**
3
3
  * Reads theme preference from the `cookieName` cookie and resolves dark mode
4
- * for SSR. Uses `Sec-CH-Prefers-Color-Scheme` when preference is `system`.
4
+ * for SSR. For a `system` preference it uses `Sec-CH-Prefers-Color-Scheme`,
5
+ * which browsers only send once the app asks with `themeClientHintHeaders()`;
6
+ * without it, `SYSTEM_DARK_WHEN_UNKNOWN`.
5
7
  */
6
8
  export declare function getThemeContext(cookieName: string): ThemeContext;
7
9
  /**
@@ -1,15 +1,21 @@
1
1
  import { getCookie, getRequestHeader, setCookie, } from "@tanstack/react-start/server";
2
- import { resolveIsDark, ThemeSchema, } from "./index.js";
2
+ import { resolveIsDark, SYSTEM_DARK_WHEN_UNKNOWN, ThemeSchema, } from "./index.js";
3
3
  /**
4
4
  * Reads theme preference from the `cookieName` cookie and resolves dark mode
5
- * for SSR. Uses `Sec-CH-Prefers-Color-Scheme` when preference is `system`.
5
+ * for SSR. For a `system` preference it uses `Sec-CH-Prefers-Color-Scheme`,
6
+ * which browsers only send once the app asks with `themeClientHintHeaders()`;
7
+ * without it, `SYSTEM_DARK_WHEN_UNKNOWN`.
6
8
  */
7
9
  export function getThemeContext(cookieName) {
8
10
  const raw = getCookie(cookieName);
9
11
  const parsed = ThemeSchema.safeParse(raw);
10
12
  const theme = parsed.success ? parsed.data : "system";
11
- const prefersColorScheme = getRequestHeader("sec-ch-prefers-color-scheme");
12
- const prefersDark = prefersColorScheme?.toLowerCase() === "dark";
13
+ // A structured-header string: `"dark"` or `"light"`, quotes included.
14
+ const hint = getRequestHeader("sec-ch-prefers-color-scheme")
15
+ ?.replaceAll('"', "")
16
+ .trim()
17
+ .toLowerCase();
18
+ const prefersDark = hint ? hint === "dark" : SYSTEM_DARK_WHEN_UNKNOWN;
13
19
  const isDark = resolveIsDark(theme, prefersDark);
14
20
  return { theme, isDark };
15
21
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "singularity-core",
3
- "version": "0.6.0",
4
- "description": "Shared non-UI code for Singularity TanStack Start apps: auth sessions, API client middleware, API schemas, paging, route data, images, formatting, theme, SEO, security headers and telemetry.",
3
+ "version": "0.9.0",
4
+ "description": "Shared non-UI code for Singularity TanStack Start apps: auth sessions, API client middleware, API schemas, paging, route data, images, formatting, HTTP helpers, theme, cookie notice, SEO, security headers and telemetry.",
5
5
  "type": "module",
6
6
  "author": "Filip",
7
7
  "license": "MIT",
@@ -9,9 +9,8 @@
9
9
  "dist"
10
10
  ],
11
11
  "sideEffects": false,
12
- "packageManager": "pnpm@12.3.4",
13
12
  "engines": {
14
- "node": ">=25.0.0 <26.0.0",
13
+ "node": ">=26.0.0 <27.0.0",
15
14
  "pnpm": ">=12.0.0 <13.0.0"
16
15
  },
17
16
  "exports": {
@@ -43,6 +42,10 @@
43
42
  "types": "./dist/router/react.d.ts",
44
43
  "import": "./dist/router/react.js"
45
44
  },
45
+ "./cookie-notice/server": {
46
+ "types": "./dist/cookie-notice/server.d.ts",
47
+ "import": "./dist/cookie-notice/server.js"
48
+ },
46
49
  "./theme": {
47
50
  "types": "./dist/theme/index.d.ts",
48
51
  "import": "./dist/theme/index.js"
@@ -82,18 +85,8 @@
82
85
  "./http": {
83
86
  "types": "./dist/http/index.d.ts",
84
87
  "import": "./dist/http/index.js"
85
- }
86
- },
87
- "scripts": {
88
- "build": "tsc -p tsconfig.build.json",
89
- "typecheck": "tsc --noEmit",
90
- "test": "vitest run",
91
- "test:watch": "vitest",
92
- "openapi-dev-types": "openapi-typescript http://localhost:5268/swagger/v1/swagger.json -o ./src/api/v1.ts --alphabetize --default-non-nullable --enum-values",
93
- "prepack": "pnpm build",
94
- "biome:check": "biome check --write",
95
- "biome:lint": "biome lint --fix",
96
- "biome:format": "biome format --write"
88
+ },
89
+ "./package.json": "./package.json"
97
90
  },
98
91
  "peerDependencies": {
99
92
  "@tanstack/react-router": "^1.170.0",
@@ -124,8 +117,10 @@
124
117
  "@biomejs/biome": "2.5.15",
125
118
  "@tanstack/react-router": "1.170.42",
126
119
  "@tanstack/react-start": "1.168.61",
127
- "@types/node": "25.9.5",
120
+ "@types/node": "26.6.5",
128
121
  "@types/react": "19.3.0",
122
+ "@types/react-dom": "19.3.0",
123
+ "happy-dom": "20.11.13",
129
124
  "jose": "6.2.12",
130
125
  "openapi-fetch": "0.17.0",
131
126
  "openapi-typescript": "7.13.0",
@@ -134,5 +129,18 @@
134
129
  "typescript": "6.0.3",
135
130
  "vitest": "5.0.3",
136
131
  "zod": "4.6.5"
132
+ },
133
+ "scripts": {
134
+ "build": "node -e \"fs.rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
135
+ "typecheck": "tsc --noEmit",
136
+ "test": "vitest run",
137
+ "test:watch": "vitest",
138
+ "openapi-dev-types": "openapi-typescript http://localhost:5268/swagger/v1/swagger.json -o ./src/api/v1.ts --alphabetize --default-non-nullable --enum-values",
139
+ "openapi-types": "openapi-typescript https://api.filion.se/swagger/v1/swagger.json -o ./src/api/v1.ts --alphabetize --default-non-nullable --enum-values",
140
+ "check": "biome check",
141
+ "verify": "pnpm run typecheck && pnpm run check && pnpm run test",
142
+ "biome:check": "biome check --write",
143
+ "biome:lint": "biome lint --fix",
144
+ "biome:format": "biome format --write"
137
145
  }
138
- }
146
+ }