basalt-ui 2.8.0 → 2.8.1

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 (54) hide show
  1. package/CHANGELOG.md +186 -190
  2. package/MIGRATING.md +52 -13
  3. package/dist/cli/doctor-upgrade.d.ts +5 -4
  4. package/dist/cli/doctor-upgrade.d.ts.map +1 -1
  5. package/dist/cli/doctor-upgrade.js +23 -99
  6. package/dist/cli/doctor.d.ts +2 -1
  7. package/dist/cli/doctor.d.ts.map +1 -1
  8. package/dist/cli/doctor.js +17 -13
  9. package/dist/cli/index.d.ts +15 -6
  10. package/dist/cli/index.d.ts.map +1 -1
  11. package/dist/cli/index.js +16 -27
  12. package/dist/cli/init.d.ts.map +1 -1
  13. package/dist/cli/init.js +9 -6
  14. package/dist/cli/router-wiring.d.ts +37 -0
  15. package/dist/cli/router-wiring.d.ts.map +1 -0
  16. package/dist/cli/router-wiring.js +116 -0
  17. package/dist/cli/source-text.d.ts +12 -0
  18. package/dist/cli/source-text.d.ts.map +1 -0
  19. package/dist/cli/source-text.js +46 -0
  20. package/dist/cli/sync.d.ts.map +1 -1
  21. package/dist/cli/sync.js +15 -10
  22. package/dist/content/code-block.d.ts.map +1 -1
  23. package/dist/content/code-block.js +36 -27
  24. package/dist/content/code-block.module.css +19 -1
  25. package/dist/content/mermaid-sanitize.d.ts +15 -0
  26. package/dist/content/mermaid-sanitize.d.ts.map +1 -0
  27. package/dist/content/mermaid-sanitize.js +28 -0
  28. package/dist/content/mermaid.d.ts +6 -0
  29. package/dist/content/mermaid.d.ts.map +1 -1
  30. package/dist/content/mermaid.js +3 -1
  31. package/dist/provider/index.d.ts.map +1 -1
  32. package/dist/provider/index.js +3 -2
  33. package/dist/vite-boot.d.ts +25 -0
  34. package/dist/vite-boot.d.ts.map +1 -0
  35. package/dist/vite-boot.js +36 -0
  36. package/dist/vite.d.ts +24 -3
  37. package/dist/vite.d.ts.map +1 -1
  38. package/dist/vite.js +7 -16
  39. package/llms.txt +4 -3
  40. package/package.json +1 -1
  41. package/src/cli/doctor-upgrade.ts +29 -145
  42. package/src/cli/doctor.ts +19 -14
  43. package/src/cli/index.ts +26 -41
  44. package/src/cli/init.ts +9 -6
  45. package/src/cli/router-wiring.ts +185 -0
  46. package/src/cli/source-text.ts +62 -0
  47. package/src/cli/sync.ts +17 -10
  48. package/src/content/code-block.module.css +19 -1
  49. package/src/content/code-block.tsx +7 -2
  50. package/src/content/mermaid-sanitize.ts +49 -0
  51. package/src/content/mermaid.tsx +3 -2
  52. package/src/provider/index.tsx +6 -3
  53. package/src/vite-boot.ts +109 -0
  54. package/src/vite.ts +32 -61
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Router wiring: is an app TanStack Start, code-routed (route tree defined in code) or file-routed
3
+ * (plugin or `routeTree.gen.*`)? Textual, no TS program. A leaf module shared by init/sync/doctor.
4
+ */
5
+ import { existsSync } from 'node:fs'
6
+ import { dirname, resolve } from 'node:path'
7
+
8
+ import { hasDependency, readIfExists, tokenize } from './source-text'
9
+
10
+ /** Relative-import hops (static or dynamic) `callsIn` follows from the entry; a router often lives in a singleton module. */
11
+ const IMPORT_DEPTH = 3
12
+
13
+ const VITE_CONFIGS = ['ts', 'mts', 'cts', 'js', 'mjs', 'cjs'].map((e) => `vite.config.${e}`)
14
+ /** The first local `<script type="module" src>` in index.html (comments and remote src skipped). */
15
+ function htmlEntry(html: string): string | undefined {
16
+ for (const [, attrs = ''] of html
17
+ .replace(/<!--[\s\S]*?-->/g, '')
18
+ .matchAll(/<script\b([^>]*)>/gi)) {
19
+ const src = /\bsrc\s*=\s*["']?([^"'\s>]+)/i.exec(attrs)?.[1]
20
+ if (
21
+ /\btype\s*=\s*["']?module\b/i.test(attrs) &&
22
+ src !== undefined &&
23
+ !/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(src)
24
+ ) {
25
+ return src
26
+ }
27
+ }
28
+ return undefined
29
+ }
30
+
31
+ /** True when `src` calls a binding imported from `@tanstack/router-plugin` after its `plugins` key (a textual proxy for "inside the array"). */
32
+ function registersRouterPlugin(src: string): boolean {
33
+ const { code, inLiteral } = tokenize(src)
34
+ const pluginsAt = [...code.matchAll(/\bplugins\b/g)].find((m) => !inLiteral(m.index))?.index
35
+ if (pluginsAt === undefined) return false
36
+ const imports = code.matchAll(
37
+ /(?:^|;)[ \t]*import\s+(?:type\s+)?([^'"`;]*?)\s*from\s*(['"])@tanstack\/router-plugin(?:\/[^'"]*)?\2/gm,
38
+ )
39
+ return [...imports].some((m) => {
40
+ if (inLiteral(m.index)) return false
41
+ const names = (m[1] ?? '')
42
+ .replace(/[{}]/g, '')
43
+ .split(',')
44
+ .map((part) => part.trim())
45
+ .filter((part) => part !== '' && !/^type\s/.test(part))
46
+ .map((part) => part.split(/\s+as\s+/).pop() ?? part)
47
+ return names.some((name) =>
48
+ [
49
+ ...code.matchAll(
50
+ new RegExp(`(?<![.\\w$])${name.replace(/\$/g, '\\$')}(?:\\.\\w+)?\\s*\\(`, 'g'),
51
+ ),
52
+ ].some((call) => call.index > pluginsAt && !inLiteral(call.index)),
53
+ )
54
+ })
55
+ }
56
+
57
+ /** A relative specifier: `import … from`, `export … from`, bare `import '…'` and dynamic `import('…')`. */
58
+ const RELATIVE_IMPORT =
59
+ /(?<![.\w$])(?:(?:import|export)\b[^'";]*?\bfrom|import\s*\(?)\s*['"](\.{1,2}\/[^'"]+)['"]/g
60
+
61
+ /** An import/export specifier naming the generated route tree (`./routeTree.gen`). */
62
+ const GENERATED_TREE_IMPORT =
63
+ /(?<![.\w$])(?:(?:import|export)\b[^'";]*?\bfrom|import\s*\(?)\s*['"][^'"]*routeTree\.gen[^'"]*['"]/g
64
+
65
+ /** The source file a relative specifier names: as written, `.ts`/`.tsx` appended, or a directory index. */
66
+ function resolveRelative(from: string, spec: string): string | null {
67
+ const base = resolve(dirname(from), spec.replace(/\.[jt]sx?$/, ''))
68
+ return (
69
+ [
70
+ resolve(dirname(from), spec),
71
+ `${base}.ts`,
72
+ `${base}.tsx`,
73
+ `${base}/index.ts`,
74
+ `${base}/index.tsx`,
75
+ ].find((f) => /\.[jt]sx?$/.test(f) && existsSync(f)) ?? null
76
+ )
77
+ }
78
+
79
+ /** The module `index.html` loads for the app at `dir` (default src/main.tsx), relative to `dir`. */
80
+ export function appEntry(dir: string): string {
81
+ const src = htmlEntry(readIfExists(resolve(dir, 'index.html')) ?? '') ?? 'src/main.tsx'
82
+ return src.replace(/^\//, '')
83
+ }
84
+
85
+ type Tokens = ReturnType<typeof tokenize>
86
+
87
+ /**
88
+ * Whether the entry or a module it imports (relative imports, static or dynamic, `IMPORT_DEPTH`
89
+ * hops) matches `pattern` in code — a global regex, ignoring comments and string literals; an
90
+ * import inside a comment or a string is not followed. `entryTokens` reuses an already-tokenized entry.
91
+ */
92
+ export function callsIn(
93
+ dir: string,
94
+ entry: string,
95
+ pattern: RegExp,
96
+ entryTokens?: Tokens,
97
+ ): boolean {
98
+ const entryPath = resolve(dir, entry)
99
+ const seen = new Set([entryPath])
100
+ let frontier = [entryPath]
101
+ for (let depth = 0; depth <= IMPORT_DEPTH && frontier.length > 0; depth++) {
102
+ const next: string[] = []
103
+ for (const file of frontier) {
104
+ const { code, inLiteral } =
105
+ file === entryPath && entryTokens ? entryTokens : tokenize(readIfExists(file) ?? '')
106
+ if ([...code.matchAll(pattern)].some((c) => !inLiteral(c.index))) return true
107
+ for (const m of code.matchAll(RELATIVE_IMPORT)) {
108
+ if (inLiteral(m.index)) continue
109
+ const dep = resolveRelative(file, m[1] ?? '')
110
+ if (dep === null || seen.has(dep)) continue
111
+ seen.add(dep)
112
+ next.push(dep)
113
+ }
114
+ }
115
+ frontier = next
116
+ }
117
+ return false
118
+ }
119
+
120
+ /** A global regex matching a CALL of `name` (itself a regex source), generic or not — not an import or bare mention. */
121
+ export function callOf(pattern: string): RegExp {
122
+ return new RegExp(`\\b${pattern}\\b\\s*(?:<[^()]*>)?\\s*\\(`, 'g')
123
+ }
124
+
125
+ const CREATE_BASALT_ROUTER = callOf('createBasaltRouter')
126
+
127
+ /** The directories a generated `routeTree.gen.*` is looked for in: beside the entry, then src/. */
128
+ export function routeTreeDirs(entry: string): string[] {
129
+ return [...new Set([dirname(entry), 'src'])]
130
+ }
131
+
132
+ /** A TanStack router plugin in the vite config, or a `routeTree.gen.*` in `routeTreeDirs`. */
133
+ export function hasRouteTree(dir: string, entry: string): boolean {
134
+ const vite = VITE_CONFIGS.map((f) => readIfExists(resolve(dir, f))).find((t) => t !== null) ?? ''
135
+ return (
136
+ registersRouterPlugin(vite) ||
137
+ routeTreeDirs(entry).some((d) =>
138
+ ['ts', 'tsx', 'js'].some((e) => existsSync(resolve(dir, d, `routeTree.gen.${e}`))),
139
+ )
140
+ )
141
+ }
142
+
143
+ /** Whether `createBasaltRouter` is called in a module reachable from the entry. */
144
+ export function hasRouter(dir: string, entry: string, entryTokens?: Tokens): boolean {
145
+ return callsIn(dir, entry, CREATE_BASALT_ROUTER, entryTokens)
146
+ }
147
+
148
+ /** Whether the (tokenized) entry imports the generated route tree — a freshly seeded entry does. */
149
+ function importsGeneratedTree({ code, inLiteral }: Tokens): boolean {
150
+ return [...code.matchAll(GENERATED_TREE_IMPORT)].some((m) => !inLiteral(m.index))
151
+ }
152
+
153
+ /**
154
+ * THE classification, shared by `init`, `sync` and `doctor`: code-routed = `createBasaltRouter` is
155
+ * called in a module reachable from the entry, no router plugin is registered and no
156
+ * `routeTree.gen.*` exists, and the entry does not import a generated tree (a freshly seeded entry
157
+ * does, before the first vite run — that app is file-routed). Comments and strings do not count.
158
+ */
159
+ export function isCodeRoutedApp(cwd: string, appRel: string): boolean {
160
+ const dir = resolve(cwd, appRel)
161
+ const entry = appEntry(dir)
162
+ const tokens = tokenize(readIfExists(resolve(dir, entry)) ?? '')
163
+ if (importsGeneratedTree(tokens)) return false
164
+ return hasRouter(dir, entry, tokens) && !hasRouteTree(dir, entry)
165
+ }
166
+
167
+ /** A TanStack Start app owns its router, so its router seeds give way to an in-tree `<BasaltProvider>`. */
168
+ export function isStartApp(cwd: string, appRel: string): boolean {
169
+ return hasDependency(resolve(cwd, appRel), '@tanstack/react-start')
170
+ }
171
+
172
+ /** Why an app's router seeds are not placed (see `routerSeedSkip`). */
173
+ export type RouterSeedSkip = 'start' | 'code-routed' | null
174
+
175
+ export const CODE_ROUTED_NOTE =
176
+ 'code-routed app (createBasaltRouter, no route-tree plugin or routeTree.gen) — no main.tsx/nav.tsx/__root.tsx seeded.'
177
+
178
+ /**
179
+ * Why an app's router seeds (main/nav/__root) are not placed: `start` (Start owns the router, and
180
+ * wins when both apply) or `code-routed` (no generated tree to assume); null when they are.
181
+ */
182
+ export function routerSeedSkip(cwd: string, appRel: string): RouterSeedSkip {
183
+ if (isStartApp(cwd, appRel)) return 'start'
184
+ return isCodeRoutedApp(cwd, appRel) ? 'code-routed' : null
185
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Textual source helpers shared by the CLI's router detection and its checks: reading a file as
3
+ * `null` when it is not there, a package.json dependency probe, and a comment/string tokenizer.
4
+ */
5
+ import { readFileSync } from 'node:fs'
6
+ import { resolve } from 'node:path'
7
+
8
+ /** `abs` read as text, or null: absent, a directory, unreadable or raced away all mean "not there". */
9
+ export function readIfExists(abs: string): string | null {
10
+ try {
11
+ return readFileSync(abs, 'utf8')
12
+ } catch {
13
+ return null
14
+ }
15
+ }
16
+
17
+ /** `<dir>/package.json` parsed as `T`; null when absent or not JSON. */
18
+ export function readPackageJson<T>(dir: string): T | null {
19
+ const raw = readIfExists(resolve(dir, 'package.json'))
20
+ try {
21
+ return raw === null ? null : (JSON.parse(raw) as T)
22
+ } catch {
23
+ return null
24
+ }
25
+ }
26
+
27
+ const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies'] as const
28
+
29
+ /** True when `pkgName` appears in any of the consumer's dependencies, devDependencies or peerDependencies. */
30
+ export function hasDependency(cwd: string, pkgName: string): boolean {
31
+ const pkg =
32
+ readPackageJson<Partial<Record<(typeof DEPENDENCY_FIELDS)[number], Record<string, string>>>>(
33
+ cwd,
34
+ )
35
+ return DEPENDENCY_FIELDS.some((field) => pkg?.[field]?.[pkgName] !== undefined)
36
+ }
37
+
38
+ /**
39
+ * Strings and template literals (captured) and comments. Known, accepted gap: a regex literal that
40
+ * contains a quote (`/'/`) opens a string this tokenizer never closes, which can blank or hide code
41
+ * after it on that line; a template literal nested inside a `${…}` is not tracked either.
42
+ */
43
+ const TOKEN =
44
+ /("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\/[^\n]*|\/\*[\s\S]*?\*\//g
45
+
46
+ /** Source with comments blanked (and template text), plus a test for "offset sits inside a string". */
47
+ export function tokenize(src: string): { code: string; inLiteral: (at: number) => boolean } {
48
+ const literals: [number, number][] = []
49
+ const code = src.replace(TOKEN, (m, literal: string | undefined, at: number) => {
50
+ if (literal === undefined) return m.replace(/[^\n]/g, ' ')
51
+ if (!literal.startsWith('`')) {
52
+ literals.push([at, at + m.length])
53
+ return m
54
+ }
55
+ // Template literal: blank the text, keep the delimiters and the `${…}` code scannable.
56
+ return m.replace(
57
+ /(\$\{[^}]*\})|[^\n`]/g,
58
+ (c, interpolation: string | undefined) => interpolation ?? ' ',
59
+ )
60
+ })
61
+ return { code, inLiteral: (at) => literals.some(([from, to]) => at >= from && at < to) }
62
+ }
package/src/cli/sync.ts CHANGED
@@ -12,7 +12,6 @@ import {
12
12
  diffSummary,
13
13
  findBasaltInstall,
14
14
  inspectLefthookGate,
15
- isStartApp,
16
15
  isStringArray,
17
16
  managedFiles,
18
17
  normalizeForLedger,
@@ -31,7 +30,7 @@ import {
31
30
  reportPrune,
32
31
  resolvePlacement,
33
32
  resolveProjectDir,
34
- routerSeedDests,
33
+ routerSeedPlan,
35
34
  rootsNotices,
36
35
  sha256,
37
36
  shippedAssetPath,
@@ -114,8 +113,8 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
114
113
  if (!existsSync(resolve(cwd, MANIFEST_PATH))) {
115
114
  const elsewhere = findManifestAbove(cwd)
116
115
  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
116
+ const { skipped: skippedSeeds } = routerSeedPlan(cwd, refused.appRel)
117
+ const wouldWrite = managedFiles(refused).filter((f) => !skippedSeeds.has(f.dest)).length
119
118
  console.error(
120
119
  `✖ basalt-ui sync: no ${MANIFEST_PATH} at ${cwd} — refusing to scaffold. ` +
121
120
  `\`sync\` refreshes an EXISTING basalt install; creating one is \`basalt-ui init\`'s ` +
@@ -134,8 +133,7 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
134
133
  const ctx = renderContext(cwd)
135
134
  const manifest = readManifest(cwd)
136
135
  const placement = resolvePlacement(cwd)
137
- const startApp = isStartApp(cwd, placement.appRel)
138
- const skipped = new Set(startApp ? routerSeedDests(placement.appRel) : [])
136
+ const { skip: seedSkip, skipped } = routerSeedPlan(cwd, placement.appRel)
139
137
  const files = managedFiles(placement).filter((f) => !skipped.has(f.dest))
140
138
 
141
139
  let updated = 0
@@ -205,13 +203,22 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
205
203
  })
206
204
  staleForCheck += pruned.removed.length + pruned.drifted.length
207
205
 
206
+ // A code-routed app takes no router seeds: their manifest entries go; any file stays the consumer's.
207
+ const isTracked = (d: string): boolean => manifest.files[d] !== undefined
208
+ const codeRoutedSeeds = seedSkip === 'code-routed' ? [...skipped].filter(isTracked) : []
209
+ if (codeRoutedSeeds.length > 0 && !opts.check) {
210
+ for (const d of codeRoutedSeeds) delete manifest.files[d]
211
+ console.error(
212
+ `⚠ basalt-ui sync: code-routed app — dropped ${codeRoutedSeeds.join(', ')} from the manifest (any file is yours).`,
213
+ )
214
+ }
215
+
208
216
  // Placement notices — informational, never affecting the exit code, and PERMANENT: `--check`
209
217
  // hides them behind `--verbose` (it sits in consumers' CI chains, where three unchanging
210
218
  // "skipped" paragraphs per run are noise indistinguishable from drift) but still prints the COUNT.
211
219
  // 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
- )
220
+ const startSkippedSeeds = seedSkip === 'start' ? [...skipped] : []
221
+ const stale = startSkippedSeeds.filter((d) => isTracked(d) && existsSync(resolve(cwd, d)))
215
222
  const mounting = stale.filter((d) => !d.endsWith('nav.tsx'))
216
223
  const inert = stale.filter((d) => d.endsWith('nav.tsx'))
217
224
  const embedded =
@@ -226,7 +233,7 @@ export function sync(opts: SyncOptions = {}, invocationCwd: string = process.cwd
226
233
  `⚠ basalt-ui sync: ${inert.join(', ')} was seeded before this became a Start app; it mounts nothing, so keep or delete it. Left untouched.`,
227
234
  )
228
235
  }
229
- if (startApp && (!opts.check || syncFlags.includes('--verbose')))
236
+ if (seedSkip === 'start' && (!opts.check || syncFlags.includes('--verbose')))
230
237
  console.log(`basalt-ui sync: ${START_APP_NOTE}`)
231
238
  const placementSkips = placementNotices(cwd, placement)
232
239
  if (opts.check !== true || syncFlags.includes('--verbose')) {
@@ -77,7 +77,13 @@
77
77
  );
78
78
  }
79
79
 
80
- .body :global(pre.shiki) {
80
+ /* Both body states — the highlighted wrapper's `pre.shiki` and the bare fallback `<pre class=body>`
81
+ * — outrank Prose's `.root.article pre` block margin (0,2,1): at a tie, stylesheet order decided
82
+ * whether the inner pre kept 18px, so the fallback was ~36px taller than the highlighted fence and
83
+ * the swap jumped. `.body.body` lifts the fallback to (0,3,0); the outer `.container` margin alone
84
+ * owns the rhythm. */
85
+ .container .body.body,
86
+ .container .body :global(pre.shiki) {
81
87
  margin: 0;
82
88
  padding: 0;
83
89
  background: transparent !important;
@@ -93,6 +99,18 @@ html[data-mantine-color-scheme='light'] .body :global(.shiki span) {
93
99
  color: var(--shiki-light);
94
100
  }
95
101
 
102
+ /* The floating button sits over the body's top-right corner, so the body reserves its box: the
103
+ * first line starts below offset + button height instead of running underneath it on touch (always
104
+ * visible) or on hover. `--code-block-copy-size` mirrors ActionIcon size="sm" (Mantine scopes its
105
+ * own `--ai-size-sm` to the button, out of the body's reach); the layout suite pins the two. */
106
+ .container[data-floating-copy] {
107
+ --code-block-copy-size: calc(1.375rem * var(--mantine-scale, 1));
108
+ }
109
+
110
+ .container[data-floating-copy] .body {
111
+ padding-top: calc(var(--vx-space-code-block-floating-copy-offset) + var(--code-block-copy-size));
112
+ }
113
+
96
114
  /* Floating copy button — shown only when there is no header (no title), revealed on hover/focus. */
97
115
  .floatingCopy {
98
116
  position: absolute;
@@ -88,9 +88,14 @@ export function CodeBlock({
88
88
  }, [html, code])
89
89
 
90
90
  const containerClass = [classes.container, className].filter(Boolean).join(' ')
91
+ const showFloatingCopy = title === undefined && showCopy
91
92
 
92
93
  return (
93
- <div className={containerClass} {...(style !== undefined && { style })}>
94
+ <div
95
+ className={containerClass}
96
+ {...(showFloatingCopy && { 'data-floating-copy': true })}
97
+ {...(style !== undefined && { style })}
98
+ >
94
99
  {title !== undefined && (
95
100
  <div className={classes.header}>
96
101
  <span className={classes.title}>{title}</span>
@@ -116,7 +121,7 @@ export function CodeBlock({
116
121
  <code>{code}</code>
117
122
  </pre>
118
123
  )}
119
- {title === undefined && showCopy && (
124
+ {showFloatingCopy && (
120
125
  <div className={classes.floatingCopy}>
121
126
  <CopyAction value={code} ariaLabel="Copy code" />
122
127
  </div>
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Post-process for beautiful-mermaid's SVG (consumed by `./mermaid`).
3
+ *
4
+ * `buildStyleBlock(font)` treats the font as a family NAME: it emits a Google Fonts `@import` (plus
5
+ * a JetBrains Mono one when `mono` is set) and writes `text { font-family: '<font>', … }`. basalt
6
+ * feeds it `var(--basalt-font-sans)`, so the import is a broken request and the quoted `'var(…)'`
7
+ * is an invalid family. basalt self-hosts its fonts: drop the import, unquote the var().
8
+ *
9
+ * Patterns verified against beautiful-mermaid 1.1.3 (peer range ^1.1.0): the style block is a
10
+ * single `<style>` holding the `@import`s and one `text { font-family }` rule; `font-family`
11
+ * never appears as a presentation attribute. Only `<style>` content is rewritten — a node label
12
+ * that happens to contain the same text is left alone.
13
+ */
14
+
15
+ const STYLE_BLOCK = /(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi
16
+
17
+ // One `@import` statement, built from fragments. The family URL itself contains `;` (`wght@400;500`,
18
+ // `&amp;`), so each form is bounded by its closing quote / `)` — never by `;` — and never crosses
19
+ // a newline or `}`: a truncated import cannot eat unrelated CSS.
20
+ const HOST = String.raw`(?:https?:)?\/\/fonts\.googleapis\.com`
21
+ const QUOTED_FORM = String.raw`(?:url\(\s*)?(['"])${HOST}[^'"}\n]*\1(?:\s*\))?` // 'url' | url('url') | url("url")
22
+ const URL_FORM = String.raw`url\(\s*${HOST}[^}'"\n]*?\)` // url(url)
23
+ const MEDIA_LIST = String.raw`(?:[ \t]+[^;{}\n]*)?` // `url(…) screen`
24
+ const GOOGLE_FONTS_IMPORT = new RegExp(
25
+ String.raw`@import\s+(?:${QUOTED_FORM}|${URL_FORM})${MEDIA_LIST}[ \t]*;?`,
26
+ 'g',
27
+ )
28
+
29
+ // `font-family: 'var(--x)'` — a value that is exactly a quoted var(). `var(--a, 'fallback')` has a
30
+ // quote inside and `'Inter', var(--x)` does not start with var(, so neither matches.
31
+ const QUOTED_VAR_FONT_FAMILY = /(font-family\s*:\s*)(['"])(var\([^'"]*\))\2/g
32
+
33
+ function sanitizeStyle(css: string): string {
34
+ const cleaned = css.replace(GOOGLE_FONTS_IMPORT, '').replace(QUOTED_VAR_FONT_FAMILY, '$1$3')
35
+ if (process.env.NODE_ENV !== 'production' && /googleapis/i.test(cleaned)) {
36
+ console.warn(
37
+ '[basalt] MermaidDiagram: a remote font import survived sanitization — beautiful-mermaid ' +
38
+ 'changed its <style> output; update src/content/mermaid-sanitize.ts.',
39
+ )
40
+ }
41
+ return cleaned
42
+ }
43
+
44
+ export function sanitizeMermaidFonts(svg: string): string {
45
+ return svg.replace(
46
+ STYLE_BLOCK,
47
+ (_block, open: string, css: string, close: string) => open + sanitizeStyle(css) + close,
48
+ )
49
+ }
@@ -23,6 +23,7 @@ import type { CSSProperties, ReactNode } from 'react'
23
23
  import { useEffect, useMemo, useState } from 'react'
24
24
  import { CodeBlock } from './code-block'
25
25
  import classes from './mermaid.module.css'
26
+ import { sanitizeMermaidFonts } from './mermaid-sanitize'
26
27
 
27
28
  // Import the type only — erased at runtime (verbatimModuleSyntax safe). `beautiful-mermaid` is a
28
29
  // devDependency purely so this type resolves; the runtime import below is fully dynamic.
@@ -36,7 +37,7 @@ type MermaidModule = {
36
37
  * Static theme mapping onto the `--vx-*` token layer — every value is a `var(--vx-*)` string, so
37
38
  * this object never changes across renders/schemes and can live at module scope.
38
39
  */
39
- const MERMAID_THEME_OPTIONS: RenderOptions = {
40
+ export const MERMAID_THEME_OPTIONS: RenderOptions = {
40
41
  bg: 'var(--vx-surface-panel)',
41
42
  fg: 'var(--vx-ink)',
42
43
  line: 'var(--vx-line)',
@@ -87,7 +88,7 @@ export function MermaidDiagram({ code, className, style, fallback }: MermaidDiag
87
88
  const rendered = useMemo(() => {
88
89
  if (!mod) return null
89
90
  try {
90
- return mod.renderMermaidSVG(code, MERMAID_THEME_OPTIONS)
91
+ return sanitizeMermaidFonts(mod.renderMermaidSVG(code, MERMAID_THEME_OPTIONS))
91
92
  } catch {
92
93
  return undefined
93
94
  }
@@ -418,8 +418,11 @@ function useDataTelemetry(router: AnyRouter, client: QueryClient, emit: Telemetr
418
418
  }
419
419
 
420
420
  // ── Dev dock (dev-only, behind a literal NODE_ENV read at the lazy site) ──────────────────────────
421
+ // The gate wraps `lazy()` itself so the dock chunks never ship; the consumer bundler must define
422
+ // `process.env.NODE_ENV` for the fold, as it already must for `lab-theme.ts`.
421
423
 
422
- const LazyDevDock = lazy(() => import('../dev-dock').then((m) => ({ default: m.BasaltDevDock })))
424
+ const loadDevDock = () => import('../dev-dock').then((m) => ({ default: m.BasaltDevDock }))
425
+ const LazyDevDock = process.env.NODE_ENV === 'production' ? null : lazy(loadDevDock)
423
426
 
424
427
  function readQueryClient(router: AnyRouter): QueryClient {
425
428
  const client = (router.options.context as Partial<BasaltRouterContext> | undefined)?.queryClient
@@ -523,8 +526,8 @@ export function BasaltProvider({
523
526
  ) : (
524
527
  <RouterProvider router={mountedRouter} />
525
528
  )}
526
- {/* The literal read sits at the branch, so a production build drops the import. */}
527
- {process.env.NODE_ENV !== 'production' && (
529
+ {/* `LazyDevDock` is `null` in production (module-scope gate above), so nothing mounts. */}
530
+ {LazyDevDock !== null && (
528
531
  <Suspense fallback={null}>
529
532
  <LazyDevDock
530
533
  tool={devTool}
@@ -0,0 +1,109 @@
1
+ /**
2
+ * vite-boot.ts — the anti-FOUC boot subsystem of `basaltAppPlugin`: the unlayered `<style>` that
3
+ * paints the page before any stylesheet lands, and the tiny inline script that makes that paint
4
+ * follow the scheme the user last stored.
5
+ *
6
+ * Internal to the `./vite` subpath only — deliberately NOT re-exported from `vite.ts`.
7
+ */
8
+ import type { HtmlTagDescriptor } from 'vite'
9
+
10
+ /**
11
+ * The selector every anti-FOUC declaration is scoped to.
12
+ *
13
+ * The rule paints the page before any stylesheet lands, so it is UNLAYERED by construction — and an
14
+ * unlayered declaration outranks every layered one regardless of specificity. Through 1.20.0 that
15
+ * meant a flat `html{color-scheme:dark}` permanently beat Mantine's own
16
+ * `@layer mantine{:root{color-scheme:var(--mantine-color-scheme)}}`: a light-scheme consumer got
17
+ * dark scrollbars, dark `<select>` popups and dark date pickers forever, with no opt-out (found
18
+ * independently by two consumers).
19
+ *
20
+ * `MantineProvider` writes `data-mantine-color-scheme` onto `<html>` as soon as it mounts, so
21
+ * scoping the boot rule to its ABSENCE makes it expire exactly when the real theme exists — which
22
+ * is the anti-FOUC contract stated honestly. A cascade layer would also work in principle and is
23
+ * deliberately NOT used: a layer's position is fixed by where its name is first encountered, and in
24
+ * dev Mantine's CSS is injected by JS after this `<style>` is already in the document, so the layer
25
+ * order would depend on bundler mode. Selector scoping depends on nothing.
26
+ */
27
+ const BOOT_SCOPE = 'html:not([data-mantine-color-scheme])'
28
+
29
+ /** Boot-only attribute `BOOT_SCRIPT` sets; never `data-mantine-color-scheme`, which would expire the rule. */
30
+ const BOOT_ATTRIBUTE = 'data-basalt-boot'
31
+
32
+ /** Mantine's default `localStorageColorSchemeManager` key — BasaltProvider installs no manager of its own. */
33
+ const BOOT_STORAGE_KEY = 'mantine-color-scheme-value'
34
+
35
+ /**
36
+ * Stored value is Mantine's raw `light` | `dark` | `auto` string; `auto` resolves through
37
+ * `prefers-color-scheme`. A throwing or empty store, or a missing `matchMedia`, leaves the
38
+ * attribute off. IIFE + `let`: a classic inline script shares the page's global scope.
39
+ */
40
+ const BOOT_SCRIPT =
41
+ '(function(){try{' +
42
+ `let v=localStorage.getItem('${BOOT_STORAGE_KEY}');` +
43
+ "if(v==='auto')v=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';" +
44
+ `if(v==='light'||v==='dark')document.documentElement.setAttribute('${BOOT_ATTRIBUTE}',v)` +
45
+ '}catch(e){}})()'
46
+
47
+ /** The `color-scheme` value each boot mode declares. `false` declares none. */
48
+ const BOOT_COLOR_SCHEME = { dark: 'dark', light: 'light', auto: 'light dark' } as const
49
+
50
+ /** The `colorScheme` option: which scheme the boot paint assumes; `false` declares no `color-scheme`. */
51
+ export type BootColorScheme = 'dark' | 'light' | 'auto' | false
52
+
53
+ type BootInput = {
54
+ colorScheme: BootColorScheme
55
+ themeColor: { light: string; dark: string }
56
+ backgroundColor: string
57
+ explicitBackground: boolean
58
+ /** Inject the stored-scheme script and the variant rules it drives. */
59
+ bootScript: boolean
60
+ }
61
+
62
+ /**
63
+ * The base rule: paint the surface (and, unless opted out, tell the UA which native-control palette
64
+ * to use) for the frames between first paint and Mantine's stylesheet.
65
+ *
66
+ * `'auto'` with no explicit `backgroundColor` emits a `prefers-color-scheme` pair so the pre-boot
67
+ * paint follows the OS the same way `color-scheme: light dark` does; an explicit `backgroundColor`
68
+ * is used verbatim for both, since the consumer has named one color on purpose.
69
+ */
70
+ function buildBaseBootStyle(input: BootInput): string {
71
+ const { colorScheme, themeColor, backgroundColor, explicitBackground } = input
72
+
73
+ if (colorScheme === false) return `${BOOT_SCOPE}{background-color:${backgroundColor}}`
74
+
75
+ const scheme = BOOT_COLOR_SCHEME[colorScheme]
76
+ if (colorScheme !== 'auto' || explicitBackground) {
77
+ return `${BOOT_SCOPE}{background-color:${backgroundColor};color-scheme:${scheme}}`
78
+ }
79
+ return (
80
+ `${BOOT_SCOPE}{background-color:${themeColor.light};color-scheme:${scheme}}` +
81
+ `@media(prefers-color-scheme:dark){${BOOT_SCOPE}{background-color:${themeColor.dark}}}`
82
+ )
83
+ }
84
+
85
+ function buildBootStyle(input: BootInput): string {
86
+ const { colorScheme, themeColor, explicitBackground, bootScript } = input
87
+ const base = buildBaseBootStyle(input)
88
+ if (!bootScript) return base
89
+
90
+ // Stored-scheme variants: keyed off the attribute BOOT_SCRIPT sets, still inside BOOT_SCOPE so
91
+ // they expire with the rest. The extra attribute outranks the base rule and its `auto` media pair.
92
+ // An explicit backgroundColor is the consumer's one chosen color — only `color-scheme` follows.
93
+ const variants = (['light', 'dark'] as const).map((scheme) => {
94
+ const declarations = [
95
+ ...(explicitBackground ? [] : [`background-color:${themeColor[scheme]}`]),
96
+ ...(colorScheme === false ? [] : [`color-scheme:${scheme}`]),
97
+ ]
98
+ if (declarations.length === 0) return ''
99
+ return `${BOOT_SCOPE}[${BOOT_ATTRIBUTE}=${scheme}]{${declarations.join(';')}}`
100
+ })
101
+ return base + variants.join('')
102
+ }
103
+
104
+ /** The boot `<style>`, then (unless `bootScript: false`) the script — adjacent, head-prepend. */
105
+ export function buildBootTags(input: BootInput): HtmlTagDescriptor[] {
106
+ const tags: HtmlTagDescriptor[] = [{ tag: 'style', children: buildBootStyle(input) }]
107
+ if (input.bootScript) tags.push({ tag: 'script', children: BOOT_SCRIPT })
108
+ return tags
109
+ }