@sssb/tools 0.0.0 → 0.3.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/bin/sssb.js +116 -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/add-app.js +344 -0
  9. package/src/commands/check-demo-size.js +80 -0
  10. package/src/commands/check-doc-paths.js +48 -0
  11. package/src/commands/check-e2e.js +611 -0
  12. package/src/commands/check-fences.js +51 -0
  13. package/src/commands/check-real-env.js +165 -0
  14. package/src/commands/check-tmpdir-leak.js +78 -0
  15. package/src/commands/ci.js +350 -0
  16. package/src/commands/dev-tick.js +25 -0
  17. package/src/commands/doctor-checks.js +1396 -0
  18. package/src/commands/doctor-settings.js +583 -0
  19. package/src/commands/doctor-vitest.js +262 -0
  20. package/src/commands/doctor.js +1033 -0
  21. package/src/commands/e2e-profile.js +94 -0
  22. package/src/commands/guide.js +108 -0
  23. package/src/commands/launch-json.js +55 -0
  24. package/src/commands/pin.js +411 -0
  25. package/src/commands/port.js +22 -0
  26. package/src/commands/remove-items.js +191 -0
  27. package/src/commands/serve-standalone.js +78 -0
  28. package/src/commands/tick.js +27 -0
  29. package/src/doc-paths.d.ts +106 -0
  30. package/src/doc-paths.js +328 -0
  31. package/src/framework-guard.js +35 -0
  32. package/src/kit.d.ts +49 -0
  33. package/src/kit.js +216 -0
  34. package/src/next.d.ts +16 -0
  35. package/src/next.js +55 -0
  36. package/src/ports.d.ts +72 -0
  37. package/src/ports.js +307 -0
  38. package/src/prune-mantine-css.js +171 -0
  39. package/src/remove-items/code.patch +798 -0
  40. package/src/remove-items/database.patch +218 -0
  41. package/src/remove-items/exact-patch.js +122 -0
  42. package/src/testing/tmp-dir-marker.js +9 -0
  43. package/src/testing/tmp-dir-setup.d.ts +2 -0
  44. package/src/testing/tmp-dir-setup.js +9 -0
  45. package/src/testing/tmp-dir.d.ts +20 -0
  46. package/src/testing/tmp-dir.js +174 -0
  47. package/src/tick/dev-tick.js +128 -0
  48. package/src/tick/tick.js +317 -0
  49. package/src/tick/ticker-marker.d.ts +17 -0
  50. package/src/tick/ticker-marker.js +83 -0
  51. package/src/tick/ticker.d.ts +36 -0
  52. package/src/tick/ticker.js +142 -0
  53. package/src/vite.d.ts +38 -0
  54. package/src/vite.js +64 -0
  55. package/src/vitest.d.ts +38 -0
  56. package/src/vitest.js +82 -0
  57. package/tsconfig.base.json +33 -0
  58. package/README.md +0 -3
package/src/next.js ADDED
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ // THE NEXT PRESET (ADR-0014 parts 2 and 6).
3
+ //
4
+ // // apps/<app>/next.config.ts
5
+ // import { withSssb } from '@sssb/tools/next'
6
+ // export default withSssb({ typedRoutes: true }, { appDir: __dirname })
7
+ //
8
+ // What every SSSB app's Next config needs, with the app's own settings layered over it:
9
+ // - `transpilePackages: ['@sssb/kit']`: the framework ships TypeScript source, compiled by the app's build.
10
+ // - next-intl's plugin, pointed at the framework's request config. next-intl's default lookup only knows
11
+ // ./src/i18n/request.ts, and SSSB's lives in the framework (ADR-0012). The path is the published subpath
12
+ // `@sssb/kit/i18n/request`, resolved from the app's directory through the shared resolver (rule 4), never a path
13
+ // into the package's internal layout, and handed to the plugin relative to the app, as next-intl and Turbopack
14
+ // read it. The plugin itself is the app's own next-intl, loaded from the app's directory.
15
+ // - `output: 'standalone'`: the deployed artifact is the standalone server in a Lambda (ADR-0001).
16
+ // - the native and WASM server dependencies kept external, so their runtime file loading keeps working.
17
+ // - `agentRules: false` and `experimental.agentUpgrade: false`, so `next dev` stays hermetic: without the first it
18
+ // writes an AGENTS.md into the app whenever it detects an AI coding agent; without the second every `next dev`
19
+ // outside CI queries npm's advisory feed for the installed next, and an agent's run stops when an advisory matches.
20
+ // Both are defined in node_modules/next/dist/docs/01-app/03-api-reference/05-config/01-next-config-js/.
21
+ //
22
+ // Pass the app's directory: Next loads the config with the app as the working directory, which is the default, but
23
+ // another tool that loads it (knip does) may not.
24
+ import { realpathSync } from 'node:fs'
25
+ import { createRequire } from 'node:module'
26
+ import path from 'node:path'
27
+ import { resolveAppsKit, resolveFromApp } from './kit.js'
28
+
29
+ /** @param {string[] | undefined} list @param {string[]} add */
30
+ const union = (list, add) => [...new Set([...(list ?? []), ...add])]
31
+
32
+ /** @type {import('./next.d.ts').withSssb} */
33
+ export function withSssb(nextConfig = {}, { appDir = process.cwd() } = {}) {
34
+ // Real paths on both ends: the request config comes back as a real path (the shared check returns one), so the
35
+ // app's directory must be one too, or a checkout behind a symlink (macOS's /tmp, a symlinked home or worktree)
36
+ // gets a relative path that climbs out of one spelling and back in through the other, and a module graph that
37
+ // resolves under two spellings loads two copies of next's modules.
38
+ const root = realpathSync(path.resolve(appDir))
39
+ const request = resolveAppsKit(root, 'i18n/request')
40
+ const relative = path.relative(root, request).split(path.sep).join('/')
41
+ const pluginFile = resolveFromApp(root, 'next-intl/plugin', "the framework's i18n needs")
42
+ const plugin = createRequire(pluginFile)(pluginFile)
43
+ /** @type {(path: string) => (config: import('next').NextConfig) => import('next').NextConfig} */
44
+ const createNextIntlPlugin = plugin.default ?? plugin
45
+ const withNextIntl = createNextIntlPlugin(relative.startsWith('.') ? relative : `./${relative}`)
46
+
47
+ return withNextIntl({
48
+ output: 'standalone',
49
+ agentRules: false,
50
+ ...nextConfig,
51
+ transpilePackages: union(nextConfig.transpilePackages, ['@sssb/kit']),
52
+ serverExternalPackages: union(nextConfig.serverExternalPackages, ['@electric-sql/pglite', 'pg']),
53
+ experimental: { agentUpgrade: false, ...nextConfig.experimental },
54
+ })
55
+ }
package/src/ports.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ /** The built-in port services: SSSB's two reference apps' slots and two tools. */
2
+ export type PortService = 'showcase' | 'starter' | 'ladle' | 'contractPg'
3
+
4
+ /**
5
+ * A port slot an app names for itself, in its package.json: `"sssb": { "port": { "name": "ledger", "default": 3800 } }`.
6
+ * `name` is lowercase words joined by `-` (at most 32 characters) and is not a built-in's; it names the `LEDGER_PORT`
7
+ * variable (`<NAME>_PORT`, with `-` as `_`). `default` is the port in a main checkout, an integer from 1024 to 49151
8
+ * that no built-in service or custom slot's derived band holds.
9
+ */
10
+ export interface PortSlot {
11
+ name: string
12
+ default: number
13
+ }
14
+
15
+ /** What an app declares: a built-in service's name (today's form) or a slot of its own. */
16
+ export type PortDeclaration = PortService | PortSlot
17
+
18
+ /** The built-in port services, for a usage message. */
19
+ export declare const SERVICE_NAMES: readonly PortService[]
20
+
21
+ /**
22
+ * Checks a port declaration, as a package.json holds it, and returns it. Throws an Error naming what is wrong (with
23
+ * `where`, the file it was read from, in front when given).
24
+ */
25
+ export declare function parsePortDeclaration(value: unknown, where?: string): PortDeclaration
26
+
27
+ /**
28
+ * The port declaration in the package.json of `appDir` (`"sssb": { "port": … }`), checked; undefined when it has none.
29
+ * Throws when the file cannot be read or the declaration is not valid.
30
+ */
31
+ export declare function readPortDeclaration(appDir: string): PortDeclaration | undefined
32
+
33
+ /**
34
+ * What port a checkout at `root` should use for a service, given an environment: the service's env var
35
+ * (`STARTER_PORT`, `LEDGER_PORT`) when set, a port derived from the path in a linked worktree
36
+ * (`.claude/worktrees/`), and the documented default otherwise. A built-in's derived port is keyed on the checkout
37
+ * alone; a custom slot's also on its name, so two slots of one worktree differ, and comes from a band no built-in
38
+ * uses (20000-29999). Pure, so it can be tested against checkouts that do not exist.
39
+ */
40
+ export declare function portForRoot(
41
+ root: string,
42
+ service: PortDeclaration,
43
+ env?: Record<string, string | undefined>,
44
+ ): number
45
+
46
+ /**
47
+ * The port THIS checkout (found from the working directory) should use for a service. With no argument, the service
48
+ * the app around the working directory declares (the nearest package.json that declares a port, up to the checkout root): the app's own, from a Playwright config or a test run from the
49
+ * app's directory.
50
+ */
51
+ export declare function portFor(service?: PortDeclaration): number
52
+
53
+ /**
54
+ * `http://localhost:<port>` for a service: the form Playwright's `use.baseURL` and `webServer.url` want. With no
55
+ * argument, the app's declared one, as `portFor`.
56
+ */
57
+ export declare function originFor(service?: PortDeclaration): string
58
+
59
+ /**
60
+ * Why `service` may not be used by an app that makes `declared`: a message when `service` is another app's built-in
61
+ * slot (`showcase`, `starter`) and the app declares a slot of its own, null otherwise. Using it would leave the app's
62
+ * dev server on its own slot and its ticker or e2e run on the other app's port.
63
+ */
64
+ export declare function foreignAppSlotProblem(service: string, declared: PortDeclaration | undefined): string | null
65
+
66
+ /**
67
+ * `http://localhost:<port>` for the app whose package.json is in `appDir`, from the port slot it declares: for a
68
+ * Playwright config of an app on a slot of its own, `originForApp(__dirname)`, which names the app wherever the config
69
+ * is loaded from (the workspace root, by knip or `playwright test -c`, or the app's own directory). Throws when the app
70
+ * declares none.
71
+ */
72
+ export declare function originForApp(appDir: string): string
package/src/ports.js ADDED
@@ -0,0 +1,307 @@
1
+ // @ts-check
2
+ // Per-checkout ports, so two agent sessions in two git worktrees can run dev servers and e2e suites at the same
3
+ // time without silently driving each other's app.
4
+ //
5
+ // The failure this prevents is recorded three times in SSSB's docs/build-notes.md: Playwright's webServer sets
6
+ // `reuseExistingServer: !CI`, so a `next dev` that another worktree left on :3000 is ADOPTED rather than replaced,
7
+ // and the suite quietly tests someone else's build. The symptoms look exactly like product defects, the tell is
8
+ // easy to miss (no `[WebServer]` startup lines in the log), and it has burned multiple full verify runs.
9
+ //
10
+ // Two properties this derivation must have, and one it must not:
11
+ //
12
+ // * PURE FUNCTION OF THE CHECKOUT PATH, not a scan for a free port. An app's `test:e2e` may run several
13
+ // `playwright test` invocations and all must land on the same port. A free-port scan could disagree between
14
+ // them; a hash cannot.
15
+ // * STABLE ACROSS PROCESSES. The package script that starts the server and the Playwright config that points
16
+ // at it compute it independently: they agree only because neither one guesses.
17
+ // * NOT applied to a main checkout. It keeps the documented defaults, so every runbook that names :3000 or
18
+ // :3100 stays true for the person reading it. Only linked worktrees under .claude/worktrees/ derive.
19
+ //
20
+ // An explicit env var always wins, which is what makes an isolated one-off run possible without editing
21
+ // anything: `SHOWCASE_PORT=3210 pnpm dev`.
22
+ //
23
+ // A SERVICE is one of the built-ins below, named by a string, or a SLOT an app declares for itself in its package.json,
24
+ // `"sssb": { "port": { "name": "ledger", "default": 3800 } }`. Every app of a workspace needs a slot of its own, since two
25
+ // apps on one slot bind one port (`@sssb/create` and `sssb add-app` give each app a slot named for it, and an app
26
+ // generated before keeps the built-in `starter`). A custom slot follows the same three rules: its
27
+ // variable is `LEDGER_PORT`, a main checkout gets its `default`, and a linked worktree derives from a band the
28
+ // built-ins do not use (CUSTOM_BAND), keyed on the name as well as the checkout so two slots of one worktree differ.
29
+ //
30
+ // THIS MODULE MUST PARSE AS BOTH ESM AND CJS, which rules out `import.meta` and `__dirname` alike: Playwright
31
+ // compiles `playwright.config.ts`, and everything it imports from outside node_modules, to CommonJS, where
32
+ // `import.meta` is a syntax error at config-load time that takes the whole suite with it. Inside SSSB's own
33
+ // repository this package is a workspace link, so its real path is outside node_modules and Playwright compiles
34
+ // it. Walking up from the working directory is the portable option.
35
+ import { createHash } from 'node:crypto'
36
+ import { existsSync, readFileSync, realpathSync } from 'node:fs'
37
+ import path from 'node:path'
38
+
39
+ /**
40
+ * The checkout's root: the nearest directory holding `pnpm-workspace.yaml`, else (a repository that is one package,
41
+ * with no workspace file) the nearest holding `.git`, else the working directory itself.
42
+ * @param {string} start
43
+ */
44
+ function findCheckoutRoot(start) {
45
+ for (const marker of ['pnpm-workspace.yaml', '.git']) {
46
+ for (let dir = path.resolve(start); ; dir = path.dirname(dir)) {
47
+ if (existsSync(path.join(dir, marker))) return dir
48
+ if (path.dirname(dir) === dir) break
49
+ }
50
+ }
51
+ return path.resolve(start)
52
+ }
53
+
54
+ /**
55
+ * Wide enough that a handful of concurrent worktrees rarely collide (4 worktrees over 200 slots is ~3%), narrow
56
+ * enough to stay in a memorable band. A collision is not silent: the second server fails to bind, which is a
57
+ * loud EADDRINUSE rather than the quiet wrong-app adoption above.
58
+ */
59
+ const SLOTS = 200
60
+
61
+ /**
62
+ * The port services. They are SSSB's two reference apps' slots plus two tools. An app `@sssb/create` writes declares a
63
+ * slot of its own instead (named for its slug), and one generated before it did keeps `starter`. Derived showcase and
64
+ * starter ports share a slot and sit adjacent (3200/3201, 3202/3203, …) so one session's pair never straddles
65
+ * another's. No derived band overlaps the defaults.
66
+ * @type {Record<string, { env: string, fallback: number, derive: (slot: number) => number }>}
67
+ */
68
+ const SERVICES = {
69
+ showcase: { env: 'SHOWCASE_PORT', fallback: 3000, derive: (slot) => 3200 + slot * 2 },
70
+ starter: { env: 'STARTER_PORT', fallback: 3100, derive: (slot) => 3201 + slot * 2 },
71
+ ladle: { env: 'LADLE_PORT', fallback: 61000, derive: (slot) => 61000 + slot },
72
+ contractPg: { env: 'CONTRACT_PG_PORT', fallback: 5439, derive: (slot) => 5440 + slot },
73
+ }
74
+
75
+ /**
76
+ * @param {string} root
77
+ * @param {string} [name] a custom slot's name, which keys its port as well as the checkout, so two custom slots in
78
+ * one worktree get different ports. The built-in services pass none and key on the checkout alone, as they always have.
79
+ */
80
+ function hashOf(root, name) {
81
+ // Any stable spread works; sha1 is here for distribution, not for security.
82
+ return createHash('sha1')
83
+ .update(name === undefined ? root : `${root}\0${name}`)
84
+ .digest()
85
+ .readUInt32BE(0)
86
+ }
87
+
88
+ /** @param {string} root */
89
+ const slotFor = (root) => hashOf(root) % SLOTS
90
+
91
+ /**
92
+ * The band a custom slot's derived port comes from in a linked worktree: 10000 ports, so two custom slots of one
93
+ * worktree collide about once in ten thousand (a loud EADDRINUSE, never a silent adoption). Clear of every built-in
94
+ * default and derived band (3000, 3100, 3200-3599, 5439-5639, 61000-61199), and below Linux's ephemeral range (32768)
95
+ * and macOS's (49152), so the OS never hands one of these to an outbound connection.
96
+ */
97
+ const CUSTOM_BAND = { start: 20000, size: 10000 }
98
+
99
+ /** The highest port an app may declare as its main-checkout default: above it the OS hands ports out at random. */
100
+ const MAX_DECLARED_DEFAULT = 49151
101
+
102
+ /** The lowest: below it a port needs privileges. */
103
+ const MIN_DECLARED_DEFAULT = 1024
104
+
105
+ const CUSTOM_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
106
+ const MAX_CUSTOM_NAME_LENGTH = 32
107
+
108
+ /** @param {string} name */
109
+ const customEnvVar = (name) => `${name.toUpperCase().replaceAll('-', '_')}_PORT`
110
+
111
+ /**
112
+ * What already holds `port` (a built-in default, a built-in derived band or the custom band), or null.
113
+ * @param {number} port
114
+ * @returns {string | null}
115
+ */
116
+ function reservedFor(port) {
117
+ for (const [name, spec] of Object.entries(SERVICES)) {
118
+ if (port === spec.fallback) return `the default of the built-in "${name}"`
119
+ if (port >= spec.derive(0) && port <= spec.derive(SLOTS - 1)) {
120
+ return `inside the derived worktree ports of the built-in "${name}"`
121
+ }
122
+ }
123
+ if (port >= CUSTOM_BAND.start && port < CUSTOM_BAND.start + CUSTOM_BAND.size) {
124
+ return 'inside the derived worktree ports of custom slots'
125
+ }
126
+ return null
127
+ }
128
+
129
+ /** @type {import('./ports.d.ts').parsePortDeclaration} */
130
+ export function parsePortDeclaration(value, where) {
131
+ const at = where === undefined ? 'ports: ' : `ports: ${where}: `
132
+ if (typeof value === 'string') {
133
+ if (!Object.hasOwn(SERVICES, value)) {
134
+ throw new Error(
135
+ `${at}unknown service "${value}" (known: ${Object.keys(SERVICES).join(', ')}; or declare a slot of ` +
136
+ 'your own, { "name": "<name>", "default": <port> })',
137
+ )
138
+ }
139
+ return /** @type {import('./ports.d.ts').PortService} */ (value)
140
+ }
141
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
142
+ throw new Error(
143
+ `${at}a port declaration is a service name or { "name": "<name>", "default": <port> }, got ${JSON.stringify(value)}`,
144
+ )
145
+ }
146
+ const { name, default: fallback, ...rest } = /** @type {Record<string, unknown>} */ (value)
147
+ if (Object.keys(rest).length > 0) {
148
+ throw new Error(`${at}a port slot has only "name" and "default", not ${Object.keys(rest).join(', ')}`)
149
+ }
150
+ if (typeof name !== 'string' || !CUSTOM_NAME.test(name) || name.length > MAX_CUSTOM_NAME_LENGTH) {
151
+ throw new Error(
152
+ `${at}a port slot's name is lowercase words joined by "-", at most ${MAX_CUSTOM_NAME_LENGTH} characters ` +
153
+ `(it names the <NAME>_PORT variable), got ${JSON.stringify(name)}`,
154
+ )
155
+ }
156
+ const taken = Object.entries(SERVICES).find(([, spec]) => spec.env === customEnvVar(name))
157
+ if (taken) {
158
+ throw new Error(
159
+ `${at}port slot "${name}" would read ${customEnvVar(name)}, the variable of the built-in service "${taken[0]}": pick another name`,
160
+ )
161
+ }
162
+ if (
163
+ typeof fallback !== 'number' ||
164
+ !Number.isInteger(fallback) ||
165
+ fallback < MIN_DECLARED_DEFAULT ||
166
+ fallback > MAX_DECLARED_DEFAULT
167
+ ) {
168
+ throw new Error(
169
+ `${at}port slot "${name}": "default" must be an integer from ${MIN_DECLARED_DEFAULT} to ${MAX_DECLARED_DEFAULT}, got ${JSON.stringify(fallback)}`,
170
+ )
171
+ }
172
+ const holder = reservedFor(fallback)
173
+ if (holder !== null) {
174
+ throw new Error(`${at}port slot "${name}": default ${fallback} is ${holder}: pick a port outside SSSB's own`)
175
+ }
176
+ return { name, default: fallback }
177
+ }
178
+
179
+ /**
180
+ * @param {import('./ports.d.ts').PortDeclaration} service
181
+ * @returns {{ env: string, fallback: number, derive: (root: string) => number }}
182
+ */
183
+ function specFor(service) {
184
+ const declaration = parsePortDeclaration(service)
185
+ if (typeof declaration === 'string') {
186
+ const spec = SERVICES[declaration]
187
+ return { env: spec.env, fallback: spec.fallback, derive: (root) => spec.derive(slotFor(root)) }
188
+ }
189
+ return {
190
+ env: customEnvVar(declaration.name),
191
+ fallback: declaration.default,
192
+ derive: (root) => CUSTOM_BAND.start + (hashOf(root, declaration.name) % CUSTOM_BAND.size),
193
+ }
194
+ }
195
+
196
+ /** @type {import('./ports.d.ts').readPortDeclaration} */
197
+ export function readPortDeclaration(appDir) {
198
+ const file = path.join(appDir, 'package.json')
199
+ let manifest
200
+ try {
201
+ manifest = JSON.parse(readFileSync(file, 'utf8'))
202
+ } catch (error) {
203
+ throw new Error(`ports: cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`, {
204
+ cause: error,
205
+ })
206
+ }
207
+ const declared = manifest?.sssb?.port
208
+ return declared === undefined ? undefined : parsePortDeclaration(declared, file)
209
+ }
210
+
211
+ /** @type {import('./ports.d.ts').portForRoot} */
212
+ export function portForRoot(root, service, env = process.env) {
213
+ const spec = specFor(service)
214
+
215
+ const override = env[spec.env]
216
+ if (override) {
217
+ const parsed = Number(override)
218
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
219
+ throw new Error(`ports: ${spec.env} must be a port number, got "${override}"`)
220
+ }
221
+ return parsed
222
+ }
223
+
224
+ const linked = root.includes(`${path.sep}.claude${path.sep}worktrees${path.sep}`)
225
+ return linked ? spec.derive(root) : spec.fallback
226
+ }
227
+
228
+ /**
229
+ * The app the working directory is in: the nearest directory at or above it whose package.json declares a port
230
+ * (`"sssb": { "port": … }`), no higher than the checkout's root, so a package nested in the app (its `infra/`, say)
231
+ * does not hide the app's slot. Undefined when there is none.
232
+ * @param {string} start
233
+ * @returns {string | undefined}
234
+ */
235
+ function appDirOf(start) {
236
+ const top = findCheckoutRoot(start)
237
+ for (let dir = path.resolve(start); ; dir = path.dirname(dir)) {
238
+ try {
239
+ if (JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8'))?.sssb?.port !== undefined) return dir
240
+ } catch {
241
+ // No package.json here, or not one that parses: not the app's, so keep looking.
242
+ }
243
+ if (dir === top || path.dirname(dir) === dir) return undefined
244
+ }
245
+ }
246
+
247
+ /**
248
+ * The declaration to use when a caller names none: the one the app the working directory is in makes (a Playwright
249
+ * run, a test, a script from the app's own directory or below it).
250
+ * @returns {import('./ports.d.ts').PortDeclaration}
251
+ */
252
+ function declaredHere() {
253
+ const appDir = appDirOf(process.cwd())
254
+ const declared = appDir === undefined ? undefined : readPortDeclaration(appDir)
255
+ if (declared === undefined) {
256
+ throw new Error(
257
+ `ports: no service named, and the app around ${process.cwd()} declares none ("sssb": { "port": … } in its ` +
258
+ "package.json): name one, run this from the app's directory, or use originForApp(<the app's directory>)",
259
+ )
260
+ }
261
+ return declared
262
+ }
263
+
264
+ /** The built-in services that are an APP's slot, as against the tools' (`ladle`, `contractPg`). */
265
+ const APP_SERVICES = ['showcase', 'starter']
266
+
267
+ /** @type {import('./ports.d.ts').foreignAppSlotProblem} */
268
+ export function foreignAppSlotProblem(service, declared) {
269
+ if (typeof service !== 'string' || !APP_SERVICES.includes(service)) return null
270
+ if (declared === undefined || typeof declared === 'string') return null
271
+ return (
272
+ `"${service}" is another app's port slot, and this app declares its own, "${declared.name}": ask for it by ` +
273
+ `leaving the service out (originFor(), sssb port, sssb tick) or by name, and drop "${service}" from this app's ` +
274
+ 'scripts and Playwright config, or its dev server and its ticker and e2e run would use different ports'
275
+ )
276
+ }
277
+
278
+ /** @type {import('./ports.d.ts').portFor} */
279
+ export function portFor(service) {
280
+ // A service an app copied from the starter, `originFor('starter')`, would silently name the starter's port in an
281
+ // app that declares a slot of its own: its dev server on its slot, its e2e run on another app's. Refused.
282
+ const appDir = typeof service === 'string' && APP_SERVICES.includes(service) ? appDirOf(process.cwd()) : undefined
283
+ if (appDir !== undefined) {
284
+ const problem = foreignAppSlotProblem(service, readPortDeclaration(appDir))
285
+ if (problem !== null) throw new Error(`ports: ${problem}`)
286
+ }
287
+ return portForRoot(findCheckoutRoot(process.cwd()), service ?? declaredHere())
288
+ }
289
+
290
+ /** @type {import('./ports.d.ts').originFor} */
291
+ export function originFor(service) {
292
+ return `http://localhost:${portFor(service)}`
293
+ }
294
+
295
+ /** @type {import('./ports.d.ts').originForApp} */
296
+ export function originForApp(appDir) {
297
+ const declared = readPortDeclaration(appDir)
298
+ if (declared === undefined) {
299
+ throw new Error(`ports: ${path.join(appDir, 'package.json')} declares no port service ("sssb": { "port": … })`)
300
+ }
301
+ // The real path, as `sssb port` sees it (a process's working directory is never a symlink): a worktree reached
302
+ // through a link must derive the same port as the dev server it points the suite at.
303
+ return `http://localhost:${portForRoot(findCheckoutRoot(realpathSync(appDir)), declared)}`
304
+ }
305
+
306
+ /** @type {import('./ports.d.ts').SERVICE_NAMES} */
307
+ export const SERVICE_NAMES = /** @type {import('./ports.d.ts').PortService[]} */ (Object.keys(SERVICES))
@@ -0,0 +1,171 @@
1
+ // @ts-check
2
+ import postcss from 'postcss'
3
+
4
+ /**
5
+ * Drops the stylesheet rules the single-file static demo can never match, so the demo carries the CSS of
6
+ * the Mantine components it actually ships and not the whole library's.
7
+ *
8
+ * WHY: `@mantine/core/styles.css` is every component's stylesheet in one file, and the apps import it
9
+ * whole. The starter's bundle reaches 33 of its ~100 component stylesheets (42 component directories in the
10
+ * module graph, 33 with a sheet of their own), so 130 KB of the demo's 231 KB of CSS styled nothing — 15% of
11
+ * the artifact, doing nothing. Mantine ships per-component sheets (`@mantine/core/styles/<Name>.css`) for
12
+ * this, but that is a list a person keeps
13
+ * (and gets wrong silently: an unstyled component passes every test); this finds the same set by asking the
14
+ * bundle itself.
15
+ *
16
+ * HOW: Mantine's components are CSS modules whose class names are hashed (`m_77c9d27d`), and those hashes
17
+ * are written out in the component's JavaScript (`{ root: 'm_77c9d27d' }`) and nowhere else. A rule whose
18
+ * selector needs a hashed class that appears in no shipped file cannot match any element the demo renders,
19
+ * so it is removed. Nothing else is touched: no rule is reordered, rewritten or merged, so the cascade among
20
+ * the rules that remain is the cascade of the full sheet. A new component an app imports ships its hashes,
21
+ * so its rules stay with no list to update.
22
+ *
23
+ * WHAT IT WILL NOT DO, deliberately, because each is the way this could silently unstyle something:
24
+ * - It only reads a hashed class at the TOP LEVEL of a selector. One inside `:not()`, `:is()`, `:where()`
25
+ * or `:has()` is no requirement (`.a:not(.m_x)` matches precisely when `.m_x` is absent), so such a
26
+ * selector is never judged by it.
27
+ * - A rule with several selectors goes only when EVERY one of them is dead.
28
+ * - Only rules are judged: an `@keyframes` (whose steps name no class) is never touched, and an at-rule is
29
+ * removed only once it holds nothing.
30
+ * - Only hashed classes are judged. Every selector with none (element, attribute and `mantine-*` rules,
31
+ * Panda's utilities, the app's own CSS) is kept.
32
+ */
33
+
34
+ /** The shape Mantine's CSS modules give a class: `m_` and a 32-bit hash in hex: 8 digits, or fewer when
35
+ * leading zeros are dropped (`m_77c9d27d`; `m_a74036a` has 7). The floor of 5 allows for a few of them. A
36
+ * class shorter still is not recognised as hashed, and a selector with no hashed class is KEPT, so the
37
+ * floor errs toward keeping rules. */
38
+ const HASHED_CLASS = /^m_[0-9a-f]{5,8}$/
39
+ const HASHED_CLASS_ANYWHERE = /\bm_[0-9a-f]{5,8}\b/g
40
+
41
+ /** Characters an unescaped CSS identifier is made of, enough to read a class name off a selector. */
42
+ const IDENT = /[\w-]/
43
+
44
+ /**
45
+ * The hashed classes a selector REQUIRES — those written outside every `(...)` and `[...]`. `.m_a .m_b > i`
46
+ * yields both; `.m_a:not(.m_b)` yields only `m_a`; `[data-x='.m_c']` yields none.
47
+ */
48
+ /** @type {import('./vite.d.ts').requiredHashedClasses} */
49
+ export function requiredHashedClasses(selector) {
50
+ /** @type {string[]} */
51
+ const required = []
52
+ let depth = 0
53
+ /** @type {string | null} */
54
+ let quote = null
55
+ for (let i = 0; i < selector.length; i++) {
56
+ const char = /** @type {string} */ (selector[i])
57
+ if (quote) {
58
+ if (char === '\\') i++
59
+ else if (char === quote) quote = null
60
+ continue
61
+ }
62
+ if (char === '\\') i++
63
+ else if (char === '"' || char === "'") quote = char
64
+ else if (char === '(' || char === '[') depth++
65
+ else if (char === ')' || char === ']') depth = Math.max(0, depth - 1)
66
+ else if (char === '.' && depth === 0) {
67
+ let end = i + 1
68
+ while (end < selector.length && IDENT.test(/** @type {string} */ (selector[end]))) end++
69
+ const name = selector.slice(i + 1, end)
70
+ if (HASHED_CLASS.test(name)) required.push(name)
71
+ i = end - 1
72
+ }
73
+ }
74
+ return required
75
+ }
76
+
77
+ /** The hashed class names written in `shipped` — the JavaScript and HTML the stylesheet is shipped with. */
78
+ /** @type {import('./vite.d.ts').shippedHashedClasses} */
79
+ export function shippedHashedClasses(shipped) {
80
+ return new Set(shipped.match(HASHED_CLASS_ANYWHERE))
81
+ }
82
+
83
+ /**
84
+ * Removes every rule of `css` that needs a hashed class not in `shipped`. Pure; throws on CSS postcss
85
+ * cannot parse (a stylesheet that broken is not one to guess about).
86
+ */
87
+ /** @type {import('./vite.d.ts').pruneUnreachableRules} */
88
+ export function pruneUnreachableRules(css, shipped) {
89
+ const root = postcss.parse(css)
90
+ let removedRules = 0
91
+ let keptRules = 0
92
+ // The at-rules a removed rule sat in: only these can have been emptied BY THIS PASS.
93
+ /** @type {Set<import('postcss').AtRule>} */
94
+ const touched = new Set()
95
+ root.walkRules((rule) => {
96
+ const unreachable = rule.selectors.every((selector) =>
97
+ requiredHashedClasses(selector).some((name) => !shipped.has(name)),
98
+ )
99
+ if (unreachable) {
100
+ for (let parent = rule.parent; parent?.type === 'atrule'; parent = parent.parent) {
101
+ touched.add(/** @type {import('postcss').AtRule} */ (parent))
102
+ }
103
+ rule.remove()
104
+ removedRules++
105
+ } else keptRules++
106
+ })
107
+ // An at-rule this pass emptied (a `@media` of removed rules) goes too. One that was empty to begin with
108
+ // (`@layer base {}`, which still orders a cascade layer) and a block-less one (`@layer a;`) stay.
109
+ // Nested at-rules empty from the inside out, so repeat until a pass removes nothing.
110
+ for (let removed = true; removed;) {
111
+ removed = false
112
+ for (const atRule of touched) {
113
+ if (atRule.parent && atRule.nodes?.length === 0) {
114
+ atRule.remove()
115
+ removed = true
116
+ }
117
+ }
118
+ }
119
+ return { css: root.toString(), removedRules, keptRules }
120
+ }
121
+
122
+ /** @param {string | Uint8Array} source */
123
+ function textOf(source) {
124
+ return typeof source === 'string' ? source : new TextDecoder().decode(source)
125
+ }
126
+
127
+ /**
128
+ * The Vite plugin: at `generateBundle` it reads every non-CSS file of the bundle (the chunks, the page) as
129
+ * the evidence of what ships, and prunes each emitted stylesheet against it.
130
+ *
131
+ * `enforce: 'post'` is load-bearing: Vite emits the one stylesheet (`cssCodeSplit: false`) in its own
132
+ * `generateBundle`, which runs after every ordinary plugin's, so an unmarked plugin would find no
133
+ * stylesheet at all. And register it BEFORE `viteSingleFile()`, the other `post` plugin, which inlines the
134
+ * stylesheet into the page in its own `generateBundle` — plugins of one phase run in array order, so the
135
+ * inlined copy is then the pruned one. A bundle with no stylesheet at this point is an error, never a quiet
136
+ * no-op: a demo always has one, and a plugin that silently stops working is how 130 KB comes back.
137
+ *
138
+ * @type {import('./vite.d.ts').pruneMantineCss}
139
+ */
140
+ export function pruneMantineCss() {
141
+ return {
142
+ name: 'sssb:prune-mantine-css',
143
+ apply: 'build',
144
+ enforce: 'post',
145
+ generateBundle(_options, bundle) {
146
+ const items = Object.values(bundle)
147
+ const stylesheets = items.filter((item) => item.type === 'asset' && item.fileName.endsWith('.css'))
148
+ if (stylesheets.length === 0) {
149
+ this.error(
150
+ 'sssb:prune-mantine-css found no stylesheet in the bundle. It must run after Vite emits it ' +
151
+ "(`enforce: 'post'`) and before vite-plugin-singlefile inlines it (earlier in `plugins`).",
152
+ )
153
+ }
154
+ const evidence = items
155
+ .filter((item) => !stylesheets.includes(item))
156
+ .map((item) => (item.type === 'chunk' ? item.code : textOf(item.source)))
157
+ .join('\n')
158
+ const shipped = shippedHashedClasses(evidence)
159
+ for (const stylesheet of stylesheets) {
160
+ if (stylesheet.type !== 'asset') continue
161
+ const before = textOf(stylesheet.source)
162
+ const { css, removedRules, keptRules } = pruneUnreachableRules(before, shipped)
163
+ stylesheet.source = css
164
+ this.info(
165
+ `${stylesheet.fileName}: ${before.length} -> ${css.length} bytes ` +
166
+ `(${removedRules} of ${removedRules + keptRules} rules unreachable)`,
167
+ )
168
+ }
169
+ },
170
+ }
171
+ }