feat: smooth same-origin page changes
Cache versioned styles, images, and scripts so repeat clicks do not wait on them, crossfade navigations while the chrome stays put, and prefetch ordinary links on hover.
This commit is contained in:
1 parent
5e0e4a55a8
commit
747e6e25e0
8 files changed
+236
-36
No files matched your search
@@ -170,6 +170,11 @@ a.btn:active {
|
|||||||
color: var(--hope-ink);
|
color: var(--hope-ink);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Same-origin clicks crossfade. Named chrome stays in place while the page changes. */
|
||||||
|
@view-transition {
|
||||||
|
navigation: auto;
|
||||||
|
}
|
||||||
|
|
||||||
.header {
|
.header {
|
||||||
position: relative;
|
position: relative;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
@@ -179,6 +184,7 @@ a.btn:active {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.nav {
|
.nav {
|
||||||
|
view-transition-name: site-header;
|
||||||
left: 0;
|
left: 0;
|
||||||
position: fixed;
|
position: fixed;
|
||||||
z-index: 999;
|
z-index: 999;
|
||||||
@@ -298,6 +304,7 @@ a.btn:active {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.session-bar {
|
.session-bar {
|
||||||
|
view-transition-name: session-bar;
|
||||||
position: fixed;
|
position: fixed;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
top: 118px;
|
top: 118px;
|
||||||
@@ -1921,6 +1928,7 @@ button.btn-quiet::before {
|
|||||||
/* Footer. Pixel sizes match hopefoodpantrysc.org. */
|
/* Footer. Pixel sizes match hopefoodpantrysc.org. */
|
||||||
|
|
||||||
.footer {
|
.footer {
|
||||||
|
view-transition-name: site-footer;
|
||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -2701,6 +2709,16 @@ button.btn-quiet::before {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
@view-transition {
|
||||||
|
navigation: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::view-transition-group(*),
|
||||||
|
::view-transition-old(*),
|
||||||
|
::view-transition-new(*) {
|
||||||
|
animation: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
html {
|
html {
|
||||||
scroll-behavior: auto;
|
scroll-behavior: auto;
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-4
@@ -16,6 +16,7 @@ import {
|
|||||||
import type { SignupErrors, SignupValues } from './signup-form.js';
|
import type { SignupErrors, SignupValues } from './signup-form.js';
|
||||||
import { addLocalDays, todayInZone } from './time.js';
|
import { addLocalDays, todayInZone } from './time.js';
|
||||||
import { ShiftTargetOptions } from './shift-options.js';
|
import { ShiftTargetOptions } from './shift-options.js';
|
||||||
|
import { assetHref } from './static-assets.js';
|
||||||
import { appPath } from './url.js';
|
import { appPath } from './url.js';
|
||||||
|
|
||||||
export type WalkInState = {
|
export type WalkInState = {
|
||||||
@@ -243,12 +244,12 @@ export function AdminHome(props: {
|
|||||||
/>
|
/>
|
||||||
<form method="dialog" class="event-dialog-dismiss">
|
<form method="dialog" class="event-dialog-dismiss">
|
||||||
<button type="submit" class="event-dialog-close" aria-label="Close">
|
<button type="submit" class="event-dialog-close" aria-label="Close">
|
||||||
<img src={appPath(props.config, '/img/icons/close.svg')} alt="" />
|
<img src={assetHref(props.config, '/img/icons/close.svg')} alt="" />
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
<script src={appPath(props.config, '/js/event-dialog.js')} defer />
|
<script src={assetHref(props.config, '/js/event-dialog.js')} defer />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -877,7 +878,7 @@ function ConfirmDialog(props: { config: AppConfig; csrf: string; prompt?: Confir
|
|||||||
<div class="confirm-card">
|
<div class="confirm-card">
|
||||||
<form method="dialog" id="confirm-dismiss" class="confirm-x">
|
<form method="dialog" id="confirm-dismiss" class="confirm-x">
|
||||||
<button type="submit" class="event-dialog-close" aria-label="Close">
|
<button type="submit" class="event-dialog-close" aria-label="Close">
|
||||||
<img src={appPath(props.config, '/img/icons/close.svg')} alt="" />
|
<img src={assetHref(props.config, '/img/icons/close.svg')} alt="" />
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
<form method="post" id="confirm-form" class="confirm-form" action={prompt?.action ?? ''} data-keep-place="">
|
<form method="post" id="confirm-form" class="confirm-form" action={prompt?.action ?? ''} data-keep-place="">
|
||||||
@@ -904,7 +905,7 @@ function ConfirmDialog(props: { config: AppConfig; csrf: string; prompt?: Confir
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</dialog>
|
</dialog>
|
||||||
<script src={appPath(props.config, '/js/confirm-dialog.js')} defer />
|
<script src={assetHref(props.config, '/js/confirm-dialog.js')} defer />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-19
@@ -1,6 +1,3 @@
|
|||||||
import path from 'node:path';
|
|
||||||
import { fileURLToPath } from 'node:url';
|
|
||||||
import { serveStatic } from '@hono/node-server/serve-static';
|
|
||||||
import type Database from 'better-sqlite3';
|
import type Database from 'better-sqlite3';
|
||||||
import { Hono, type Context } from 'hono';
|
import { Hono, type Context } from 'hono';
|
||||||
import { bodyLimit } from 'hono/body-limit';
|
import { bodyLimit } from 'hono/body-limit';
|
||||||
@@ -14,12 +11,11 @@ import { privacyParagraphs, readPantrySettings } from './settings.js';
|
|||||||
import { registerReminderOff } from './reminder-http.js';
|
import { registerReminderOff } from './reminder-http.js';
|
||||||
import { registerPublicSignup } from './signup-http.js';
|
import { registerPublicSignup } from './signup-http.js';
|
||||||
import { securityHeaders } from './security.js';
|
import { securityHeaders } from './security.js';
|
||||||
|
import { SHARED_ASSET_CACHE, SPECULATION_RULES, assetCacheControl, publicDirectory, readPublicFile, rewriteCssUrls, staticAssetStamp } from './static-assets.js';
|
||||||
import { nowUtc } from './time.js';
|
import { nowUtc } from './time.js';
|
||||||
import { appPath } from './url.js';
|
import { appPath } from './url.js';
|
||||||
|
|
||||||
export function publicDirectory(): string {
|
export { publicDirectory };
|
||||||
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../public');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createApp(
|
export function createApp(
|
||||||
config: AppConfig,
|
config: AppConfig,
|
||||||
@@ -35,7 +31,7 @@ export function createApp(
|
|||||||
const now = () => options?.now ?? nowUtc();
|
const now = () => options?.now ?? nowUtc();
|
||||||
const publicDir = options?.publicDir ?? publicDirectory();
|
const publicDir = options?.publicDir ?? publicDirectory();
|
||||||
|
|
||||||
app.use('*', securityHeaders({ https: config.secureCookies }));
|
app.use('*', securityHeaders({ https: config.secureCookies, speculationRules: appPath(config, '/speculation-rules.json') }));
|
||||||
app.use('*', bodyLimit({
|
app.use('*', bodyLimit({
|
||||||
maxSize: 64 * 1024,
|
maxSize: 64 * 1024,
|
||||||
onError: (c) => {
|
onError: (c) => {
|
||||||
@@ -48,6 +44,12 @@ export function createApp(
|
|||||||
app.use(appPath(config, '/img/*'), staticFiles(config, publicDir));
|
app.use(appPath(config, '/img/*'), staticFiles(config, publicDir));
|
||||||
app.use(appPath(config, '/js/*'), staticFiles(config, publicDir));
|
app.use(appPath(config, '/js/*'), staticFiles(config, publicDir));
|
||||||
|
|
||||||
|
app.get(appPath(config, '/speculation-rules.json'), (c) => {
|
||||||
|
c.header('Cache-Control', SHARED_ASSET_CACHE);
|
||||||
|
c.header('Content-Type', 'application/speculationrules+json; charset=utf-8');
|
||||||
|
return c.body(JSON.stringify(SPECULATION_RULES));
|
||||||
|
});
|
||||||
|
|
||||||
app.get(appPath(config, '/healthz'), (c) => {
|
app.get(appPath(config, '/healthz'), (c) => {
|
||||||
c.header('Cache-Control', 'no-store');
|
c.header('Cache-Control', 'no-store');
|
||||||
try {
|
try {
|
||||||
@@ -150,17 +152,16 @@ function page(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function staticFiles(config: AppConfig, publicDir: string) {
|
function staticFiles(config: AppConfig, publicDir: string) {
|
||||||
return serveStatic({
|
return async (c: Context, next: () => Promise<void>) => {
|
||||||
root: publicDir,
|
const file = readPublicFile(publicDir, c.req.path, config.basePath);
|
||||||
onFound: (_path, c) => {
|
if (!file) return next();
|
||||||
c.header('Cache-Control', 'no-cache');
|
const cache = assetCacheControl(c.req.query('v'), publicDir);
|
||||||
},
|
c.header('Cache-Control', cache);
|
||||||
rewriteRequestPath: (requestPath) => {
|
c.header('Content-Type', file.type);
|
||||||
if (config.basePath !== '' && requestPath.startsWith(config.basePath)) {
|
if (file.type.startsWith('text/css')) {
|
||||||
return requestPath.slice(config.basePath.length) || '/';
|
return c.body(rewriteCssUrls(file.body.toString('utf8'), staticAssetStamp(publicDir)));
|
||||||
}
|
}
|
||||||
return requestPath;
|
return c.body(new Uint8Array(file.body));
|
||||||
},
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
+6
-5
@@ -6,12 +6,13 @@ import type { SignupErrors, SignupValues } from './signup-form.js';
|
|||||||
import type { MoveTarget } from './admin/store.js';
|
import type { MoveTarget } from './admin/store.js';
|
||||||
import { ShiftTargetOptions } from './shift-options.js';
|
import { ShiftTargetOptions } from './shift-options.js';
|
||||||
import type { ManageView } from './signup.js';
|
import type { ManageView } from './signup.js';
|
||||||
|
import { assetHref } from './static-assets.js';
|
||||||
import { appPath } from './url.js';
|
import { appPath } from './url.js';
|
||||||
|
|
||||||
const PANTRY_SITE = 'https://hopefoodpantrysc.org';
|
const PANTRY_SITE = 'https://hopefoodpantrysc.org';
|
||||||
|
|
||||||
function asset(config: AppConfig, file: string): string {
|
function asset(config: AppConfig, file: string): string {
|
||||||
return appPath(config, file);
|
return assetHref(config, file);
|
||||||
}
|
}
|
||||||
|
|
||||||
function pathIs(path: string | undefined, target: string): boolean {
|
function pathIs(path: string | undefined, target: string): boolean {
|
||||||
@@ -45,9 +46,9 @@ export function Layout(props: {
|
|||||||
<title>{props.title}</title>
|
<title>{props.title}</title>
|
||||||
<link rel="icon" href={asset(props.config, '/img/favicons/favicon.png')} />
|
<link rel="icon" href={asset(props.config, '/img/favicons/favicon.png')} />
|
||||||
<link rel="apple-touch-icon" href={asset(props.config, '/img/favicons/favicon-apple.png')} />
|
<link rel="apple-touch-icon" href={asset(props.config, '/img/favicons/favicon-apple.png')} />
|
||||||
<link rel="stylesheet" href={appPath(props.config, '/brand/tokens.css')} />
|
<link rel="stylesheet" href={asset(props.config, '/brand/tokens.css')} />
|
||||||
<link rel="stylesheet" href={appPath(props.config, '/css/app.css')} />
|
<link rel="stylesheet" href={asset(props.config, '/css/app.css')} />
|
||||||
<script src={appPath(props.config, '/js/desk.js')} />
|
<script src={asset(props.config, '/js/desk.js')} />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<a class="skip-link" href="#content">
|
<a class="skip-link" href="#content">
|
||||||
@@ -208,7 +209,7 @@ export function Layout(props: {
|
|||||||
</p>
|
</p>
|
||||||
</footer>
|
</footer>
|
||||||
{props.turnstile ? <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer /> : null}
|
{props.turnstile ? <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer /> : null}
|
||||||
<script src={appPath(props.config, '/js/enhance.js')} defer />
|
<script src={asset(props.config, '/js/enhance.js')} defer />
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|||||||
+4
-1
@@ -24,7 +24,7 @@ export const PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=(), pay
|
|||||||
export const STRICT_TRANSPORT_SECURITY = 'max-age=31536000';
|
export const STRICT_TRANSPORT_SECURITY = 'max-age=31536000';
|
||||||
|
|
||||||
/** HSTS is sent only when BASE_URL is https. A browser ignores it over http. */
|
/** HSTS is sent only when BASE_URL is https. A browser ignores it over http. */
|
||||||
export function securityHeaders(options: { https: boolean }): MiddlewareHandler {
|
export function securityHeaders(options: { https: boolean; speculationRules?: string }): MiddlewareHandler {
|
||||||
return async (c, next) => {
|
return async (c, next) => {
|
||||||
await next();
|
await next();
|
||||||
c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);
|
c.header('Content-Security-Policy', CONTENT_SECURITY_POLICY);
|
||||||
@@ -32,5 +32,8 @@ export function securityHeaders(options: { https: boolean }): MiddlewareHandler
|
|||||||
c.header('X-Content-Type-Options', 'nosniff');
|
c.header('X-Content-Type-Options', 'nosniff');
|
||||||
c.header('Permissions-Policy', PERMISSIONS_POLICY);
|
c.header('Permissions-Policy', PERMISSIONS_POLICY);
|
||||||
if (options.https) c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);
|
if (options.https) c.header('Strict-Transport-Security', STRICT_TRANSPORT_SECURITY);
|
||||||
|
if (options.speculationRules && (c.res.headers.get('content-type') ?? '').includes('text/html')) {
|
||||||
|
c.header('Speculation-Rules', `"${options.speculationRules}"`);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import type { AppConfig } from './config.js';
|
||||||
|
import { appPath } from './url.js';
|
||||||
|
|
||||||
|
/** A fresh versioned URL can stay cached. The query changes when a file in public/ changes. */
|
||||||
|
export const VERSIONED_ASSET_CACHE = 'public, max-age=31536000, immutable';
|
||||||
|
|
||||||
|
/** An unversioned or stale URL can be reused for an hour, then checked again. */
|
||||||
|
export const SHARED_ASSET_CACHE = 'public, max-age=3600';
|
||||||
|
|
||||||
|
const ASSET_ROOTS = ['css', 'brand', 'img', 'js'];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same-origin GET links are fetched on hover.
|
||||||
|
* Confirm and new-event controls open a dialog instead of navigating.
|
||||||
|
* Cross-origin links are not eligible unless a rule asks for them.
|
||||||
|
*/
|
||||||
|
export const SPECULATION_RULES = {
|
||||||
|
prefetch: [
|
||||||
|
{
|
||||||
|
source: 'document',
|
||||||
|
where: {
|
||||||
|
and: [
|
||||||
|
{ href_matches: '/*' },
|
||||||
|
{ not: { selector_matches: '[data-confirm], [data-open-event]' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
eagerness: 'moderate',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type StampCache = { fingerprint: string; stamp: string };
|
||||||
|
let stampCache: StampCache | undefined;
|
||||||
|
|
||||||
|
/** Bumped so browsers drop the empty images and scripts cached under the first versioned URLs. */
|
||||||
|
const STAMP_EPOCH = '2';
|
||||||
|
|
||||||
|
export function publicDirectory(): string {
|
||||||
|
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../public');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Short token that changes when a stylesheet, font, image, or script changes. */
|
||||||
|
export function staticAssetStamp(dir: string): string {
|
||||||
|
const fingerprint = fingerprintPublic(dir);
|
||||||
|
if (stampCache?.fingerprint === fingerprint) return stampCache.stamp;
|
||||||
|
const stamp = createHash('sha256').update(`${STAMP_EPOCH}\n${fingerprint}`).digest('base64url').slice(0, 12);
|
||||||
|
stampCache = { fingerprint, stamp };
|
||||||
|
return stamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assetHref(config: Pick<AppConfig, 'basePath'>, file: string, dir = publicDirectory()): string {
|
||||||
|
return `${appPath(config, file)}?v=${staticAssetStamp(dir)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function assetCacheControl(requested: string | undefined, dir: string): string {
|
||||||
|
return requested === staticAssetStamp(dir) ? VERSIONED_ASSET_CACHE : SHARED_ASSET_CACHE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIME: Record<string, string> = {
|
||||||
|
'.css': 'text/css; charset=utf-8',
|
||||||
|
'.js': 'text/javascript; charset=utf-8',
|
||||||
|
'.png': 'image/png',
|
||||||
|
'.svg': 'image/svg+xml',
|
||||||
|
'.woff2': 'font/woff2',
|
||||||
|
'.txt': 'text/plain; charset=utf-8',
|
||||||
|
'.webp': 'image/webp',
|
||||||
|
'.jpg': 'image/jpeg',
|
||||||
|
'.jpeg': 'image/jpeg',
|
||||||
|
'.gif': 'image/gif',
|
||||||
|
'.ico': 'image/x-icon',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Read a public file as bytes. Rebuilding the static-file stream dropped image and script bodies. */
|
||||||
|
export function readPublicFile(publicDir: string, requestPath: string, basePath: string): { body: Buffer; type: string } | undefined {
|
||||||
|
const full = resolvePublicFile(publicDir, requestPath, basePath);
|
||||||
|
if (!full) return undefined;
|
||||||
|
const type = MIME[path.extname(full).toLowerCase()];
|
||||||
|
if (!type) return undefined;
|
||||||
|
try {
|
||||||
|
if (!statSync(full).isFile()) return undefined;
|
||||||
|
return { body: readFileSync(full), type };
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePublicFile(publicDir: string, requestPath: string, basePath: string): string | undefined {
|
||||||
|
let rel = requestPath;
|
||||||
|
if (basePath !== '' && rel.startsWith(basePath)) rel = rel.slice(basePath.length) || '/';
|
||||||
|
if (!rel.startsWith('/') || rel.includes('..') || rel.includes('\\') || rel.includes('\0')) return undefined;
|
||||||
|
const root = path.resolve(publicDir);
|
||||||
|
const full = path.resolve(root, `.${rel}`);
|
||||||
|
if (full !== root && !full.startsWith(`${root}${path.sep}`)) return undefined;
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Font addresses live inside CSS, so the served sheet carries the same version query as the document. */
|
||||||
|
export function rewriteCssUrls(css: string, stamp: string): string {
|
||||||
|
return css.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (full, quote: string, target: string) => {
|
||||||
|
const trimmed = target.trim();
|
||||||
|
if (trimmed.startsWith('data:') || trimmed.startsWith('http://') || trimmed.startsWith('https://') || trimmed.includes('?')) {
|
||||||
|
return full;
|
||||||
|
}
|
||||||
|
return `url(${quote}${trimmed}?v=${stamp}${quote})`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fingerprintPublic(dir: string): string {
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (const root of ASSET_ROOTS) collect(path.join(dir, root), root, lines);
|
||||||
|
lines.sort();
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function collect(dir: string, rel: string, lines: string[]): void {
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
entries = readdirSync(dir, { withFileTypes: true });
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const entry of entries) {
|
||||||
|
const child = `${rel}/${entry.name}`;
|
||||||
|
if (entry.isDirectory()) collect(path.join(dir, entry.name), child, lines);
|
||||||
|
else if (entry.isFile()) {
|
||||||
|
const stat = statSync(path.join(dir, entry.name));
|
||||||
|
lines.push(`${child}:${stat.mtimeMs}:${stat.size}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -327,7 +327,7 @@ describe('coordinator screens', () => {
|
|||||||
const page = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
const page = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
||||||
const html = await page.text();
|
const html = await page.text();
|
||||||
expect(html).toContain('Add a walk-in');
|
expect(html).toContain('Add a walk-in');
|
||||||
expect(html).toContain('src="/js/enhance.js"');
|
expect(html).toContain('src="/js/enhance.js?v=');
|
||||||
expect(html).toContain('data-under-18');
|
expect(html).toContain('data-under-18');
|
||||||
expect(html).toContain('data-guardian');
|
expect(html).toContain('data-guardian');
|
||||||
expect(html).not.toMatch(/id="walkin-under-18"[^>]*\schecked/);
|
expect(html).not.toMatch(/id="walkin-under-18"[^>]*\schecked/);
|
||||||
|
|||||||
@@ -76,11 +76,11 @@ describe('public pages', () => {
|
|||||||
expect(html).not.toContain('SECRET-PERSON-NOTE');
|
expect(html).not.toContain('SECRET-PERSON-NOTE');
|
||||||
expect(html).not.toContain('SECRET-SHIFT-NOTE');
|
expect(html).not.toContain('SECRET-SHIFT-NOTE');
|
||||||
expect(html).not.toContain('<form');
|
expect(html).not.toContain('<form');
|
||||||
expect(html).toContain('src="/js/desk.js"');
|
expect(html).toContain('src="/js/desk.js?v=');
|
||||||
expect(html).toContain('src="/js/enhance.js"');
|
expect(html).toContain('src="/js/enhance.js?v=');
|
||||||
expect(html).not.toContain('<script>alert(1)</script>');
|
expect(html).not.toContain('<script>alert(1)</script>');
|
||||||
expect(html).toContain('href="/css/app.css"');
|
expect(html).toContain('href="/css/app.css?v=');
|
||||||
expect(html).toContain('href="/brand/tokens.css"');
|
expect(html).toContain('href="/brand/tokens.css?v=');
|
||||||
expect(html).toContain(`href="/s/${ids.open}"`);
|
expect(html).toContain(`href="/s/${ids.open}"`);
|
||||||
expect(home.headers.get('content-security-policy')).toBe(CONTENT_SECURITY_POLICY);
|
expect(home.headers.get('content-security-policy')).toBe(CONTENT_SECURITY_POLICY);
|
||||||
expect(home.headers.get('referrer-policy')).toBe('no-referrer');
|
expect(home.headers.get('referrer-policy')).toBe('no-referrer');
|
||||||
@@ -186,12 +186,46 @@ describe('public pages', () => {
|
|||||||
const css = await app.request('/css/app.css');
|
const css = await app.request('/css/app.css');
|
||||||
expect(css.status).toBe(200);
|
expect(css.status).toBe(200);
|
||||||
expect(css.headers.get('content-type')).toContain('text/css');
|
expect(css.headers.get('content-type')).toContain('text/css');
|
||||||
|
expect(css.headers.get('cache-control')).toBe('public, max-age=3600');
|
||||||
const stylesheet = await css.text();
|
const stylesheet = await css.text();
|
||||||
expect(stylesheet).toContain('var(--hope-ink)');
|
expect(stylesheet).toContain('var(--hope-ink)');
|
||||||
|
expect(stylesheet).toContain('@view-transition');
|
||||||
|
expect(stylesheet).toContain('view-transition-name: site-header');
|
||||||
|
expect(stylesheet).toMatch(/lexend-latin\.woff2\?v=/);
|
||||||
expect(stylesheet).not.toContain('sunburst');
|
expect(stylesheet).not.toContain('sunburst');
|
||||||
const tokens = await app.request('/brand/tokens.css');
|
const tokens = await app.request('/brand/tokens.css');
|
||||||
expect(tokens.status).toBe(200);
|
expect(tokens.status).toBe(200);
|
||||||
expect(await tokens.text()).toContain('--hope-yellow:#f9e194');
|
expect(await tokens.text()).toContain('--hope-yellow:#f9e194');
|
||||||
|
|
||||||
|
const home = await app.request('/');
|
||||||
|
expect(home.headers.get('cache-control')).toBe('no-store');
|
||||||
|
expect(home.headers.get('speculation-rules')).toBe('"/speculation-rules.json"');
|
||||||
|
const homeHtml = await home.text();
|
||||||
|
const styled = versionedAsset(homeHtml, '/css/app.css');
|
||||||
|
const versioned = await app.request(styled);
|
||||||
|
expect(versioned.headers.get('cache-control')).toBe('public, max-age=31536000, immutable');
|
||||||
|
const font = stylesheet.match(/(\/brand\/fonts\/lexend-latin\.woff2\?v=[A-Za-z0-9_-]+)/);
|
||||||
|
const fontFile = await app.request(font?.[1] ?? '/missing');
|
||||||
|
expect(fontFile.status).toBe(200);
|
||||||
|
expect(fontFile.headers.get('cache-control')).toBe('public, max-age=31536000, immutable');
|
||||||
|
expect(Buffer.from(await fontFile.arrayBuffer()).length).toBeGreaterThan(1000);
|
||||||
|
const logo = await app.request(versionedAsset(homeHtml, '/img/logo.png'));
|
||||||
|
expect(logo.status).toBe(200);
|
||||||
|
expect(logo.headers.get('content-type')).toContain('image/png');
|
||||||
|
const logoBytes = Buffer.from(await logo.arrayBuffer());
|
||||||
|
expect(logoBytes.subarray(0, 4).toString('hex')).toBe('89504e47');
|
||||||
|
expect(logoBytes.length).toBeGreaterThan(1000);
|
||||||
|
const script = await app.request(versionedAsset(homeHtml, '/js/desk.js'));
|
||||||
|
expect(script.status).toBe(200);
|
||||||
|
expect((await script.text()).length).toBeGreaterThan(20);
|
||||||
|
|
||||||
|
const rules = await app.request('/speculation-rules.json');
|
||||||
|
expect(rules.status).toBe(200);
|
||||||
|
expect(rules.headers.get('content-type')).toContain('application/speculationrules+json');
|
||||||
|
const body = await rules.json();
|
||||||
|
expect(body.prefetch[0].eagerness).toBe('moderate');
|
||||||
|
expect(body.prefetch[0].where.and[1].not.selector_matches).toContain('[data-confirm]');
|
||||||
|
expect(body.prefetch[0].where.and[1].not.selector_matches).toContain('[data-open-event]');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('prefixes routes and assets when the app is mounted at /volunteer', async () => {
|
it('prefixes routes and assets when the app is mounted at /volunteer', async () => {
|
||||||
@@ -201,8 +235,9 @@ describe('public pages', () => {
|
|||||||
const home = await app.request('/volunteer');
|
const home = await app.request('/volunteer');
|
||||||
expect(home.status).toBe(200);
|
expect(home.status).toBe(200);
|
||||||
const html = await home.text();
|
const html = await home.text();
|
||||||
expect(html).toContain('href="/volunteer/css/app.css"');
|
expect(html).toContain('href="/volunteer/css/app.css?v=');
|
||||||
expect(html).toContain('href="/volunteer/brand/tokens.css"');
|
expect(html).toContain('href="/volunteer/brand/tokens.css?v=');
|
||||||
|
expect(home.headers.get('speculation-rules')).toBe('"/volunteer/speculation-rules.json"');
|
||||||
expect(html).toContain('Weekly pantry');
|
expect(html).toContain('Weekly pantry');
|
||||||
expect(html).not.toContain('Upcoming shifts');
|
expect(html).not.toContain('Upcoming shifts');
|
||||||
expect((await app.request('/volunteer/e/weekly-pantry')).status).toBe(200);
|
expect((await app.request('/volunteer/e/weekly-pantry')).status).toBe(200);
|
||||||
@@ -344,6 +379,13 @@ function insertShift(
|
|||||||
return Number(result.lastInsertRowid);
|
return Number(result.lastInsertRowid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function versionedAsset(html: string, file: string): string {
|
||||||
|
const escaped = file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
const match = html.match(new RegExp(`${escaped}\\?v=([A-Za-z0-9_-]+)`));
|
||||||
|
if (!match?.[1]) throw new Error(`Missing versioned asset ${file}`);
|
||||||
|
return `${file}?v=${match[1]}`;
|
||||||
|
}
|
||||||
|
|
||||||
function insertSignup(db: import('better-sqlite3').Database, shiftId: number): void {
|
function insertSignup(db: import('better-sqlite3').Database, shiftId: number): void {
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`INSERT INTO signups (
|
`INSERT INTO signups (
|
||||||
|
|||||||
Reference in new issue
Block a user