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