slicejs-cli 4.3.0 → 4.5.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.
Files changed (52) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +260 -257
  3. package/client.js +958 -823
  4. package/commands/Print.js +163 -163
  5. package/commands/Validations.js +92 -92
  6. package/commands/build/build.js +97 -107
  7. package/commands/buildProduction/buildProduction.js +613 -613
  8. package/commands/bundle/bundle.js +251 -239
  9. package/commands/createComponent/VisualComponentTemplate.js +55 -55
  10. package/commands/createComponent/createComponent.js +128 -128
  11. package/commands/deleteComponent/deleteComponent.js +81 -81
  12. package/commands/docs/docs.js +365 -365
  13. package/commands/doctor/doctor.js +730 -563
  14. package/commands/getComponent/getComponent.js +841 -842
  15. package/commands/init/init.js +526 -475
  16. package/commands/lint/lint.js +75 -0
  17. package/commands/lint/types.js +85 -0
  18. package/commands/listComponents/listComponents.js +172 -172
  19. package/commands/seo/check.js +94 -0
  20. package/commands/seo/images.js +641 -0
  21. package/commands/seo/sitemap.js +109 -0
  22. package/commands/seo/support.js +192 -0
  23. package/commands/setup/lint.js +151 -0
  24. package/commands/skill/skill.js +236 -236
  25. package/commands/startServer/startServer.js +240 -240
  26. package/commands/startServer/watchServer.js +66 -66
  27. package/commands/translator/check.js +32 -0
  28. package/commands/translator/init.js +125 -0
  29. package/commands/translator/scan.js +444 -0
  30. package/commands/typecheck/typecheck.js +83 -0
  31. package/commands/types/types.js +1378 -1097
  32. package/commands/utils/JsMinifier.js +230 -230
  33. package/commands/utils/LocalCliDelegation.js +78 -53
  34. package/commands/utils/PackageManager.js +148 -148
  35. package/commands/utils/PathHelper.js +87 -75
  36. package/commands/utils/ProjectValidation.js +274 -0
  37. package/commands/utils/SourceDiagnostics.js +201 -201
  38. package/commands/utils/VersionChecker.js +169 -169
  39. package/commands/utils/analyzeSource.js +77 -77
  40. package/commands/utils/bundling/BundleGenerator.js +3748 -3776
  41. package/commands/utils/bundling/DependencyAnalyzer.js +12 -2
  42. package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
  43. package/commands/utils/componentAudit.js +74 -0
  44. package/commands/utils/compressAssets.js +103 -103
  45. package/commands/utils/cssScope.js +83 -0
  46. package/commands/utils/loadConfig.js +31 -31
  47. package/commands/utils/semver.js +66 -0
  48. package/commands/utils/sliceConfigSchema.js +106 -0
  49. package/commands/utils/sliceScripts.js +48 -48
  50. package/commands/utils/updateManager.js +471 -471
  51. package/eslint-config.js +128 -0
  52. package/package.json +19 -13
@@ -0,0 +1,641 @@
1
+ // slice seo images — the social cards each route advertises.
2
+ //
3
+ // The command owns the mechanism (browser context, determinism, capture, card,
4
+ // encoding, hashing, cleanup). The app owns the intent (theme, selector,
5
+ // template, where the files go). It never edits `seo.json`: that file is
6
+ // generated by the app's pipeline, so the cards live in their own manifest
7
+ // (`<outDir>/manifest.json`), which the framework merges via `seo.images`.
8
+
9
+ import fs from 'node:fs';
10
+ import fsp from 'node:fs/promises';
11
+ import path from 'node:path';
12
+ import { spawn } from 'node:child_process';
13
+ import { createServer } from 'node:net';
14
+ import { createHash } from 'node:crypto';
15
+ import { createRequire } from 'node:module';
16
+ import { pathToFileURL } from 'node:url';
17
+ import Print from '../Print.js';
18
+ import { loadFrameworkSeo, loadManifest, loadSeoTranslator, writeFileConfirmed } from './support.js';
19
+
20
+ const CARD = { width: 1200, height: 630 };
21
+ const DEVICE_SCALE = 2;
22
+ const DEFAULT_BUDGET_KB = 120;
23
+ const DEFAULT_OUT_DIR = path.join('src', 'public', 'og');
24
+ const FIXED_TIME = new Date('2026-01-15T10:30:00Z');
25
+
26
+ const DEFAULTS = {
27
+ selector: null,
28
+ template: null,
29
+ theme: 'default',
30
+ budgetKB: DEFAULT_BUDGET_KB
31
+ };
32
+
33
+ // ── pure helpers ────────────────────────────────────────────────────────────
34
+
35
+ export const routeSlug = (route) => (route === '/'
36
+ ? 'home'
37
+ : String(route)
38
+ .replace(/^\/+|\/+$/g, '')
39
+ .replace(/[^a-z0-9]+/gi, '-')
40
+ .replace(/^-+|-+$/g, '')
41
+ .toLowerCase());
42
+
43
+ const escapeHtml = (value) => String(value ?? '')
44
+ .replace(/&/g, '&amp;')
45
+ .replace(/</g, '&lt;')
46
+ .replace(/>/g, '&gt;')
47
+ .replace(/"/g, '&quot;');
48
+
49
+ /** Pixel size from a PNG IHDR or a JPEG SOF marker. */
50
+ export function imageSize(buffer) {
51
+ if (buffer.readUInt32BE(0) === 0x89504e47) {
52
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20), type: 'image/png' };
53
+ }
54
+ let offset = 2;
55
+ while (offset < buffer.length - 9) {
56
+ if (buffer[offset] !== 0xff) { offset += 1; continue; }
57
+ const marker = buffer[offset + 1];
58
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
59
+ if (isSof) {
60
+ return { height: buffer.readUInt16BE(offset + 5), width: buffer.readUInt16BE(offset + 7), type: 'image/jpeg' };
61
+ }
62
+ offset += 2 + buffer.readUInt16BE(offset + 2);
63
+ }
64
+ throw new Error('could not read the image size');
65
+ }
66
+
67
+ const luminance = (hex) => {
68
+ const value = String(hex || '').replace('#', '');
69
+ if (!/^[0-9a-f]{3,8}$/i.test(value)) return null;
70
+ const expand = value.length <= 3 ? value.split('').map((c) => c + c).join('') : value;
71
+ const r = parseInt(expand.slice(0, 2), 16);
72
+ const g = parseInt(expand.slice(2, 4), 16);
73
+ const b = parseInt(expand.slice(4, 6), 16);
74
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255;
75
+ };
76
+
77
+ /** Routes that deserve a card: indexable literals only. */
78
+ export function selectRoutes(manifest, only = null) {
79
+ const wanted = only ? new Set(String(only).split(',').map((item) => item.trim())) : null;
80
+ return Object.entries(manifest?.routes || {})
81
+ .filter(([route, meta]) => {
82
+ if (/\$\{[^}]+\}/.test(route)) return false; // a pattern cannot be enumerated
83
+ if (meta?.robots === false || meta?.robots?.index === false) return false;
84
+ if (meta?.sitemap === false) return false;
85
+ return wanted ? wanted.has(route) : true;
86
+ })
87
+ .map(([route, meta]) => ({ route, meta }))
88
+ .sort((a, b) => a.route.localeCompare(b.route));
89
+ }
90
+
91
+ /**
92
+ * One card target per route — or per route and locale when the translator puts the locale
93
+ * in the URL. `url` is both what the browser captures and the key in the cards manifest,
94
+ * so the server can pick the card for the exact page it is serving.
95
+ */
96
+ export function cardTargets(manifest, translator = null, only = null) {
97
+ const wanted = only ? new Set(String(only).split(',').map((item) => item.trim())) : null;
98
+ const locales = translator?.enabled
99
+ ? (translator.localePrefix ? translator.locales : [translator.defaultLocale])
100
+ : [null];
101
+ const targets = [];
102
+
103
+ for (const { route, meta } of selectRoutes(manifest, null)) {
104
+ for (const locale of locales) {
105
+ const url = translator?.enabled ? translator.localize(route, locale) : route;
106
+ if (wanted && !wanted.has(route) && !wanted.has(url)) continue;
107
+ targets.push({ route, url, locale, meta });
108
+ }
109
+ }
110
+
111
+ return targets;
112
+ }
113
+
114
+ /** Neutral 1200×630 card. `template` replaces it entirely. */
115
+ export function buildCardHtml({ title, route, host, imageData, dark = false, template = null }) {
116
+ if (template) {
117
+ return String(template)
118
+ .replace(/{{title}}/g, escapeHtml(title))
119
+ .replace(/{{route}}/g, escapeHtml(route))
120
+ .replace(/{{host}}/g, escapeHtml(host))
121
+ .replace(/{{image}}/g, imageData || '');
122
+ }
123
+
124
+ const palette = dark
125
+ ? { bg: '#0f0d17', ink: '#f4f1fb', muted: '#a99cc4', line: '#2a2438', stage: '#16121f' }
126
+ : { bg: '#fbfaff', ink: '#1a0b2e', muted: '#6b46c1', line: '#e9e2f5', stage: '#ffffff' };
127
+
128
+ return `<!DOCTYPE html>
129
+ <html><head><meta charset="utf-8" /><style>
130
+ * { box-sizing: border-box; margin: 0; padding: 0; }
131
+ html, body { width: ${CARD.width}px; height: ${CARD.height}px; overflow: hidden; }
132
+ body {
133
+ font-family: "Source Sans 3", "Segoe UI", "Helvetica Neue", Arial, sans-serif;
134
+ background: ${palette.bg};
135
+ color: ${palette.ink};
136
+ -webkit-font-smoothing: antialiased;
137
+ }
138
+ .card { width: ${CARD.width}px; height: ${CARD.height}px; padding: 44px 56px 30px; display: flex; flex-direction: column; gap: 22px; }
139
+ .eyebrow { font-size: 13px; font-weight: 700; letter-spacing: 3.2px; text-transform: uppercase; color: ${palette.muted}; }
140
+ h1 { font-size: ${String(title).length > 34 ? 38 : String(title).length > 24 ? 44 : 54}px; line-height: 1.05; letter-spacing: -0.02em; }
141
+ .stage {
142
+ flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center;
143
+ overflow: hidden; padding: 26px; border-radius: 18px;
144
+ border: 1px solid ${palette.line}; background: ${palette.stage};
145
+ }
146
+ .stage img { display: block; max-width: 100%; max-height: 100%; }
147
+ footer { display: flex; justify-content: space-between; font-size: 15px; font-weight: 600; color: ${palette.muted}; }
148
+ </style></head>
149
+ <body><div class="card">
150
+ <div class="eyebrow">${escapeHtml(host)}</div>
151
+ <h1>${escapeHtml(title)}</h1>
152
+ <div class="stage">${imageData ? `<img src="${imageData}" alt="" />` : ''}</div>
153
+ <footer><span>${escapeHtml(route)}</span><span>${escapeHtml(host)}</span></footer>
154
+ </div></body></html>`;
155
+ }
156
+
157
+ /** Deterministic JSON: sorted keys, two-space indent. */
158
+ const stableJson = (value) => `${JSON.stringify(value, null, 2)}\n`;
159
+
160
+ // ── project plumbing ────────────────────────────────────────────────────────
161
+
162
+ export function loadPlaywright(projectRoot) {
163
+ const require = createRequire(path.join(projectRoot, 'package.json'));
164
+ for (const spec of ['playwright', '@playwright/test']) {
165
+ try {
166
+ const mod = require(spec);
167
+ if (mod?.chromium) return mod;
168
+ } catch {
169
+ // try the next one
170
+ }
171
+ }
172
+ throw new Error(
173
+ 'Playwright is not installed in this project. Run:\n' +
174
+ ' npm i -D playwright && npx playwright install chromium\n' +
175
+ '(or `pnpm add -D playwright && pnpm exec playwright install chromium`)'
176
+ );
177
+ }
178
+
179
+ const readJson = (file) => JSON.parse(fs.readFileSync(file, 'utf8'));
180
+
181
+ export function loadImagesConfig(projectRoot, manifest) {
182
+ return { ...DEFAULTS, ...(manifest?.images || {}) };
183
+ }
184
+
185
+ /** The theme the app would show, and whether it is dark. */
186
+ export function resolveTheme(projectRoot, config) {
187
+ const configFile = path.join(projectRoot, 'src', 'sliceConfig.json');
188
+ let themeManager = { enabled: false };
189
+ try {
190
+ themeManager = readJson(configFile).themeManager || themeManager;
191
+ } catch {
192
+ // no config: no theme system
193
+ }
194
+
195
+ if (!themeManager.enabled) {
196
+ return { themeName: null, dark: false, colorScheme: 'light', localTheme: null };
197
+ }
198
+
199
+ const requested = config.theme && config.theme !== 'default' ? config.theme : themeManager.defaultTheme;
200
+ const themeFile = path.join(projectRoot, 'src', 'public', 'Themes', `${requested}.css`);
201
+ if (!fs.existsSync(themeFile)) {
202
+ throw new Error(`Theme "${requested}" not found: expected ${path.relative(projectRoot, themeFile)}`);
203
+ }
204
+
205
+ const css = fs.readFileSync(themeFile, 'utf8');
206
+ const background = /--primary-background-color:\s*([^;]+)/.exec(css)?.[1]?.trim();
207
+ const value = luminance(background);
208
+ const dark = value === null ? false : value < 0.5;
209
+
210
+ // The theme manager reads localStorage only when the app saves it; otherwise
211
+ // the app's defaultTheme wins and asking for another one has to fail loudly.
212
+ const isRequested = requested !== themeManager.defaultTheme;
213
+ if (isRequested && !themeManager.saveThemeLocally && !themeManager.useBrowserTheme) {
214
+ throw new Error(
215
+ `Cannot capture theme "${requested}": sliceConfig.themeManager has saveThemeLocally and ` +
216
+ 'useBrowserTheme off, so the app always starts on ' + themeManager.defaultTheme
217
+ );
218
+ }
219
+
220
+ return {
221
+ themeName: requested,
222
+ dark,
223
+ colorScheme: dark ? 'dark' : 'light',
224
+ localTheme: themeManager.saveThemeLocally ? requested : null
225
+ };
226
+ }
227
+
228
+ const freePort = () => new Promise((resolve, reject) => {
229
+ const probe = createServer();
230
+ probe.unref();
231
+ probe.on('error', reject);
232
+ probe.listen(0, '127.0.0.1', () => {
233
+ const { port } = probe.address();
234
+ probe.close(() => resolve(port));
235
+ });
236
+ });
237
+
238
+ const waitForServer = async (baseUrl, timeoutMs = 60_000) => {
239
+ const deadline = Date.now() + timeoutMs;
240
+ while (Date.now() < deadline) {
241
+ try {
242
+ if ((await fetch(`${baseUrl}/api/status`, { signal: AbortSignal.timeout(1500) })).ok) return;
243
+ } catch {
244
+ // still booting
245
+ }
246
+ await new Promise((resolve) => setTimeout(resolve, 200));
247
+ }
248
+ throw new Error(`the dev server did not answer at ${baseUrl}`);
249
+ };
250
+
251
+ /** Boot the project's own server (development mode) on a free port. */
252
+ async function startDevServer(projectRoot) {
253
+ const port = await freePort();
254
+ const child = spawn(process.execPath, ['api/index.js'], {
255
+ cwd: projectRoot,
256
+ env: { ...process.env, PORT: String(port) },
257
+ stdio: ['ignore', 'pipe', 'pipe']
258
+ });
259
+ let output = '';
260
+ child.stdout.on('data', (chunk) => { output += chunk; });
261
+ child.stderr.on('data', (chunk) => { output += chunk; });
262
+ const baseUrl = `http://127.0.0.1:${port}`;
263
+ try {
264
+ await waitForServer(baseUrl);
265
+ } catch (error) {
266
+ child.kill();
267
+ throw new Error(`${error.message}\n${output}`, { cause: error });
268
+ }
269
+ return { baseUrl, stop: () => child.kill() };
270
+ }
271
+
272
+ // ── the pipeline ────────────────────────────────────────────────────────────
273
+
274
+ const settle = async (page, ms = 200) => {
275
+ await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))));
276
+ if (ms) await page.waitForTimeout(ms);
277
+ };
278
+
279
+ /** Wait until the DOM stops growing: async builds, no magic delay. */
280
+ const waitForStableDom = async (page, { quietMs = 400, timeoutMs = 8_000 } = {}) => {
281
+ const deadline = Date.now() + timeoutMs;
282
+ let last = -1;
283
+ let stableSince = 0;
284
+ while (Date.now() < deadline) {
285
+ const size = await page.evaluate(() => document.body.innerHTML.length);
286
+ if (size === last) {
287
+ if (!stableSince) stableSince = Date.now();
288
+ if (Date.now() - stableSince >= quietMs) return;
289
+ } else {
290
+ last = size;
291
+ stableSince = 0;
292
+ }
293
+ await page.waitForTimeout(100);
294
+ }
295
+ };
296
+
297
+ const trimEdges = async (page, buffer, cut) => {
298
+ const base64 = await page.evaluate(async ({ src, px }) => {
299
+ const image = new Image();
300
+ image.src = `data:image/png;base64,${src}`;
301
+ await image.decode();
302
+ const canvas = document.createElement('canvas');
303
+ canvas.width = image.naturalWidth - px * 2;
304
+ canvas.height = image.naturalHeight - px * 2;
305
+ canvas.getContext('2d').drawImage(image, -px, -px);
306
+ return canvas.toDataURL('image/png').split(',')[1];
307
+ }, { src: buffer.toString('base64'), px: cut });
308
+ return Buffer.from(base64, 'base64');
309
+ };
310
+
311
+ async function captureRoute(page, { baseUrl, route, selector, runner }) {
312
+ await page.goto(`${baseUrl}${route}`, { waitUntil: 'domcontentloaded', timeout: 60_000 });
313
+ if (runner?.prepare) await runner.prepare(page, route);
314
+ await page.evaluate(() => document.fonts.ready.then(() => true));
315
+ await waitForStableDom(page);
316
+
317
+ const target = runner?.capture || selector;
318
+ if (target) {
319
+ const shot = await page.locator(target).first().screenshot({ type: 'png', animations: 'disabled' });
320
+ return { kind: 'demo', shot: await trimEdges(page, shot, DEVICE_SCALE) };
321
+ }
322
+
323
+ const shot = await page.screenshot({
324
+ type: 'png',
325
+ animations: 'disabled',
326
+ clip: { x: 0, y: 0, width: CARD.width, height: CARD.height }
327
+ });
328
+ return { kind: 'page', shot };
329
+ }
330
+
331
+ const encodeCard = async (cardPage, { title, route, host, shot, kind, dark, template }) => {
332
+ const html = buildCardHtml({
333
+ title,
334
+ route,
335
+ host,
336
+ dark,
337
+ template,
338
+ imageData: shot ? `data:image/png;base64,${shot.toString('base64')}` : null
339
+ });
340
+ await cardPage.setContent(html, { waitUntil: 'load' });
341
+ await cardPage.evaluate(() => document.fonts.ready.then(() => true));
342
+
343
+ // PNG keeps flat UI and text crisp; a page slice is photographic enough that
344
+ // JPEG is a third of the size with no visible cost.
345
+ // A page slice is photographic enough for JPEG; an element capture keeps PNG
346
+ // so text and flat UI stay crisp.
347
+ const jpeg = kind === 'page';
348
+ const buffer = await cardPage.screenshot({
349
+ type: jpeg ? 'jpeg' : 'png',
350
+ quality: jpeg ? 86 : undefined,
351
+ animations: 'disabled',
352
+ clip: { x: 0, y: 0, width: CARD.width, height: CARD.height }
353
+ });
354
+ return { buffer, ext: jpeg ? '.jpg' : '.png', type: jpeg ? 'image/jpeg' : 'image/png' };
355
+ };
356
+
357
+ /**
358
+ * Render the cards. Everything is injectable so the tests do not need a browser
359
+ * or a server: `browserFactory`, `baseUrl`, `confirm`.
360
+ */
361
+ export async function generateImages(options = {}) {
362
+ const {
363
+ projectRoot,
364
+ only = null,
365
+ dryRun = false,
366
+ yes = false,
367
+ confirm = null,
368
+ runner = null
369
+ } = options;
370
+
371
+ const { manifest } = loadManifest(projectRoot);
372
+ if (!manifest) {
373
+ return { errors: ['seo.json not found: run `slice docs:generate` first, or write one'], files: [], patched: null };
374
+ }
375
+ if (!manifest.origin) {
376
+ return { errors: ['seo.json has no origin'], files: [], patched: null };
377
+ }
378
+
379
+ const config = {
380
+ ...loadImagesConfig(projectRoot, manifest),
381
+ ...(options.selector ? { selector: options.selector } : {}),
382
+ ...(options.outDir || options.out ? { outDir: options.outDir || options.out } : {})
383
+ };
384
+
385
+ // The translator is optional: an older framework, or a project that has not enabled it,
386
+ // yields one single-language target per route and the old manifest keys.
387
+ let frameworkSeo = options.framework || null;
388
+ let translator = options.translator ?? null;
389
+ if (translator === null) {
390
+ try {
391
+ frameworkSeo = frameworkSeo || await loadFrameworkSeo(projectRoot);
392
+ translator = await loadSeoTranslator(projectRoot, frameworkSeo);
393
+ } catch {
394
+ translator = null;
395
+ }
396
+ }
397
+
398
+ const targets = cardTargets(manifest, translator, only);
399
+ if (!targets.length) {
400
+ return { errors: [`no indexable route matched${only ? ` --only=${only}` : ''}`], files: [], patched: null };
401
+ }
402
+
403
+ const configuredOut = config.outDir || DEFAULT_OUT_DIR;
404
+ const outDir = path.isAbsolute(configuredOut) ? configuredOut : path.join(projectRoot, configuredOut);
405
+ const budgetBytes = Math.round((config.budgetKB || DEFAULT_BUDGET_KB) * 1024);
406
+ const theme = resolveTheme(projectRoot, config);
407
+ const template = config.template
408
+ ? fs.readFileSync(path.join(projectRoot, config.template), 'utf8')
409
+ : null;
410
+ const host = String(manifest.origin).replace(/^https?:\/\//, '');
411
+ const runnerModule = runner
412
+ ? (await import(pathToFileURL(path.resolve(projectRoot, runner)).href)).default
413
+ : null;
414
+
415
+ const server = options.baseUrl ? null : await startDevServer(projectRoot);
416
+ const baseUrl = options.baseUrl || server.baseUrl;
417
+ const playwright = options.browserFactory ? null : loadPlaywright(projectRoot);
418
+ const browser = options.browserFactory
419
+ ? await options.browserFactory()
420
+ : await playwright.chromium.launch();
421
+
422
+ const images = {};
423
+ const files = [];
424
+ let failed = 0;
425
+
426
+ try {
427
+ const captureContext = await browser.newContext({
428
+ viewport: { width: 1440, height: 960 },
429
+ deviceScaleFactor: DEVICE_SCALE,
430
+ colorScheme: theme.colorScheme,
431
+ reducedMotion: 'reduce',
432
+ locale: config.locale || 'en-US',
433
+ timezoneId: 'UTC',
434
+ ...(options.storageState ? { storageState: options.storageState } : {})
435
+ });
436
+ if (theme.localTheme) {
437
+ await captureContext.addInitScript((name) => {
438
+ try { localStorage.setItem('sliceTheme', name); } catch { /* storage blocked */ }
439
+ }, theme.localTheme);
440
+ }
441
+ const cardContext = await browser.newContext({
442
+ viewport: CARD,
443
+ deviceScaleFactor: 1,
444
+ colorScheme: theme.colorScheme,
445
+ reducedMotion: 'reduce',
446
+ locale: config.locale || 'en-US'
447
+ });
448
+
449
+ for (const target of targets) {
450
+ const page = await captureContext.newPage();
451
+ const cardPage = await cardContext.newPage();
452
+ try {
453
+ await page.clock?.setFixedTime?.(FIXED_TIME).catch?.(() => {});
454
+ const capture = await captureRoute(page, {
455
+ baseUrl,
456
+ route: target.url,
457
+ selector: config.selector,
458
+ runner: runnerModule
459
+ });
460
+ const rawTitle = translator?.enabled
461
+ ? frameworkSeo?.resolveSeoText?.(target.meta.title, (key, params) => translator.t(target.locale || translator.defaultLocale, key, params))
462
+ : target.meta.title;
463
+ const title = typeof rawTitle === 'string' && rawTitle ? rawTitle : target.route;
464
+ const card = await encodeCard(cardPage, {
465
+ title,
466
+ route: target.url,
467
+ host,
468
+ shot: capture.shot,
469
+ kind: capture.kind,
470
+ dark: theme.dark,
471
+ template
472
+ });
473
+
474
+ const hash = createHash('sha256').update(card.buffer).digest('hex').slice(0, 10);
475
+ const prefix = target.locale ? `${target.locale}-` : '';
476
+ const fileName = `${prefix}${routeSlug(target.route)}-${hash}${card.ext}`;
477
+ const file = path.join(outDir, fileName);
478
+
479
+ if (card.buffer.length > budgetBytes) {
480
+ throw new Error(`${(card.buffer.length / 1024).toFixed(1)} KB is over the ${config.budgetKB || DEFAULT_BUDGET_KB} KB budget`);
481
+ }
482
+
483
+ if (!dryRun) {
484
+ await fsp.mkdir(outDir, { recursive: true });
485
+ if (!fs.existsSync(file)) await fsp.writeFile(file, card.buffer);
486
+ }
487
+
488
+ images[target.url] = {
489
+ path: `/og/${fileName}`,
490
+ width: CARD.width,
491
+ height: CARD.height,
492
+ type: card.type,
493
+ bytes: card.buffer.length,
494
+ kind: capture.kind
495
+ };
496
+ files.push({ route: target.url, file, status: dryRun ? 'would-write' : 'written', bytes: card.buffer.length });
497
+ } catch (error) {
498
+ failed += 1;
499
+ files.push({ route: target.url, status: 'failed', error: error.message });
500
+ } finally {
501
+ await page.close();
502
+ await cardPage.close();
503
+ }
504
+ }
505
+
506
+ if (failed) {
507
+ return { errors: [`${failed} route(s) failed; the manifest was left untouched`], files, patched: null };
508
+ }
509
+
510
+ // --only renders a subset, so merge with what is already there; a full run
511
+ // replaces the set (and the orphan sweep removes what is gone).
512
+ const merged = options.only
513
+ ? { ...(readExistingManifest(outDir)?.images || {}), ...images }
514
+ : images;
515
+ const manifestPayload = {
516
+ version: 1,
517
+ generator: 'slice seo images',
518
+ card: { width: CARD.width, height: CARD.height },
519
+ images: Object.fromEntries(Object.entries(merged).sort(([a], [b]) => a.localeCompare(b)))
520
+ };
521
+
522
+ const manifestFile = path.join(outDir, 'manifest.json');
523
+ let manifestStatus = 'written';
524
+ if (dryRun) {
525
+ manifestStatus = 'would-write';
526
+ } else {
527
+ // Generated output, derived from the images just written: no prompt. The
528
+ // overwrite rule belongs to human-reviewed artifacts (the sitemap).
529
+ const written = await writeFileConfirmed(manifestFile, stableJson(manifestPayload), { yes: true });
530
+ manifestStatus = written.status;
531
+ if (written.status === 'unchanged') manifestStatus = 'unchanged';
532
+
533
+ // Orphans: an image no manifest entry points at anymore.
534
+ const referenced = new Set(Object.values(manifestPayload.images).map((entry) => path.basename(entry.path)));
535
+ for (const name of fs.readdirSync(outDir)) {
536
+ if (!/\.(png|jpe?g|webp)$/i.test(name) || referenced.has(name)) continue;
537
+ await fsp.unlink(path.join(outDir, name));
538
+ files.push({ route: null, file: path.join(outDir, name), status: 'removed-orphan' });
539
+ }
540
+ }
541
+
542
+ return { errors: [], files, patched: { file: manifestFile, status: manifestStatus } };
543
+ } finally {
544
+ await browser.close();
545
+ if (server) server.stop();
546
+ }
547
+ }
548
+
549
+ const readExistingManifest = (outDir) => {
550
+ const file = path.join(outDir, 'manifest.json');
551
+ if (!fs.existsSync(file)) return null;
552
+ try { return readJson(file); } catch { return null; }
553
+ };
554
+
555
+ /** `--check`: no browser, no server. Every indexable route must have a card that fits. */
556
+ export function checkImages({ projectRoot, only = null, translator = null }) {
557
+ const { manifest } = loadManifest(projectRoot);
558
+ if (!manifest) return { errors: ['seo.json not found'], checks: [] };
559
+
560
+ const config = loadImagesConfig(projectRoot, manifest);
561
+ const configuredOut = config.outDir || DEFAULT_OUT_DIR;
562
+ const outDir = path.isAbsolute(configuredOut) ? configuredOut : path.join(projectRoot, configuredOut);
563
+ const budgetBytes = Math.round((config.budgetKB || DEFAULT_BUDGET_KB) * 1024);
564
+ const cards = readExistingManifest(outDir)?.images || {};
565
+ const targets = cardTargets(manifest, translator, only);
566
+ const errors = [];
567
+ const checks = [];
568
+
569
+ for (const { url } of targets) {
570
+ const card = cards[url];
571
+ if (!card) { errors.push(`${url} has no card: run \`slice seo images\``); continue; }
572
+ const file = path.join(projectRoot, config.outDir || DEFAULT_OUT_DIR, path.basename(card.path));
573
+ if (!fs.existsSync(file)) { errors.push(`${url}: missing ${card.path}`); continue; }
574
+ const buffer = fs.readFileSync(file);
575
+ const size = imageSize(buffer);
576
+ if (size.width !== CARD.width || size.height !== CARD.height) {
577
+ errors.push(`${url}: ${size.width}×${size.height}, expected ${CARD.width}×${CARD.height}`);
578
+ }
579
+ if (buffer.length > budgetBytes) {
580
+ errors.push(`${url}: ${(buffer.length / 1024).toFixed(1)} KB over the budget`);
581
+ }
582
+ checks.push(url);
583
+ }
584
+
585
+ return { errors, checks };
586
+ }
587
+
588
+ // ── the command ─────────────────────────────────────────────────────────────
589
+
590
+ const STATUS = {
591
+ written: 'written',
592
+ 'would-write': 'would write',
593
+ unchanged: 'unchanged',
594
+ 'removed-orphan': 'removed orphan',
595
+ failed: 'FAILED'
596
+ };
597
+
598
+ export default async function imagesCommand(options = {}, projectRoot) {
599
+ try {
600
+ if (options.check) {
601
+ let translator = options.translator ?? null;
602
+ if (translator === null) {
603
+ try {
604
+ translator = await loadSeoTranslator(projectRoot, await loadFrameworkSeo(projectRoot));
605
+ } catch {
606
+ translator = null;
607
+ }
608
+ }
609
+ const result = checkImages({ projectRoot, only: options.only, translator });
610
+ if (result.errors.length) {
611
+ for (const error of result.errors) Print.error(error);
612
+ Print.error(`SEO images check failed: ${result.errors.length} problem(s).`);
613
+ process.exitCode = 1;
614
+ return;
615
+ }
616
+ Print.success(`SEO images OK: ${result.checks.length} card(s), 1200×630, within budget.`);
617
+ return;
618
+ }
619
+
620
+ const result = await generateImages({ projectRoot, ...options });
621
+ for (const file of result.files) {
622
+ const label = STATUS[file.status] || file.status;
623
+ const name = file.route ? `${file.route} → ${path.basename(file.file)}` : path.basename(file.file);
624
+ const message = `${name} (${label}${file.bytes ? `, ${(file.bytes / 1024).toFixed(1)} KB` : ''}${file.error ? `, ${file.error}` : ''})`;
625
+ if (file.status === 'failed') Print.error(message);
626
+ else if (file.status === 'removed-orphan') Print.info(message);
627
+ else Print.success(message);
628
+ }
629
+
630
+ if (result.patched) {
631
+ Print.info(`Manifest: ${path.relative(projectRoot, result.patched.file)} (${result.patched.status})`);
632
+ }
633
+ if (result.errors.length) {
634
+ for (const error of result.errors) Print.error(error);
635
+ process.exitCode = 1;
636
+ }
637
+ } catch (error) {
638
+ Print.error('slice seo images failed:', error.message);
639
+ process.exitCode = 1;
640
+ }
641
+ }