basalt-ui 2.7.3 → 2.8.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 (40) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/MIGRATING.md +97 -15
  3. package/agent/rules/basalt-batteries.md +1 -1
  4. package/agent/rules/basalt-controls.md +1 -1
  5. package/agent/rules/basalt-mantine.md +1 -1
  6. package/agent/skills/basalt-app/SKILL.md +7 -7
  7. package/agent/templates/AGENTS-block.md.tpl +1 -1
  8. package/dist/charts/BandStrip.d.ts +13 -0
  9. package/dist/charts/BandStrip.d.ts.map +1 -1
  10. package/dist/charts/BandStrip.js +142 -44
  11. package/dist/cli/doctor-upgrade.d.ts +11 -0
  12. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  13. package/dist/cli/doctor-upgrade.js +122 -10
  14. package/dist/cli/doctor.d.ts.map +1 -1
  15. package/dist/cli/doctor.js +4 -0
  16. package/dist/cli/help.js +1 -1
  17. package/dist/cli/index.d.ts +5 -0
  18. package/dist/cli/index.d.ts.map +1 -1
  19. package/dist/cli/index.js +12 -0
  20. package/dist/cli/init.d.ts.map +1 -1
  21. package/dist/cli/init.js +7 -4
  22. package/dist/cli/sync.d.ts.map +1 -1
  23. package/dist/cli/sync.js +27 -2
  24. package/dist/provider/index.d.ts +22 -4
  25. package/dist/provider/index.d.ts.map +1 -1
  26. package/dist/provider/index.js +21 -6
  27. package/dist/provider/test-router.d.ts +2 -1
  28. package/dist/provider/test-router.d.ts.map +1 -1
  29. package/dist/provider/test-router.js +6 -7
  30. package/llms.txt +35 -3
  31. package/package.json +1 -1
  32. package/src/charts/BandStrip.tsx +223 -48
  33. package/src/cli/doctor-upgrade.ts +171 -15
  34. package/src/cli/doctor.ts +4 -0
  35. package/src/cli/help.ts +1 -1
  36. package/src/cli/index.ts +16 -0
  37. package/src/cli/init.ts +7 -6
  38. package/src/cli/sync.ts +29 -2
  39. package/src/provider/index.tsx +65 -15
  40. package/src/provider/test-router.tsx +9 -9
@@ -8,7 +8,14 @@ import { dirname, relative, resolve } from 'node:path'
8
8
 
9
9
  import { BASALT_CONFIG_KEYS, RETIRED_CONFIG_KEYS } from './config'
10
10
  import type { BasaltConfig } from './config'
11
- import { parseJsonc, readIfExists, readPackageJson, scannableFiles } from './index'
11
+ import {
12
+ isStartApp,
13
+ parseJsonc,
14
+ readIfExists,
15
+ readPackageJson,
16
+ routerSeedDest,
17
+ scannableFiles,
18
+ } from './index'
12
19
  import type { BasaltInstall } from './index'
13
20
 
14
21
  export type Check = { fail: string } | { skip: string } | null
@@ -225,15 +232,46 @@ function basaltImports(src: string): [string, number][] {
225
232
  .map((m) => [m[2] as string, code.slice(0, m.index + m[0].length).split('\n').length])
226
233
  }
227
234
 
228
- /** `[subpath, file, line]` per `basalt-ui/<subpath>` import in the app's source files. */
235
+ /** `@import 'basalt-ui/x'`, `@import "basalt-ui/x"`, `@import url(basalt-ui/x)` in a stylesheet (at-rule position only). */
236
+ const CSS_SUBPATH_IMPORT = /(?:^|[;{}])\s*@import\s+(?:url\(\s*)?(['"]?)basalt-ui\/([^'")\s;]+)\1/g
237
+
238
+ /** `[subpath, line]` per `basalt-ui/<subpath>` `@import` in a stylesheet (comments blanked). */
239
+ function cssImports(src: string): [string, number][] {
240
+ const blank = (m: string): string => m.replace(/[^\n]/g, ' ')
241
+ const code = src
242
+ .replace(/\/\*[\s\S]*?\*\//g, blank)
243
+ // A quoted string that is not an @import/url() target is a value: `content: "a; @import …"`.
244
+ .replace(/(@import\s+|url\(\s*)?(["'])(?:\\.|(?!\2)[^\\\n])*\2/g, (m, target) =>
245
+ target === undefined ? blank(m) : m,
246
+ )
247
+ return [...code.matchAll(CSS_SUBPATH_IMPORT)].map((m) => [
248
+ m[2] as string,
249
+ code.slice(0, m.index + m[0].length).split('\n').length,
250
+ ])
251
+ }
252
+
253
+ /** `[subpath, file, line]` per `basalt-ui/<subpath>` import in the app's source and style files. */
229
254
  const appImports = (cwd: string, cfg: BasaltConfig): [string, string, number][] =>
230
- scannableFiles(cwd, cfg)
231
- .filter((f) => /\.(?:[cm]?[jt]sx?|vue|astro)$/.test(f))
232
- .flatMap((rel) =>
233
- basaltImports(readIfExists(resolve(cwd, rel)) ?? '').map(
234
- ([sub, line]): [string, string, number] => [sub, rel, line],
235
- ),
255
+ scannableFiles(cwd, cfg).flatMap((rel) => {
256
+ const isCode = /\.(?:[cm]?[jt]sx?|vue|astro)$/.test(rel)
257
+ if (!isCode && !rel.endsWith('.css')) return []
258
+ const src = readIfExists(resolve(cwd, rel)) ?? ''
259
+ return (isCode ? basaltImports(src) : cssImports(src)).map(
260
+ ([sub, line]): [string, string, number] => [sub, rel, line],
236
261
  )
262
+ })
263
+
264
+ /** Subpaths 2.x removed, checked besides the install's `exports`: a walked-up 1.x install exports them. */
265
+ const DROPPED_FIXES = new Map([
266
+ [
267
+ 'tokens.css',
268
+ 'commit the emit instead: `basalt-ui tokens:css --out src/tokens.css` and import that file',
269
+ ],
270
+ [
271
+ 'router-tanstack',
272
+ 'nav symbols (`defineNav`, `navTarget`, …) now import from `basalt-ui`, stores (`createSearchStore`, `field`, …) from `basalt-ui/state`',
273
+ ],
274
+ ])
237
275
 
238
276
  /** `dropped-subpaths`: `basalt-ui/<subpath>` imports the installed `exports` map does not have. */
239
277
  export function droppedSubpathsCheck(
@@ -249,17 +287,51 @@ export function droppedSubpathsCheck(
249
287
  // No `exports` field means nothing restricts the deep imports.
250
288
  if (exportsMap === undefined) return null
251
289
  const keys = Object.keys(exportsMap)
252
- const has = (sub: string): boolean =>
290
+ const hasExport = (sub: string): boolean =>
253
291
  keys.some(
254
292
  (k) => k === `./${sub}` || (k.endsWith('*') && `./${sub}`.startsWith(k.slice(0, -1))),
255
293
  )
256
- const hits = appImports(cwd, cfg)
257
- .filter(([sub]) => !has(sub))
258
- .map(([sub, rel, line]) => `${rel}:${line} imports basalt-ui/${sub}`)
259
- if (hits.length === 0) return null
294
+ const isDropped = (sub: string): boolean => DROPPED_FIXES.has(sub) || !hasExport(sub)
295
+ const found = appImports(cwd, cfg).filter(([sub]) => isDropped(sub))
296
+ if (found.length === 0) return null
297
+ const hits = found.map(([sub, rel, line]) => `${rel}:${line} imports basalt-ui/${sub}`)
260
298
  const more = hits.length > 10 ? ` (+${hits.length - 10} more)` : ''
299
+ const fixes = [...new Set(found.map(([sub]) => sub))].flatMap((sub) => {
300
+ const fix = DROPPED_FIXES.get(sub)
301
+ return fix === undefined ? [] : [`basalt-ui/${sub}: ${fix}`]
302
+ })
303
+ fixes.push("see MIGRATING.md § 2.0 for each subpath's replacement")
304
+ return { fail: `${id}: ${hits.slice(0, 10).join('; ')}${more}. Fix: ${fixes.join('; ')}.` }
305
+ })
306
+ }
307
+
308
+ /** The oldest oxlint that parses the shipped preset (1.78 lacks `react/globals` and friends). */
309
+ const OXLINT_FLOOR = '1.79.0'
310
+
311
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(-[^+]+)?(?:\+.*)?$/
312
+
313
+ /** True when `version` is below `floor`; a prerelease of the floor is below it, build metadata is ignored. */
314
+ function isBelowFloor(version: string, floor: string): boolean {
315
+ const [v, f] = [SEMVER.exec(version), SEMVER.exec(floor)]
316
+ if (v === null || f === null) return false
317
+ for (const i of [1, 2, 3]) {
318
+ if (Number(v[i]) !== Number(f[i])) return Number(v[i]) < Number(f[i])
319
+ }
320
+ return v[4] !== undefined
321
+ }
322
+
323
+ /**
324
+ * `oxlint-floor`: fails when the nearest installed oxlint is older than {@link OXLINT_FLOOR}, which
325
+ * cannot parse the preset. Reads `cwd`, as `oxlint-preset` does; a missing oxlint is that check's job.
326
+ */
327
+ export function oxlintFloorCheck(cwd: string): Check {
328
+ const id = 'oxlint-floor'
329
+ return guarded(id, () => {
330
+ if (readIfExists(resolve(cwd, '.oxlintrc.json')) === null) return null
331
+ const version = installedVersion(cwd, 'oxlint')
332
+ if (version === null || !isBelowFloor(version, OXLINT_FLOOR)) return null
261
333
  return {
262
- fail: `${id}: ${hits.slice(0, 10).join('; ')}${more}. Fix: see MIGRATING.md § 2.0 for each subpath's replacement.`,
334
+ fail: `${id}: oxlint ${version} is installed, but the shipped preset needs >= ${OXLINT_FLOOR} (older versions reject its react/* rules). Fix: \`bun add -D oxlint@^${OXLINT_FLOOR}\`.`,
263
335
  }
264
336
  })
265
337
  }
@@ -408,6 +480,89 @@ function routerCreatedInImports(cwd: string, entry: string): boolean {
408
480
  return false
409
481
  }
410
482
 
483
+ /** True when `{` at `i` opens a `{...spread}`: sticky, so any whitespace width is read. */
484
+ function isSpreadAt(code: string, i: number): boolean {
485
+ const spread = /\{\s*\.\.\./y
486
+ spread.lastIndex = i
487
+ return spread.test(code)
488
+ }
489
+
490
+ type ProviderTag = { attrs: string; spread: boolean }
491
+
492
+ /**
493
+ * Every `<BasaltProvider …>` opening tag in a root route: its attribute text at JSX brace depth 0,
494
+ * with string literals skipped (so `className="a > b"` cannot end the tag, nor `"router="` count),
495
+ * and whether a `{...spread}` could carry a `router`.
496
+ */
497
+ function providerTags(src: string): ProviderTag[] {
498
+ const { code, inLiteral } = tokenize(src)
499
+ return [...code.matchAll(/<BasaltProvider\b/g)]
500
+ .filter((m) => !inLiteral(m.index))
501
+ .map((m) => {
502
+ const tag: ProviderTag = { attrs: '', spread: false }
503
+ let depth = 0
504
+ for (let i = m.index + m[0].length; i < code.length; i++) {
505
+ const ch = code[i]!
506
+ if (inLiteral(i)) continue
507
+ if (ch === '{') {
508
+ if (depth++ === 0 && isSpreadAt(code, i)) tag.spread = true
509
+ } else if (ch === '}') depth--
510
+ else if (ch === '>' && depth === 0) break
511
+ else if (depth === 0) tag.attrs += ch
512
+ }
513
+ return tag
514
+ })
515
+ }
516
+
517
+ const carriesRouter = (tag: ProviderTag): boolean => /(^|\s)router\s*=/.test(tag.attrs)
518
+
519
+ /**
520
+ * A Start app owns its router and entry: the wiring is an embedded `<BasaltProvider>` (no `router=`)
521
+ * in its root route component, around `<Outlet />`. ANY tag with `router=` mounts a second router
522
+ * inside Start's, so it fails even beside an embedded one.
523
+ */
524
+ function startWiring(cwd: string): { fail: string } | null {
525
+ const root = routerSeedDest('', 'root')
526
+ const text = readIfExists(resolve(cwd, root))
527
+ const tags = providerTags(text ?? '')
528
+ const mounting = tags.some(carriesRouter)
529
+ if (!mounting && tags.length > 0) return null
530
+ const problem =
531
+ text === null
532
+ ? 'does not exist'
533
+ : mounting
534
+ ? 'passes router= to BasaltProvider, which mounts a second router inside Start'
535
+ : 'does not render <BasaltProvider>'
536
+ return {
537
+ fail: `app-wiring: ${root} ${problem} (TanStack Start app). Fix: render <BasaltProvider><Outlet /></BasaltProvider> in the root route component.`,
538
+ }
539
+ }
540
+
541
+ /**
542
+ * Warnings for a Start app's embedded provider; heuristics, not proofs. A `{...spread}` on the tag
543
+ * could carry a `router`; `src/router.tsx` never mentioning `queryClient` means the embedded
544
+ * provider will find no `context.queryClient`. Empty when there is nothing to judge.
545
+ */
546
+ export function startWiringWarnings(cwd: string): string[] {
547
+ if (!isStartApp(cwd, '')) return []
548
+ const out: string[] = []
549
+ const root = readIfExists(resolve(cwd, routerSeedDest('', 'root')))
550
+ if (root !== null && providerTags(root).some((t) => t.spread)) {
551
+ out.push(
552
+ 'app-wiring: <BasaltProvider {...spread}> in the root route could pass router=, which mounts ' +
553
+ 'a second router inside Start (heuristic: the spread is not followed).',
554
+ )
555
+ }
556
+ const router = readIfExists(resolve(cwd, 'src/router.tsx'))
557
+ if (router !== null && !/queryClient/.test(router)) {
558
+ out.push(
559
+ 'app-wiring: src/router.tsx never mentions queryClient — embedded BasaltProvider needs ' +
560
+ 'context.queryClient on the Start router (heuristic text check; ignore if you build it elsewhere).',
561
+ )
562
+ }
563
+ return out
564
+ }
565
+
411
566
  /**
412
567
  * `app-wiring`: the entry module `index.html` loads (default src/main.tsx) mounts `BasaltProvider`
413
568
  * on a `createBasaltRouter` router (called in the entry or a module it imports), and the router tree is generated: the vite config calls a
@@ -417,6 +572,7 @@ function routerCreatedInImports(cwd: string, entry: string): boolean {
417
572
  */
418
573
  export function appWiringCheck(cwd: string): Check {
419
574
  return guarded('app-wiring', () => {
575
+ if (isStartApp(cwd, '')) return startWiring(cwd)
420
576
  const entry = (
421
577
  htmlEntry(readIfExists(resolve(cwd, 'index.html')) ?? '') ?? 'src/main.tsx'
422
578
  ).replace(/^\//, '')
@@ -483,7 +639,7 @@ const EXACT_VERSION = /^\d+\.\d+\.\d+$/
483
639
  function installedVersion(cwd: string, pkg: string): string | null {
484
640
  for (let dir = cwd; ; dir = dirname(dir)) {
485
641
  const manifest = readPackageJson<{ version?: string }>(resolve(dir, 'node_modules', pkg))
486
- if (manifest !== null) return manifest.version ?? null
642
+ if (manifest !== null) return typeof manifest.version === 'string' ? manifest.version : null
487
643
  if (dirname(dir) === dir) return null
488
644
  }
489
645
  }
package/src/cli/doctor.ts CHANGED
@@ -37,8 +37,10 @@ import {
37
37
  import { resolveRoots } from './config'
38
38
  import {
39
39
  appWiringCheck,
40
+ startWiringWarnings,
40
41
  droppedSubpathsCheck,
41
42
  exactPeersCheck,
43
+ oxlintFloorCheck,
42
44
  retiredLintRulesCheck,
43
45
  subpathPeersCheck,
44
46
  tsconfigBaseCheck,
@@ -397,6 +399,7 @@ export function doctor(invocationCwd: string = process.cwd(), flags: string[] =
397
399
  'dropped-subpaths: no import of a basalt-ui subpath the install lacks',
398
400
  droppedSubpathsCheck(appDir, cfg, install),
399
401
  ],
402
+ ['oxlint-floor: the installed oxlint parses the shipped preset', oxlintFloorCheck(cwd)],
400
403
  [
401
404
  'app-wiring: the entry mounts BasaltProvider and the router tree is generated',
402
405
  appWiringCheck(appDir),
@@ -416,6 +419,7 @@ export function doctor(invocationCwd: string = process.cwd(), flags: string[] =
416
419
  else if ('fail' in check) fail(check.fail)
417
420
  else skip(check.skip)
418
421
  }
422
+ for (const line of startWiringWarnings(appDir)) warn(line)
419
423
  }
420
424
 
421
425
  // ── Report ──────────────────────────────────────────────────────────────────
package/src/cli/help.ts CHANGED
@@ -76,7 +76,7 @@ export const USAGE =
76
76
  ' [--light-class <class>] [--dark-value <v>] [--light-value <v>]\n' +
77
77
  ' [--default-scheme <dark|light|none>] [--media-fallback] [--only <core|all>]\n' +
78
78
  ' [--no-legacy-aliases]\n' +
79
- ' Emit the --vx-* stylesheet (stdout unless --out). Defaults reproduce basalt-ui/tokens.css.\n' +
79
+ ' Emit the --vx-* stylesheet (stdout unless --out). Defaults emit the stock identity; commit the output as your tokens file.\n' +
80
80
  ' --selector-class emits `:root.dark` instead of an attribute selector (the Tailwind convention).\n' +
81
81
  ' --check writes nothing and exits 1 when --out differs from what would be emitted (a CI gate).\n' +
82
82
  ' --no-legacy-aliases drops the deprecated camelCase spellings (--vx-accentFill and friends),\n' +
package/src/cli/index.ts CHANGED
@@ -670,6 +670,22 @@ export function routerSeedDest(appRel: string, seed: keyof typeof ROUTER_SEED_DE
670
670
  return appRel === '' ? ROUTER_SEED_DESTS[seed] : `${appRel}/${ROUTER_SEED_DESTS[seed]}`
671
671
  }
672
672
 
673
+ /** The router seeds' dests for an app dir (`main.tsx`, `nav.tsx`, `__root.tsx`). */
674
+ export function routerSeedDests(appRel: string): string[] {
675
+ return (Object.keys(ROUTER_SEED_DESTS) as (keyof typeof ROUTER_SEED_DESTS)[]).map((seed) =>
676
+ routerSeedDest(appRel, seed),
677
+ )
678
+ }
679
+
680
+ /** A TanStack Start app owns its router, so its router seeds give way to an in-tree `<BasaltProvider>`. */
681
+ export function isStartApp(cwd: string, appRel: string): boolean {
682
+ return hasDependency(resolve(cwd, appRel), '@tanstack/react-start')
683
+ }
684
+
685
+ export const START_APP_NOTE =
686
+ 'TanStack Start app — no main.tsx/nav.tsx/__root.tsx seeded (Start owns the router); render ' +
687
+ '<BasaltProvider><Outlet /></BasaltProvider> in your root route component.'
688
+
673
689
  /** The app directory a command's app-scoped half targets: `rel` is '' when it is the install root. */
674
690
  export type AppResolution = { dir: string; rel: string } | { error: string }
675
691
 
package/src/cli/init.ts CHANGED
@@ -11,9 +11,10 @@ import type { MergeLintResult, ScaffoldFlags } from './index'
11
11
  import {
12
12
  MANIFEST_PATH,
13
13
  declaredProfile,
14
+ isStartApp,
15
+ routerSeedDests,
16
+ START_APP_NOTE,
14
17
  readBasaltConfig,
15
- ROUTER_SEED_DESTS,
16
- routerSeedDest,
17
18
  findBasaltInstall,
18
19
  managedFiles,
19
20
  mergeOxlintExtends,
@@ -127,10 +128,9 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
127
128
  const placement = resolvePlacement(cwd)
128
129
  // A tokens-only consumer has no use for the Mantine/React scaffolds (doctor skips them there too).
129
130
  const tokensOnly = declaredProfile(readBasaltConfig(cwd), []) === 'tokens-only'
130
- const routerSeeds: string[] = (
131
- Object.keys(ROUTER_SEED_DESTS) as (keyof typeof ROUTER_SEED_DESTS)[]
132
- ).map((seed) => routerSeedDest(placement.appRel, seed))
133
- const files = managedFiles(placement).filter((f) => !(tokensOnly && routerSeeds.includes(f.dest)))
131
+ const startApp = isStartApp(cwd, placement.appRel)
132
+ const skippedSeeds = new Set(tokensOnly || startApp ? routerSeedDests(placement.appRel) : [])
133
+ const files = managedFiles(placement).filter((f) => !skippedSeeds.has(f.dest))
134
134
 
135
135
  const writtenFiles: string[] = []
136
136
  const keptFiles: string[] = []
@@ -205,6 +205,7 @@ export function init(cwd: string = process.cwd(), scaffoldFlags: ScaffoldFlags =
205
205
  const tsconfigLine = tokensOnly ? null : seedTsconfigExtends(cwd)
206
206
  if (tsconfigLine !== null) console.log(`basalt-ui init: ${tsconfigLine}`)
207
207
  if (buildNote !== null) console.log(`basalt-ui init: ${buildNote}`)
208
+ if (startApp && !tokensOnly) console.log(`basalt-ui init: ${START_APP_NOTE}`)
208
209
  const rootsMessages = rootsNotices(rootsState)
209
210
  for (const line of rootsMessages.log) console.log(`basalt-ui init: ${line}`)
210
211
  for (const line of rootsMessages.error) console.error(`⚠ basalt-ui init: ${line}`)
package/src/cli/sync.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  diffSummary,
13
13
  findBasaltInstall,
14
14
  inspectLefthookGate,
15
+ isStartApp,
15
16
  isStringArray,
16
17
  managedFiles,
17
18
  normalizeForLedger,
@@ -30,9 +31,11 @@ import {
30
31
  reportPrune,
31
32
  resolvePlacement,
32
33
  resolveProjectDir,
34
+ routerSeedDests,
33
35
  rootsNotices,
34
36
  sha256,
35
37
  shippedAssetPath,
38
+ START_APP_NOTE,
36
39
  unitState,
37
40
  writeFileEnsuringDir,
38
41
  writeUnit,
@@ -110,7 +113,9 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
110
113
  // Refuse BEFORE reconcileRoots, which writes `basalt.roots` into package.json.
111
114
  if (!existsSync(resolve(cwd, MANIFEST_PATH))) {
112
115
  const elsewhere = findManifestAbove(cwd)
113
- const wouldWrite = managedFiles(resolvePlacement(cwd)).length
116
+ const refused = resolvePlacement(cwd)
117
+ const startSeeds = isStartApp(cwd, refused.appRel) ? routerSeedDests(refused.appRel) : []
118
+ const wouldWrite = managedFiles(refused).filter((f) => !startSeeds.includes(f.dest)).length
114
119
  console.error(
115
120
  `✖ basalt-ui sync: no ${MANIFEST_PATH} at ${cwd} — refusing to scaffold. ` +
116
121
  `\`sync\` refreshes an EXISTING basalt install; creating one is \`basalt-ui init\`'s ` +
@@ -129,7 +134,9 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
129
134
  const ctx = renderContext(cwd)
130
135
  const manifest = readManifest(cwd)
131
136
  const placement = resolvePlacement(cwd)
132
- const files = managedFiles(placement)
137
+ const startApp = isStartApp(cwd, placement.appRel)
138
+ const skipped = new Set(startApp ? routerSeedDests(placement.appRel) : [])
139
+ const files = managedFiles(placement).filter((f) => !skipped.has(f.dest))
133
140
 
134
141
  let updated = 0
135
142
  // `created` and `recreated` were one counter, and `0 updated, 20 recreated` is what a full
@@ -201,6 +208,26 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
201
208
  // Placement notices — informational, never affecting the exit code, and PERMANENT: `--check`
202
209
  // hides them behind `--verbose` (it sits in consumers' CI chains, where three unchanging
203
210
  // "skipped" paragraphs per run are noise indistinguishable from drift) but still prints the COUNT.
211
+ // Start added AFTER a pre-Start init: the old seeds are the consumer's now — left untouched, named.
212
+ const stale = [...skipped].filter(
213
+ (d) => manifest.files[d] !== undefined && existsSync(resolve(cwd, d)),
214
+ )
215
+ const mounting = stale.filter((d) => !d.endsWith('nav.tsx'))
216
+ const inert = stale.filter((d) => d.endsWith('nav.tsx'))
217
+ const embedded =
218
+ 'Delete them and render <BasaltProvider><Outlet /></BasaltProvider> in the Start root route (embedded mode).'
219
+ if (mounting.length > 0) {
220
+ console.error(
221
+ `⚠ basalt-ui sync: ${mounting.join(', ')} mount a second router inside this TanStack Start app; left untouched. ${embedded}`,
222
+ )
223
+ }
224
+ if (inert.length > 0) {
225
+ console.error(
226
+ `⚠ basalt-ui sync: ${inert.join(', ')} was seeded before this became a Start app; it mounts nothing, so keep or delete it. Left untouched.`,
227
+ )
228
+ }
229
+ if (startApp && (!opts.check || syncFlags.includes('--verbose')))
230
+ console.log(`basalt-ui sync: ${START_APP_NOTE}`)
204
231
  const placementSkips = placementNotices(cwd, placement)
205
232
  if (opts.check !== true || syncFlags.includes('--verbose')) {
206
233
  for (const line of placementSkips) console.log(`basalt-ui sync: ${line}`)
@@ -18,7 +18,7 @@ import { Spotlight } from '@mantine/spotlight'
18
18
  import type { SpotlightActionData } from '@mantine/spotlight'
19
19
  import { QueryClientProvider } from '@tanstack/react-query'
20
20
  import type { QueryClient } from '@tanstack/react-query'
21
- import { RouterProvider } from '@tanstack/react-router'
21
+ import { RouterProvider, useRouter } from '@tanstack/react-router'
22
22
  import type { AnyRouter } from '@tanstack/react-router'
23
23
  import { Component, Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react'
24
24
  import type { ErrorInfo, ReactNode } from 'react'
@@ -50,9 +50,7 @@ import { useRegistryHotkeys } from './hotkeys'
50
50
  import type { FlatNavItem } from '../router-tanstack/nav'
51
51
  import { buildSpotlightActions } from './spotlight-actions'
52
52
 
53
- export type BasaltProviderProps = {
54
- /** From `createBasaltRouter`; the provider mounts it and reads its `queryClient`. */
55
- router: BasaltRouter
53
+ type BasaltProviderCommonProps = {
56
54
  /** Theme override merged onto the Basalt base. Defaults to `createBasaltTheme()`. */
57
55
  theme?: MantineProviderProps['theme']
58
56
  /**
@@ -92,8 +90,33 @@ export type BasaltProviderProps = {
92
90
  * entry with id `nav.<id>` replaces the generated one outright.
93
91
  */
94
92
  navCommandLabel?: (item: FlatNavItem) => string
93
+ /**
94
+ * Mount Basalt's `<Spotlight>` (Cmd+K) with the generated nav + command actions. Default `true`.
95
+ * Set `false` when the app owns its own palette: neither the component nor its action wiring mounts.
96
+ */
97
+ spotlight?: boolean
95
98
  } & Omit<MantineProviderProps, 'children' | 'theme' | 'defaultColorScheme' | 'cssVariablesResolver'>
96
99
 
100
+ /**
101
+ * Two modes, never both: pass a `createBasaltRouter` `router` and the provider mounts it, or pass
102
+ * `children` and render the provider INSIDE a router the app does not own (around the `<Outlet />`
103
+ * of TanStack Start's root route component) — the router then comes from `useRouter()` and must carry
104
+ * `context.queryClient` (its `getRouter()` builds the same context `createBasaltRouter` does).
105
+ */
106
+ export type BasaltProviderProps = BasaltProviderCommonProps &
107
+ (
108
+ | {
109
+ /** From `createBasaltRouter`; the provider mounts it and reads its `queryClient`. */
110
+ router: BasaltRouter
111
+ children?: never
112
+ }
113
+ | {
114
+ router?: never
115
+ /** The subtree inside the app's own router; rendered where `<RouterProvider>` would be. */
116
+ children: ReactNode
117
+ }
118
+ )
119
+
97
120
  // ── Root error boundary ───────────────────────────────────────────────────────────────────────────
98
121
 
99
122
  type RootBoundaryProps = {
@@ -402,17 +425,32 @@ function readQueryClient(router: AnyRouter): QueryClient {
402
425
  const client = (router.options.context as Partial<BasaltRouterContext> | undefined)?.queryClient
403
426
  if (client === undefined) {
404
427
  throw new Error(
405
- '[basalt] BasaltProvider: the router has no context.queryClient — create it with ' +
406
- 'createBasaltRouter({ routeTree }).',
428
+ '[basalt] BasaltProvider: no context.queryClient — pass `router` from createBasaltRouter, ' +
429
+ 'or with `children` put a QueryClient in the router context.',
407
430
  )
408
431
  }
409
432
  return client
410
433
  }
411
434
 
435
+ /**
436
+ * The router this provider serves: the one it mounts (`router`), else — embedded mode — the one the
437
+ * host already mounted above it. `warn: false`: mount mode sits ABOVE any router, so no context is
438
+ * expected there. The context read is SSR-safe.
439
+ */
440
+ function useEffectiveRouter(mounted: BasaltRouter | undefined): AnyRouter {
441
+ const ambient: AnyRouter | undefined = useRouter<AnyRouter>({ warn: false })
442
+ const router = mounted ?? ambient
443
+ if (!router) {
444
+ throw new Error(
445
+ '[basalt] BasaltProvider: no router — pass `router` to mount one, or `children` inside one.',
446
+ )
447
+ }
448
+ return router
449
+ }
450
+
412
451
  // ── Public provider ───────────────────────────────────────────────────────────────────────────────
413
452
 
414
453
  export function BasaltProvider({
415
- router,
416
454
  theme,
417
455
  telemetry,
418
456
  fallback,
@@ -422,6 +460,9 @@ export function BasaltProvider({
422
460
  nonce,
423
461
  sizeClassHint = 'compact',
424
462
  navCommandLabel,
463
+ spotlight = true,
464
+ router: mountedRouter,
465
+ children,
425
466
  ...rest
426
467
  }: BasaltProviderProps) {
427
468
  useDuplicateProviderGuard()
@@ -438,6 +479,7 @@ export function BasaltProvider({
438
479
  // `overlays.confirm` is an imperative call; this tells it a `ModalsProvider` is live.
439
480
  useEffect(() => registerModalsProvider(), [])
440
481
 
482
+ const router = useEffectiveRouter(mountedRouter)
441
483
  const client = readQueryClient(router)
442
484
  useDataTelemetry(router, client, emit)
443
485
 
@@ -449,7 +491,9 @@ export function BasaltProvider({
449
491
  () => setActions(buildSpotlightActions(router, setDevTool, navCommandLabel)),
450
492
  [router, navCommandLabel],
451
493
  )
452
- useEffect(refreshActions, [refreshActions])
494
+ useEffect(() => {
495
+ if (spotlight) refreshActions()
496
+ }, [spotlight, refreshActions])
453
497
 
454
498
  // `createBasaltTheme(theme)` — plus, when the theme lab's "Apply" switch is on, the delta of its
455
499
  // persisted config, so the dev tool moves the numeric `defaultProps` and `theme.spacing` a `<style>`
@@ -474,7 +518,11 @@ export function BasaltProvider({
474
518
  <QueryClientProvider client={client}>
475
519
  {/* ModalsProvider WRAPS the router, so `useModals()` / `openContextModal` have real context. */}
476
520
  <ModalsProvider>
477
- <RouterProvider router={router} />
521
+ {mountedRouter === undefined ? (
522
+ children
523
+ ) : (
524
+ <RouterProvider router={mountedRouter} />
525
+ )}
478
526
  {/* The literal read sits at the branch, so a production build drops the import. */}
479
527
  {process.env.NODE_ENV !== 'production' && (
480
528
  <Suspense fallback={null}>
@@ -488,12 +536,14 @@ export function BasaltProvider({
488
536
  </ModalsProvider>
489
537
  </QueryClientProvider>
490
538
  <Notifications position="bottom-right" autoClose={4000} limit={5} />
491
- <Spotlight
492
- actions={actions}
493
- onSpotlightOpen={refreshActions}
494
- shortcut="mod + K"
495
- maxHeight={420}
496
- />
539
+ {spotlight && (
540
+ <Spotlight
541
+ actions={actions}
542
+ onSpotlightOpen={refreshActions}
543
+ shortcut="mod + K"
544
+ maxHeight={420}
545
+ />
546
+ )}
497
547
  </SizeClassHintContext.Provider>
498
548
  </TelemetryContext.Provider>
499
549
  </BasaltBridge>
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { Outlet, createRootRoute, createRoute } from '@tanstack/react-router'
6
6
  import type { AnyRouter } from '@tanstack/react-router'
7
+ import type { ReactNode } from 'react'
7
8
  import { createBasaltRouter } from './create-router'
8
9
  import type { BasaltRouterContext } from './create-router'
9
10
 
@@ -11,15 +12,14 @@ import type { BasaltRouterContext } from './create-router'
11
12
  export const queryClientOf = (router: AnyRouter): BasaltRouterContext['queryClient'] =>
12
13
  (router.options.context as BasaltRouterContext).queryClient
13
14
 
14
- export function testRouter(text = 'content') {
15
- const root = createRootRoute({
16
- component: () => (
17
- <>
18
- <div>{text}</div>
19
- <Outlet />
20
- </>
21
- ),
22
- })
15
+ export function testRouter(text = 'content', wrap?: (children: ReactNode) => ReactNode) {
16
+ const body = (
17
+ <>
18
+ <div>{text}</div>
19
+ <Outlet />
20
+ </>
21
+ )
22
+ const root = createRootRoute({ component: () => (wrap ? wrap(body) : body) })
23
23
  const other = createRoute({ getParentRoute: () => root, path: '/other', component: () => null })
24
24
  return createBasaltRouter({ routeTree: root.addChildren([other]) })
25
25
  }