|
| 1 | +#!/usr/bin/env bun |
| 2 | +/** |
| 3 | + * Guards against the Next.js `'use client'` server-import foot-gun. |
| 4 | + * |
| 5 | + * Next.js rewrites EVERY export of a `'use client'` module into a client |
| 6 | + * reference in the server bundle. Server-evaluated code can only *render* such |
| 7 | + * an export as a component or pass it as a prop — *calling* one throws at |
| 8 | + * runtime ("Attempted to call X from the server but X is on the client"). The |
| 9 | + * crash for an object export looks like `tableKeys.list is not a function`. |
| 10 | + * `next build` does NOT catch this; only SSR/runtime does. |
| 11 | + * |
| 12 | + * This script flags any **value** import (not `import type`) that resolves to a |
| 13 | + * `'use client'` module from a server-evaluated, non-JSX surface — the places |
| 14 | + * that never legitimately render a client component and so only ever import a |
| 15 | + * client module to (illegally) call its values: |
| 16 | + * |
| 17 | + * - `apps/sim/app/** /prefetch*.ts` (RSC server prefetch) |
| 18 | + * - `apps/sim/app/api/** /route.ts(x)` (route handlers) |
| 19 | + * - `apps/sim/triggers/**` (trigger.dev tasks/pollers/webhooks) |
| 20 | + * - `apps/sim/blocks/**` (block definitions — evaluated server-side) |
| 21 | + * |
| 22 | + * Fix: move the imported query-key factory / standalone fetcher / mapper / |
| 23 | + * constant into a non-`'use client'` module (e.g. `hooks/queries/utils/*-keys.ts` |
| 24 | + * or `hooks/queries/utils/fetch-*.ts`) and import it from there. See the rule in |
| 25 | + * `.claude/rules/sim-queries.md`. |
| 26 | + * |
| 27 | + * Escape hatch: `// client-boundary-allow: <reason>` on the line directly above |
| 28 | + * the import (reason required). Use only for a genuinely browser-only code path. |
| 29 | + * |
| 30 | + * Usage: |
| 31 | + * bun run scripts/check-client-boundary-imports.ts # report |
| 32 | + * bun run scripts/check-client-boundary-imports.ts --check # CI gate (fail on any) |
| 33 | + */ |
| 34 | +import { readdir, readFile } from 'node:fs/promises' |
| 35 | +import path from 'node:path' |
| 36 | + |
| 37 | +const ROOT = path.resolve(import.meta.dir, '..') |
| 38 | +const APP_DIR = path.join(ROOT, 'apps/sim') |
| 39 | + |
| 40 | +/** Server-evaluated, non-JSX surfaces. A file matches if its path passes one. */ |
| 41 | +function isServerSurface(rel: string): boolean { |
| 42 | + if (/(^|\/)prefetch[^/]*\.ts$/.test(rel)) return true |
| 43 | + if (/^app\/api\/.+\/route\.tsx?$/.test(rel)) return true |
| 44 | + if (/^triggers\//.test(rel)) return true |
| 45 | + if (/^blocks\//.test(rel)) return true |
| 46 | + return false |
| 47 | +} |
| 48 | + |
| 49 | +const SOURCE_EXTENSIONS = ['.ts', '.tsx'] |
| 50 | +const ALLOW_DIRECTIVE = 'client-boundary-allow' |
| 51 | + |
| 52 | +async function listFiles(dir: string): Promise<string[]> { |
| 53 | + const out: string[] = [] |
| 54 | + let entries: Awaited<ReturnType<typeof readdir>> |
| 55 | + try { |
| 56 | + entries = await readdir(dir, { withFileTypes: true }) |
| 57 | + } catch { |
| 58 | + return out |
| 59 | + } |
| 60 | + for (const entry of entries) { |
| 61 | + const full = path.join(dir, entry.name) |
| 62 | + if (entry.isDirectory()) { |
| 63 | + if (entry.name === 'node_modules' || entry.name === '.next') continue |
| 64 | + out.push(...(await listFiles(full))) |
| 65 | + } else if (SOURCE_EXTENSIONS.includes(path.extname(entry.name))) { |
| 66 | + out.push(full) |
| 67 | + } |
| 68 | + } |
| 69 | + return out |
| 70 | +} |
| 71 | + |
| 72 | +const useClientCache = new Map<string, boolean>() |
| 73 | + |
| 74 | +async function isUseClientModule(absFile: string): Promise<boolean> { |
| 75 | + const cached = useClientCache.get(absFile) |
| 76 | + if (cached !== undefined) return cached |
| 77 | + let content: string |
| 78 | + try { |
| 79 | + content = await readFile(absFile, 'utf8') |
| 80 | + } catch { |
| 81 | + useClientCache.set(absFile, false) |
| 82 | + return false |
| 83 | + } |
| 84 | + // The directive must be the first statement (comments/blank lines may precede it). |
| 85 | + let isClient = false |
| 86 | + for (const raw of content.split('\n')) { |
| 87 | + const line = raw.trim() |
| 88 | + if (line === '' || line.startsWith('//') || line.startsWith('/*') || line.startsWith('*')) { |
| 89 | + continue |
| 90 | + } |
| 91 | + isClient = line === "'use client'" || line === '"use client"' |
| 92 | + break |
| 93 | + } |
| 94 | + useClientCache.set(absFile, isClient) |
| 95 | + return isClient |
| 96 | +} |
| 97 | + |
| 98 | +/** Resolve an import specifier to an absolute source file, or null if external/unresolved. */ |
| 99 | +async function resolveSpecifier(spec: string, fromFile: string): Promise<string | null> { |
| 100 | + let base: string |
| 101 | + if (spec.startsWith('@/')) { |
| 102 | + base = path.join(APP_DIR, spec.slice(2)) |
| 103 | + } else if (spec.startsWith('./') || spec.startsWith('../')) { |
| 104 | + base = path.resolve(path.dirname(fromFile), spec) |
| 105 | + } else { |
| 106 | + return null // external package |
| 107 | + } |
| 108 | + const candidates = [ |
| 109 | + base, |
| 110 | + ...SOURCE_EXTENSIONS.map((ext) => base + ext), |
| 111 | + ...SOURCE_EXTENSIONS.map((ext) => path.join(base, `index${ext}`)), |
| 112 | + ] |
| 113 | + for (const candidate of candidates) { |
| 114 | + if (!SOURCE_EXTENSIONS.includes(path.extname(candidate))) continue |
| 115 | + try { |
| 116 | + await readFile(candidate, 'utf8') |
| 117 | + return candidate |
| 118 | + } catch {} |
| 119 | + } |
| 120 | + return null |
| 121 | +} |
| 122 | + |
| 123 | +interface ImportInfo { |
| 124 | + line: number |
| 125 | + specifier: string |
| 126 | + clause: string |
| 127 | +} |
| 128 | + |
| 129 | +/** Parse `import ... from '...'` statements, skipping side-effect-only imports. */ |
| 130 | +function parseImports(content: string): ImportInfo[] { |
| 131 | + const lines = content.split('\n') |
| 132 | + const imports: ImportInfo[] = [] |
| 133 | + const re = /^\s*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/ |
| 134 | + for (let i = 0; i < lines.length; i++) { |
| 135 | + if (!/^\s*import\b/.test(lines[i]) || !lines[i].includes('import')) continue |
| 136 | + // Join up to 12 following lines to capture multi-line import clauses. |
| 137 | + const block = lines.slice(i, i + 12).join('\n') |
| 138 | + const match = re.exec(block) |
| 139 | + if (!match) continue |
| 140 | + imports.push({ line: i + 1, clause: match[1], specifier: match[2] }) |
| 141 | + } |
| 142 | + return imports |
| 143 | +} |
| 144 | + |
| 145 | +/** True when the import brings in at least one runtime VALUE (not purely types). */ |
| 146 | +function importsAValue(clause: string): boolean { |
| 147 | + const trimmed = clause.trim() |
| 148 | + if (trimmed.startsWith('type ')) return false // `import type { ... }` / `import type X` |
| 149 | + const braceStart = trimmed.indexOf('{') |
| 150 | + // A default or namespace binding outside the braces is always a value. |
| 151 | + const beforeBrace = braceStart === -1 ? trimmed : trimmed.slice(0, braceStart) |
| 152 | + if (beforeBrace.replace(/[,\s]/g, '').length > 0) return true |
| 153 | + if (braceStart === -1) return true |
| 154 | + const inner = trimmed.slice(braceStart + 1, trimmed.lastIndexOf('}')) |
| 155 | + // A named import is a value unless every member is `type`-prefixed. |
| 156 | + return inner |
| 157 | + .split(',') |
| 158 | + .map((s) => s.trim()) |
| 159 | + .filter(Boolean) |
| 160 | + .some((member) => !member.startsWith('type ')) |
| 161 | +} |
| 162 | + |
| 163 | +function hasAllowDirective(content: string, importLine: number): boolean { |
| 164 | + const lines = content.split('\n') |
| 165 | + for (let i = importLine - 2; i >= 0 && i >= importLine - 5; i--) { |
| 166 | + const line = lines[i]?.trim() ?? '' |
| 167 | + if (line === '' || line.startsWith('//') || line.startsWith('*') || line.startsWith('/*')) { |
| 168 | + if (line.includes(ALLOW_DIRECTIVE)) { |
| 169 | + const reason = |
| 170 | + line |
| 171 | + .split(ALLOW_DIRECTIVE)[1] |
| 172 | + ?.replace(/^[:\s]+/, '') |
| 173 | + .trim() ?? '' |
| 174 | + return reason.length > 0 |
| 175 | + } |
| 176 | + continue |
| 177 | + } |
| 178 | + break |
| 179 | + } |
| 180 | + return false |
| 181 | +} |
| 182 | + |
| 183 | +interface Violation { |
| 184 | + file: string |
| 185 | + line: number |
| 186 | + specifier: string |
| 187 | +} |
| 188 | + |
| 189 | +async function main() { |
| 190 | + const checkMode = process.argv.includes('--check') |
| 191 | + const allFiles = await listFiles(APP_DIR) |
| 192 | + const violations: Violation[] = [] |
| 193 | + |
| 194 | + for (const absFile of allFiles) { |
| 195 | + const rel = path.relative(APP_DIR, absFile) |
| 196 | + if (!isServerSurface(rel)) continue |
| 197 | + // A server file that is itself `'use client'` is a client component — out of scope. |
| 198 | + if (await isUseClientModule(absFile)) continue |
| 199 | + |
| 200 | + const content = await readFile(absFile, 'utf8') |
| 201 | + for (const imp of parseImports(content)) { |
| 202 | + if (!importsAValue(imp.clause)) continue |
| 203 | + const resolved = await resolveSpecifier(imp.specifier, absFile) |
| 204 | + if (!resolved) continue |
| 205 | + if (!(await isUseClientModule(resolved))) continue |
| 206 | + if (hasAllowDirective(content, imp.line)) continue |
| 207 | + violations.push({ file: rel, line: imp.line, specifier: imp.specifier }) |
| 208 | + } |
| 209 | + } |
| 210 | + |
| 211 | + if (violations.length === 0) { |
| 212 | + console.log( |
| 213 | + "✓ Client-boundary import check passed (no server file imports a value from a 'use client' module)." |
| 214 | + ) |
| 215 | + return |
| 216 | + } |
| 217 | + |
| 218 | + console.error( |
| 219 | + `\n✗ ${violations.length} server file(s) import a runtime value from a 'use client' module.\n` + |
| 220 | + ` On the server these resolve to client-reference stubs and throw when called (e.g. 'X.list is not a function').\n` + |
| 221 | + ` Move the imported factory/fetcher/constant into a non-'use client' module (hooks/queries/utils/*-keys.ts or fetch-*.ts).\n` + |
| 222 | + ` See .claude/rules/sim-queries.md. Escape hatch: // ${ALLOW_DIRECTIVE}: <reason> above the import.\n` |
| 223 | + ) |
| 224 | + for (const v of violations) { |
| 225 | + console.error(` ${v.file}:${v.line} imports from '${v.specifier}'`) |
| 226 | + } |
| 227 | + if (checkMode) process.exit(1) |
| 228 | +} |
| 229 | + |
| 230 | +main().catch((error) => { |
| 231 | + console.error(error) |
| 232 | + process.exit(1) |
| 233 | +}) |
0 commit comments