Public: anyone can read this; the crew can change it.
OG cards as SVG: `/og/:kind/:ref.svg` composed from live data with the studio's tokens, cached by input hash #1418
torque/forge:torque/1054-og-cards-as-svg-og-kind-ref-svg-composed → main 3 commits fork
9 files
changed +879
−2
docs/STANDARDS.md +1
| @@ -14,6 +14,7 @@ its own mark. Nothing here is configured, and nothing here is optional. | ||
| 14 | 14 | | `/manifest.webmanifest` | the forge as an installable app | — | |
| 15 | 15 | | `/llms.txt` | the forge for an agent (llmstxt.org): how to report, how to offer a change, the API and MCP, the public repositories | `listReposVisibleTo(db, nobody)`, the report limits | |
| 16 | 16 | | `/icons/forge-<size>.png` | the mark at 192, 512, 512-maskable and 180 (iOS), painted at boot | `design/mark.ts`, the favicon's two colours | |
| 17 | | `/og/<kind>/<ref>.svg` | a 1200×630 Open Graph card for an app, repo, issue, pull or run (`/og/repo/alice/web.svg`, `/og/issue/alice/web/12.svg`, `/og/run/<id>.svg`, `/og/app/<slug>.svg`); ETag from the input's sha256, 304 on a repeat, `public` only when anyone may read it | `web/og/card.ts` from live rows, read through `canRead`/`mayView`; a card you may not read is 404 | | |
| 17 | 18 | | `/:owner/:name/activity.atom` | a repository's activity as Atom: pushes, issues, pulls, forks | a fixed list of kinds, as sentences; never a raw payload | |
| 18 | 19 | |
| 19 | 20 | Every page carries a description, Open Graph and Twitter card metadata, the |
scripts/gate.ts +1
| @@ -188,6 +188,7 @@ export const GATE: readonly string[] = [ | ||
| 188 | 188 | "test/name-marks.test.ts", |
| 189 | 189 | "test/new-forge.test.ts", |
| 190 | 190 | "test/notify.test.ts", |
| 191 | "test/og-card.test.ts", | |
| 191 | 192 | "test/onboarding.test.ts", |
| 192 | 193 | "test/org-owners.test.ts", |
| 193 | 194 | "test/origins-oauth.test.ts", |
src/core/reserved.ts +1
| @@ -79,6 +79,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 79 | 79 | "mode", |
| 80 | 80 | "new", |
| 81 | 81 | "oauth", |
| 82 | "og", | |
| 82 | 83 | "organizations", |
| 83 | 84 | "origins", |
| 84 | 85 | "robots.txt", |
src/design/type.ts added +14
| @@ -0,0 +1,14 @@ | ||
| 1 | /** | |
| 2 | * The type tokens: the two font stacks every surface draws text with. The | |
| 3 | * stylesheet names them as `--font` and `--mono`; the OG card | |
| 4 | * (`web/og/card.ts`) writes them into its SVG, so a shared link looks like | |
| 5 | * the page it points at. | |
| 6 | */ | |
| 7 | ||
| 8 | /** Prose and chrome: the platform's own UI face. */ | |
| 9 | export const FONT_SANS = | |
| 10 | 'system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'; | |
| 11 | ||
| 12 | /** Code, ids and hashes. */ | |
| 13 | export const FONT_MONO = | |
| 14 | 'ui-monospace, "SF Mono", SFMono-Regular, "Cascadia Code", "JetBrains Mono", Menlo, Consolas, "Liberation Mono", monospace'; |
src/http/server.ts +3
| @@ -112,6 +112,7 @@ import { | ||
| 112 | 112 | subscriptionHeadroom, |
| 113 | 113 | subscriptionWake, |
| 114 | 114 | } from "../web/pages/subscriptions.ts"; |
| 115 | import { ogCardPage } from "../web/pages/og.ts"; | |
| 115 | 116 | import { |
| 116 | 117 | changePassword, |
| 117 | 118 | iconPng, |
| @@ -523,6 +524,8 @@ export function buildRouter(): Router<Handler> { | ||
| 523 | 524 | router.add("GET", "/sitemap.xml", sitemapXml); |
| 524 | 525 | router.add("GET", "/manifest.webmanifest", webManifest); |
| 525 | 526 | router.add("GET", "/icons/:spec.png", iconPng); |
| 527 | // Open Graph cards: `/og/:kind/<ref>.svg`, the ref the thing's own path. | |
| 528 | router.add("GET", "/og/:kind/*ref", ogCardPage); | |
| 526 | 529 | // The highlighter bundle, content-addressed. A stale hash is a 404 rather |
| 527 | 530 | // than a redirect: the page that asked for it names the hash it was built |
| 528 | 531 | // with, so a miss means an old tab, and an old tab should reload. |
src/web/og/card.ts added +238
| @@ -0,0 +1,238 @@ | ||
| 1 | /** | |
| 2 | * The Open Graph card: typed page data in, a 1200×630 SVG out. 1200×630 | |
| 3 | * (1.91:1) is the size the Open Graph consumers (Facebook, LinkedIn, Slack, | |
| 4 | * Discord, X's `summary_large_image`) crop to without letterboxing. | |
| 5 | * | |
| 6 | * Pure: no database, no clock, no request — the same card always draws the | |
| 7 | * same bytes, which is what lets `pages/og.ts` cache it by a hash of its | |
| 8 | * input. Colours are the default theme's tokens (`design/themes.ts`) and | |
| 9 | * type is the studio's stacks (`design/type.ts`). | |
| 10 | * | |
| 11 | * Text cannot be measured here (the reader's renderer picks the face), so | |
| 12 | * widths are estimated from a per-character advance table that errs wide: | |
| 13 | * a line may stop a little early, it never runs off the card. Everything is | |
| 14 | * drawn with presentation attributes, never `style`, so the forge's | |
| 15 | * `default-src 'none'` floor leaves the card intact when it is opened | |
| 16 | * directly. | |
| 17 | */ | |
| 18 | ||
| 19 | import { THEMES } from "../../design/themes.ts"; | |
| 20 | import { FONT_SANS } from "../../design/type.ts"; | |
| 21 | ||
| 22 | export const OG_KINDS = ["app", "repo", "issue", "pull", "run"] as const; | |
| 23 | export type OgKind = (typeof OG_KINDS)[number]; | |
| 24 | ||
| 25 | export function isOgKind(value: string): value is OgKind { | |
| 26 | return (OG_KINDS as readonly string[]).includes(value); | |
| 27 | } | |
| 28 | ||
| 29 | export interface Card { | |
| 30 | readonly kind: OgKind; | |
| 31 | /** The one big line: a repository's name, an issue's title. Wraps to two lines. */ | |
| 32 | readonly title: string; | |
| 33 | /** Context under the title, one line each; at most `MAX_LINES` are drawn. */ | |
| 34 | readonly lines: readonly string[]; | |
| 35 | /** The one fact at the foot: a state, a count. */ | |
| 36 | readonly stat: string; | |
| 37 | } | |
| 38 | ||
| 39 | export const WIDTH = 1200; | |
| 40 | export const HEIGHT = 630; | |
| 41 | /** Left and right margin, px. The text column is `WIDTH - 2 * PAD` = 1040 px. */ | |
| 42 | const PAD = 80; | |
| 43 | const COLUMN = WIDTH - 2 * PAD; | |
| 44 | export const MAX_LINES = 3; | |
| 45 | const TITLE_LINES = 2; | |
| 46 | ||
| 47 | /** What the eyebrow over the title calls each kind. */ | |
| 48 | const KIND_LABEL: Record<OgKind, string> = { | |
| 49 | app: "App", | |
| 50 | repo: "Repository", | |
| 51 | issue: "Issue", | |
| 52 | pull: "Pull request", | |
| 53 | run: "Run", | |
| 54 | }; | |
| 55 | ||
| 56 | interface Font { | |
| 57 | /** px */ | |
| 58 | readonly size: number; | |
| 59 | readonly bold: boolean; | |
| 60 | } | |
| 61 | ||
| 62 | const EYEBROW: Font = { size: 26, bold: true }; | |
| 63 | const TITLE: Font = { size: 64, bold: true }; | |
| 64 | const LINE: Font = { size: 30, bold: false }; | |
| 65 | const STAT: Font = { size: 30, bold: true }; | |
| 66 | const MARK: Font = { size: 26, bold: true }; | |
| 67 | ||
| 68 | const NARROW = new Set("iljI.,:;'|!`·"); | |
| 69 | const SLIM = new Set("frt()[]{}-/\\\" "); | |
| 70 | const WIDE = new Set("mwMW@%&"); | |
| 71 | ||
| 72 | /** | |
| 73 | * Advance width in em of one code point, at regular weight. The figures are | |
| 74 | * rounded up from Arial/Helvetica's metrics (e.g. `i` 0.222, `a` 0.556, | |
| 75 | * `M` 0.833, digits 0.556, in 1/1000 em), the widest common fallback for | |
| 76 | * `system-ui`; CJK and emoji take a full em. | |
| 77 | */ | |
| 78 | function advance(ch: string): number { | |
| 79 | const cp = ch.codePointAt(0) ?? 0; | |
| 80 | if (cp >= 0x300 && cp <= 0x36f) return 0; // combining marks | |
| 81 | if (cp >= 0x2e80) return 1; | |
| 82 | if (NARROW.has(ch)) return 0.3; | |
| 83 | if (SLIM.has(ch)) return 0.4; | |
| 84 | if (WIDE.has(ch)) return 0.95; | |
| 85 | if (cp >= 0x41 && cp <= 0x5a) return 0.74; // A–Z | |
| 86 | return 0.6; | |
| 87 | } | |
| 88 | ||
| 89 | /** Bold faces run about 6% wider than regular in the same stacks; 10% is the margin. */ | |
| 90 | const BOLD = 1.1; | |
| 91 | ||
| 92 | /** Estimated width of `text` in px. */ | |
| 93 | export function textWidth(text: string, font: Font): number { | |
| 94 | let em = 0; | |
| 95 | for (const ch of text) em += advance(ch); | |
| 96 | return em * font.size * (font.bold ? BOLD : 1); | |
| 97 | } | |
| 98 | ||
| 99 | const ELLIPSIS = "…"; | |
| 100 | ||
| 101 | /** `text` cut to fit `max` px, ending in an ellipsis when it was cut. */ | |
| 102 | export function clamp(text: string, font: Font, max: number): string { | |
| 103 | if (textWidth(text, font) <= max) return text; | |
| 104 | const room = max - textWidth(ELLIPSIS, font); | |
| 105 | const scale = font.size * (font.bold ? BOLD : 1); | |
| 106 | let used = 0; | |
| 107 | let out = ""; | |
| 108 | for (const ch of text) { | |
| 109 | used += advance(ch) * scale; | |
| 110 | if (used > room) break; | |
| 111 | out += ch; | |
| 112 | } | |
| 113 | return out.trimEnd() + ELLIPSIS; | |
| 114 | } | |
| 115 | ||
| 116 | /** | |
| 117 | * Greedy word wrap into at most `lines` lines, each within `max` px; the | |
| 118 | * last line is clamped. A word wider than a line is broken where it fills. | |
| 119 | */ | |
| 120 | export function wrap( | |
| 121 | text: string, | |
| 122 | font: Font, | |
| 123 | max: number, | |
| 124 | lines: number, | |
| 125 | ): string[] { | |
| 126 | const out: string[] = []; | |
| 127 | let rest = text; | |
| 128 | while (rest !== "" && out.length < lines - 1) { | |
| 129 | if (textWidth(rest, font) <= max) { | |
| 130 | out.push(rest); | |
| 131 | return out; | |
| 132 | } | |
| 133 | const cut = breakAt(rest, font, max); | |
| 134 | out.push(rest.slice(0, cut).trimEnd()); | |
| 135 | rest = rest.slice(cut).trimStart(); | |
| 136 | } | |
| 137 | if (rest !== "") out.push(clamp(rest, font, max)); | |
| 138 | return out; | |
| 139 | } | |
| 140 | ||
| 141 | /** The index to end a line at: the last space that fits, else as much as fits. */ | |
| 142 | function breakAt(text: string, font: Font, max: number): number { | |
| 143 | const scale = font.size * (font.bold ? BOLD : 1); | |
| 144 | let used = 0; | |
| 145 | let fit = 0; | |
| 146 | let space = -1; | |
| 147 | let i = 0; | |
| 148 | for (const ch of text) { | |
| 149 | used += advance(ch) * scale; | |
| 150 | if (used > max) break; | |
| 151 | if (ch === " ") space = i; | |
| 152 | i += ch.length; | |
| 153 | fit = i; | |
| 154 | } | |
| 155 | if (space > 0) return space; | |
| 156 | // Always make progress, even when one character is wider than the line. | |
| 157 | return Math.max(fit, (text.codePointAt(0) ?? 0) > 0xffff ? 2 : 1); | |
| 158 | } | |
| 159 | ||
| 160 | /** | |
| 161 | * Plain text as it may stand in an SVG text node: characters XML 1.0 does | |
| 162 | * not allow (C0 controls but tab/newline/return, lone surrogates, U+FFFE/F) | |
| 163 | * dropped, every run of whitespace one space. | |
| 164 | */ | |
| 165 | export function plain(text: string): string { | |
| 166 | return text | |
| 167 | .replace(/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu, "") | |
| 168 | .replace(/\s+/g, " ") | |
| 169 | .trim(); | |
| 170 | } | |
| 171 | ||
| 172 | /** XML-escape text for a text node or a double-quoted attribute. */ | |
| 173 | export function xml(text: string): string { | |
| 174 | return text | |
| 175 | .replace(/&/g, "&") | |
| 176 | .replace(/</g, "<") | |
| 177 | .replace(/>/g, ">") | |
| 178 | .replace(/"/g, """) | |
| 179 | .replace(/'/g, "'"); | |
| 180 | } | |
| 181 | ||
| 182 | function textEl( | |
| 183 | x: number, | |
| 184 | y: number, | |
| 185 | font: Font, | |
| 186 | fill: string, | |
| 187 | body: string, | |
| 188 | anchor: "start" | "end" = "start", | |
| 189 | ): string { | |
| 190 | const weight = font.bold ? ` font-weight="700"` : ""; | |
| 191 | const end = anchor === "end" ? ` text-anchor="end"` : ""; | |
| 192 | return `<text x="${x}" y="${y}" font-size="${font.size}"${weight}${end} fill="${fill}">${xml(body)}</text>`; | |
| 193 | } | |
| 194 | ||
| 195 | /** The card as an SVG document. */ | |
| 196 | export function ogCard(card: Card): string { | |
| 197 | const t = THEMES.light.tokens; | |
| 198 | const parts: string[] = []; | |
| 199 | parts.push(`<rect width="${WIDTH}" height="${HEIGHT}" fill="${t.card}"/>`); | |
| 200 | parts.push(`<rect width="${WIDTH}" height="12" fill="${t.accent}"/>`); | |
| 201 | parts.push( | |
| 202 | textEl(PAD, 128, EYEBROW, t["muted-fg"], clamp(KIND_LABEL[card.kind], EYEBROW, COLUMN)), | |
| 203 | ); | |
| 204 | ||
| 205 | // Title baselines at 216 and 292 (64 px type on a 76 px line). | |
| 206 | const title = wrap(plain(card.title), TITLE, COLUMN, TITLE_LINES); | |
| 207 | let y = 216; | |
| 208 | for (const line of title) { | |
| 209 | parts.push(textEl(PAD, y, TITLE, t.fg, line)); | |
| 210 | y += 76; | |
| 211 | } | |
| 212 | ||
| 213 | // Context lines start a gap below the title, 44 px apart, and stop above the rule. | |
| 214 | y += 6; | |
| 215 | for (const raw of card.lines.slice(0, MAX_LINES)) { | |
| 216 | const line = clamp(plain(raw), LINE, COLUMN); | |
| 217 | if (line === "") continue; | |
| 218 | parts.push(textEl(PAD, y, LINE, t["muted-fg"], line)); | |
| 219 | y += 44; | |
| 220 | } | |
| 221 | ||
| 222 | // The foot: a rule, the stat on the left, the mark on the right. | |
| 223 | parts.push( | |
| 224 | `<rect x="${PAD}" y="520" width="${COLUMN}" height="2" fill="${t.border}"/>`, | |
| 225 | ); | |
| 226 | const mark = "forge"; | |
| 227 | const markRoom = textWidth(mark, MARK) + 40; | |
| 228 | parts.push( | |
| 229 | textEl(PAD, 578, STAT, t.accent, clamp(plain(card.stat), STAT, COLUMN - markRoom)), | |
| 230 | ); | |
| 231 | parts.push(textEl(WIDTH - PAD, 578, MARK, t.faint, mark, "end")); | |
| 232 | ||
| 233 | return ( | |
| 234 | `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}" font-family="${xml(FONT_SANS)}">` + | |
| 235 | parts.join("") + | |
| 236 | `</svg>` | |
| 237 | ); | |
| 238 | } |
src/web/pages/og.ts added +254
| @@ -0,0 +1,254 @@ | ||
| 1 | /** | |
| 2 | * `GET /og/:kind/:ref.svg` — the Open Graph card for an app, a repository, | |
| 3 | * an issue, a pull or a run, drawn by `og/card.ts` from what the forge | |
| 4 | * holds now. The ref is the thing's own path, its slashes kept or encoded: | |
| 5 | * | |
| 6 | * /og/app/<slug>.svg | |
| 7 | * /og/repo/<owner>/<name>.svg | |
| 8 | * /og/issue/<owner>/<name>/<number>.svg | |
| 9 | * /og/pull/<owner>/<name>/<number>.svg | |
| 10 | * /og/run/<id>.svg | |
| 11 | * | |
| 12 | * A card reads only what its viewer may read, through the checks every | |
| 13 | * page uses; anything else — an unknown kind, a private repository, a | |
| 14 | * sealed issue — is the one `not_found`. | |
| 15 | * | |
| 16 | * Cards are cached in memory by the sha256 of their input, which is also | |
| 17 | * the ETag, so a repeat answers 304 and a warm miss on the client costs a | |
| 18 | * few queries and a map lookup. A card anyone may read is | |
| 19 | * `Cache-Control: public`; one only this viewer may read is `private`, so a | |
| 20 | * shared cache never hands a private repository's card to someone else. | |
| 21 | */ | |
| 22 | ||
| 23 | import { getRepoRun } from "../../actions/runs.ts"; | |
| 24 | import { getAppBySlug, isSlug } from "../../core/apps.ts"; | |
| 25 | import { getIssue } from "../../core/issues.ts"; | |
| 26 | import { getPull } from "../../core/pulls.ts"; | |
| 27 | import { | |
| 28 | canRead, | |
| 29 | countsForRepos, | |
| 30 | getRepo, | |
| 31 | getRepoById, | |
| 32 | type Repo, | |
| 33 | } from "../../core/repos.ts"; | |
| 34 | import { getRun } from "../../core/runs.ts"; | |
| 35 | import { mayView } from "../../core/sealed.ts"; | |
| 36 | import type { User } from "../../core/users.ts"; | |
| 37 | import type { Ctx } from "../../http/context.ts"; | |
| 38 | import { notFound } from "../../http/respond.ts"; | |
| 39 | import { sha256 } from "../../kernel/hash.ts"; | |
| 40 | import { isOgKind, ogCard, type Card, type OgKind } from "../og/card.ts"; | |
| 41 | ||
| 42 | /** How long a reader may reuse a card before asking again, in seconds. */ | |
| 43 | const MAX_AGE = 300; | |
| 44 | ||
| 45 | /** Cards kept drawn; the oldest goes first. ~2 KB each, so about 1 MB. */ | |
| 46 | const CACHE_MAX = 500; | |
| 47 | ||
| 48 | interface Drawn { | |
| 49 | readonly svg: string; | |
| 50 | readonly etag: string; | |
| 51 | } | |
| 52 | ||
| 53 | const drawn = new Map<string, Drawn>(); | |
| 54 | ||
| 55 | /** The card for `card`, from the cache or drawn now; keyed by the sha256 of the input. */ | |
| 56 | export function drawCard(card: Card): Drawn { | |
| 57 | const hash = sha256( | |
| 58 | JSON.stringify([card.kind, card.title, card.lines, card.stat]), | |
| 59 | ); | |
| 60 | const hit = drawn.get(hash); | |
| 61 | if (hit !== undefined) return hit; | |
| 62 | const made = { svg: ogCard(card), etag: `"${hash}"` }; | |
| 63 | if (drawn.size >= CACHE_MAX) { | |
| 64 | const oldest = drawn.keys().next(); | |
| 65 | if (!oldest.done) drawn.delete(oldest.value); | |
| 66 | } | |
| 67 | drawn.set(hash, made); | |
| 68 | return made; | |
| 69 | } | |
| 70 | ||
| 71 | /** A card, and whether a reader who is not signed in would see the same one. */ | |
| 72 | interface Found { | |
| 73 | readonly card: Card; | |
| 74 | readonly open: boolean; | |
| 75 | } | |
| 76 | ||
| 77 | const NUMBER = /^[1-9][0-9]{0,8}$/; | |
| 78 | const RUN_ID = /^[0-9A-Za-z]{1,64}$/; | |
| 79 | ||
| 80 | function plural(n: number, one: string, many: string): string { | |
| 81 | return `${n} ${n === 1 ? one : many}`; | |
| 82 | } | |
| 83 | ||
| 84 | function readableRepo( | |
| 85 | ctx: Ctx, | |
| 86 | owner: string | undefined, | |
| 87 | name: string | undefined, | |
| 88 | ): Repo | undefined { | |
| 89 | if (owner === undefined || name === undefined) return undefined; | |
| 90 | const repo = getRepo(ctx.app.db, owner, name); | |
| 91 | if (!repo || !canRead(ctx.app.db, repo, ctx.auth.user)) return undefined; | |
| 92 | return repo; | |
| 93 | } | |
| 94 | ||
| 95 | const anyone = (ctx: Ctx, repo: Repo): boolean => | |
| 96 | canRead(ctx.app.db, repo, undefined); | |
| 97 | ||
| 98 | function repoCard(ctx: Ctx, parts: string[]): Found | undefined { | |
| 99 | if (parts.length !== 2) return undefined; | |
| 100 | const repo = readableRepo(ctx, parts[0], parts[1]); | |
| 101 | if (!repo) return undefined; | |
| 102 | const counts = countsForRepos(ctx.app.db, [repo.id]).get(repo.id); | |
| 103 | const issues = counts?.openIssues ?? 0; | |
| 104 | const pulls = counts?.openPulls ?? 0; | |
| 105 | return { | |
| 106 | card: { | |
| 107 | kind: "repo", | |
| 108 | title: `${repo.ownerName}/${repo.name}`, | |
| 109 | lines: [repo.description], | |
| 110 | stat: `${plural(issues, "open issue", "open issues")} · ${plural(pulls, "open pull", "open pulls")}`, | |
| 111 | }, | |
| 112 | open: anyone(ctx, repo), | |
| 113 | }; | |
| 114 | } | |
| 115 | ||
| 116 | function threadCard( | |
| 117 | ctx: Ctx, | |
| 118 | kind: "issue" | "pull", | |
| 119 | parts: string[], | |
| 120 | ): Found | undefined { | |
| 121 | if (parts.length !== 3 || !NUMBER.test(parts[2] ?? "")) return undefined; | |
| 122 | const repo = readableRepo(ctx, parts[0], parts[1]); | |
| 123 | if (!repo) return undefined; | |
| 124 | const number = Number(parts[2]); | |
| 125 | const where = `${repo.ownerName}/${repo.name} #${number}`; | |
| 126 | const viewer: User | undefined = ctx.auth.user; | |
| 127 | if (kind === "issue") { | |
| 128 | const issue = getIssue(ctx.app.db, repo.id, number); | |
| 129 | if (!issue || issue.kind !== "issue") return undefined; | |
| 130 | if (!mayView(ctx.app.db, repo, issue, viewer)) return undefined; | |
| 131 | return { | |
| 132 | card: { | |
| 133 | kind, | |
| 134 | title: issue.title, | |
| 135 | lines: [where, `opened by ${issue.originAuthor ?? issue.authorName}`], | |
| 136 | stat: issue.state === "open" ? "Open" : "Closed", | |
| 137 | }, | |
| 138 | open: anyone(ctx, repo) && mayView(ctx.app.db, repo, issue, undefined), | |
| 139 | }; | |
| 140 | } | |
| 141 | const pull = getPull(ctx.app.db, repo.id, number); | |
| 142 | if (!pull || !mayView(ctx.app.db, repo, pull, viewer)) return undefined; | |
| 143 | return { | |
| 144 | card: { | |
| 145 | kind, | |
| 146 | title: pull.title, | |
| 147 | lines: [ | |
| 148 | where, | |
| 149 | `${pull.headBranch} → ${pull.baseBranch}, by ${pull.originAuthor ?? pull.authorName}`, | |
| 150 | ], | |
| 151 | stat: | |
| 152 | pull.mergedAt !== null | |
| 153 | ? "Merged" | |
| 154 | : pull.state === "open" | |
| 155 | ? "Open" | |
| 156 | : "Closed", | |
| 157 | }, | |
| 158 | open: anyone(ctx, repo) && mayView(ctx.app.db, repo, pull, undefined), | |
| 159 | }; | |
| 160 | } | |
| 161 | ||
| 162 | const RUN_STATE: Record<string, string> = { | |
| 163 | queued: "Queued", | |
| 164 | running: "Running", | |
| 165 | ok: "Passed", | |
| 166 | failed: "Failed", | |
| 167 | cancelled: "Cancelled", | |
| 168 | }; | |
| 169 | ||
| 170 | function runCard(ctx: Ctx, parts: string[]): Found | undefined { | |
| 171 | const id = parts.length === 1 ? (parts[0] ?? "") : ""; | |
| 172 | if (!RUN_ID.test(id)) return undefined; | |
| 173 | const found = getRun(ctx.app.db, id); | |
| 174 | const repo = found && getRepoById(ctx.app.db, found.repoId); | |
| 175 | if (!repo) return undefined; | |
| 176 | const run = getRepoRun(ctx.app, ctx.auth.user, repo, id); | |
| 177 | if (!run.ok) return undefined; | |
| 178 | const r = run.value; | |
| 179 | const what = r.kind === "deploy" ? "Deploy" : r.kind === "agent" ? "Agent run" : "Check"; | |
| 180 | const at = [r.env, r.branch, r.commitOid.slice(0, 12)].filter((s) => s !== ""); | |
| 181 | return { | |
| 182 | card: { | |
| 183 | kind: "run", | |
| 184 | title: r.summary !== "" ? r.summary : `${what} on ${repo.ownerName}/${repo.name}`, | |
| 185 | lines: [`${what} · ${repo.ownerName}/${repo.name}`, at.join(" · ")], | |
| 186 | stat: RUN_STATE[r.state] ?? r.state, | |
| 187 | }, | |
| 188 | open: getRepoRun(ctx.app, undefined, repo, id).ok, | |
| 189 | }; | |
| 190 | } | |
| 191 | ||
| 192 | function appCard(ctx: Ctx, parts: string[]): Found | undefined { | |
| 193 | const slug = parts.length === 1 ? (parts[0] ?? "") : ""; | |
| 194 | if (!isSlug(slug)) return undefined; | |
| 195 | const record = getAppBySlug(ctx.app.db, slug); | |
| 196 | const repo = record && getRepoById(ctx.app.db, record.repoId); | |
| 197 | if (!record || !repo || !canRead(ctx.app.db, repo, ctx.auth.user)) | |
| 198 | return undefined; | |
| 199 | return { | |
| 200 | card: { | |
| 201 | kind: "app", | |
| 202 | title: record.slug, | |
| 203 | lines: [repo.description, `from ${repo.ownerName}/${repo.name}`], | |
| 204 | stat: record.access === "public" ? "Open to anyone" : "Private", | |
| 205 | }, | |
| 206 | open: anyone(ctx, repo) && record.access === "public", | |
| 207 | }; | |
| 208 | } | |
| 209 | ||
| 210 | function find(ctx: Ctx, kind: OgKind, parts: string[]): Found | undefined { | |
| 211 | switch (kind) { | |
| 212 | case "repo": | |
| 213 | return repoCard(ctx, parts); | |
| 214 | case "issue": | |
| 215 | case "pull": | |
| 216 | return threadCard(ctx, kind, parts); | |
| 217 | case "run": | |
| 218 | return runCard(ctx, parts); | |
| 219 | case "app": | |
| 220 | return appCard(ctx, parts); | |
| 221 | } | |
| 222 | } | |
| 223 | ||
| 224 | /** Whether an `If-None-Match` header names this ETag (or `*`). */ | |
| 225 | function matches(header: string | null, etag: string): boolean { | |
| 226 | if (header === null) return false; | |
| 227 | return header | |
| 228 | .split(",") | |
| 229 | .map((tag) => tag.trim().replace(/^W\//, "")) | |
| 230 | .some((tag) => tag === etag || tag === "*"); | |
| 231 | } | |
| 232 | ||
| 233 | /** GET /og/:kind/*ref — `ref` ends in `.svg`. */ | |
| 234 | export function ogCardPage(ctx: Ctx): Response { | |
| 235 | const kind = ctx.params["kind"] ?? ""; | |
| 236 | const ref = ctx.params["ref"] ?? ""; | |
| 237 | if (!isOgKind(kind) || !ref.endsWith(".svg") || ref.length > 512) | |
| 238 | return notFound(); | |
| 239 | const parts = ref.slice(0, -".svg".length).split("/"); | |
| 240 | if (parts.some((p) => p === "")) return notFound(); | |
| 241 | const found = find(ctx, kind, parts); | |
| 242 | if (!found) return notFound(); | |
| 243 | const { svg, etag } = drawCard(found.card); | |
| 244 | const headers = { | |
| 245 | etag, | |
| 246 | "cache-control": `${found.open ? "public" : "private"}, max-age=${MAX_AGE}`, | |
| 247 | vary: "Cookie, Authorization", | |
| 248 | }; | |
| 249 | if (matches(ctx.request.headers.get("if-none-match"), etag)) | |
| 250 | return new Response(null, { status: 304, headers }); | |
| 251 | return new Response(svg, { | |
| 252 | headers: { ...headers, "content-type": "image/svg+xml; charset=utf-8" }, | |
| 253 | }); | |
| 254 | } |
src/web/style/base.ts +4 −2
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | * prose. Hierarchy comes from weight and color, not size. |
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | import { FONT_MONO, FONT_SANS } from "../../design/type.ts"; | |
| 12 | ||
| 11 | 13 | /** |
| 12 | 14 | * The cascade order, declared once and up front, plus the one at-rule that |
| 13 | 15 | * must sit outside every layer. Cross-document view transitions are pure |
| @@ -30,8 +32,8 @@ export const base = /* css */ ` | ||
| 30 | 32 | --page: 1120px; |
| 31 | 33 | --measure: 72ch; |
| 32 | 34 | --ease: cubic-bezier(.2, 0, 0, 1); |
| 33 | --font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; | |
| 34 | --mono: ui-monospace, "SF Mono", SFMono-Regular, "Cascadia Code", "JetBrains Mono", Menlo, Consolas, "Liberation Mono", monospace; | |
| 35 | --font: ${FONT_SANS}; | |
| 36 | --mono: ${FONT_MONO}; | |
| 35 | 37 | } |
| 36 | 38 | |
| 37 | 39 | html { |
test/og-card.test.ts added +363
| @@ -0,0 +1,363 @@ | ||
| 1 | /** | |
| 2 | * Open Graph cards (#1054): `og/card.ts` draws a 1200×630 SVG from typed | |
| 3 | * data, with hostile text escaped and clamped; `/og/:kind/<ref>.svg` draws | |
| 4 | * one for each kind from live data, only for what the viewer may read, | |
| 5 | * cached by the hash of its input and answered 304 on a repeat. | |
| 6 | */ | |
| 7 | ||
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { openIssue } from "../src/actions/issues.ts"; | |
| 14 | import { openPull } from "../src/actions/pulls.ts"; | |
| 15 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 17 | import type { Repo } from "../src/core/repos.ts"; | |
| 18 | import { createRun } from "../src/core/runs.ts"; | |
| 19 | import { createSession } from "../src/core/sessions.ts"; | |
| 20 | import { createUser, type User } from "../src/core/users.ts"; | |
| 21 | import { securityFloor } from "../src/http/respond.ts"; | |
| 22 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 23 | import { | |
| 24 | clamp, | |
| 25 | HEIGHT, | |
| 26 | ogCard, | |
| 27 | OG_KINDS, | |
| 28 | textWidth, | |
| 29 | WIDTH, | |
| 30 | wrap, | |
| 31 | type Card, | |
| 32 | } from "../src/web/og/card.ts"; | |
| 33 | import { quietLogs } from "./helpers/globals.ts"; | |
| 34 | ||
| 35 | quietLogs(); | |
| 36 | ||
| 37 | /** | |
| 38 | * A small well-formedness check, enough for what the card writes: every | |
| 39 | * tag closes in order, every attribute is quoted, and no `<` or bare `&` | |
| 40 | * stands in text or in an attribute. Returns the element names, in order. | |
| 41 | */ | |
| 42 | function wellFormed(doc: string): string[] { | |
| 43 | const names: string[] = []; | |
| 44 | const open: string[] = []; | |
| 45 | const entity = /^&(amp|lt|gt|quot|apos|#[0-9]+|#x[0-9a-fA-F]+);/; | |
| 46 | let i = 0; | |
| 47 | const text = (s: string) => { | |
| 48 | for (let j = 0; j < s.length; j++) { | |
| 49 | if (s[j] === "<") throw new Error(`raw < at ${i + j}`); | |
| 50 | if (s[j] === "&" && !entity.test(s.slice(j))) | |
| 51 | throw new Error(`bare & at ${i + j}`); | |
| 52 | } | |
| 53 | }; | |
| 54 | while (i < doc.length) { | |
| 55 | const lt = doc.indexOf("<", i); | |
| 56 | if (lt === -1) { | |
| 57 | text(doc.slice(i)); | |
| 58 | break; | |
| 59 | } | |
| 60 | text(doc.slice(i, lt)); | |
| 61 | const gt = doc.indexOf(">", lt); | |
| 62 | if (gt === -1) throw new Error("unclosed tag"); | |
| 63 | const tag = doc.slice(lt + 1, gt); | |
| 64 | if (tag.startsWith("/")) { | |
| 65 | const name = tag.slice(1); | |
| 66 | if (open.pop() !== name) throw new Error(`mismatched </${name}>`); | |
| 67 | } else { | |
| 68 | const selfClosing = tag.endsWith("/"); | |
| 69 | const body = selfClosing ? tag.slice(0, -1) : tag; | |
| 70 | const m = /^([a-zA-Z][\w:-]*)((?:\s+[\w:-]+="[^"<]*")*)\s*$/.exec(body); | |
| 71 | if (m === null) throw new Error(`bad tag <${tag}>`); | |
| 72 | for (const value of m[2]!.matchAll(/="([^"]*)"/g)) text(value[1]!); | |
| 73 | names.push(m[1]!); | |
| 74 | if (!selfClosing) open.push(m[1]!); | |
| 75 | } | |
| 76 | i = gt + 1; | |
| 77 | } | |
| 78 | if (open.length !== 0) throw new Error(`unclosed <${open.join(", ")}>`); | |
| 79 | return names; | |
| 80 | } | |
| 81 | ||
| 82 | /** The text nodes of a card, unescaped. */ | |
| 83 | function texts(svg: string): string[] { | |
| 84 | return [...svg.matchAll(/<text[^>]*>([^<]*)<\/text>/g)].map((m) => | |
| 85 | m[1]! | |
| 86 | .replace(/</g, "<") | |
| 87 | .replace(/>/g, ">") | |
| 88 | .replace(/"/g, '"') | |
| 89 | .replace(/'/g, "'") | |
| 90 | .replace(/&/g, "&"), | |
| 91 | ); | |
| 92 | } | |
| 93 | ||
| 94 | const HOSTILE = `<script>alert("x")</script> & 'friends' ${"W".repeat(500)}`; | |
| 95 | ||
| 96 | describe("og/card", () => { | |
| 97 | test("each kind renders well-formed XML at 1200×630", () => { | |
| 98 | for (const kind of OG_KINDS) { | |
| 99 | const svg = ogCard({ | |
| 100 | kind, | |
| 101 | title: `A ${kind}`, | |
| 102 | lines: ["one", "two"], | |
| 103 | stat: "Open", | |
| 104 | }); | |
| 105 | expect(wellFormed(svg)[0]).toBe("svg"); | |
| 106 | expect(svg).toContain(`width="${WIDTH}" height="${HEIGHT}"`); | |
| 107 | expect(svg).toContain(`viewBox="0 0 1200 630"`); | |
| 108 | expect(WIDTH).toBe(1200); | |
| 109 | expect(HEIGHT).toBe(630); | |
| 110 | } | |
| 111 | }); | |
| 112 | ||
| 113 | test("a hostile title is escaped and clamped to the card", () => { | |
| 114 | const card: Card = { | |
| 115 | kind: "issue", | |
| 116 | title: HOSTILE, | |
| 117 | lines: [HOSTILE, "\u0000\u0008control\uD800 bytes"], | |
| 118 | stat: HOSTILE, | |
| 119 | }; | |
| 120 | const svg = ogCard(card); | |
| 121 | wellFormed(svg); | |
| 122 | expect(svg).not.toContain("<script"); | |
| 123 | expect(svg).toContain("<script>"); | |
| 124 | expect(svg).toContain("& 'friends'"); | |
| 125 | // Characters XML forbids are gone, not escaped. | |
| 126 | expect(svg).not.toMatch(/[\u0000-\u0008]/); | |
| 127 | expect(svg).toContain(">control bytes<"); | |
| 128 | const drawn = texts(svg); | |
| 129 | // Eyebrow, two title lines, two context lines, stat, mark. | |
| 130 | expect(drawn).toHaveLength(7); | |
| 131 | const [, first, second, line, , stat] = drawn; | |
| 132 | expect(first).toBe(`<script>alert("x")</script>`); | |
| 133 | expect(second!.endsWith("…")).toBe(true); | |
| 134 | expect(textWidth(second!, { size: 64, bold: true })).toBeLessThanOrEqual(1040); | |
| 135 | expect(line!.endsWith("…")).toBe(true); | |
| 136 | expect(textWidth(line!, { size: 30, bold: false })).toBeLessThanOrEqual(1040); | |
| 137 | expect(stat!.endsWith("…")).toBe(true); | |
| 138 | expect(textWidth(stat!, { size: 30, bold: true })).toBeLessThanOrEqual(1040); | |
| 139 | }); | |
| 140 | ||
| 141 | test("clamp and wrap keep every line inside the width, by hand", () => { | |
| 142 | // "W" is 0.95 em; at 20 px regular that is 19 px a character. | |
| 143 | const font = { size: 20, bold: false }; | |
| 144 | expect(textWidth("WW", font)).toBeCloseTo(38, 6); | |
| 145 | expect(clamp("WWW", font, 57)).toBe("WWW"); | |
| 146 | // 56 px: the ellipsis (0.6 em = 12 px) leaves 44, so two W fit. | |
| 147 | expect(clamp("WWW", font, 56)).toBe("WW…"); | |
| 148 | const lines = wrap("aaaa bbbb cccc dddd", font, 120, 2); | |
| 149 | // "a" is 0.6 em = 12 px, space 0.4 em = 8 px: "aaaa bbbb" is 104 px. | |
| 150 | expect(lines[0]).toBe("aaaa bbbb"); | |
| 151 | expect(lines[1]).toBe("cccc dddd"); | |
| 152 | for (const line of wrap("x".repeat(400), font, 120, 2)) | |
| 153 | expect(textWidth(line, font)).toBeLessThanOrEqual(120); | |
| 154 | }); | |
| 155 | }); | |
| 156 | ||
| 157 | describe("GET /og/:kind/:ref.svg", () => { | |
| 158 | let dataDir: string; | |
| 159 | let app: App; | |
| 160 | let http: ForgeHttp; | |
| 161 | let alice: User; | |
| 162 | let mallory: User; | |
| 163 | let open: Repo; | |
| 164 | let closed: Repo; | |
| 165 | let runId = ""; | |
| 166 | let closedRunId = ""; | |
| 167 | ||
| 168 | beforeAll(async () => { | |
| 169 | dataDir = await mkdtemp(join(tmpdir(), "forge-og-")); | |
| 170 | app = createApp({ dataDir, port: 0 }); | |
| 171 | // The forge's whole request path (auth, routing, the security floor), | |
| 172 | // without a listener. | |
| 173 | http = forgeHttp(app); | |
| 174 | const a = await createUser(app.db, { | |
| 175 | trusted: true, | |
| 176 | username: "alice", | |
| 177 | email: "[email protected]", | |
| 178 | password: "a-good-passphrase", | |
| 179 | adminIfFirst: true, | |
| 180 | }); | |
| 181 | if (!a.ok) throw new Error(a.error); | |
| 182 | alice = a.value; | |
| 183 | const m = await createUser(app.db, { | |
| 184 | trusted: true, | |
| 185 | username: "mallory", | |
| 186 | email: "[email protected]", | |
| 187 | password: "a-good-passphrase", | |
| 188 | }); | |
| 189 | if (!m.ok) throw new Error(m.error); | |
| 190 | mallory = m.value; | |
| 191 | const pub = await createRepo(app, alice, { | |
| 192 | name: "open", | |
| 193 | visibility: "public", | |
| 194 | description: "A garden & a <fence>", | |
| 195 | }); | |
| 196 | if (!pub.ok) throw new Error(String(pub.error)); | |
| 197 | open = pub.value; | |
| 198 | const priv = await createRepo(app, alice, { | |
| 199 | name: "closed", | |
| 200 | visibility: "private", | |
| 201 | }); | |
| 202 | if (!priv.ok) throw new Error(String(priv.error)); | |
| 203 | closed = priv.value; | |
| 204 | for (const repo of [open, closed]) { | |
| 205 | await commitToBranch(app, alice, repo, { | |
| 206 | message: "seed", | |
| 207 | files: [{ path: "README.md", content: "# seed\n" }], | |
| 208 | }); | |
| 209 | const issue = openIssue(app, alice, repo, { | |
| 210 | title: `<script>x</script> & ${"W".repeat(200)}`, | |
| 211 | }); | |
| 212 | if (!issue.ok) throw new Error(String(issue.error)); | |
| 213 | const committed = await commitToBranch(app, alice, repo, { | |
| 214 | branch: "feature", | |
| 215 | base: "main", | |
| 216 | message: "feature", | |
| 217 | files: [{ path: "f.md", content: "x\n" }], | |
| 218 | }); | |
| 219 | if (!committed.ok) throw new Error(String(committed.error)); | |
| 220 | const pull = await openPull(app, alice, repo, { | |
| 221 | title: "Add the feature", | |
| 222 | baseBranch: "main", | |
| 223 | headBranch: "feature", | |
| 224 | }); | |
| 225 | if (!pull.ok) throw new Error(String(pull.error)); | |
| 226 | } | |
| 227 | runId = createRun(app.db, { | |
| 228 | repoId: open.id, | |
| 229 | kind: "deploy", | |
| 230 | env: "production", | |
| 231 | summary: "Deployed to production", | |
| 232 | }).id; | |
| 233 | closedRunId = createRun(app.db, { repoId: closed.id, kind: "deploy" }).id; | |
| 234 | createAppRecord(app.db, { repoId: open.id, slug: "garden", access: "public" }); | |
| 235 | createAppRecord(app.db, { repoId: closed.id, slug: "vault", access: "private" }); | |
| 236 | }); | |
| 237 | ||
| 238 | afterAll(async () => { | |
| 239 | http.close(); | |
| 240 | app.close(); | |
| 241 | await rm(dataDir, { recursive: true, force: true }); | |
| 242 | }); | |
| 243 | ||
| 244 | // The floor every response leaves `serve` with, applied the same way. | |
| 245 | const get = async (path: string, headers: Record<string, string> = {}) => | |
| 246 | securityFloor( | |
| 247 | await http.handle(new Request(`http://forge.test${path}`, { headers })), | |
| 248 | ); | |
| 249 | const as = (user: User) => ({ | |
| 250 | cookie: `forge_session=${createSession(app.db, user.id).token}`, | |
| 251 | }); | |
| 252 | ||
| 253 | test("each kind answers a well-formed 1200×630 SVG from live data", async () => { | |
| 254 | const cases: [string, string][] = [ | |
| 255 | ["/og/repo/alice/open.svg", "alice/open"], | |
| 256 | ["/og/repo/alice%2Fopen.svg", "alice/open"], | |
| 257 | ["/og/issue/alice/open/1.svg", "<script>"], | |
| 258 | ["/og/pull/alice/open/2.svg", "Add the feature"], | |
| 259 | [`/og/run/${runId}.svg`, "Deployed to production"], | |
| 260 | ["/og/app/garden.svg", "garden"], | |
| 261 | ]; | |
| 262 | for (const [path, says] of cases) { | |
| 263 | const res = await get(path); | |
| 264 | expect(res.status).toBe(200); | |
| 265 | expect(res.headers.get("content-type")).toBe("image/svg+xml; charset=utf-8"); | |
| 266 | expect(res.headers.get("cache-control")).toBe("public, max-age=300"); | |
| 267 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 268 | expect(res.headers.get("content-security-policy")).toContain("default-src 'none'"); | |
| 269 | const svg = await res.text(); | |
| 270 | expect(wellFormed(svg)[0]).toBe("svg"); | |
| 271 | expect(svg).toContain(`width="1200" height="630"`); | |
| 272 | expect(svg).toContain(says); | |
| 273 | expect(svg).not.toContain("<script"); | |
| 274 | } | |
| 275 | // Live: the repository card counts what is open now, and says the description escaped. | |
| 276 | const repo = await get("/og/repo/alice/open.svg").then((r) => r.text()); | |
| 277 | expect(repo).toContain("1 open issue · 1 open pull"); | |
| 278 | expect(repo).toContain("A garden & a <fence>"); | |
| 279 | }); | |
| 280 | ||
| 281 | test("a private repository, its threads, runs and app are 404 to anyone who cannot read them", async () => { | |
| 282 | const hidden = [ | |
| 283 | "/og/repo/alice/closed.svg", | |
| 284 | "/og/issue/alice/closed/1.svg", | |
| 285 | "/og/pull/alice/closed/2.svg", | |
| 286 | `/og/run/${closedRunId}.svg`, | |
| 287 | "/og/app/vault.svg", | |
| 288 | ]; | |
| 289 | for (const path of hidden) { | |
| 290 | expect((await get(path)).status).toBe(404); | |
| 291 | expect((await get(path, as(mallory))).status).toBe(404); | |
| 292 | } | |
| 293 | // Its owner reads each, and no shared cache may keep them. | |
| 294 | for (const path of hidden) { | |
| 295 | const res = await get(path, as(alice)); | |
| 296 | expect(res.status).toBe(200); | |
| 297 | expect(res.headers.get("cache-control")).toBe("private, max-age=300"); | |
| 298 | } | |
| 299 | }); | |
| 300 | ||
| 301 | test("unknown kinds, wrong kinds and malformed refs are 404", async () => { | |
| 302 | for (const path of [ | |
| 303 | "/og/user/alice.svg", | |
| 304 | "/og/repo/alice/open.png", | |
| 305 | "/og/repo/alice.svg", | |
| 306 | "/og/repo/alice/nope.svg", | |
| 307 | "/og/issue/alice/open/2.svg", // a pull, not an issue | |
| 308 | "/og/pull/alice/open/1.svg", // an issue, not a pull | |
| 309 | "/og/issue/alice/open/0.svg", | |
| 310 | "/og/issue/alice/open/1e3.svg", | |
| 311 | "/og/run/..%2F..%2Fetc.svg", | |
| 312 | "/og/app/NO%20SUCH.svg", | |
| 313 | ]) | |
| 314 | expect((await get(path)).status).toBe(404); | |
| 315 | }); | |
| 316 | ||
| 317 | test("the ETag is the input's hash and a repeat answers 304", async () => { | |
| 318 | const first = await get("/og/pull/alice/open/2.svg"); | |
| 319 | const etag = first.headers.get("etag") ?? ""; | |
| 320 | expect(etag).toMatch(/^"[0-9a-f]{64}"$/); | |
| 321 | await first.text(); | |
| 322 | const again = await get("/og/pull/alice/open/2.svg", { "if-none-match": etag }); | |
| 323 | expect(again.status).toBe(304); | |
| 324 | expect(again.headers.get("etag")).toBe(etag); | |
| 325 | expect(again.headers.get("cache-control")).toBe("public, max-age=300"); | |
| 326 | expect(await again.text()).toBe(""); | |
| 327 | const weak = await get("/og/pull/alice/open/2.svg", { | |
| 328 | "if-none-match": `"other", W/${etag}`, | |
| 329 | }); | |
| 330 | expect(weak.status).toBe(304); | |
| 331 | // Another card's tag is not this one's. | |
| 332 | const other = await get("/og/repo/alice/open.svg", { "if-none-match": etag }); | |
| 333 | expect(other.status).toBe(200); | |
| 334 | await other.text(); | |
| 335 | }); | |
| 336 | ||
| 337 | test("the card follows the data: a new title is a new ETag", async () => { | |
| 338 | const before = await get("/og/issue/alice/open/1.svg"); | |
| 339 | const tag = before.headers.get("etag"); | |
| 340 | await before.text(); | |
| 341 | app.db | |
| 342 | .query("UPDATE issue SET title = 'Renamed' WHERE repo_id = ?1 AND number = 1") | |
| 343 | .run(open.id); | |
| 344 | const after = await get("/og/issue/alice/open/1.svg", { "if-none-match": tag ?? "" }); | |
| 345 | expect(after.status).toBe(200); | |
| 346 | expect(after.headers.get("etag")).not.toBe(tag); | |
| 347 | expect(await after.text()).toContain("Renamed"); | |
| 348 | }); | |
| 349 | ||
| 350 | test("a warm request answers in under 5 ms", async () => { | |
| 351 | const path = "/og/repo/alice/open.svg"; | |
| 352 | await get(path).then((r) => r.text()); | |
| 353 | const times: number[] = []; | |
| 354 | for (let n = 0; n < 21; n++) { | |
| 355 | const t0 = performance.now(); | |
| 356 | const res = await get(path); | |
| 357 | await res.text(); | |
| 358 | times.push(performance.now() - t0); | |
| 359 | } | |
| 360 | times.sort((x, y) => x - y); | |
| 361 | expect(times[10]!).toBeLessThan(5); | |
| 362 | }); | |
| 363 | }); |
new above
offline