ReviewOS

also looking at this

stacks/bench-review

Adopt the hq-apps app conventions

#76
Merged glennmichael123 wants to merge chore/hq-apps-conventions into main
31 files +1656 -395
scripts/smoke-deployment.tsadded+143-0
Changes to scripts/smoke-deployment.ts
@@ -0,0 +1,143 @@
1import { readFileSync } from 'node:fs'
2import { resolve } from 'node:path'
3
4interface SmokeContract {
5 domain: string
6 homeText: string
7}
8
9interface HealthPayload {
10 app?: unknown
11 status?: unknown
12 checks?: {
13 database?: {
14 ok?: unknown
15 message?: unknown
16 }
17 }
18}
19
20const CONTRACTS: Record<string, SmokeContract> = {
21 'bench-review': { domain: 'benchreview.org', homeText: 'Bench Review' },
22 analyticshq: { domain: 'analyticshq.org', homeText: 'analyticshq' },
23 bughq: { domain: 'bughq.org', homeText: 'Error tracking for people who ship.' },
24 commshq: { domain: 'commshq.org', homeText: 'Grow an audience worth knowing.' },
25 loghq: { domain: 'loghq.org', homeText: 'Your logs, finally worth reading.' },
26 reportshq: { domain: 'reportshq.org', homeText: 'Reports that build themselves' },
27 status: { domain: 'statushq.org', homeText: 'Know the moment' },
28}
29
30const projectRoot = resolve(import.meta.dir, '..')
31const packageJson = JSON.parse(readFileSync(resolve(projectRoot, 'package.json'), 'utf8')) as { name?: string }
32const packageName = String(packageJson.name || '')
33const directoryName = projectRoot.split('/').pop() || ''
34const appName = CONTRACTS[packageName] ? packageName : directoryName
35const contract = CONTRACTS[appName]
36
37if (!contract) throw new Error(`No deployment smoke contract exists for ${appName || '(unnamed)'}.`)
38
39const baseUrl = String(process.env.SMOKE_BASE_URL || `https://${contract.domain}`).replace(/\/$/, '')
40const attempts = Math.max(1, Number(process.env.SMOKE_ATTEMPTS || 10))
41const pauseMs = Math.max(0, Number(process.env.SMOKE_RETRY_MS || 3000))
42
43async function readWithRetry(path: string): Promise<string> {
44 let lastFailure = 'no response'
45 for (let attempt = 1; attempt <= attempts; attempt += 1) {
46 try {
47 const separator = path.includes('?') ? '&' : '?'
48 const response = await fetch(`${baseUrl}${path}${separator}smoke=${Date.now()}`, {
49 headers: {
50 accept: path === '/robots.txt'
51 ? 'text/plain'
52 : path === '/api/health'
53 ? 'application/json'
54 : 'text/html',
55 },
56 redirect: 'follow',
57 signal: AbortSignal.timeout(10_000),
58 })
59 const body = await response.text()
60 if (response.ok) return body
61 lastFailure = `HTTP ${response.status}`
62 }
63 catch (error) {
64 lastFailure = error instanceof Error ? error.message : String(error)
65 }
66 if (attempt < attempts) await Bun.sleep(pauseMs)
67 }
68 throw new Error(`${baseUrl}${path} failed after ${attempts} attempts: ${lastFailure}`)
69}
70
71export function assertHealthyDeployment(body: string, expectedApp: string = appName): void {
72 let health: HealthPayload
73 try {
74 health = JSON.parse(body) as HealthPayload
75 }
76 catch {
77 throw new Error('Health smoke response is not valid JSON.')
78 }
79
80 if (health.app !== expectedApp)
81 throw new Error(`Health smoke response belongs to ${String(health.app || 'an unknown app')}, not ${expectedApp}.`)
82
83 if (health.status !== 'healthy')
84 throw new Error(`Health smoke reported application status ${String(health.status || 'unknown')}.`)
85
86 if (health.checks?.database?.ok !== true) {
87 const detail = health.checks?.database?.message
88 throw new Error(`Health smoke reported an unhealthy database${detail ? `: ${String(detail)}` : '.'}`)
89 }
90}
91
92/*
93 * Unresolved stx expressions in the SERVED html.
94 *
95 * This has to run against a served page, because the two render paths disagree:
96 * `bun run build` resolves a component's expressions correctly, while
97 * `buddy serve` — what production actually runs — can ship the component's own
98 * template verbatim. bughq went live with every <Button> reading
99 * `class="{⁠{ buttonClasses }}"` while its dist/ was correct and lint, tsc, stx
100 * typecheck, the tests and release:validate were all clean (stacksjs/stx#2037).
101 * No check over dist/ can see it.
102 *
103 * Attributes specifically: the visual gate already looks for `{⁠{`, but through
104 * `document.body.innerText`, which by definition never contains an attribute
105 * value. That blind spot is why it shipped. A served attribute value never
106 * legitimately contains `{⁠{`.
107 */
108function unresolvedAttributes(html: string): string[] {
109 const found = new Set<string>()
110 for (const m of html.matchAll(/\s([a-zA-Z_:@][\w:.-]*)\s*=\s*"([^"]*\{\{[^"]*)"/g))
111 found.add(`${m[1]}="${m[2].trim()}"`)
112 return [...found]
113}
114
115async function run(): Promise<void> {
116 const home = await readWithRetry('/')
117 if (!home.includes(contract.homeText)) throw new Error(`Homepage does not contain the expected release marker: ${contract.homeText}`)
118
119 const login = await readWithRetry('/login')
120 if (!/<(?:form|main)\b/i.test(login)) throw new Error('Login smoke response does not contain an application form or main region.')
121
122 const health = await readWithRetry('/api/health')
123 assertHealthyDeployment(health)
124
125 for (const [label, body] of [['homepage', home], ['login', login]] as const) {
126 const leftovers = unresolvedAttributes(body)
127 if (leftovers.length > 0) {
128 throw new Error(
129 `Deployed ${label} ships ${leftovers.length} unresolved stx expression(s) in attributes, `
130 + `so a component rendered its own template instead of its output: ${leftovers.join(', ')}`,
131 )
132 }
133 }
134
135 const robots = await readWithRetry('/robots.txt')
136 if (robots.includes('http://localhost')) throw new Error('Deployed robots.txt contains a localhost URL.')
137 if (!robots.includes(new URL(baseUrl).hostname)) throw new Error(`Deployed robots.txt does not name ${new URL(baseUrl).hostname}.`)
138
139 console.log(`Deployment smoke passed for ${baseUrl}: homepage, login, database health, robots metadata, and no unresolved stx expressions are live.`)
140}
141
142if (import.meta.main)
143 await run()