@realadvisor-sites/kit-core 0.4.2 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,7 @@
7
7
  * pnpm screenshot -- --url http://localhost:4321 --max 40
8
8
  * pnpm screenshot -- /listings /contact # only these paths
9
9
  * pnpm screenshot -- --jobs 1 # one page at a time (default 4)
10
+ * pnpm screenshot -- --inject fault.css # add a CSS file to every page (critic calibration)
10
11
  *
11
12
  * Output: screenshots/<route>@1440.png, screenshots/<route>@390.png and
12
13
  * screenshots/report.json. Exit code 1 if any page has console errors, failed
@@ -16,6 +17,7 @@
16
17
  import { chromium } from 'playwright';
17
18
  import { spawn, spawnSync } from 'node:child_process';
18
19
  import { mkdir, rm, writeFile } from 'node:fs/promises';
20
+ import { readFileSync } from 'node:fs';
19
21
  import { resolve } from 'node:path';
20
22
  import { pathToFileURL } from 'node:url';
21
23
 
@@ -34,6 +36,9 @@ const MAX = Number(opt('max', '30'));
34
36
  // timers), so 4 at a time is about 3x faster than one after the other, even on 4 vCPUs.
35
37
  const JOBS = Math.max(1, Number(opt('jobs', process.env.SCREENSHOT_JOBS ?? '4')));
36
38
  const OUT = opt('out', 'screenshots');
39
+ // A CSS file added to every page after load (the critic's calibration cases put a fault back with it).
40
+ const INJECT = opt('inject', '');
41
+ const injectCss = INJECT ? readFileSync(INJECT, 'utf8') : '';
37
42
  const explicit = args.filter((a) => a.startsWith('/'));
38
43
  const WIDTHS = [
39
44
  { name: '1440', width: 1440, height: 900 },
@@ -243,6 +248,7 @@ async function shoot({ path, vp, i }) {
243
248
  return null;
244
249
  });
245
250
  await page.waitForLoadState('load', { timeout: 10000 }).catch(() => {});
251
+ if (injectCss) await page.addStyleTag({ content: injectCss }).catch(() => {});
246
252
  const status = res?.status() ?? 0;
247
253
  entry.status = Math.max(entry.status, status);
248
254
  if (status >= 400) entry.problems.push(`[${vp.name}] page HTTP ${status}`);
@@ -375,15 +381,206 @@ async function shoot({ path, vp, i }) {
375
381
  const drawnH = contain ? Math.min(r.height, r.width / nat) : r.height;
376
382
  return { name: (i.alt || i.currentSrc.split('/').pop() || '').slice(0, 40), fit, dev: (r.width / r.height) / nat, contain, drawnW, drawnH };
377
383
  })(),
384
+ // Taste (TASTE.md): proportions, colour restraint, reading comfort. Measured, never judged.
385
+ taste: (() => {
386
+ const vw = innerWidth, vh = innerHeight;
387
+ const rgb = (c) => (c.match(/[\d.]+/g) || []).map(Number);
388
+ const hsl = ([r, g, b]) => {
389
+ r /= 255; g /= 255; b /= 255;
390
+ const mx = Math.max(r, g, b), mn = Math.min(r, g, b), l = (mx + mn) / 2, d = mx - mn;
391
+ const sat = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
392
+ let h = 0;
393
+ if (d) h = mx === r ? ((g - b) / d) % 6 : mx === g ? (b - r) / d + 2 : (r - g) / d + 4;
394
+ return { h: (h * 60 + 360) % 360, s: sat, l };
395
+ };
396
+ const vivid = (c) => { const v = rgb(c); if (v.length < 3 || (v.length > 3 && v[3] < 0.9)) return null; const x = hsl(v); return x.s >= 0.6 && x.l >= 0.3 && x.l <= 0.72 ? x : null; };
397
+ const header = document.querySelector('header, [role="banner"]');
398
+ const headerH = header ? header.getBoundingClientRect().height : 0;
399
+ // Large vivid fields: a full-bleed band or block in a saturated colour.
400
+ const fields = [];
401
+ const hues = new Map();
402
+ for (const n of document.querySelectorAll('body *')) {
403
+ const cs = getComputedStyle(n);
404
+ if (cs.display === 'none' || cs.visibility === 'hidden') continue;
405
+ const r = n.getBoundingClientRect();
406
+ if (!r.width || !r.height) continue;
407
+ const bg = vivid(cs.backgroundColor);
408
+ if (bg) {
409
+ const area = r.width * Math.min(r.height, vh);
410
+ const bucket = Math.round(bg.h / 30) * 30;
411
+ hues.set(bucket, (hues.get(bucket) || 0) + area);
412
+ if (area >= vw * vh * 0.2) fields.push(`${n.tagName.toLowerCase()}${n.className && typeof n.className === 'string' ? '.' + n.className.trim().split(/\s+/)[0] : ''} ${cs.backgroundColor} ${Math.round(r.width)}x${Math.round(r.height)}`);
413
+ }
414
+ const fg = vivid(cs.color);
415
+ if (fg && n.childNodes.length && [...n.childNodes].some((c) => c.nodeType === 3 && c.textContent.trim())) {
416
+ const bucket = Math.round(fg.h / 30) * 30;
417
+ hues.set(bucket, (hues.get(bucket) || 0) + r.width * r.height);
418
+ }
419
+ }
420
+ const accentHues = [...hues].filter(([, a]) => a >= 400).map(([h]) => h % 360);
421
+ // Reading comfort: body paragraphs.
422
+ let longLines = 0, smallBody = 0, paras = 0;
423
+ for (const p of document.querySelectorAll('main p, article p')) {
424
+ const cs = getComputedStyle(p), fs = parseFloat(cs.fontSize), lh = parseFloat(cs.lineHeight) || fs * 1.4;
425
+ const r = p.getBoundingClientRect(), text = p.textContent.trim();
426
+ if (!r.width || text.length < 120 || fs > 22) continue;
427
+ paras++;
428
+ const lines = Math.max(1, Math.round(r.height / lh));
429
+ if (lines >= 3 && text.length / lines > 90) longLines++;
430
+ if (fs < 15) smallBody++;
431
+ }
432
+ // Soft photos: the file actually loaded (its real pixels, not the srcset's claim; an
433
+ // image CDN never enlarges) against the box it fills x devicePixelRatio (capped at 1.5:
434
+ // a 1.5x file already looks sharp on a 2x phone). Decorative images are exempt unless
435
+ // they are the hero or a big photo (an aria-hidden hero link still counts).
436
+ const dpr = Math.min(devicePixelRatio || 1, 1.5);
437
+ const soft = [];
438
+ for (const i of document.images) {
439
+ const r = i.getBoundingClientRect();
440
+ const src = i.currentSrc || i.src;
441
+ const realW = Number(i.dataset.realW) || i.naturalWidth;
442
+ const realH = Number(i.dataset.realH) || i.naturalHeight;
443
+ if (r.width < 160 || r.height < 120 || !realW || !realH || /\.svg(\?|$)/i.test(src) || i.closest('header, [role="banner"]')) continue;
444
+ const cs = getComputedStyle(i);
445
+ if (cs.filter.includes('blur')) continue; // a blurred placeholder or backdrop
446
+ const big = r.width >= vw * 0.4;
447
+ const hero = i.getAttribute('fetchpriority') === 'high' || i.closest('[data-hero]');
448
+ if (i.getAttribute('alt') === '' && !hero && !big) continue;
449
+ const nat = realW / realH;
450
+ const cover = cs.objectFit !== 'contain' && cs.objectFit !== 'scale-down';
451
+ const fillW = cover ? Math.max(r.width, r.height * nat) : r.width;
452
+ const up = (fillW * dpr) / realW;
453
+ // An image CDN hides the file name in base64: name the original file.
454
+ let file = src.split('/').pop()?.split('?')[0] ?? '';
455
+ try { const o = atob(file.split('.')[0].replace(/-/g, '+').replace(/_/g, '/')); if (/^https?:\/\//.test(o)) file = o.split('/').pop(); } catch {}
456
+ if (up > 1.15) soft.push(`"${(i.alt || file || '').slice(0, 40)}" file ${realW}x${realH} fills ${Math.round(fillW)}px x ${dpr} dpr (upscaled ${Math.round(up * 100)}%)${hero ? ', the hero' : ''}`);
457
+ }
458
+ // Ledes: the first paragraph after a section heading (h1/h2, an eyebrow may sit
459
+ // between). One style for every lede: family, size, weight, italic, full or muted
460
+ // colour (contrast with the ground under it). Colour is relative, so white on ink
461
+ // and near-black on paper are the same style.
462
+ const ground = (n) => {
463
+ for (let e = n; e; e = e.parentElement) {
464
+ const c = rgb(getComputedStyle(e).backgroundColor);
465
+ if (c.length >= 3 && (c.length < 4 || c[3] > 0.5)) return c.slice(0, 3);
466
+ }
467
+ return [255, 255, 255];
468
+ };
469
+ const lin = (v) => ((v /= 255) <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
470
+ const lum = ([r, g, b]) => 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
471
+ const contrast = (a, b) => { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); };
472
+ const blend = (c, under) => (c.length > 3 && c[3] < 1 ? c.slice(0, 3).map((v, k) => v * c[3] + under[k] * (1 - c[3])) : c.slice(0, 3));
473
+ const family = (f) => f.split(',')[0].trim().replace(/^["']|["']$/g, '');
474
+ const ledes = new Map();
475
+ for (const h of document.querySelectorAll('main h1, main h2')) {
476
+ let p = h.nextElementSibling;
477
+ if (p && p.tagName !== 'P' && (p.textContent || '').trim().length < 40) p = p.nextElementSibling; // an eyebrow or rule after the heading
478
+ if (!p || p.tagName !== 'P') continue;
479
+ const cs = getComputedStyle(p), r = p.getBoundingClientRect(), text = p.textContent.trim();
480
+ if (!r.width || text.length < 40 || parseFloat(cs.fontSize) < 15 || p.closest('form, [data-enquiry]')) continue;
481
+ // A heading styled as an eyebrow (a small h2 over a statement or a big number) has no lede.
482
+ if (parseFloat(getComputedStyle(h).fontSize) < parseFloat(cs.fontSize) * 1.25) continue;
483
+ const g = ground(p);
484
+ const tone = contrast(blend(rgb(cs.color), g), g) >= 9 ? 'full' : 'muted';
485
+ const sig = `${family(cs.fontFamily)} ${Math.round(parseFloat(cs.fontSize))}px ${cs.fontWeight}${cs.fontStyle === 'italic' ? ' italic' : ''} ${tone}`;
486
+ if (!ledes.has(sig)) ledes.set(sig, []);
487
+ ledes.get(sig).push(`"${text.slice(0, 24)}…"`);
488
+ }
489
+ // Families in use, by characters drawn (a family under 3% of the text is a detail),
490
+ // and webfonts the CSS asks for that never loaded (a silent fallback to Georgia/Arial).
491
+ const chars = new Map();
492
+ let total = 0;
493
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
494
+ for (let t = walker.nextNode(); t; t = walker.nextNode()) {
495
+ const el = t.parentElement, n = t.textContent.trim().length;
496
+ if (!n || !el || el.closest('script, style, noscript, [hidden], .sr-only')) continue;
497
+ const r = el.getBoundingClientRect();
498
+ if (!r.width || !r.height) continue;
499
+ const f = family(getComputedStyle(el).fontFamily);
500
+ chars.set(f, (chars.get(f) || 0) + n);
501
+ total += n;
502
+ }
503
+ const families = [...chars].filter(([, n]) => n / total >= 0.03).sort((a, b) => b[1] - a[1]).map(([f, n]) => `${f} ${Math.round((n / total) * 100)}%`);
504
+ const faces = [...document.fonts];
505
+ const declared = (f) => faces.filter((ff) => ff.family.replace(/["']/g, '') === f);
506
+ // Only families the page itself declares (@font-face): a missing local font is not a bug here.
507
+ const notLoaded = [...chars.keys()].filter((f) => chars.get(f) / total >= 0.03 && declared(f).length && !declared(f).some((ff) => ff.status === 'loaded'));
508
+ // Craft defaults (DESIGN.md section 10). Elements with their own text, shown.
509
+ const own = (el) => [...el.childNodes].filter((c) => c.nodeType === 3).map((c) => c.textContent).join('').trim();
510
+ const label = (el) => `${el.tagName.toLowerCase()}${typeof el.className === 'string' && el.className.trim() ? '.' + el.className.trim().split(/\s+/)[0] : ''} "${(el.innerText || '').trim().replace(/\s+/g, ' ').slice(0, 28)}"`;
511
+ const shown = [...document.querySelectorAll('body *')].filter((el) => {
512
+ if (el.closest('script, style, noscript, [hidden], .sr-only, [aria-hidden="true"]')) return false;
513
+ const r = el.getBoundingClientRect();
514
+ return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== 'hidden';
515
+ });
516
+ const texts = shown.filter((el) => own(el));
517
+ // Justified body text, caps on sentences, straight double quotes in text.
518
+ const justified = [...document.querySelectorAll('main p, article p')].filter((p) => shown.includes(p) && getComputedStyle(p).textAlign === 'justify' && p.textContent.trim().length >= 120).map(label);
519
+ const longCaps = texts.filter((el) => {
520
+ const t = own(el);
521
+ return t.length > 40 && (getComputedStyle(el).textTransform === 'uppercase' || (/[A-ZÄÖÜÉÈÀ]{2}/.test(t) && t === t.toUpperCase() && /[A-Z]/.test(t) && t.replace(/[^A-Za-zÀ-ÿ]/g, '').length >= 20));
522
+ }).map(label);
523
+ const quotes = texts.filter((el) => !el.closest('code, pre, kbd, samp, input, textarea') && /"/.test(own(el))).map(label);
524
+ // Off-grid: a block whose left and right edges match no edge the layout gives it:
525
+ // another block's edge, its parent's content edges, its parent's grid tracks or the
526
+ // page edge (±3px). Catches ad-hoc margins and nudges, not a deliberate second
527
+ // column. Centred blocks and blocks inside another block are skipped.
528
+ const BLOCK = 'h1, h2, h3, p, ul, ol, dl, figure, form, picture, img, blockquote, address, table, a.more, .button, .btn';
529
+ const blocks = [...document.querySelectorAll(`main :is(${BLOCK})`)].filter((el) => shown.includes(el) && !el.parentElement.closest(BLOCK) && el.getBoundingClientRect().width >= 24);
530
+ const box = blocks.map((el) => ({ el, r: el.getBoundingClientRect() }));
531
+ const near = (x, xs) => xs.some((v) => Math.abs(v - x) <= 3);
532
+ const offGrid = box.filter(({ el, r }) => {
533
+ const cs = getComputedStyle(el);
534
+ const parent = el.parentElement.getBoundingClientRect();
535
+ if (cs.textAlign === 'center' && Math.abs((r.left - parent.left) - (parent.right - r.right)) < 6) return false;
536
+ // Second item in a row (a link after a button): it follows its sibling.
537
+ const prev = el.previousElementSibling?.getBoundingClientRect();
538
+ if (prev && prev.width && prev.top < r.bottom && prev.bottom > r.top && r.left - prev.right >= 0 && r.left - prev.right <= 64) return false;
539
+ const others = box.filter((o) => o.el !== el).flatMap((o) => [o.r.left, o.r.right]);
540
+ others.push(0, vw);
541
+ const pcs = getComputedStyle(el.parentElement);
542
+ const cl = parent.left + parseFloat(pcs.borderLeftWidth) + parseFloat(pcs.paddingLeft);
543
+ const cr = parent.right - parseFloat(pcs.borderRightWidth) - parseFloat(pcs.paddingRight);
544
+ others.push(cl, cr);
545
+ if (pcs.display.includes('grid')) {
546
+ const gap = parseFloat(pcs.columnGap) || 0;
547
+ let x = cl;
548
+ for (const t of pcs.gridTemplateColumns.split(/\s+/).map(parseFloat).filter((n) => !Number.isNaN(n))) { others.push(x, x + t); x += t + gap; }
549
+ }
550
+ return !near(r.left, others) && !near(r.right, others);
551
+ }).map(({ el }) => label(el));
552
+ return { vw, vh, headerH, fields: [...new Set(fields)].slice(0, 3), accentHues: [...new Set(accentHues)], longLines, smallBody, paras, soft: soft.slice(0, 4), ledes: [...ledes].map(([s, l]) => `${s} (${l.slice(0, 3).join(', ')})`), families, notLoaded, justified, longCaps, quotes, offGrid };
553
+ })(),
378
554
  }));
379
555
  // Hero text legibility: text over the hero photo, contrast against the pixels behind it.
380
556
  for (const t of await heroContrast(page)) entry.problems.push(`[${vp.name}] hero text "${t.text}" contrast ${t.ratio.toFixed(1)}:1 on the photo (need ${t.need}:1): add a scrim (gradient >= 0.55 black at the text's top edge) or a panel`);
381
557
  const lg = checks.logo;
382
558
  if (lg) {
383
559
  if (!lg.contain && (lg.dev > 1.05 || lg.dev < 0.95)) entry.problems.push(`[${vp.name}] logo "${lg.name}" ${lg.fit === 'fill' ? 'stretched' : 'cropped'} (box ratio ${(lg.dev * 100 - 100).toFixed(0)}% off the file): set only height (width: auto), no fixed box, no object-fit: cover`);
384
- if (vp.name === '1440' && (lg.drawnW < 100 || lg.drawnH < 32)) entry.problems.push(`[1440] logo "${lg.name}" drawn ${Math.round(lg.drawnW)}x${Math.round(lg.drawnH)}px: at least 100px wide and 32px tall (140–180px wide for a detailed logo)`);
560
+ // A wide wordmark is sized by width, a tall or square mark (a monogram, a stacked numeral) by height.
561
+ const wide = lg.drawnW / lg.drawnH >= 1.3;
562
+ if (vp.name === '1440' && wide && (lg.drawnW < 100 || lg.drawnH < 32)) entry.problems.push(`[1440] logo "${lg.name}" drawn ${Math.round(lg.drawnW)}x${Math.round(lg.drawnH)}px: at least 100px wide and 32px tall (140–180px wide for a detailed logo)`);
563
+ if (vp.name === '1440' && !wide && (lg.drawnH < 40 || lg.drawnH > 72)) entry.problems.push(`[1440] logo "${lg.name}" (a tall or square mark) drawn ${Math.round(lg.drawnH)}px tall: 40–72px tall`);
564
+ if (vp.name === '1440' && wide && lg.drawnH > 72) entry.problems.push(`[1440] taste: logo "${lg.name}" drawn ${Math.round(lg.drawnH)}px tall: at most 72px, the header stays slim`);
385
565
  if (vp.name === '390' && lg.drawnH < 28) entry.problems.push(`[390] logo "${lg.name}" drawn ${Math.round(lg.drawnH)}px tall: at least 28px`);
386
566
  }
567
+ const ts = checks.taste;
568
+ if (ts) {
569
+ const maxHeader = Math.round(ts.vh * 0.12);
570
+ if (ts.headerH > maxHeader) entry.problems.push(`[${vp.name}] taste: header ${Math.round(ts.headerH)}px tall, more than 12% of the screen (${maxHeader}px): slim it (logo 40–72px, one row)`);
571
+ for (const f of ts.fields) entry.problems.push(`[${vp.name}] taste: large field in a saturated colour (${f}): keep vivid brand colours for small accents; use a deep or muted shade, the ink colour or a neutral surface for bands`);
572
+ if (vp.name === '1440' && ts.accentHues.length > 2) entry.problems.push(`[1440] taste: ${ts.accentHues.length} saturated accent hues (${ts.accentHues.join(', ')}°): one accent, two at most`);
573
+ if (vp.name === '1440' && ts.longLines) entry.problems.push(`[1440] taste: ${ts.longLines} paragraph(s) over 90 characters a line: limit the measure (max-width about 65ch)`);
574
+ if (vp.name === '1440' && ts.smallBody) entry.problems.push(`[1440] taste: ${ts.smallBody} body paragraph(s) under 15px: body text 16–20px on desktop`);
575
+ for (const s of ts.soft) entry.problems.push(`[${vp.name}] taste: soft photo, ${s}: use a larger source or a smaller box (the file must cover the box x devicePixelRatio, up to 1.5x)`);
576
+ if (vp.name === '1440' && ts.ledes.length > 1) entry.problems.push(`[1440] taste: section ledes in ${ts.ledes.length} styles: ${ts.ledes.join(' | ')}: one lede style (one class) for every section`);
577
+ if (vp.name === '1440' && ts.families.length > 2) entry.problems.push(`[1440] taste: ${ts.families.length} font families in use (${ts.families.join(', ')}): two at most`);
578
+ if (vp.name === '1440' && ts.offGrid.length) entry.problems.push(`[1440] taste: off-grid, ${ts.offGrid.length} block(s) on no edge the layout gives them (other blocks, the parent's content box or grid tracks): ${ts.offGrid.slice(0, 3).join(', ')}: put them on the section's column edges`);
579
+ if (vp.name === '1440' && ts.justified.length) entry.problems.push(`[1440] taste: justified body text (${ts.justified.slice(0, 2).join(', ')}): left-align it, ragged right`);
580
+ if (vp.name === '1440' && ts.longCaps.length) entry.problems.push(`[1440] taste: caps on text over 40 characters (${ts.longCaps.slice(0, 2).join(', ')}): caps only for short labels`);
581
+ if (vp.name === '1440' && ts.quotes.length) entry.problems.push(`[1440] taste: straight " quotes in text (${ts.quotes.slice(0, 2).join(', ')}): use the language's marks („…“ de, « … » fr, «…» it/es, “…” en)`);
582
+ for (const f of ts.notLoaded) entry.problems.push(`[${vp.name}] taste: font "${f}" is declared but never loaded: the text falls back to another font (check the @fontsource import and the family name)`);
583
+ }
387
584
  for (const b of new Set(checks.blockers)) entry.problems.push(`[${vp.name}] invisible element blocks clicks: ${b} (closed overlays need visibility:hidden + pointer-events:none)`);
388
585
  // Click-through: a link below the fold must be the element under its own centre.
389
586
  const click = await page.evaluate(async () => {
@@ -13,10 +13,10 @@
13
13
  * pnpm kit test map # http://localhost:4321/listings
14
14
  * pnpm kit test map --url http://localhost:4391 --path /proprietes
15
15
  *
16
- * `data` (the agency fixture in src/data/, loadData) checks the cards
16
+ * `data` (the agency fixture in src/data/ or app/data/, loadData) checks the cards
17
17
  * against the listings' coordinates; without it those checks are skipped.
18
18
  */
19
- import { readdirSync, readFileSync } from 'node:fs';
19
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
20
20
  import { pathToFileURL } from 'node:url';
21
21
 
22
22
  const W = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -170,8 +170,13 @@ export async function checkSearchMap({ browser, base, path = '/listings', data =
170
170
  return ran;
171
171
  }
172
172
 
173
- /** The agency fixture in `<siteDir>/src/data/` (SITES_FIXTURE picks one), or null. */
173
+ /** The agency fixture in `<siteDir>/src/data/` (SITES_FIXTURE picks one) or `<siteDir>/app/data/fixture.json` (React Router), or null. */
174
174
  export function loadData(siteDir) {
175
+ const react = new URL('app/data/fixture.json', siteDir);
176
+ if (existsSync(react)) {
177
+ const d = JSON.parse(readFileSync(react, 'utf8'));
178
+ return d?.organisation && Array.isArray(d.listings) ? d : null;
179
+ }
175
180
  const dir = new URL('src/data/', siteDir);
176
181
  const wanted = process.env.SITES_FIXTURE;
177
182
  for (const f of readdirSync(dir).filter((f) => f.endsWith('.json'))) {
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Put a fixture in src/data/ for fixture mode (used when SITES_API_KEY is unset).
3
+ * Put a fixture in the site's data folder for fixture mode (used when
4
+ * SITES_API_KEY is unset): src/data/ on an Astro site, app/data/fixture.json
5
+ * on a React Router site (react-router.config.ts at the root; its
6
+ * data.server.ts imports that one file).
4
7
  * pnpm fixture # the kit's demo-agency.json (the fictional Demo Agency)
5
8
  * pnpm fixture demo-agency # same
6
9
  * pnpm fixture path/to/file.json
@@ -24,8 +27,10 @@ const RETIRED = new Set(['jan-skubincan', 'rockwell', 'phoenix-real-estate']);
24
27
 
25
28
  const ifEmpty = process.argv.includes('--if-empty');
26
29
  const arg = process.argv.slice(2).find((a) => !a.startsWith('--')) ?? process.env.SITES_FIXTURE;
27
- await mkdir('src/data', { recursive: true });
28
- const current = (await readdir('src/data')).filter((f) => f.endsWith('.json'));
30
+ const react = ['ts', 'mts', 'js', 'mjs'].some((x) => existsSync(`react-router.config.${x}`));
31
+ const DIR = react ? 'app/data' : 'src/data';
32
+ await mkdir(DIR, { recursive: true });
33
+ const current = (await readdir(DIR)).filter((f) => f.endsWith('.json'));
29
34
  if (ifEmpty && current.length) process.exit(0);
30
35
 
31
36
  const named = (name) => [`${FIXTURES}${name}.json`].find(existsSync);
@@ -34,7 +39,7 @@ let dest;
34
39
  if (arg && RETIRED.has(arg) && !named(arg)) {
35
40
  src = named(DEMO);
36
41
  dest = `${arg}.json`;
37
- if (src) console.warn(`Fixture ${arg} is retired: using the fictional Demo Agency (${DEMO}.json) as src/data/${dest}`);
42
+ if (src) console.warn(`Fixture ${arg} is retired: using the fictional Demo Agency (${DEMO}.json) as ${DIR}/${dest}`);
38
43
  } else if (arg) {
39
44
  src = arg.endsWith('.json') ? [arg].find(existsSync) : named(arg);
40
45
  } else {
@@ -49,7 +54,7 @@ if (!src) {
49
54
  console.error(`Fixture not found (${arg ?? `${FIXTURES}${DEMO}.json`})`);
50
55
  process.exit(1);
51
56
  }
52
- for (const f of current) await rm(`src/data/${f}`);
53
- dest ??= basename(src);
54
- await copyFile(src, `src/data/${dest}`);
55
- console.log(`Fixture mode uses src/data/${dest}`);
57
+ for (const f of current) await rm(`${DIR}/${f}`);
58
+ dest = react ? 'fixture.json' : (dest ?? basename(src));
59
+ await copyFile(src, `${DIR}/${dest}`);
60
+ console.log(`Fixture mode uses ${DIR}/${dest}`);