rvlib-shipkit 2.24.0 → 2.25.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 (81) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/package.json +1 -1
  3. package/src/agent-time/live.ts +153 -0
  4. package/src/annex/offload.ts +16 -7
  5. package/src/check.ts +3 -1
  6. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  7. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  8. package/src/checks/SK033-global-contribution.check.ts +1 -1
  9. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  10. package/src/checks/SK040-release-words.check.ts +1 -1
  11. package/src/checks/SK042-post-kinds.check.ts +1 -1
  12. package/src/cli/cmd_Annex.ts +12 -7
  13. package/src/cli/cmd_Assets.ts +5 -5
  14. package/src/cli/cmd_Backup.ts +11 -5
  15. package/src/cli/cmd_Capacity.ts +10 -6
  16. package/src/cli/cmd_Checks.ts +12 -1
  17. package/src/cli/cmd_Ci.ts +2 -2
  18. package/src/cli/cmd_Commands.ts +11 -2
  19. package/src/cli/cmd_ConfigKeys.ts +17 -0
  20. package/src/cli/cmd_Home.ts +1 -1
  21. package/src/cli/cmd_Keys.ts +4 -1
  22. package/src/cli/cmd_Lanes.ts +35 -0
  23. package/src/cli/cmd_Mv.ts +6 -7
  24. package/src/cli/cmd_Rec.ts +22 -7
  25. package/src/cli/cmd_Review.ts +107 -39
  26. package/src/cli/cmd_Shot.ts +15 -4
  27. package/src/cli/cmd_Status.ts +6 -5
  28. package/src/cli/cmd_Time.ts +10 -4
  29. package/src/cli/cmd_Veille.ts +10 -6
  30. package/src/cli/family-help.ts +136 -0
  31. package/src/cli/family-pages.ts +0 -19
  32. package/src/cli/kit/calls.ts +35 -0
  33. package/src/cli/kit/project-cli.ts +2 -12
  34. package/src/cli/registry.ts +39 -6
  35. package/src/cli.ts +8 -4
  36. package/src/core/capacity.ts +89 -33
  37. package/src/core/check-runner.ts +5 -1
  38. package/src/core/floor-resolve.ts +6 -2
  39. package/src/core/floor.ts +6 -2
  40. package/src/core/history-files.ts +18 -0
  41. package/src/core/jobs.ts +35 -16
  42. package/src/core/layout.ts +2 -2
  43. package/src/core/nearest.ts +16 -0
  44. package/src/core/remove-tree.ts +19 -0
  45. package/src/core/runs.ts +12 -3
  46. package/src/core/throwaway-worktree.ts +22 -4
  47. package/src/core/trace-audit.ts +17 -4
  48. package/src/home/daemon-jobs.ts +41 -4
  49. package/src/home/machine-temp.ts +2 -10
  50. package/src/ledger/gate-checks.ts +3 -2
  51. package/src/ledger/git-key.ts +25 -4
  52. package/src/ledger/git-scan.ts +10 -0
  53. package/src/media-store/backup/daemon.ts +92 -20
  54. package/src/media-store/backup/run.ts +21 -15
  55. package/src/media-store/backup/sources.ts +166 -21
  56. package/src/media-store/backup/watch.ts +106 -0
  57. package/src/media-store/daemon.ts +36 -8
  58. package/src/media-store/hand.ts +3 -1
  59. package/src/mv/mv-md.ts +50 -18
  60. package/src/pb/run-pb.ts +2 -10
  61. package/src/plan/repo-source.ts +25 -14
  62. package/src/recordings/model.ts +1 -1
  63. package/src/release/run-bump.ts +3 -2
  64. package/src/release/run-release.ts +12 -4
  65. package/src/review/cells.ts +2 -1
  66. package/src/review/format.ts +1 -1
  67. package/src/review/model.ts +14 -1
  68. package/src/review/store.ts +15 -7
  69. package/src/review/trailer-model.ts +2 -2
  70. package/src/shot/client.ts +4 -2
  71. package/src/shot/serve-shot.ts +71 -2
  72. package/src/shot/shooter.ts +65 -11
  73. package/src/shot/shot-ask.ts +32 -9
  74. package/src/suite/select.ts +13 -2
  75. package/src/suite/test-units.ts +31 -12
  76. package/src/trailer/graph.ts +2 -1
  77. package/src/ts/config.ts +12 -35
  78. package/src/ts/rename.ts +31 -17
  79. package/src/ts/workspaces.ts +45 -0
  80. package/src/wiki/run-wiki.ts +7 -2
  81. package/src/wiki/scan-md.ts +2 -1
@@ -36,7 +36,6 @@ import {
36
36
  verdictMessageOf,
37
37
  verdictOf,
38
38
  viewIndexOf,
39
- withdrawnOf,
40
39
  inWork,
41
40
  UPDATE_STATES,
42
41
  UPDATE_WORDS,
@@ -62,6 +61,7 @@ import {
62
61
  viewFilesOf,
63
62
  mediaFilesOf,
64
63
  threadMediaOf,
64
+ isGallery,
65
65
  } from './model.ts'
66
66
  import { beatRole, roleOf } from './role.ts'
67
67
  import { chainOf, coveringHead, followedIds, isFollowed } from './threads.ts'
@@ -794,12 +794,20 @@ export function markSeen(dir: string, id: string, now = new Date()): boolean {
794
794
  return verdictOf(x) !== null || read > 0
795
795
  }
796
796
 
797
- /** takes an unanswered card back: false when it is unknown or already answered */
798
- export function withdraw(dir: string, id: string, why: string, now = new Date()): boolean {
797
+ /** takes an unanswered card back; `already` names who took it back before, `refused` says why it may not and what to type */
798
+ export function withdraw(dir: string, id: string, why: string, now = new Date()): { already?: string } | { refused: string } {
799
799
  const x = ID_RE.test(id) ? readItem(dir, id) : null
800
- if (!x || verdictOf(x) || withdrawnOf(x) !== undefined) return false
800
+ if (!x) return { refused: `no card ${id}` }
801
+ const before = x.thread.filter((m) => m.op === 'withdraw').at(-1)
802
+ if (before) return { already: `by ${before.who}, ${before.at.slice(0, 16).replace('T', ' ')} UTC` }
803
+ const v = verdictOf(x)
804
+ if (v) {
805
+ const owes = v.status === 'approved-with-fix' ? `sk review done ${id} "<what changed>", ` : ''
806
+ const close = v.status === 'approved-with-fix' || v.status === 'rejected' ? `; what it owes: ${owes}--supersedes ${id} on its new card, or sk review wontfix ${id} --note "<why>"` : ''
807
+ return { refused: `${id}: he answered it (${v.status}), so it waits on him no more${close}` }
808
+ }
801
809
  appendMessage(dir, id, { who: agentName(), op: 'withdraw', note: why }, { now })
802
- return true
810
+ return {}
803
811
  }
804
812
 
805
813
  /** an answered card waits for his answer again: its verdict stays in the thread, before the reopen. `who`: an agent
@@ -1057,7 +1065,7 @@ export async function refreshDraft(dir: string, id: string, o: { image: string;
1057
1065
  const r = x.item
1058
1066
  if (!r.wip || verdictOf(x)) throw new Error(`${id} is not a draft card waiting`)
1059
1067
  const f0 = r.views[0]
1060
- if (!f0 || !('files' in f0) || !('image' in f0.files)) throw new Error(`${id}: its first view is no image`)
1068
+ if (!f0 || isGallery(f0) || !('image' in f0.files)) throw new Error(`${id}: its first view is no image`)
1061
1069
  const folder = join(dir, id)
1062
1070
  const main = await loadView({ label: f0.label, image: o.image }, 'the live frame')
1063
1071
  const image = f0.files.image
@@ -1097,7 +1105,7 @@ export async function readyItem(dir: string, id: string, o: { image?: string; no
1097
1105
  let item: Item = rest
1098
1106
  if (o.image !== undefined) {
1099
1107
  const f0 = rest.views[0]
1100
- if (!f0 || !('files' in f0)) throw new Error(`${id} has no image to replace`)
1108
+ if (!f0 || isGallery(f0)) throw new Error(`${id} has no image to replace`)
1101
1109
  const loaded = await loadView({ label: f0.label, image: o.image }, '--image')
1102
1110
  const folder = join(dir, id)
1103
1111
  const old = 'image' in f0.files ? f0.files.image : undefined
@@ -1,6 +1,6 @@
1
1
  // the trailer view's shapes (wiki tools/trailer/index.md, Frame notes): what the hub answers about a repo's cuts, and a frame
2
2
  // note as the view shows it, read from its item of the one store. Pure: the routes and the page share them
3
- import { isFrame, isReply, partyOf, stateOf, type ReviewItem } from './model.ts'
3
+ import { isFrame, isGallery, isReply, partyOf, stateOf, type ReviewItem } from './model.ts'
4
4
  import type { CutStates } from '../trailer/shot-state.ts'
5
5
 
6
6
  export type NoteState = 'open' | 'done' | 'wontfix'
@@ -98,7 +98,7 @@ export function noteOf(x: ReviewItem, n: number): TrailerNote | null {
98
98
  ...(closing?.note ? { reply: closing.note } : {}),
99
99
  written: x.item.created,
100
100
  ...(closing ? { closed: closing.at } : {}),
101
- still: first && 'files' in first && 'image' in first.files ? first.files.image : 'image.png',
101
+ still: first && !isGallery(first) && 'image' in first.files ? first.files.image : 'image.png',
102
102
  }
103
103
  }
104
104
 
@@ -11,7 +11,7 @@ export const SHOT_PROCESS = 'shot'
11
11
 
12
12
  /** `root`: the repo the shot is for, whose browser cap it holds a slot of while it runs (browser-slot.ts); default the
13
13
  * repo the cwd is in */
14
- export type ShotInput = { url: string; out: string; viewport?: Viewport; dpr?: number; reload?: boolean; waitMs?: number; step?: string; at?: number; root?: string }
14
+ export type ShotInput = { url: string; out: string; viewport?: Viewport; dpr?: number; reload?: boolean; waitMs?: number; step?: string; at?: number; full?: boolean; root?: string }
15
15
  export type ClipInput = ShotInput & { seconds: number; fps?: number; dom?: boolean }
16
16
  export type ShotResult = ShotDone & { via: 'warm' | 'started' | 'local' | 'box' }
17
17
 
@@ -22,11 +22,13 @@ const shotAsk = (i: ShotInput): ShotAsk => ({
22
22
  dpr: i.dpr ?? 1,
23
23
  reload: i.reload ?? false,
24
24
  waitMs: i.waitMs ?? DEFAULT_WAIT_MS,
25
+ ...(i.full ? { full: true } : {}),
25
26
  })
26
27
 
27
28
  /** a service of an older shipkit takes a stepped ask, ignores the step and shoots the page as it loads: never kept */
28
- function stepped(i: { step?: string }, r: ShotResult): void {
29
+ function stepped(i: { step?: string; full?: boolean }, r: ShotResult): void {
29
30
  if (i.step && r.stepped !== true) throw new Error(`the shot service on ${shotUrlBase()} did not step the page (it says: ${r.note}); it runs an older shipkit: sk gp restart ${SHOT_PROCESS}`)
31
+ if (i.full && r.full !== true) throw new Error(`the shot service on ${shotUrlBase()} shot the viewport, not the whole page (it says: ${r.note}); it runs an older shipkit: sk gp restart ${SHOT_PROCESS}`)
30
32
  }
31
33
 
32
34
  /** a png of `url` at `out` (absolute), through the warm browser; with `step`, the page drawn at `at` first */
@@ -1,15 +1,17 @@
1
1
  // the warm shot service, the `shot` global process pm keeps up: an http
2
2
  // door on 127.0.0.1 over one Shooter. `sk shot` and `shotUrl` post an ask
3
3
  // and get back where the file landed. The browser launches on the first
4
- // ask and closes after BROWSER_IDLE_MS; this process itself stays, idle.
4
+ // ask and closes after BROWSER_IDLE_MS; this process itself stays, idle,
5
+ // and runs its own code again once that code moved (reloadWhenIdle).
5
6
  import { dirname } from 'path'
6
7
  import { LIB_VERSION } from '../core/lib-version.ts'
8
+ import type { LoadAnswer } from '../core/load-probe.ts'
7
9
  import { type ClipAsk, isClip, type ShotAsk, shotPort } from './shot-ask.ts'
8
10
  import { Shooter } from './shooter.ts'
9
11
 
10
12
  export const SHOT_SERVICE = 'shipkit-shot'
11
13
 
12
- export function serveShots(port = shotPort(), roots = [process.cwd(), dirname(import.meta.dir)]): { stop(): Promise<void> } {
14
+ export function serveShots(port = shotPort(), roots = [process.cwd(), dirname(import.meta.dir)]): { stop(): Promise<void>; idle(): boolean } {
13
15
  const shooter = new Shooter(roots)
14
16
  const server = Bun.serve({
15
17
  hostname: '127.0.0.1',
@@ -42,12 +44,79 @@ export function serveShots(port = shotPort(), roots = [process.cwd(), dirname(im
42
44
  await shooter.close()
43
45
  void server.stop(true)
44
46
  },
47
+ idle: () => shooter.warm.waiting === 0,
45
48
  }
46
49
  }
47
50
 
51
+ export interface ReloadDeps {
52
+ /** what moved in the service's own code, once settled, else null; `seq` counts every write */
53
+ moved(): string | null
54
+ seq(): number
55
+ idle(): boolean
56
+ loads(): Promise<LoadAnswer>
57
+ /** closes the browser and the server; then `again` runs this invocation on the new code */
58
+ before(): Promise<void>
59
+ again(): void
60
+ say(l: string): void
61
+ }
62
+
63
+ /** one look: the service runs its code again, same pid, once that code moved, no ask is in flight and the new code
64
+ * loads; a tree that fails to load is said once a change and the running code keeps serving */
65
+ export function reloadLook(d: ReloadDeps, held: { seq: number }): Promise<'reloaded' | 'held' | 'stay'> {
66
+ const why = d.moved()
67
+ if (why == null || !d.idle() || held.seq === d.seq()) return Promise.resolve('stay')
68
+ const seq = d.seq()
69
+ return d.loads().then(async (v) => {
70
+ if (!v.ok) {
71
+ held.seq = seq
72
+ d.say(`WARN ${why}, and ${v.file} fails to load (${v.error}): the shot service keeps its running code`)
73
+ return 'held'
74
+ }
75
+ if (!d.idle()) return 'stay'
76
+ d.say(`ok: ${why}: the shot service runs again on it`)
77
+ await d.before()
78
+ d.again()
79
+ return 'reloaded'
80
+ })
81
+ }
82
+
83
+ /** the service's own watch: the lib files its entry reaches, looked at every few seconds */
84
+ async function reloadWhenIdle(s: { stop(): Promise<void>; idle(): boolean }): Promise<void> {
85
+ const { LibWatch, roleGraph } = await import('../home/lib-watch.ts')
86
+ const { probeLoad } = await import('../core/load-probe.ts')
87
+ const { reexecBlocker, reexecSelf } = await import('../core/reexec.ts')
88
+ const lib = dirname(dirname(import.meta.dir))
89
+ const watch = new LibWatch(lib, { only: roleGraph(import.meta.path) })
90
+ if (watch.error != null) return console.error(`WARN no watch on the shipkit source (${watch.error}): an edit of the shots needs sk gp restart shot`)
91
+ const held = { seq: -1 }
92
+ const d: ReloadDeps = {
93
+ moved: () => watch.why(),
94
+ seq: () => watch.seq,
95
+ idle: () => s.idle(),
96
+ loads: () => probeLoad(lib, [import.meta.path]),
97
+ before: () => s.stop(),
98
+ again: () => {
99
+ const blocked = reexecBlocker()
100
+ if (blocked != null) {
101
+ console.error(`FAIL: the shot service stopped to run again and cannot: ${blocked}`)
102
+ process.exit(1)
103
+ }
104
+ reexecSelf()
105
+ },
106
+ say: (l) => (l.startsWith('WARN') ? console.error(l) : console.log(l)),
107
+ }
108
+ let busy = false
109
+ setInterval(() => {
110
+ if (busy) return
111
+ busy = true
112
+ void reloadLook(d, held).finally(() => (busy = false))
113
+ }, 5_000).unref()
114
+ }
115
+
48
116
  if (import.meta.main) {
49
117
  const s = serveShots()
50
118
  console.log(`ok shots on 127.0.0.1:${shotPort()}`)
119
+ void reloadWhenIdle(s)
51
120
  const bye = (): void => void s.stop().finally(() => process.exit(0))
52
121
  process.on('SIGTERM', bye)
53
122
  process.on('SIGINT', bye)
@@ -28,7 +28,7 @@ import { CLIP_INIT, CLIP_QUANTIZER, clipDone, installClip, KEY_EVERY, muxArgs, t
28
28
  import { type ClipPath, clipPathOf, domEncodeArgs, FrameTimeline, largestCanvas, screencastParams } from './dom-clip.ts'
29
29
  import { CLOSE_MS, openBrowser, type PwBrowser, slotFor } from './box.ts'
30
30
  import type { BrowserLease } from './browser-slot.ts'
31
- import { capMsOf, type ClipAsk, pageMove, readMark, type ShotAsk, slotKey, stillFormat, Turns, waitReady } from './shot-ask.ts'
31
+ import { capMsOf, type Clock, type ClipAsk, FULL_MAX_PX, MOVED, navigatedUnder, pageMove, readMark, type ShotAsk, slotKey, stillFormat, Turns, waitReady } from './shot-ask.ts'
32
32
 
33
33
  /** the slice of playwright the shots touch, so the lib types nothing it does not ship */
34
34
  type Cdp = {
@@ -36,11 +36,16 @@ type Cdp = {
36
36
  on(event: string, cb: (e: Record<string, unknown>) => void): unknown
37
37
  off(event: string, cb: (e: Record<string, unknown>) => void): unknown
38
38
  }
39
+ /** a response the page received, as playwright hands it */
40
+ type Answer = { status(): number; url(): string; request(): { method(): string } }
39
41
  type Page = {
40
42
  goto(url: string, o?: { waitUntil?: string; timeout?: number }): Promise<unknown>
41
43
  reload(o?: { waitUntil?: string; timeout?: number }): Promise<unknown>
44
+ url(): string
42
45
  evaluate<R, A>(fn: (a: A) => R | Promise<R>, arg?: A): Promise<R>
43
46
  waitForTimeout(ms: number): Promise<void>
47
+ waitForLoadState(state: 'load', o?: { timeout?: number }): Promise<void>
48
+ on(event: 'response', cb: (r: Answer) => void): void
44
49
  on(event: string, cb: (x: { message?: string; text?(): string; type?(): string; args?(): { jsonValue(): Promise<unknown> }[] }) => void): void
45
50
  close(): Promise<void>
46
51
  isClosed(): boolean
@@ -56,6 +61,16 @@ export async function consoleWords(m: { args?(): { jsonValue(): Promise<unknown>
56
61
  return null
57
62
  }
58
63
  }
64
+ /** the page line of a request the app refused: a shot of a page that is signed out reads as a page that worked.
65
+ * Cookies follow every shot; a page's local storage stays with its context (a viewport, a clip), as on the box */
66
+ export function deniedLine(status: number, method: string, url: string): string | null {
67
+ if (status !== 401 && status !== 403) return null
68
+ return `denied: ${status} on ${method} ${url}, so this shot is likely the page signed out. A sign in kept in local storage does not follow a new viewport, a clip or the idle close (cookies do): sign in at this viewport first`
69
+ }
70
+
71
+ /** chromium's console line for a response answered 401 or 403 */
72
+ export const DENIED_CONSOLE = /^Failed to load resource: the server responded with a status of 40[13]\b/
73
+
59
74
  /** a cookie as playwright reads and writes it */
60
75
  type Cookie = { name: string; value: string; domain: string; path: string } & Record<string, unknown>
61
76
  type Context = {
@@ -86,7 +101,7 @@ export const SHOT_NICE = 10
86
101
  /** a page that paints nothing once the screencast starts is filmed from one still taken after this */
87
102
  const FIRST_FRAME_MS = 1000
88
103
 
89
- export type ShotDone = { out: string; ms: number; phases: Record<string, number>; errors: string[]; note: string; stepped?: true }
104
+ export type ShotDone = { out: string; ms: number; phases: Record<string, number>; errors: string[]; note: string; stepped?: true; full?: true }
90
105
 
91
106
  type Slot = { key: string; url: string; ctx: Context; page: Page; cdp: Cdp; errors: string[]; frozen: boolean }
92
107
 
@@ -105,6 +120,33 @@ export async function resolvePlaywright(roots: string[]): Promise<Playwright> {
105
120
 
106
121
  const ms = (t0: number): number => Math.round(performance.now() - t0)
107
122
 
123
+ /** the page's ready mark; MOVED once a navigation that ran under the probe (a sign in that redirects, a dev server's
124
+ * reload) has loaded its new page */
125
+ const markOf =
126
+ (page: Page) =>
127
+ async (): Promise<string | null | typeof MOVED> => {
128
+ try {
129
+ return await page.evaluate(readMark)
130
+ } catch (e) {
131
+ if (!navigatedUnder(e)) throw e
132
+ await page.waitForLoadState('load', { timeout: 60_000 }).catch(() => undefined)
133
+ return MOVED
134
+ }
135
+ }
136
+ /** the clip of the whole page: the viewport's width, the content's height up to what chromium draws */
137
+ async function wholePage(cdp: Cdp, a: ShotAsk): Promise<{ clip: { x: number; y: number; width: number; height: number; scale: number }; note: string }> {
138
+ const m = await cdp.send('Page.getLayoutMetrics')
139
+ const content = (m['cssContentSize'] ?? m['contentSize']) as { height?: number } | undefined
140
+ const tall = Math.ceil(content?.height ?? a.viewport.height)
141
+ const max = Math.floor(FULL_MAX_PX / a.dpr)
142
+ const height = Math.max(a.viewport.height, Math.min(tall, max))
143
+ return { clip: { x: 0, y: 0, width: a.viewport.width, height, scale: 1 }, note: `whole page ${a.viewport.width}x${height}${tall > max ? ` (cut from ${tall}: chromium draws ${FULL_MAX_PX} px at most)` : ''}` }
144
+ }
145
+
146
+ /** a failure with the first errors the page printed meanwhile: a page that never says ready often says why */
147
+ export const withPageErrors = (msg: string, errors: readonly string[]): string => (errors.length === 0 ? msg : `${msg}; the page said: ${errors.slice(0, 3).join(' | ')}${errors.length > 3 ? ` (+${errors.length - 3} more)` : ''}`)
148
+ const clockOf = (page: Page): Clock => ({ now: () => performance.now(), sleep: (n) => page.waitForTimeout(n) })
149
+
108
150
  const withCap = <T>(what: string, capMs: number, p: Promise<T>): Promise<T> =>
109
151
  Promise.race([p, new Promise<T>((_, fail) => setTimeout(() => fail(new Error(`${what} took past ${capMs / 1000} s`)), capMs).unref?.())])
110
152
 
@@ -240,11 +282,18 @@ export class Shooter {
240
282
 
241
283
  static #listen(page: Page, errors: string[]): void {
242
284
  page.on('pageerror', (e) => errors.push(`pageerror: ${e.message ?? ''}`))
285
+ page.on('response', (r) => {
286
+ const line = deniedLine(r.status(), r.request().method(), r.url())
287
+ if (line != null && !errors.includes(line)) errors.push(line)
288
+ })
243
289
  page.on('console', (m) => {
244
290
  if (m.type?.() !== 'error') return
245
291
  // the text at once, so no error is lost; then its %s filled from the call's own arguments (React names
246
292
  // the duplicate key there), unless the list was cleared or the line moved meanwhile
247
- const line = `console: ${m.text?.() ?? ''}`
293
+ const text = m.text?.() ?? ''
294
+ // chromium's own line for a refused request: the denied line above names it with its url
295
+ if (DENIED_CONSOLE.test(text)) return
296
+ const line = `console: ${text}`
248
297
  const at = errors.push(line) - 1
249
298
  void consoleWords(m).then((w) => {
250
299
  if (w != null && errors[at] === line) errors[at] = `console: ${w}`
@@ -279,11 +328,13 @@ export class Shooter {
279
328
  slot.frozen = false
280
329
  }
281
330
  // a frozen page may have missed an edit: it loads again
282
- if (move === 'none' && thawed) move = 'reload'
331
+ const thawLoad = move === 'none' && thawed
332
+ if (thawLoad) move = 'reload'
283
333
  if (move !== 'none') {
284
334
  const t = performance.now()
285
335
  slot.url = a.url
286
- if (move === 'reload') await slot.page.reload({ waitUntil: 'load', timeout: 60_000 })
336
+ // a page that navigated away from its url (a sign in that redirects) reloads the url, not where it went
337
+ if (move === 'reload' && slot.page.url() === a.url) await slot.page.reload({ waitUntil: 'load', timeout: 60_000 })
287
338
  else {
288
339
  await this.#reach(a.url)
289
340
  await slot.page.goto(a.url, { waitUntil: 'load', timeout: 60_000 })
@@ -291,24 +342,27 @@ export class Shooter {
291
342
  phases['load'] = ms(t)
292
343
  }
293
344
  let t = performance.now()
294
- const how = await waitReady(() => slot.page.evaluate(readMark), move === 'none' ? 0 : a.waitMs, { now: () => performance.now(), sleep: (n) => slot.page.waitForTimeout(n) })
345
+ const how = await waitReady(markOf(slot.page), move === 'none' ? 0 : a.waitMs, clockOf(slot.page)).catch((e: Error) => {
346
+ throw new Error(withPageErrors(e.message, slot.errors))
347
+ })
295
348
  phases['ready'] = ms(t)
296
349
  if (a.step) {
297
350
  t = performance.now()
298
351
  const { stepTo } = await import('./stepped-clip.ts')
299
352
  if (!(await slot.page.evaluate(stepTo, [a.step, a.at ?? 0] as [string, number]))) throw new Error(`the page has no window.${a.step}(t): a stepped page draws the time it is given there`)
300
- await waitReady(() => slot.page.evaluate(readMark), 0, { now: () => performance.now(), sleep: (n) => slot.page.waitForTimeout(n) })
353
+ await waitReady(markOf(slot.page), 0, clockOf(slot.page))
301
354
  // the warm page now shows that moment: the next plain shot of this url loads it again
302
355
  slot.url = ''
303
356
  phases['step'] = ms(t)
304
357
  }
305
358
  t = performance.now()
306
- const r = await slot.cdp.send('Page.captureScreenshot', { ...stillFormat(a.out), optimizeForSpeed: true })
359
+ const whole = a.full ? await wholePage(slot.cdp, a) : null
360
+ const r = await slot.cdp.send('Page.captureScreenshot', { ...stillFormat(a.out), optimizeForSpeed: true, ...(whole ? { clip: whole.clip, captureBeyondViewport: true } : {}) })
307
361
  phases['capture'] = ms(t)
308
362
  mkdirSync(dirname(a.out), { recursive: true })
309
363
  await Bun.write(a.out, Buffer.from(String(r['data']), 'base64'))
310
- const note = `${move === 'none' ? 'warm page' : thawed ? 'frozen page reloaded' : move}, ${how === 'ready' ? 'ready mark' : move === 'none' ? 'no wait' : `${a.waitMs} ms after load`}${a.step ? `, drawn at ${a.at ?? 0}s through window.${a.step}(t)` : ''}`
311
- return { out: a.out, ms: ms(t0), phases, errors: [...slot.errors], note, ...(a.step ? { stepped: true as const } : {}) }
364
+ const note = `${move === 'none' ? 'warm page' : thawLoad ? 'frozen page reloaded' : move}, ${how === 'ready' ? 'ready mark' : move === 'none' ? 'no wait' : `${a.waitMs} ms after load`}${a.step ? `, drawn at ${a.at ?? 0}s through window.${a.step}(t)` : ''}${whole ? `, ${whole.note}` : ''}`
365
+ return { out: a.out, ms: ms(t0), phases, errors: [...slot.errors], note, ...(a.step ? { stepped: true as const } : {}), ...(whole ? { full: true as const } : {}) }
312
366
  }
313
367
 
314
368
  async #clip(a: ClipAsk): Promise<ShotDone> {
@@ -323,7 +377,7 @@ export class Shooter {
323
377
  let t = performance.now()
324
378
  await this.#reach(a.url)
325
379
  await page.goto(a.url, { waitUntil: 'load', timeout: 60_000 })
326
- await waitReady(() => page.evaluate(readMark), a.waitMs, { now: () => performance.now(), sleep: (n) => page.waitForTimeout(n) })
380
+ await waitReady(markOf(page), a.waitMs, clockOf(page))
327
381
  phases['load'] = ms(t)
328
382
  t = performance.now()
329
383
  const stepped = a.step ? { stepped: true as const } : {}
@@ -20,8 +20,13 @@ export type ShotAsk = {
20
20
  /** a still of a stepped page: `window[step](at)` on a fresh load, then its ready mark, then the shot */
21
21
  step?: string
22
22
  at?: number
23
+ /** the whole page, past the viewport's height (a still only) */
24
+ full?: boolean
23
25
  }
24
26
 
27
+ /** a still of the whole page stops at this many device pixels high: chromium draws no taller surface */
28
+ export const FULL_MAX_PX = 16_384
29
+
25
30
  export type ClipAsk = ShotAsk & {
26
31
  seconds: number
27
32
  fps: number
@@ -52,17 +57,17 @@ export function parseViewport(s: string): Viewport {
52
57
  const m = /^\s*(\d+)\s*[,x]\s*(\d+)\s*$/.exec(s)
53
58
  const width = Number(m?.[1])
54
59
  const height = Number(m?.[2])
55
- if (!m || width < 16 || height < 16 || width > 7680 || height > 4320) throw new Error(`--viewport '${s}' is not w,h in pixels (16 to 7680 by 4320), like 1280,720`)
60
+ if (!m || width < 16 || height < 16 || width > 7680 || height > 4320) throw new Error(`--viewport '${s}' is not w,h in pixels (16 to 7680 by 4320), like 1280,720; a whole tall page: --full`)
56
61
  return { width, height }
57
62
  }
58
63
 
59
- /** a bare `localhost:5173/x` or `/x` against nothing reads as http */
64
+ /** a bare `localhost:5173/x` or `/x` against nothing reads as http; a `file://` url is kept */
60
65
  export function normalizeUrl(s: string): string {
61
66
  const t = s.trim()
62
- if (/^https?:\/\//.test(t)) return t
67
+ if (/^(https?|file):\/\//.test(t)) return t
63
68
  if (/^(localhost|127\.0\.0\.1|\[::1\]|[\w.-]+\.\w+)(:\d+)?(\/|$)/.test(t)) return `http://${t}`
64
69
  if (/^:\d+(\/|$)/.test(t)) return `http://localhost${t}`
65
- throw new Error(`'${s}' is not a url: give http://host:port/path, localhost:5173/path or :5173/path`)
70
+ throw new Error(`'${s}' is not a url: give http://host:port/path, localhost:5173/path, :5173/path, or the path of a file`)
66
71
  }
67
72
 
68
73
  /** a still's quality as webp or jpeg: the page's text stays sharp at about an eighth of the png's bytes (a 1280x800
@@ -79,7 +84,7 @@ export function stillFormat(out: string): { format: 'webp' | 'jpeg'; quality: nu
79
84
  * is a webp */
80
85
  export function defaultOut(url: string, ext: 'webp' | 'mp4'): string {
81
86
  const u = new URL(url)
82
- const slug = `${u.hostname}-${u.port || (u.protocol === 'https:' ? '443' : '80')}${u.pathname}${u.search}${u.hash}`
87
+ const slug = (u.protocol === 'file:' ? `file-${u.pathname.split('/').pop() ?? ''}` : `${u.hostname}-${u.port || (u.protocol === 'https:' ? '443' : '80')}${u.pathname}${u.search}${u.hash}`)
83
88
  .replace(/[^\w.-]+/g, '-')
84
89
  .replace(/-+/g, '-')
85
90
  .replace(/^-|-$/g, '')
@@ -100,6 +105,7 @@ export type ShotFlags = {
100
105
  dom?: boolean
101
106
  step?: string
102
107
  at?: string
108
+ full?: boolean
103
109
  }
104
110
 
105
111
  const positive = (flag: string, s: string, max: number): number => {
@@ -115,6 +121,7 @@ export function askOf(f: ShotFlags, cwd: string): ShotAsk | ClipAsk {
115
121
  if (seconds != null && seconds > MAX_CLIP_SECONDS && f.long !== true) throw new Error(`--video ${seconds}: a clip past ${MAX_CLIP_SECONDS} s needs --long (a long clip is a long wait and a big file)`)
116
122
  if (seconds == null && f.fps != null) throw new Error('--fps only applies to a clip: add --video <seconds>')
117
123
  if (seconds == null && f.dom === true) throw new Error('--dom only applies to a clip: add --video <seconds>')
124
+ if (seconds != null && f.full === true) throw new Error('--full only applies to a still: a clip films the viewport (--viewport w,h)')
118
125
  if (f.step != null && !/^[A-Za-z_$][\w$]*$/.test(f.step)) throw new Error(`--step '${f.step}' is not a window function name, like __trailerStep`)
119
126
  if (f.at != null && f.step == null) throw new Error('--at only applies to a stepped still: add --step <hook>')
120
127
  if (f.at != null && seconds != null) throw new Error('--at only applies to a still: a stepped clip draws every time from 0')
@@ -129,7 +136,7 @@ export function askOf(f: ShotFlags, cwd: string): ShotAsk | ClipAsk {
129
136
  waitMs: f.wait == null ? DEFAULT_WAIT_MS : f.wait === '0' ? 0 : positive('--wait', f.wait, 60_000),
130
137
  }
131
138
  const step = f.step == null ? {} : { step: f.step }
132
- if (seconds == null) return { ...base, ...step, ...(f.step == null ? {} : { at: at ?? 0 }) }
139
+ if (seconds == null) return { ...base, ...step, ...(f.step == null ? {} : { at: at ?? 0 }), ...(f.full === true ? { full: true } : {}) }
133
140
  if (!base.out.endsWith('.mp4')) throw new Error(`--out '${f.out}': a clip is an mp4 (H.264)`)
134
141
  return { ...base, seconds, fps: f.fps == null ? DEFAULT_FPS : positive('--fps', f.fps, 60), dom: f.dom === true, ...step }
135
142
  }
@@ -165,12 +172,28 @@ export interface Clock {
165
172
  sleep(ms: number): Promise<void>
166
173
  }
167
174
 
175
+ /** what a probe answers when the page navigated under it (a sign in that redirects, a dev server's reload): the new
176
+ * page loaded, and its wait starts again */
177
+ export const MOVED: unique symbol = Symbol('moved')
178
+ /** a page that navigates more often than this while it loads never holds still */
179
+ export const MAX_MOVES = 50
180
+
181
+ /** the error playwright throws when the page navigated while it ran something in it */
182
+ export const navigatedUnder = (e: unknown): boolean => /Execution context was destroyed|Cannot find context with specified id|frame was detached/i.test((e as Error)?.message ?? '')
183
+
168
184
  /** polls the page until it is ready to shoot: 'ready' once its mark says so, 'fallback' once a page with no mark had
169
185
  * its wait. A page whose mark never says ready fails loud at the cap */
170
- export async function waitReady(probe: () => Promise<string | null>, fallbackMs: number, clock: Clock, capMs = READY_CAP_MS): Promise<'ready' | 'fallback'> {
171
- const t0 = clock.now()
186
+ export async function waitReady(probe: () => Promise<string | null | typeof MOVED>, fallbackMs: number, clock: Clock, capMs = READY_CAP_MS): Promise<'ready' | 'fallback'> {
187
+ let t0 = clock.now()
188
+ let moves = 0
172
189
  for (;;) {
173
- const s = readyOf(await probe())
190
+ const got = await probe()
191
+ if (got === MOVED) {
192
+ if (++moves > MAX_MOVES) throw new Error(`the page navigated ${MAX_MOVES} times while it loaded and never held still`)
193
+ t0 = clock.now()
194
+ continue
195
+ }
196
+ const s = readyOf(got)
174
197
  if (s === 'ready') return 'ready'
175
198
  const spent = clock.now() - t0
176
199
  if (s === 'silent' && spent >= fallbackMs) return 'fallback'
@@ -401,7 +401,18 @@ export function selectSuites(o: {
401
401
  * import and no recorded read claims runs every suite */
402
402
  roots?: string[]
403
403
  }): Selection {
404
- for (const c of o.changed) if (isRunConfig(c, o.envFiles)) return { all: true, why: `${c} changed, and it configures every suite` }
404
+ // bun finds a module's tsconfig and package.json by walking up from it, so a
405
+ // run config configures the run only in a dir holding one of its modules,
406
+ // or above one: another unit's is no read of this run
407
+ const moduleDirs = new Set<string>(['.'])
408
+ for (const m of [...Object.keys(o.graph), ...o.suites, ...o.preloads]) {
409
+ for (let d = posix.dirname(m); !moduleDirs.has(d); d = posix.dirname(d)) {
410
+ moduleDirs.add(d)
411
+ if (d === posix.dirname(d)) break
412
+ }
413
+ }
414
+ const elsewhere = (c: string): boolean => isRunConfig(c, o.envFiles) && !o.envFiles.includes(c) && !moduleDirs.has(posix.dirname(c))
415
+ for (const c of o.changed) if (isRunConfig(c, o.envFiles) && !elsewhere(c)) return { all: true, why: `${c} changed, and it configures every suite` }
405
416
  // the recorder sees only what it hooks (a preload's own load, a tool it
406
417
  // does not know, an API it does not wrap go unseen), so a change where
407
418
  // suites live that nothing claims is unsure, and unsure runs everything
@@ -418,7 +429,7 @@ export function selectSuites(o: {
418
429
  c.endsWith('/') || c.endsWith('/**') || o.graph[c] != null || readSet.has(c) || lists.has(posix.dirname(c)) || trees.some((t) => c.startsWith(t))
419
430
  const under = (c: string): boolean => (o.roots ?? []).some((r) => r === '' || r === '.' || c.startsWith(`${r}/`))
420
431
  const preloadDirs = o.preloads.map((p) => posix.dirname(p))
421
- for (const c of o.changed) if (!claimed(c) && under(c) && !noUnseenReader(c, preloadDirs)) return { all: true, why: `${c} changed, and neither an import nor a recorded read claims it` }
432
+ for (const c of o.changed) if (!claimed(c) && under(c) && !elsewhere(c) && !noUnseenReader(c, preloadDirs)) return { all: true, why: `${c} changed, and neither an import nor a recorded read claims it` }
422
433
  // a changed file moves every module that loads it with itself, and one a
423
434
  // preload loads moves every suite: the preload ran it before any suite
424
435
  const importersOf = (withRuntime: boolean): Map<string, string[]> => {
@@ -100,22 +100,41 @@ export function unitTestBody(pkgText: string | null): { script: string | null; b
100
100
  return { script: null, body: 'bun test' }
101
101
  }
102
102
 
103
- /** the sibling units a unit's tests can read: the ones its package.json names
104
- * in any dependency block, and the ones its tsconfig `paths` point into (a
105
- * bench resolving the libs at their source folders names them nowhere else).
106
- * Their dirs belong to its inputs. Derived, never hand kept, and over
107
- * declaring is safe where under declaring is a stale green */
108
- export function siblingUnits(units: TestUnitDecl[], read: (rel: string) => string | null): Map<string, string[]> {
109
- const pkgs = new Map(units.map((u) => [u.id, parsePkg(read(posix.join(u.rel, 'package.json')))]))
110
- const byName = new Map<string, TestUnitDecl>()
111
- for (const u of units) { const n = pkgs.get(u.id)?.name; if (n != null) byName.set(n, u) }
103
+ /** the package dirs a unit's tests can read, beside its own: every package its
104
+ * package.json names in any dependency block, and every one its tsconfig
105
+ * `paths` point into (a bench resolving the libs at their source folders
106
+ * names them nowhere else), then what those name in turn. A package is a
107
+ * sibling unit or any workspace package, a unit or not: an import reads the
108
+ * folder whatever the release config says of it. Their dirs belong to its
109
+ * inputs. Derived, never hand kept, and over declaring is safe where under
110
+ * declaring is a stale green */
111
+ export function siblingUnits(units: TestUnitDecl[], read: (rel: string) => string | null, workspaces: readonly { name: string; dir: string }[] = []): Map<string, string[]> {
112
+ const manifests = new Map<string, Pkg | null>()
113
+ const manifest = (rel: string): Pkg | null => {
114
+ if (!manifests.has(rel)) manifests.set(rel, parsePkg(read(posix.join(rel, 'package.json'))))
115
+ return manifests.get(rel)!
116
+ }
117
+ const byName = new Map<string, string>(workspaces.map((w) => [w.name, normSuitePath(w.dir).replace(/\/+$/, '')]))
118
+ for (const u of units) { const n = manifest(u.rel)?.name; if (n != null) byName.set(n, u.rel) }
119
+ const dirs = [...new Set([...units.map((u) => u.rel), ...byName.values()])]
120
+ const named = (rel: string): string[] => {
121
+ const p = manifest(rel)
122
+ return [p?.dependencies, p?.devDependencies, p?.peerDependencies, p?.optionalDependencies].flatMap((b) => Object.keys(b ?? {})).flatMap((n) => byName.get(n) ?? [])
123
+ }
112
124
  const out = new Map<string, string[]>()
113
125
  for (const u of units) {
114
- const p = pkgs.get(u.id)
115
- const names = new Set([p?.dependencies, p?.devDependencies, p?.peerDependencies, p?.optionalDependencies].flatMap((b) => Object.keys(b ?? {})))
116
126
  const tsconfig = unitTsconfig(u)
117
127
  const targets = pathTargets(read(tsconfig)).map((t) => posix.normalize(posix.join(posix.dirname(tsconfig), t)))
118
- out.set(u.id, units.filter((s) => s.id !== u.id && ([...names].some((n) => byName.get(n) === s) || targets.some((t) => under(t, s.rel)))).map((s) => s.rel))
128
+ const own = (d: string): boolean => under(d, u.rel)
129
+ // the unit's own dir is in its inputs already, and what it names is followed all the same
130
+ const seen = new Set<string>()
131
+ const queue = [...named(u.rel), ...dirs.filter((d) => targets.some((t) => under(t, d)))]
132
+ for (let d = queue.shift(); d != null; d = queue.shift()) {
133
+ if (seen.has(d)) continue
134
+ seen.add(d)
135
+ queue.push(...named(d))
136
+ }
137
+ out.set(u.id, [...seen].filter((d) => !own(d)).sort())
119
138
  }
120
139
  return out
121
140
  }
@@ -561,7 +561,8 @@ export function nextMixLevel(master: number | null, passes: readonly MixPass[]):
561
561
  const trim = over > 0 ? +(level.trim - over - 0.1).toFixed(2) : level.trim
562
562
  const left = +(gap - (trim - level.trim)).toFixed(2)
563
563
  if (master === null || Math.abs(left) <= MASTER_TOLERANCE) return { gain: level.gain, trim }
564
- const before = passes.findLast((p) => p.level.gain !== level.gain)
564
+ // no findLast: a consumer's own typecheck reads this source, under whatever lib its tsconfig names
565
+ const before = [...passes].reverse().find((p) => p.level.gain !== level.gain)
565
566
  const moved = before ? (m.lufs - level.trim - (before.m.lufs - before.level.trim)) / (level.gain - before.level.gain) : 1
566
567
  const slope = Math.min(1, Math.max(MIN_SLOPE, moved))
567
568
  return { gain: +(level.gain + left / slope).toFixed(2), trim }
package/src/ts/config.ts CHANGED
@@ -17,6 +17,7 @@ import { join } from 'path'
17
17
  import { gitRoot } from '../core/git-root.ts'
18
18
  import { isVendored } from '../core/vendored.ts'
19
19
  import { readVendored } from '../core/vendored-read.ts'
20
+ import { workspacePackagesOf } from './workspaces.ts'
20
21
 
21
22
  export type RvtPackage = {
22
23
  name: string // package.json "name" — the import root for files inside
@@ -120,45 +121,21 @@ function discoverPackages(root: string, roots: string[], skip: string[], vendore
120
121
  // the package.json `workspaces` (an array, or `{ packages }`), each a dir or a glob of dirs, with each one's `exports`:
121
122
  // a workspace outside the roots is still imported by its name, and the test selection's graph follows that edge
122
123
  export function workspacePackages(root: string, vendored: readonly string[] = []): (RvtPackage & { exports?: unknown })[] {
123
- let globs: string[] = []
124
- try {
125
- const w = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { workspaces?: string[] | { packages?: string[] } }).workspaces
126
- globs = Array.isArray(w) ? w : w?.packages ?? []
127
- } catch {
128
- return []
129
- }
130
- const dirs = (pattern: string): string[] => {
131
- let at = ['']
132
- for (const seg of pattern.replace(/\/+$/, '').split('/')) {
133
- if (!seg.includes('*')) {
134
- at = at.map((d) => (d === '' ? seg : `${d}/${seg}`))
135
- continue
136
- }
137
- const re = new RegExp(`^${seg.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`)
138
- at = at.flatMap((d) => {
139
- try {
140
- return readdirSync(join(root, d), { withFileTypes: true }).filter((e) => e.isDirectory() && re.test(e.name)).map((e) => (d === '' ? e.name : `${d}/${e.name}`))
141
- } catch {
142
- return []
143
- }
144
- })
124
+ const read = (rel: string): string | null => {
125
+ try {
126
+ return readFileSync(join(root, rel), 'utf8')
127
+ } catch {
128
+ return null
145
129
  }
146
- return at
147
130
  }
148
- const out: (RvtPackage & { exports?: unknown })[] = []
149
- for (const g of globs) {
150
- if (g.startsWith('!')) continue
151
- for (const dir of dirs(g)) {
152
- if (isVendored(dir, vendored)) continue
153
- try {
154
- const m = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8')) as { name?: string; exports?: unknown }
155
- if (m.name != null && m.name !== '') out.push({ name: m.name, dir, ...(m.exports !== undefined ? { exports: m.exports } : {}) })
156
- } catch {
157
- // no named manifest: not a package
158
- }
131
+ const subdirs = (rel: string): string[] => {
132
+ try {
133
+ return readdirSync(join(root, rel), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name)
134
+ } catch {
135
+ return []
159
136
  }
160
137
  }
161
- return out
138
+ return workspacePackagesOf(read, subdirs, vendored)
162
139
  }
163
140
 
164
141
  export function loadConfig(cwd: string = process.cwd()): RvtConfig {