basalt-ui 2.16.0 → 2.18.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 (146) hide show
  1. package/CHANGELOG.md +165 -124
  2. package/MIGRATING.md +133 -15
  3. package/agent/agents/basalt-design-reviewer.md +2 -2
  4. package/agent/skills/basalt-design/SKILL.md +3 -3
  5. package/configs/oxlint-plugin.js +2 -2
  6. package/dist/charts/Donut.d.ts.map +1 -1
  7. package/dist/charts/Donut.js +2 -2
  8. package/dist/charts/DualPanel.js +2 -2
  9. package/dist/charts/Heatmap.d.ts.map +1 -1
  10. package/dist/charts/Heatmap.js +2 -2
  11. package/dist/charts/MirroredBars.js +2 -2
  12. package/dist/charts/Sparkline.d.ts +4 -2
  13. package/dist/charts/Sparkline.d.ts.map +1 -1
  14. package/dist/charts/Sparkline.js +3 -3
  15. package/dist/charts/compile.d.ts +8 -3
  16. package/dist/charts/compile.d.ts.map +1 -1
  17. package/dist/charts/compile.js +19 -9
  18. package/dist/charts/cursor.d.ts +14 -1
  19. package/dist/charts/cursor.d.ts.map +1 -1
  20. package/dist/charts/cursor.js +29 -3
  21. package/dist/charts/date-tick-format.d.ts +17 -0
  22. package/dist/charts/date-tick-format.d.ts.map +1 -0
  23. package/dist/charts/date-tick-format.js +81 -0
  24. package/dist/charts/panel.d.ts +2 -1
  25. package/dist/charts/panel.d.ts.map +1 -1
  26. package/dist/charts/panel.js +3 -2
  27. package/dist/charts/types.d.ts +5 -1
  28. package/dist/charts/types.d.ts.map +1 -1
  29. package/dist/cli/help.d.ts +1 -0
  30. package/dist/cli/help.d.ts.map +1 -1
  31. package/dist/cli/help.js +8 -2
  32. package/dist/cli/shot/capture.d.ts +28 -1
  33. package/dist/cli/shot/capture.d.ts.map +1 -1
  34. package/dist/cli/shot/capture.js +96 -13
  35. package/dist/cli/shot/index.d.ts +10 -1
  36. package/dist/cli/shot/index.d.ts.map +1 -1
  37. package/dist/cli/shot/index.js +40 -5
  38. package/dist/cli/shot/playwright.d.ts +4 -0
  39. package/dist/cli/shot/playwright.d.ts.map +1 -1
  40. package/dist/cli/shot/real-data.d.ts +35 -0
  41. package/dist/cli/shot/real-data.d.ts.map +1 -0
  42. package/dist/cli/shot/real-data.js +120 -0
  43. package/dist/cli/shot/serve.d.ts +2 -2
  44. package/dist/cli/shot/serve.d.ts.map +1 -1
  45. package/dist/cli/shot/serve.js +16 -2
  46. package/dist/dashboard/bar-list.d.ts +29 -0
  47. package/dist/dashboard/bar-list.d.ts.map +1 -0
  48. package/dist/dashboard/bar-list.js +52 -0
  49. package/dist/dashboard/bar-list.module.css +73 -0
  50. package/dist/dashboard/bar-list.module.css.d.ts +16 -0
  51. package/dist/dashboard/delta-badge.d.ts +2 -2
  52. package/dist/dashboard/delta-badge.d.ts.map +1 -1
  53. package/dist/dashboard/delta-badge.js +12 -14
  54. package/dist/dashboard/index.d.ts +2 -0
  55. package/dist/dashboard/index.d.ts.map +1 -1
  56. package/dist/dashboard/index.js +4 -0
  57. package/dist/dashboard/meter-model.d.ts +78 -0
  58. package/dist/dashboard/meter-model.d.ts.map +1 -0
  59. package/dist/dashboard/meter-model.js +91 -0
  60. package/dist/dashboard/meter-parts.d.ts +42 -0
  61. package/dist/dashboard/meter-parts.d.ts.map +1 -0
  62. package/dist/dashboard/meter-parts.js +163 -0
  63. package/dist/dashboard/meter.d.ts +112 -0
  64. package/dist/dashboard/meter.d.ts.map +1 -0
  65. package/dist/dashboard/meter.js +43 -0
  66. package/dist/dashboard/meter.module.css +150 -0
  67. package/dist/dashboard/meter.module.css.d.ts +28 -0
  68. package/dist/dashboard/query-state.d.ts +35 -0
  69. package/dist/dashboard/query-state.d.ts.map +1 -1
  70. package/dist/dashboard/query-state.js +12 -1
  71. package/dist/dashboard/scale.d.ts +9 -0
  72. package/dist/dashboard/scale.d.ts.map +1 -0
  73. package/dist/dashboard/scale.js +10 -0
  74. package/dist/dashboard/stat-card-parts.d.ts +40 -0
  75. package/dist/dashboard/stat-card-parts.d.ts.map +1 -0
  76. package/dist/dashboard/stat-card-parts.js +55 -0
  77. package/dist/dashboard/stat-card.d.ts +46 -34
  78. package/dist/dashboard/stat-card.d.ts.map +1 -1
  79. package/dist/dashboard/stat-card.js +148 -79
  80. package/dist/dashboard/stat-card.module.css +220 -7
  81. package/dist/dashboard/stat-card.module.css.d.ts +20 -0
  82. package/dist/dashboard/widget-header.d.ts.map +1 -1
  83. package/dist/dashboard/widget-header.js +73 -9
  84. package/dist/dashboard/widget-header.module.css +25 -17
  85. package/dist/guard/index.js +2 -2
  86. package/dist/index.d.ts +1 -1
  87. package/dist/index.d.ts.map +1 -1
  88. package/dist/index.js +5 -1
  89. package/dist/theme/chrome-vars.d.ts +82 -0
  90. package/dist/theme/chrome-vars.d.ts.map +1 -0
  91. package/dist/theme/chrome-vars.js +36 -0
  92. package/dist/theme/controls.module.css +20 -1
  93. package/dist/theme/controls.module.css.d.ts +1 -0
  94. package/dist/theme/index.d.ts.map +1 -1
  95. package/dist/theme/index.js +30 -33
  96. package/dist/tokens/derive.d.ts +11 -1
  97. package/dist/tokens/derive.d.ts.map +1 -1
  98. package/dist/tokens/derive.js +9 -24
  99. package/dist/tokens/status-text.d.ts +26 -0
  100. package/dist/tokens/status-text.d.ts.map +1 -0
  101. package/dist/tokens/status-text.js +68 -0
  102. package/llms.txt +36 -4
  103. package/package.json +1 -1
  104. package/src/charts/Donut.tsx +2 -2
  105. package/src/charts/DualPanel.tsx +2 -2
  106. package/src/charts/Heatmap.tsx +2 -2
  107. package/src/charts/MirroredBars.tsx +2 -2
  108. package/src/charts/Sparkline.tsx +7 -5
  109. package/src/charts/compile.ts +31 -11
  110. package/src/charts/cursor.ts +48 -3
  111. package/src/charts/date-tick-format.ts +132 -0
  112. package/src/charts/panel.tsx +5 -3
  113. package/src/charts/types.ts +5 -1
  114. package/src/cli/help.ts +22 -2
  115. package/src/cli/shot/capture.ts +133 -12
  116. package/src/cli/shot/index.ts +50 -4
  117. package/src/cli/shot/playwright.ts +1 -1
  118. package/src/cli/shot/real-data.ts +165 -0
  119. package/src/cli/shot/serve.ts +28 -3
  120. package/src/dashboard/bar-list.module.css +73 -0
  121. package/src/dashboard/bar-list.module.css.d.ts +16 -0
  122. package/src/dashboard/bar-list.tsx +112 -0
  123. package/src/dashboard/delta-badge.tsx +24 -18
  124. package/src/dashboard/index.ts +2 -0
  125. package/src/dashboard/meter-model.ts +161 -0
  126. package/src/dashboard/meter-parts.tsx +223 -0
  127. package/src/dashboard/meter.module.css +150 -0
  128. package/src/dashboard/meter.module.css.d.ts +28 -0
  129. package/src/dashboard/meter.tsx +162 -0
  130. package/src/dashboard/query-state.tsx +38 -0
  131. package/src/dashboard/scale.ts +13 -0
  132. package/src/dashboard/stat-card-parts.tsx +108 -0
  133. package/src/dashboard/stat-card.module.css +220 -7
  134. package/src/dashboard/stat-card.module.css.d.ts +20 -0
  135. package/src/dashboard/stat-card.tsx +282 -174
  136. package/src/dashboard/widget-header.module.css +25 -17
  137. package/src/dashboard/widget-header.tsx +103 -7
  138. package/src/guard/index.ts +2 -2
  139. package/src/index.ts +4 -0
  140. package/src/theme/__snapshots__/plain-theme.test.ts.snap +128 -40
  141. package/src/theme/chrome-vars.ts +111 -0
  142. package/src/theme/controls.module.css +20 -1
  143. package/src/theme/controls.module.css.d.ts +1 -0
  144. package/src/theme/index.ts +39 -101
  145. package/src/tokens/derive.ts +19 -26
  146. package/src/tokens/status-text.ts +85 -0
package/src/cli/help.ts CHANGED
@@ -12,7 +12,10 @@
12
12
  */
13
13
  import { parseArgs } from 'node:util'
14
14
 
15
- export const COMMAND_OPTIONS: Record<string, Record<string, { type: 'string' | 'boolean' }>> = {
15
+ export const COMMAND_OPTIONS: Record<
16
+ string,
17
+ Record<string, { type: 'string' | 'boolean'; multiple?: boolean }>
18
+ > = {
16
19
  init: {
17
20
  'no-merge-lint': { type: 'boolean' },
18
21
  },
@@ -48,6 +51,12 @@ export const COMMAND_OPTIONS: Record<string, Record<string, { type: 'string' | '
48
51
  dist: { type: 'string' },
49
52
  out: { type: 'string' },
50
53
  states: { type: 'string' },
54
+ 'local-storage': { type: 'string', multiple: true },
55
+ api: { type: 'string', multiple: true },
56
+ header: { type: 'string', multiple: true },
57
+ wait: { type: 'string' },
58
+ 'auto-anchors': { type: 'boolean' },
59
+ 'api-allow-writes': { type: 'boolean' },
51
60
  },
52
61
  }
53
62
 
@@ -92,7 +101,18 @@ export const USAGE =
92
101
  ' Render routes in Chromium (Playwright from YOUR project: bun add -d playwright) and write\n' +
93
102
  ' board.html, metrics.json and png/* — every data-shot anchor × light/dark × desktop/mobile ×\n' +
94
103
  ' rest, hover, focus, tooltip, empty, loading, error. --dist serves a built SPA dir itself.\n' +
95
- ' Default --out .basalt/shots (emptied each run); .basalt/shots/last.json names the last out dir.\n\n' +
104
+ ' Default --out .basalt/shots (emptied each run); .basalt/shots/last.json names the last out dir.\n' +
105
+ ' A real, signed-in app: [--local-storage <key>=<@env:NAME|@file:path>]… seeds localStorage (app origin\n' +
106
+ ' only) before any page script; [--api <prefix>=<origin>]… (with --dist) proxies GET/HEAD under that\n' +
107
+ ' prefix to the origin (other methods get 405 unless --api-allow-writes); [--header <name>=@env:NAME]… is\n' +
108
+ ' added to every proxied request, to EVERY --api origin (never on a navigation; https required);\n' +
109
+ ' [--wait <ms|networkidle>] adds ms of settle AFTER networkidle (default none); [--auto-anchors] crops\n' +
110
+ ' each Card, Paper and table over 120×60 px on a page with no data-shot. Values are never printed or\n' +
111
+ ' written; a redirect, 401/403/404, 5xx or dead API fails every shot of that page. Shots of real data go to the\n' +
112
+ ' reviewer subagent and so to its model provider: point --api at staging or synthetic data when the\n' +
113
+ " app holds other people's data. Example:\n" +
114
+ ' basalt-ui shot /overview --dist dist --api /api=https://app.example.com \\\n' +
115
+ ' --local-storage auth-token=@env:APP_TOKEN --header authorization=@env:APP_BEARER --auto-anchors\n\n' +
96
116
  'doctor [--tokens-only|--framework]\n' +
97
117
  ' Checks THIS project only: the manifest exists, the oxlint preset is wired, the pre-commit\n' +
98
118
  ' hook runs check-theme (via `lefthook dump`), and the ai package major is consistent within\n' +
@@ -4,6 +4,8 @@ import { readFileSync } from 'node:fs'
4
4
  import { basename, join } from 'node:path'
5
5
 
6
6
  import { buildSheet } from './board'
7
+ import { SEED_FLAG, seedScript } from './real-data'
8
+ import type { Pair } from './real-data'
7
9
 
8
10
  import { finishMeasurement, measureAnchor } from './measure'
9
11
  import type { Box, PwBrowser, PwContext, PwLocator, PwPage, ShotOptions } from './playwright'
@@ -33,6 +35,14 @@ export type CaptureInput = {
33
35
  routes: readonly string[]
34
36
  states: readonly ShotState[]
35
37
  pngDir: string
38
+ /** Seeded before any page script runs (values may be secrets: never logged or written). */
39
+ localStorage?: readonly Pair[]
40
+ /** Extra settle in ms after `networkidle`; omitted: none. */
41
+ wait?: number
42
+ /** Drains the proxied calls that failed since the last read (401/403, no answer). */
43
+ apiProblems?: () => string[]
44
+ /** On a page with no `data-shot`, tag each large Card, Paper and table as an anchor. */
45
+ autoAnchors?: boolean
36
46
  /** Replaces the in-page measurer (tests). */
37
47
  measure?: (anchor: PwLocator) => Promise<Measurement>
38
48
  log: (line: string) => void
@@ -51,6 +61,8 @@ type Ctx = {
51
61
  anchors: AnchorMetrics[]
52
62
  shots: ShotRecord[]
53
63
  measured: Set<string>
64
+ /** What the last visit showed to be wrong about the data itself: a failed seed, a 401/403, no API answer. */
65
+ problems: string[]
54
66
  /** Read on the first page of a context that loads. */
55
67
  scale?: Steps | undefined
56
68
  scaleError?: string | undefined
@@ -124,9 +136,20 @@ function record(c: Ctx, { name, state, status, file, note }: Outcome): void {
124
136
  c.input.log(`[shot] ${route} ${name} ${scheme}/${viewport}/${state}: ${note}`)
125
137
  }
126
138
 
127
- async function load(page: PwPage, url: string): Promise<void> {
139
+ async function load(page: PwPage, url: string, settle = 0): Promise<void> {
128
140
  await page.goto(url, { waitUntil: 'networkidle' })
129
141
  await page.evaluate('document.fonts.ready.then(() => undefined)')
142
+ if (settle > 0) await new Promise((done) => setTimeout(done, settle))
143
+ }
144
+
145
+ /** Runs in the page: numbers every Card, Paper and table in DOM order, tagging those over 120×60 px as anchors. */
146
+ export function tagAutoAnchors(): void {
147
+ const found = document.querySelectorAll('.mantine-Card-root, .mantine-Paper-root, table')
148
+ Array.from(found).forEach((el, i) => {
149
+ const { width, height } = el.getBoundingClientRect()
150
+ if (width > 120 && height > 60)
151
+ el.setAttribute('data-shot', `auto-${String(i + 1).padStart(2, '0')}`)
152
+ })
130
153
  }
131
154
 
132
155
  const readFacts = (page: PwPage): Promise<PageFacts> =>
@@ -135,6 +158,54 @@ const readFacts = (page: PwPage): Promise<PageFacts> =>
135
158
  declared: [...document.querySelectorAll('[data-shot-states]')].flatMap((e) => (e.getAttribute('data-shot-states') ?? '').split(/\\s+/)).filter(Boolean),
136
159
  }))()`)
137
160
 
161
+ const addProblem = (c: Ctx, problem: string): void => {
162
+ if (!c.problems.includes(problem)) c.problems.push(problem)
163
+ }
164
+
165
+ /** Moves the proxied calls that failed since the last read into this page visit's problems. */
166
+ const collect = (c: Ctx): void => {
167
+ for (const problem of c.input.apiProblems?.() ?? []) addProblem(c, problem)
168
+ }
169
+
170
+ /**
171
+ * One load of `url`: settle, auto-anchor a page that declares none, read its facts, and collect
172
+ * what is wrong with the data (`c.problems`) so a board never looks fine over a failed login.
173
+ */
174
+ async function visit(c: Ctx, url: string): Promise<PageFacts> {
175
+ const { input, page } = c
176
+ await load(page, url, input.wait)
177
+ let facts = await readFacts(page)
178
+ if (input.autoAnchors && facts.anchors.length === 0) {
179
+ await page.evaluate(tagAutoAnchors, undefined)
180
+ facts = await readFacts(page)
181
+ }
182
+ collect(c)
183
+ if (input.localStorage?.length) {
184
+ const failed = await page.evaluate<unknown>(`globalThis.${SEED_FLAG} ?? ''`)
185
+ if (failed === 'origin') {
186
+ input.log(`[shot] ${c.route}: page left the app origin; not seeded`)
187
+ } else if (typeof failed === 'string' && failed !== '') {
188
+ addProblem(c, `localStorage seed failed (${failed})`)
189
+ input.log(`[shot] ${c.route}: localStorage seed failed (${failed})`)
190
+ }
191
+ }
192
+ return facts
193
+ }
194
+
195
+ /**
196
+ * When this page visit's data is untrustworthy, every shot of it (page and anchors, every state)
197
+ * becomes an error carrying the problem; a page shot is added when `rest` was not requested.
198
+ */
199
+ function flagProblems(c: Ctx): void {
200
+ if (c.problems.length === 0) return
201
+ const note = c.problems.join('; ')
202
+ for (const shot of c.shots)
203
+ if (shot.status === 'ok') Object.assign(shot, { status: 'error', note })
204
+ if (!c.shots.some((s) => s.name === PAGE_ANCHOR && s.state === 'rest'))
205
+ record(c, { name: PAGE_ANCHOR, state: 'rest', status: 'error', note })
206
+ c.input.log(`[shot] ${c.route} ${c.scheme}/${c.viewport}: ${note}`)
207
+ }
208
+
138
209
  /** Brings the anchor into view; throws when it is absent, hidden or off-screen at this viewport. */
139
210
  async function reveal(anchor: PwLocator): Promise<void> {
140
211
  if ((await anchor.count()) === 0) throw new Error('anchor not found')
@@ -225,6 +296,38 @@ export const tooltipSelector = (describedBy: string): string =>
225
296
  ? `[role="tooltip"][id=${JSON.stringify(describedBy)}]`
226
297
  : '[role="tooltip"]:not([data-shot-seen])'
227
298
 
299
+ /** `tooltipSelector`, narrowed to a rendered readout: a hidden 0×0 one of another chart never wins `.first()`. */
300
+ export const visibleTooltip = (describedBy: string): string =>
301
+ `${tooltipSelector(describedBy)}:visible`
302
+
303
+ /**
304
+ * Where a trigger is hovered: its centre, or the `data-shot-at="x,y"` fractions of its box when the
305
+ * centre paints no readout (a donut's hole).
306
+ */
307
+ export function hoverAtOf(el: Element | null): string {
308
+ return el?.getAttribute('data-shot-at') ?? ''
309
+ }
310
+
311
+ const HOVER_AT = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\s*$/
312
+
313
+ /**
314
+ * Exactly two non-negative numbers, each in [0, 1): 1 is the box's far edge, outside it. Anything else (a missing half, a third
315
+ * field, a value outside the box, a sign) is null, so the trigger is hovered at its centre.
316
+ */
317
+ export function parseHoverAt(raw: string): { x: number; y: number } | null {
318
+ const m = HOVER_AT.exec(raw)
319
+ if (!m) return null
320
+ const [x, y] = [Number(m[1]), Number(m[2])]
321
+ return x < 1 && y < 1 ? { x, y } : null
322
+ }
323
+
324
+ export async function hoverTrigger(target: PwLocator): Promise<void> {
325
+ const at = parseHoverAt(String(await target.evaluate(hoverAtOf)))
326
+ const box = at ? await target.boundingBox() : null
327
+ const position = at && box ? { x: at.x * box.width, y: at.y * box.height } : undefined
328
+ await target.hover({ timeout: HOVER_TIMEOUT_MS, ...(position && { position }) })
329
+ }
330
+
228
331
  /**
229
332
  * The box of the tooltip an action opened, or null when none shows up. Call `markVisibleTooltips`
230
333
  * before the action; `describedBy` is the trigger's own tooltip id, when it has one.
@@ -234,7 +337,7 @@ async function openTooltipBox(
234
337
  describedBy: string,
235
338
  timeout = TIP_PROBE_MS,
236
339
  ): Promise<Box | null> {
237
- const tip = c.page.locator(tooltipSelector(describedBy)).first()
340
+ const tip = c.page.locator(visibleTooltip(describedBy)).first()
238
341
  try {
239
342
  await tip.waitFor({ state: 'visible', timeout })
240
343
  } catch {
@@ -262,7 +365,7 @@ async function captureHover(c: Ctx, name: string): Promise<void> {
262
365
  const inner = c.page.locator(`${sel(name)} [data-shot-hover]`).first()
263
366
  const target = (await inner.count()) > 0 ? inner : anchor
264
367
  await c.page.evaluate(markVisibleTooltips, undefined)
265
- await target.hover({ timeout: HOVER_TIMEOUT_MS })
368
+ await hoverTrigger(target)
266
369
  const describedBy = idOf(await target.evaluate(describedByOf))
267
370
  const [box, tip] = [await anchor.boundingBox(), await openTooltipBox(c, describedBy)]
268
371
  if (!box || !tip) return void (await snap(anchor, path))
@@ -337,7 +440,7 @@ async function captureTooltip(c: Ctx, name: string): Promise<void> {
337
440
  const anchor = anchorOf(c, name)
338
441
  await reveal(anchor)
339
442
  await c.page.evaluate(markVisibleTooltips, undefined)
340
- await trigger.hover({ timeout: HOVER_TIMEOUT_MS })
443
+ await hoverTrigger(trigger)
341
444
  const describedBy = idOf(await trigger.evaluate(describedByOf))
342
445
  const t = await openTooltipBox(c, describedBy, TOOLTIP_TIMEOUT_MS)
343
446
  if (!t) throw new Error('no visible [role="tooltip"] after hover')
@@ -366,8 +469,7 @@ async function captureUrlState(c: Ctx, state: ShotState): Promise<void> {
366
469
  }
367
470
  let here: PageFacts
368
471
  try {
369
- await load(c.page, c.input.base + withParam(c.route, state))
370
- here = await readFacts(c.page)
472
+ here = await visit(c, c.input.base + withParam(c.route, state))
371
473
  } catch (error) {
372
474
  for (const name of restNames)
373
475
  record(c, { name, state, status: 'error', note: `load failed: ${firstLine(error)}` })
@@ -469,7 +571,7 @@ export function groupScale({ mantine, vx }: ScaleRead): Steps {
469
571
  }
470
572
 
471
573
  async function capturePage(
472
- args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured'> & { wantScale: boolean },
574
+ args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured' | 'problems'> & { wantScale: boolean },
473
575
  ) {
474
576
  const { wantScale, ...rest } = args
475
577
  const c: Ctx = {
@@ -478,11 +580,12 @@ async function capturePage(
478
580
  anchors: [],
479
581
  shots: [],
480
582
  measured: new Set(),
583
+ problems: [],
481
584
  }
482
585
  const { input, route } = c
586
+ input.apiProblems?.() // calls still in flight from an earlier route are not this page's
483
587
  try {
484
- await load(c.page, input.base + route)
485
- c.facts = await readFacts(c.page)
588
+ c.facts = await visit(c, input.base + route)
486
589
  } catch (error) {
487
590
  record(c, {
488
591
  name: PAGE_ANCHOR,
@@ -512,12 +615,20 @@ async function capturePage(
512
615
  snap(c.page, path, { fullPage: true }).then(() => undefined),
513
616
  )
514
617
  }
618
+ flagProblems(c)
515
619
  for (const name of usable) {
516
620
  for (const [state, capture] of Object.entries(POINTER_STATES)) {
517
- if (input.states.includes(state as ShotState)) await capture(c, name)
621
+ if (!input.states.includes(state as ShotState)) continue
622
+ await capture(c, name)
623
+ collect(c)
518
624
  }
519
625
  }
520
- for (const state of URL_STATES) if (input.states.includes(state)) await captureUrlState(c, state)
626
+ for (const state of URL_STATES) {
627
+ if (!input.states.includes(state)) continue
628
+ await captureUrlState(c, state)
629
+ collect(c)
630
+ }
631
+ flagProblems(c)
521
632
  return c
522
633
  }
523
634
 
@@ -526,6 +637,8 @@ export async function openContext<C extends PwContext>(
526
637
  browser: PwBrowser<C>,
527
638
  scheme: Scheme,
528
639
  viewport: Viewport,
640
+ seeded: readonly Pair[] = [],
641
+ origin = '',
529
642
  ): Promise<C> {
530
643
  const spec = VIEWPORT_SPECS[viewport]
531
644
  const context = await browser.newContext({
@@ -537,6 +650,7 @@ export async function openContext<C extends PwContext>(
537
650
  reducedMotion: 'reduce',
538
651
  })
539
652
  await context.addInitScript(`localStorage.setItem('mantine-color-scheme-value', '${scheme}')`)
653
+ if (seeded.length > 0) await context.addInitScript(seedScript(seeded, origin))
540
654
  return context
541
655
  }
542
656
 
@@ -612,7 +726,14 @@ export async function capture(input: CaptureInput): Promise<{
612
726
  }
613
727
  for (const scheme of SCHEMES) {
614
728
  for (const viewport of VIEWPORTS) {
615
- const context = await openContext(input.browser, scheme, viewport)
729
+ input.apiProblems?.() // a new context starts with a clean queue
730
+ const context = await openContext(
731
+ input.browser,
732
+ scheme,
733
+ viewport,
734
+ input.localStorage,
735
+ new URL(input.base).origin,
736
+ )
616
737
  try {
617
738
  const page = await context.newPage()
618
739
  page.setDefaultTimeout(NAV_TIMEOUT_MS)
@@ -21,6 +21,8 @@ import { buildBoard } from './board'
21
21
  import { capture } from './capture'
22
22
  import { INSTALL_LINE, ShotError, resolvePlaywright, withBrowser } from './playwright'
23
23
  import type { Playwright, PlaywrightResolver } from './playwright'
24
+ import { apiProxy, parseApi, parseHeaders, parseStorage } from './real-data'
25
+ import type { ApiRoute, Pair, Source } from './real-data'
24
26
  import { serveDist } from './serve'
25
27
  import { SCHEMES, STATES, VIEWPORTS } from './types'
26
28
  import type { ShotMetrics, ShotState } from './types'
@@ -29,7 +31,7 @@ const HOME = '.basalt/shots'
29
31
  /** A run dir under the home, so `last.json` and a named run's dir never share the default out. */
30
32
  const DEFAULT_OUT = `${HOME}/latest`
31
33
  const USAGE_LINE =
32
- 'usage: basalt-ui shot <route…> (--base <url> | --dist <dir>) [--out <dir>] [--states <list>]'
34
+ 'usage: basalt-ui shot <route…> (--base <url> | --dist <dir>) [--out <dir>] [--states <list>] [--local-storage k=@env:X] [--api /p=origin] [--header n=@env:X] [--api-allow-writes] [--wait ms] [--auto-anchors]'
33
35
 
34
36
  export type ShotDeps = {
35
37
  resolve?: PlaywrightResolver
@@ -45,10 +47,21 @@ export type ShotArgs = {
45
47
  dist?: string
46
48
  out: string
47
49
  states: ShotState[]
50
+ /** Resolved secrets: held for the browser only, never written anywhere. */
51
+ localStorage: Pair[]
52
+ api: ApiRoute[]
53
+ headers: Pair[]
54
+ /** Extra settle in ms after networkidle. */
55
+ wait: number
56
+ allowWrites: boolean
57
+ autoAnchors: boolean
48
58
  }
49
59
 
50
60
  /** Parses argv; throws `ShotError` with the one-line reason. */
51
- export function parseShotArgs(flags: readonly string[]): ShotArgs {
61
+ export function parseShotArgs(
62
+ flags: readonly string[],
63
+ src: Source = { env: process.env, cwd: process.cwd() },
64
+ ): ShotArgs {
52
65
  let parsed
53
66
  try {
54
67
  parsed = parseArgs({
@@ -59,6 +72,12 @@ export function parseShotArgs(flags: readonly string[]): ShotArgs {
59
72
  dist: { type: 'string' },
60
73
  out: { type: 'string' },
61
74
  states: { type: 'string' },
75
+ 'local-storage': { type: 'string', multiple: true },
76
+ api: { type: 'string', multiple: true },
77
+ header: { type: 'string', multiple: true },
78
+ wait: { type: 'string' },
79
+ 'auto-anchors': { type: 'boolean' },
80
+ 'api-allow-writes': { type: 'boolean' },
62
81
  },
63
82
  })
64
83
  } catch (error) {
@@ -80,8 +99,27 @@ export function parseShotArgs(flags: readonly string[]): ShotArgs {
80
99
  : [...STATES]
81
100
  const unknown = states.find((s) => !(STATES as readonly string[]).includes(s))
82
101
  if (unknown) throw new ShotError(`unknown state '${unknown}'. Known: ${STATES.join(', ')}`)
102
+ const secrets = (values.header?.length ?? 0) + (values['local-storage']?.length ?? 0) > 0
103
+ const api = parseApi(values.api ?? [], secrets)
104
+ if (api.length > 0 && !values.dist)
105
+ throw new ShotError(`--api needs --dist (it proxies the static server).\n${USAGE_LINE}`)
106
+ if ((values.header?.length ?? 0) > 0 && new Set(api.map((r) => r.origin)).size > 1)
107
+ throw new ShotError(
108
+ `--header goes to every --api origin; it is refused when --api names more than one.\n${USAGE_LINE}`,
109
+ )
110
+ if ((values.header?.length ?? 0) > 0 && api.length === 0)
111
+ throw new ShotError(`--header is sent on --api requests only; pass --api.\n${USAGE_LINE}`)
112
+ const wait = values.wait ?? 'networkidle'
113
+ if (wait !== 'networkidle' && !/^\d+$/.test(wait))
114
+ throw new ShotError(`--wait takes milliseconds or 'networkidle'.\n${USAGE_LINE}`)
83
115
  return {
84
116
  routes: positionals,
117
+ localStorage: parseStorage(values['local-storage'] ?? [], src),
118
+ api,
119
+ headers: parseHeaders(values.header ?? [], src),
120
+ wait: wait === 'networkidle' ? 0 : Number(wait),
121
+ allowWrites: values['api-allow-writes'] ?? false,
122
+ autoAnchors: values['auto-anchors'] ?? false,
85
123
  ...(values.base ? { base: values.base.replace(/\/+$/, '') } : {}),
86
124
  ...(values.dist ? { dist: values.dist } : {}),
87
125
  out: values.out ?? DEFAULT_OUT,
@@ -284,14 +322,18 @@ export async function shot(
284
322
  const stops: (() => unknown)[] = []
285
323
  const uninstall = exitOnSignal(stops)
286
324
  try {
287
- const args = parseShotArgs(flags)
325
+ const args = parseShotArgs(flags, { env: process.env, cwd })
288
326
  const outDir = planOut(cwd, args.out)
289
327
  recoverOut(outDir)
290
328
  const pw: Playwright | null = (deps.resolve ?? resolvePlaywright)(cwd)
291
329
  if (!pw) throw new ShotError(INSTALL_LINE)
292
330
  const now = (deps.now ?? (() => new Date()))()
293
331
  sweepStaleTmp(join(cwd, HOME), now)
294
- const server = args.dist ? serveDist(resolve(cwd, args.dist)) : null
332
+ const proxy =
333
+ args.api.length > 0
334
+ ? apiProxy(args.api, args.headers, { log, allowWrites: args.allowWrites })
335
+ : null
336
+ const server = args.dist ? serveDist(resolve(cwd, args.dist), proxy?.handle) : null
295
337
  if (server) stops.push(server.stop)
296
338
  let tmp = ''
297
339
  stops.push(() => tmp && rmSync(tmp, { recursive: true, force: true }))
@@ -313,6 +355,10 @@ export async function shot(
313
355
  routes: args.routes,
314
356
  states: args.states,
315
357
  pngDir: join(tmp, 'png'),
358
+ localStorage: args.localStorage,
359
+ wait: args.wait,
360
+ autoAnchors: args.autoAnchors,
361
+ ...(proxy && { apiProblems: proxy.drain }),
316
362
  log,
317
363
  })
318
364
  },
@@ -26,7 +26,7 @@ export type ShotOptions = {
26
26
  export type PwLocator = {
27
27
  first(): PwLocator
28
28
  count(): Promise<number>
29
- hover(options?: { timeout?: number }): Promise<void>
29
+ hover(options?: { timeout?: number; position?: { x: number; y: number } }): Promise<void>
30
30
  isVisible(): Promise<boolean>
31
31
  boundingBox(): Promise<Box | null>
32
32
  scrollIntoViewIfNeeded(): Promise<void>
@@ -0,0 +1,165 @@
1
+ /** Flags that point `shot` at a real, authenticated app: seeded localStorage and a proxied API. */
2
+ import { readFileSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+
5
+ import { ShotError } from './playwright'
6
+
7
+ export type ApiRoute = { prefix: string; origin: string }
8
+ export type Pair = readonly [name: string, value: string]
9
+ export type Source = { env: Readonly<Record<string, string | undefined>>; cwd: string }
10
+
11
+ /** `<name>=<value>` split at the first `=`; errors name the flag, never the text (it may hold a secret). */
12
+ function splitPair(flag: string, raw: string): Pair {
13
+ const at = raw.indexOf('=')
14
+ if (at <= 0) throw new ShotError(`--${flag} expects <name>=<value>`)
15
+ return [raw.slice(0, at), raw.slice(at + 1)]
16
+ }
17
+
18
+ /** `@env:NAME` or `@file:path`: a secret never sits in argv, so there is no literal form. */
19
+ function resolveValue(flag: string, raw: string, src: Source): string {
20
+ const [, kind, ref = ''] = /^@(env|file):(.*)$/s.exec(raw) ?? []
21
+ let value: string | undefined
22
+ if (kind === 'env') value = Object.hasOwn(src.env, ref) ? src.env[ref] : undefined
23
+ else if (kind === 'file') {
24
+ try {
25
+ value = readFileSync(resolve(src.cwd, ref), 'utf8').trim()
26
+ } catch {
27
+ throw new ShotError(`--${flag}: cannot read @file:${ref}`)
28
+ }
29
+ } else throw new ShotError(`--${flag} takes @env:NAME or @file:path, never a literal`)
30
+ if (!value) throw new ShotError(`--${flag}: ${raw} is empty`)
31
+ return value
32
+ }
33
+
34
+ export const parseStorage = (list: readonly string[], src: Source): Pair[] =>
35
+ list.map((raw) => {
36
+ const [key, value] = splitPair('local-storage', raw)
37
+ return [key, resolveValue('local-storage', value, src)]
38
+ })
39
+
40
+ const NOT_FORWARDED = new Set(['host', 'origin', 'referer', 'connection', 'content-length'])
41
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~\w-]+$/
42
+ const HEADER_VALUE = /^[\t\x20-\x7e]*$/
43
+
44
+ /** `--header` pairs: a valid, forwardable name and a value that cannot split the request. */
45
+ export const parseHeaders = (list: readonly string[], src: Source): Pair[] =>
46
+ list.map((raw) => {
47
+ const [name, value] = splitPair('header', raw)
48
+ if (!HEADER_NAME.test(name) || NOT_FORWARDED.has(name.toLowerCase()))
49
+ throw new ShotError(`--header ${name}: not a header shot can send`)
50
+ const resolved = resolveValue('header', value, src)
51
+ if (!HEADER_VALUE.test(resolved))
52
+ throw new ShotError(`--header ${name}: value has characters a header cannot carry`)
53
+ return [name, resolved]
54
+ })
55
+
56
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]'])
57
+
58
+ /** `--api <prefix>=<origin>`; with any secret configured (`--header`, `--local-storage`), a remote origin must be https. */
59
+ export function parseApi(list: readonly string[], secrets: boolean): ApiRoute[] {
60
+ return list.map((raw) => {
61
+ const [given, target] = splitPair('api', raw)
62
+ const prefix = given.replace(/\/+$/, '')
63
+ if (!prefix.startsWith('/'))
64
+ throw new ShotError('--api prefix must start with "/" and name a path, not "/"')
65
+ let url: URL
66
+ try {
67
+ url = new URL(target ?? '')
68
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new Error('protocol')
69
+ } catch {
70
+ throw new ShotError('--api <prefix>=<origin>: origin must be an http(s) URL')
71
+ }
72
+ if (secrets && url.protocol !== 'https:' && !LOOPBACK.has(url.hostname))
73
+ throw new ShotError(
74
+ `--api ${prefix}: with a secret configured (--header, --local-storage) the origin must be https (loopback excepted)`,
75
+ )
76
+ return { prefix, origin: url.origin }
77
+ })
78
+ }
79
+
80
+ const NOT_RETURNED = ['content-encoding', 'content-length', 'transfer-encoding']
81
+ const READ_ONLY = new Set(['GET', 'HEAD'])
82
+ /** A status that means the page shows something other than the app's data: a redirect, a missing resource, a failure, a refusal. */
83
+ const UNTRUSTED = (status: number): boolean =>
84
+ status >= 500 ||
85
+ (status >= 300 && status < 400) ||
86
+ status === 401 ||
87
+ status === 403 ||
88
+ status === 404
89
+ const TIMEOUT_MS = 20_000
90
+
91
+ export type ApiProxy = {
92
+ handle: (req: Request) => Promise<Response | null>
93
+ /** The calls since the last drain that make a board untrustworthy: a 3xx, 401, 403, 404, 5xx or no answer. */
94
+ drain: () => string[]
95
+ }
96
+
97
+ /**
98
+ * The static server's API hook: a GET/HEAD under a prefix goes to `<origin><path>?<query>` with the
99
+ * `--header` values added, except on a navigation; any other method is a 405 unless `allowWrites`.
100
+ * Anything else is null (served from `--dist`). Every non-2xx or failed call is logged by method,
101
+ * path and status or error class, never a header or a query.
102
+ */
103
+ export function apiProxy(
104
+ api: readonly ApiRoute[],
105
+ headers: readonly Pair[],
106
+ opts: { log: (line: string) => void; allowWrites?: boolean; timeoutMs?: number },
107
+ ): ApiProxy {
108
+ let problems: string[] = []
109
+ const handle = async (req: Request): Promise<Response | null> => {
110
+ const url = new URL(req.url)
111
+ const route = api.find(
112
+ (r) => url.pathname === r.prefix || url.pathname.startsWith(r.prefix + '/'),
113
+ )
114
+ if (!route) return null
115
+ // Method, prefix and depth only: path segments can hold identifiers, so they never reach a log.
116
+ const depth = url.pathname.slice(route.prefix.length).split('/').filter(Boolean).length
117
+ const label = `${req.method} ${route.prefix} +${depth}`
118
+ if (!opts.allowWrites && !READ_ONLY.has(req.method)) {
119
+ opts.log(`[shot] api ${label} blocked: read-only run (--api-allow-writes lifts it)`)
120
+ return new Response('read-only', { status: 405 })
121
+ }
122
+ const out = new Headers()
123
+ for (const [name, value] of req.headers) if (!NOT_FORWARDED.has(name)) out.set(name, value)
124
+ const navigating =
125
+ req.headers.get('sec-fetch-mode') === 'navigate' ||
126
+ req.headers.get('sec-fetch-dest') === 'document'
127
+ if (!navigating) for (const [name, value] of headers) out.set(name, value)
128
+ try {
129
+ const res = await fetch(route.origin + url.pathname + url.search, {
130
+ method: req.method,
131
+ headers: out,
132
+ redirect: 'manual',
133
+ signal: AbortSignal.timeout(opts.timeoutMs ?? TIMEOUT_MS),
134
+ ...(READ_ONLY.has(req.method) ? {} : { body: await req.arrayBuffer() }),
135
+ })
136
+ if (!res.ok) opts.log(`[shot] api ${label} → ${res.status}`)
137
+ if (UNTRUSTED(res.status)) problems.push(`${label} ${res.status}`)
138
+ const back = new Headers(res.headers)
139
+ for (const name of NOT_RETURNED) back.delete(name)
140
+ return new Response(res.body, { status: res.status, headers: back })
141
+ } catch (error) {
142
+ const kind = error instanceof Error ? error.name : 'Error'
143
+ opts.log(`[shot] api ${label} failed: ${kind}`)
144
+ problems.push(`${label} ${kind}`)
145
+ return new Response('proxy error', { status: 502 })
146
+ }
147
+ }
148
+ return {
149
+ handle,
150
+ drain: () => {
151
+ const seen = problems
152
+ problems = []
153
+ return seen
154
+ },
155
+ }
156
+ }
157
+
158
+ /** The page global the seed script reports through: `origin`, or the keys it could not set. */
159
+ export const SEED_FLAG = '__shotSeedFailed'
160
+
161
+ /** The init script that seeds localStorage, only on `origin` and only for an absent key (a token the app rotates survives), before any page script runs. */
162
+ export const seedScript = (entries: readonly Pair[], origin: string): string =>
163
+ `(()=>{if(location.origin!==${JSON.stringify(origin)}){globalThis.${SEED_FLAG}='origin';return}` +
164
+ `const f=[];for(const [k,v] of ${JSON.stringify(entries)}){try{if(localStorage.getItem(k)===null)localStorage.setItem(k,v)}catch{f.push(k)}}` +
165
+ `if(f.length)globalThis.${SEED_FLAG}=f.join(',')})()`
@@ -3,8 +3,28 @@ import { join, normalize, resolve, sep } from 'node:path'
3
3
 
4
4
  import { ShotError } from './playwright'
5
5
 
6
- /** Static server for a built SPA dir: real files as-is, extensionless misses fall back to index.html. */
7
- export function serveDist(distDir: string): { origin: string; stop: () => void } {
6
+ const FETCH_MODES = new Set(['cors', 'same-origin', 'navigate'])
7
+
8
+ /**
9
+ * With a proxy live only the shot's own page may reach this port: its Host, no foreign Origin, no
10
+ * cross-site request, and no cross-origin no-Origin request (a `no-cors` image or form from another
11
+ * local page). A same-origin `no-cors` load (the app's own stylesheet) is fine.
12
+ */
13
+ function fromOwnBrowser(req: Request, own: string): boolean {
14
+ const origin = req.headers.get('origin')
15
+ const mode = req.headers.get('sec-fetch-mode')
16
+ const site = req.headers.get('sec-fetch-site')
17
+ if (req.headers.get('host') !== own) return false
18
+ if (origin !== null) return origin === `http://${own}`
19
+ if (site === 'cross-site') return false
20
+ return mode === null || FETCH_MODES.has(mode) || site === 'same-origin'
21
+ }
22
+
23
+ /** Static server for a built SPA dir: real files as-is, extensionless misses fall back to index.html; `proxy` answers first. */
24
+ export function serveDist(
25
+ distDir: string,
26
+ proxy?: (req: Request) => Promise<Response | null>,
27
+ ): { origin: string; stop: () => void } {
8
28
  const root = resolve(distDir)
9
29
  if (!existsSync(root) || !statSync(root).isDirectory()) {
10
30
  throw new ShotError(`--dist ${distDir} is not a directory`)
@@ -20,8 +40,13 @@ export function serveDist(distDir: string): { origin: string; stop: () => void }
20
40
  const server = Bun.serve({
21
41
  port: 0,
22
42
  hostname: '127.0.0.1',
23
- fetch(req) {
43
+ async fetch(req) {
24
44
  try {
45
+ // With a proxy live, only the shot's own browser may talk to this port (no DNS rebinding, no other page).
46
+ const own = `127.0.0.1:${server.port}`
47
+ if (proxy && !fromOwnBrowser(req, own)) return new Response('forbidden', { status: 403 })
48
+ const proxied = await proxy?.(req)
49
+ if (proxied) return proxied
25
50
  const file = fileFor(new URL(req.url).pathname)
26
51
  return file
27
52
  ? new Response(Bun.file(file), { headers: { 'cache-control': 'no-store' } })