@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,460 @@
1
+ import { genericBlocks } from '@contentbit/blocks'
2
+ import {
3
+ analyzeDocument,
4
+ buildLinkIndex,
5
+ createBlockRegistry,
6
+ extractFrontmatter,
7
+ parseDocument,
8
+ stripFrontmatter,
9
+ validateDocument,
10
+ validateLinks,
11
+ type BlockDefinition,
12
+ type BlockRegistry,
13
+ type Diagnostic,
14
+ type LinkInput,
15
+ } from '@contentbit/core'
16
+ import { readFile } from 'node:fs/promises'
17
+ import { basename, isAbsolute, join, relative } from 'node:path'
18
+ import { pathToFileURL } from 'node:url'
19
+ import { glob } from 'tinyglobby'
20
+
21
+ import { renderStudioPreview } from './preview.js'
22
+ import type {
23
+ StudioDocument,
24
+ StudioFileSummary,
25
+ StudioFinding,
26
+ StudioGraph,
27
+ StudioGraphEdge,
28
+ StudioGraphNode,
29
+ StudioKeywordData,
30
+ StudioOptions,
31
+ StudioProject,
32
+ StudioStatus,
33
+ } from './types.js'
34
+
35
+ const DEFAULT_MIN_SECTION_WORDS = 25
36
+ const BLOCKLESS_WORDS = 250
37
+
38
+ interface ScanContext {
39
+ files: string[]
40
+ registry: BlockRegistry
41
+ sources: Map<string, string>
42
+ frontmatter: Map<string, Record<string, unknown>>
43
+ findings: StudioFinding[]
44
+ summaries: StudioFileSummary[]
45
+ linkInputs: LinkInput[]
46
+ index?: ReturnType<typeof buildLinkIndex>
47
+ }
48
+
49
+ export async function scanProject(options: StudioOptions): Promise<StudioProject> {
50
+ const context = await scanContext(options)
51
+ const blockUsage: Record<string, number> = {}
52
+ let words = 0
53
+ let blocks = 0
54
+ let links = 0
55
+ let missingAlt = 0
56
+ let withPrimary = 0
57
+ let withSecondary = 0
58
+
59
+ for (const file of context.summaries) {
60
+ words += file.words
61
+ blocks += file.blocks
62
+ links += file.links
63
+ missingAlt += file.missingAlt
64
+ if (file.keywords?.primary) withPrimary++
65
+ if ((file.keywords?.secondary?.length ?? 0) > 0) withSecondary++
66
+ for (const [name, count] of Object.entries(file.blockNames)) {
67
+ blockUsage[name] = (blockUsage[name] ?? 0) + count
68
+ }
69
+ }
70
+
71
+ const summary = summarize(context.findings)
72
+ return {
73
+ root: options.cwd ?? process.cwd(),
74
+ files: context.summaries,
75
+ summary: {
76
+ files: context.summaries.length,
77
+ errors: summary.errors,
78
+ warnings: summary.warnings,
79
+ suggestions: summary.suggestions,
80
+ words,
81
+ blocks,
82
+ links,
83
+ missingAlt,
84
+ },
85
+ blockUsage,
86
+ keywordCoverage: {
87
+ total: context.summaries.length,
88
+ withPrimary,
89
+ withSecondary,
90
+ },
91
+ ...(context.index ? { linkGraph: graphSummary(context.index) } : {}),
92
+ findings: context.findings,
93
+ }
94
+ }
95
+
96
+ export async function scanDocument(
97
+ options: StudioOptions,
98
+ requestedPath: string,
99
+ ): Promise<StudioDocument | null> {
100
+ const context = await scanContext(options)
101
+ const file = findAllowedFile(context, options.cwd ?? process.cwd(), requestedPath)
102
+ if (!file) return null
103
+ const source = context.sources.get(file)!
104
+ const summary = context.summaries.find((item) => item.path === file)
105
+ if (!summary) return null
106
+
107
+ const validation = validateDocument(parseDocument(stripFrontmatter(source)), context.registry)
108
+ const previewHtml = renderStudioPreview(
109
+ validation.document,
110
+ (await options.previewComponents?.()) ?? {},
111
+ )
112
+ const stats = analyzeDocument(source, { path: file })
113
+ const page = context.index
114
+ ? [...context.index.pages.values()].find((entry) => entry.path === file)
115
+ : undefined
116
+
117
+ return {
118
+ file: summary,
119
+ source,
120
+ frontmatter: context.frontmatter.get(file) ?? {},
121
+ stats,
122
+ findings: context.findings.filter((finding) => finding.file === file),
123
+ linksTo: page ? (page.linkRefs.length > 0 ? page.linkRefs : page.linksTo) : [],
124
+ linkedFrom: page
125
+ ? page.linkedFromRefs.length > 0
126
+ ? page.linkedFromRefs
127
+ : page.linkedFrom
128
+ : [],
129
+ previewHtml,
130
+ }
131
+ }
132
+
133
+ export async function scanGraph(options: StudioOptions): Promise<StudioGraph> {
134
+ const context = await scanContext(options)
135
+ if (!context.index) return { nodes: [], edges: [] }
136
+
137
+ const summaryByPath = new Map(context.summaries.map((summary) => [summary.path, summary]))
138
+ const nodes: StudioGraphNode[] = [...context.index.pages.values()].map((page) => ({
139
+ id: pageIdentity(page),
140
+ label: page.title ?? page.slug,
141
+ path: page.path,
142
+ status: summaryByPath.get(page.path)?.status ?? 'healthy',
143
+ slug: page.slug,
144
+ ...(page.key ? { key: page.key } : {}),
145
+ ...(page.locale ? { locale: page.locale } : {}),
146
+ }))
147
+
148
+ const pageByPath = new Map([...context.index.pages.values()].map((page) => [page.path, page]))
149
+ const edges: StudioGraphEdge[] = []
150
+ for (const page of context.index.pages.values()) {
151
+ for (const ref of page.linkRefs) {
152
+ const target = [...context.index.pages.values()].find(
153
+ (candidate) =>
154
+ candidate.slug === ref.slug &&
155
+ candidate.key === ref.key &&
156
+ candidate.locale === ref.locale,
157
+ )
158
+ edges.push({
159
+ from: pageIdentity(page),
160
+ to: target ? pageIdentity(target) : undefined,
161
+ target: ref.target ?? ref.key ?? ref.slug,
162
+ status:
163
+ target === page
164
+ ? 'self'
165
+ : ref.locale && ref.locale !== page.locale
166
+ ? 'cross-locale'
167
+ : 'resolved',
168
+ })
169
+ }
170
+ }
171
+
172
+ for (const finding of context.findings) {
173
+ if (finding.source !== 'links') continue
174
+ if (finding.code !== 'CB_LINK_UNRESOLVED' && finding.code !== 'CB_LINK_LOCALE_MISSING') continue
175
+ const page = pageByPath.get(finding.file)
176
+ if (!page) continue
177
+ edges.push({
178
+ from: pageIdentity(page),
179
+ target: targetFromMessage(finding.message) ?? 'unresolved',
180
+ status: 'unresolved',
181
+ })
182
+ }
183
+
184
+ return { nodes, edges }
185
+ }
186
+
187
+ async function scanContext(options: StudioOptions): Promise<ScanContext> {
188
+ if (options.globs.length === 0) throw new Error('studio: provide at least one file or glob.')
189
+ const cwd = options.cwd ?? process.cwd()
190
+ const files = (await glob(options.globs, { absolute: true, cwd })).sort()
191
+ if (files.length === 0) throw new Error(`studio: no files matched ${options.globs.join(' ')}`)
192
+
193
+ const registry = await loadStudioRegistry(options.registryPath, cwd)
194
+ const sources = new Map<string, string>()
195
+ const frontmatter = new Map<string, Record<string, unknown>>()
196
+ const findings: StudioFinding[] = []
197
+ const summaries: StudioFileSummary[] = []
198
+ const linkInputs: LinkInput[] = []
199
+
200
+ for (const file of files) {
201
+ const source = await readFile(file, 'utf8')
202
+ const fm = extractFrontmatter(source)?.data ?? {}
203
+ sources.set(file, source)
204
+ frontmatter.set(file, fm)
205
+ linkInputs.push({ path: file, data: fm })
206
+
207
+ const validation = validateDocument(parseDocument(stripFrontmatter(source)), registry)
208
+ for (const diagnostic of validation.diagnostics) {
209
+ findings.push(findingFromDiagnostic('validation', file, cwd, diagnostic))
210
+ }
211
+
212
+ const stats = analyzeDocument(source, { path: file })
213
+ findings.push(
214
+ ...statsFindings(file, cwd, stats, options.minSectionWords ?? DEFAULT_MIN_SECTION_WORDS),
215
+ )
216
+ summaries.push(
217
+ fileSummary(
218
+ file,
219
+ cwd,
220
+ fm,
221
+ stats,
222
+ findings.filter((finding) => finding.file === file),
223
+ options,
224
+ ),
225
+ )
226
+ }
227
+
228
+ let index: ScanContext['index']
229
+ if (hasLinkFrontmatter(linkInputs, options.linkOptions?.slugField)) {
230
+ for (const { file, diagnostic } of validateLinks(linkInputs, options.linkOptions)) {
231
+ findings.push(findingFromDiagnostic('links', file, cwd, diagnostic))
232
+ }
233
+ index = buildLinkIndex(linkInputs, options.linkOptions)
234
+ refreshSummaryFindings(summaries, findings)
235
+ }
236
+
237
+ findings.sort(compareFindings)
238
+ return { files, registry, sources, frontmatter, findings, summaries, linkInputs, index }
239
+ }
240
+
241
+ async function loadStudioRegistry(
242
+ registryPath?: string,
243
+ cwd = process.cwd(),
244
+ ): Promise<BlockRegistry> {
245
+ const registry = createBlockRegistry().use(genericBlocks())
246
+ if (!registryPath) return registry
247
+
248
+ const resolvedPath = isAbsolute(registryPath) ? registryPath : join(cwd, registryPath)
249
+ const mod = (await import(pathToFileURL(resolvedPath).href)) as {
250
+ default?: BlockDefinition<unknown>[]
251
+ }
252
+ if (!Array.isArray(mod.default)) {
253
+ throw new Error(
254
+ `--registry module must default-export an array of block definitions: ${resolvedPath}`,
255
+ )
256
+ }
257
+ registry.use(mod.default)
258
+ return registry
259
+ }
260
+
261
+ function statsFindings(
262
+ file: string,
263
+ cwd: string,
264
+ stats: ReturnType<typeof analyzeDocument>,
265
+ minSectionWords: number,
266
+ ): StudioFinding[] {
267
+ const findings: StudioFinding[] = []
268
+ for (const section of stats.outline) {
269
+ if (section.words < minSectionWords) {
270
+ findings.push({
271
+ severity: 'info',
272
+ source: 'stats',
273
+ code: 'CB_THIN_SECTION',
274
+ file,
275
+ relativePath: relativePath(cwd, file),
276
+ line: section.line,
277
+ column: 1,
278
+ message: `section "${section.text}" has ${section.words} words`,
279
+ hint: `Add detail or merge it with a nearby section. Threshold: ${minSectionWords} words.`,
280
+ })
281
+ }
282
+ }
283
+ if (stats.length.words >= BLOCKLESS_WORDS && stats.blocks.total === 0) {
284
+ findings.push({
285
+ severity: 'info',
286
+ source: 'stats',
287
+ code: 'CB_BLOCKLESS_DOCUMENT',
288
+ file,
289
+ relativePath: relativePath(cwd, file),
290
+ message: `document has ${stats.length.words} words and no structured blocks`,
291
+ hint: 'Consider a callout, steps, comparison, FAQ, or another registered block if it clarifies the page.',
292
+ })
293
+ }
294
+ if (stats.images.missingAlt > 0) {
295
+ findings.push({
296
+ severity: 'info',
297
+ source: 'stats',
298
+ code: 'CB_IMAGE_ALT_MISSING',
299
+ file,
300
+ relativePath: relativePath(cwd, file),
301
+ message: `${stats.images.missingAlt} image(s) are missing alt text`,
302
+ hint: 'Add descriptive alt text for meaningful images; use empty alt only for decorative images.',
303
+ })
304
+ }
305
+ return findings
306
+ }
307
+
308
+ function findingFromDiagnostic(
309
+ source: 'validation' | 'links',
310
+ file: string,
311
+ cwd: string,
312
+ diagnostic: Diagnostic,
313
+ ): StudioFinding {
314
+ return {
315
+ severity: diagnostic.severity,
316
+ source,
317
+ code: diagnostic.code,
318
+ file,
319
+ relativePath: relativePath(cwd, file),
320
+ line: diagnostic.position.start.line,
321
+ column: diagnostic.position.start.column,
322
+ message: diagnostic.message,
323
+ ...(diagnostic.hint ? { hint: diagnostic.hint } : {}),
324
+ }
325
+ }
326
+
327
+ function fileSummary(
328
+ file: string,
329
+ cwd: string,
330
+ frontmatter: Record<string, unknown>,
331
+ stats: ReturnType<typeof analyzeDocument>,
332
+ findings: StudioFinding[],
333
+ options: StudioOptions,
334
+ ): StudioFileSummary {
335
+ const counts = summarize(findings)
336
+ const keywords = keywordData(frontmatter.keywords)
337
+ const slug = stringValue(frontmatter[options.linkOptions?.slugField ?? 'slug'])
338
+ const key = stringValue(frontmatter[options.linkOptions?.keyField ?? 'key'])
339
+ const locale = stringValue(frontmatter[options.linkOptions?.localeField ?? 'locale'])
340
+ return {
341
+ path: file,
342
+ relativePath: relativePath(cwd, file),
343
+ title: titleFor(file, frontmatter, stats),
344
+ ...(slug ? { slug } : {}),
345
+ ...(key ? { key } : {}),
346
+ ...(locale ? { locale } : {}),
347
+ ...(keywords ? { keywords } : {}),
348
+ words: stats.length.words,
349
+ readingMinutes: stats.length.readingMinutes,
350
+ blocks: stats.blocks.total,
351
+ blockNames: stats.blocks.byName,
352
+ links: stats.links.total,
353
+ externalLinks: stats.links.external,
354
+ missingAlt: stats.images.missingAlt,
355
+ findings: counts,
356
+ status: statusFor(counts),
357
+ }
358
+ }
359
+
360
+ function refreshSummaryFindings(summaries: StudioFileSummary[], findings: StudioFinding[]): void {
361
+ for (const summary of summaries) {
362
+ summary.findings = summarize(findings.filter((finding) => finding.file === summary.path))
363
+ summary.status = statusFor(summary.findings)
364
+ }
365
+ }
366
+
367
+ function titleFor(
368
+ file: string,
369
+ frontmatter: Record<string, unknown>,
370
+ stats: ReturnType<typeof analyzeDocument>,
371
+ ): string {
372
+ return stringValue(frontmatter.title) ?? stats.outline[0]?.text ?? basename(file)
373
+ }
374
+
375
+ function keywordData(value: unknown): StudioKeywordData | undefined {
376
+ if (!value || typeof value !== 'object') return undefined
377
+ const record = value as Record<string, unknown>
378
+ const primary = stringValue(record.primary)
379
+ const secondary = Array.isArray(record.secondary)
380
+ ? record.secondary.filter((item): item is string => typeof item === 'string')
381
+ : undefined
382
+ return primary || (secondary?.length ?? 0) > 0
383
+ ? { ...(primary ? { primary } : {}), ...(secondary ? { secondary } : {}) }
384
+ : undefined
385
+ }
386
+
387
+ function summarize(findings: StudioFinding[]): StudioFileSummary['findings'] {
388
+ return {
389
+ errors: findings.filter((finding) => finding.severity === 'error').length,
390
+ warnings: findings.filter((finding) => finding.severity === 'warning').length,
391
+ suggestions: findings.filter((finding) => finding.severity === 'info').length,
392
+ }
393
+ }
394
+
395
+ function statusFor(findings: StudioFileSummary['findings']): StudioStatus {
396
+ if (findings.errors > 0) return 'error'
397
+ if (findings.warnings > 0) return 'warning'
398
+ if (findings.suggestions > 0) return 'suggestion'
399
+ return 'healthy'
400
+ }
401
+
402
+ function graphSummary(index: NonNullable<ScanContext['index']>): StudioProject['linkGraph'] {
403
+ let links = 0
404
+ for (const page of index.pages.values()) links += page.linksTo.length
405
+ return {
406
+ pages: index.pages.size,
407
+ links,
408
+ orphans: [...index.pages.values()].filter((page) => page.linkedFrom.length === 0).length,
409
+ }
410
+ }
411
+
412
+ function hasLinkFrontmatter(inputs: LinkInput[], configuredSlugField: string | undefined): boolean {
413
+ const slugField = configuredSlugField ?? 'slug'
414
+ return inputs.some((input) => Object.prototype.hasOwnProperty.call(input.data, slugField))
415
+ }
416
+
417
+ function findAllowedFile(context: ScanContext, cwd: string, requestedPath: string): string | null {
418
+ return (
419
+ context.files.find(
420
+ (file) => file === requestedPath || relativePath(cwd, file) === requestedPath,
421
+ ) ?? null
422
+ )
423
+ }
424
+
425
+ function compareFindings(a: StudioFinding, b: StudioFinding): number {
426
+ return (
427
+ rank(a) - rank(b) ||
428
+ a.relativePath.localeCompare(b.relativePath) ||
429
+ (a.line ?? 0) - (b.line ?? 0) ||
430
+ (a.column ?? 0) - (b.column ?? 0) ||
431
+ a.code.localeCompare(b.code)
432
+ )
433
+ }
434
+
435
+ function rank(finding: StudioFinding): number {
436
+ if (finding.severity === 'error' && finding.source === 'validation') return 0
437
+ if (finding.severity === 'error' && finding.source === 'links') return 1
438
+ if (finding.severity === 'warning') return 2
439
+ if (finding.code === 'CB_THIN_SECTION') return 3
440
+ if (finding.code === 'CB_BLOCKLESS_DOCUMENT') return 4
441
+ if (finding.code === 'CB_IMAGE_ALT_MISSING') return 5
442
+ return 6
443
+ }
444
+
445
+ function pageIdentity(page: { locale?: string; key?: string; slug: string }): string {
446
+ return `${page.locale ?? ''}\0${page.key ?? page.slug}`
447
+ }
448
+
449
+ function targetFromMessage(message: string): string | undefined {
450
+ return message.match(/linksTo "([^"]+)"/)?.[1]
451
+ }
452
+
453
+ function stringValue(value: unknown): string | undefined {
454
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined
455
+ }
456
+
457
+ function relativePath(cwd: string, file: string): string {
458
+ const rel = relative(cwd, file)
459
+ return rel.startsWith('..') ? file : rel
460
+ }
@@ -0,0 +1,109 @@
1
+ import type { DocumentStats, LinkReference, LinkResolverOptions } from '@contentbit/core'
2
+ import type { BlockComponent } from '@contentbit/react'
3
+
4
+ export type StudioSeverity = 'error' | 'warning' | 'info'
5
+ export type StudioStatus = 'error' | 'warning' | 'suggestion' | 'healthy'
6
+ export type StudioFindingSource = 'validation' | 'links' | 'stats'
7
+
8
+ export interface StudioFinding {
9
+ severity: StudioSeverity
10
+ source: StudioFindingSource
11
+ code: string
12
+ file: string
13
+ relativePath: string
14
+ line?: number
15
+ column?: number
16
+ message: string
17
+ hint?: string
18
+ }
19
+
20
+ export interface StudioKeywordData {
21
+ primary?: string
22
+ secondary?: string[]
23
+ }
24
+
25
+ export interface StudioFileSummary {
26
+ path: string
27
+ relativePath: string
28
+ title: string
29
+ slug?: string
30
+ key?: string
31
+ locale?: string
32
+ keywords?: StudioKeywordData
33
+ words: number
34
+ readingMinutes: number
35
+ blocks: number
36
+ blockNames: Record<string, number>
37
+ links: number
38
+ externalLinks: number
39
+ missingAlt: number
40
+ findings: { errors: number; warnings: number; suggestions: number }
41
+ status: StudioStatus
42
+ }
43
+
44
+ export interface StudioProject {
45
+ root: string
46
+ files: StudioFileSummary[]
47
+ summary: {
48
+ files: number
49
+ errors: number
50
+ warnings: number
51
+ suggestions: number
52
+ words: number
53
+ blocks: number
54
+ links: number
55
+ missingAlt: number
56
+ }
57
+ blockUsage: Record<string, number>
58
+ keywordCoverage: { total: number; withPrimary: number; withSecondary: number }
59
+ linkGraph?: { pages: number; links: number; orphans: number }
60
+ findings: StudioFinding[]
61
+ }
62
+
63
+ export interface StudioDocument {
64
+ file: StudioFileSummary
65
+ source: string
66
+ frontmatter: Record<string, unknown>
67
+ stats: DocumentStats
68
+ findings: StudioFinding[]
69
+ linksTo: string[] | LinkReference[]
70
+ linkedFrom: string[] | LinkReference[]
71
+ previewHtml: string
72
+ }
73
+
74
+ export interface StudioGraphNode {
75
+ id: string
76
+ label: string
77
+ path: string
78
+ status: StudioStatus
79
+ slug?: string
80
+ key?: string
81
+ locale?: string
82
+ }
83
+
84
+ export interface StudioGraphEdge {
85
+ from: string
86
+ to?: string
87
+ target: string
88
+ status: 'resolved' | 'unresolved' | 'cross-locale' | 'self'
89
+ }
90
+
91
+ export interface StudioGraph {
92
+ nodes: StudioGraphNode[]
93
+ edges: StudioGraphEdge[]
94
+ }
95
+
96
+ export interface StudioOptions {
97
+ globs: string[]
98
+ registryPath?: string
99
+ cwd?: string
100
+ linkOptions?: LinkResolverOptions
101
+ minSectionWords?: number
102
+ previewComponents?: () => Promise<Record<string, BlockComponent> | undefined>
103
+ }
104
+
105
+ export interface StartStudioOptions extends StudioOptions {
106
+ host?: string
107
+ port?: number
108
+ open?: boolean
109
+ }