@sssb/tools 0.0.0 → 0.2.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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +102 -0
  3. package/package.json +89 -5
  4. package/src/app-port.js +77 -0
  5. package/src/app.js +142 -0
  6. package/src/assembly-checks.d.ts +57 -0
  7. package/src/assembly-checks.js +259 -0
  8. package/src/commands/check-demo-size.js +80 -0
  9. package/src/commands/check-doc-paths.js +48 -0
  10. package/src/commands/check-e2e.js +611 -0
  11. package/src/commands/check-fences.js +51 -0
  12. package/src/commands/check-real-env.js +165 -0
  13. package/src/commands/check-tmpdir-leak.js +78 -0
  14. package/src/commands/ci.js +350 -0
  15. package/src/commands/dev-tick.js +25 -0
  16. package/src/commands/doctor-checks.js +1276 -0
  17. package/src/commands/doctor-vitest.js +262 -0
  18. package/src/commands/doctor.js +954 -0
  19. package/src/commands/e2e-profile.js +94 -0
  20. package/src/commands/guide.js +108 -0
  21. package/src/commands/launch-json.js +55 -0
  22. package/src/commands/port.js +22 -0
  23. package/src/commands/serve-standalone.js +78 -0
  24. package/src/commands/tick.js +27 -0
  25. package/src/doc-paths.d.ts +106 -0
  26. package/src/doc-paths.js +328 -0
  27. package/src/framework-guard.js +35 -0
  28. package/src/kit.d.ts +43 -0
  29. package/src/kit.js +205 -0
  30. package/src/next.d.ts +16 -0
  31. package/src/next.js +55 -0
  32. package/src/ports.d.ts +72 -0
  33. package/src/ports.js +306 -0
  34. package/src/prune-mantine-css.js +171 -0
  35. package/src/testing/tmp-dir-marker.js +9 -0
  36. package/src/testing/tmp-dir-setup.d.ts +2 -0
  37. package/src/testing/tmp-dir-setup.js +9 -0
  38. package/src/testing/tmp-dir.d.ts +20 -0
  39. package/src/testing/tmp-dir.js +174 -0
  40. package/src/tick/dev-tick.js +128 -0
  41. package/src/tick/tick.js +315 -0
  42. package/src/tick/ticker-marker.d.ts +17 -0
  43. package/src/tick/ticker-marker.js +83 -0
  44. package/src/tick/ticker.d.ts +36 -0
  45. package/src/tick/ticker.js +142 -0
  46. package/src/vite.d.ts +38 -0
  47. package/src/vite.js +64 -0
  48. package/src/vitest.d.ts +21 -0
  49. package/src/vitest.js +55 -0
  50. package/tsconfig.base.json +33 -0
  51. package/README.md +0 -3
@@ -0,0 +1,94 @@
1
+ // @ts-check
2
+ // `sssb e2e-profile [playwright args…]`: where the e2e wall clock actually goes.
3
+ //
4
+ // The alternative is optimising by intuition: "which tests are slow" is not guessable from reading them, because
5
+ // the expensive ones are expensive for different reasons (cold route compiles, real polling, repeated UI sign-ins)
6
+ // and only a ranking separates those. Run from an app's directory; every argument is forwarded to `playwright test`
7
+ // (`--project=chromium`, `--workers=1 --no-deps`), so this profiles whatever you can already run. It reads
8
+ // Playwright's own JSON report, so the numbers are Playwright's, not a wrapper's stopwatch.
9
+ import { spawnSync } from 'node:child_process'
10
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import path from 'node:path'
13
+ import { takeAppDir } from '../app.js'
14
+
15
+ const TOP_N = 20
16
+
17
+ /**
18
+ * @typedef {{ duration?: number }} Result
19
+ * @typedef {{ status?: string, results?: Result[] }} Test
20
+ * @typedef {{ title: string, tests?: Test[] }} Spec
21
+ * @typedef {{ file?: string, specs?: Spec[], suites?: Suite[] }} Suite
22
+ */
23
+
24
+ /** @param {string[]} args */
25
+ export async function run(args) {
26
+ const appDir = takeAppDir(args)
27
+ const scratch = mkdtempSync(path.join(tmpdir(), 'e2e-profile-'))
28
+ const reportFile = path.join(scratch, 'report.json')
29
+ try {
30
+ // The JSON reporter goes to a FILE, not stdout: stdout also carries `[WebServer]` output and the dev
31
+ // server's own logging, which would make the report unparseable.
32
+ const result = spawnSync('pnpm', ['exec', 'playwright', 'test', '--reporter=json', ...args], {
33
+ cwd: appDir,
34
+ stdio: 'inherit',
35
+ env: { ...process.env, PLAYWRIGHT_JSON_OUTPUT_NAME: reportFile },
36
+ })
37
+
38
+ /** @type {{ suites?: Suite[], stats?: { duration?: number } }} */
39
+ let report
40
+ try {
41
+ report = JSON.parse(readFileSync(reportFile, 'utf8'))
42
+ } catch {
43
+ console.error('\ne2e-profile: no parseable JSON report: the run probably failed before reporting.')
44
+ return result.status ?? 1
45
+ }
46
+
47
+ /** @type {{ title: string, file: string, duration: number }[]} */
48
+ const tests = []
49
+ /** @param {Suite} suite @param {string | undefined} file */
50
+ const walk = (suite, file) => {
51
+ const here = suite.file ?? file
52
+ for (const spec of suite.specs ?? []) {
53
+ for (const test of spec.tests ?? []) {
54
+ // Retries produce several results; charge the test the total, since that is the wall clock the
55
+ // run actually spent on it.
56
+ const duration = (test.results ?? []).reduce((sum, r) => sum + (r.duration ?? 0), 0)
57
+ tests.push({ title: spec.title, file: here ?? '?', duration })
58
+ }
59
+ }
60
+ for (const child of suite.suites ?? []) walk(child, here)
61
+ }
62
+ for (const suite of report.suites ?? []) walk(suite, undefined)
63
+
64
+ const wall = report.stats?.duration ?? 0
65
+ const summed = tests.reduce((sum, t) => sum + t.duration, 0)
66
+ const slowest = [...tests].sort((a, b) => b.duration - a.duration).slice(0, TOP_N)
67
+ /** @type {Map<string, number>} */
68
+ const byFile = new Map()
69
+ for (const t of tests) byFile.set(t.file, (byFile.get(t.file) ?? 0) + t.duration)
70
+
71
+ /** @param {number} ms */
72
+ const secs = (ms) => `${(ms / 1000).toFixed(1)}s`
73
+ /** @param {number} ms */
74
+ const pct = (ms) => (summed > 0 ? `${((ms / summed) * 100).toFixed(1)}%` : '-')
75
+
76
+ console.log(`\n${'='.repeat(78)}`)
77
+ console.log(`wall clock ${secs(wall)} across ${tests.length} tests (summed test time ${secs(summed)})`)
78
+ // Summed > wall means parallelism is working; summed ≈ wall means it is not.
79
+ console.log(`parallel speedup ${wall > 0 ? (summed / wall).toFixed(1) : '-'}x`)
80
+ console.log('='.repeat(78))
81
+ console.log(`\nslowest ${Math.min(TOP_N, slowest.length)} tests`)
82
+ for (const t of slowest) {
83
+ console.log(` ${secs(t.duration).padStart(7)} ${pct(t.duration).padStart(6)} ${t.file} › ${t.title}`)
84
+ }
85
+ console.log('\nby spec file')
86
+ for (const [file, ms] of [...byFile.entries()].sort((a, b) => b[1] - a[1])) {
87
+ console.log(` ${secs(ms).padStart(7)} ${pct(ms).padStart(6)} ${file}`)
88
+ }
89
+ console.log()
90
+ return result.status ?? 0
91
+ } finally {
92
+ rmSync(scratch, { recursive: true, force: true })
93
+ }
94
+ }
@@ -0,0 +1,108 @@
1
+ // @ts-check
2
+ // `sssb guide [--app <dir>] [--out <file>] [--check]`: copies the app guide that @sssb/kit ships (the rules an app author follows:
3
+ // the seam, vendor SDKs, getDb, i18n, router-agnostic screens, hermetic dev) into the repository, with a hash of its
4
+ // content stamped in a header line. The adopter's own CLAUDE.md imports that copy with Claude Code's `@path` import.
5
+ //
6
+ // THE TRUST DECISION (ADR-0014 part 9): agent instructions steer every agent working in the repository, so a change
7
+ // to them must arrive as a reviewable diff in the adopter's own PR, never silently through node_modules. `--check`
8
+ // (and, from P5, `sssb doctor`) fails when the stamped hash differs from the installed guide's, so an upgrade is not
9
+ // finished until the copy is refreshed and the change sits in the adopter's diff. The hash, not the bytes, is
10
+ // compared, so the adopter's formatter cannot make the copy look stale.
11
+ //
12
+ // The guide is the framework's published subpath `@sssb/kit/guide.md`, resolved from the app's directory through the
13
+ // shared resolver (rule 4). The framework starts shipping it at ADR-0014's P7; before that this command says so.
14
+ import { createHash } from 'node:crypto'
15
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { readJson, takeAppDir, takeFlag, takeOption, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
18
+ import { kitDirOf, resolveAppsKit } from '../kit.js'
19
+
20
+ const STAMP = /^<!-- sssb-guide sha256:([0-9a-f]{64}) /
21
+
22
+ /** @param {string | Buffer} text */
23
+ const sha256 = (text) => createHash('sha256').update(text).digest('hex')
24
+
25
+ /**
26
+ * The app whose kit's guide is copied. The copy is the workspace's, so the command has to work where people type it,
27
+ * the root, as `sssb doctor` does: with no `--app`, a working directory that resolves `@sssb/kit` is the app, and a
28
+ * workspace root that does not (a generated workspace's root takes no framework) uses the workspace's first app
29
+ * (`sssb.apps`, else `apps/*`).
30
+ * @param {string[]} args
31
+ * @param {string} [cwd]
32
+ * @returns {string}
33
+ */
34
+ function guideApp(args, cwd = process.cwd()) {
35
+ if (args.includes('--app')) return takeAppDir(args, cwd)
36
+ const here = path.resolve(cwd)
37
+ const isRoot = existsSync(path.join(here, 'pnpm-workspace.yaml')) && existsSync(path.join(here, 'package.json'))
38
+ if (isRoot && !resolvesKit(here)) {
39
+ const apps = workspaceApps(here)
40
+ if (apps.length === 0) {
41
+ throw new UsageError(
42
+ `sssb guide: ${here} is a workspace root that takes no @sssb/kit and has no apps (\`sssb.apps\` in its ` +
43
+ 'package.json, or apps/<name>): pass --app <dir>',
44
+ )
45
+ }
46
+ console.log(`sssb guide: no --app, and ${here} takes no @sssb/kit: using the guide of ${apps[0]}'s kit`)
47
+ return path.resolve(here, /** @type {string} */ (apps[0]))
48
+ }
49
+ // Anything else: the app is the working directory, and kitDirOf's refusal says to name one with --app.
50
+ return takeAppDir(args, cwd)
51
+ }
52
+
53
+ /** @param {string} dir */
54
+ function resolvesKit(dir) {
55
+ try {
56
+ kitDirOf(dir)
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ /** @param {string[]} args */
64
+ export async function run(args) {
65
+ const appDir = guideApp(args)
66
+ const check = takeFlag(args, '--check')
67
+ const out = takeOption(args, '--out')
68
+ if (args.length > 0) throw new UsageError('usage: sssb guide [--app <dir>] [--out <file>] [--check]')
69
+ const target = path.resolve(out ?? path.join(workspaceRootOf(appDir), '.claude', 'sssb-guide.md'))
70
+
71
+ const kitDir = kitDirOf(appDir)
72
+ const version = readJson(path.join(kitDir, 'package.json')).version
73
+ let guide
74
+ try {
75
+ guide = resolveAppsKit(appDir, 'guide.md')
76
+ } catch (error) {
77
+ throw new UsageError(
78
+ `sssb guide: the @sssb/kit ${version} this app installs ships no app guide (\`@sssb/kit/guide.md\`); ` +
79
+ `it arrives with ADR-0014's P7 (${error instanceof Error ? error.message : String(error)})`,
80
+ )
81
+ }
82
+ const body = readFileSync(guide)
83
+ const hash = sha256(body)
84
+
85
+ if (check) {
86
+ const stamped = existsSync(target) ? STAMP.exec(readFileSync(target, 'utf8'))?.[1] : undefined
87
+ if (stamped === hash) {
88
+ console.log(`sssb guide: ${path.relative(process.cwd(), target)} matches @sssb/kit ${version}'s guide`)
89
+ return 0
90
+ }
91
+ console.error(
92
+ stamped === undefined
93
+ ? `sssb guide: ${target} is missing or carries no stamp. Run \`pnpm exec sssb guide\` and commit the copy.`
94
+ : `sssb guide: ${target} was copied from a different guide than @sssb/kit ${version} ships. Run ` +
95
+ '`pnpm exec sssb guide`, review the diff, and commit it with the upgrade.',
96
+ )
97
+ return 1
98
+ }
99
+ mkdirSync(path.dirname(target), { recursive: true })
100
+ writeFileSync(
101
+ target,
102
+ `<!-- sssb-guide sha256:${hash} (copied from @sssb/kit ${version} by \`sssb guide\`: edit nothing here; ` +
103
+ 'rerun it after an upgrade and review the diff) -->\n\n' +
104
+ body.toString('utf8'),
105
+ )
106
+ console.log(`sssb guide: wrote ${path.relative(process.cwd(), target)} from @sssb/kit ${version}`)
107
+ return 0
108
+ }
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ // `sssb launch-json`: generates `.claude/launch.json` for THIS checkout.
3
+ //
4
+ // The Claude desktop app's browser pane starts a dev server by name from that file and then waits on the `port`
5
+ // it declares. The file is static JSON with no way to read an env var, so a checked-in `"port": 3000` was wrong in
6
+ // every linked worktree the moment ports became per-checkout (src/ports.js): `pnpm dev` would bind the derived
7
+ // port while the pane waited on 3000 and timed out. The right value differs per checkout, so the file is
8
+ // generated and gitignored, and this generator is what is tracked instead. Run it from the workspace root's
9
+ // `prepare` script, so a fresh clone and every new worktree get a correct one from `pnpm install`.
10
+ //
11
+ // One configuration per workspace app (`sssb.apps`, else `apps/*`) that has a `dev` script and declares its port
12
+ // service (`"sssb": { "port": … }`), named `<app directory>-dev`.
13
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
14
+ import path from 'node:path'
15
+ import { declaredPortService } from '../app-port.js'
16
+ import { appLabels, readJson, UsageError, workspaceApps, workspaceRootOf } from '../app.js'
17
+ import { portForRoot } from '../ports.js'
18
+
19
+ /** @param {string[]} args */
20
+ export async function run(args) {
21
+ if (args.length > 0) throw new UsageError('usage: sssb launch-json')
22
+ const root = workspaceRootOf(process.cwd())
23
+ const configurations = []
24
+ const apps = workspaceApps(root)
25
+ const labels = appLabels(root, apps)
26
+ for (const app of apps) {
27
+ const appDir = path.join(root, app)
28
+ const manifest = readJson(path.join(appDir, 'package.json'))
29
+ const service = declaredPortService(appDir)
30
+ if (!manifest.scripts?.dev || service === undefined) continue
31
+ configurations.push({
32
+ name: `${labels.get(app) ?? app}-dev`,
33
+ runtimeExecutable: 'pnpm',
34
+ runtimeArgs: ['--filter', manifest.name, 'dev'],
35
+ port: portForRoot(root, service),
36
+ })
37
+ }
38
+ const target = path.join(root, '.claude', 'launch.json')
39
+ const next = `${JSON.stringify({ version: '0.0.1', configurations }, null, 4)}\n`
40
+
41
+ // Only write when the content changes: `prepare` runs on every install, and rewriting an identical file would
42
+ // churn mtimes and any watcher pointed at it.
43
+ let current
44
+ try {
45
+ current = readFileSync(target, 'utf8')
46
+ } catch {
47
+ // No file yet (fresh clone, new worktree): fall through and write one.
48
+ }
49
+ if (current !== next) {
50
+ mkdirSync(path.dirname(target), { recursive: true })
51
+ writeFileSync(target, next)
52
+ console.log(`launch.json: ${configurations.map((c) => `${c.name} on ${c.port}`).join(', ') || 'no apps'}`)
53
+ }
54
+ return 0
55
+ }
@@ -0,0 +1,22 @@
1
+ // @ts-check
2
+ // `sssb port [service]`: prints one port, so package scripts can say `next dev --port "$(sssb port)"`.
3
+ import { appPortService, serviceNamed, servicesKnownTo } from '../app-port.js'
4
+ import { takeAppDir, UsageError } from '../app.js'
5
+ import { portFor } from '../ports.js'
6
+
7
+ /** @param {string[]} args */
8
+ export async function run(args) {
9
+ const appDir = takeAppDir(args)
10
+ if (args.length > 1) throw new UsageError(`usage: sssb port [${servicesKnownTo(appDir).join('|')}]`)
11
+ const service = args[0] === undefined ? appPortService(appDir) : serviceNamed(appDir, args[0])
12
+ if (service === undefined) {
13
+ throw new UsageError(`sssb port: unknown service "${args[0]}" (known: ${servicesKnownTo(appDir).join(', ')})`)
14
+ }
15
+ // `process.stdout.write` of a STRING, never `console.log` of a number. Playwright injects FORCE_COLOR=1 into
16
+ // every webServer process it spawns, and `console.log` of a NUMBER goes through util.inspect, which then colours
17
+ // it: the bytes become `\e[33m3240\e[39m`. That renders as a clean "3240" in a terminal and in a log file, so the
18
+ // corruption is invisible; but `$(...)` captures the escape codes too, and `next dev --port` then fails with
19
+ // "'3240' is not a non-negative number". Strings are never coloured, so this cannot recur.
20
+ process.stdout.write(`${portFor(service)}\n`)
21
+ return 0
22
+ }
@@ -0,0 +1,78 @@
1
+ // @ts-check
2
+ // `sssb serve-standalone [service]`: runs the app's standalone production build locally (`next start` does not
3
+ // serve `output: 'standalone'`). Copies the static assets the way the Lambda packaging step does, then boots
4
+ // server.js.
5
+ //
6
+ // In a monorepo Next nests the standalone output under the app's path relative to the inferred workspace root, so
7
+ // the server is at `.next/standalone/<…>/apps/<app>/server.js`, not at the top, and static assets must sit beside
8
+ // THAT file. The exact prefix depends on where Next infers the root, so it is discovered rather than assumed.
9
+ //
10
+ // The port: PORT when set, else the named port service, else the app's declared one (`"sssb": { "port": … }`).
11
+ import { spawn } from 'node:child_process'
12
+ import { cpSync, existsSync, readdirSync } from 'node:fs'
13
+ import path from 'node:path'
14
+ import { appPortService, serviceNamed, servicesKnownTo } from '../app-port.js'
15
+ import { takeAppDir, UsageError } from '../app.js'
16
+ import { portFor } from '../ports.js'
17
+
18
+ /**
19
+ * The single server.js Next emitted, wherever it nested it.
20
+ * @param {string} dir
21
+ * @returns {string | null}
22
+ */
23
+ function findServer(dir) {
24
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
25
+ if (entry.isFile() && entry.name === 'server.js') return path.join(dir, entry.name)
26
+ if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.next') {
27
+ const found = findServer(path.join(dir, entry.name))
28
+ if (found) return found
29
+ }
30
+ }
31
+ return null
32
+ }
33
+
34
+ /** @param {string[]} args */
35
+ export async function run(args) {
36
+ const root = takeAppDir(args)
37
+ if (args.length > 1) throw new UsageError(`usage: sssb serve-standalone [${servicesKnownTo(root).join('|')}]`)
38
+ const service =
39
+ args[0] === undefined ? (process.env['PORT'] ? undefined : appPortService(root)) : serviceNamed(root, args[0])
40
+ if (args[0] !== undefined && service === undefined)
41
+ throw new UsageError(`sssb serve-standalone: unknown port service "${args[0]}"`)
42
+
43
+ const standalone = path.join(root, '.next', 'standalone')
44
+ if (!existsSync(standalone)) {
45
+ throw new UsageError('No standalone build found: build the app first (its `build:demo` or `build` script).')
46
+ }
47
+ const server = findServer(standalone)
48
+ if (!server) throw new UsageError(`No server.js under ${standalone}: the standalone build looks incomplete.`)
49
+ const serverDir = path.dirname(server)
50
+
51
+ cpSync(path.join(root, '.next', 'static'), path.join(serverDir, '.next', 'static'), { recursive: true })
52
+ if (existsSync(path.join(root, 'public'))) {
53
+ cpSync(path.join(root, 'public'), path.join(serverDir, 'public'), { recursive: true })
54
+ }
55
+
56
+ const port = process.env['PORT'] ?? String(portFor(service))
57
+
58
+ // PIN THE WORLD TO THE APP, not to the build output. The fake adapters resolve `.data` relative to the working
59
+ // directory, and this child's is `serverDir`, somewhere inside `.next/standalone/…`. Left alone it writes its
60
+ // world THERE, which is invisible from the app directory: `rm -rf .data` looks like it reset everything and
61
+ // resets nothing, so state leaks between runs. That cost two e2e failures that looked like product bugs before
62
+ // the cause was found. An explicit APP_DATA_DIR still wins, which is how the shard runner gives each shard its own.
63
+ const dataDir = process.env['APP_DATA_DIR'] ?? path.join(root, '.data')
64
+
65
+ console.log(`serving standalone build on http://localhost:${port} (world: ${dataDir})`)
66
+ const child = spawn(process.execPath, [server], {
67
+ stdio: 'inherit',
68
+ env: { ...process.env, PORT: port, HOSTNAME: '127.0.0.1', APP_DATA_DIR: dataDir },
69
+ cwd: serverDir,
70
+ })
71
+ return await new Promise((resolve) => {
72
+ child.on('error', (error) => {
73
+ console.error(`Could not start the standalone server: ${error.message}`)
74
+ resolve(1)
75
+ })
76
+ child.on('exit', (code) => resolve(code ?? 0))
77
+ })
78
+ }
@@ -0,0 +1,27 @@
1
+ // @ts-check
2
+ // `sssb tick [<app>] [--url <origin>] [--timeout <seconds>] [--app <dir>]`: calls the running dev server's
3
+ // scheduled-tick route once and says what ran. The logic is ../tick/tick.js. It runs in the app's directory (`--app`,
4
+ // else the working directory), where the server keeps `.data`, and `<app>` (the port slot) defaults to the one the
5
+ // app declares (`"sssb": { "port": … }`).
6
+ import { declaredPortService, portNameOf } from '../app-port.js'
7
+ import { existsSync } from 'node:fs'
8
+ import path from 'node:path'
9
+ import { takeAppDir } from '../app.js'
10
+ import { main } from '../tick/tick.js'
11
+
12
+ /** @param {string[]} args */
13
+ export async function run(args) {
14
+ // With `--app`, or from a package's directory, the slot defaults to the app's declaration; from anywhere else the
15
+ // command takes its slot as an argument and the working directory as it is, as it always has.
16
+ const hasApp = args.includes('--app') || existsSync(path.join(process.cwd(), 'package.json'))
17
+ const appDir = hasApp ? takeAppDir(args) : process.cwd()
18
+ process.chdir(appDir)
19
+ const declared = hasApp ? declaredPortService(appDir) : undefined
20
+ const first = args[0]
21
+ return await main(
22
+ declared !== undefined && (first === undefined || first.startsWith('-'))
23
+ ? [portNameOf(declared), ...args]
24
+ : args,
25
+ declared,
26
+ )
27
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The gate that fails the build when a doctrine doc cites a path that does not exist, and the parser the adoption
3
+ * rewriter shares with it. Everything about WHICH repository this is lives in the adopter's own root package.json
4
+ * under `sssb.docPaths`, so the gate survives the day `packages/kit` leaves the tree.
5
+ */
6
+
7
+ export interface DocPathsConfig {
8
+ /** Prefixes that make a backticked token unambiguously a path in this repo (`docs/`, `apps/`, ...). */
9
+ roots: string[]
10
+ /**
11
+ * Directories walked for `.md` files, and individual files, relative to the workspace root. Root-level files are
12
+ * listed rather than globbed because a repo root accumulates markdown that is NOT doctrine: a stray NOTES.md
13
+ * should not become a build gate.
14
+ */
15
+ include: string[]
16
+ /**
17
+ * Path prefixes (root-relative, forward slashes) never gated, each an append-only dated record or not this
18
+ * checkout's content. Rewriting a record to match today's tree would be revisionist, so such files are corrected
19
+ * opportunistically but never gated. SSSB's own, with the reason for each:
20
+ *
21
+ * - `docs/adr/`: dated decisions, amended by appending a dated addendum, never by editing the body.
22
+ * - `docs/build-notes.md`: a running log of dated lessons.
23
+ * - `docs/decision-log.md`: a running log of dated decisions.
24
+ * - `.claude/future-tasks/resolved/`: finished tasks; the work that resolved one routinely moved what it cites.
25
+ * - `.claude/worktrees/`: linked worktrees from agent sessions, not this checkout's content.
26
+ */
27
+ exempt: string[]
28
+ /**
29
+ * Apps a citation may name while absent from the tree (SSSB: `showcase`, `starter`). Optional, default none, in
30
+ * which case every citation is checked strictly. See `resolves` for the rule.
31
+ */
32
+ referenceApps?: string[]
33
+ /**
34
+ * Path segments that are build outputs, never checked. A doc may legitimately name one, but whether it exists on
35
+ * disk depends on whether you happened to run a build, which would make the gate pass locally and fail on a clean
36
+ * checkout: a gate whose verdict depends on build state is not a gate. Default: `dist-demo`, `.next`, `coverage`,
37
+ * `playwright-report`, `test-results`, `node_modules`, `.data`.
38
+ */
39
+ buildOutputs?: string[]
40
+ /**
41
+ * Docs whose citations are relative to a directory rather than to the root: doc path (root-relative, as `include`
42
+ * finds it) to that directory. SSSB maps the app guide `@sssb/kit` ships, `packages/kit/src/guide.md`, to
43
+ * `apps/starter`; an adopter maps its copy, `.claude/sssb-guide.md`, to its own app. Every citation in such a doc
44
+ * is joined onto the directory before it is resolved, and the reference-app rule then applies to the result.
45
+ * Optional, default none. A doc is gated only if `include` reaches it; this says only how to read it.
46
+ */
47
+ relativeTo?: Record<string, string>
48
+ }
49
+
50
+ /** One path a doc cites. */
51
+ export interface Citation {
52
+ /** The path as the gate reads it: globs and `<metavariables>` truncated to their static prefix. */
53
+ path: string
54
+ /**
55
+ * The full backticked span the path was read out of, which for a command citation is the whole command and can
56
+ * be SHARED by several citations. `generalizeAppCitations` is the only sanctioned way to rewrite on it.
57
+ */
58
+ raw: string
59
+ line: number
60
+ }
61
+
62
+ /**
63
+ * Reads `sssb.docPaths` from `<root>/package.json` and validates its shape. Throws an `Error` naming the key when
64
+ * the block is absent or malformed.
65
+ */
66
+ export declare function readDocPathsConfig(root: string): DocPathsConfig
67
+
68
+ /**
69
+ * Every gated markdown file, as root-relative forward-slash paths in a stable (sorted) order. Resolved against
70
+ * `root`, never the process's working directory. An `include` entry that does not exist is skipped: an adopter may
71
+ * have no `.claude/`.
72
+ */
73
+ export declare function docFiles(root: string, config: DocPathsConfig): string[]
74
+
75
+ /** The path citations in a markdown text, one per path token inside each backticked span. */
76
+ export declare function citationsIn(text: string, config: DocPathsConfig): Citation[]
77
+
78
+ /**
79
+ * `citationsIn` over a file; `file` is resolved against `root`. When `relativeTo` maps the file to a directory, each
80
+ * citation's `path` is joined onto that directory (its `raw` span is unchanged).
81
+ */
82
+ export declare function citedPaths(file: string, config: DocPathsConfig, root: string): Citation[]
83
+
84
+ /**
85
+ * Whether a cited path resolves under `root`. A directory citation must resolve outright; a FILE citation may also
86
+ * pass on its parent directory existing, because a doc may legitimately name a file you are meant to create. A
87
+ * citation under a reference app that is not in the tree (no `apps/<app>/package.json`) resolves, because it names
88
+ * the template's own app and is not the adopter's to fix.
89
+ */
90
+ export declare function resolves(path: string, root: string, config: DocPathsConfig): boolean
91
+
92
+ /**
93
+ * Generalizes every citation of an `apps/<name>/` path that `isMissing` reports as gone into `apps/<app>/...`,
94
+ * which the gate reads as asserting only that `apps/` exists. A span carrying several citations is rewritten once.
95
+ */
96
+ export declare function generalizeAppCitations(
97
+ text: string,
98
+ isMissing: (path: string) => boolean,
99
+ config: DocPathsConfig,
100
+ ): string
101
+
102
+ /** Every broken citation under `root`, as `<file>:<line> cites \`<path>\``. */
103
+ export declare function docPathProblems(root: string, config: DocPathsConfig): string[]
104
+
105
+ /** The `include` entries that name nothing in the tree; `docPathProblems` and `sssb check-doc-paths` fail on each. */
106
+ export declare function missingIncludes(root: string, config: DocPathsConfig): string[]