@sssb/tools 0.3.0 → 0.5.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sssb/tools",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -44,8 +44,16 @@ export declare function failClosedEnvironmentProblems(env: Record<string, unknow
44
44
 
45
45
  /**
46
46
  * Problems with Secrets Manager and managed-policy grants: every Secrets Manager grant names only the
47
- * cluster's own secret, and no role attaches an AWS-managed policy the check cannot read. Needs the one
48
- * `AWS::RDS::DBCluster` in the template; runs on every database shape.
47
+ * cluster's own secret, no role, user or group attaches an AWS-managed policy the check cannot read, and no
48
+ * `AWS::IAM::*` resource is of a type the check does not read. Grants are read from `AWS::IAM::Policy`,
49
+ * `ManagedPolicy`, `RolePolicy`, `UserPolicy` and `GroupPolicy`, and from a `Role`'s, `User`'s or `Group`'s inline
50
+ * `Policies`; the IAM types that grant nothing (an instance profile, an identity provider, a service-linked role,
51
+ * an access key, a certificate, an MFA device, a user-to-group addition) pass. A `*` or `?` in a granted resource
52
+ * is a wildcard. An `AWS::SecretsManager::ResourcePolicy` on the cluster's secret (or on a secret the check cannot
53
+ * tell is another) may let in only the roles the stack's own Lambda functions run as, each named as
54
+ * `{ AWS: { Fn::GetAtt: [<role>, Arn] } }`: any other principal (`*`, an account, a service, a `NotPrincipal`), or a
55
+ * policy the check cannot read, is a problem. Needs the one `AWS::RDS::DBCluster` in the template; runs on every
56
+ * database shape.
49
57
  */
50
58
  export declare function secretGrantProblems(resources: Resources): string[]
51
59
 
@@ -78,22 +78,63 @@ export function failClosedEnvironmentProblems(env) {
78
78
  return problems
79
79
  }
80
80
 
81
+ // THE IAM TYPES THE CHECKS READ, and the ones that grant nothing. A grant is read from a policy resource's own
82
+ // document (a policy, a managed policy, a role's, user's or group's policy), from a principal's inline policies, and,
83
+ // for an AWS-managed policy a principal attaches, judged by name (unreadablePolicies). Any other `AWS::IAM::*` type
84
+ // fails closed (unreadTypes): one this file does not know could carry a grant it cannot see.
85
+ const POLICY_TYPES = new Set([
86
+ 'AWS::IAM::Policy',
87
+ 'AWS::IAM::ManagedPolicy',
88
+ 'AWS::IAM::RolePolicy',
89
+ 'AWS::IAM::UserPolicy',
90
+ 'AWS::IAM::GroupPolicy',
91
+ ])
92
+ const PRINCIPAL_TYPES = new Set(['AWS::IAM::Role', 'AWS::IAM::User', 'AWS::IAM::Group'])
93
+ // Each grants nothing of its own: a role's carrier for EC2, identity providers, a service-linked role (whose policy
94
+ // is the service's, fixed by AWS), credentials and certificates, and a user put in a group (the group's grants are
95
+ // read where the group is).
96
+ const GRANTS_NOTHING = new Set([
97
+ 'AWS::IAM::InstanceProfile',
98
+ 'AWS::IAM::OIDCProvider',
99
+ 'AWS::IAM::SAMLProvider',
100
+ 'AWS::IAM::ServiceLinkedRole',
101
+ 'AWS::IAM::ServerCertificate',
102
+ 'AWS::IAM::VirtualMFADevice',
103
+ 'AWS::IAM::AccessKey',
104
+ 'AWS::IAM::UserToGroupAddition',
105
+ ])
106
+
81
107
  /**
82
- * The permission documents a resource carries: a policy's, a managed policy's, or a role's inline ones.
108
+ * The permission documents a resource carries: a policy resource's own, or a role's, user's or group's inline ones.
83
109
  * @param {Resource} resource
84
110
  * @returns {unknown[]}
85
111
  */
86
112
  function policyDocuments(resource) {
87
- if (resource.Type === 'AWS::IAM::Policy' || resource.Type === 'AWS::IAM::ManagedPolicy') {
88
- return [resource.Properties?.PolicyDocument]
89
- }
90
- if (resource.Type === 'AWS::IAM::Role') {
113
+ if (POLICY_TYPES.has(resource.Type)) return [resource.Properties?.PolicyDocument]
114
+ if (PRINCIPAL_TYPES.has(resource.Type)) {
91
115
  const inline = /** @type {{ PolicyDocument?: unknown }[] | undefined} */ (resource.Properties?.Policies) ?? []
92
116
  return inline.map((policy) => policy.PolicyDocument)
93
117
  }
94
118
  return []
95
119
  }
96
120
 
121
+ /**
122
+ * Each `AWS::IAM::*` resource of a type the checks neither read nor know to grant nothing, as `<id> (<type>)`.
123
+ * @param {Resources} all
124
+ * @returns {string[]}
125
+ */
126
+ function unreadTypes(all) {
127
+ return Object.entries(all)
128
+ .filter(
129
+ ([, r]) =>
130
+ r.Type.startsWith('AWS::IAM::') &&
131
+ !POLICY_TYPES.has(r.Type) &&
132
+ !PRINCIPAL_TYPES.has(r.Type) &&
133
+ !GRANTS_NOTHING.has(r.Type),
134
+ )
135
+ .map(([id, r]) => `${id} (${r.Type})`)
136
+ }
137
+
97
138
  /**
98
139
  * Whether an IAM action pattern can name one of `service`'s actions. IAM matches `*` and `?` anywhere in
99
140
  * an action, so `*`, `rds-data:*` and `rds*:Execute*` all reach `rds-data:ExecuteStatement`.
@@ -110,7 +151,7 @@ function reaches(action, service) {
110
151
  }
111
152
 
112
153
  /**
113
- * Every Allow statement in the stack's IAM policies, managed policies and roles' inline policies that can
154
+ * Every Allow statement in the stack's IAM policy resources and its roles', users' and groups' inline policies that can
114
155
  * grant one of `service`'s actions (`rds-data`, `secretsmanager`): by naming one, by a wildcard that
115
156
  * reaches one (`*` reaches every service), or by `NotAction`, which grants everything it does not name.
116
157
  * Roles' trust policies grant nothing and are not read.
@@ -153,7 +194,7 @@ function unreadablePolicies(all) {
153
194
  .map(([id]) => id),
154
195
  )
155
196
  return Object.entries(all)
156
- .filter(([, r]) => r.Type === 'AWS::IAM::Role')
197
+ .filter(([, r]) => PRINCIPAL_TYPES.has(r.Type))
157
198
  .flatMap(([id, r]) =>
158
199
  /** @type {unknown[] | undefined} */ (r.Properties?.ManagedPolicyArns ?? [])
159
200
  .filter((arn) => {
@@ -188,7 +229,80 @@ function databaseSecretIds(all, clusterId) {
188
229
  }
189
230
 
190
231
  /**
191
- * Whether every resource `statement` grants refers to one of `ids`, and none is a wildcard.
232
+ * The roles the stack's Lambda functions run as, by logical id: the only principals a resource policy on the cluster's
233
+ * secret may name (the server's and the migrator's are among them).
234
+ * @param {Resources} all
235
+ * @returns {Set<string>}
236
+ */
237
+ function functionRoles(all) {
238
+ return new Set(
239
+ Object.values(all)
240
+ .filter((r) => r.Type === 'AWS::Lambda::Function')
241
+ .map((r) => /** @type {{ 'Fn::GetAtt'?: unknown[] } | undefined} */ (r.Properties?.Role)?.['Fn::GetAtt'])
242
+ .filter((att) => Array.isArray(att) && att[1] === 'Arn' && typeof att[0] === 'string')
243
+ .map((att) => /** @type {string} */ (/** @type {unknown[]} */ (att)[0]))
244
+ .filter((id) => all[id]?.Type === 'AWS::IAM::Role'),
245
+ )
246
+ }
247
+
248
+ /**
249
+ * Each resource policy on the cluster's secret that lets in a principal other than a role one of the stack's own
250
+ * functions runs as, as `<id>`. A resource policy grants with no IAM resource at all (`Principal: "*"` and
251
+ * `GetSecretValue` is the secret for anyone), so it is read here. Fails closed: a policy whose secret is not a `Ref` to
252
+ * another secret of the stack counts as on the cluster's, and a principal that is not exactly
253
+ * `{ AWS: { Fn::GetAtt: [<role>, Arn] } }` (or a list of those), a `NotPrincipal`, or a document the check cannot
254
+ * read, is a problem.
255
+ * @param {Resources} all
256
+ * @param {readonly string[]} secretIds
257
+ * @returns {string[]}
258
+ */
259
+ function secretResourcePolicies(all, secretIds) {
260
+ const roles = functionRoles(all)
261
+ /** @param {unknown} principal */
262
+ const isOwnRole = (principal) => {
263
+ if (principal === null || typeof principal !== 'object' || Object.keys(principal).length !== 1) return false
264
+ const att = /** @type {{ 'Fn::GetAtt'?: unknown[] }} */ (principal)['Fn::GetAtt']
265
+ return (
266
+ Array.isArray(att) &&
267
+ att.length === 2 &&
268
+ att[1] === 'Arn' &&
269
+ typeof att[0] === 'string' &&
270
+ roles.has(att[0])
271
+ )
272
+ }
273
+ /** @param {unknown} principal */
274
+ const onlyOwnRoles = (principal) => {
275
+ if (principal === null || typeof principal !== 'object' || Array.isArray(principal)) return false
276
+ const keys = Object.keys(principal)
277
+ if (keys.length !== 1 || keys[0] !== 'AWS') return false
278
+ const aws = /** @type {{ AWS: unknown }} */ (principal).AWS
279
+ const list = Array.isArray(aws) ? aws : [aws]
280
+ return list.length > 0 && list.every(isOwnRole)
281
+ }
282
+ return Object.entries(all)
283
+ .filter(([, r]) => r.Type === 'AWS::SecretsManager::ResourcePolicy')
284
+ .filter(([, r]) => {
285
+ const ref = /** @type {{ Ref?: unknown } | undefined} */ (r.Properties?.SecretId)?.Ref
286
+ const another =
287
+ typeof ref === 'string' && !secretIds.includes(ref) && all[ref]?.Type === 'AWS::SecretsManager::Secret'
288
+ return !another
289
+ })
290
+ .filter(([, r]) => {
291
+ const statements = /** @type {{ Statement?: unknown } | undefined} */ (r.Properties?.ResourcePolicy)
292
+ ?.Statement
293
+ if (!Array.isArray(statements)) return true
294
+ return statements.some((statement) => {
295
+ const st = /** @type {Statement & { Principal?: unknown, NotPrincipal?: unknown }} */ (statement)
296
+ if (st.Effect === 'Deny') return false
297
+ return st.NotPrincipal !== undefined || !onlyOwnRoles(st.Principal)
298
+ })
299
+ })
300
+ .map(([id]) => id)
301
+ }
302
+
303
+ /**
304
+ * Whether every resource `statement` grants refers to one of `ids`, and none is a wildcard (`*` or `?`, which IAM
305
+ * matches anywhere in a resource).
192
306
  * @param {Statement} statement
193
307
  * @param {readonly string[]} ids
194
308
  */
@@ -196,7 +310,7 @@ function namesOnly(statement, ids) {
196
310
  const granted = Array.isArray(statement.Resource) ? statement.Resource : [statement.Resource ?? '*']
197
311
  return granted.every((resource) => {
198
312
  const text = JSON.stringify(resource)
199
- return !text.includes('*') && ids.some((id) => text.includes(`"Ref":"${id}"`))
313
+ return !/[*?]/.test(text) && ids.some((id) => text.includes(`"Ref":"${id}"`))
200
314
  })
201
315
  }
202
316
 
@@ -225,7 +339,19 @@ export function secretGrantProblems(resources) {
225
339
  }
226
340
  const unreadable = unreadablePolicies(resources)
227
341
  if (unreadable.length > 0) {
228
- problems.push(`no role attaches an AWS-managed policy the check cannot read: ${unreadable.join('; ')}`)
342
+ problems.push(
343
+ `no role, user or group attaches an AWS-managed policy the check cannot read: ${unreadable.join('; ')}`,
344
+ )
345
+ }
346
+ const open = secretResourcePolicies(resources, secretIds)
347
+ if (open.length > 0) {
348
+ problems.push(
349
+ `no resource policy on the cluster’s secret lets in any principal but the stack’s own functions’ roles: ${open.join('; ')}`,
350
+ )
351
+ }
352
+ const unread = unreadTypes(resources)
353
+ if (unread.length > 0) {
354
+ problems.push(`no IAM resource is of a type this check does not read: ${unread.join('; ')}`)
229
355
  }
230
356
  return problems
231
357
  }
@@ -14,11 +14,12 @@
14
14
  // it to Node. So a bare specifier is FOLLOWED when its real path is outside node_modules (the app's own files, its `@/`
15
15
  // alias, a sibling workspace package and whatever that imports) or is framework source in any copy (its nearest named
16
16
  // package.json is `@sssb/kit`'s), and the seam always; every other package stays external. A `require()` esbuild can
17
- // see is followed like an import. A function made by `createRequire(...)` it cannot see through, so a followed file
18
- // outside the kit that names `createRequire` in its code and, as a string literal in its code, an `@sssb/kit`
19
- // specifier esbuild did not resolve (other than the entry and the kit's `package.json`) fails too; the file is read
20
- // by the app's own TypeScript parser, so a comment is not code. A computed specifier stays out of reach of any static
21
- // check.
17
+ // see is followed like an import. A loader it cannot see through (a function made by `createRequire(...)`, a plain
18
+ // `require` handed a variable that holds the specifier) is not, so a followed file outside the kit that writes, as a
19
+ // string literal in its code, an `@sssb/kit` specifier esbuild did not resolve (other than the entry and a `.md` or
20
+ // `.json` file of the kit, such as the guide or its `package.json`, other than a property name, and other than an import or export declaration's or a type `import('…')`'s, which esbuild reads or
21
+ // which load nothing) fails too; the file is read by the app's own TypeScript parser, so a comment is not code. A
22
+ // computed specifier stays out of reach of any static check.
22
23
  //
23
24
  // WHICH FILES: Playwright is asked. Each Playwright config of the app (`playwright.config.*`,
24
25
  // `playwright.<name>.config.*` in its directory), plus each `--config <file>` given (repeatable, relative to the
@@ -54,8 +55,10 @@ import { isInRepoKit, seamOfKit } from './doctor-checks.js'
54
55
 
55
56
  const KIT = '@sssb/kit'
56
57
  const ENTRY = `${KIT}/testing/e2e`
57
- /** Kit specifiers beside `createRequire` that load no framework code. */
58
+ /** Kit specifiers written in code that load no framework code: the entry, and a data file (the guide, a manifest). */
58
59
  const NOT_FRAMEWORK = new Set([ENTRY, `${KIT}/package.json`])
60
+ /** @param {string} specifier */
61
+ const loadsNoFramework = (specifier) => NOT_FRAMEWORK.has(specifier) || /\.(md|json)$/.test(specifier)
59
62
  const KEEP = /^@sssb\/(kit|app-config)(\/|$)/
60
63
  const PROBE = 'sssbCheckE2eProbe'
61
64
  const CONFIG = /^playwright(\.[\w-]+)?\.config\.(c|m)?[jt]s$/
@@ -369,20 +372,22 @@ function chain(metafile, from, to) {
369
372
  const typescripts = new Map()
370
373
 
371
374
  /**
372
- * The `@sssb/kit` specifiers `file` writes as string literals in its CODE, when its code also names `createRequire`
373
- * (none otherwise). Read by the app's own TypeScript parser, as doctor reads the app's tsconfig: comments are not code.
375
+ * The `@sssb/kit` specifiers `file` writes as string literals in its CODE, outside the module specifier of an import or
376
+ * export declaration and a type `import('…')` (esbuild follows the first, and neither a type-only declaration nor a type
377
+ * import loads anything) and a `declare module` name. Read by the app's own TypeScript parser, as doctor reads the
378
+ * app's tsconfig: comments are not code.
374
379
  * @param {string} app
375
380
  * @param {string} file
376
381
  * @param {string} text
377
382
  * @returns {string[]}
378
383
  */
379
- function kitLiteralsBesideCreateRequire(app, file, text) {
384
+ function kitLiteralsInCode(app, file, text) {
380
385
  let ts = typescripts.get(app)
381
386
  if (ts === undefined) {
382
387
  const resolved = resolveFromApp(
383
388
  app,
384
389
  'typescript',
385
- 'sssb check-e2e reads the files that name `createRequire` with',
390
+ 'sssb check-e2e reads the files it follows for a kit specifier esbuild cannot see with',
386
391
  )
387
392
  ts = /** @type {typeof import('typescript')} */ (createRequire(import.meta.url)(resolved))
388
393
  typescripts.set(app, ts)
@@ -396,29 +401,36 @@ function kitLiteralsBesideCreateRequire(app, file, text) {
396
401
  : /^\.[cm]?ts$/.test(ext)
397
402
  ? ts.ScriptKind.TS
398
403
  : ts.ScriptKind.JS
399
- const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false, kind)
400
- let creates = false
404
+ const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind)
401
405
  /** @type {string[]} */
402
406
  const literals = []
403
407
  /** @param {import('typescript').Node} node */
404
408
  const visit = (node) => {
405
- if (ts.isIdentifier(node) && node.text === 'createRequire') creates = true
406
- else if (
409
+ if (
407
410
  (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) &&
408
411
  /^@sssb\/kit(\/|$)/.test(node.text)
409
- )
410
- literals.push(node.text)
412
+ ) {
413
+ const parent = node.parent
414
+ const named =
415
+ ((ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) &&
416
+ parent.moduleSpecifier === node) ||
417
+ // a string-literal TYPE (`type S = '@sssb/kit/…'`, an import('…') type's argument): a type loads nothing
418
+ ts.isLiteralTypeNode(parent) ||
419
+ // a NAME (an object-literal or class key, an interface member, a `declare module`): never a specifier
420
+ ('name' in parent && parent.name === node)
421
+ if (!named) literals.push(node.text)
422
+ }
411
423
  ts.forEachChild(node, visit)
412
424
  }
413
425
  visit(source)
414
- return creates ? literals : []
426
+ return literals
415
427
  }
416
428
 
417
429
  /**
418
430
  * @typedef {{ file: string, error?: string, reached: { kitFile: string, via: string[] }[], count: number,
419
431
  * unfollowed: string[], throughEntry: boolean }} SpecReach
420
432
  * `reached`: the kit files outside the entry that the file enters the kit through (each with its import chain);
421
- * `count`: every kit file outside the entry it reaches; `unfollowed`: a kit specifier named beside `createRequire`
433
+ * `count`: every kit file outside the entry it reaches; `unfollowed`: a kit specifier named where esbuild cannot follow it
422
434
  * that esbuild could not follow; `throughEntry`: whether it reaches the allowed entry at all
423
435
  */
424
436
 
@@ -511,18 +523,20 @@ export async function e2eReach(appDir, extraConfigs = []) {
511
523
  input.imports.some((i) => i.path === key && !i.external),
512
524
  ),
513
525
  )
514
- // What esbuild cannot see: a kit specifier beside `createRequire` in a followed file outside the kit.
526
+ // What esbuild cannot see: a kit specifier written in the code of a followed file outside the kit, which it did not
527
+ // resolve as an import (a `createRequire(...)` function, a `require` of a variable).
515
528
  /** @type {string[]} */
516
529
  const unfollowed = []
517
530
  for (const [key, input] of Object.entries(result.metafile.inputs)) {
518
531
  const source = realOf.get(key) ?? key
519
532
  if (!path.isAbsolute(source) || isKit(source) || underNodeModules(source)) continue
520
533
  const text = readFileSync(source, 'utf8')
521
- if (!/\bcreateRequire\b/.test(text)) continue
522
534
  const seen = new Set(input.imports.map((i) => i.original))
523
- for (const specifier of kitLiteralsBesideCreateRequire(app, source, text)) {
524
- if (!NOT_FRAMEWORK.has(specifier) && !seen.has(specifier))
525
- unfollowed.push(`${show(source)} names '${specifier}' beside createRequire`)
535
+ for (const specifier of kitLiteralsInCode(app, source, text)) {
536
+ if (!loadsNoFramework(specifier) && !seen.has(specifier))
537
+ unfollowed.push(
538
+ `${show(source)} names '${specifier}' where esbuild cannot follow it: reach the kit through ${ENTRY}, or keep the specifier out of code a spec loads`,
539
+ )
526
540
  }
527
541
  }
528
542
  reach.push({
@@ -278,7 +278,11 @@ export async function run(args) {
278
278
  // checks under the config a bare `vitest` loads for each app. It runs for the first app, not the root, because
279
279
  // an adopter's root need not resolve @sssb/kit. Then, in each app, no e2e spec reaching the kit other than
280
280
  // through @sssb/kit/testing/e2e.
281
- const { run: doctor } = await import('./doctor.js')
281
+ // The walk is held to every app the job fans out over, as a bare `sssb doctor` at the root holds it to every app
282
+ // the workspace names: an app the workspace's packages do not reach fails here, with doctor's own line.
283
+ const { doctorFor } = await import('./doctor.js')
284
+ const named = apps.map((app) => path.join(root, app))
285
+ const doctor = async () => doctorFor({ dir: path.join(root, apps[0] ?? '.'), defaulted: false, named })
282
286
  checks.push(['doctor', doctor, ['--app', path.join(root, apps[0] ?? '.')]])
283
287
  const { run: checkE2e } = await import('./check-e2e.js')
284
288
  for (const app of apps) checks.push(['check-e2e', checkE2e, ['--app', path.join(root, app)]])
@@ -141,8 +141,18 @@ export function doctorApp(args, cwd = process.cwd()) {
141
141
  /** @param {string[]} args */
142
142
  export async function run(args) {
143
143
  const chosen = doctorApp(args)
144
- const appDir = realpathSync(chosen.dir)
145
144
  if (args.length > 0) throw new UsageError(`sssb doctor: unknown argument ${args[0]} (usage: doctor [--app <dir>])`)
145
+ return doctorFor(chosen)
146
+ }
147
+
148
+ /**
149
+ * One doctor run, from `dir`, holding the walk to reach every app in `named` (absolute directories). `sssb ci` calls it
150
+ * with the apps it fans out over, so CI's doctor makes the same check as a bare `sssb doctor` at the root.
151
+ * @param {{ dir: string, defaulted: boolean, named: string[] }} chosen
152
+ * @returns {Promise<number>}
153
+ */
154
+ export async function doctorFor(chosen) {
155
+ const appDir = realpathSync(chosen.dir)
146
156
  const root = realpathSync(workspaceRootOf(appDir))
147
157
  const rel = relativeTo(root)
148
158
  // Said before anything can fail on the app it chose, so a failure there is read with the reason it was picked.
@@ -8,8 +8,9 @@
8
8
  // against the starter without Items, applied EXACTLY by ./exact-patch.js). The code half removes everything an app's
9
9
  // code says about Items: the card, the route, the query, the ability, the catalog namespace, the dashboard's glue, the
10
10
  // static demo's card, the specs that name Items, and the proofs of paging. It writes nothing of its own: the starter's
11
- // other e2e spec (the Simulator's) stays, so the app still has one for `sssb check-e2e`. The database half removes the migrations, the table's type and its
12
- // RLS proofs, and only runs with `--drop-migrations`.
11
+ // e2e specs that do not name Items (the Simulator's among them) stay, so the app still has some for `sssb check-e2e`.
12
+ // The database half removes the migrations, the table's type and its RLS proofs, and only runs with
13
+ // `--drop-migrations`.
13
14
  //
14
15
  // THE RULE FOR MIGRATIONS. A database that ran `1001_items` records it, and the migrator refuses to start when a migration
15
16
  // it recorded is gone from the code (Kysely: "previously executed migration ... is missing"). So this command never
@@ -10,6 +10,7 @@
10
10
  // The port: PORT when set, else the named port service, else the app's declared one (`"sssb": { "port": … }`).
11
11
  import { spawn } from 'node:child_process'
12
12
  import { cpSync, existsSync, readdirSync } from 'node:fs'
13
+ import { constants } from 'node:os'
13
14
  import path from 'node:path'
14
15
  import { appPortService, serviceNamed, servicesKnownTo } from '../app-port.js'
15
16
  import { takeAppDir, UsageError } from '../app.js'
@@ -68,11 +69,23 @@ export async function run(args) {
68
69
  env: { ...process.env, PORT: port, HOSTNAME: '127.0.0.1', APP_DATA_DIR: dataDir },
69
70
  cwd: serverDir,
70
71
  })
72
+ // A signal sent to this process alone (`kill <pid>`, a supervisor, a CI cancel) is forwarded, so the server does not
73
+ // outlive the wrapper holding the app's port, where the next run's `reuseExistingServer` would adopt a stale
74
+ // build. A server that dies on a signal is a failure (128 + the signal's number), never a success.
75
+ /** @type {NodeJS.Signals[]} */
76
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP']
77
+ const forwards = signals.map((signal) => /** @type {const} */ ([signal, () => child.kill(signal)]))
78
+ for (const [signal, forward] of forwards) process.on(signal, forward)
71
79
  return await new Promise((resolve) => {
80
+ /** @param {number} status */
81
+ const done = (status) => {
82
+ for (const [signal, forward] of forwards) process.off(signal, forward)
83
+ resolve(status)
84
+ }
72
85
  child.on('error', (error) => {
73
86
  console.error(`Could not start the standalone server: ${error.message}`)
74
- resolve(1)
87
+ done(1)
75
88
  })
76
- child.on('exit', (code) => resolve(code ?? 0))
89
+ child.on('exit', (code, signal) => done(code ?? 128 + (signal ? constants.signals[signal] : 1)))
77
90
  })
78
91
  }
package/src/ports.d.ts CHANGED
@@ -32,10 +32,11 @@ export declare function readPortDeclaration(appDir: string): PortDeclaration | u
32
32
 
33
33
  /**
34
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.
35
+ * (`STARTER_PORT`, `LEDGER_PORT`) when set, a port derived from the path in a linked git worktree (a checkout whose
36
+ * `.git` is a file pointing into a repository's `.git/worktrees/`, or any path under `.claude/worktrees/`), and the
37
+ * documented default otherwise. A built-in's derived port is keyed on the checkout alone; a custom slot's also on its
38
+ * name, so two slots of one worktree differ, and comes from a band no built-in uses (20000-29999). It reads nothing but
39
+ * that `.git`, so it can be tested against checkouts that do not exist.
39
40
  */
40
41
  export declare function portForRoot(
41
42
  root: string,
package/src/ports.js CHANGED
@@ -15,7 +15,11 @@
15
15
  // * STABLE ACROSS PROCESSES. The package script that starts the server and the Playwright config that points
16
16
  // at it compute it independently: they agree only because neither one guesses.
17
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.
18
+ // :3100 stays true for the person reading it. Only a linked git worktree derives: one whose `.git` (at the
19
+ // checkout's root or the nearest above it) is a FILE pointing into the main repository's `.git/worktrees/`,
20
+ // which is what `git worktree add` writes wherever the worktree is, and, read from the path alone, any checkout
21
+ // under `.claude/worktrees/` (Claude Code's own, and a checkout that does not exist yet). A submodule's `.git` is
22
+ // a file too, pointing into `.git/modules/`, and keeps the defaults.
19
23
  //
20
24
  // An explicit env var always wins, which is what makes an isolated one-off run possible without editing
21
25
  // anything: `SHOWCASE_PORT=3210 pnpm dev`.
@@ -33,7 +37,7 @@
33
37
  // repository this package is a workspace link, so its real path is outside node_modules and Playwright compiles
34
38
  // it. Walking up from the working directory is the portable option.
35
39
  import { createHash } from 'node:crypto'
36
- import { existsSync, readFileSync, realpathSync } from 'node:fs'
40
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
37
41
  import path from 'node:path'
38
42
 
39
43
  /**
@@ -68,7 +72,7 @@ const SLOTS = 200
68
72
  const SERVICES = {
69
73
  showcase: { env: 'SHOWCASE_PORT', fallback: 3000, derive: (slot) => 3200 + slot * 2 },
70
74
  starter: { env: 'STARTER_PORT', fallback: 3100, derive: (slot) => 3201 + slot * 2 },
71
- ladle: { env: 'LADLE_PORT', fallback: 61000, derive: (slot) => 61000 + slot },
75
+ ladle: { env: 'LADLE_PORT', fallback: 61000, derive: (slot) => 61001 + slot },
72
76
  contractPg: { env: 'CONTRACT_PG_PORT', fallback: 5439, derive: (slot) => 5440 + slot },
73
77
  }
74
78
 
@@ -91,7 +95,7 @@ const slotFor = (root) => hashOf(root) % SLOTS
91
95
  /**
92
96
  * The band a custom slot's derived port comes from in a linked worktree: 10000 ports, so two custom slots of one
93
97
  * 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)
98
+ * default and derived band (3000, 3100, 3200-3599, 5439-5639, 61000-61200), and below Linux's ephemeral range (32768)
95
99
  * and macOS's (49152), so the OS never hands one of these to an outbound connection.
96
100
  */
97
101
  const CUSTOM_BAND = { start: 20000, size: 10000 }
@@ -221,8 +225,35 @@ export function portForRoot(root, service, env = process.env) {
221
225
  return parsed
222
226
  }
223
227
 
224
- const linked = root.includes(`${path.sep}.claude${path.sep}worktrees${path.sep}`)
225
- return linked ? spec.derive(root) : spec.fallback
228
+ return isLinkedWorktree(root) ? spec.derive(root) : spec.fallback
229
+ }
230
+
231
+ // The `gitdir:` line `git worktree add` writes into a linked worktree's `.git` file: a directory under the main
232
+ // repository's `.git/worktrees/`.
233
+ const LINKED_GITDIR = /^gitdir:\s*(.+?)\s*$/m
234
+ const WORKTREES_ENTRY = /[\\/]worktrees[\\/][^\\/]+[\\/]?$/
235
+
236
+ /**
237
+ * Whether `root` is a linked git worktree: under `.claude/worktrees/` by its path alone, or with a `.git` FILE at it or
238
+ * the nearest above it that points into a repository's `.git/worktrees/`. A main checkout's `.git` is a directory; a
239
+ * submodule's is a file pointing into `.git/modules/`.
240
+ * @param {string} root
241
+ */
242
+ function isLinkedWorktree(root) {
243
+ if (root.includes(`${path.sep}.claude${path.sep}worktrees${path.sep}`)) return true
244
+ for (let dir = path.resolve(root); ; dir = path.dirname(dir)) {
245
+ const git = path.join(dir, '.git')
246
+ if (existsSync(git)) {
247
+ if (!statSync(git).isFile()) return false
248
+ try {
249
+ const gitdir = LINKED_GITDIR.exec(readFileSync(git, 'utf8'))?.[1]
250
+ return gitdir !== undefined && WORKTREES_ENTRY.test(gitdir)
251
+ } catch {
252
+ return false
253
+ }
254
+ }
255
+ if (path.dirname(dir) === dir) return false
256
+ }
226
257
  }
227
258
 
228
259
  /**
@@ -1,8 +1,8 @@
1
1
  diff --git a/messages/en.json b/messages/en.json
2
- index 43e5945..15cd515 100644
2
+ index 63e30fc..15cd515 100644
3
3
  --- a/messages/en.json
4
4
  +++ b/messages/en.json
5
- @@ -8,14 +8,5 @@
5
+ @@ -8,15 +8,5 @@
6
6
  "dashboard": {
7
7
  "title": "Dashboard",
8
8
  "signedInAs": "Signed in as {name} ({role})."
@@ -12,16 +12,17 @@ index 43e5945..15cd515 100644
12
12
  - "hint": "Items belong to the team you're working in — and never leave your tenant.",
13
13
  - "empty": "No items in this team yet.",
14
14
  - "addLabel": "New item",
15
+ - "addError": "That item could not be added. Your text is still here: try again.",
15
16
  - "addButton": "Add item",
16
17
  - "readOnlyHint": "You have read-only access to items in this team.",
17
18
  - "loadMore": "Show older items"
18
19
  }
19
20
  }
20
21
  diff --git a/messages/es.json b/messages/es.json
21
- index 07b6b29..7a7ecf8 100644
22
+ index b6428fd..7a7ecf8 100644
22
23
  --- a/messages/es.json
23
24
  +++ b/messages/es.json
24
- @@ -8,14 +8,5 @@
25
+ @@ -8,15 +8,5 @@
25
26
  "dashboard": {
26
27
  "title": "Panel",
27
28
  "signedInAs": "Sesión iniciada como {name} ({role})."
@@ -31,34 +32,25 @@ index 07b6b29..7a7ecf8 100644
31
32
  - "hint": "Los elementos pertenecen al equipo en el que trabajas y nunca salen de tu organización.",
32
33
  - "empty": "Aún no hay elementos en este equipo.",
33
34
  - "addLabel": "Nuevo elemento",
35
+ - "addError": "No se pudo añadir el elemento. Tu texto sigue aquí: inténtalo de nuevo.",
34
36
  - "addButton": "Añadir elemento",
35
37
  - "readOnlyHint": "Tienes acceso de solo lectura a los elementos de este equipo.",
36
38
  - "loadMore": "Ver elementos anteriores"
37
39
  }
38
40
  }
39
41
  diff --git a/playwright.config.ts b/playwright.config.ts
40
- index a4815c5..e5a31e1 100644
42
+ index 9317684..106ccfc 100644
41
43
  --- a/playwright.config.ts
42
44
  +++ b/playwright.config.ts
43
- @@ -20,15 +20,15 @@ const BASE_URL = originForApp(__dirname)
44
- export default defineConfig({
45
+ @@ -21,7 +21,7 @@ export default defineConfig({
45
46
  testDir: './tests/e2e',
46
47
  fullyParallel: true,
47
- - // This app's whole suite is two short specs, so the first always starts against a cold dev server and pays a
48
+ // This app's whole suite is a few short specs, so the first always starts against a cold dev server and pays a
48
49
  - // full Next compile on every route it touches — sign-in, dashboard, the items route, the Simulator's. The default
49
- + // This app's whole suite is one short spec, so it always starts against a cold dev server and pays a
50
50
  + // full Next compile on every route it touches — sign-in, dashboard, the Simulator's. The default
51
51
  // 30s is marginal for that (it timed out on the first run and passed on retry), and there is no
52
52
  // warm-up pass to inherit, so the budget is raised rather than left to flake.
53
53
  timeout: 60_000,
54
- expect: { timeout: 15_000 },
55
- forbidOnly: !!process.env['CI'],
56
- retries: process.env['CI'] ? 2 : 1,
57
- - // One worker, on CI too — this app's whole suite is two short specs, so parallelism buys little here,
58
- + // One worker, on CI too — this app's whole suite is one short spec, so parallelism buys little here,
59
- // and more workers against one shared world (one `.data` behind one dev server) cost reliability rather than
60
- // saving time.
61
- workers: 1,
62
54
  diff --git a/src/app-config/abilities.ts b/src/app-config/abilities.ts
63
55
  index c69a9ec..851160c 100644
64
56
  --- a/src/app-config/abilities.ts
@@ -256,7 +248,7 @@ index 117cbdc..6539ae5 100644
256
248
  /**
257
249
  * The app's catalog for one locale. Framework code (the next-intl request config, the parity tests)
258
250
  diff --git a/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx b/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
259
- index 5fdea5a..874f935 100644
251
+ index 1aa84a0..874f935 100644
260
252
  --- a/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
261
253
  +++ b/src/app/[locale]/(protected)/dashboard/dashboard-glue.tsx
262
254
  @@ -1,61 +1,7 @@
@@ -312,10 +304,10 @@ index 5fdea5a..874f935 100644
312
304
  - headers: { 'content-type': 'application/json' },
313
305
  - body: JSON.stringify({ title }),
314
306
  - })
315
- - if (response.ok) {
316
- - const { item } = (await response.json()) as { item: Item }
317
- - setItems((prev) => [item, ...prev])
318
- - }
307
+ - // A refusal rejects, so the card keeps the draft and shows its error.
308
+ - if (!response.ok) throw new Error(`POST /api/items answered ${response.status}`)
309
+ - const { item } = (await response.json()) as { item: Item }
310
+ - setItems((prev) => [item, ...prev])
319
311
  - }}
320
312
  - />
321
313
  - </DashboardScreen>
@@ -352,9 +344,47 @@ index 1794523..9fba9eb 100644
352
344
  + // from @sssb/kit/authz/authorize, and re-check with `authorize()` in every route that writes.
353
345
  + return <DashboardGlue user={{ name: user.name, role: user.role }} />
354
346
  }
347
+ diff --git a/src/app/api/items/route.test.ts b/src/app/api/items/route.test.ts
348
+ deleted file mode 100644
349
+ index d0672c3..0000000
350
+ --- a/src/app/api/items/route.test.ts
351
+ +++ /dev/null
352
+ @@ -1,32 +0,0 @@
353
+ -import { beforeEach, describe, expect, test, vi } from 'vitest'
354
+ -import { POST } from './route'
355
+ -
356
+ -const h = vi.hoisted(() => ({ requireUser: vi.fn(), withTenant: vi.fn() }))
357
+ -vi.mock('@sssb/kit/adapters/index', () => ({ auth: { requireUser: h.requireUser }, db: { withTenant: h.withTenant } }))
358
+ -
359
+ -function post(body: string): Promise<Response> {
360
+ - return POST(new Request('http://localhost/api/items', { method: 'POST', body }))
361
+ -}
362
+ -
363
+ -beforeEach(() => {
364
+ - h.requireUser.mockReset()
365
+ - h.withTenant.mockReset()
366
+ - h.requireUser.mockResolvedValue({ id: 'user-one', tenantSlug: 'acme', orgSlug: 'team', restricted: false })
367
+ -})
368
+ -
369
+ -describe('POST /api/items: a malformed body is a 400, never a 500', () => {
370
+ - test.each([['{'], ['null'], ['[]']])('a body %s that is not an object', async (body) => {
371
+ - expect((await post(body)).status).toBe(400)
372
+ - expect(h.withTenant).not.toHaveBeenCalled()
373
+ - })
374
+ -
375
+ - test.each([[JSON.stringify({ title: 5 })], [JSON.stringify({ title: ' ' })], [JSON.stringify({})]])(
376
+ - 'a title that is not a non-empty string: %s',
377
+ - async (body) => {
378
+ - const response = await post(body)
379
+ - expect(response.status).toBe(400)
380
+ - expect(await response.json()).toEqual({ error: 'empty item' })
381
+ - expect(h.withTenant).not.toHaveBeenCalled()
382
+ - },
383
+ - )
384
+ -})
355
385
  diff --git a/src/app/api/items/route.ts b/src/app/api/items/route.ts
356
386
  deleted file mode 100644
357
- index cb2d480..0000000
387
+ index f1caa3f..0000000
358
388
  --- a/src/app/api/items/route.ts
359
389
  +++ /dev/null
360
390
  @@ -1,59 +0,0 @@
@@ -365,7 +395,7 @@ index cb2d480..0000000
365
395
  -import { orgIdForSlug } from '@sssb/kit/db/org-lookup'
366
396
  -import { tenantIdForSlug } from '@sssb/kit/db/tenant-lookup'
367
397
  -import { listItems } from '@/domain/db/items'
368
- -import { withPortErrors } from '../respond'
398
+ -import { readJsonObject, withPortErrors } from '../respond'
369
399
  -
370
400
  -/**
371
401
  - * The app's only product route. Items are tenant-scoped by RLS (the hostile-isolation boundary) AND
@@ -398,8 +428,8 @@ index cb2d480..0000000
398
428
  -export async function POST(request: Request): Promise<Response> {
399
429
  - return withPortErrors(async () => {
400
430
  - const user = await auth.requireUser()
401
- - const { title } = (await request.json()) as { title: string }
402
- - if (!title?.trim()) return Response.json({ error: 'empty item' }, { status: 400 })
431
+ - const { title } = await readJsonObject(request)
432
+ - if (typeof title !== 'string' || !title.trim()) return Response.json({ error: 'empty item' }, { status: 400 })
403
433
  - const tenantId = await tenantIdForSlug(db, user.tenantSlug)
404
434
  - if (!tenantId) return Response.json({ error: 'unknown tenant' }, { status: 404 })
405
435
  - const orgId = await orgIdForSlug(db, tenantId, user.orgSlug)
@@ -432,12 +462,76 @@ index 42b10b7..20ada9e 100644
432
462
  const t = useTranslations('dashboard')
433
463
  return (
434
464
  <Container component="main" size="sm" py="xl">
465
+ diff --git a/src/components/items-card.test.tsx b/src/components/items-card.test.tsx
466
+ deleted file mode 100644
467
+ index 2380455..0000000
468
+ --- a/src/components/items-card.test.tsx
469
+ +++ /dev/null
470
+ @@ -1,58 +0,0 @@
471
+ -import { MantineProvider } from '@mantine/core'
472
+ -import { NextIntlClientProvider } from 'next-intl'
473
+ -import { act } from 'react'
474
+ -import { createRoot } from 'react-dom/client'
475
+ -import { afterEach, describe, expect, it } from 'vitest'
476
+ -import en from '../../messages/en.json'
477
+ -import { ItemsCard } from './items-card'
478
+ -
479
+ -/** A create that fails keeps what the person typed and says so; one that succeeds clears the box. */
480
+ -
481
+ -const unmounts: Array<() => void> = []
482
+ -afterEach(() => {
483
+ - for (const unmount of unmounts.splice(0)) act(unmount)
484
+ -})
485
+ -
486
+ -async function addWith(onAdd: (title: string) => Promise<void>): Promise<HTMLElement> {
487
+ - ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
488
+ - const container = document.createElement('div')
489
+ - document.body.append(container)
490
+ - const root = createRoot(container)
491
+ - await act(async () => {
492
+ - root.render(
493
+ - <NextIntlClientProvider locale="en" messages={en}>
494
+ - <MantineProvider>
495
+ - <ItemsCard items={[]} onAdd={onAdd} />
496
+ - </MantineProvider>
497
+ - </NextIntlClientProvider>,
498
+ - )
499
+ - })
500
+ - unmounts.push(() => root.unmount())
501
+ - const input = container.querySelector<HTMLInputElement>('[data-testid="item-input"]')!
502
+ - await act(async () => {
503
+ - // React tracks a controlled input's value; set it through the native setter so onChange sees the change.
504
+ - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'my important draft')
505
+ - input.dispatchEvent(new Event('input', { bubbles: true }))
506
+ - })
507
+ - await act(async () => {
508
+ - container.querySelector<HTMLButtonElement>('[data-testid="item-add"]')!.click()
509
+ - })
510
+ - return container
511
+ -}
512
+ -
513
+ -const inputValue = (container: HTMLElement) =>
514
+ - container.querySelector<HTMLInputElement>('[data-testid="item-input"]')!.value
515
+ -
516
+ -describe('ItemsCard', () => {
517
+ - it('keeps the draft and shows an alert when the create fails', async () => {
518
+ - const container = await addWith(() => Promise.reject(new Error('403')))
519
+ - expect(inputValue(container)).toBe('my important draft')
520
+ - expect(container.querySelector('[role="alert"]')?.textContent).toBe(en.items.addError)
521
+ - })
522
+ -
523
+ - it('clears the draft, with no alert, when the create succeeds', async () => {
524
+ - const container = await addWith(() => Promise.resolve())
525
+ - expect(inputValue(container)).toBe('')
526
+ - expect(container.querySelector('[role="alert"]')).toBeNull()
527
+ - })
528
+ -})
435
529
  diff --git a/src/components/items-card.tsx b/src/components/items-card.tsx
436
530
  deleted file mode 100644
437
- index 9a501ae..0000000
531
+ index a36ed54..0000000
438
532
  --- a/src/components/items-card.tsx
439
533
  +++ /dev/null
440
- @@ -1,106 +0,0 @@
534
+ @@ -1,117 +0,0 @@
441
535
  -'use client'
442
536
  -
443
537
  -import { Button, Card, Group, Stack, Text, TextInput, Title } from '@mantine/core'
@@ -462,6 +556,7 @@ index 9a501ae..0000000
462
556
  - onLoadMore,
463
557
  -}: {
464
558
  - items: Item[]
559
+ - /** Rejects when the item was not created: the card then keeps the draft and says so. */
465
560
  - onAdd: (title: string) => Promise<void>
466
561
  - /** When false (restricted members), the add affordance is disabled and a read-only hint shows. */
467
562
  - canCreate?: boolean
@@ -473,6 +568,7 @@ index 9a501ae..0000000
473
568
  - const t = useTranslations('items')
474
569
  - const [draft, setDraft] = useState('')
475
570
  - const [busy, setBusy] = useState(false)
571
+ - const [addFailed, setAddFailed] = useState(false)
476
572
  - const [loadingMore, setLoadingMore] = useState(false)
477
573
  -
478
574
  - return (
@@ -527,14 +623,23 @@ index 9a501ae..0000000
527
623
  - data-testid="item-add"
528
624
  - onClick={() => {
529
625
  - setBusy(true)
626
+ - setAddFailed(false)
530
627
  - onAdd(draft.trim())
531
- - .then(() => setDraft(''))
628
+ - .then(
629
+ - () => setDraft(''),
630
+ - () => setAddFailed(true),
631
+ - )
532
632
  - .finally(() => setBusy(false))
533
633
  - }}
534
634
  - >
535
635
  - {t('addButton')}
536
636
  - </Button>
537
637
  - </Group>
638
+ - {addFailed ? (
639
+ - <Text size="sm" c="red.8" role="alert" data-testid="items-add-error">
640
+ - {t('addError')}
641
+ - </Text>
642
+ - ) : null}
538
643
  - {!canCreate ? (
539
644
  - <Text size="sm" c="gray.7" data-testid="items-readonly-hint">
540
645
  - {t('readOnlyHint')}
package/src/tick/tick.js CHANGED
@@ -267,8 +267,11 @@ function count(value) {
267
267
  }
268
268
 
269
269
  /**
270
- * What a tick did, in one line. `failed` is a schedule whose spawn failed (the next tick retries it) and a delivery
271
- * that failed or died: shown, but it is the tick reporting work that went wrong, not the tick failing.
270
+ * What a tick did, in one line. `failed` is a schedule whose spawn failed, and a delivery that failed or died: shown,
271
+ * but it is the tick reporting work that went wrong, not the tick failing. A failed schedule is retried by the next tick
272
+ * only when the failure was inside the spawn transaction (it rolled back); after that transaction commits, the job is
273
+ * left queued and the schedule has moved on (the in-process runner's sweep fails the job after five minutes; see
274
+ * `@sssb/kit/db/schedules`).
272
275
  *
273
276
  * @param {Record<string, unknown>} body the route's JSON: `{ ok, spawned, failed, deliveries: { delivered, failed, dead } }`
274
277
  */
@@ -16,7 +16,7 @@ export interface TickerStatus {
16
16
  export interface Ticker {
17
17
  /** Starts ticking every `seconds`, or does nothing if it already is (an interval change is a stop then a start). */
18
18
  start(seconds: number): TickerStatus
19
- /** Stops ticking and waits for a tick in flight to end. */
19
+ /** Stops ticking, waits for a tick in flight to end, and resolves to the status then (`running: false`). */
20
20
  stop(): Promise<TickerStatus>
21
21
  status(): TickerStatus
22
22
  }
@@ -32,5 +32,8 @@ export interface TickerOptions {
32
32
  now?: () => Date
33
33
  }
34
34
 
35
+ /** A sleep that ends early, and quietly, when `signal` aborts: the ticker's default `sleep`. */
36
+ export declare function abortableSleep(ms: number, signal: AbortSignal): Promise<void>
37
+
35
38
  /** The dev ticker: one object that owns start, stop, the interval and whether it is running. */
36
39
  export declare function createTicker(options: TickerOptions): Ticker
@@ -123,15 +123,21 @@ export function createTicker({
123
123
  return { ...state }
124
124
  },
125
125
 
126
- /** Stops it, cancels a tick in flight, and resolves once the loop has ended. Safe to call when not running. */
126
+ /**
127
+ * Stops it, cancels a tick in flight, and resolves to the status once the loop has ended. Safe to call when not
128
+ * running.
129
+ *
130
+ * @returns {Promise<TickerStatus>}
131
+ */
127
132
  async stop() {
128
133
  const stopping = controller
129
134
  controller = null
130
- if (!stopping) return
135
+ if (!stopping) return { ...state }
131
136
  stopping.abort()
132
137
  if (markerFile) removeTickerMarker(markerFile)
133
138
  state = { ...state, running: false }
134
139
  await loop
140
+ return { ...state }
135
141
  },
136
142
 
137
143
  /** @returns {TickerStatus} */