@acowale/orion-boneyard 0.0.0-stage → 1.10.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.
package/bin/cli.js ADDED
@@ -0,0 +1,1582 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * boneyard CLI
4
+ *
5
+ * Visits your running app at every breakpoint, captures all named <Skeleton>
6
+ * components, and writes responsive bones JSON files to disk.
7
+ *
8
+ * Usage:
9
+ * npx orion-boneyard build [url] [options]
10
+ * npx orion-boneyard build ← auto-detects your dev server
11
+ * npx orion-boneyard build http://localhost:5173 ← explicit URL
12
+ * npx orion-boneyard build http://localhost:3000/blog http://localhost:3000/shop
13
+ *
14
+ * Options:
15
+ * --out <dir> Where to write .bones.json files (default: auto-detected)
16
+ * --breakpoints <bp> Viewport widths to capture, comma-separated (default: 375,768,1280)
17
+ * --wait <ms> Extra ms to wait after page load (default: 800)
18
+ * --cookie <n=v> Pass auth cookie (repeatable). e.g. --cookie "session=abc123"
19
+ * --no-scan Skip filesystem route scanning (only crawl links)
20
+ *
21
+ * Requires playwright:
22
+ * npm install -D playwright && npx playwright install chromium
23
+ */
24
+
25
+ import { writeFileSync, mkdirSync, existsSync, readFileSync, readdirSync } from 'fs'
26
+ import { resolve, join, dirname } from 'path'
27
+ import { fileURLToPath } from 'url'
28
+ import http from 'http'
29
+ import https from 'https'
30
+ import { detectRegistryExtension } from './registry-file.js'
31
+ import { isSinglePageMode, resolveCdpEndpoint } from './url-helpers.js'
32
+ import { mergePreservingExisting } from './bone-merge.js'
33
+
34
+ // Read our own version from the package.json that ships with this CLI.
35
+ // `@acowale/orion-boneyard` may be installed anywhere — walk from this file rather than cwd.
36
+ function getPackageVersion() {
37
+ try {
38
+ const selfDir = dirname(fileURLToPath(import.meta.url))
39
+ const pkgPath = resolve(selfDir, '..', 'package.json')
40
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
41
+ return pkg.version ?? 'unknown'
42
+ } catch {
43
+ return 'unknown'
44
+ }
45
+ }
46
+
47
+ function loadEnvFile(filePath) {
48
+ if (!existsSync(filePath)) {
49
+ console.error(` boneyard: env file not found: ${filePath}`)
50
+ process.exit(1)
51
+ }
52
+ // Path traversal check
53
+ const resolved = resolve(filePath)
54
+ const cwd = resolve(process.cwd())
55
+ if (!resolved.startsWith(cwd)) {
56
+ console.error(` boneyard: env file must be within the project directory`)
57
+ process.exit(1)
58
+ }
59
+ const lines = readFileSync(filePath, 'utf-8').split('\n')
60
+ for (const line of lines) {
61
+ const trimmed = line.trim()
62
+ if (!trimmed || trimmed.startsWith('#')) continue
63
+ // Strip optional "export " prefix
64
+ const entry = trimmed.startsWith('export ') ? trimmed.slice(7) : trimmed
65
+ const eqIdx = entry.indexOf('=')
66
+ if (eqIdx < 0) continue
67
+ const key = entry.slice(0, eqIdx).trim()
68
+ const raw = entry.slice(eqIdx + 1).trim()
69
+ if (key && !(key in process.env)) {
70
+ process.env[key] = raw.replace(/^(['"])(.*)\1$/, '$2')
71
+ }
72
+ }
73
+ process.stdout.write(` boneyard: loaded env from ${filePath}\n`)
74
+ }
75
+
76
+ const args = process.argv.slice(2)
77
+ const command = args[0]
78
+
79
+ if (command === '--version' || command === '-v') {
80
+ console.log(`@acowale/orion-boneyard ${getPackageVersion()}`)
81
+ process.exit(0)
82
+ }
83
+
84
+ if (!command || command === '--help' || command === '-h') {
85
+ printHelp()
86
+ process.exit(0)
87
+ }
88
+
89
+ if (command !== 'build') {
90
+ console.error(`boneyard: unknown command "${command}". Try: npx orion-boneyard build`)
91
+ process.exit(1)
92
+ }
93
+
94
+ // ── Parse args ────────────────────────────────────────────────────────────────
95
+
96
+ const urls = []
97
+ const defaultOutDir = existsSync(resolve(process.cwd(), 'src')) ? './src/bones' : './bones'
98
+ let outDir = defaultOutDir
99
+ let breakpoints = null // null = auto-detect
100
+ let waitMs = 800
101
+ let cliSetOut = false
102
+ let cliSetBreakpoints = false
103
+ let cliSetWait = false
104
+ let forceRebuild = false
105
+ let nativeMode = false
106
+ let noScan = false
107
+ let envFilePath = null
108
+ let watchMode = false
109
+ let cdpEndpoint = null
110
+ let config = {}
111
+ const cliCookies = []
112
+
113
+ for (let i = 1; i < args.length; i++) {
114
+ if (args[i] === '--out') {
115
+ outDir = args[++i]
116
+ cliSetOut = true
117
+ } else if (args[i] === '--breakpoints') {
118
+ breakpoints = args[++i].split(',').map(Number).filter(n => n > 0)
119
+ cliSetBreakpoints = true
120
+ } else if (args[i] === '--wait') {
121
+ waitMs = Math.max(0, Number(args[++i]) || 800)
122
+ cliSetWait = true
123
+ } else if (args[i] === '--force') {
124
+ forceRebuild = true
125
+ } else if (args[i] === '--native') {
126
+ nativeMode = true
127
+ } else if (args[i] === '--no-scan') {
128
+ noScan = true
129
+ } else if (args[i] === '--env-file') {
130
+ envFilePath = args[++i]
131
+ if (!envFilePath) {
132
+ console.error(' boneyard: --env-file requires a path argument')
133
+ process.exit(1)
134
+ }
135
+ } else if (args[i] === '--watch') {
136
+ watchMode = true
137
+ } else if (args[i] === '--cdp') {
138
+ cdpEndpoint = resolveCdpEndpoint(args[++i])
139
+ if (!cdpEndpoint) {
140
+ console.error(' boneyard: --cdp requires a port number or a CDP endpoint URL\n' +
141
+ ' (e.g. --cdp 9222, or --cdp ws://127.0.0.1:9222/devtools/browser/<uuid>)')
142
+ process.exit(1)
143
+ }
144
+ } else if (args[i] === '--cookie') {
145
+ // --cookie "name=value" — shorthand for auth.cookies config
146
+ const cookieStr = args[++i]
147
+ if (!cookieStr || !cookieStr.includes('=')) {
148
+ console.error(' boneyard: --cookie requires name=value format (e.g. --cookie "session=abc123")')
149
+ process.exit(1)
150
+ }
151
+ const eqIdx = cookieStr.indexOf('=')
152
+ const cliCookieName = cookieStr.slice(0, eqIdx)
153
+ const cliCookieValue = cookieStr.slice(eqIdx + 1)
154
+ cliCookies.push({ name: cliCookieName, value: cliCookieValue })
155
+ } else if (!args[i].startsWith('--')) {
156
+ urls.push(args[i])
157
+ }
158
+ }
159
+
160
+ // ── Load config file ─────────────────────────────────────────────────────────
161
+
162
+ const configPath = resolve(process.cwd(), 'boneyard.config.json')
163
+ if (existsSync(configPath)) {
164
+ try {
165
+ config = JSON.parse(readFileSync(configPath, 'utf-8'))
166
+ process.stdout.write(` boneyard: loaded config from boneyard.config.json\n`)
167
+ } catch (e) {
168
+ console.error(` boneyard: failed to parse boneyard.config.json — ${e.message}`)
169
+ }
170
+ }
171
+
172
+ // Merge CLI cookies into config (after config file load so they aren't overwritten)
173
+ if (cliCookies.length) config._cliCookies = cliCookies
174
+
175
+ // Apply config as defaults — CLI flags take priority
176
+ if (!cliSetBreakpoints && Array.isArray(config.breakpoints)) {
177
+ breakpoints = config.breakpoints
178
+ }
179
+ if (!cliSetOut && config.out) {
180
+ outDir = config.out
181
+ }
182
+ if (!cliSetWait && typeof config.wait === 'number') {
183
+ waitMs = config.wait
184
+ }
185
+
186
+ // Resolve env vars in auth config
187
+ const allowedCookieKeys = new Set(['name', 'value', 'path', 'domain', 'expires', 'httpOnly', 'secure', 'sameSite'])
188
+ const blockedHeaders = new Set(['host', 'content-length', 'transfer-encoding', 'connection', 'upgrade'])
189
+
190
+ if (envFilePath) {
191
+ loadEnvFile(resolve(process.cwd(), envFilePath))
192
+ }
193
+
194
+ if (config.resolveEnvVars && config.auth) {
195
+ if (config.auth.cookies) {
196
+ config.auth.cookies = config.auth.cookies.map(c => {
197
+ const safe = {}
198
+ for (const [k, v] of Object.entries(c)) {
199
+ if (allowedCookieKeys.has(k)) safe[k] = v
200
+ }
201
+ safe.value = replaceEnvStrings(safe.value)
202
+ return safe
203
+ })
204
+ }
205
+ if (config.auth.headers) {
206
+ for (const [key, val] of Object.entries(config.auth.headers)) {
207
+ if (blockedHeaders.has(key.toLowerCase())) {
208
+ console.error(`\nboneyard: blocked unsafe header '${key}' in auth config`)
209
+ process.exit(1)
210
+ }
211
+ config.auth.headers[key] = replaceEnvStrings(val)
212
+ }
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Only active if config.resolveEnvVars is true
218
+ * Resolves all `env[...]` in a config value
219
+ *
220
+ * @returns {string} the value with all env strings resolved
221
+ */
222
+ function replaceEnvStrings(value) {
223
+ if (typeof value !== 'string') {
224
+ return value
225
+ }
226
+ const regex = /env\[[^\]]*\]/g
227
+ return value.replace(regex, resolveEnv)
228
+ }
229
+
230
+ /**
231
+ * @param {string} str
232
+ * @returns the resolved env string
233
+ */
234
+ function resolveEnv(str) {
235
+ const start = str.indexOf('[') + 1;
236
+ const end = str.indexOf(']');
237
+ let key
238
+ if (end > start && end === str.length - 1) {
239
+ key = str.substring(start, end)
240
+ } else {
241
+ console.error(
242
+ `\nboneyard: could not parse environment variable: ${str}` +
243
+ `\n it should look like this: env[<VAR_NAME>]`
244
+ )
245
+ process.exit(1)
246
+ }
247
+
248
+ const value = process.env[key]
249
+ if (value) {
250
+ return value
251
+ } else {
252
+ console.error(
253
+ `\nboneyard: no environment variable '${key} found'` +
254
+ `\n try: export $${key}='...'`
255
+ )
256
+ process.exit(1)
257
+ }
258
+ }
259
+
260
+
261
+ // ── Auto-detect breakpoints from Tailwind ────────────────────────────────────
262
+
263
+ /** Tailwind v4 default breakpoints */
264
+ const TAILWIND_DEFAULTS = [640, 768, 1024, 1280, 1536]
265
+
266
+ async function detectTailwindBreakpoints() {
267
+ // Check for Tailwind v4 (CSS-based config)
268
+ const cssConfigPaths = [
269
+ 'src/app/globals.css',
270
+ 'src/globals.css',
271
+ 'app/globals.css',
272
+ 'styles/globals.css',
273
+ 'src/index.css',
274
+ 'index.css',
275
+ ]
276
+
277
+ for (const p of cssConfigPaths) {
278
+ const full = resolve(process.cwd(), p)
279
+ if (!existsSync(full)) continue
280
+ try {
281
+ const css = readFileSync(full, 'utf-8')
282
+ if (css.includes('@import "tailwindcss"') || css.includes("@import 'tailwindcss'") || css.includes('@tailwind')) {
283
+ return TAILWIND_DEFAULTS
284
+ }
285
+ } catch {}
286
+ }
287
+
288
+ // Check for tailwind in package.json dependencies
289
+ try {
290
+ const pkgPath = resolve(process.cwd(), 'package.json')
291
+ if (existsSync(pkgPath)) {
292
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
293
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies }
294
+ if (allDeps['tailwindcss']) return TAILWIND_DEFAULTS
295
+ }
296
+ } catch {}
297
+
298
+ return null
299
+ }
300
+
301
+ if (!breakpoints) {
302
+ const tw = await detectTailwindBreakpoints()
303
+ if (tw) {
304
+ // Add mobile (375) as the smallest breakpoint since Tailwind's start at 640
305
+ breakpoints = [375, ...tw]
306
+ process.stdout.write(` boneyard: detected Tailwind — using breakpoints: ${breakpoints.join(', ')}px\n`)
307
+ } else {
308
+ breakpoints = [375, 768, 1280]
309
+ }
310
+ }
311
+
312
+ // ── Auto-detect dev server ────────────────────────────────────────────────────
313
+
314
+ /**
315
+ * Check if a URL is responding. Returns true if we get any HTTP response
316
+ * (even 4xx/5xx — we just want to know something is listening).
317
+ */
318
+ function probe(url) {
319
+ return new Promise(resolve => {
320
+ const isHttps = url.startsWith('https')
321
+ const mod = isHttps ? https : http
322
+ // Local dev servers frequently terminate TLS with self-signed certs
323
+ // (mkcert, vite preview, Next.js --experimental-https). Reject-unauthorised
324
+ // would make the probe fail before we learn there's a server there.
325
+ const opts = { timeout: 1500, ...(isHttps ? { rejectUnauthorized: false } : {}) }
326
+ const req = mod.get(url, opts, res => {
327
+ res.destroy()
328
+ resolve(true)
329
+ })
330
+ req.on('error', () => resolve(false))
331
+ req.on('timeout', () => { req.destroy(); resolve(false) })
332
+ })
333
+ }
334
+
335
+ /** Common dev server ports in priority order */
336
+ const DEV_PORTS = nativeMode
337
+ ? [8081, 19006, 8082, 3000, 3001, 8080]
338
+ : [3000, 3001, 3002, 5173, 5174, 4321, 8080, 8000, 4200, 8888]
339
+
340
+ async function detectDevServer() {
341
+ // Try HTTP first (still the common case). If nothing responds on any of
342
+ // the usual ports, fall back to HTTPS — Vite / Next.js / SvelteKit all
343
+ // support running the dev server behind TLS, and some browser APIs
344
+ // (crypto.subtle, service workers in some modes, navigator.mediaDevices)
345
+ // are secure-context-only so users occasionally run dev over https. #80.
346
+ for (const port of DEV_PORTS) {
347
+ const url = `http://localhost:${port}`
348
+ if (await probe(url)) return url
349
+ }
350
+ for (const port of DEV_PORTS) {
351
+ const url = `https://localhost:${port}`
352
+ if (await probe(url)) return url
353
+ }
354
+ return null
355
+ }
356
+
357
+ // --native always uses the native scan receiver — no web server needed
358
+ if (nativeMode && urls.length === 0) {
359
+ await runScan()
360
+ process.exit(0)
361
+ }
362
+
363
+ if (urls.length === 0) {
364
+ process.stdout.write(' boneyard: no URL provided — scanning for dev server...')
365
+ const detected = await detectDevServer()
366
+ if (detected) {
367
+ process.stdout.write(` found ${detected}\n`)
368
+ urls.push(detected)
369
+ } else {
370
+ process.stdout.write(' none found\n\n')
371
+ console.error(
372
+ ' boneyard: could not find a running dev server.\n\n' +
373
+ ' Start your dev server first, then run:\n' +
374
+ ' npx orion-boneyard build\n\n' +
375
+ ' Or pass your URL explicitly:\n' +
376
+ ' npx orion-boneyard build http://localhost:3000\n'
377
+ )
378
+ process.exit(1)
379
+ }
380
+ }
381
+
382
+ // ── Load playwright ───────────────────────────────────────────────────────────
383
+
384
+ let chromium
385
+ try {
386
+ const pw = await import('playwright')
387
+ chromium = pw.chromium
388
+ } catch {
389
+ console.error(
390
+ '\nboneyard: playwright not found.\n\n' +
391
+ 'Install it:\n' +
392
+ ' npm install -D playwright\n' +
393
+ ' npx playwright install chromium\n'
394
+ )
395
+ process.exit(1)
396
+ }
397
+
398
+ // ── Capture ───────────────────────────────────────────────────────────────────
399
+
400
+ console.log(`\n \x1b[1m💀 boneyard build\x1b[0m`)
401
+ console.log(` \x1b[2m${'─'.repeat(50)}\x1b[0m`)
402
+ console.log(` \x1b[2mbreakpoints\x1b[0m ${breakpoints.join(', ')}px`)
403
+ console.log(` \x1b[2moutput\x1b[0m ${outDir}`)
404
+ if (watchMode) console.log(` \x1b[2mwatch\x1b[0m on`)
405
+ if (cdpEndpoint) console.log(` \x1b[2mcdp\x1b[0m ${cdpEndpoint}`)
406
+ console.log('')
407
+
408
+ let browser
409
+ let cdpContext = null
410
+ if (cdpEndpoint) {
411
+ try {
412
+ browser = await chromium.connectOverCDP(cdpEndpoint)
413
+ // Reuse the existing browser context so cookies and auth state from
414
+ // the user's Chrome session carry over. `--cdp` documents this as
415
+ // "reuses cookies, auth, state" — a fresh context breaks that promise.
416
+ cdpContext = browser.contexts()[0] ?? await browser.newContext()
417
+ console.log(` \x1b[2mConnected to Chrome at ${cdpEndpoint}\x1b[0m\n`)
418
+ } catch (e) {
419
+ console.error(
420
+ `\nboneyard: could not connect to Chrome at ${cdpEndpoint}.\n\n` +
421
+ 'For a port, Chrome must be launched with a debug port AND a non-default\n' +
422
+ 'profile (Chrome 136+ ignores --remote-debugging-port on the default profile):\n' +
423
+ ' google-chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug\n' +
424
+ ' # or on macOS:\n' +
425
+ ' /Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome \\\n' +
426
+ ' --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-debug\n\n' +
427
+ 'To attach to your normal running Chrome instead (Chrome 144+), enable\n' +
428
+ 'chrome://inspect/#remote-debugging → "Allow remote debugging", then pass the\n' +
429
+ 'WebSocket endpoint from <user-data-dir>/DevToolsActivePort:\n' +
430
+ ' --cdp ws://127.0.0.1:<port>/devtools/browser/<uuid>\n'
431
+ )
432
+ process.exit(1)
433
+ }
434
+ } else {
435
+ try {
436
+ browser = await chromium.launch()
437
+ } catch (e) {
438
+ if (e.message.includes("Executable doesn't exist")) {
439
+ console.log(' boneyard: installing chromium...\n')
440
+ const { execSync } = await import('child_process')
441
+ const { createRequire } = await import('module')
442
+ const require = createRequire(import.meta.url)
443
+ const pwPath = dirname(require.resolve('playwright/package.json'))
444
+ const playwrightCli = join(pwPath, 'cli.js')
445
+ execSync(`node "${playwrightCli}" install chromium`, { stdio: 'inherit' })
446
+ browser = await chromium.launch()
447
+ } else {
448
+ throw e
449
+ }
450
+ }
451
+ }
452
+ // For non-CDP launches, create a context with ignoreHTTPSErrors so local
453
+ // dev servers with self-signed certs (mkcert, vite preview, Next.js
454
+ // --experimental-https) don't get rejected at navigation time. #80.
455
+ // CDP mode reuses the user's Chrome context — their existing cert
456
+ // handling applies there and we don't override it.
457
+ const browserContext = cdpContext ?? await browser.newContext({ ignoreHTTPSErrors: true })
458
+ const page = await browserContext.newPage()
459
+
460
+ // Apply auth if configured (config file or --cookie CLI flag)
461
+ if (config._cliCookies?.length) {
462
+ // Merge CLI --cookie flags into config.auth.cookies
463
+ config.auth ??= {}
464
+ config.auth.cookies ??= []
465
+ const origin = new URL(urls[0] || `http://localhost:${port || 3000}`)
466
+ for (const c of config._cliCookies) {
467
+ config.auth.cookies.push({
468
+ name: c.name,
469
+ value: c.value,
470
+ domain: origin.hostname,
471
+ path: '/',
472
+ })
473
+ }
474
+ }
475
+ if (config.auth) {
476
+ if (config.auth.cookies?.length) {
477
+ console.log(` \x1b[2mApplying ${config.auth.cookies.length} cookie(s) to browser session\x1b[0m`)
478
+ await page.context().addCookies(config.auth.cookies)
479
+ }
480
+ if (config.auth.headers) {
481
+ const count = Object.keys(config.auth.headers).length
482
+ console.log(` \x1b[2mApplying ${count} header(s) to browser session\x1b[0m`)
483
+ await page.setExtraHTTPHeaders(config.auth.headers)
484
+ }
485
+ }
486
+
487
+ // Set build mode flag before any page loads so <Skeleton fixture={...}> renders mock content
488
+ await page.addInitScript(() => {
489
+ window.__BONEYARD_BUILD = true
490
+ })
491
+
492
+ // ── Load existing bones for incremental builds ──────────────────────────────
493
+ import { createHash } from 'crypto'
494
+
495
+ const existingBones = {}
496
+ const outputDir = resolve(process.cwd(), outDir)
497
+ if (!forceRebuild && existsSync(outputDir)) {
498
+ const files = (await import('fs')).readdirSync(outputDir)
499
+ for (const f of files) {
500
+ if (!f.endsWith('.bones.json')) continue
501
+ try {
502
+ const data = JSON.parse(readFileSync(join(outputDir, f), 'utf-8'))
503
+ const name = f.replace('.bones.json', '')
504
+ existingBones[name] = data
505
+ } catch {}
506
+ }
507
+ }
508
+
509
+ function hashContent(html) {
510
+ return createHash('md5').update(html).digest('hex')
511
+ }
512
+
513
+
514
+ // ── gotoPage logic ────────────────────────────────────────────────────────────────
515
+
516
+ var guidedWaitOverrides = null
517
+
518
+ async function gotoPage(page, pageUrl) {
519
+ try {
520
+ await page.goto(pageUrl, { waitUntil: 'networkidle', timeout: 15_000 })
521
+ } catch {
522
+ // networkidle can timeout on heavy pages — still try to capture
523
+ }
524
+
525
+ // Detect redirects (e.g. auth middleware sending to /login)
526
+ const finalUrl = page.url()
527
+ const requestedPath = new URL(pageUrl).pathname
528
+ const finalPath = new URL(finalUrl).pathname
529
+ const wasRedirected = finalPath !== requestedPath
530
+ if (wasRedirected) {
531
+ console.log(` \x1b[33m⚠ Redirected: ${requestedPath} → ${finalPath}\x1b[0m`)
532
+ }
533
+
534
+ const effectiveWait = (typeof guidedWaitOverrides === 'object' && guidedWaitOverrides !== null && guidedWaitOverrides[pageUrl]) || waitMs
535
+ if (effectiveWait > 0) await page.waitForTimeout(effectiveWait)
536
+
537
+ return { redirected: wasRedirected }
538
+ }
539
+
540
+ const skippedSkeletons = new Set()
541
+
542
+ // { [skeletonName]: { breakpoints: { [width]: SkeletonResult } } }
543
+ const collected = {}
544
+
545
+ // Crawl: discover all internal links starting from the provided URLs
546
+ const visited = new Set()
547
+ const toVisit = [...urls]
548
+
549
+ async function capturePage(pageUrl) {
550
+ const pageSkeletons = new Map()
551
+ const shortPath = pageUrl.replace(new URL(pageUrl).origin, '') || '/'
552
+ console.log(` ${shortPath}`)
553
+
554
+ // At the first breakpoint, collect hashes to detect changes
555
+ let pageHashes = {}
556
+ const isFirstBreakpoint = (width) => width === breakpoints[0]
557
+
558
+ for (const width of breakpoints) {
559
+ await page.setViewportSize({ width, height: 900 })
560
+
561
+ const { redirected } = await gotoPage(page, pageUrl)
562
+
563
+ // Skip remaining breakpoints if page redirected (auth wall, etc.)
564
+ if (redirected) break
565
+
566
+ // Find [data-boneyard] elements and extract bones using the real snapshotBones function
567
+ const bones = await page.evaluate((collectHashes) => {
568
+ const fn = window.__BONEYARD_SNAPSHOT
569
+ if (!fn) return { results: {}, hashes: {}, snapshotMissing: true }
570
+
571
+ const elements = document.querySelectorAll('[data-boneyard]')
572
+ const results = {}
573
+ const hashes = {}
574
+ const duplicates = []
575
+
576
+ for (const el of elements) {
577
+ const name = el.getAttribute('data-boneyard')
578
+ if (!name) continue
579
+
580
+ // Only capture the first occurrence of each name — duplicates are skipped
581
+ if (results[name]) {
582
+ duplicates.push(name)
583
+ continue
584
+ }
585
+
586
+ // Read snapshotConfig from data attribute
587
+ const configStr = el.getAttribute('data-boneyard-config')
588
+ const config = configStr ? JSON.parse(configStr) : undefined
589
+
590
+ // Target the inner wrapper div that contains the fixture content
591
+ const target = el.firstElementChild
592
+ if (!target) continue
593
+
594
+ // Collect hash of innerHTML for incremental builds
595
+ if (collectHashes) {
596
+ hashes[name] = target.innerHTML
597
+ }
598
+
599
+ try {
600
+ results[name] = fn(target, name, config)
601
+ } catch {
602
+ // skip on error
603
+ }
604
+ }
605
+
606
+ // Surface duplicate names so the user can fix them
607
+ if (duplicates.length > 0) {
608
+ results.__duplicates = [...new Set(duplicates)]
609
+ }
610
+
611
+ return { results, hashes }
612
+ }, isFirstBreakpoint(width))
613
+
614
+ // Log when __BONEYARD_SNAPSHOT is not found — usually means the <Skeleton> component
615
+ // didn't mount (auth redirect, hydration failure, or addInitScript timing issue)
616
+ if (bones.snapshotMissing && isFirstBreakpoint(width)) {
617
+ console.log(` \x1b[33m⚠ boneyard: __BONEYARD_SNAPSHOT not found — <Skeleton> may not have mounted on this page\x1b[0m`)
618
+ }
619
+
620
+ // On first breakpoint, compute hashes and check for unchanged skeletons
621
+ if (isFirstBreakpoint(width) && bones.hashes) {
622
+ for (const [name, html] of Object.entries(bones.hashes)) {
623
+ const hash = hashContent(html)
624
+ pageHashes[name] = hash
625
+ if (!forceRebuild && existingBones[name]?._hash === hash) {
626
+ // Skeleton unchanged — reuse existing data
627
+ collected[name] = existingBones[name]
628
+ skippedSkeletons.add(name)
629
+ }
630
+ }
631
+ }
632
+
633
+ // Replace bones with the results object
634
+ const boneResults = bones.results ?? bones
635
+
636
+ // Warn about duplicate skeleton names
637
+ if (boneResults.__duplicates) {
638
+ for (const dup of boneResults.__duplicates) {
639
+ console.log(` ⚠ Duplicate name "${dup}" — only the first occurrence was captured`)
640
+ }
641
+ delete boneResults.__duplicates
642
+ }
643
+
644
+ const names = Object.keys(boneResults)
645
+
646
+ if (names.length === 0) {
647
+ continue
648
+ }
649
+
650
+ for (const name of names) {
651
+ // Skip unchanged skeletons
652
+ if (skippedSkeletons.has(name)) continue
653
+
654
+ collected[name] ??= { breakpoints: {} }
655
+ // Convert bones to compact array format
656
+ const result = boneResults[name]
657
+ if (result.bones) {
658
+ result.bones = result.bones.map(b => {
659
+ const arr = [b.x, b.y, b.w, b.h, b.r]
660
+ if (b.c) arr.push(true)
661
+ return arr
662
+ })
663
+ }
664
+ collected[name].breakpoints[width] = result
665
+ // Store hash from first breakpoint
666
+ if (pageHashes[name]) {
667
+ collected[name]._hash = pageHashes[name]
668
+ }
669
+ const boneCount = result.bones?.length ?? 0
670
+ if (!pageSkeletons.has(name)) {
671
+ pageSkeletons.set(name, { counts: [] })
672
+ }
673
+ pageSkeletons.get(name).counts.push(boneCount)
674
+ }
675
+ }
676
+
677
+ // Print grouped summary for this page
678
+ // Show skipped skeletons found on this page
679
+ const pageSkeletonNames = new Set([...pageSkeletons.keys()])
680
+ const skippedOnPage = [...skippedSkeletons].filter(n => !pageSkeletonNames.has(n))
681
+
682
+ if (pageSkeletons.size === 0 && skippedOnPage.length === 0) {
683
+ // Check if there were skipped skeletons via hash from this page's evaluate
684
+ const skippedHere = Object.keys(pageHashes).filter(n => skippedSkeletons.has(n))
685
+ if (skippedHere.length > 0) {
686
+ for (const name of skippedHere) {
687
+ console.log(` ⊘ ${name.padEnd(24)} unchanged`)
688
+ }
689
+ } else {
690
+ console.log(` – No skeletons found`)
691
+ }
692
+ } else {
693
+ // Show skipped from this page's hashes
694
+ for (const name of Object.keys(pageHashes)) {
695
+ if (skippedSkeletons.has(name)) {
696
+ console.log(` ⊘ ${name.padEnd(24)} unchanged`)
697
+ }
698
+ }
699
+ for (const [name, info] of pageSkeletons) {
700
+ const min = Math.min(...info.counts)
701
+ const max = Math.max(...info.counts)
702
+ const boneStr = min === max
703
+ ? `${min} bones`
704
+ : `${min} → ${max} bones (responsive)`
705
+ console.log(` ✓ ${name.padEnd(24)} ${boneStr}`)
706
+ }
707
+ }
708
+ }
709
+
710
+ // Discover internal links from a page
711
+ async function discoverLinks(pageUrl) {
712
+ await gotoPage(page, pageUrl)
713
+
714
+ const origin = new URL(pageUrl).origin
715
+ const links = await page.evaluate((orig) => {
716
+ return [...document.querySelectorAll('a[href]')]
717
+ .map(a => a.href)
718
+ .filter(href => href.startsWith(orig))
719
+ .map(href => {
720
+ const u = new URL(href)
721
+ u.hash = ''
722
+ u.search = ''
723
+ return u.toString()
724
+ })
725
+ }, origin)
726
+
727
+ return [...new Set(links)]
728
+ }
729
+
730
+ // Discover routes from filesystem (Next.js, SvelteKit, Vite/Remix)
731
+ function discoverRoutes(origin) {
732
+ const cwd = process.cwd()
733
+ const routes = []
734
+
735
+ // Normalize filesystem paths to forward-slash URL paths. On Windows node's
736
+ // `path.dirname` / `path.join` use `\`, which breaks every downstream regex
737
+ // and string op in this function (issue #65 — SvelteKit groups never strip,
738
+ // Next.js nested routes lose their separators, etc.).
739
+ const toUrlPath = (s) => s.split(/[\\/]+/).join('/')
740
+
741
+ function walkDir(dir) {
742
+ if (!existsSync(dir)) return []
743
+ const entries = []
744
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
745
+ const full = join(dir, entry.name)
746
+ if (entry.isDirectory()) {
747
+ // Skip dynamic route segments like [id], (groups), __tests__
748
+ if (entry.name.startsWith('_') || entry.name.startsWith('.')) continue
749
+ entries.push(...walkDir(full))
750
+ } else {
751
+ entries.push(full)
752
+ }
753
+ }
754
+ return entries
755
+ }
756
+
757
+ // Next.js App Router: app/**/page.{tsx,jsx,ts,js}
758
+ const appDir = existsSync(join(cwd, 'src/app')) ? join(cwd, 'src/app') : join(cwd, 'app')
759
+ if (existsSync(appDir)) {
760
+ const appDirUrl = toUrlPath(appDir)
761
+ for (const file of walkDir(appDir)) {
762
+ const fileUrl = toUrlPath(file)
763
+ const base = fileUrl.split('/').pop()
764
+ if (/^page\.(tsx|jsx|ts|js)$/.test(base)) {
765
+ let route = toUrlPath(dirname(file)).replace(appDirUrl, '') || '/'
766
+ // Skip route groups like (marketing) — flatten them
767
+ route = route.replace(/\/\([^)]+\)/g, '')
768
+ if (!route) route = '/'
769
+ routes.push(route)
770
+ }
771
+ }
772
+ }
773
+
774
+ // Next.js Pages Router: pages/**/*.{tsx,jsx,ts,js}
775
+ const pagesDir = existsSync(join(cwd, 'src/pages')) ? join(cwd, 'src/pages') : join(cwd, 'pages')
776
+ if (existsSync(pagesDir) && !existsSync(appDir)) {
777
+ const pagesDirUrl = toUrlPath(pagesDir)
778
+ for (const file of walkDir(pagesDir)) {
779
+ const fileUrl = toUrlPath(file)
780
+ const base = fileUrl.split('/').pop()
781
+ if (!/\.(tsx|jsx|ts|js)$/.test(base)) continue
782
+ // Skip Next.js special files and API routes
783
+ const name = base.replace(/\.(tsx|jsx|ts|js)$/, '')
784
+ if (['_app', '_document', '_error', '404', '500'].includes(name)) continue
785
+ let route = fileUrl.replace(pagesDirUrl, '').replace(/\.(tsx|jsx|ts|js)$/, '')
786
+ if (route.includes('/api/')) continue
787
+ if (route.endsWith('/index')) route = route.replace(/\/index$/, '') || '/'
788
+ routes.push(route)
789
+ }
790
+ }
791
+
792
+ // SvelteKit: src/routes/**/+page.svelte
793
+ const svelteDir = join(cwd, 'src/routes')
794
+ if (existsSync(svelteDir)) {
795
+ const svelteDirUrl = toUrlPath(svelteDir)
796
+ for (const file of walkDir(svelteDir)) {
797
+ const fileUrl = toUrlPath(file)
798
+ if (fileUrl.endsWith('+page.svelte')) {
799
+ let route = toUrlPath(dirname(file)).replace(svelteDirUrl, '') || '/'
800
+ route = route.replace(/\/\([^)]+\)/g, '')
801
+ if (!route) route = '/'
802
+ routes.push(route)
803
+ }
804
+ }
805
+ }
806
+
807
+ // Nuxt: pages/**/*.vue
808
+ const nuxtDir = existsSync(join(cwd, 'pages')) ? join(cwd, 'pages') : null
809
+ if (nuxtDir && !existsSync(appDir) && !existsSync(pagesDir)) {
810
+ const nuxtDirUrl = toUrlPath(nuxtDir)
811
+ for (const file of walkDir(nuxtDir)) {
812
+ const fileUrl = toUrlPath(file)
813
+ if (!fileUrl.endsWith('.vue')) continue
814
+ let route = fileUrl.replace(nuxtDirUrl, '').replace(/\.vue$/, '')
815
+ if (route.endsWith('/index')) route = route.replace(/\/index$/, '') || '/'
816
+ routes.push(route)
817
+ }
818
+ }
819
+
820
+ // Remix / React Router v7: app/routes/**/*.{tsx,jsx,ts,js}
821
+ const remixDir = join(cwd, 'app/routes')
822
+ if (existsSync(remixDir)) {
823
+ const remixDirUrl = toUrlPath(remixDir)
824
+ for (const file of walkDir(remixDir)) {
825
+ const fileUrl = toUrlPath(file)
826
+ const base = fileUrl.split('/').pop()
827
+ if (!/\.(tsx|jsx|ts|js)$/.test(base)) continue
828
+ let route = fileUrl.replace(remixDirUrl, '').replace(/\.(tsx|jsx|ts|js)$/, '')
829
+ // Remix flat routes: dots become slashes, _ prefix = pathless layout
830
+ route = route.replace(/\./g, '/')
831
+ if (route.endsWith('/index') || route.endsWith('/_index')) route = route.replace(/\/_?index$/, '') || '/'
832
+ // Skip layout routes (prefixed with _)
833
+ const segments = route.split('/')
834
+ if (segments.some(s => s.startsWith('_') && s !== '_index')) continue
835
+ routes.push(route)
836
+ }
837
+ }
838
+
839
+ // Convert to full URLs and deduplicate
840
+ const seen = new Set()
841
+ const urls = []
842
+ for (const route of routes) {
843
+ // Skip dynamic segments — can't visit without params
844
+ if (route.includes('[')) continue
845
+ const url = `${origin}${route}`
846
+ if (!seen.has(url)) {
847
+ seen.add(url)
848
+ urls.push(url)
849
+ }
850
+ }
851
+ return urls
852
+ }
853
+
854
+ // Crawl all pages
855
+ const startUrl = urls[0]
856
+ const startOrigin = new URL(startUrl).origin
857
+
858
+ // Single-page mode: when the user explicitly passed at least one URL with
859
+ // a non-root path (e.g. `npx orion-boneyard build http://localhost:3000/dashboard`)
860
+ // the docs promise "Specific page" capture (apps/docs/src/app/cli/page.tsx).
861
+ // Honour that promise — skip link-following, skip filesystem route discovery,
862
+ // skip config.routes/skeletons augmentation. The given URLs ARE the queue.
863
+ // Bare-origin URLs and the auto-detect path keep the legacy crawl behaviour.
864
+ const singlePageMode = isSinglePageMode(urls)
865
+
866
+ // Per-skeleton guided crawling: skip route discovery and go directly to specified routes
867
+ const skeletonsConfig = config.skeletons
868
+ if (singlePageMode) {
869
+ const label = urls.length === 1 ? 'page' : 'pages'
870
+ console.log(` \x1b[2mSpecific ${label}: ${urls.length} URL(s) — no link/filesystem crawl\x1b[0m\n`)
871
+ // toVisit was initialized with [...urls] above — that's already the full
872
+ // queue. Nothing else to add.
873
+ } else if (skeletonsConfig && typeof skeletonsConfig === 'object' && Object.keys(skeletonsConfig).length > 0) {
874
+ const entries = Object.entries(skeletonsConfig)
875
+ console.log(` \x1b[2mGuided crawl: ${entries.length} skeleton(s) configured\x1b[0m\n`)
876
+ const guidedRoutes = new Set()
877
+ const perRouteWait = {}
878
+ for (const [name, opts] of entries) {
879
+ if (!opts.route) continue
880
+ const fullUrl = `${startOrigin}${opts.route}`
881
+ guidedRoutes.add(fullUrl)
882
+ if (opts.wait) perRouteWait[fullUrl] = opts.wait
883
+ }
884
+ // Replace toVisit with guided routes only
885
+ toVisit.length = 0
886
+ toVisit.push(...guidedRoutes)
887
+ // Store per-route wait overrides for use in gotoPage
888
+ guidedWaitOverrides = perRouteWait
889
+ } else {
890
+ console.log(` \x1b[2mCrawling ${startOrigin}\x1b[0m\n`)
891
+
892
+ // Discover links from starting URLs
893
+ for (const url of urls) {
894
+ if (!visited.has(url)) {
895
+ const links = await discoverLinks(url)
896
+ for (const link of links) {
897
+ if (!visited.has(link) && !toVisit.includes(link)) {
898
+ toVisit.push(link)
899
+ }
900
+ }
901
+ }
902
+ }
903
+
904
+ // Discover routes from filesystem
905
+ if (!noScan) {
906
+ const fsRoutes = discoverRoutes(startOrigin)
907
+ let added = 0
908
+ for (const route of fsRoutes) {
909
+ if (!visited.has(route) && !toVisit.includes(route)) {
910
+ toVisit.push(route)
911
+ added++
912
+ }
913
+ }
914
+ if (added > 0) {
915
+ console.log(` \x1b[2mFound ${added} additional route(s) from filesystem\x1b[0m\n`)
916
+ }
917
+ }
918
+
919
+ // Explicit routes from boneyard.config.json — universal escape hatch for
920
+ // frameworks whose filesystem can't be parsed reliably (Angular lazy modules,
921
+ // custom routers, server-defined routes, etc.). Supports plain strings
922
+ // ("/dashboard") or full URLs on the same origin as the crawl target.
923
+ if (Array.isArray(config.routes) && config.routes.length > 0) {
924
+ let added = 0
925
+ for (const r of config.routes) {
926
+ if (typeof r !== 'string' || r.length === 0) continue
927
+ let url
928
+ if (/^https?:\/\//i.test(r)) {
929
+ // Full URL — guard against accidentally crawling an external site.
930
+ const parsed = (() => { try { return new URL(r) } catch { return null } })()
931
+ if (!parsed) continue
932
+ if (parsed.origin !== startOrigin) {
933
+ console.log(` \x1b[33m⚠ skipping config.routes entry from a different origin: ${r}\x1b[0m`)
934
+ continue
935
+ }
936
+ url = parsed.toString()
937
+ } else {
938
+ url = `${startOrigin}${r.startsWith('/') ? r : '/' + r}`
939
+ }
940
+ if (!visited.has(url) && !toVisit.includes(url)) {
941
+ toVisit.push(url)
942
+ added++
943
+ }
944
+ }
945
+ if (added > 0) {
946
+ console.log(` \x1b[2mAdded ${added} route(s) from boneyard.config.json\x1b[0m\n`)
947
+ }
948
+ }
949
+ }
950
+
951
+ // Visit all discovered pages
952
+ for (const pageUrl of toVisit) {
953
+ if (visited.has(pageUrl)) continue
954
+ visited.add(pageUrl)
955
+ await capturePage(pageUrl)
956
+ }
957
+
958
+ if (!watchMode) {
959
+ if (cdpContext) await cdpContext.close()
960
+ await browser.close()
961
+ }
962
+
963
+ // ── Write files ───────────────────────────────────────────────────────────────
964
+
965
+ if (Object.keys(collected).length === 0) {
966
+ if (watchMode) {
967
+ console.log('\n boneyard: no skeletons found on first pass — will keep watching...\n')
968
+ } else {
969
+ console.error(
970
+ '\n boneyard: nothing captured.\n\n' +
971
+ ' Make sure your components have <Skeleton name="my-component" loading={false}>\n' +
972
+ ' so boneyard can snapshot them before the CLI reads the registry.\n\n' +
973
+ ' If your skeletons live on routes that aren\'t linked from the start page\n' +
974
+ ' (common for Angular lazy modules, auth-gated pages, etc.), list them in\n' +
975
+ ' boneyard.config.json:\n\n' +
976
+ ' { "routes": ["/dashboard", "/settings/profile"] }\n'
977
+ )
978
+ process.exit(1)
979
+ }
980
+ }
981
+
982
+ // ── Validate bones before writing ────────────────────────────────────────────
983
+ let hasWarnings = false
984
+ for (const [name, data] of Object.entries(collected)) {
985
+ for (const [bp, result] of Object.entries(data.breakpoints)) {
986
+ const bones = result.bones
987
+ if (!bones || bones.length === 0) continue
988
+ const maxRight = Math.max(...bones.map(b => b.x + b.w))
989
+ if (maxRight < 50) {
990
+ if (!hasWarnings) {
991
+ console.log(`\n \x1b[33m⚠ Bone coverage warnings:\x1b[0m`)
992
+ hasWarnings = true
993
+ }
994
+ console.log(` "${name}" at ${bp}px: bones only cover ${maxRight.toFixed(0)}% of container width`)
995
+ console.log(` This usually means the skeleton was captured from a container wider than its content.`)
996
+ console.log(` Check that the element rendered inside <Skeleton name="${name}"> fills its container.\n`)
997
+ }
998
+ }
999
+ }
1000
+
1001
+ mkdirSync(outputDir, { recursive: true })
1002
+
1003
+ console.log(`\n \x1b[2m${'─'.repeat(50)}\x1b[0m`)
1004
+ console.log(` \x1b[1mWriting files\x1b[0m\n`)
1005
+ for (const [name, data] of Object.entries(collected)) {
1006
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_')
1007
+ const outPath = resolve(outputDir, `${safeName}.bones.json`)
1008
+ if (!outPath.startsWith(resolve(outputDir))) {
1009
+ console.error(` \x1b[31m✗\x1b[0m Skipping "${name}" — path escapes output directory`)
1010
+ continue
1011
+ }
1012
+ writeFileSync(outPath, JSON.stringify(data, null, 2))
1013
+ const bpCount = Object.keys(data.breakpoints).length
1014
+ console.log(` \x1b[32m→\x1b[0m ${safeName}.bones.json \x1b[2m(${bpCount} breakpoint${bpCount !== 1 ? 's' : ''})\x1b[0m`)
1015
+ }
1016
+
1017
+ // Preserve previously-captured bones that weren't re-visited this run so
1018
+ // they don't silently drop out of the registry (#81). Typical scenario:
1019
+ // user captured /login while unauthenticated, then added auth.cookies and
1020
+ // re-ran — /login now redirects to /dashboard, so only /dashboard enters
1021
+ // `collected`, but login.bones.json is still on disk and valid. Use
1022
+ // --force to rebuild from scratch.
1023
+ if (!forceRebuild) {
1024
+ mergePreservingExisting(collected, existingBones)
1025
+ }
1026
+
1027
+ // ── Generate registry.js ─────────────────────────────────────────────────────
1028
+ const names = Object.keys(collected)
1029
+ const runtimeKeys = ['color', 'darkColor', 'animate', 'shimmerColor', 'darkShimmerColor', 'speed', 'shimmerAngle', 'stagger', 'transition', 'boneClass']
1030
+ const hasRuntimeConfig = runtimeKeys.some(k => config[k] !== undefined)
1031
+ // Detect framework for registry import — registerBones is always from the base
1032
+ // package (shared across all adapters), configureBoneyard needs the framework path
1033
+ function detectFramework() {
1034
+ if (nativeMode) return 'native'
1035
+ try {
1036
+ const pkgPath = resolve(process.cwd(), 'package.json')
1037
+ if (existsSync(pkgPath)) {
1038
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
1039
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies }
1040
+ if (allDeps['vue'] || allDeps['nuxt']) return 'vue'
1041
+ if (allDeps['svelte'] || allDeps['@sveltejs/kit']) return 'svelte'
1042
+ if (allDeps['@angular/core']) return 'angular'
1043
+ if (allDeps['preact']) return 'preact'
1044
+ }
1045
+ } catch {}
1046
+ return 'react'
1047
+ }
1048
+ const detectedFramework = detectFramework()
1049
+ const registryExtension = detectRegistryExtension()
1050
+ const registryFilename = `registry.${registryExtension}`
1051
+ // registerBones lives in @acowale/orion-boneyard (shared). configureBoneyard is framework-specific.
1052
+ const frameworkPaths = { react: '@acowale/orion-boneyard/react', vue: '@acowale/orion-boneyard/vue', native: '@acowale/orion-boneyard/native', svelte: '@acowale/orion-boneyard/svelte', angular: '@acowale/orion-boneyard/angular', preact: '@acowale/orion-boneyard/preact' }
1053
+ const registryImportPath = '@acowale/orion-boneyard'
1054
+ const configImportPath = frameworkPaths[detectedFramework] || '@acowale/orion-boneyard/react'
1055
+ const registryLines = [
1056
+ ...(detectedFramework === 'react' ? ['"use client"'] : []),
1057
+ '// Auto-generated by `npx orion-boneyard build` — do not edit',
1058
+ ]
1059
+ if (hasRuntimeConfig) {
1060
+ registryLines.push(`import { registerBones } from '${registryImportPath}'`)
1061
+ registryLines.push(`import { configureBoneyard } from '${configImportPath}'`)
1062
+ } else {
1063
+ registryLines.push(`import { registerBones } from '${registryImportPath}'`)
1064
+ }
1065
+ registryLines.push('')
1066
+ for (const name of names) {
1067
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_')
1068
+ const varName = '_' + safeName.replace(/[^a-zA-Z0-9]/g, '_')
1069
+ registryLines.push(`import ${varName} from './${safeName}.bones.json'`)
1070
+ }
1071
+ registryLines.push('')
1072
+
1073
+ // Emit configureBoneyard call if runtime defaults exist in config
1074
+ if (hasRuntimeConfig) {
1075
+ const runtimeConfig = {}
1076
+ for (const k of runtimeKeys) {
1077
+ if (config[k] !== undefined) runtimeConfig[k] = config[k]
1078
+ }
1079
+ registryLines.push(`configureBoneyard(${JSON.stringify(runtimeConfig)})`)
1080
+ registryLines.push('')
1081
+ }
1082
+
1083
+ registryLines.push('registerBones({')
1084
+ for (const name of names) {
1085
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_')
1086
+ const varName = '_' + safeName.replace(/[^a-zA-Z0-9]/g, '_')
1087
+ registryLines.push(` "${safeName}": ${varName},`)
1088
+ }
1089
+ registryLines.push('})')
1090
+ registryLines.push('')
1091
+
1092
+ const registryPath = join(outputDir, registryFilename)
1093
+ writeFileSync(registryPath, registryLines.join('\n'))
1094
+ console.log(` \x1b[32m→\x1b[0m ${registryFilename} \x1b[2m(${names.length} skeleton${names.length !== 1 ? 's' : ''})\x1b[0m`)
1095
+
1096
+ const count = names.length
1097
+ const skippedCount = skippedSkeletons.size
1098
+ const updatedCount = count - skippedCount
1099
+ if (skippedCount > 0) {
1100
+ console.log(`\n \x1b[32m\x1b[1m💀 ${count} skeleton${count !== 1 ? 's' : ''}\x1b[0m \x1b[2m(${updatedCount} updated, ${skippedCount} unchanged)\x1b[0m\n`)
1101
+ } else {
1102
+ console.log(`\n \x1b[32m\x1b[1m💀 ${count} skeleton${count !== 1 ? 's' : ''} captured.\x1b[0m\n`)
1103
+ }
1104
+ console.log(` \x1b[2mAdd once to your app entry:\x1b[0m import '${outDir}/registry'`)
1105
+ if (nativeMode) {
1106
+ console.log(` \x1b[2mImport Skeleton from:\x1b[0m import { Skeleton } from '@acowale/orion-boneyard/native'`)
1107
+ }
1108
+ console.log(` \x1b[2mThen just use:\x1b[0m <Skeleton name="..." loading={isLoading}>\n`)
1109
+
1110
+
1111
+ // ── Watch mode ───────────────────────────────────────────────────────────────
1112
+
1113
+ if (watchMode && !nativeMode) {
1114
+ console.log(` \x1b[2m👀 Watching for changes... (Ctrl+C to stop)\x1b[0m\n`)
1115
+
1116
+ // Store a snapshot of all bone hashes from the initial build
1117
+ let lastSnapshot = JSON.stringify(collected)
1118
+
1119
+ function writeWatchResults() {
1120
+ const writeNames = Object.keys(collected)
1121
+ if (writeNames.length === 0) return
1122
+
1123
+ mkdirSync(outputDir, { recursive: true })
1124
+ for (const [wName, wData] of Object.entries(collected)) {
1125
+ const safeName = wName.replace(/[^a-zA-Z0-9._-]/g, '_')
1126
+ const wPath = resolve(outputDir, `${safeName}.bones.json`)
1127
+ if (!wPath.startsWith(resolve(outputDir))) continue
1128
+ writeFileSync(wPath, JSON.stringify(wData, null, 2))
1129
+ }
1130
+
1131
+ const wRegistryLines = [
1132
+ ...(detectedFramework === 'react' ? ['"use client"'] : []),
1133
+ '// Auto-generated by `npx orion-boneyard build` — do not edit',
1134
+ ]
1135
+ if (hasRuntimeConfig) {
1136
+ wRegistryLines.push(`import { registerBones } from '${registryImportPath}'`)
1137
+ wRegistryLines.push(`import { configureBoneyard } from '${configImportPath}'`)
1138
+ } else {
1139
+ wRegistryLines.push(`import { registerBones } from '${registryImportPath}'`)
1140
+ }
1141
+ wRegistryLines.push('')
1142
+ for (const wn of writeNames) {
1143
+ const wsafe = wn.replace(/[^a-zA-Z0-9._-]/g, '_')
1144
+ const wv = '_' + wsafe.replace(/[^a-zA-Z0-9]/g, '_')
1145
+ wRegistryLines.push(`import ${wv} from './${wsafe}.bones.json'`)
1146
+ }
1147
+ wRegistryLines.push('')
1148
+ if (hasRuntimeConfig) {
1149
+ const rc = {}
1150
+ if (config.color) rc.color = config.color
1151
+ if (config.darkColor) rc.darkColor = config.darkColor
1152
+ if (config.animate !== undefined) rc.animate = config.animate
1153
+ wRegistryLines.push(`configureBoneyard(${JSON.stringify(rc)})`)
1154
+ wRegistryLines.push('')
1155
+ }
1156
+ wRegistryLines.push('registerBones({')
1157
+ for (const wn of writeNames) {
1158
+ const wsafe = wn.replace(/[^a-zA-Z0-9._-]/g, '_')
1159
+ const wv = '_' + wsafe.replace(/[^a-zA-Z0-9]/g, '_')
1160
+ wRegistryLines.push(` "${wsafe}": ${wv},`)
1161
+ }
1162
+ wRegistryLines.push('})')
1163
+ wRegistryLines.push('')
1164
+ writeFileSync(join(outputDir, registryFilename), wRegistryLines.join('\n'))
1165
+ }
1166
+
1167
+ async function recapture() {
1168
+ const originalLog = console.log
1169
+ originalLog(` \x1b[2m⟳ Change detected — recapturing...\x1b[0m`)
1170
+ console.log = () => {}
1171
+ try {
1172
+ // Don't wipe `collected` on recapture — skeletons whose routes aren't
1173
+ // re-visited this pass should stay in the registry (#81). Fresh
1174
+ // captures will overwrite their entries via `capturePage`.
1175
+ skippedSkeletons.clear()
1176
+ visited.clear()
1177
+ toVisit.length = 0
1178
+ for (const url of urls) toVisit.push(url)
1179
+
1180
+ for (const watchUrl of [...toVisit]) {
1181
+ if (visited.has(watchUrl)) continue
1182
+ visited.add(watchUrl)
1183
+ // In single-page mode the explicit URLs are the entire queue —
1184
+ // do not follow links out of them.
1185
+ if (singlePageMode) continue
1186
+ const links = await discoverLinks(watchUrl)
1187
+ for (const link of links) {
1188
+ if (!visited.has(link) && !toVisit.includes(link)) toVisit.push(link)
1189
+ }
1190
+ }
1191
+ for (const watchUrl of toVisit) {
1192
+ await capturePage(watchUrl)
1193
+ }
1194
+
1195
+ const newSnapshot = JSON.stringify(collected)
1196
+ if (newSnapshot !== lastSnapshot && Object.keys(collected).length > 0) {
1197
+ lastSnapshot = newSnapshot
1198
+ const ts = new Date().toLocaleTimeString()
1199
+ const updatedNames = Object.keys(collected)
1200
+ originalLog(` \x1b[32m↻\x1b[0m \x1b[2m${ts}\x1b[0m Updated: ${updatedNames.join(', ')}`)
1201
+ writeWatchResults()
1202
+ }
1203
+ } catch {
1204
+ // Dev server might be restarting — ignore
1205
+ } finally {
1206
+ console.log = originalLog
1207
+ }
1208
+ }
1209
+
1210
+ let debounceTimer = null
1211
+ let isRecapturing = false
1212
+
1213
+ function scheduleRecapture() {
1214
+ if (isRecapturing) return
1215
+ if (debounceTimer) clearTimeout(debounceTimer)
1216
+ debounceTimer = setTimeout(async () => {
1217
+ if (isRecapturing) return
1218
+ isRecapturing = true
1219
+ try { await recapture() } finally { isRecapturing = false }
1220
+ }, 2000)
1221
+ }
1222
+
1223
+ // Navigate to the start page and wait for it to settle
1224
+ await gotoPage(page, urls[0])
1225
+
1226
+ // NOW start listening — after initial build + navigation are done
1227
+ // Detect HMR updates across frameworks:
1228
+ // Vite: "[vite] hot updated: /src/App.vue"
1229
+ // Next.js: "[Fast Refresh] done" or "[HMR] connected"
1230
+ // Webpack: "[HMR] Updated modules:" or "[webpack] Recompiling"
1231
+ // Nuxt: "[vite] hot updated"
1232
+ // SvelteKit: "[vite] hot updated"
1233
+ page.on('console', (msg) => {
1234
+ const text = msg.text()
1235
+ if (text.includes('hot updated') ||
1236
+ text.includes('Fast Refresh] done') ||
1237
+ text.includes('[HMR] Updated') ||
1238
+ text.includes('Recompiling')) {
1239
+ scheduleRecapture()
1240
+ }
1241
+ })
1242
+
1243
+ // Graceful shutdown
1244
+ process.on('SIGINT', async () => {
1245
+ if (debounceTimer) clearTimeout(debounceTimer)
1246
+ if (cdpContext) await cdpContext.close()
1247
+ await browser.close()
1248
+ console.log('\n \x1b[2mWatch stopped.\x1b[0m\n')
1249
+ process.exit(0)
1250
+ })
1251
+
1252
+ // Keep process alive
1253
+ await new Promise(() => {})
1254
+ }
1255
+
1256
+ // ── Native scan command ──────────────────────────────────────────────────────
1257
+
1258
+ async function runScan() {
1259
+ const scanOut = outDir
1260
+ const scanPort = 9999
1261
+ const scanTimeout = watchMode ? 0 : 120000
1262
+
1263
+ const scanOutDir = resolve(process.cwd(), scanOut)
1264
+ mkdirSync(scanOutDir, { recursive: true })
1265
+
1266
+ const collected = {}
1267
+ let skeletonCount = 0
1268
+
1269
+ // Seed previously-captured bones from disk so re-running a scan (or opening
1270
+ // a single screen) doesn't drop other skeletons from the registry. The
1271
+ // native flow captures one mounted screen at a time, so without this the
1272
+ // registry was rewritten with only the screen visible this run (#87).
1273
+ // Mirrors the web/vite --cdp preservation from #81.
1274
+ const existingBones = {}
1275
+ if (existsSync(scanOutDir)) {
1276
+ try {
1277
+ for (const f of readdirSync(scanOutDir)) {
1278
+ if (!f.endsWith('.bones.json')) continue
1279
+ try {
1280
+ existingBones[f.replace(/\.bones\.json$/, '')] = JSON.parse(readFileSync(join(scanOutDir, f), 'utf-8'))
1281
+ } catch { /* malformed file — a fresh capture will overwrite it */ }
1282
+ }
1283
+ } catch { /* directory unreadable — no-op */ }
1284
+ }
1285
+
1286
+ console.log('')
1287
+ console.log(' \x1b[1m💀 boneyard build --native\x1b[0m')
1288
+ console.log('')
1289
+ console.log(` \x1b[2mListening on port ${scanPort}...\x1b[0m`)
1290
+ console.log(` \x1b[2mSaving to: ${scanOut}\x1b[0m`)
1291
+ console.log('')
1292
+ console.log(' Open your app — bones are captured automatically.')
1293
+ if (watchMode) {
1294
+ console.log(' \x1b[2m👀 Watch mode — stays open until you press Ctrl+C.\x1b[0m')
1295
+ } else {
1296
+ console.log(' \x1b[2mPress Ctrl+C when done, or wait for all bones.\x1b[0m')
1297
+ }
1298
+ console.log('')
1299
+
1300
+ return new Promise((resolvePromise) => {
1301
+ let doneTimer = null
1302
+
1303
+ function writeBones() {
1304
+ const freshCount = Object.keys(collected).length
1305
+ // Merge in previously-captured skeletons not seen this run so the
1306
+ // registry keeps them instead of dropping to just this run's screens
1307
+ // (#87). Fresh captures always win over the on-disk copy.
1308
+ mergePreservingExisting(collected, existingBones)
1309
+ const names = Object.keys(collected)
1310
+ if (names.length === 0) {
1311
+ console.log(' \x1b[33m⚠ No bones received.\x1b[0m')
1312
+ console.log(' Make sure your app has <Skeleton name="..." loading={...}> components')
1313
+ console.log(' and the app is open on device/simulator.\n')
1314
+ resolvePromise()
1315
+ return
1316
+ }
1317
+ if (freshCount === 0) {
1318
+ const kept = names.length
1319
+ console.log(` \x1b[33m⚠ No new bones received — keeping ${kept} previously captured skeleton${kept !== 1 ? 's' : ''}.\x1b[0m`)
1320
+ }
1321
+
1322
+ console.log(`\n \x1b[2m${'─'.repeat(50)}\x1b[0m`)
1323
+ console.log(' \x1b[1mWriting files\x1b[0m\n')
1324
+
1325
+ for (const [name, data] of Object.entries(collected)) {
1326
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_')
1327
+ const outPath = join(scanOutDir, `${safeName}.bones.json`)
1328
+ // Ensure the resolved path stays within the output directory
1329
+ const resolvedOut = resolve(outPath)
1330
+ const resolvedDir = resolve(scanOutDir)
1331
+ if (!resolvedOut.startsWith(resolvedDir)) {
1332
+ console.error(` \x1b[31m✗\x1b[0m Skipping "${name}" — path escapes output directory`)
1333
+ continue
1334
+ }
1335
+ writeFileSync(resolvedOut, JSON.stringify(data, null, 2))
1336
+ const bpCount = Object.keys(data.breakpoints).length
1337
+ console.log(` \x1b[32m→\x1b[0m ${safeName}.bones.json \x1b[2m(${bpCount} breakpoint${bpCount !== 1 ? 's' : ''})\x1b[0m`)
1338
+ }
1339
+
1340
+ // Generate registry
1341
+ const registryLines = [
1342
+ '// Auto-generated by `npx orion-boneyard scan` — do not edit',
1343
+ "import { registerBones } from '@acowale/orion-boneyard/native'",
1344
+ '',
1345
+ ]
1346
+ for (const name of names) {
1347
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_')
1348
+ const varName = '_' + safeName.replace(/[^a-zA-Z0-9]/g, '_')
1349
+ registryLines.push(`import ${varName} from './${safeName}.bones.json'`)
1350
+ }
1351
+ registryLines.push('')
1352
+ registryLines.push('registerBones({')
1353
+ for (const name of names) {
1354
+ const safeName = name.replace(/[^a-zA-Z0-9._-]/g, '_')
1355
+ const varName = '_' + safeName.replace(/[^a-zA-Z0-9]/g, '_')
1356
+ registryLines.push(` "${safeName}": ${varName},`)
1357
+ }
1358
+ registryLines.push('})')
1359
+ registryLines.push('')
1360
+
1361
+ const scanRegistryExt = detectRegistryExtension()
1362
+ const scanRegistryName = `registry.${scanRegistryExt}`
1363
+ const registryPath = join(scanOutDir, scanRegistryName)
1364
+ writeFileSync(registryPath, registryLines.join('\n'))
1365
+ console.log(` \x1b[32m→\x1b[0m ${scanRegistryName} \x1b[2m(${names.length} skeleton${names.length !== 1 ? 's' : ''})\x1b[0m`)
1366
+
1367
+ console.log(`\n \x1b[32m\x1b[1m💀 ${names.length} skeleton${names.length !== 1 ? 's' : ''} captured.\x1b[0m\n`)
1368
+ console.log(` \x1b[2mAdd once to your app entry:\x1b[0m import '${scanOut}/registry'`)
1369
+ console.log(` \x1b[2mImport Skeleton from:\x1b[0m import { Skeleton } from '@acowale/orion-boneyard/native'`)
1370
+ console.log(` \x1b[2mThen just use:\x1b[0m <Skeleton name="..." loading={isLoading}>\n`)
1371
+
1372
+ resolvePromise()
1373
+ }
1374
+
1375
+ // Auto-finish 2s after last bone received (watch mode: only write if changed)
1376
+ let lastWrittenSnapshot = ''
1377
+ function resetDoneTimer() {
1378
+ if (watchMode) {
1379
+ // Only write if bones actually changed — prevents Metro hot reload loop
1380
+ const snapshot = JSON.stringify(collected)
1381
+ if (snapshot !== lastWrittenSnapshot && Object.keys(collected).length > 0) {
1382
+ lastWrittenSnapshot = snapshot
1383
+ writeBones()
1384
+ }
1385
+ return
1386
+ }
1387
+ if (doneTimer) clearTimeout(doneTimer)
1388
+ doneTimer = setTimeout(() => {
1389
+ server.close()
1390
+ writeBones()
1391
+ }, 2000)
1392
+ }
1393
+
1394
+ const server = http.createServer((req, res) => {
1395
+ // CORS for device → localhost
1396
+ res.setHeader('Access-Control-Allow-Origin', '*')
1397
+ res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS')
1398
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
1399
+
1400
+ if (req.method === 'OPTIONS') {
1401
+ res.writeHead(200)
1402
+ res.end()
1403
+ return
1404
+ }
1405
+
1406
+ if (req.method === 'POST' && req.url === '/bones') {
1407
+ const MAX_BODY = 5 * 1024 * 1024 // 5MB limit
1408
+ let body = ''
1409
+ let overflow = false
1410
+ req.on('data', chunk => {
1411
+ body += chunk
1412
+ if (body.length > MAX_BODY) {
1413
+ overflow = true
1414
+ req.destroy()
1415
+ }
1416
+ })
1417
+ req.on('end', () => {
1418
+ if (overflow) {
1419
+ res.writeHead(413)
1420
+ res.end(JSON.stringify({ error: 'Request body too large' }))
1421
+ return
1422
+ }
1423
+ try {
1424
+ const data = JSON.parse(body)
1425
+ const name = data.name
1426
+ const result = data.result
1427
+ const responsive = data.responsive
1428
+
1429
+ // Validate name: must be a non-empty string with safe characters only
1430
+ if (!name || typeof name !== 'string' || !/^[a-zA-Z0-9._-]+$/.test(name)) {
1431
+ res.writeHead(400)
1432
+ res.end(JSON.stringify({ error: 'Invalid skeleton name. Use only alphanumeric, dot, dash, underscore.' }))
1433
+ return
1434
+ }
1435
+
1436
+ if (responsive && typeof responsive === 'object' && responsive.breakpoints) {
1437
+ collected[name] = responsive
1438
+ const bpCount = Object.keys(responsive.breakpoints).length
1439
+ console.log(` \x1b[32m✓\x1b[0m ${name} \x1b[2m(${bpCount} breakpoints)\x1b[0m`)
1440
+ skeletonCount++
1441
+ } else if (result && typeof result === 'object') {
1442
+ if (!collected[name]) collected[name] = { breakpoints: {} }
1443
+ const bp = result.viewportWidth || result.width
1444
+ collected[name].breakpoints[bp] = result
1445
+ const boneCount = result.bones?.length ?? 0
1446
+ console.log(` \x1b[32m✓\x1b[0m ${name} \x1b[2m(${boneCount} bones @ ${bp}px)\x1b[0m`)
1447
+ skeletonCount++
1448
+ }
1449
+
1450
+ resetDoneTimer()
1451
+ res.writeHead(200, { 'Content-Type': 'application/json' })
1452
+ res.end(JSON.stringify({ ok: true }))
1453
+ } catch (err) {
1454
+ console.error(` \x1b[31m✗\x1b[0m Error: ${err.message}`)
1455
+ res.writeHead(400)
1456
+ res.end(JSON.stringify({ error: err.message }))
1457
+ }
1458
+ })
1459
+ return
1460
+ }
1461
+
1462
+ // Health check — BoneScan pings this to know the CLI is running
1463
+ if (req.method === 'GET' && req.url === '/ping') {
1464
+ res.writeHead(200, { 'Content-Type': 'application/json' })
1465
+ res.end(JSON.stringify({ boneyard: true }))
1466
+ return
1467
+ }
1468
+
1469
+ res.writeHead(404)
1470
+ res.end('Not found')
1471
+ })
1472
+
1473
+ server.listen(scanPort, '0.0.0.0')
1474
+
1475
+ // Global timeout (disabled in watch mode)
1476
+ if (scanTimeout > 0) {
1477
+ setTimeout(() => {
1478
+ server.close()
1479
+ writeBones()
1480
+ }, scanTimeout)
1481
+ }
1482
+
1483
+ // Handle Ctrl+C gracefully
1484
+ process.on('SIGINT', () => {
1485
+ server.close()
1486
+ writeBones()
1487
+ })
1488
+ })
1489
+ }
1490
+
1491
+ // ── Help ──────────────────────────────────────────────────────────────────────
1492
+
1493
+ function printHelp() {
1494
+ console.log(`
1495
+ boneyard build [url] [options]
1496
+ boneyard --version
1497
+
1498
+ Visits your app in a headless browser, captures all named <Skeleton>
1499
+ components, and writes .bones.json files + a registry to disk.
1500
+
1501
+ Auto-detects your dev server if no URL is given (scans ports 3000, 5173, etc.).
1502
+
1503
+ Options:
1504
+ --version, -v Print @acowale/orion-boneyard version and exit
1505
+ --out <dir> Output directory (default: ./src/bones)
1506
+ --breakpoints <bp> Comma-separated px widths (default: 375,768,1280)
1507
+ --wait <ms> Extra wait after page load (default: 800)
1508
+ --env-file <path> Load env vars from file (useful for Bun runtime)
1509
+ --force Recapture all skeletons (skip incremental cache)
1510
+ --no-scan Skip filesystem route scanning (only crawl links)
1511
+ --watch Re-capture when your app changes (listens for HMR)
1512
+ --cdp <port|ws-url> Connect to existing Chrome via debug port instead
1513
+ of launching Playwright (reuses cookies, auth, state).
1514
+ Launch Chrome with: --remote-debugging-port=<port>
1515
+ --user-data-dir=<dir> (required on Chrome 136+), or
1516
+ pass the ws://.../devtools/browser/<uuid> endpoint
1517
+ from the chrome://inspect remote-debugging toggle
1518
+ --native React Native mode — captures bones from a running
1519
+ native app on device/simulator (no browser needed).
1520
+ Registry imports from @acowale/orion-boneyard/native.
1521
+
1522
+ Config file:
1523
+ Create boneyard.config.json in your project root to set defaults:
1524
+
1525
+ {
1526
+ "breakpoints": [375, 768, 1280],
1527
+ "out": "./src/bones",
1528
+ "wait": 800,
1529
+ "routes": ["/dashboard", "/settings/profile"]
1530
+ }
1531
+
1532
+ CLI flags override config file values. Use "routes" to explicitly list
1533
+ pages the CLI should visit (useful for Angular lazy modules, auth-gated
1534
+ pages, or any route not linked from the start page).
1535
+
1536
+ Authentication (for pages requiring login):
1537
+ {
1538
+ "resolveEnvVars": true,
1539
+ "auth": {
1540
+ "cookies": [{ "name": "session", "value": "env[SESSION_TOKEN]" }],
1541
+ "headers": { "Authorization": "Bearer env[TOKEN]" }
1542
+ }
1543
+ }
1544
+
1545
+ Use env[VAR_NAME] syntax to reference environment variables.
1546
+ Set resolveEnvVars: true to enable env var resolution.
1547
+ Note: env var resolution is only supported for auth config (cookies and headers).
1548
+ Use --env-file .env.local if env vars aren't in your shell (e.g. Bun runtime).
1549
+
1550
+ Examples:
1551
+ npx orion-boneyard build
1552
+ npx orion-boneyard build http://localhost:5173
1553
+ npx orion-boneyard build --watch
1554
+ npx orion-boneyard build --native --out ./bones
1555
+
1556
+ Web setup:
1557
+ 1. Wrap your component:
1558
+ <Skeleton name="blog-card" loading={isLoading}>
1559
+ <BlogCard />
1560
+ </Skeleton>
1561
+
1562
+ 2. Run: npx orion-boneyard build
1563
+
1564
+ 3. Import the registry once in your app entry:
1565
+ import './bones/registry'
1566
+
1567
+ React Native setup:
1568
+ 1. Wrap your component:
1569
+ import { Skeleton } from '@acowale/orion-boneyard/native'
1570
+ <Skeleton name="blog-card" loading={isLoading}>
1571
+ <BlogCard />
1572
+ </Skeleton>
1573
+
1574
+ 2. Run: npx orion-boneyard build --native
1575
+ Then open your app on device — bones capture automatically.
1576
+
1577
+ 3. Import the registry once in your app entry:
1578
+ import './bones/registry'
1579
+
1580
+ Done. Every <Skeleton name="..."> auto-resolves its bones.
1581
+ `)
1582
+ }