@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,165 @@
1
+ // @ts-check
2
+ // `sssb check-real-env`: the `dev:real` preflight. Prints exactly which cutover items the real adapters' environment
3
+ // still lacks, instead of letting the server crash on its first request.
4
+ //
5
+ // THROUGH esbuild, NOT tsx OR NODE (ADR-0014 part 2). @sssb/kit ships TypeScript source, and Node refuses to strip
6
+ // types from a file under node_modules, so the framework is bundled first. The bundle holds the framework and every
7
+ // file outside node_modules: the app's own source (its seam, and what the seam imports through the app's `@/` alias)
8
+ // and any workspace package the seam reaches, which is TypeScript source too and may itself import the framework.
9
+ // Every package under node_modules stays EXTERNAL, imported by the absolute path esbuild resolved it to from the file
10
+ // that imports it, so a framework dependency loads from the framework's own node_modules as it would in the app.
11
+ //
12
+ // THE FRAMEWORK IS THE APP'S (rule 4). The entry imports the framework by the real paths the shared resolver
13
+ // returns from the app's directory; every bare `@sssb/kit` specifier is resolved and checked the same way; and every
14
+ // bundled input and every external that is framework source (its nearest package.json is `@sssb/kit`, wherever it
15
+ // sits, a copy of the framework's tree included) must be the app's own instance. The seam is
16
+ // passed explicitly (`@sssb/app-config` aliased to the app's `src/app-config`), as every SSSB builder passes it:
17
+ // in an adopter's app that is redundant with the seam link, and in SSSB's repository it is the only way, since there
18
+ // the fallback would be the repo's tsconfig mapping to the framework's test fixture (ADR-0014 part 1).
19
+ import { spawnSync } from 'node:child_process'
20
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs'
21
+ import { tmpdir } from 'node:os'
22
+ import path from 'node:path'
23
+ import { pathToFileURL } from 'node:url'
24
+ import { takeAppDir, UsageError } from '../app.js'
25
+ import { assertAppsKitFile, assertNoForeignFramework, isFrameworkFile, resolveAppsKit } from '../kit.js'
26
+
27
+ const NODE_MODULES = `${path.sep}node_modules${path.sep}`
28
+ /**
29
+ * esbuild's loader for a source file, by its extension.
30
+ * @param {string} file
31
+ * @returns {'ts' | 'tsx' | 'js' | 'jsx'}
32
+ */
33
+ function loaderFor(file) {
34
+ const ext = path.extname(file).replace(/^\.[cm]?/, '.')
35
+ return ext === '.tsx' ? 'tsx' : ext === '.ts' ? 'ts' : ext === '.jsx' ? 'jsx' : 'js'
36
+ }
37
+
38
+ /** The in-memory entry's name, as the metafile lists it. */
39
+ const ENTRY = 'sssb-check-real-env.ts'
40
+
41
+ /** @param {string[]} args */
42
+ export async function run(args) {
43
+ const appDir = realpathSync(takeAppDir(args))
44
+ if (args.length > 0) throw new UsageError('usage: sssb check-real-env [--app <dir>]')
45
+ const seam = path.join(appDir, 'src', 'app-config')
46
+ if (!existsSync(seam)) throw new UsageError(`sssb check-real-env: ${appDir} has no seam at src/app-config`)
47
+ const realIndex = resolveAppsKit(appDir, 'adapters/real/index')
48
+ const errors = resolveAppsKit(appDir, 'ports/errors')
49
+
50
+ const { build, transform } = await import('esbuild')
51
+ const outDir = mkdtempSync(path.join(tmpdir(), 'sssb-check-real-env-'))
52
+ try {
53
+ const outfile = path.join(outDir, 'preflight.cjs')
54
+ const tsconfig = path.join(appDir, 'tsconfig.json')
55
+ const result = await build({
56
+ stdin: {
57
+ contents: [
58
+ `import { assertRealEnv } from ${JSON.stringify(realIndex)}`,
59
+ `import { CutoverPendingError } from ${JSON.stringify(errors)}`,
60
+ 'try {',
61
+ ' assertRealEnv()',
62
+ " console.log('real-mode env complete: starting dev:real')",
63
+ '} catch (error) {',
64
+ ' if (!(error instanceof CutoverPendingError)) throw error',
65
+ " console.error('\\ndev:real is not available yet.\\n')",
66
+ ' console.error(error.message)',
67
+ " console.error('\\nEach item is a row in the cutover checklist, with what unlocks it.\\n')",
68
+ ' process.exit(1)',
69
+ '}',
70
+ ].join('\n'),
71
+ resolveDir: appDir,
72
+ sourcefile: ENTRY,
73
+ loader: 'ts',
74
+ },
75
+ absWorkingDir: appDir,
76
+ bundle: true,
77
+ platform: 'node',
78
+ // CommonJS, so every external is a require() with esbuild's interop: the packages left external are
79
+ // loaded by their CommonJS builds where they have one (below), and Node 24 requires an ES-only one.
80
+ format: 'cjs',
81
+ target: 'node22',
82
+ outfile,
83
+ metafile: true,
84
+ logLevel: 'warning',
85
+ ...(existsSync(tsconfig) ? { tsconfig } : {}),
86
+ alias: { '@sssb/app-config': seam },
87
+ plugins: [
88
+ {
89
+ name: 'sssb-bundle-only-the-framework-and-the-app',
90
+ setup(build) {
91
+ // The bundle is CommonJS, where `import.meta` is empty, so a bundled file (the framework, the
92
+ // app, a workspace package) that finds a file beside it with `new URL('./x', import.meta.url)`
93
+ // or `import.meta.dirname` would break or look in the bundle's temp directory. Each such file is
94
+ // first transformed with `import.meta` defined as an object holding its own location. A define
95
+ // replaces expressions, never text inside a string, and covers `import.meta.url`, `.dirname`,
96
+ // `.filename` and a destructured or bare `import.meta`; `.resolve` and `.env` stay undefined.
97
+ // TypeScript is stripped here and JSX kept, so the bundle still compiles JSX with the app's
98
+ // tsconfig.
99
+ build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (args) => {
100
+ if (args.path.includes(NODE_MODULES) && !isFrameworkFile(args.path)) return undefined
101
+ const text = readFileSync(args.path, 'utf8')
102
+ if (!text.includes('import.meta')) return undefined
103
+ const loader = loaderFor(args.path)
104
+ const meta = {
105
+ url: pathToFileURL(args.path).href,
106
+ dirname: path.dirname(args.path),
107
+ filename: args.path,
108
+ }
109
+ const { code } = await transform(text, {
110
+ loader,
111
+ format: 'esm',
112
+ jsx: 'preserve',
113
+ sourcefile: args.path,
114
+ define: { 'import.meta': JSON.stringify(meta) },
115
+ logLevel: 'silent',
116
+ })
117
+ return { contents: code, loader: loader === 'tsx' || loader === 'jsx' ? 'jsx' : 'js' }
118
+ })
119
+ build.onResolve({ filter: /^[^./]/ }, async (args) => {
120
+ if (args.pluginData === 'sssb-inner') return undefined
121
+ const resolved = await build.resolve(args.path, {
122
+ kind: args.kind,
123
+ importer: args.importer,
124
+ resolveDir: args.resolveDir,
125
+ pluginData: 'sssb-inner',
126
+ })
127
+ if (resolved.errors.length > 0) return { errors: resolved.errors }
128
+ if (resolved.external) return { path: resolved.path, external: true }
129
+ if (args.path === '@sssb/kit' || args.path.startsWith('@sssb/kit/')) {
130
+ return { path: assertAppsKitFile(appDir, resolved.path) }
131
+ }
132
+ const real = realpathSync(resolved.path)
133
+ if (!real.includes(NODE_MODULES)) return { path: real }
134
+ // An external package is loaded by plain Node, so it gets the entry Node can load: the
135
+ // `require` build where the package has one. Some packages' ES builds are written for
136
+ // bundlers only (@clerk/nextjs's imports directories, which Node refuses), and a CommonJS
137
+ // build resolves its own dependencies with Node's resolver from where it sits.
138
+ const required = await build.resolve(args.path, {
139
+ kind: 'require-call',
140
+ importer: args.importer,
141
+ resolveDir: args.resolveDir,
142
+ pluginData: 'sssb-inner',
143
+ })
144
+ const loadable = realpathSync(
145
+ required.errors.length === 0 && !required.external ? required.path : real,
146
+ )
147
+ assertNoForeignFramework(appDir, loadable)
148
+ return { path: loadable, external: true }
149
+ })
150
+ },
151
+ },
152
+ ],
153
+ })
154
+ // Every bundled input that is framework source is the app's own instance: nothing reached another copy by a
155
+ // relative path, an alias or a workspace package the plugin above never saw as a bare `@sssb/kit`.
156
+ for (const input of Object.keys(result.metafile.inputs)) {
157
+ if (input !== ENTRY) assertNoForeignFramework(appDir, path.resolve(appDir, input))
158
+ }
159
+ const run = spawnSync(process.execPath, [outfile], { stdio: 'inherit', env: process.env, cwd: appDir })
160
+ if (run.error) throw run.error
161
+ return run.status ?? 1
162
+ } finally {
163
+ rmSync(outDir, { recursive: true, force: true })
164
+ }
165
+ }
@@ -0,0 +1,78 @@
1
+ // @ts-check
2
+ // `sssb check-tmpdir-leak <command> [args…]`: runs a test command with a private TMPDIR and fails if a scratch
3
+ // directory made through `makeTestTmpDir` (@sssb/tools/testing/tmp-dir) is still there afterwards.
4
+ //
5
+ // Every test temp directory is created under os.tmpdir(), which reads $TMPDIR on POSIX and $TEMP/$TMP on Windows;
6
+ // the child gets all three, so the redirect holds on either. Pointing it at a fresh per-run directory puts ALL of the
7
+ // run's scratch space in one place this command owns, which makes the leak check exact: any marker file left in it
8
+ // is a directory the helper's cleanup did not remove. A before/after count of markers in the SHARED tmpdir would
9
+ // instead false-positive whenever another worktree runs its tests at the same moment.
10
+ //
11
+ // The run directory is removed unconditionally at the end, so even a raw `mkdtemp` that slipped past the lint rule
12
+ // (and leaves no marker) cannot accumulate across runs. Route every test run that is meant to gate through this.
13
+ import { spawn } from 'node:child_process'
14
+ import { mkdtempSync, readdirSync, rmSync } from 'node:fs'
15
+ import { constants, tmpdir } from 'node:os'
16
+ import path from 'node:path'
17
+ import { UsageError } from '../app.js'
18
+ import { TMP_DIR_MARKER_SUFFIX } from '../testing/tmp-dir-marker.js'
19
+
20
+ /**
21
+ * Runs the command to completion; resolves to its exit status (128 + n when it died on a signal).
22
+ * @param {string} command
23
+ * @param {string[]} args
24
+ * @param {NodeJS.ProcessEnv} env
25
+ * @returns {Promise<number>}
26
+ */
27
+ function runChild(command, args, env) {
28
+ return new Promise((resolve) => {
29
+ // stdio inherited and no shell. A terminal Ctrl-C reaches the child through the shared process group; the
30
+ // explicit forwarding below covers a signal sent to this process alone (a CI cancel, `kill <pid>`), and
31
+ // having a listener at all is what stops node from exiting on the signal before the `finally` in run() has
32
+ // removed the run directory.
33
+ const child = spawn(command, args, { stdio: 'inherit', env })
34
+ /** @param {NodeJS.Signals} signal */
35
+ const forward = (signal) => () => child.kill(signal)
36
+ const onInt = forward('SIGINT')
37
+ const onTerm = forward('SIGTERM')
38
+ process.on('SIGINT', onInt)
39
+ process.on('SIGTERM', onTerm)
40
+ /** @param {number} status */
41
+ const done = (status) => {
42
+ process.off('SIGINT', onInt)
43
+ process.off('SIGTERM', onTerm)
44
+ resolve(status)
45
+ }
46
+ child.on('error', (error) => {
47
+ console.error(`check-tmpdir-leak: could not run \`${command}\`: ${error.message}`)
48
+ done(1)
49
+ })
50
+ child.on('close', (code, signal) => done(code ?? 128 + (signal ? constants.signals[signal] : 1)))
51
+ })
52
+ }
53
+
54
+ /** @param {string[]} args */
55
+ export async function run(args) {
56
+ const [command, ...rest] = args
57
+ if (!command) throw new UsageError('usage: sssb check-tmpdir-leak <command> [args...]')
58
+ const runDir = mkdtempSync(path.join(tmpdir(), 'sssb-test-run-'))
59
+ try {
60
+ const status = await runChild(command, rest, { ...process.env, TMPDIR: runDir, TEMP: runDir, TMP: runDir })
61
+ if (status !== 0) return status
62
+
63
+ // Deliberately not in a try/catch: a missing run directory means something removed it under us, and that
64
+ // must fail loudly rather than read as "no leaks".
65
+ const leaked = readdirSync(runDir).filter((name) => name.endsWith(TMP_DIR_MARKER_SUFFIX))
66
+ console.log(`check-tmpdir-leak: ${leaked.length} unremoved test temp dir(s)`)
67
+ if (leaked.length === 0) return 0
68
+ console.error(
69
+ `check-tmpdir-leak: ${leaked.length} test temp dir(s) outlived the run:\n` +
70
+ leaked.map((name) => ` ${name}`).join('\n') +
71
+ '\nA marker survives only when its directory could not be removed or the cleanup hook never ran. ' +
72
+ 'See @sssb/tools/testing/tmp-dir.',
73
+ )
74
+ return 1
75
+ } finally {
76
+ rmSync(runDir, { recursive: true, force: true })
77
+ }
78
+ }
@@ -0,0 +1,350 @@
1
+ // @ts-check
2
+ // `sssb ci <job>`: the logic of a CI job, so a workflow step is one command that comes from the app's lockfile and
3
+ // cannot drift from the installed packages (ADR-0014 part 7). The reusable workflow
4
+ // (.github/workflows/app-checks.yml, P10) runs every job here, and SSSB's own checks.yml runs it.
5
+ //
6
+ // sssb ci lint-typecheck-unit [--apps <dirs>] the workspace's lint, typecheck and unit tests, then
7
+ // `sssb check-fences` in each app, `sssb doctor` once and
8
+ // `sssb check-e2e` in each app
9
+ // sssb ci contract the workspace's real-Postgres contract tests
10
+ // sssb ci matrix [--apps <dirs>] print the e2e shards and the static-demo apps (and write both to
11
+ // $GITHUB_OUTPUT as `e2e=` and `demo-static=`)
12
+ // sssb ci e2e-shards [--apps <dirs>] print the e2e shard matrix alone (and write `matrix=`)
13
+ // sssb ci e2e [--app <dir>] [--project <p>] run one shard (the app in the working directory by default)
14
+ // sssb ci demo-static [--app <dir>] build an app's static demo (each app's, with no --app), check its
15
+ // size, run its e2e
16
+ // sssb ci synth --filter <selector> run `synth` in the infra package(s) a pnpm filter selects
17
+ //
18
+ // `--apps` is a whitespace-separated list of app directories relative to the workspace root; without it, the
19
+ // workspace's apps (the root package.json's `sssb.apps`, or every `apps/<name>` package). A job that finds nothing to
20
+ // run FAILS rather than passing empty: a check that ran nothing is not a green check.
21
+ //
22
+ // `e2e-shards` and `matrix` import nothing outside Node, so they can run before `pnpm install`, from the package's
23
+ // source; app-checks.yml's `discover` installs first because it runs `pnpm exec`.
24
+ import { spawnSync } from 'node:child_process'
25
+ import { appendFileSync, existsSync, readdirSync, readFileSync } from 'node:fs'
26
+ import path from 'node:path'
27
+ import {
28
+ appLabels,
29
+ normalAppDir,
30
+ readJson,
31
+ takeAppDir,
32
+ takeOption,
33
+ UsageError,
34
+ workspaceApps,
35
+ workspaceRootOf,
36
+ } from '../app.js'
37
+
38
+ const PLAYWRIGHT_CONFIGS = [
39
+ 'playwright.config.ts',
40
+ 'playwright.config.mts',
41
+ 'playwright.config.cts',
42
+ 'playwright.config.js',
43
+ 'playwright.config.mjs',
44
+ 'playwright.config.cjs',
45
+ ]
46
+
47
+ /**
48
+ * @param {string} cwd
49
+ * @param {string[]} command
50
+ */
51
+ function sh(cwd, command) {
52
+ console.log(`\n$ (${cwd}) ${command.join(' ')}`)
53
+ const result = spawnSync(command[0] ?? '', command.slice(1), { cwd, stdio: 'inherit' })
54
+ if (result.error) throw result.error
55
+ return result.status ?? 1
56
+ }
57
+
58
+ /**
59
+ * The apps a job covers, relative to the workspace root: `--apps`'s list when given, each of which must be a package,
60
+ * or the workspace's apps. A listed app is normalised (`./apps/a/` is `apps/a`) and named once. An app the list leaves
61
+ * out (`--apps`, or the root's `sssb.apps` when there is no `--apps`), among the workspace's apps and every
62
+ * `apps/<name>` package, is named in a warning (a GitHub Actions annotation on CI): the caller chose the list, and a
63
+ * list that went stale when an app was added is the way an app goes unchecked with every check green.
64
+ * @param {string} root
65
+ * @param {string | undefined} listed
66
+ * @param {{ warn?: boolean }} [options] `warn: false` for a job that covers the same apps as one that warns
67
+ * @returns {string[]}
68
+ */
69
+ export function appsOf(root, listed, { warn = true } = {}) {
70
+ if (listed === undefined || listed.trim() === '') {
71
+ const apps = workspaceApps(root)
72
+ if (warn) warnLeftOut(root, apps, '`sssb.apps` in the root package.json')
73
+ return apps
74
+ }
75
+ /** @type {string[]} */
76
+ const apps = []
77
+ for (const app of listed.split(/\s+/).filter(Boolean)) {
78
+ if (path.isAbsolute(app) || app.split(/[\\/]/).includes('..')) {
79
+ throw new UsageError(`sssb ci: --apps names ${app}: each app is a directory inside the workspace`)
80
+ }
81
+ if (!existsSync(path.join(root, app, 'package.json'))) {
82
+ throw new UsageError(`sssb ci: --apps names ${app}, which is not a package (no package.json)`)
83
+ }
84
+ const normal = normalAppDir(app)
85
+ if (!apps.includes(normal)) apps.push(normal)
86
+ }
87
+ if (warn) warnLeftOut(root, apps, '--apps')
88
+ return apps
89
+ }
90
+
91
+ /**
92
+ * Names, in a warning (a GitHub Actions annotation on CI), every app the job does not cover: one the workspace lists
93
+ * as an app, or an `apps/<name>` package. The caller chose the list, so this is not a failure, but a list that went
94
+ * stale when an app was added is the way an app goes unchecked with every check green.
95
+ * @param {string} root
96
+ * @param {string[]} apps
97
+ * @param {string} source
98
+ */
99
+ function warnLeftOut(root, apps, source) {
100
+ const appsDir = path.join(root, 'apps')
101
+ const underApps = existsSync(appsDir)
102
+ ? readdirSync(appsDir, { withFileTypes: true })
103
+ .filter((entry) => entry.isDirectory() && existsSync(path.join(appsDir, entry.name, 'package.json')))
104
+ .map((entry) => `apps/${entry.name}`)
105
+ : []
106
+ const left = [...new Set([...workspaceApps(root), ...underApps])].filter((app) => !apps.includes(app)).sort()
107
+ if (left.length === 0) return
108
+ const note = `${source} leaves out ${left.join(', ')}: their e2e, static demo and check-fences do not run`
109
+ console.log(process.env['GITHUB_ACTIONS'] ? `::warning title=sssb ci::${note}` : `WARNING: ${note}`)
110
+ }
111
+
112
+ /**
113
+ * One shard per app running its own `test:e2e` script, UNLESS the app's Playwright config declares a project
114
+ * literally named `destructive`, in which case it splits in two: the `chromium` project, and the destructive one
115
+ * with `--workers=1 --no-deps`, whose specs still share one world with each other. Parallelism is only safe where
116
+ * the worlds are separate, and separate runners have separate worlds, so shards buy it safely. Discovered from the
117
+ * workspace's apps, never hand-listed, so a renamed or added app needs no edit to the workflow.
118
+ * @param {string} root
119
+ * @param {string[]} [apps]
120
+ */
121
+ export function e2eShards(root, apps = workspaceApps(root)) {
122
+ /** @type {{ name: string, app: string, project?: string, run: string }[]} */
123
+ const shards = []
124
+ const labels = appLabels(root, apps)
125
+ for (const app of apps) {
126
+ const config = PLAYWRIGHT_CONFIGS.map((name) => path.join(root, app, name)).find((file) => existsSync(file))
127
+ if (!config) continue
128
+ const name = labels.get(app) ?? app
129
+ const base = `pnpm exec sssb ci e2e --app ${app}`
130
+ if (/name:\s*['"]destructive['"]/.test(readFileSync(config, 'utf8'))) {
131
+ shards.push({ name, app, project: 'chromium', run: `${base} --project chromium` })
132
+ shards.push({
133
+ name: `${name}-destructive`,
134
+ app,
135
+ project: 'destructive',
136
+ run: `${base} --project destructive`,
137
+ })
138
+ } else {
139
+ shards.push({ name, app, run: base })
140
+ }
141
+ }
142
+ // Shard names name CI jobs and their report artifacts, so they must be unique: an app's `-destructive` shard could
143
+ // meet another app labelled that way.
144
+ /** @type {Set<string>} */
145
+ const taken = new Set()
146
+ for (const shard of shards) {
147
+ const wanted = shard.name
148
+ for (let n = 2; taken.has(shard.name); n++) shard.name = `${wanted}-${n}`
149
+ taken.add(shard.name)
150
+ }
151
+ return shards
152
+ }
153
+
154
+ /**
155
+ * The apps with a static demo (a `build:demo-static` script), each named as its e2e shard is.
156
+ * @param {string} root
157
+ * @param {string[]} apps
158
+ * @returns {{ name: string, app: string }[]}
159
+ */
160
+ export function demoApps(root, apps) {
161
+ const labels = appLabels(root, apps)
162
+ return apps
163
+ .filter((app) => readJson(path.join(root, app, 'package.json')).scripts?.['build:demo-static'])
164
+ .map((app) => ({ name: labels.get(app) ?? app, app }))
165
+ }
166
+
167
+ /** @param {string} line */
168
+ function output(line) {
169
+ const file = process.env['GITHUB_OUTPUT']
170
+ if (file) appendFileSync(file, `${line}\n`)
171
+ }
172
+
173
+ /**
174
+ * The root package.json's scripts, and the one a job needs, which must exist: a job does not pass by finding
175
+ * nothing to run.
176
+ * @param {string} root
177
+ * @param {string} job
178
+ * @param {string[]} names the first of these the workspace defines is run
179
+ */
180
+ function rootScript(root, job, names) {
181
+ const scripts = readJson(path.join(root, 'package.json')).scripts ?? {}
182
+ const found = names.find((name) => typeof scripts[name] === 'string')
183
+ if (!found) {
184
+ throw new UsageError(
185
+ `sssb ci ${job}: the workspace root's package.json has no ${names.map((n) => `\`${n}\``).join(' or ')} ` +
186
+ 'script, so this job has nothing to run (a check that ran nothing is not green)',
187
+ )
188
+ }
189
+ return found
190
+ }
191
+
192
+ /**
193
+ * Runs one of this package's commands in this process, as `sssb <command> <args>` would. A usage error (an app the
194
+ * command cannot check) is printed and counts as a failure, so the steps after it still run.
195
+ * @param {string} root
196
+ * @param {string} command
197
+ * @param {(args: string[]) => Promise<number>} runCommand
198
+ * @param {string[]} args
199
+ * @returns {Promise<number>}
200
+ */
201
+ async function inProcess(root, command, runCommand, args) {
202
+ console.log(
203
+ `\n$ (${root}) sssb ${command} ${args.map((arg) => (arg === '--app' ? arg : path.relative(root, arg) || '.')).join(' ')}`,
204
+ )
205
+ try {
206
+ return await runCommand(args)
207
+ } catch (error) {
208
+ if (!(error instanceof UsageError)) throw error
209
+ console.error(error.message)
210
+ return 1
211
+ }
212
+ }
213
+
214
+ /** @param {string[]} args */
215
+ export async function run(args) {
216
+ const [job, ...rest] = args
217
+ if (job === 'e2e-shards' || job === 'matrix') {
218
+ const listed = takeOption(rest, '--apps')
219
+ if (rest.length > 0) throw new UsageError(`usage: sssb ci ${job} [--apps <dirs>]`)
220
+ const root = workspaceRootOf(process.cwd())
221
+ const apps = appsOf(root, listed)
222
+ if (apps.length === 0) throw new UsageError(`sssb ci ${job}: the workspace has no apps`)
223
+ const shards = e2eShards(root, apps)
224
+ const noE2e = apps.filter((app) => !shards.some((shard) => shard.app === app))
225
+ if (noE2e.length > 0) {
226
+ throw new UsageError(
227
+ `sssb ci ${job}: ${noE2e.join(', ')} has no Playwright config (${PLAYWRIGHT_CONFIGS.join(', ')}), so its e2e would not run`,
228
+ )
229
+ }
230
+ if (job === 'e2e-shards') {
231
+ const matrix = JSON.stringify(shards)
232
+ console.log(`computed matrix: ${matrix}`)
233
+ output(`matrix=${matrix}`)
234
+ return 0
235
+ }
236
+ // EVERY app the job covers has e2e and a static demo: one that lacks either would drop out of the matrix with
237
+ // every check still green. (A matrix with no entries would fail its job in GitHub Actions without saying why.)
238
+ const demos = demoApps(root, apps)
239
+ const noDemo = apps.filter((app) => !demos.some((demo) => demo.app === app))
240
+ if (noDemo.length > 0) {
241
+ throw new UsageError(
242
+ `sssb ci matrix: ${noDemo.join(', ')} has no build:demo-static script, so its static demo would not be checked`,
243
+ )
244
+ }
245
+ console.log(`e2e shards: ${JSON.stringify(shards)}`)
246
+ console.log(`static demos: ${JSON.stringify(demos)}`)
247
+ output(`e2e=${JSON.stringify(shards)}`)
248
+ output(`demo-static=${JSON.stringify(demos)}`)
249
+ return 0
250
+ }
251
+ if (job === 'lint-typecheck-unit') {
252
+ const listed = takeOption(rest, '--apps')
253
+ if (rest.length > 0) throw new UsageError('usage: sssb ci lint-typecheck-unit [--apps <dirs>]')
254
+ const root = workspaceRootOf(process.cwd())
255
+ // `discover` (`sssb ci matrix`) warns about apps left out, for the same list; one warning a run is enough.
256
+ const apps = appsOf(root, listed, { warn: false })
257
+ if (apps.length === 0) throw new UsageError('sssb ci lint-typecheck-unit: the workspace has no apps')
258
+ const steps = [
259
+ rootScript(root, job, ['lint']),
260
+ rootScript(root, job, ['typecheck']),
261
+ // The coverage run is the unit run with coverage on; a workspace that defines it runs that one instead.
262
+ rootScript(root, job, ['test:coverage', 'test:unit']),
263
+ ]
264
+ // Every step runs, so one red step does not hide the others; the job fails if any did.
265
+ let status = 0
266
+ for (const script of steps) {
267
+ const result = sh(root, ['pnpm', 'run', script])
268
+ status ||= result
269
+ }
270
+ // Each check runs even when one before it fails or cannot run: a usage error (an app that does not resolve the
271
+ // plugin, say) fails that check and the job, and the next check still runs.
272
+ /** @type {[string, (args: string[]) => Promise<number>, string[]][]} */
273
+ const checks = []
274
+ const { run: checkFences } = await import('./check-fences.js')
275
+ for (const app of apps) checks.push(['check-fences', checkFences, ['--app', path.join(root, app)]])
276
+ // ADR-0014 parts 2, 3 and 5 (P5). ONE doctor run checks every app of the workspace, whatever `--apps` lists:
277
+ // one copy of each singleton, each app on its own seam, the @sssb packages in step, and the conformance suite's
278
+ // checks under the config a bare `vitest` loads for each app. It runs for the first app, not the root, because
279
+ // an adopter's root need not resolve @sssb/kit. Then, in each app, no e2e spec reaching the kit other than
280
+ // through @sssb/kit/testing/e2e.
281
+ const { run: doctor } = await import('./doctor.js')
282
+ checks.push(['doctor', doctor, ['--app', path.join(root, apps[0] ?? '.')]])
283
+ const { run: checkE2e } = await import('./check-e2e.js')
284
+ for (const app of apps) checks.push(['check-e2e', checkE2e, ['--app', path.join(root, app)]])
285
+ for (const [command, runCommand, commandArgs] of checks) {
286
+ const result = await inProcess(root, command, runCommand, commandArgs)
287
+ status ||= result
288
+ }
289
+ return status
290
+ }
291
+ if (job === 'contract') {
292
+ if (rest.length > 0) throw new UsageError('usage: sssb ci contract')
293
+ const root = workspaceRootOf(process.cwd())
294
+ return sh(root, ['pnpm', 'run', rootScript(root, job, ['test:contract'])])
295
+ }
296
+ if (job === 'synth') {
297
+ const filter = takeOption(rest, '--filter')
298
+ if (filter === undefined || rest.length > 0) throw new UsageError('usage: sssb ci synth --filter <selector>')
299
+ const root = workspaceRootOf(process.cwd())
300
+ // EVERY package the selector matches has a `synth` script: pnpm's recursive run skips one that does not, and
301
+ // fails only when none has it. --fail-if-no-match: a selector that names no package fails too.
302
+ const listing = spawnSync('pnpm', ['--filter', filter, 'list', '--depth', '-1', '--json'], {
303
+ cwd: root,
304
+ encoding: 'utf8',
305
+ })
306
+ if (listing.status !== 0)
307
+ throw new UsageError(
308
+ `sssb ci synth: pnpm could not list --filter ${filter}\n${listing.stdout}${listing.stderr}`,
309
+ )
310
+ /** @type {{ path: string }[]} */
311
+ const matched = JSON.parse(listing.stdout || '[]')
312
+ if (matched.length === 0) throw new UsageError(`sssb ci synth: --filter ${filter} matches no package`)
313
+ const noSynth = matched.filter(
314
+ (pkg) => typeof readJson(path.join(pkg.path, 'package.json')).scripts?.synth !== 'string',
315
+ )
316
+ if (noSynth.length > 0) {
317
+ throw new UsageError(
318
+ `sssb ci synth: ${noSynth.map((pkg) => path.relative(root, pkg.path)).join(', ')} has no synth script`,
319
+ )
320
+ }
321
+ return sh(root, ['pnpm', '--filter', filter, '--fail-if-no-match', 'run', 'synth'])
322
+ }
323
+ if (job === 'e2e') {
324
+ const appDir = takeAppDir(rest)
325
+ const project = takeOption(rest, '--project')
326
+ if (rest.length > 0) throw new UsageError('usage: sssb ci e2e --app <dir> [--project <name>]')
327
+ if (project === undefined) return sh(appDir, ['pnpm', 'run', 'test:e2e'])
328
+ const extra = project === 'destructive' ? ['--workers=1', '--no-deps'] : []
329
+ return sh(appDir, ['pnpm', 'exec', 'playwright', 'test', `--project=${project}`, ...extra])
330
+ }
331
+ if (job === 'demo-static') {
332
+ const named = rest.includes('--app') ? [takeAppDir(rest)] : undefined
333
+ if (rest.length > 0) throw new UsageError('usage: sssb ci demo-static [--app <dir>]')
334
+ const root = workspaceRootOf(process.cwd())
335
+ const apps = (named ?? workspaceApps(root).map((app) => path.join(root, app))).filter(
336
+ (dir) => readJson(path.join(dir, 'package.json')).scripts?.['build:demo-static'],
337
+ )
338
+ if (apps.length === 0) throw new UsageError('sssb ci demo-static: no app has a build:demo-static script')
339
+ for (const step of ['build:demo-static', 'check:demo-size', 'e2e:demo-static']) {
340
+ for (const dir of apps) {
341
+ const status = sh(dir, ['pnpm', 'run', step])
342
+ if (status !== 0) return status
343
+ }
344
+ }
345
+ return 0
346
+ }
347
+ throw new UsageError(
348
+ 'usage: sssb ci <lint-typecheck-unit | contract | matrix | e2e-shards | e2e | demo-static | synth>',
349
+ )
350
+ }
@@ -0,0 +1,25 @@
1
+ // @ts-check
2
+ // `sssb dev-tick [<app>] [--app <dir>] -- <the dev server's command…>`: what an app's `pnpm dev` runs, its `next dev`
3
+ // plus, only when `DEV_TICK_SECONDS` asks, the tick on a timer. The policy is ../tick/dev-tick.js. It runs in the app's
4
+ // directory (`--app`, else the working directory), and `<app>` (the port slot) defaults to the one the app declares.
5
+ import { declaredPortService, portNameOf } from '../app-port.js'
6
+ import { existsSync } from 'node:fs'
7
+ import path from 'node:path'
8
+ import { takeAppDir } from '../app.js'
9
+ import { main } from '../tick/dev-tick.js'
10
+
11
+ /** @param {string[]} args */
12
+ export async function run(args) {
13
+ // `--app` only before the `--`: what follows it is the dev server's own command line.
14
+ const split = args.indexOf('--')
15
+ const own = split < 0 ? args : args.slice(0, split)
16
+ const hasApp = own.includes('--app') || existsSync(path.join(process.cwd(), 'package.json'))
17
+ const appDir = hasApp ? takeAppDir(own) : process.cwd()
18
+ process.chdir(appDir)
19
+ const command = split < 0 ? [] : args.slice(split)
20
+ const declared = hasApp ? declaredPortService(appDir) : undefined
21
+ return await main(
22
+ own.length === 0 && declared !== undefined ? [portNameOf(declared), ...command] : [...own, ...command],
23
+ declared,
24
+ )
25
+ }