@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.
- package/LICENSE +21 -0
- package/bin/sssb.js +102 -0
- package/package.json +89 -5
- package/src/app-port.js +77 -0
- package/src/app.js +142 -0
- package/src/assembly-checks.d.ts +57 -0
- package/src/assembly-checks.js +259 -0
- package/src/commands/check-demo-size.js +80 -0
- package/src/commands/check-doc-paths.js +48 -0
- package/src/commands/check-e2e.js +611 -0
- package/src/commands/check-fences.js +51 -0
- package/src/commands/check-real-env.js +165 -0
- package/src/commands/check-tmpdir-leak.js +78 -0
- package/src/commands/ci.js +350 -0
- package/src/commands/dev-tick.js +25 -0
- package/src/commands/doctor-checks.js +1276 -0
- package/src/commands/doctor-vitest.js +262 -0
- package/src/commands/doctor.js +954 -0
- package/src/commands/e2e-profile.js +94 -0
- package/src/commands/guide.js +108 -0
- package/src/commands/launch-json.js +55 -0
- package/src/commands/port.js +22 -0
- package/src/commands/serve-standalone.js +78 -0
- package/src/commands/tick.js +27 -0
- package/src/doc-paths.d.ts +106 -0
- package/src/doc-paths.js +328 -0
- package/src/framework-guard.js +35 -0
- package/src/kit.d.ts +43 -0
- package/src/kit.js +205 -0
- package/src/next.d.ts +16 -0
- package/src/next.js +55 -0
- package/src/ports.d.ts +72 -0
- package/src/ports.js +306 -0
- package/src/prune-mantine-css.js +171 -0
- package/src/testing/tmp-dir-marker.js +9 -0
- package/src/testing/tmp-dir-setup.d.ts +2 -0
- package/src/testing/tmp-dir-setup.js +9 -0
- package/src/testing/tmp-dir.d.ts +20 -0
- package/src/testing/tmp-dir.js +174 -0
- package/src/tick/dev-tick.js +128 -0
- package/src/tick/tick.js +315 -0
- package/src/tick/ticker-marker.d.ts +17 -0
- package/src/tick/ticker-marker.js +83 -0
- package/src/tick/ticker.d.ts +36 -0
- package/src/tick/ticker.js +142 -0
- package/src/vite.d.ts +38 -0
- package/src/vite.js +64 -0
- package/src/vitest.d.ts +21 -0
- package/src/vitest.js +55 -0
- package/tsconfig.base.json +33 -0
- 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": 3700 } }`.
|
|
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,306 @@
|
|
|
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": 3700 } }`, for a workspace whose apps are not SSSB's two: without
|
|
25
|
+
// it two apps made from the starter share `starter`, and so one port. A custom slot follows the same three rules: its
|
|
26
|
+
// variable is `LEDGER_PORT`, a main checkout gets its `default`, and a linked worktree derives from a band the
|
|
27
|
+
// built-ins do not use (CUSTOM_BAND), keyed on the name as well as the checkout so two slots of one worktree differ.
|
|
28
|
+
//
|
|
29
|
+
// THIS MODULE MUST PARSE AS BOTH ESM AND CJS, which rules out `import.meta` and `__dirname` alike: Playwright
|
|
30
|
+
// compiles `playwright.config.ts`, and everything it imports from outside node_modules, to CommonJS, where
|
|
31
|
+
// `import.meta` is a syntax error at config-load time that takes the whole suite with it. Inside SSSB's own
|
|
32
|
+
// repository this package is a workspace link, so its real path is outside node_modules and Playwright compiles
|
|
33
|
+
// it. Walking up from the working directory is the portable option.
|
|
34
|
+
import { createHash } from 'node:crypto'
|
|
35
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs'
|
|
36
|
+
import path from 'node:path'
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The checkout's root: the nearest directory holding `pnpm-workspace.yaml`, else (a repository that is one package,
|
|
40
|
+
* with no workspace file) the nearest holding `.git`, else the working directory itself.
|
|
41
|
+
* @param {string} start
|
|
42
|
+
*/
|
|
43
|
+
function findCheckoutRoot(start) {
|
|
44
|
+
for (const marker of ['pnpm-workspace.yaml', '.git']) {
|
|
45
|
+
for (let dir = path.resolve(start); ; dir = path.dirname(dir)) {
|
|
46
|
+
if (existsSync(path.join(dir, marker))) return dir
|
|
47
|
+
if (path.dirname(dir) === dir) break
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return path.resolve(start)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Wide enough that a handful of concurrent worktrees rarely collide (4 worktrees over 200 slots is ~3%), narrow
|
|
55
|
+
* enough to stay in a memorable band. A collision is not silent: the second server fails to bind, which is a
|
|
56
|
+
* loud EADDRINUSE rather than the quiet wrong-app adoption above.
|
|
57
|
+
*/
|
|
58
|
+
const SLOTS = 200
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The port services. They are SSSB's two reference apps' slots plus two tools, and an app keeps the slot it was
|
|
62
|
+
* generated with when it is renamed (the starter's `starter` slot is the adopter's app's). Derived showcase and
|
|
63
|
+
* starter ports share a slot and sit adjacent (3200/3201, 3202/3203, …) so one session's pair never straddles
|
|
64
|
+
* another's. No derived band overlaps the defaults.
|
|
65
|
+
* @type {Record<string, { env: string, fallback: number, derive: (slot: number) => number }>}
|
|
66
|
+
*/
|
|
67
|
+
const SERVICES = {
|
|
68
|
+
showcase: { env: 'SHOWCASE_PORT', fallback: 3000, derive: (slot) => 3200 + slot * 2 },
|
|
69
|
+
starter: { env: 'STARTER_PORT', fallback: 3100, derive: (slot) => 3201 + slot * 2 },
|
|
70
|
+
ladle: { env: 'LADLE_PORT', fallback: 61000, derive: (slot) => 61000 + slot },
|
|
71
|
+
contractPg: { env: 'CONTRACT_PG_PORT', fallback: 5439, derive: (slot) => 5440 + slot },
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* @param {string} root
|
|
76
|
+
* @param {string} [name] a custom slot's name, which keys its port as well as the checkout, so two custom slots in
|
|
77
|
+
* one worktree get different ports. The built-in services pass none and key on the checkout alone, as they always have.
|
|
78
|
+
*/
|
|
79
|
+
function hashOf(root, name) {
|
|
80
|
+
// Any stable spread works; sha1 is here for distribution, not for security.
|
|
81
|
+
return createHash('sha1')
|
|
82
|
+
.update(name === undefined ? root : `${root}\0${name}`)
|
|
83
|
+
.digest()
|
|
84
|
+
.readUInt32BE(0)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** @param {string} root */
|
|
88
|
+
const slotFor = (root) => hashOf(root) % SLOTS
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* The band a custom slot's derived port comes from in a linked worktree: 10000 ports, so two custom slots of one
|
|
92
|
+
* worktree collide about once in ten thousand (a loud EADDRINUSE, never a silent adoption). Clear of every built-in
|
|
93
|
+
* default and derived band (3000, 3100, 3200-3599, 5439-5639, 61000-61199), and below Linux's ephemeral range (32768)
|
|
94
|
+
* and macOS's (49152), so the OS never hands one of these to an outbound connection.
|
|
95
|
+
*/
|
|
96
|
+
const CUSTOM_BAND = { start: 20000, size: 10000 }
|
|
97
|
+
|
|
98
|
+
/** The highest port an app may declare as its main-checkout default: above it the OS hands ports out at random. */
|
|
99
|
+
const MAX_DECLARED_DEFAULT = 49151
|
|
100
|
+
|
|
101
|
+
/** The lowest: below it a port needs privileges. */
|
|
102
|
+
const MIN_DECLARED_DEFAULT = 1024
|
|
103
|
+
|
|
104
|
+
const CUSTOM_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
|
|
105
|
+
const MAX_CUSTOM_NAME_LENGTH = 32
|
|
106
|
+
|
|
107
|
+
/** @param {string} name */
|
|
108
|
+
const customEnvVar = (name) => `${name.toUpperCase().replaceAll('-', '_')}_PORT`
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* What already holds `port` (a built-in default, a built-in derived band or the custom band), or null.
|
|
112
|
+
* @param {number} port
|
|
113
|
+
* @returns {string | null}
|
|
114
|
+
*/
|
|
115
|
+
function reservedFor(port) {
|
|
116
|
+
for (const [name, spec] of Object.entries(SERVICES)) {
|
|
117
|
+
if (port === spec.fallback) return `the default of the built-in "${name}"`
|
|
118
|
+
if (port >= spec.derive(0) && port <= spec.derive(SLOTS - 1)) {
|
|
119
|
+
return `inside the derived worktree ports of the built-in "${name}"`
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (port >= CUSTOM_BAND.start && port < CUSTOM_BAND.start + CUSTOM_BAND.size) {
|
|
123
|
+
return 'inside the derived worktree ports of custom slots'
|
|
124
|
+
}
|
|
125
|
+
return null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** @type {import('./ports.d.ts').parsePortDeclaration} */
|
|
129
|
+
export function parsePortDeclaration(value, where) {
|
|
130
|
+
const at = where === undefined ? 'ports: ' : `ports: ${where}: `
|
|
131
|
+
if (typeof value === 'string') {
|
|
132
|
+
if (!Object.hasOwn(SERVICES, value)) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`${at}unknown service "${value}" (known: ${Object.keys(SERVICES).join(', ')}; or declare a slot of ` +
|
|
135
|
+
'your own, { "name": "<name>", "default": <port> })',
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
return /** @type {import('./ports.d.ts').PortService} */ (value)
|
|
139
|
+
}
|
|
140
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
141
|
+
throw new Error(
|
|
142
|
+
`${at}a port declaration is a service name or { "name": "<name>", "default": <port> }, got ${JSON.stringify(value)}`,
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
const { name, default: fallback, ...rest } = /** @type {Record<string, unknown>} */ (value)
|
|
146
|
+
if (Object.keys(rest).length > 0) {
|
|
147
|
+
throw new Error(`${at}a port slot has only "name" and "default", not ${Object.keys(rest).join(', ')}`)
|
|
148
|
+
}
|
|
149
|
+
if (typeof name !== 'string' || !CUSTOM_NAME.test(name) || name.length > MAX_CUSTOM_NAME_LENGTH) {
|
|
150
|
+
throw new Error(
|
|
151
|
+
`${at}a port slot's name is lowercase words joined by "-", at most ${MAX_CUSTOM_NAME_LENGTH} characters ` +
|
|
152
|
+
`(it names the <NAME>_PORT variable), got ${JSON.stringify(name)}`,
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
const taken = Object.entries(SERVICES).find(([, spec]) => spec.env === customEnvVar(name))
|
|
156
|
+
if (taken) {
|
|
157
|
+
throw new Error(
|
|
158
|
+
`${at}port slot "${name}" would read ${customEnvVar(name)}, the variable of the built-in service "${taken[0]}": pick another name`,
|
|
159
|
+
)
|
|
160
|
+
}
|
|
161
|
+
if (
|
|
162
|
+
typeof fallback !== 'number' ||
|
|
163
|
+
!Number.isInteger(fallback) ||
|
|
164
|
+
fallback < MIN_DECLARED_DEFAULT ||
|
|
165
|
+
fallback > MAX_DECLARED_DEFAULT
|
|
166
|
+
) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`${at}port slot "${name}": "default" must be an integer from ${MIN_DECLARED_DEFAULT} to ${MAX_DECLARED_DEFAULT}, got ${JSON.stringify(fallback)}`,
|
|
169
|
+
)
|
|
170
|
+
}
|
|
171
|
+
const holder = reservedFor(fallback)
|
|
172
|
+
if (holder !== null) {
|
|
173
|
+
throw new Error(`${at}port slot "${name}": default ${fallback} is ${holder}: pick a port outside SSSB's own`)
|
|
174
|
+
}
|
|
175
|
+
return { name, default: fallback }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @param {import('./ports.d.ts').PortDeclaration} service
|
|
180
|
+
* @returns {{ env: string, fallback: number, derive: (root: string) => number }}
|
|
181
|
+
*/
|
|
182
|
+
function specFor(service) {
|
|
183
|
+
const declaration = parsePortDeclaration(service)
|
|
184
|
+
if (typeof declaration === 'string') {
|
|
185
|
+
const spec = SERVICES[declaration]
|
|
186
|
+
return { env: spec.env, fallback: spec.fallback, derive: (root) => spec.derive(slotFor(root)) }
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
env: customEnvVar(declaration.name),
|
|
190
|
+
fallback: declaration.default,
|
|
191
|
+
derive: (root) => CUSTOM_BAND.start + (hashOf(root, declaration.name) % CUSTOM_BAND.size),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** @type {import('./ports.d.ts').readPortDeclaration} */
|
|
196
|
+
export function readPortDeclaration(appDir) {
|
|
197
|
+
const file = path.join(appDir, 'package.json')
|
|
198
|
+
let manifest
|
|
199
|
+
try {
|
|
200
|
+
manifest = JSON.parse(readFileSync(file, 'utf8'))
|
|
201
|
+
} catch (error) {
|
|
202
|
+
throw new Error(`ports: cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`, {
|
|
203
|
+
cause: error,
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
const declared = manifest?.sssb?.port
|
|
207
|
+
return declared === undefined ? undefined : parsePortDeclaration(declared, file)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** @type {import('./ports.d.ts').portForRoot} */
|
|
211
|
+
export function portForRoot(root, service, env = process.env) {
|
|
212
|
+
const spec = specFor(service)
|
|
213
|
+
|
|
214
|
+
const override = env[spec.env]
|
|
215
|
+
if (override) {
|
|
216
|
+
const parsed = Number(override)
|
|
217
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
|
|
218
|
+
throw new Error(`ports: ${spec.env} must be a port number, got "${override}"`)
|
|
219
|
+
}
|
|
220
|
+
return parsed
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const linked = root.includes(`${path.sep}.claude${path.sep}worktrees${path.sep}`)
|
|
224
|
+
return linked ? spec.derive(root) : spec.fallback
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* The app the working directory is in: the nearest directory at or above it whose package.json declares a port
|
|
229
|
+
* (`"sssb": { "port": … }`), no higher than the checkout's root, so a package nested in the app (its `infra/`, say)
|
|
230
|
+
* does not hide the app's slot. Undefined when there is none.
|
|
231
|
+
* @param {string} start
|
|
232
|
+
* @returns {string | undefined}
|
|
233
|
+
*/
|
|
234
|
+
function appDirOf(start) {
|
|
235
|
+
const top = findCheckoutRoot(start)
|
|
236
|
+
for (let dir = path.resolve(start); ; dir = path.dirname(dir)) {
|
|
237
|
+
try {
|
|
238
|
+
if (JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8'))?.sssb?.port !== undefined) return dir
|
|
239
|
+
} catch {
|
|
240
|
+
// No package.json here, or not one that parses: not the app's, so keep looking.
|
|
241
|
+
}
|
|
242
|
+
if (dir === top || path.dirname(dir) === dir) return undefined
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* The declaration to use when a caller names none: the one the app the working directory is in makes (a Playwright
|
|
248
|
+
* run, a test, a script from the app's own directory or below it).
|
|
249
|
+
* @returns {import('./ports.d.ts').PortDeclaration}
|
|
250
|
+
*/
|
|
251
|
+
function declaredHere() {
|
|
252
|
+
const appDir = appDirOf(process.cwd())
|
|
253
|
+
const declared = appDir === undefined ? undefined : readPortDeclaration(appDir)
|
|
254
|
+
if (declared === undefined) {
|
|
255
|
+
throw new Error(
|
|
256
|
+
`ports: no service named, and the app around ${process.cwd()} declares none ("sssb": { "port": … } in its ` +
|
|
257
|
+
"package.json): name one, run this from the app's directory, or use originForApp(<the app's directory>)",
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
return declared
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The built-in services that are an APP's slot, as against the tools' (`ladle`, `contractPg`). */
|
|
264
|
+
const APP_SERVICES = ['showcase', 'starter']
|
|
265
|
+
|
|
266
|
+
/** @type {import('./ports.d.ts').foreignAppSlotProblem} */
|
|
267
|
+
export function foreignAppSlotProblem(service, declared) {
|
|
268
|
+
if (typeof service !== 'string' || !APP_SERVICES.includes(service)) return null
|
|
269
|
+
if (declared === undefined || typeof declared === 'string') return null
|
|
270
|
+
return (
|
|
271
|
+
`"${service}" is another app's port slot, and this app declares its own, "${declared.name}": ask for it by ` +
|
|
272
|
+
`leaving the service out (originFor(), sssb port, sssb tick) or by name, and drop "${service}" from this app's ` +
|
|
273
|
+
'scripts and Playwright config, or its dev server and its ticker and e2e run would use different ports'
|
|
274
|
+
)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** @type {import('./ports.d.ts').portFor} */
|
|
278
|
+
export function portFor(service) {
|
|
279
|
+
// A service an app copied from the starter, `originFor('starter')`, would silently name the starter's port in an
|
|
280
|
+
// app that declares a slot of its own: its dev server on its slot, its e2e run on another app's. Refused.
|
|
281
|
+
const appDir = typeof service === 'string' && APP_SERVICES.includes(service) ? appDirOf(process.cwd()) : undefined
|
|
282
|
+
if (appDir !== undefined) {
|
|
283
|
+
const problem = foreignAppSlotProblem(service, readPortDeclaration(appDir))
|
|
284
|
+
if (problem !== null) throw new Error(`ports: ${problem}`)
|
|
285
|
+
}
|
|
286
|
+
return portForRoot(findCheckoutRoot(process.cwd()), service ?? declaredHere())
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** @type {import('./ports.d.ts').originFor} */
|
|
290
|
+
export function originFor(service) {
|
|
291
|
+
return `http://localhost:${portFor(service)}`
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** @type {import('./ports.d.ts').originForApp} */
|
|
295
|
+
export function originForApp(appDir) {
|
|
296
|
+
const declared = readPortDeclaration(appDir)
|
|
297
|
+
if (declared === undefined) {
|
|
298
|
+
throw new Error(`ports: ${path.join(appDir, 'package.json')} declares no port service ("sssb": { "port": … })`)
|
|
299
|
+
}
|
|
300
|
+
// The real path, as `sssb port` sees it (a process's working directory is never a symlink): a worktree reached
|
|
301
|
+
// through a link must derive the same port as the dev server it points the suite at.
|
|
302
|
+
return `http://localhost:${portForRoot(findCheckoutRoot(realpathSync(appDir)), declared)}`
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** @type {import('./ports.d.ts').SERVICE_NAMES} */
|
|
306
|
+
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
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// The suffix of the empty sibling file that tmp-dir.js (beside it) drops next to every scratch directory it
|
|
3
|
+
// creates (`<dir>` + this suffix). Its own module so the leak wrapper (`sssb check-tmpdir-leak`) reads the same
|
|
4
|
+
// constant the helper writes with, without loading the helper, which imports vitest.
|
|
5
|
+
//
|
|
6
|
+
// @sssb/kit keeps a copy of the helper for its own shipped tests (packages/kit/src/testing), because the framework
|
|
7
|
+
// depends on no other SSSB package (ADR-0014, rule 4). Its marker suffix must be this one, or the wrapper would not see
|
|
8
|
+
// the framework's leaks; tests/tooling/tmp-dir.test.ts holds the two equal.
|
|
9
|
+
export const TMP_DIR_MARKER_SUFFIX = '.sssb-test-tmp'
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// A Vitest setup file (`test.setupFiles`): registers the scratch-directory helper's cleanup hook at the top of every
|
|
3
|
+
// test file, before the file's own code. Vitest runs setup files before each file even with `isolate: false`, where
|
|
4
|
+
// the helper (./tmp-dir.js) loads only once per worker; this is what keeps its cleanup per file and last in order
|
|
5
|
+
// there. SSSB's Vitest preset (`@sssb/tools/vitest`) adds it to every app project; another config adds
|
|
6
|
+
// `'@sssb/tools/testing/tmp-dir-setup'` to its `setupFiles`.
|
|
7
|
+
import { registerTestTmpDirCleanup } from './tmp-dir.js'
|
|
8
|
+
|
|
9
|
+
registerTestTmpDirCleanup()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Make a scratch directory, `<tmpdir>/<prefix>XXXXXX`, that is removed when the test file finishes. Synchronous
|
|
3
|
+
* variant. Import this module before anything else in the file that registers hooks.
|
|
4
|
+
*/
|
|
5
|
+
export declare function makeTestTmpDir(prefix: string): string
|
|
6
|
+
|
|
7
|
+
/** Make a scratch directory that is removed when the test file finishes. Async variant. */
|
|
8
|
+
export declare function makeTestTmpDirAsync(prefix: string): Promise<string>
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Remove a directory this module made, and its marker, now rather than when the test file finishes. Does nothing for a
|
|
12
|
+
* path it did not make, or has already removed.
|
|
13
|
+
*/
|
|
14
|
+
export declare function removeTestTmpDir(dir: string): void
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Register the current test file's cleanup hook, if it has none: what the setup module `@sssb/tools/testing/tmp-dir-setup`
|
|
18
|
+
* does before every file. Call it at a file's top level, never from a hook or a test.
|
|
19
|
+
*/
|
|
20
|
+
export declare function registerTestTmpDirCleanup(): void
|