@contentbit/studio 0.4.0 → 0.4.2

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 (35) hide show
  1. package/LICENSE +21 -0
  2. package/components.json +25 -0
  3. package/dist/client/assets/{api-C-Xwc2aB.js → api-MWiK2l_P.js} +1 -1
  4. package/dist/client/assets/{document-Yk8nlK-k.js → document-w62o-wDp.js} +1 -1
  5. package/dist/client/assets/{index-BwvfKCmy.js → index-DTXIZgkK.js} +2 -2
  6. package/dist/client/assets/{routes-DHIbdBYB.js → routes-Dg9spe-7.js} +1 -1
  7. package/dist/client/assets/{styles-BGHadX26.css → styles-DxZJz8Oi.css} +1 -1
  8. package/dist/server/assets/_tanstack-start-manifest_v-wPlN1Hjy.js +25 -0
  9. package/dist/server/assets/{router-D3JhQdql.js → router-D4DnWGjU.js} +1 -1
  10. package/dist/server/index.d.ts.map +1 -1
  11. package/dist/server/index.js +13 -2
  12. package/dist/server/server.js +2 -2
  13. package/package.json +23 -18
  14. package/public/favicon.ico +0 -0
  15. package/public/manifest.json +25 -0
  16. package/public/robots.txt +3 -0
  17. package/src/components/ui/button.tsx +67 -0
  18. package/src/lib/api.ts +22 -0
  19. package/src/lib/utils.ts +6 -0
  20. package/src/logo.svg +12 -0
  21. package/src/routeTree.gen.ts +86 -0
  22. package/src/router.tsx +20 -0
  23. package/src/routes/__root.tsx +48 -0
  24. package/src/routes/document.tsx +268 -0
  25. package/src/routes/index.tsx +465 -0
  26. package/src/server/api.ts +58 -0
  27. package/src/server/index.ts +151 -0
  28. package/src/server/preview.ts +46 -0
  29. package/src/server/scan.test.ts +283 -0
  30. package/src/server/scan.ts +460 -0
  31. package/src/server/types.ts +109 -0
  32. package/src/styles.css +222 -0
  33. package/tsconfig.json +27 -0
  34. package/vite.config.ts +16 -0
  35. package/dist/server/assets/_tanstack-start-manifest_v-Djlrg1a7.js +0 -25
@@ -0,0 +1,465 @@
1
+ import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
2
+ import {
3
+ AlertTriangle,
4
+ ArrowRight,
5
+ Blocks,
6
+ FileText,
7
+ Filter,
8
+ Link2,
9
+ RefreshCw,
10
+ Search,
11
+ ChevronsUpDown,
12
+ } from 'lucide-react'
13
+ import type { ReactNode } from 'react'
14
+ import { useEffect, useMemo, useState } from 'react'
15
+
16
+ import { Button } from '@/components/ui/button'
17
+ import { fetchGraph, fetchProject } from '@/lib/api'
18
+ import type { StudioFileSummary, StudioGraph, StudioProject, StudioStatus } from '@/server/types'
19
+
20
+ type StatusFilter = 'all' | StudioStatus
21
+ type SortKey = 'document' | 'status' | 'blocks' | 'keywords' | 'findings'
22
+ type SortDir = 'asc' | 'desc'
23
+
24
+ interface DashboardSearch {
25
+ q: string
26
+ status: StatusFilter
27
+ sort: SortKey
28
+ dir: SortDir
29
+ }
30
+
31
+ export const Route = createFileRoute('/')({
32
+ validateSearch: (search: Record<string, unknown>): DashboardSearch => ({
33
+ q: typeof search.q === 'string' ? search.q : '',
34
+ status: isStatus(search.status) ? search.status : 'all',
35
+ sort: isSortKey(search.sort) ? search.sort : 'status',
36
+ dir: search.dir === 'asc' || search.dir === 'desc' ? search.dir : 'asc',
37
+ }),
38
+ component: Dashboard,
39
+ })
40
+
41
+ function Dashboard() {
42
+ const search = Route.useSearch()
43
+ const navigate = useNavigate({ from: '/' })
44
+ const [project, setProject] = useState<StudioProject | null>(null)
45
+ const [graph, setGraph] = useState<StudioGraph | null>(null)
46
+ const [error, setError] = useState<string | null>(null)
47
+ const [refreshing, setRefreshing] = useState(false)
48
+
49
+ async function refresh() {
50
+ setRefreshing(true)
51
+ setError(null)
52
+ try {
53
+ const [project, graph] = await Promise.all([fetchProject(), fetchGraph()])
54
+ setProject(project)
55
+ setGraph(graph)
56
+ } catch (err) {
57
+ setError(err instanceof Error ? err.message : String(err))
58
+ } finally {
59
+ setRefreshing(false)
60
+ }
61
+ }
62
+
63
+ useEffect(() => {
64
+ void refresh()
65
+ }, [])
66
+
67
+ const files = useMemo(() => {
68
+ if (!project) return []
69
+ const query = search.q.toLowerCase().trim()
70
+ return project.files
71
+ .filter((file) => {
72
+ const haystack = [
73
+ file.relativePath,
74
+ file.title,
75
+ file.slug,
76
+ file.key,
77
+ file.locale,
78
+ file.keywords?.primary,
79
+ ...(file.keywords?.secondary ?? []),
80
+ ]
81
+ .filter(Boolean)
82
+ .join(' ')
83
+ .toLowerCase()
84
+ return (
85
+ (search.status === 'all' || file.status === search.status) && haystack.includes(query)
86
+ )
87
+ })
88
+ .sort((a, b) => compareFiles(a, b, search.sort, search.dir))
89
+ }, [project, search.dir, search.q, search.sort, search.status])
90
+
91
+ function setSearch(next: Partial<DashboardSearch>) {
92
+ void navigate({ to: '/', search: (prev) => ({ ...prev, ...next }) })
93
+ }
94
+
95
+ function setSort(sort: SortKey) {
96
+ setSearch({ sort, dir: search.sort === sort && search.dir === 'asc' ? 'desc' : 'asc' })
97
+ }
98
+
99
+ return (
100
+ <main className="min-h-svh bg-background text-foreground">
101
+ <section className="border-b bg-muted/30">
102
+ <div className="mx-auto flex max-w-7xl flex-col gap-6 px-5 py-6">
103
+ <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
104
+ <div>
105
+ <p className="font-mono text-xs uppercase text-muted-foreground">contentbit studio</p>
106
+ <h1 className="mt-1 text-3xl font-semibold tracking-tight">Content dashboard</h1>
107
+ <p className="mt-2 max-w-2xl text-sm text-muted-foreground">
108
+ Read-only view of content health, structure, links, keywords, and previews.
109
+ </p>
110
+ </div>
111
+ <Button onClick={refresh} disabled={refreshing} className="w-fit gap-2">
112
+ <RefreshCw className={refreshing ? 'size-4 animate-spin' : 'size-4'} />
113
+ Refresh
114
+ </Button>
115
+ </div>
116
+
117
+ {project && (
118
+ <div className="grid gap-px overflow-hidden rounded-sm border bg-border md:grid-cols-4">
119
+ <Metric
120
+ label="files"
121
+ value={project.summary.files}
122
+ icon={<FileText className="size-4" />}
123
+ />
124
+ <Metric
125
+ label="findings"
126
+ value={
127
+ project.summary.errors + project.summary.warnings + project.summary.suggestions
128
+ }
129
+ icon={<AlertTriangle className="size-4" />}
130
+ tone={
131
+ project.summary.errors > 0 ? 'bad' : project.summary.warnings > 0 ? 'warn' : 'ok'
132
+ }
133
+ />
134
+ <Metric
135
+ label="blocks"
136
+ value={project.summary.blocks}
137
+ icon={<Blocks className="size-4" />}
138
+ />
139
+ <Metric
140
+ label="graph"
141
+ value={
142
+ project.linkGraph
143
+ ? `${project.linkGraph.pages}/${project.linkGraph.links}`
144
+ : 'off'
145
+ }
146
+ icon={<Link2 className="size-4" />}
147
+ />
148
+ </div>
149
+ )}
150
+ </div>
151
+ </section>
152
+
153
+ <section className="mx-auto grid max-w-7xl gap-5 px-5 py-5 lg:grid-cols-[minmax(0,1fr)_320px]">
154
+ <div className="min-w-0">
155
+ <div className="mb-3 flex flex-col gap-2 md:flex-row">
156
+ <label className="relative flex min-w-0 flex-1 items-center">
157
+ <Search className="pointer-events-none absolute left-3 size-4 text-muted-foreground" />
158
+ <input
159
+ value={search.q}
160
+ onChange={(event) => setSearch({ q: event.target.value })}
161
+ placeholder="Search path, title, slug, keyword..."
162
+ className="h-10 w-full border bg-background pl-9 pr-3 text-sm outline-none transition-colors focus:border-foreground"
163
+ />
164
+ </label>
165
+ <div className="flex items-center gap-1 border bg-background p-1">
166
+ <Filter className="mx-2 size-4 text-muted-foreground" />
167
+ {(['all', 'error', 'warning', 'suggestion', 'healthy'] as const).map((status) => (
168
+ <button
169
+ key={status}
170
+ onClick={() => setSearch({ status })}
171
+ className={
172
+ search.status === status
173
+ ? 'bg-foreground px-2.5 py-1.5 text-xs font-medium text-background'
174
+ : 'px-2.5 py-1.5 text-xs text-muted-foreground hover:text-foreground'
175
+ }
176
+ >
177
+ {status}
178
+ </button>
179
+ ))}
180
+ </div>
181
+ </div>
182
+
183
+ <div className="overflow-hidden border">
184
+ <div className="grid grid-cols-[1.4fr_0.6fr_0.6fr_0.6fr_2rem] gap-px border-b bg-border text-xs font-medium uppercase text-muted-foreground">
185
+ <SortHeader
186
+ label="Document"
187
+ active={search.sort === 'document'}
188
+ onClick={() => setSort('document')}
189
+ />
190
+ <SortHeader
191
+ label="Status"
192
+ active={search.sort === 'status'}
193
+ onClick={() => setSort('status')}
194
+ />
195
+ <SortHeader
196
+ label="Blocks"
197
+ active={search.sort === 'blocks'}
198
+ onClick={() => setSort('blocks')}
199
+ />
200
+ <SortHeader
201
+ label="Keywords"
202
+ active={search.sort === 'keywords'}
203
+ onClick={() => setSort('keywords')}
204
+ />
205
+ <div className="bg-muted/50 px-2 py-2" />
206
+ </div>
207
+ {error ? (
208
+ <div className="p-4 text-sm text-destructive">{error}</div>
209
+ ) : project ? (
210
+ <div className="divide-y">
211
+ {files.map((file) => (
212
+ <FileRow key={file.path} file={file} />
213
+ ))}
214
+ {files.length === 0 && (
215
+ <div className="p-4 text-sm text-muted-foreground">
216
+ No documents match the current filters.
217
+ </div>
218
+ )}
219
+ </div>
220
+ ) : (
221
+ <div className="p-4 text-sm text-muted-foreground">Scanning content...</div>
222
+ )}
223
+ </div>
224
+ </div>
225
+
226
+ <aside className="flex flex-col gap-4">
227
+ <Panel title="Link graph">
228
+ {project?.linkGraph ? (
229
+ <div className="grid grid-cols-3 gap-px overflow-hidden border bg-border text-center">
230
+ <TinyMetric value={project.linkGraph.pages} label="pages" />
231
+ <TinyMetric value={project.linkGraph.links} label="links" />
232
+ <TinyMetric value={project.linkGraph.orphans} label="orphans" />
233
+ </div>
234
+ ) : (
235
+ <p className="text-sm text-muted-foreground">No slug frontmatter detected.</p>
236
+ )}
237
+ {graph && graph.edges.length > 0 && (
238
+ <ul className="mt-3 flex max-h-56 flex-col gap-2 overflow-auto text-xs">
239
+ {graph.edges.slice(0, 12).map((edge, index) => (
240
+ <li
241
+ key={`${edge.from}-${edge.target}-${index}`}
242
+ className="flex items-center gap-2"
243
+ >
244
+ <span
245
+ className={
246
+ edge.status === 'unresolved' ? 'text-destructive' : 'text-muted-foreground'
247
+ }
248
+ >
249
+ {edge.status}
250
+ </span>
251
+ <span className="truncate">{edge.target}</span>
252
+ </li>
253
+ ))}
254
+ </ul>
255
+ )}
256
+ </Panel>
257
+
258
+ <Panel title="Block usage">
259
+ {project && Object.keys(project.blockUsage).length > 0 ? (
260
+ <div className="flex flex-wrap gap-1">
261
+ {Object.entries(project.blockUsage).map(([name, count]) => (
262
+ <span key={name} className="border bg-muted px-2 py-1 font-mono text-xs">
263
+ {name} x{count}
264
+ </span>
265
+ ))}
266
+ </div>
267
+ ) : (
268
+ <p className="text-sm text-muted-foreground">No blocks found yet.</p>
269
+ )}
270
+ </Panel>
271
+
272
+ <Panel title="Keyword coverage">
273
+ {project && (
274
+ <div className="space-y-2 text-sm">
275
+ <Coverage
276
+ label="primary"
277
+ value={project.keywordCoverage.withPrimary}
278
+ total={project.keywordCoverage.total}
279
+ />
280
+ <Coverage
281
+ label="secondary"
282
+ value={project.keywordCoverage.withSecondary}
283
+ total={project.keywordCoverage.total}
284
+ />
285
+ </div>
286
+ )}
287
+ </Panel>
288
+ </aside>
289
+ </section>
290
+ </main>
291
+ )
292
+ }
293
+
294
+ function FileRow({ file }: { file: StudioFileSummary }) {
295
+ return (
296
+ <Link
297
+ to="/document"
298
+ search={{ path: file.path }}
299
+ className="grid grid-cols-[1.4fr_0.6fr_0.6fr_0.6fr_2rem] gap-px bg-border text-sm transition-colors hover:bg-foreground/20"
300
+ >
301
+ <div className="min-w-0 bg-background px-3 py-3">
302
+ <p className="truncate font-medium">{file.title}</p>
303
+ <p className="truncate font-mono text-xs text-muted-foreground">{file.relativePath}</p>
304
+ </div>
305
+ <div className="bg-background px-3 py-3">
306
+ <StatusBadge status={file.status} />
307
+ </div>
308
+ <div className="bg-background px-3 py-3 font-mono text-xs">{file.blocks}</div>
309
+ <div className="bg-background px-3 py-3 text-xs text-muted-foreground">
310
+ {file.keywords?.primary ? 'primary' : 'missing'}
311
+ </div>
312
+ <div className="flex items-center justify-center bg-background px-2 py-3">
313
+ <ArrowRight className="size-4 text-muted-foreground" />
314
+ </div>
315
+ </Link>
316
+ )
317
+ }
318
+
319
+ function Metric({
320
+ label,
321
+ value,
322
+ icon,
323
+ tone,
324
+ }: {
325
+ label: string
326
+ value: number | string
327
+ icon: ReactNode
328
+ tone?: 'bad' | 'warn' | 'ok'
329
+ }) {
330
+ const color =
331
+ tone === 'bad'
332
+ ? 'text-destructive'
333
+ : tone === 'warn'
334
+ ? 'text-amber-600'
335
+ : tone === 'ok'
336
+ ? 'text-emerald-600'
337
+ : 'text-foreground'
338
+ return (
339
+ <div className="bg-background p-4">
340
+ <div className="mb-3 flex items-center justify-between text-muted-foreground">
341
+ <span className="text-xs uppercase">{label}</span>
342
+ {icon}
343
+ </div>
344
+ <div className={`font-mono text-3xl font-semibold ${color}`}>{value}</div>
345
+ </div>
346
+ )
347
+ }
348
+
349
+ function TinyMetric({ value, label }: { value: number | string; label: string }) {
350
+ return (
351
+ <div className="bg-background px-2 py-2">
352
+ <div className="font-mono text-lg font-semibold">{value}</div>
353
+ <div className="text-[0.65rem] uppercase text-muted-foreground">{label}</div>
354
+ </div>
355
+ )
356
+ }
357
+
358
+ function Panel({ title, children }: { title: string; children: ReactNode }) {
359
+ return (
360
+ <section className="border bg-background p-4">
361
+ <h2 className="mb-3 text-sm font-semibold">{title}</h2>
362
+ {children}
363
+ </section>
364
+ )
365
+ }
366
+
367
+ function Coverage({ label, value, total }: { label: string; value: number; total: number }) {
368
+ const pct = total === 0 ? 0 : Math.round((value / total) * 100)
369
+ return (
370
+ <div>
371
+ <div className="mb-1 flex justify-between text-xs">
372
+ <span className="text-muted-foreground">{label}</span>
373
+ <span className="font-mono">{pct}%</span>
374
+ </div>
375
+ <div className="h-2 bg-muted">
376
+ <div className="h-full bg-foreground" style={{ width: `${pct}%` }} />
377
+ </div>
378
+ </div>
379
+ )
380
+ }
381
+
382
+ function StatusBadge({ status }: { status: StudioStatus }) {
383
+ const cls =
384
+ status === 'error'
385
+ ? 'border-destructive/40 bg-destructive/10 text-destructive'
386
+ : status === 'warning'
387
+ ? 'border-amber-500/40 bg-amber-500/10 text-amber-700'
388
+ : status === 'suggestion'
389
+ ? 'border-blue-500/40 bg-blue-500/10 text-blue-700'
390
+ : 'border-emerald-500/40 bg-emerald-500/10 text-emerald-700'
391
+ return <span className={`inline-flex border px-2 py-0.5 text-xs ${cls}`}>{status}</span>
392
+ }
393
+
394
+ function isStatus(value: unknown): value is StatusFilter {
395
+ return (
396
+ value === 'all' ||
397
+ value === 'error' ||
398
+ value === 'warning' ||
399
+ value === 'suggestion' ||
400
+ value === 'healthy'
401
+ )
402
+ }
403
+
404
+ function SortHeader({
405
+ label,
406
+ active,
407
+ onClick,
408
+ }: {
409
+ label: string
410
+ active: boolean
411
+ onClick(): void
412
+ }) {
413
+ return (
414
+ <button
415
+ className={
416
+ active
417
+ ? 'flex items-center gap-1 bg-muted px-3 py-2 text-foreground'
418
+ : 'flex items-center gap-1 bg-muted/50 px-3 py-2 hover:text-foreground'
419
+ }
420
+ onClick={onClick}
421
+ >
422
+ {label}
423
+ <ChevronsUpDown className="size-3" />
424
+ </button>
425
+ )
426
+ }
427
+
428
+ function compareFiles(a: StudioFileSummary, b: StudioFileSummary, sort: SortKey, dir: SortDir) {
429
+ const direction = dir === 'asc' ? 1 : -1
430
+ const statusOrder: Record<StudioStatus, number> = {
431
+ error: 0,
432
+ warning: 1,
433
+ suggestion: 2,
434
+ healthy: 3,
435
+ }
436
+ const result =
437
+ sort === 'status'
438
+ ? statusOrder[a.status] - statusOrder[b.status]
439
+ : sort === 'blocks'
440
+ ? a.blocks - b.blocks
441
+ : sort === 'keywords'
442
+ ? keywordScore(a) - keywordScore(b)
443
+ : sort === 'findings'
444
+ ? findingScore(a) - findingScore(b)
445
+ : a.relativePath.localeCompare(b.relativePath)
446
+ return (result || a.relativePath.localeCompare(b.relativePath)) * direction
447
+ }
448
+
449
+ function keywordScore(file: StudioFileSummary): number {
450
+ return (file.keywords?.primary ? 1 : 0) + (file.keywords?.secondary?.length ? 1 : 0)
451
+ }
452
+
453
+ function findingScore(file: StudioFileSummary): number {
454
+ return file.findings.errors * 100 + file.findings.warnings * 10 + file.findings.suggestions
455
+ }
456
+
457
+ function isSortKey(value: unknown): value is SortKey {
458
+ return (
459
+ value === 'document' ||
460
+ value === 'status' ||
461
+ value === 'blocks' ||
462
+ value === 'keywords' ||
463
+ value === 'findings'
464
+ )
465
+ }
@@ -0,0 +1,58 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http'
2
+
3
+ import { scanDocument, scanGraph, scanProject } from './scan.js'
4
+ import type { StudioOptions } from './types.js'
5
+
6
+ export async function handleStudioApiRequest(
7
+ options: StudioOptions,
8
+ req: IncomingMessage,
9
+ res: ServerResponse,
10
+ ): Promise<boolean> {
11
+ if (!req.url) return false
12
+ const url = new URL(req.url, 'http://contentbit.local')
13
+ if (!url.pathname.startsWith('/api/')) return false
14
+
15
+ try {
16
+ if (req.method !== 'GET') {
17
+ sendJson(res, 405, { error: 'Studio API is read-only.' })
18
+ return true
19
+ }
20
+
21
+ if (url.pathname === '/api/project') {
22
+ sendJson(res, 200, await scanProject(options))
23
+ return true
24
+ }
25
+
26
+ if (url.pathname === '/api/graph') {
27
+ sendJson(res, 200, await scanGraph(options))
28
+ return true
29
+ }
30
+
31
+ if (url.pathname === '/api/document') {
32
+ const path = url.searchParams.get('path')
33
+ if (!path) {
34
+ sendJson(res, 400, { error: 'Missing ?path=' })
35
+ return true
36
+ }
37
+ const document = await scanDocument(options, path)
38
+ if (!document) {
39
+ sendJson(res, 404, { error: 'Document is not in the configured content set.' })
40
+ return true
41
+ }
42
+ sendJson(res, 200, document)
43
+ return true
44
+ }
45
+
46
+ sendJson(res, 404, { error: 'Unknown Studio API route.' })
47
+ return true
48
+ } catch (err) {
49
+ sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) })
50
+ return true
51
+ }
52
+ }
53
+
54
+ function sendJson(res: ServerResponse, status: number, body: unknown): void {
55
+ res.statusCode = status
56
+ res.setHeader('content-type', 'application/json; charset=utf-8')
57
+ res.end(JSON.stringify(body, null, 2))
58
+ }
@@ -0,0 +1,151 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { createServer, searchForWorkspaceRoot, type Plugin, type ViteDevServer } from 'vite'
6
+ import type { BlockComponent } from '@contentbit/react'
7
+
8
+ import { handleStudioApiRequest } from './api.js'
9
+ import type { StartStudioOptions, StudioOptions } from './types.js'
10
+
11
+ export type {
12
+ StartStudioOptions,
13
+ StudioDocument,
14
+ StudioFileSummary,
15
+ StudioFinding,
16
+ StudioGraph,
17
+ StudioProject,
18
+ } from './types.js'
19
+ export { scanDocument, scanGraph, scanProject } from './scan.js'
20
+
21
+ export interface StudioServer {
22
+ url: string
23
+ close(): Promise<void>
24
+ closed: Promise<void>
25
+ vite: ViteDevServer
26
+ }
27
+
28
+ export async function startStudio(options: StartStudioOptions): Promise<StudioServer> {
29
+ const root = findPackageRoot()
30
+ const host = options.host ?? '127.0.0.1'
31
+ const port = options.port ?? 4377
32
+ const cwd = options.cwd ?? process.cwd()
33
+ // Vite serves only files under `fs.allow`. We need:
34
+ // - `root`: the Studio package itself (its built UI and source).
35
+ // - `searchForWorkspaceRoot(root)`: the workspace that hoists Studio's deps,
36
+ // so packaged fonts and other Vite-served dependency assets resolve when
37
+ // Studio is installed into a monorepo.
38
+ // - `cwd`: the consuming project, so Studio can read its content/blocks.
39
+ // We deliberately do NOT add `searchForWorkspaceRoot(cwd)`: in a project with
40
+ // no workspace marker, Vite walks up past the git root to the nearest ancestor
41
+ // `package.json`, which can expose an unexpectedly broad directory over HTTP
42
+ // (notably with `--host`).
43
+ const fsAllow = [...new Set([root, searchForWorkspaceRoot(root), cwd])]
44
+ const apiOptions: StudioOptions = {
45
+ globs: options.globs,
46
+ cwd,
47
+ registryPath: options.registryPath,
48
+ linkOptions: options.linkOptions,
49
+ minSectionWords: options.minSectionWords,
50
+ }
51
+
52
+ const vite = await createServer({
53
+ root,
54
+ configFile: join(root, 'vite.config.ts'),
55
+ plugins: [studioApiPlugin(apiOptions)],
56
+ server: {
57
+ host,
58
+ port,
59
+ strictPort: options.port !== undefined && options.port !== 0,
60
+ open: false,
61
+ fs: {
62
+ allow: fsAllow,
63
+ },
64
+ },
65
+ })
66
+ apiOptions.previewComponents = () =>
67
+ loadProjectComponents(vite, { cwd, registryPath: options.registryPath })
68
+
69
+ await vite.listen()
70
+ const address = vite.httpServer?.address()
71
+ const resolvedPort = typeof address === 'object' && address ? address.port : port
72
+ const url = `http://${host}:${resolvedPort}/`
73
+ if (options.open !== false) openBrowser(url)
74
+
75
+ return {
76
+ url,
77
+ vite,
78
+ close: () => vite.close(),
79
+ closed: new Promise((resolve) => {
80
+ vite.httpServer?.once('close', () => resolve())
81
+ }),
82
+ }
83
+ }
84
+
85
+ async function loadProjectComponents(
86
+ vite: ViteDevServer,
87
+ options: { cwd: string; registryPath?: string },
88
+ ): Promise<Record<string, BlockComponent> | undefined> {
89
+ for (const candidate of componentCandidates(options)) {
90
+ if (!existsSync(candidate)) continue
91
+ const mod = (await vite.ssrLoadModule(candidate)) as {
92
+ blockComponents?: Record<string, BlockComponent>
93
+ components?: Record<string, BlockComponent>
94
+ default?: Record<string, BlockComponent>
95
+ }
96
+ const components = mod.blockComponents ?? mod.components ?? mod.default
97
+ if (components && typeof components === 'object') return components
98
+ }
99
+ return undefined
100
+ }
101
+
102
+ function componentCandidates(options: { cwd: string; registryPath?: string }): string[] {
103
+ const dirs = new Set<string>()
104
+ if (options.registryPath) {
105
+ const registryPath = isAbsolute(options.registryPath)
106
+ ? options.registryPath
107
+ : resolve(options.cwd, options.registryPath)
108
+ dirs.add(dirname(registryPath))
109
+ }
110
+ dirs.add(join(options.cwd, 'blocks'))
111
+
112
+ return [...dirs].flatMap((dir) => [
113
+ join(dir, 'components.tsx'),
114
+ join(dir, 'components.ts'),
115
+ join(dir, 'preview.tsx'),
116
+ join(dir, 'preview.ts'),
117
+ join(dir, 'renderers.tsx'),
118
+ join(dir, 'renderers.ts'),
119
+ ])
120
+ }
121
+
122
+ function studioApiPlugin(options: StudioOptions): Plugin {
123
+ return {
124
+ name: 'contentbit-studio-api',
125
+ configureServer(server) {
126
+ server.middlewares.use((req, res, next) => {
127
+ void handleStudioApiRequest(options, req, res).then((handled) => {
128
+ if (!handled) next()
129
+ })
130
+ })
131
+ },
132
+ }
133
+ }
134
+
135
+ function findPackageRoot(): string {
136
+ let dir = dirname(fileURLToPath(import.meta.url))
137
+ for (;;) {
138
+ if (existsSync(join(dir, 'package.json'))) return dir
139
+ const next = dirname(dir)
140
+ if (next === dir) throw new Error('Could not locate @contentbit/studio package root.')
141
+ dir = next
142
+ }
143
+ }
144
+
145
+ function openBrowser(url: string): void {
146
+ const command =
147
+ process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open'
148
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]
149
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' })
150
+ child.unref()
151
+ }