basalt-ui 2.17.0 → 2.19.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 (120) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/MIGRATING.md +108 -12
  3. package/agent/agents/basalt-design-reviewer.md +2 -2
  4. package/agent/skills/basalt-design/SKILL.md +1 -1
  5. package/dist/cli/help.d.ts +1 -0
  6. package/dist/cli/help.d.ts.map +1 -1
  7. package/dist/cli/help.js +8 -2
  8. package/dist/cli/shot/capture.d.ts +12 -1
  9. package/dist/cli/shot/capture.d.ts.map +1 -1
  10. package/dist/cli/shot/capture.js +72 -10
  11. package/dist/cli/shot/index.d.ts +10 -1
  12. package/dist/cli/shot/index.d.ts.map +1 -1
  13. package/dist/cli/shot/index.js +40 -5
  14. package/dist/cli/shot/real-data.d.ts +35 -0
  15. package/dist/cli/shot/real-data.d.ts.map +1 -0
  16. package/dist/cli/shot/real-data.js +120 -0
  17. package/dist/cli/shot/serve.d.ts +2 -2
  18. package/dist/cli/shot/serve.d.ts.map +1 -1
  19. package/dist/cli/shot/serve.js +16 -2
  20. package/dist/commands/notifications/center.d.ts.map +1 -1
  21. package/dist/commands/notifications/center.js +18 -26
  22. package/dist/content/callout.d.ts +1 -1
  23. package/dist/content/callout.d.ts.map +1 -1
  24. package/dist/content/callout.js +10 -1
  25. package/dist/content/callout.module.css +15 -3
  26. package/dist/content/callout.module.css.d.ts +1 -0
  27. package/dist/dashboard/bar-list.d.ts +29 -0
  28. package/dist/dashboard/bar-list.d.ts.map +1 -0
  29. package/dist/dashboard/bar-list.js +65 -0
  30. package/dist/dashboard/bar-list.module.css +91 -0
  31. package/dist/dashboard/bar-list.module.css.d.ts +17 -0
  32. package/dist/dashboard/index.d.ts +2 -0
  33. package/dist/dashboard/index.d.ts.map +1 -1
  34. package/dist/dashboard/index.js +4 -0
  35. package/dist/dashboard/meter-model.d.ts +126 -0
  36. package/dist/dashboard/meter-model.d.ts.map +1 -0
  37. package/dist/dashboard/meter-model.js +135 -0
  38. package/dist/dashboard/meter-parts.d.ts +42 -0
  39. package/dist/dashboard/meter-parts.d.ts.map +1 -0
  40. package/dist/dashboard/meter-parts.js +297 -0
  41. package/dist/dashboard/meter.d.ts +123 -0
  42. package/dist/dashboard/meter.d.ts.map +1 -0
  43. package/dist/dashboard/meter.js +43 -0
  44. package/dist/dashboard/meter.module.css +268 -0
  45. package/dist/dashboard/meter.module.css.d.ts +39 -0
  46. package/dist/dashboard/scale.d.ts +9 -0
  47. package/dist/dashboard/scale.d.ts.map +1 -0
  48. package/dist/dashboard/scale.js +10 -0
  49. package/dist/dashboard/stat-card-parts.d.ts +3 -1
  50. package/dist/dashboard/stat-card-parts.d.ts.map +1 -1
  51. package/dist/dashboard/stat-card-parts.js +18 -3
  52. package/dist/dashboard/stat-card.d.ts +6 -5
  53. package/dist/dashboard/stat-card.d.ts.map +1 -1
  54. package/dist/dashboard/stat-card.js +48 -77
  55. package/dist/dashboard/stat-card.module.css +27 -7
  56. package/dist/dashboard/widget-header.d.ts.map +1 -1
  57. package/dist/dashboard/widget-header.js +2 -1
  58. package/dist/dashboard/widget-header.module.css +28 -1
  59. package/dist/index.d.ts +1 -1
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +5 -1
  62. package/dist/theme/chrome-vars.d.ts +29 -17
  63. package/dist/theme/chrome-vars.d.ts.map +1 -1
  64. package/dist/theme/chrome-vars.js +18 -8
  65. package/dist/theme/index.d.ts.map +1 -1
  66. package/dist/theme/index.js +9 -5
  67. package/dist/theme/status-dot.d.ts +6 -0
  68. package/dist/theme/status-dot.d.ts.map +1 -0
  69. package/dist/theme/status-dot.js +9 -0
  70. package/dist/theme/status-dot.module.css +9 -0
  71. package/dist/theme/status-dot.module.css.d.ts +8 -0
  72. package/dist/theme/status-verdict.d.ts +9 -0
  73. package/dist/theme/status-verdict.d.ts.map +1 -0
  74. package/dist/theme/status-verdict.js +13 -0
  75. package/dist/theme/status-verdict.module.css +23 -0
  76. package/dist/theme/status-verdict.module.css.d.ts +9 -0
  77. package/dist/tokens/derive.d.ts +11 -1
  78. package/dist/tokens/derive.d.ts.map +1 -1
  79. package/dist/tokens/derive.js +9 -24
  80. package/dist/tokens/status-text.d.ts +26 -0
  81. package/dist/tokens/status-text.d.ts.map +1 -0
  82. package/dist/tokens/status-text.js +68 -0
  83. package/llms.txt +32 -3
  84. package/package.json +1 -1
  85. package/src/cli/help.ts +22 -2
  86. package/src/cli/shot/capture.ts +98 -9
  87. package/src/cli/shot/index.ts +50 -4
  88. package/src/cli/shot/real-data.ts +165 -0
  89. package/src/cli/shot/serve.ts +28 -3
  90. package/src/commands/notifications/center.tsx +29 -32
  91. package/src/content/callout.module.css +15 -3
  92. package/src/content/callout.module.css.d.ts +1 -0
  93. package/src/content/callout.tsx +15 -2
  94. package/src/dashboard/bar-list.module.css +91 -0
  95. package/src/dashboard/bar-list.module.css.d.ts +17 -0
  96. package/src/dashboard/bar-list.tsx +125 -0
  97. package/src/dashboard/index.ts +2 -0
  98. package/src/dashboard/meter-model.ts +254 -0
  99. package/src/dashboard/meter-parts.tsx +407 -0
  100. package/src/dashboard/meter.module.css +268 -0
  101. package/src/dashboard/meter.module.css.d.ts +39 -0
  102. package/src/dashboard/meter.tsx +173 -0
  103. package/src/dashboard/scale.ts +13 -0
  104. package/src/dashboard/stat-card-parts.tsx +22 -2
  105. package/src/dashboard/stat-card.module.css +27 -7
  106. package/src/dashboard/stat-card.tsx +18 -52
  107. package/src/dashboard/widget-header.module.css +28 -1
  108. package/src/dashboard/widget-header.tsx +4 -1
  109. package/src/index.ts +4 -0
  110. package/src/theme/__snapshots__/plain-theme.test.ts.snap +88 -16
  111. package/src/theme/chrome-vars.ts +48 -23
  112. package/src/theme/index.ts +10 -6
  113. package/src/theme/status-dot.module.css +9 -0
  114. package/src/theme/status-dot.module.css.d.ts +8 -0
  115. package/src/theme/status-dot.tsx +19 -0
  116. package/src/theme/status-verdict.module.css +23 -0
  117. package/src/theme/status-verdict.module.css.d.ts +9 -0
  118. package/src/theme/status-verdict.tsx +27 -0
  119. package/src/tokens/derive.ts +19 -31
  120. package/src/tokens/status-text.ts +85 -0
package/llms.txt CHANGED
@@ -1,4 +1,4 @@
1
- # basalt-ui v2.17.0
1
+ # basalt-ui v2.19.0
2
2
  # Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets
3
3
  #
4
4
  # Entry points: use the exact import specifier below; do not guess.
@@ -13,13 +13,24 @@
13
13
  # A subpath's `Install:` line is its required peers; `OptionalPeers:` are import()-only, install on use.
14
14
 
15
15
  Package: basalt-ui
16
- Version: 2.17.0
16
+ Version: 2.19.0
17
17
 
18
18
  ## basalt-ui
19
19
  Import: import { ... } from 'basalt-ui'
20
20
  Description: Wiring (`BasaltProvider`, `createBasaltTheme`, `createBasaltRouter`, `unwrap`), shell + nav (`BasaltShell`, `PageBar`, `PageAside`, `PageTitle`, `ThemeToggle`, `defineNav`/`navGroup`/`navTarget`/`flattenNav`, `useBasaltNav`, `useSizeClass`, `useCoarsePointer`), dashboard (`Section`, `WidgetHeader`, `StatCard`, `StatGroup`, `DeltaBadge`, `EmptyState`, `SettingsSection`/`SettingsRow`/`DangerZone`). Reaches no subpath-required peer.
21
21
  Layer: mantine-coupled
22
22
  Rule: basalt-mantine
23
+ Signature: BarList(props: BarListProps): JSX.Element
24
+ className?: string
25
+ style?: CSSProperties
26
+ label: string
27
+ items: readonly BarListItem[]
28
+ format?: (value: number) => string
29
+ max?: number
30
+ accentLeader?: boolean
31
+ loading?: boolean
32
+ loadingRows?: number
33
+ emptyText?: string
23
34
  Signature: BasaltProvider(props: BasaltProviderProps): JSX.Element
24
35
  one of: router | children
25
36
  theme?: PartialObjectDeep<MantineTheme, { recurseIntoArrays: false;…
@@ -80,6 +91,24 @@ Signature: EmptyState(props: EmptyStateProps): JSX.Element
80
91
  description?: string
81
92
  action?: ReactNode
82
93
  tier?: "section" | "page"
94
+ Signature: Meter(props: MeterProps): JSX.Element
95
+ className?: string
96
+ style?: CSSProperties
97
+ label: string
98
+ min?: number
99
+ max?: number
100
+ format?: (value: number) => string
101
+ loading?: boolean
102
+ emptyText?: string
103
+ shape?: "bar" | "ring"
104
+ target?: number [with segments | zones]
105
+ startCaption?: ReactNode [with segments | zones]
106
+ endCaption?: ReactNode [with segments | zones]
107
+ value?: number | null [with zones]
108
+ color?: string
109
+ segments: readonly MeterSegment[]
110
+ zones: readonly MeterZone[]
111
+ forecastCaption?: string [with segments]
83
112
  Signature: PageAside(props: PageAsideProps): ReactNode
84
113
  className?: string
85
114
  style?: CSSProperties
@@ -426,7 +455,7 @@ Signature: Sparkline(props: SparklineProps): ReactElement<unknown, string | JSXE
426
455
  data: readonly number[]
427
456
  height: number
428
457
  width?: number
429
- mark?: "line" | "bar"
458
+ mark?: "bar" | "line"
430
459
  color?: string
431
460
  emphasizeLast?: boolean
432
461
  emphasisColor?: string
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basalt-ui",
3
- "version": "2.17.0",
3
+ "version": "2.19.0",
4
4
  "description": "Opinionated framework for Mantine-based React apps — theme, app shell, TanStack Charts, toolchain presets",
5
5
  "keywords": [
6
6
  "charts",
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')
@@ -398,8 +469,7 @@ async function captureUrlState(c: Ctx, state: ShotState): Promise<void> {
398
469
  }
399
470
  let here: PageFacts
400
471
  try {
401
- await load(c.page, c.input.base + withParam(c.route, state))
402
- here = await readFacts(c.page)
472
+ here = await visit(c, c.input.base + withParam(c.route, state))
403
473
  } catch (error) {
404
474
  for (const name of restNames)
405
475
  record(c, { name, state, status: 'error', note: `load failed: ${firstLine(error)}` })
@@ -501,7 +571,7 @@ export function groupScale({ mantine, vx }: ScaleRead): Steps {
501
571
  }
502
572
 
503
573
  async function capturePage(
504
- args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured'> & { wantScale: boolean },
574
+ args: Omit<Ctx, 'facts' | 'anchors' | 'shots' | 'measured' | 'problems'> & { wantScale: boolean },
505
575
  ) {
506
576
  const { wantScale, ...rest } = args
507
577
  const c: Ctx = {
@@ -510,11 +580,12 @@ async function capturePage(
510
580
  anchors: [],
511
581
  shots: [],
512
582
  measured: new Set(),
583
+ problems: [],
513
584
  }
514
585
  const { input, route } = c
586
+ input.apiProblems?.() // calls still in flight from an earlier route are not this page's
515
587
  try {
516
- await load(c.page, input.base + route)
517
- c.facts = await readFacts(c.page)
588
+ c.facts = await visit(c, input.base + route)
518
589
  } catch (error) {
519
590
  record(c, {
520
591
  name: PAGE_ANCHOR,
@@ -544,12 +615,20 @@ async function capturePage(
544
615
  snap(c.page, path, { fullPage: true }).then(() => undefined),
545
616
  )
546
617
  }
618
+ flagProblems(c)
547
619
  for (const name of usable) {
548
620
  for (const [state, capture] of Object.entries(POINTER_STATES)) {
549
- 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)
550
624
  }
551
625
  }
552
- 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)
553
632
  return c
554
633
  }
555
634
 
@@ -558,6 +637,8 @@ export async function openContext<C extends PwContext>(
558
637
  browser: PwBrowser<C>,
559
638
  scheme: Scheme,
560
639
  viewport: Viewport,
640
+ seeded: readonly Pair[] = [],
641
+ origin = '',
561
642
  ): Promise<C> {
562
643
  const spec = VIEWPORT_SPECS[viewport]
563
644
  const context = await browser.newContext({
@@ -569,6 +650,7 @@ export async function openContext<C extends PwContext>(
569
650
  reducedMotion: 'reduce',
570
651
  })
571
652
  await context.addInitScript(`localStorage.setItem('mantine-color-scheme-value', '${scheme}')`)
653
+ if (seeded.length > 0) await context.addInitScript(seedScript(seeded, origin))
572
654
  return context
573
655
  }
574
656
 
@@ -644,7 +726,14 @@ export async function capture(input: CaptureInput): Promise<{
644
726
  }
645
727
  for (const scheme of SCHEMES) {
646
728
  for (const viewport of VIEWPORTS) {
647
- 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
+ )
648
737
  try {
649
738
  const page = await context.newPage()
650
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
  },
@@ -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' } })