singularity-core 0.6.0 → 0.14.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.
@@ -9,17 +9,24 @@ export declare const USER_ROLES: readonly UserRole[];
9
9
  export declare const UserRoleEnum: { readonly [Role in UserRole]: Role; };
10
10
  export declare const UserRoleEnumSchema: z.ZodEnum<{
11
11
  ADMIN: "ADMIN";
12
- WRITER: "WRITER";
13
- USER: "USER";
12
+ BLOG_WRITER: "BLOG_WRITER";
13
+ BLOG_USER: "BLOG_USER";
14
14
  }>;
15
15
  export type EntityWithRoles = {
16
16
  roles?: UserRoles;
17
17
  } | null | undefined;
18
+ /**
19
+ * True when the entity holds `role`, or ADMIN: admin is global and passes
20
+ * every site's role checks, as it does in the API.
21
+ */
18
22
  export declare function hasRoleAccess(entity: EntityWithRoles, role: UserRole): boolean;
23
+ /** ADMIN: the admin app, and every site's features. */
19
24
  export declare function hasAdminAccess(entity: EntityWithRoles): boolean;
20
- export declare function hasWriterAccess(entity: EntityWithRoles): boolean;
21
- /** Admin or writer — can access the dashboard area. */
22
- export declare function hasDashboardAccess(entity: EntityWithRoles): boolean;
25
+ /**
26
+ * True when no roles are required, or the entity holds one of them or ADMIN.
27
+ * Site roles start with the site's name (`BLOG_WRITER`); list each one a
28
+ * feature accepts, ADMIN never needs listing.
29
+ */
23
30
  export declare function hasRequiredRoles(entity: EntityWithRoles, requiredRoles: UserRoles): boolean;
24
31
  export declare const isValidRole: (role: string) => role is UserRole;
25
32
  /**
@@ -5,25 +5,28 @@ export const USER_ROLES = userRoleValues;
5
5
  /** Each role by name, e.g. `UserRoleEnum.ADMIN === "ADMIN"`. */
6
6
  export const UserRoleEnum = Object.fromEntries(USER_ROLES.map((role) => [role, role]));
7
7
  export const UserRoleEnumSchema = z.enum(USER_ROLES);
8
+ /**
9
+ * True when the entity holds `role`, or ADMIN: admin is global and passes
10
+ * every site's role checks, as it does in the API.
11
+ */
8
12
  export function hasRoleAccess(entity, role) {
9
- return entity?.roles?.includes(role) ?? false;
13
+ return hasRequiredRoles(entity, [role]);
10
14
  }
15
+ /** ADMIN: the admin app, and every site's features. */
11
16
  export function hasAdminAccess(entity) {
12
- return hasRoleAccess(entity, UserRoleEnum.ADMIN);
13
- }
14
- export function hasWriterAccess(entity) {
15
- return hasRoleAccess(entity, UserRoleEnum.WRITER);
16
- }
17
- /** Admin or writer — can access the dashboard area. */
18
- export function hasDashboardAccess(entity) {
19
- return hasAdminAccess(entity) || hasWriterAccess(entity);
17
+ return entity?.roles?.includes(UserRoleEnum.ADMIN) ?? false;
20
18
  }
19
+ /**
20
+ * True when no roles are required, or the entity holds one of them or ADMIN.
21
+ * Site roles start with the site's name (`BLOG_WRITER`); list each one a
22
+ * feature accepts, ADMIN never needs listing.
23
+ */
21
24
  export function hasRequiredRoles(entity, requiredRoles) {
22
25
  if (!requiredRoles || requiredRoles.length === 0)
23
26
  return true;
24
- if (!entity?.roles)
25
- return false;
26
- return requiredRoles.some((role) => entity?.roles?.includes(role));
27
+ if (hasAdminAccess(entity))
28
+ return true;
29
+ return requiredRoles.some((role) => entity?.roles?.includes(role) ?? false);
27
30
  }
28
31
  export const isValidRole = (role) => {
29
32
  return USER_ROLES.includes(role);
@@ -14,17 +14,27 @@ export declare function createAuthClient(options: {
14
14
  }): AuthClient;
15
15
  export type CookieSessionOptions = {
16
16
  client: AuthClient;
17
- /** Cookie names are `<prefix>_access_token`, `_refresh_token` and `_user_id`. */
17
+ /**
18
+ * Cookie names are `<prefix>_access_token`, `_refresh_token` and
19
+ * `_user_id`, at path `/` with no Domain, so every app on the same host that
20
+ * passes the same prefix shares one sign-in: signing in or out in one signs
21
+ * in or out in all of them.
22
+ */
18
23
  cookiePrefix: string;
19
- /** Defaults to `/`. Apps sharing a domain need distinct prefixes or paths. */
20
- cookiePath?: string;
21
24
  /**
22
- * Roles a login must have, any one of them. Other accounts are refused and
23
- * the API session the login opened is closed again.
25
+ * Roles a login through this app must have, any one of them (ADMIN always
26
+ * passes). Other accounts are refused and the API session the login opened
27
+ * is closed again; a session already signed in through another app is kept.
24
28
  */
25
29
  loginRoles?: UserRoles;
26
30
  /** Error message for a login without `loginRoles`. */
27
31
  loginRolesError?: string;
32
+ /**
33
+ * Marks the cookies `Secure`, so browsers send them over HTTPS only.
34
+ * Defaults to true; Chrome and Firefox also keep them on http://localhost.
35
+ * Pass false only for a plain-HTTP setup on another host.
36
+ */
37
+ secure?: boolean;
28
38
  };
29
39
  /** The session plus the refresh token it was read or rotated with (server only). */
30
40
  export type ServerSession = Session & {
@@ -35,7 +45,7 @@ export type ServerSession = Session & {
35
45
  * API itself, so no client code needs the tokens. Call only from server code
36
46
  * (server functions, middleware, loaders' server side).
37
47
  */
38
- export declare function createCookieSession({ client, cookiePrefix, cookiePath, loginRoles, loginRolesError, }: CookieSessionOptions): {
48
+ export declare function createCookieSession({ client, cookiePrefix, loginRoles, loginRolesError, secure, }: CookieSessionOptions): {
39
49
  login: (username: string, password: string) => Promise<import("./index.js").PublicSession | null>;
40
50
  logout: () => Promise<{
41
51
  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, 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
- path: cookiePath,
86
+ path: "/",
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
  }
@@ -1,5 +1,7 @@
1
1
  /** A `text/plain` response, e.g. for robots.txt or security.txt routes. */
2
2
  export declare function plainTextResponse(body: string): Response;
3
+ /** An `application/xml` response, e.g. for a sitemap.xml route. */
4
+ export declare function xmlResponse(body: string): Response;
3
5
  /**
4
6
  * The visitor's IP as nginx saw it: `X-Real-IP`, else the last
5
7
  * `X-Forwarded-For` hop.
@@ -4,6 +4,12 @@ export function plainTextResponse(body) {
4
4
  headers: { "Content-Type": "text/plain; charset=utf-8" },
5
5
  });
6
6
  }
7
+ /** An `application/xml` response, e.g. for a sitemap.xml route. */
8
+ export function xmlResponse(body) {
9
+ return new Response(body, {
10
+ headers: { "Content-Type": "application/xml; charset=utf-8" },
11
+ });
12
+ }
7
13
  /**
8
14
  * The visitor's IP as nginx saw it: `X-Real-IP`, else the last
9
15
  * `X-Forwarded-For` hop.
@@ -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
  }
@@ -28,11 +28,26 @@ export declare function toListParams(query: ListQuery): {
28
28
  Take: number | undefined;
29
29
  Search: string | undefined;
30
30
  };
31
+ /**
32
+ * A `ListQuery` as a server function validator: `page` and `take` are int32,
33
+ * and `take` stops at the API's largest page. Unknown keys are stripped.
34
+ */
35
+ export declare const ListQuerySchema: z.ZodObject<{
36
+ page: z.ZodOptional<z.ZodInt32>;
37
+ take: z.ZodOptional<z.ZodInt32>;
38
+ search: z.ZodOptional<z.ZodString>;
39
+ }, z.core.$strip>;
40
+ /** An id in the API's `{id:int}` routes (posts, images, authors, categories). */
41
+ export declare const IntIdSchema: z.ZodInt32;
42
+ /** An id in the API's `{id:guid}` routes (users, comments, generation jobs). */
43
+ export declare const GuidIdSchema: z.ZodGUID;
31
44
  /**
32
45
  * `?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.
46
+ * the first page; `search` filters the whole list on the API. A value that
47
+ * does not fit (`?page=abc`, a hand-typed `?search=2026`, which the router
48
+ * reads as a number) is dropped instead of failing the route.
34
49
  */
35
50
  export declare const pageSearchSchema: z.ZodObject<{
36
- page: z.ZodOptional<z.ZodNumber>;
37
- search: z.ZodOptional<z.ZodString>;
51
+ page: z.ZodCatch<z.ZodOptional<z.ZodNumber>>;
52
+ search: z.ZodCatch<z.ZodOptional<z.ZodString>>;
38
53
  }, z.core.$strip>;