@sssb/tools 0.0.0-stage → 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 -3
  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,174 @@
1
+ // @ts-check
2
+ // THE ONLY WAY A TEST MAKES A SCRATCH DIRECTORY. A raw `mkdtemp` in a test file leaves the directory behind on every
3
+ // run; left long enough that has filled a developer's temp filesystem past 100GB. SSSB's lint rule
4
+ // `sssb/no-direct-mkdtemp` bans the raw call in test files, and `sssb check-tmpdir-leak` fails the run if a
5
+ // directory made here was not removed. Any workspace package may import this: it touches no framework code, so a
6
+ // package that does not use @sssb/kit (a CLI, a CloudFront function) uses it too (ADR-0014 part 3).
7
+ //
8
+ // Each call creates `<tmpdir>/<prefix>XXXXXX`, writes an EMPTY MARKER FILE beside it (`<dir>` + TMP_DIR_MARKER_SUFFIX)
9
+ // and queues both for removal when the test file finishes. The marker is a SIBLING, never inside the directory: some
10
+ // tests assert the exact contents of their directory, and a marker inside would be a fixture they have to know about.
11
+ // The marker is deleted only after its directory is, so a directory that cannot be removed keeps its marker and the
12
+ // leak wrapper still sees it.
13
+ //
14
+ // THE FILE'S CLEANUP HOOK is one `afterAll` at the file's top level, which removes every directory still queued: a
15
+ // worker runs its files one after another, so anything queued is this file's or an earlier one's. It must exist before
16
+ // the functions are called, because Vitest silently drops a hook registered at run time from inside another hook, so
17
+ // a helper that registered its own `afterAll` on first call would leak exactly when called from a `beforeAll`. Two
18
+ // things register it:
19
+ //
20
+ // * loading this module, which with isolation (Vitest's default) happens in every file;
21
+ // * the setup module `@sssb/tools/testing/tmp-dir-setup` (./tmp-dir-setup.js), which Vitest runs before every file
22
+ // even WITHOUT isolation (`isolate: false`), where this module loads once per worker and its load-time hook is the
23
+ // first file's alone. SSSB's Vitest preset (`@sssb/tools/vitest`) adds it to every app project.
24
+ //
25
+ // ORDERING: `afterAll` hooks run in reverse registration order, so a hook registered first runs last. The setup module
26
+ // runs before the test file, and an import of this module is hoisted above the file's own code, so the cleanup runs
27
+ // AFTER a file's own `afterAll`: a file that closes a database handle living in the directory closes it before the
28
+ // directory is deleted.
29
+ //
30
+ // WITHOUT ISOLATION AND WITHOUT THE SETUP MODULE, a later file has no file-level hook, and no hook registered later
31
+ // can be both last in the order and wide enough in scope: one registered from a `describe` belongs to that
32
+ // `describe`, which may finish while another part of the file still uses a directory. So such a file never removes
33
+ // its own directories. Its first call registers a hook that removes those of EARLIER files, which have finished (a
34
+ // worker runs its files one after another): each file's directories go when the next file with a hook finishes, and the
35
+ // worker's last file's are left, for `sssb check-tmpdir-leak` to report. The first such call says so once per worker, naming the
36
+ // setup module. `removeTestTmpDir` removes one now. tests/tooling/tmp-dir-isolation.test.ts runs each case in a real
37
+ // Vitest.
38
+ //
39
+ // LIMITS, both Vitest's: a file whose tests are all skipped (`it.skip`, a `-t` filter) runs no `afterAll`, so its
40
+ // directories are left until the next file in the worker registers, and with isolation, where nothing carries to the
41
+ // next file, for good. And the order above holds for `sequence.hooks: 'stack'`, Vitest's default; under `'list'` or
42
+ // `'parallel'` the cleanup can run before the file's own `afterAll`.
43
+ //
44
+ // The kit keeps its own copy (packages/kit/src/testing/tmp-dir.ts), because the framework depends on no other SSSB
45
+ // package; both write the same marker, which tests/tooling/tmp-dir.test.ts holds equal.
46
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
47
+ import { mkdtemp, writeFile } from 'node:fs/promises'
48
+ import { tmpdir } from 'node:os'
49
+ import path from 'node:path'
50
+ import { afterAll, expect } from 'vitest'
51
+ import { TMP_DIR_MARKER_SUFFIX } from './tmp-dir-marker.js'
52
+
53
+ /** Every directory made and not yet removed, with the test file it was made in. @type {{ dir: string, file: string }[]} */
54
+ const created = []
55
+
56
+ /** Test files with a file-level hook, by path ('' when Vitest names none). @type {Set<string>} */
57
+ const hookedFiles = new Set()
58
+
59
+ /** Test files without one that have a hook removing EARLIER files' directories. @type {Set<string>} */
60
+ const sweepingFiles = new Set()
61
+
62
+ let warned = false
63
+
64
+ const currentFile = () => expect.getState().testPath ?? ''
65
+
66
+ /** @param {string} dir */
67
+ function remove(dir) {
68
+ try {
69
+ rmSync(dir, { recursive: true, force: true })
70
+ rmSync(dir + TMP_DIR_MARKER_SUFFIX, { force: true })
71
+ } catch (error) {
72
+ console.error(`tmp-dir: could not remove ${dir}`, error)
73
+ }
74
+ }
75
+
76
+ /** @param {(entry: (typeof created)[number]) => boolean} which */
77
+ function removeQueued(which) {
78
+ for (let i = created.length - 1; i >= 0; i--) {
79
+ const entry = created[i]
80
+ if (entry && which(entry)) {
81
+ created.splice(i, 1)
82
+ remove(entry.dir)
83
+ }
84
+ }
85
+ }
86
+
87
+ /**
88
+ * A file's first registration: whatever is still queued or registered for another file is an earlier file's, which has
89
+ * finished (a worker runs its files one after another). Its directories go now, which also covers a file whose tests
90
+ * were all skipped, since Vitest runs no `afterAll` for a skipped suite; and its registry entries go, so a watch-mode
91
+ * rerun of that file registers again.
92
+ *
93
+ * @param {string} file
94
+ */
95
+ function startFile(file) {
96
+ removeQueued((entry) => entry.file !== file)
97
+ for (const other of [...hookedFiles, ...sweepingFiles]) {
98
+ if (other !== file) {
99
+ hookedFiles.delete(other)
100
+ sweepingFiles.delete(other)
101
+ }
102
+ }
103
+ }
104
+
105
+ /** @type {import('./tmp-dir.d.ts').registerTestTmpDirCleanup} */
106
+ export function registerTestTmpDirCleanup() {
107
+ const file = currentFile()
108
+ if (hookedFiles.has(file)) return
109
+ startFile(file)
110
+ hookedFiles.add(file)
111
+ afterAll(() => {
112
+ // A watch-mode rerun of this file, in this worker, registers again.
113
+ hookedFiles.delete(file)
114
+ removeQueued(() => true)
115
+ })
116
+ }
117
+
118
+ registerTestTmpDirCleanup()
119
+
120
+ /**
121
+ * The file the next directory belongs to. In a file without a file-level hook, also registers that file's hook for
122
+ * earlier files' directories, on its first call. Synchronous, so the async variant calls it before its first `await`,
123
+ * while the file may still be collected.
124
+ */
125
+ function claim() {
126
+ const file = currentFile()
127
+ if (hookedFiles.has(file)) return file
128
+ if (!warned) {
129
+ warned = true
130
+ console.error(
131
+ `tmp-dir: ${file || 'a test file'} has no cleanup hook of its own: with Vitest's isolate: false, add ` +
132
+ "'@sssb/tools/testing/tmp-dir-setup' to test.setupFiles (SSSB's appTestProject does). Without it each " +
133
+ "file's scratch directories are removed only after the next file, and the last file's are left behind.",
134
+ )
135
+ }
136
+ if (!sweepingFiles.has(file)) {
137
+ startFile(file)
138
+ sweepingFiles.add(file)
139
+ afterAll(() => {
140
+ // A watch-mode rerun of this file, in this worker, registers again.
141
+ sweepingFiles.delete(file)
142
+ removeQueued((entry) => entry.file !== file)
143
+ })
144
+ }
145
+ return file
146
+ }
147
+
148
+ /** @type {import('./tmp-dir.d.ts').makeTestTmpDir} */
149
+ export function makeTestTmpDir(prefix) {
150
+ const file = claim()
151
+ const dir = mkdtempSync(path.join(tmpdir(), prefix))
152
+ created.push({ dir, file })
153
+ writeFileSync(dir + TMP_DIR_MARKER_SUFFIX, '')
154
+ return dir
155
+ }
156
+
157
+ /** @type {import('./tmp-dir.d.ts').makeTestTmpDirAsync} */
158
+ export async function makeTestTmpDirAsync(prefix) {
159
+ // Before the `await`: a hook can be registered only while the file is collected.
160
+ const file = claim()
161
+ const dir = await mkdtemp(path.join(tmpdir(), prefix))
162
+ created.push({ dir, file })
163
+ await writeFile(dir + TMP_DIR_MARKER_SUFFIX, '')
164
+ return dir
165
+ }
166
+
167
+ /** @type {import('./tmp-dir.d.ts').removeTestTmpDir} */
168
+ export function removeTestTmpDir(dir) {
169
+ const index = created.findIndex((entry) => entry.dir === dir)
170
+ // Only a directory this module made and has not removed yet: anything else is not a scratch directory.
171
+ if (index < 0) return
172
+ created.splice(index, 1)
173
+ remove(dir)
174
+ }
@@ -0,0 +1,128 @@
1
+ // @ts-check
2
+ // What `pnpm dev` runs: the app's `next dev`, plus, only when asked, `pnpm tick` on a timer.
3
+ //
4
+ // DEV_TICK_SECONDS=30 pnpm dev # also tick the scheduler every 30 seconds
5
+ // pnpm dev # as before: nothing ticks it
6
+ //
7
+ // OFF BY DEFAULT, and not by oversight (docs/decision-log.md, "`pnpm tick`, and a dev ticker that is opt-in"). The
8
+ // showcase's Simulator controls the world clock in a demo and says when a digest fires; the e2e suites expect a
9
+ // scheduler that does nothing until a test asks; and hermetic dev does not do work nobody asked for. So the ticker is a
10
+ // variable you set, never a default, and the places that must stay quiet say so themselves:
11
+ //
12
+ // * Playwright starts the server with `pnpm dev` and blanks `DEV_TICK_SECONDS` for it (both apps' playwright
13
+ // configs), so a value in your shell never reaches a server Playwright starts;
14
+ // * Playwright ADOPTS a dev server already on its port when it is not on CI, so a ticking server you left running
15
+ // would be adopted: while a ticker runs it leaves a marker (ticker-marker.js) and both playwright configs
16
+ // refuse to load while one is live;
17
+ // * `E2E_BUILD` and `DEMO_MODE` are the build-time switches of the e2e build and the demo build. Those servers
18
+ // start from `sssb serve-standalone`, not from here, but a ticker asked for with either set is refused and
19
+ // said so, rather than trusted to be unreachable;
20
+ // * the file:// static demo has no server at all, so there is nothing to tick.
21
+ //
22
+ // This wraps `next dev`, it does not live inside the app: the app's source stays free of any reading of
23
+ // `process.env`, and nothing in the server changes. The ticking itself is ticker.js, which owns start, stop,
24
+ // the interval and its status and knows nothing of the environment: this file is the policy for `pnpm dev`.
25
+ import { spawn } from 'node:child_process'
26
+ import { foreignAppSlotProblem, portFor } from '../ports.js'
27
+ import { tickAppNames, tickSlot } from './tick.js'
28
+ import { createTicker, intervalProblem } from './ticker.js'
29
+ import { tickerMarkerPath } from './ticker-marker.js'
30
+
31
+ const DEV_TICK_VARIABLE = 'DEV_TICK_SECONDS'
32
+
33
+ /**
34
+ * What the environment asks of the ticker.
35
+ *
36
+ * @param {Record<string, string | undefined>} env
37
+ * @returns {{ mode: 'off' } | { mode: 'refused', reason: string } | { mode: 'on', seconds: number } | { mode: 'invalid', reason: string }}
38
+ */
39
+ export function resolveDevTick(env) {
40
+ const raw = env[DEV_TICK_VARIABLE]
41
+ if (raw === undefined || raw.trim() === '') return { mode: 'off' }
42
+ const seconds = Number(raw)
43
+ const problem = intervalProblem(seconds)
44
+ if (problem) {
45
+ return {
46
+ mode: 'invalid',
47
+ reason: `${DEV_TICK_VARIABLE} must be ${problem} (or unset, for no ticker), got "${raw}"`,
48
+ }
49
+ }
50
+ const blocker = ['E2E_BUILD', 'DEMO_MODE'].find((name) => env[name])
51
+ if (blocker) {
52
+ return {
53
+ mode: 'refused',
54
+ reason: `${DEV_TICK_VARIABLE} is ignored while ${blocker} is set: the ticker never runs under e2e or the demo`,
55
+ }
56
+ }
57
+ return { mode: 'on', seconds }
58
+ }
59
+
60
+ /**
61
+ * `sssb dev-tick <app> -- <command...>`
62
+ *
63
+ * @param {string[]} argv
64
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
65
+ * @returns {{ app: string, command: string[] } | { error: string }}
66
+ */
67
+ export function parseDevArgs(argv, declared) {
68
+ const dash = argv.indexOf('--')
69
+ const app = argv[0]
70
+ if (dash !== 1 || argv.length < 3 || tickSlot(app, declared) === undefined) {
71
+ return {
72
+ error:
73
+ (dash === 1 && foreignAppSlotProblem(app, declared)) ||
74
+ `usage: sssb dev-tick <${tickAppNames(declared).join('|')}> -- <the dev server's command...>`,
75
+ }
76
+ }
77
+ return { app, command: argv.slice(dash + 1) }
78
+ }
79
+
80
+ /**
81
+ * @param {string[]} argv
82
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
83
+ */
84
+ export async function main(argv, declared) {
85
+ const parsed = parseDevArgs(argv, declared)
86
+ if ('error' in parsed) {
87
+ console.error(parsed.error)
88
+ return 2
89
+ }
90
+ const wanted = resolveDevTick(process.env)
91
+ if (wanted.mode === 'invalid') {
92
+ // Before the server starts: a typo'd variable is a mistake to fix, not a ticker to quietly not have.
93
+ console.error(`dev: ${wanted.reason}`)
94
+ return 2
95
+ }
96
+ if (wanted.mode === 'refused') console.warn(`[tick] ${wanted.reason}`)
97
+
98
+ const child = spawn(parsed.command[0], parsed.command.slice(1), {
99
+ stdio: 'inherit',
100
+ shell: process.platform === 'win32',
101
+ })
102
+
103
+ // This process is now the pid a supervisor holds (it was `next` itself when the script was a bare `next dev`), so
104
+ // every signal that stopped the server has to reach it. A terminal's Ctrl-C reaches the child directly as well, so
105
+ // `next` sees SIGINT twice, which it tolerates (checked: SIGINT to the whole process group of `pnpm dev` with a real
106
+ // `next dev` exited 0, removed the marker and left no process behind).
107
+ for (const name of /** @type {const} */ (['SIGINT', 'SIGTERM', 'SIGHUP'])) process.on(name, () => child.kill(name))
108
+
109
+ const origin = `http://localhost:${portFor(/** @type {import('../ports.d.ts').PortDeclaration} */ (tickSlot(parsed.app, declared)))}`
110
+ const ticker = createTicker({ origin, markerFile: tickerMarkerPath() })
111
+ if (wanted.mode === 'on') {
112
+ console.log(
113
+ `[tick] ${DEV_TICK_VARIABLE}=${wanted.seconds}: ticking ${origin} every ${wanted.seconds}s (pnpm tick does it once)`,
114
+ )
115
+ ticker.start(wanted.seconds)
116
+ }
117
+
118
+ return await new Promise((resolve) => {
119
+ child.on('error', (error) => {
120
+ console.error(`dev: could not start ${parsed.command[0]}: ${error.message}`)
121
+ void ticker.stop().then(() => resolve(1))
122
+ })
123
+ child.on('exit', (code, signal) => {
124
+ const status = code ?? (signal ? 128 + (signal === 'SIGINT' ? 2 : signal === 'SIGTERM' ? 15 : 1) : 1)
125
+ void ticker.stop().then(() => resolve(status))
126
+ })
127
+ })
128
+ }
@@ -0,0 +1,315 @@
1
+ // @ts-check
2
+ // `sssb tick <app>` (an app's `pnpm tick`) — calls the running dev server's scheduled-tick route once and says what ran.
3
+ //
4
+ // In a deployment an external scheduler POSTs each app's `/api/webhooks/cron` (the `scheduled-tick` cutover row).
5
+ // In `pnpm dev` nothing does, so a due digest or a webhook retry sits there until somebody does it by hand. This is
6
+ // the by-hand, as one command; `sssb dev-tick` (dev-tick.js) is the same call on a timer, opt-in.
7
+ //
8
+ // What this is NOT: a way around the route's guard. The route is `withWebhookSecret(...)`, and this sends it the
9
+ // per-checkout dev secret (`<app>/.data/auth/webhook-secret`, the file the simulated server generates) as a bearer,
10
+ // exactly as an external caller would. It adds nothing to the server: no flag, no header the server honours, no
11
+ // route. A server in real mode checks `WEBHOOK_SECRET` instead, never reads that file, and answers this 401.
12
+ //
13
+ // Run through the package script (`pnpm tick`, `pnpm tick:starter`): the working directory is then the app's, which is
14
+ // where the server keeps `.data` (`APP_DATA_DIR` overrides it, for both).
15
+ import { existsSync, readFileSync } from 'node:fs'
16
+ import path from 'node:path'
17
+ import { foreignAppSlotProblem, portFor } from '../ports.js'
18
+
19
+ /**
20
+ * The built-in apps that have a tick route. The key is the PORT key (a slot, not the app's name, so it survives a
21
+ * rename of the app). An app that declares a slot of its own (`"sssb": { "port": { "name": … } }`) ticks under that
22
+ * name, which `tickSlot` resolves from the declaration the command read.
23
+ */
24
+ const TICK_APPS = ['showcase', 'starter']
25
+
26
+ /**
27
+ * What an app name on a tick command line means: a built-in app, or the slot the app in the working directory
28
+ * declares under that name. Undefined when it is neither.
29
+ * @param {string} app
30
+ * @param {import('../ports.d.ts').PortDeclaration | undefined} [declared]
31
+ * @returns {import('../ports.d.ts').PortDeclaration | undefined}
32
+ */
33
+ export function tickSlot(app, declared) {
34
+ // Another app's built-in slot is no app of this one's when it declares a slot of its own (foreignAppSlotProblem).
35
+ if (TICK_APPS.includes(app)) {
36
+ return foreignAppSlotProblem(app, declared) === null
37
+ ? /** @type {import('../ports.d.ts').PortService} */ (app)
38
+ : undefined
39
+ }
40
+ return declared !== undefined && typeof declared === 'object' && declared.name === app ? declared : undefined
41
+ }
42
+
43
+ /**
44
+ * The names `tickSlot` accepts, for a usage message.
45
+ * @param {import('../ports.d.ts').PortDeclaration | undefined} [declared]
46
+ */
47
+ export function tickAppNames(declared) {
48
+ return typeof declared === 'object' ? [declared.name] : [...TICK_APPS]
49
+ }
50
+
51
+ export const TICK_PATH = '/api/webhooks/cron'
52
+
53
+ /** A cold `next dev` compiles the route on its first hit, so the default is generous. */
54
+ export const DEFAULT_TIMEOUT_SECONDS = 60
55
+
56
+ /** Bounds that keep `AbortSignal.timeout` meaningful: a value that rounds to 0 times out at once, a huge one throws. */
57
+ const MIN_TIMEOUT_SECONDS = 0.1
58
+ const MAX_TIMEOUT_SECONDS = 3600
59
+
60
+ const USAGE = `usage: pnpm tick [--url <origin>] [--timeout <seconds>] (sssb tick also takes --app <dir>)
61
+ (per app: pnpm tick = showcase, pnpm tick:starter = starter; direct: sssb tick <${TICK_APPS.join('|')}, or the slot an app declares for itself> ...)
62
+
63
+ --url <origin> the dev server's origin, loopback only (default: this checkout's port for the app)
64
+ --timeout <seconds> give up on the request after this long, ${MIN_TIMEOUT_SECONDS} to ${MAX_TIMEOUT_SECONDS} (default ${DEFAULT_TIMEOUT_SECONDS})`
65
+
66
+ /** A failure with a message meant for the person at the terminal. `usage` marks a bad command line, not a bad tick. */
67
+ export class TickError extends Error {
68
+ /** @param {string} message @param {{ usage?: boolean }} [options] */
69
+ constructor(message, { usage = false } = {}) {
70
+ super(message)
71
+ this.name = 'TickError'
72
+ this.usage = usage
73
+ }
74
+ }
75
+
76
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]'])
77
+
78
+ /**
79
+ * Loopback only. The bearer is the dev secret and it is sent in the clear, so a URL that is not this machine is
80
+ * refused rather than trusted: there is no flag to point this at a real deployment, whose scheduler is not this.
81
+ *
82
+ * @param {string} value
83
+ * @returns {string} the origin, without a trailing slash
84
+ */
85
+ export function parseLoopbackOrigin(value) {
86
+ let url
87
+ try {
88
+ url = new URL(value)
89
+ } catch {
90
+ throw new TickError(`--url must be an origin like http://localhost:3000, got "${value}"`, { usage: true })
91
+ }
92
+ if (url.protocol !== 'http:' || !LOOPBACK_HOSTS.has(url.hostname)) {
93
+ throw new TickError(
94
+ `--url must be http on localhost, 127.0.0.1 or [::1] (the dev secret is sent as a bearer), got "${value}"`,
95
+ { usage: true },
96
+ )
97
+ }
98
+ return url.origin
99
+ }
100
+
101
+ /**
102
+ * @param {string[]} argv the arguments after the script name
103
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
104
+ * @returns {{ app: string, origin: string, timeoutMs: number }}
105
+ */
106
+ export function parseTickArgs(argv, declared) {
107
+ /** @type {string | undefined} */
108
+ let app
109
+ /** @type {string | undefined} */
110
+ let url
111
+ let timeoutSeconds = DEFAULT_TIMEOUT_SECONDS
112
+
113
+ for (let i = 0; i < argv.length; i++) {
114
+ const arg = argv[i]
115
+ const flag = arg.startsWith('--') ? arg.split('=', 1)[0] : null
116
+ if (flag === '--url' || flag === '--timeout') {
117
+ const inline = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : undefined
118
+ const value = inline ?? argv[++i]
119
+ if (value === undefined || value === '' || (inline === undefined && value.startsWith('--'))) {
120
+ throw new TickError(`${flag} needs a value`, { usage: true })
121
+ }
122
+ if (flag === '--url') {
123
+ url = value
124
+ } else {
125
+ const parsed = Number(value)
126
+ if (!Number.isFinite(parsed) || parsed < MIN_TIMEOUT_SECONDS || parsed > MAX_TIMEOUT_SECONDS) {
127
+ throw new TickError(
128
+ `--timeout must be between ${MIN_TIMEOUT_SECONDS} and ${MAX_TIMEOUT_SECONDS} seconds, got "${value}"`,
129
+ { usage: true },
130
+ )
131
+ }
132
+ timeoutSeconds = parsed
133
+ }
134
+ } else if (arg.startsWith('-')) {
135
+ throw new TickError(`unknown option "${arg}"`, { usage: true })
136
+ } else if (app === undefined) {
137
+ app = arg
138
+ } else {
139
+ throw new TickError(`unexpected argument "${arg}"`, { usage: true })
140
+ }
141
+ }
142
+
143
+ if (app === undefined) throw new TickError('which app? the first argument is the app', { usage: true })
144
+ const slot = tickSlot(app, declared)
145
+ if (slot === undefined) {
146
+ throw new TickError(
147
+ foreignAppSlotProblem(app, declared) ??
148
+ `unknown app "${app}" (known: ${tickAppNames(declared).join(', ')})`,
149
+ { usage: true },
150
+ )
151
+ }
152
+
153
+ let origin
154
+ if (url !== undefined) {
155
+ origin = parseLoopbackOrigin(url)
156
+ } else {
157
+ try {
158
+ origin = `http://localhost:${portFor(slot)}`
159
+ } catch (error) {
160
+ throw new TickError(error instanceof Error ? error.message : String(error), { usage: true })
161
+ }
162
+ }
163
+ return { app, origin, timeoutMs: Math.round(timeoutSeconds * 1000) }
164
+ }
165
+
166
+ /**
167
+ * Where the simulated server keeps its inbound-webhook secret: `dataDir('auth')` in the kit
168
+ * (`APP_DATA_DIR`, else `.data` under the app's working directory) plus `webhook-secret`.
169
+ *
170
+ * @param {Record<string, string | undefined>} [env]
171
+ * @param {string} [cwd]
172
+ */
173
+ export function secretFilePath(env = process.env, cwd = process.cwd()) {
174
+ return path.join(env.APP_DATA_DIR ?? path.join(cwd, '.data'), 'auth', 'webhook-secret')
175
+ }
176
+
177
+ /**
178
+ * @param {unknown} error
179
+ * @param {string} endpoint
180
+ */
181
+ function unreachable(error, endpoint) {
182
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : error
183
+ const code = cause && typeof cause === 'object' && 'code' in cause ? String(cause.code) : null
184
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) {
185
+ return new TickError(`no answer from ${endpoint} before the timeout`)
186
+ }
187
+ if (code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'UND_ERR_SOCKET') {
188
+ return new TickError(`could not reach ${endpoint} (${code}) — is the dev server running? (\`pnpm dev\`)`)
189
+ }
190
+ return new TickError(`request to ${endpoint} failed: ${error instanceof Error ? error.message : String(error)}`)
191
+ }
192
+
193
+ /**
194
+ * One tick. Resolves to the route's JSON body; rejects with a `TickError` for anything that is not a 2xx.
195
+ *
196
+ * The first request to a checkout's server is what creates its secret file, so with none on disk yet one request
197
+ * goes out with a throwaway bearer (a 401, by design) to make the server write it, then the real one follows.
198
+ *
199
+ * `signal` ends a tick early (the dev ticker passes the one that stops it, so a tick in flight does not outlive the
200
+ * server it was for).
201
+ *
202
+ * @param {{ origin: string, timeoutMs: number, secretFile?: string, fetchImpl?: typeof fetch, signal?: AbortSignal }} options
203
+ * @returns {Promise<Record<string, unknown>>}
204
+ */
205
+ export async function tickOnce({ origin, timeoutMs, secretFile = secretFilePath(), fetchImpl = fetch, signal }) {
206
+ const endpoint = `${origin}${TICK_PATH}`
207
+ /** @param {string} bearer */
208
+ const post = async (bearer) => {
209
+ try {
210
+ return await fetchImpl(endpoint, {
211
+ method: 'POST',
212
+ headers: { authorization: `Bearer ${bearer}` },
213
+ signal: signal
214
+ ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)])
215
+ : AbortSignal.timeout(timeoutMs),
216
+ })
217
+ } catch (error) {
218
+ throw unreachable(error, endpoint)
219
+ }
220
+ }
221
+
222
+ if (!existsSync(secretFile)) {
223
+ const probe = await post('x')
224
+ await probe.body?.cancel()
225
+ if (!existsSync(secretFile)) {
226
+ throw new TickError(
227
+ `the server at ${origin} did not create a dev secret at ${secretFile}. Is it a simulated-mode dev server ` +
228
+ `(\`pnpm dev\`, not \`dev:real\`), and is this the app's own directory (APP_DATA_DIR unset or matching)?`,
229
+ )
230
+ }
231
+ }
232
+
233
+ /** @type {string} */
234
+ let secret
235
+ try {
236
+ secret = readFileSync(secretFile, 'utf8')
237
+ } catch (error) {
238
+ throw new TickError(
239
+ `could not read the dev secret at ${secretFile}: ${error instanceof Error ? error.message : String(error)}`,
240
+ )
241
+ }
242
+ const response = await post(secret)
243
+ const text = await response.text()
244
+ if (response.status === 401) {
245
+ throw new TickError(
246
+ `${endpoint} answered 401: the server did not accept the secret in ${secretFile}. A server in real mode checks ` +
247
+ `WEBHOOK_SECRET, not this file; a server started from another checkout or data dir has its own secret.`,
248
+ )
249
+ }
250
+ if (!response.ok) throw new TickError(`${endpoint} answered ${response.status}: ${text.slice(0, 300)}`)
251
+ try {
252
+ const body = JSON.parse(text)
253
+ if (body && typeof body === 'object' && !Array.isArray(body)) return body
254
+ } catch {
255
+ // fall through to the same message as a non-object body
256
+ }
257
+ throw new TickError(
258
+ `${endpoint} answered ${response.status} with a body that is not the tick's JSON: ${text.slice(0, 300)}`,
259
+ )
260
+ }
261
+
262
+ /** @param {unknown} value */
263
+ function count(value) {
264
+ return typeof value === 'number' ? value : 0
265
+ }
266
+
267
+ /**
268
+ * What a tick did, in one line. `failed` is a schedule whose spawn failed (the next tick retries it) and a delivery
269
+ * that failed or died: shown, but it is the tick reporting work that went wrong, not the tick failing.
270
+ *
271
+ * @param {Record<string, unknown>} body the route's JSON: `{ ok, spawned, failed, deliveries: { delivered, failed, dead } }`
272
+ */
273
+ export function summarizeTick(body) {
274
+ const deliveries =
275
+ body.deliveries && typeof body.deliveries === 'object'
276
+ ? /** @type {Record<string, unknown>} */ (body.deliveries)
277
+ : {}
278
+ return (
279
+ `ticked: ${count(body.spawned)} job(s) spawned from due schedules, ${count(body.failed)} schedule(s) failed; ` +
280
+ `webhook deliveries: ${count(deliveries.delivered)} delivered, ${count(deliveries.failed)} failed, ${count(deliveries.dead)} dead`
281
+ )
282
+ }
283
+
284
+ /**
285
+ * Whether a tick moved anything at all, for a caller that only wants to speak when something happened.
286
+ *
287
+ * @param {Record<string, unknown>} body
288
+ */
289
+ export function tickDidWork(body) {
290
+ const deliveries =
291
+ body.deliveries && typeof body.deliveries === 'object'
292
+ ? /** @type {Record<string, unknown>} */ (body.deliveries)
293
+ : {}
294
+ return [body.spawned, body.failed, deliveries.delivered, deliveries.failed, deliveries.dead].some(
295
+ (n) => count(n) > 0,
296
+ )
297
+ }
298
+
299
+ /**
300
+ * @param {string[]} argv
301
+ * @param {import('../ports.d.ts').PortDeclaration} [declared] the port slot the app in the working directory declares
302
+ */
303
+ export async function main(argv, declared) {
304
+ try {
305
+ const { origin, timeoutMs } = parseTickArgs(argv, declared)
306
+ const body = await tickOnce({ origin, timeoutMs })
307
+ console.log(summarizeTick(body))
308
+ return 0
309
+ } catch (error) {
310
+ if (!(error instanceof TickError)) throw error
311
+ console.error(`tick: ${error.message}`)
312
+ if (error.usage) console.error(USAGE)
313
+ return error.usage ? 2 : 1
314
+ }
315
+ }
@@ -0,0 +1,17 @@
1
+ /** Where a running dev ticker records itself: `<APP_DATA_DIR or ./.data>/dev-ticker.json`. */
2
+ export declare function tickerMarkerPath(env?: Record<string, string | undefined>, cwd?: string): string
3
+
4
+ /** Records a live ticker (this process's pid and its interval). */
5
+ export declare function writeTickerMarker(file: string, seconds: number): void
6
+
7
+ /** Removes the record, if this process wrote it: another ticker's marker is not ours to delete. */
8
+ export declare function removeTickerMarker(file: string): void
9
+
10
+ /** The live ticker a marker records, or null when there is none or its process is gone. */
11
+ export declare function liveTickerMarker(file: string): { pid: number; seconds: number; startedAt: string } | null
12
+
13
+ /**
14
+ * Throws while a dev ticker is live in this app's data directory: a Playwright config calls it so a ticking dev
15
+ * server is never adopted by an e2e run, whose scheduler must do nothing until a test asks.
16
+ */
17
+ export declare function assertNoLiveDevTicker(env?: Record<string, string | undefined>, cwd?: string): void