og-route-kit 0.0.0-stage → 0.2.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/CHANGELOG.md +74 -0
- package/LICENSE +21 -0
- package/README.md +282 -2
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +1106 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/core/index.d.ts +21 -0
- package/dist/core/index.js +133 -0
- package/dist/core/index.js.map +1 -0
- package/dist/examples/cards/index.d.ts +24 -0
- package/dist/examples/cards/index.js +129 -0
- package/dist/examples/cards/index.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +133 -0
- package/dist/index.js.map +1 -0
- package/dist/next/index.d.ts +44 -0
- package/dist/next/index.js +270 -0
- package/dist/next/index.js.map +1 -0
- package/dist/sizes-Bn3i71Bz.d.ts +34 -0
- package/package.json +92 -4
|
@@ -0,0 +1,1106 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli/index.ts
|
|
4
|
+
import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
|
|
5
|
+
import { dirname as dirname2 } from "path";
|
|
6
|
+
|
|
7
|
+
// src/cli/fetch-png.ts
|
|
8
|
+
var DEFAULT_MAX_BYTES = 8e6;
|
|
9
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
10
|
+
var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
11
|
+
function assertPngResponseHeaders(response, maxBytes) {
|
|
12
|
+
if (!response.ok) {
|
|
13
|
+
throw new Error(`Request failed: ${response.status} ${response.statusText}`);
|
|
14
|
+
}
|
|
15
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
16
|
+
if (!contentType.toLowerCase().includes("image/png")) {
|
|
17
|
+
throw new Error(`Expected image/png, received ${contentType || "unknown content type"}`);
|
|
18
|
+
}
|
|
19
|
+
const contentLength = Number(response.headers.get("content-length"));
|
|
20
|
+
if (Number.isFinite(contentLength) && contentLength > maxBytes) {
|
|
21
|
+
throw new Error(`Image is ${contentLength} bytes, above max ${maxBytes}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function assertPngSignature(bytes) {
|
|
25
|
+
const matches = bytes.byteLength >= PNG_SIGNATURE.length && PNG_SIGNATURE.every((byte, index) => bytes[index] === byte);
|
|
26
|
+
if (!matches) {
|
|
27
|
+
throw new Error("Response body is not a PNG (missing PNG signature)");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function fetchPng(url, options) {
|
|
31
|
+
const maxBytes = resolvePositiveInteger(options.maxBytes, DEFAULT_MAX_BYTES, "maxBytes");
|
|
32
|
+
const timeoutMs = resolvePositiveInteger(options.timeoutMs, DEFAULT_TIMEOUT_MS, "timeoutMs");
|
|
33
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
34
|
+
assertPngResponseHeaders(response, maxBytes);
|
|
35
|
+
const bytes = await readResponseBody(response, maxBytes);
|
|
36
|
+
assertPngSignature(bytes);
|
|
37
|
+
return bytes;
|
|
38
|
+
}
|
|
39
|
+
function resolvePositiveInteger(value, fallback, name) {
|
|
40
|
+
const resolved = value ?? fallback;
|
|
41
|
+
if (!Number.isSafeInteger(resolved) || resolved <= 0) {
|
|
42
|
+
throw new Error(`${name} must be a positive integer`);
|
|
43
|
+
}
|
|
44
|
+
return resolved;
|
|
45
|
+
}
|
|
46
|
+
async function readResponseBody(response, maxBytes) {
|
|
47
|
+
if (!response.body) {
|
|
48
|
+
throw new Error("Response body is empty");
|
|
49
|
+
}
|
|
50
|
+
const reader = response.body.getReader();
|
|
51
|
+
const chunks = [];
|
|
52
|
+
let totalBytes = 0;
|
|
53
|
+
try {
|
|
54
|
+
while (true) {
|
|
55
|
+
const { done, value } = await reader.read();
|
|
56
|
+
if (done) {
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
totalBytes += value.byteLength;
|
|
60
|
+
if (totalBytes > maxBytes) {
|
|
61
|
+
await reader.cancel();
|
|
62
|
+
throw new Error(`Image is above max ${maxBytes} bytes`);
|
|
63
|
+
}
|
|
64
|
+
chunks.push(value);
|
|
65
|
+
}
|
|
66
|
+
} finally {
|
|
67
|
+
reader.releaseLock();
|
|
68
|
+
}
|
|
69
|
+
const bytes = new Uint8Array(totalBytes);
|
|
70
|
+
let offset = 0;
|
|
71
|
+
for (const chunk of chunks) {
|
|
72
|
+
bytes.set(chunk, offset);
|
|
73
|
+
offset += chunk.byteLength;
|
|
74
|
+
}
|
|
75
|
+
return bytes;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// src/cli/args.ts
|
|
79
|
+
var PREVIEW_EXAMPLES = [
|
|
80
|
+
["Product", "eyebrow=Product&title=Ship+better+social+cards.&description=Code-rendered+Open+Graph+images."],
|
|
81
|
+
["Article", "eyebrow=Journal&title=Why+coded+OG+routes+beat+exported+PNGs&description=Typed+routes+stay+fresh."],
|
|
82
|
+
["Changelog", "eyebrow=v0.1.0&title=Initial+route+kit+release&description=Params%2C+metadata%2C+export."]
|
|
83
|
+
];
|
|
84
|
+
function parseFlags(values) {
|
|
85
|
+
const flags = {};
|
|
86
|
+
for (let index = 0; index < values.length; index += 1) {
|
|
87
|
+
const token = values[index];
|
|
88
|
+
if (!token?.startsWith("--")) {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const key = token.slice(2);
|
|
92
|
+
const next = values[index + 1];
|
|
93
|
+
if (next && !next.startsWith("--")) {
|
|
94
|
+
flags[key] = next;
|
|
95
|
+
index += 1;
|
|
96
|
+
} else {
|
|
97
|
+
flags[key] = true;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return flags;
|
|
101
|
+
}
|
|
102
|
+
function requireString(flags, key) {
|
|
103
|
+
const value = flags[key];
|
|
104
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
105
|
+
throw new Error(`Missing required flag --${key}`);
|
|
106
|
+
}
|
|
107
|
+
return value;
|
|
108
|
+
}
|
|
109
|
+
function optionalPositiveInteger(flags, key, fallback) {
|
|
110
|
+
const value = flags[key];
|
|
111
|
+
if (value === void 0) {
|
|
112
|
+
return fallback;
|
|
113
|
+
}
|
|
114
|
+
if (typeof value !== "string") {
|
|
115
|
+
throw new Error(`Flag --${key} requires a positive integer`);
|
|
116
|
+
}
|
|
117
|
+
const parsed = Number(value);
|
|
118
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
119
|
+
throw new Error(`Flag --${key} requires a positive integer`);
|
|
120
|
+
}
|
|
121
|
+
return parsed;
|
|
122
|
+
}
|
|
123
|
+
function buildPreviewUrls(flags) {
|
|
124
|
+
const origin = String(flags.origin ?? "http://localhost:3000").replace(/\/+$/, "");
|
|
125
|
+
const route = String(flags.route ?? "/api/og");
|
|
126
|
+
const base = `${origin}${route.startsWith("/") ? route : `/${route}`}`;
|
|
127
|
+
return PREVIEW_EXAMPLES.map(([label, query]) => `${label}: ${base}?${query}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/cli/audit.ts
|
|
131
|
+
import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
|
|
132
|
+
import { dirname } from "path";
|
|
133
|
+
|
|
134
|
+
// src/audit/types.ts
|
|
135
|
+
var CHECK_IDS = [
|
|
136
|
+
"page-unreachable",
|
|
137
|
+
"image-missing",
|
|
138
|
+
"image-relative",
|
|
139
|
+
"image-unreachable",
|
|
140
|
+
"image-format",
|
|
141
|
+
"image-too-large",
|
|
142
|
+
"image-heavy",
|
|
143
|
+
"image-size",
|
|
144
|
+
"image-no-alt",
|
|
145
|
+
"title-missing",
|
|
146
|
+
"title-long",
|
|
147
|
+
"description-missing",
|
|
148
|
+
"description-long",
|
|
149
|
+
"url-mismatch",
|
|
150
|
+
"twitter-card-missing",
|
|
151
|
+
"twitter-image-missing",
|
|
152
|
+
"image-duplicate"
|
|
153
|
+
];
|
|
154
|
+
|
|
155
|
+
// src/audit/fetch.ts
|
|
156
|
+
import { readFile } from "fs/promises";
|
|
157
|
+
import { gunzipSync } from "zlib";
|
|
158
|
+
|
|
159
|
+
// src/audit/parse-meta.ts
|
|
160
|
+
var META_TAG = /<meta\b((?:[^>"']|"[^"]*"|'[^']*')*)>/gi;
|
|
161
|
+
var ATTRIBUTE = /([^\s"'<>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
162
|
+
var NAMED_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
163
|
+
function parseMeta(html) {
|
|
164
|
+
const values = /* @__PURE__ */ new Map();
|
|
165
|
+
const source = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<script\b[\s\S]*?<\/script\s*>/gi, "").replace(/<style\b[\s\S]*?<\/style\s*>/gi, "");
|
|
166
|
+
for (const tag of source.matchAll(META_TAG)) {
|
|
167
|
+
const attributes = readAttributes(tag[1] ?? "");
|
|
168
|
+
const key = (attributes.get("property") ?? attributes.get("name"))?.trim().toLowerCase();
|
|
169
|
+
const content = attributes.get("content");
|
|
170
|
+
if (!key || content === void 0) {
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const list = values.get(key) ?? [];
|
|
174
|
+
list.push(decodeEntities(content).trim());
|
|
175
|
+
values.set(key, list);
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
get: (key) => values.get(key.toLowerCase())?.find((value) => value.length > 0),
|
|
179
|
+
getAll: (key) => values.get(key.toLowerCase()) ?? []
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function readAttributes(raw) {
|
|
183
|
+
const attributes = /* @__PURE__ */ new Map();
|
|
184
|
+
for (const match of raw.matchAll(ATTRIBUTE)) {
|
|
185
|
+
const name = match[1]?.toLowerCase();
|
|
186
|
+
if (name && !attributes.has(name)) {
|
|
187
|
+
attributes.set(name, match[2] ?? match[3] ?? match[4] ?? "");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return attributes;
|
|
191
|
+
}
|
|
192
|
+
function decodeEntities(value) {
|
|
193
|
+
return value.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (entity, decimal, hex, name) => {
|
|
194
|
+
if (name) {
|
|
195
|
+
return NAMED_ENTITIES[String(name).toLowerCase()] ?? entity;
|
|
196
|
+
}
|
|
197
|
+
const codePoint = decimal ? Number(decimal) : Number.parseInt(hex, 16);
|
|
198
|
+
return codePoint > 0 && codePoint <= 1114111 ? String.fromCodePoint(codePoint) : entity;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/audit/sitemap.ts
|
|
203
|
+
var MAX_SITEMAP_DEPTH = 2;
|
|
204
|
+
var MAX_SITEMAP_FILES = 200;
|
|
205
|
+
function parseSitemap(xml) {
|
|
206
|
+
const locs = [];
|
|
207
|
+
for (const match of xml.matchAll(/<loc\b[^>]*>([\s\S]*?)<\/loc\s*>/gi)) {
|
|
208
|
+
const value = decodeEntities((match[1] ?? "").replace(/^\s*<!\[CDATA\[([\s\S]*?)\]\]>\s*$/, "$1").trim());
|
|
209
|
+
if (value) {
|
|
210
|
+
locs.push(value);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { kind: /<sitemapindex[\s>]/i.test(xml) ? "index" : "urlset", locs };
|
|
214
|
+
}
|
|
215
|
+
async function collectSitemapUrls(source, options) {
|
|
216
|
+
const rootBase = isHttpUrl(source) ? new URL(source) : null;
|
|
217
|
+
const pages = /* @__PURE__ */ new Set();
|
|
218
|
+
let filesRead = 0;
|
|
219
|
+
async function visit(location, depth) {
|
|
220
|
+
if (filesRead >= MAX_SITEMAP_FILES) {
|
|
221
|
+
options.onNote?.(`Stopped after reading ${MAX_SITEMAP_FILES} sitemap files`);
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
filesRead += 1;
|
|
225
|
+
const document = parseSitemap(await options.readSource(location));
|
|
226
|
+
const base = isHttpUrl(location) ? location : void 0;
|
|
227
|
+
for (const loc of document.locs) {
|
|
228
|
+
const resolved = resolveLoc(loc, base);
|
|
229
|
+
if (!resolved) {
|
|
230
|
+
options.onNote?.(`Skipped ${loc}: not an absolute http(s) URL`);
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (rootBase && new URL(resolved).origin !== rootBase.origin) {
|
|
234
|
+
options.onNote?.(`Skipped off-origin entry ${resolved}`);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (document.kind === "urlset") {
|
|
238
|
+
pages.add(resolved);
|
|
239
|
+
} else if (depth >= MAX_SITEMAP_DEPTH) {
|
|
240
|
+
options.onNote?.(`Skipped ${resolved}: sitemap indexes are followed ${MAX_SITEMAP_DEPTH} levels deep`);
|
|
241
|
+
} else {
|
|
242
|
+
await visit(resolved, depth + 1);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
await visit(source, 0);
|
|
247
|
+
return [...pages];
|
|
248
|
+
}
|
|
249
|
+
function sampleEvenly(items, count) {
|
|
250
|
+
if (count >= items.length) {
|
|
251
|
+
return [...items];
|
|
252
|
+
}
|
|
253
|
+
return Array.from({ length: count }, (_, index) => items[Math.floor(index * items.length / count)]);
|
|
254
|
+
}
|
|
255
|
+
function resolveLoc(loc, base) {
|
|
256
|
+
try {
|
|
257
|
+
const url = new URL(loc, base);
|
|
258
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
|
259
|
+
} catch {
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function isHttpUrl(value) {
|
|
264
|
+
return /^https?:\/\//i.test(value);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// src/audit/fetch.ts
|
|
268
|
+
var USER_AGENT = "og-route-kit-audit (+https://github.com/pixelbrew-studio/og-route-kit)";
|
|
269
|
+
var DEFAULT_RETRY_DELAY_MS = 400;
|
|
270
|
+
var HEAD_BYTES = 256 * 1024;
|
|
271
|
+
var PAGE_MAX_BYTES = 2e6;
|
|
272
|
+
var SITEMAP_MAX_BYTES = 5e7;
|
|
273
|
+
async function withRetry(attempt, delayMs = DEFAULT_RETRY_DELAY_MS) {
|
|
274
|
+
const first = await attempt();
|
|
275
|
+
if (!first.retry) {
|
|
276
|
+
return first.value;
|
|
277
|
+
}
|
|
278
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
279
|
+
return (await attempt()).value;
|
|
280
|
+
}
|
|
281
|
+
async function probePage(url, options) {
|
|
282
|
+
return withRetry(async () => {
|
|
283
|
+
try {
|
|
284
|
+
const response = await fetch(url, {
|
|
285
|
+
headers: { "user-agent": USER_AGENT, accept: "text/html,application/xhtml+xml;q=0.9,*/*;q=0.5" },
|
|
286
|
+
signal: AbortSignal.timeout(options.timeoutMs)
|
|
287
|
+
});
|
|
288
|
+
if (!response.ok) {
|
|
289
|
+
await response.body?.cancel();
|
|
290
|
+
return { value: { status: response.status, finalUrl: response.url || url, html: "" }, retry: response.status >= 500 };
|
|
291
|
+
}
|
|
292
|
+
const body = await readBody(response, PAGE_MAX_BYTES);
|
|
293
|
+
return { value: { status: response.status, finalUrl: response.url || url, html: new TextDecoder().decode(body.bytes) }, retry: false };
|
|
294
|
+
} catch (error) {
|
|
295
|
+
return { value: { status: null, finalUrl: url, error: describeError(error, options.timeoutMs), html: "" }, retry: !isTimeout(error) };
|
|
296
|
+
}
|
|
297
|
+
}, options.retryDelayMs);
|
|
298
|
+
}
|
|
299
|
+
async function probeImage(url, options) {
|
|
300
|
+
const failed = (error) => ({ url, status: null, error, contentType: null, bytes: 0, truncated: false, head: new Uint8Array() });
|
|
301
|
+
if (!isHttpUrl(url)) {
|
|
302
|
+
return failed("only http(s) image URLs can be fetched");
|
|
303
|
+
}
|
|
304
|
+
return withRetry(async () => {
|
|
305
|
+
try {
|
|
306
|
+
const response = await fetch(url, {
|
|
307
|
+
headers: { "user-agent": USER_AGENT, accept: "image/png,image/*;q=0.8,*/*;q=0.5" },
|
|
308
|
+
signal: AbortSignal.timeout(options.timeoutMs)
|
|
309
|
+
});
|
|
310
|
+
const contentType = response.headers.get("content-type");
|
|
311
|
+
if (!response.ok) {
|
|
312
|
+
await response.body?.cancel();
|
|
313
|
+
return { value: { ...failed(""), status: response.status, contentType }, retry: response.status >= 500 };
|
|
314
|
+
}
|
|
315
|
+
const declared = Number(response.headers.get("content-length"));
|
|
316
|
+
const body = await readBody(response, options.maxBytes, HEAD_BYTES);
|
|
317
|
+
const bytes = body.truncated && Number.isFinite(declared) ? Math.max(body.size, declared) : body.size;
|
|
318
|
+
return {
|
|
319
|
+
value: { url, status: response.status, contentType, bytes, truncated: body.truncated, head: body.bytes },
|
|
320
|
+
retry: false
|
|
321
|
+
};
|
|
322
|
+
} catch (error) {
|
|
323
|
+
return { value: failed(describeError(error, options.timeoutMs)), retry: !isTimeout(error) };
|
|
324
|
+
}
|
|
325
|
+
}, options.retryDelayMs);
|
|
326
|
+
}
|
|
327
|
+
async function readSitemapSource(source, options) {
|
|
328
|
+
const bytes = isHttpUrl(source) ? await fetchSitemapBytes(source, options) : await readFile(source);
|
|
329
|
+
return new TextDecoder().decode(isGzip(bytes) ? gunzipSync(bytes, { maxOutputLength: SITEMAP_MAX_BYTES }) : bytes);
|
|
330
|
+
}
|
|
331
|
+
async function fetchSitemapBytes(url, options) {
|
|
332
|
+
const result = await withRetry(async () => {
|
|
333
|
+
try {
|
|
334
|
+
const response = await fetch(url, {
|
|
335
|
+
headers: { "user-agent": USER_AGENT, accept: "application/xml,text/xml;q=0.9,*/*;q=0.5" },
|
|
336
|
+
signal: AbortSignal.timeout(options.timeoutMs)
|
|
337
|
+
});
|
|
338
|
+
if (!response.ok) {
|
|
339
|
+
await response.body?.cancel();
|
|
340
|
+
return { value: { error: `HTTP ${response.status}` }, retry: response.status >= 500 };
|
|
341
|
+
}
|
|
342
|
+
return { value: { bytes: (await readBody(response, SITEMAP_MAX_BYTES)).bytes }, retry: false };
|
|
343
|
+
} catch (error) {
|
|
344
|
+
return { value: { error: describeError(error, options.timeoutMs) }, retry: !isTimeout(error) };
|
|
345
|
+
}
|
|
346
|
+
}, options.retryDelayMs);
|
|
347
|
+
if (!result.bytes) {
|
|
348
|
+
throw new Error(`Could not read sitemap ${url}: ${result.error}`);
|
|
349
|
+
}
|
|
350
|
+
return result.bytes;
|
|
351
|
+
}
|
|
352
|
+
async function mapPool(items, concurrency, task) {
|
|
353
|
+
const results = new Array(items.length);
|
|
354
|
+
let next = 0;
|
|
355
|
+
async function worker() {
|
|
356
|
+
while (next < items.length) {
|
|
357
|
+
const index = next;
|
|
358
|
+
next += 1;
|
|
359
|
+
results[index] = await task(items[index], index);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
|
|
363
|
+
return results;
|
|
364
|
+
}
|
|
365
|
+
async function readBody(response, maxBytes, keepBytes = maxBytes) {
|
|
366
|
+
if (!response.body) {
|
|
367
|
+
return { bytes: new Uint8Array(), size: 0, truncated: false };
|
|
368
|
+
}
|
|
369
|
+
const reader = response.body.getReader();
|
|
370
|
+
const chunks = [];
|
|
371
|
+
let size = 0;
|
|
372
|
+
let kept = 0;
|
|
373
|
+
let truncated = false;
|
|
374
|
+
try {
|
|
375
|
+
while (true) {
|
|
376
|
+
const { done, value } = await reader.read();
|
|
377
|
+
if (done) {
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
if (kept < keepBytes) {
|
|
381
|
+
chunks.push(value);
|
|
382
|
+
kept += value.byteLength;
|
|
383
|
+
}
|
|
384
|
+
size += value.byteLength;
|
|
385
|
+
if (size > maxBytes) {
|
|
386
|
+
truncated = true;
|
|
387
|
+
await reader.cancel();
|
|
388
|
+
break;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
} finally {
|
|
392
|
+
reader.releaseLock();
|
|
393
|
+
}
|
|
394
|
+
const bytes = new Uint8Array(Math.min(size, keepBytes));
|
|
395
|
+
let offset = 0;
|
|
396
|
+
for (const chunk of chunks) {
|
|
397
|
+
const room = bytes.byteLength - offset;
|
|
398
|
+
if (room <= 0) {
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
bytes.set(chunk.subarray(0, room), offset);
|
|
402
|
+
offset += Math.min(chunk.byteLength, room);
|
|
403
|
+
}
|
|
404
|
+
return { bytes, size, truncated };
|
|
405
|
+
}
|
|
406
|
+
function isGzip(bytes) {
|
|
407
|
+
return bytes[0] === 31 && bytes[1] === 139;
|
|
408
|
+
}
|
|
409
|
+
function isTimeout(error) {
|
|
410
|
+
return error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
411
|
+
}
|
|
412
|
+
function describeError(error, timeoutMs) {
|
|
413
|
+
if (isTimeout(error)) {
|
|
414
|
+
return `timed out after ${timeoutMs} ms`;
|
|
415
|
+
}
|
|
416
|
+
if (!(error instanceof Error)) {
|
|
417
|
+
return String(error);
|
|
418
|
+
}
|
|
419
|
+
const cause = error.cause instanceof Error ? error.cause : null;
|
|
420
|
+
return cause ? `${error.message} (${cause.code ?? cause.message})` : error.message;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// src/audit/check-image.ts
|
|
424
|
+
var HEAVY_IMAGE_BYTES = 3e5;
|
|
425
|
+
var MAX_IMAGE_BYTES = 5e6;
|
|
426
|
+
var IDEAL_WIDTH = 1200;
|
|
427
|
+
var IDEAL_HEIGHT = 630;
|
|
428
|
+
var ASPECT_TOLERANCE = 0.02;
|
|
429
|
+
var IDEAL_ASPECT = IDEAL_WIDTH / IDEAL_HEIGHT;
|
|
430
|
+
var RELIABLE_TYPES = ["image/png", "image/jpeg"];
|
|
431
|
+
var PARTIAL_TYPES = ["image/webp", "image/gif", "image/avif"];
|
|
432
|
+
var PNG_SIGNATURE2 = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
433
|
+
var IHDR_END = 24;
|
|
434
|
+
function hasPngSignature(bytes) {
|
|
435
|
+
return bytes.byteLength >= PNG_SIGNATURE2.length && PNG_SIGNATURE2.every((byte, index) => bytes[index] === byte);
|
|
436
|
+
}
|
|
437
|
+
function readPngHeader(bytes) {
|
|
438
|
+
if (!hasPngSignature(bytes) || bytes.byteLength < IHDR_END) {
|
|
439
|
+
return null;
|
|
440
|
+
}
|
|
441
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
442
|
+
const isIhdr = view.getUint32(8) === 13 && view.getUint32(12) === 1229472850;
|
|
443
|
+
if (!isIhdr) {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
const width = view.getUint32(16);
|
|
447
|
+
const height = view.getUint32(20);
|
|
448
|
+
return width > 0 && height > 0 ? { width, height } : null;
|
|
449
|
+
}
|
|
450
|
+
function readImageSize(bytes) {
|
|
451
|
+
return readPngHeader(bytes) ?? readJpegSize(bytes) ?? readWebpSize(bytes);
|
|
452
|
+
}
|
|
453
|
+
function readJpegSize(bytes) {
|
|
454
|
+
if (bytes[0] !== 255 || bytes[1] !== 216) {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
458
|
+
let offset = 2;
|
|
459
|
+
while (offset + 4 <= bytes.byteLength) {
|
|
460
|
+
if (bytes[offset] !== 255) {
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
const marker = bytes[offset + 1];
|
|
464
|
+
if (marker === 255) {
|
|
465
|
+
offset += 1;
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
if (marker === 1 || marker >= 208 && marker <= 217) {
|
|
469
|
+
offset += 2;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (marker === 218) {
|
|
473
|
+
return null;
|
|
474
|
+
}
|
|
475
|
+
const isFrame = marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
|
|
476
|
+
if (isFrame) {
|
|
477
|
+
if (offset + 9 > bytes.byteLength) {
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
const height = view.getUint16(offset + 5);
|
|
481
|
+
const width = view.getUint16(offset + 7);
|
|
482
|
+
return width > 0 && height > 0 ? { width, height } : null;
|
|
483
|
+
}
|
|
484
|
+
offset += 2 + view.getUint16(offset + 2);
|
|
485
|
+
}
|
|
486
|
+
return null;
|
|
487
|
+
}
|
|
488
|
+
function readWebpSize(bytes) {
|
|
489
|
+
const ascii = (start, length) => String.fromCharCode(...bytes.subarray(start, start + length));
|
|
490
|
+
if (bytes.byteLength < 30 || ascii(0, 4) !== "RIFF" || ascii(8, 4) !== "WEBP") {
|
|
491
|
+
return null;
|
|
492
|
+
}
|
|
493
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
494
|
+
const chunk = ascii(12, 4);
|
|
495
|
+
let size = null;
|
|
496
|
+
if (chunk === "VP8 ") {
|
|
497
|
+
const startCode = bytes[23] === 157 && bytes[24] === 1 && bytes[25] === 42;
|
|
498
|
+
size = startCode ? { width: view.getUint16(26, true) & 16383, height: view.getUint16(28, true) & 16383 } : null;
|
|
499
|
+
} else if (chunk === "VP8L") {
|
|
500
|
+
const bits = view.getUint32(21, true);
|
|
501
|
+
size = bytes[20] === 47 ? { width: (bits & 16383) + 1, height: (bits >>> 14 & 16383) + 1 } : null;
|
|
502
|
+
} else if (chunk === "VP8X") {
|
|
503
|
+
size = {
|
|
504
|
+
width: 1 + bytes[24] + (bytes[25] << 8) + (bytes[26] << 16),
|
|
505
|
+
height: 1 + bytes[27] + (bytes[28] << 8) + (bytes[29] << 16)
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
return size && size.width > 0 && size.height > 0 ? size : null;
|
|
509
|
+
}
|
|
510
|
+
function sniffContent(bytes) {
|
|
511
|
+
const text = new TextDecoder().decode(bytes.subarray(0, 64)).trimStart().toLowerCase();
|
|
512
|
+
if (text.startsWith("<!doctype") || text.startsWith("<html") || text.startsWith("<head")) return "HTML";
|
|
513
|
+
if (text.startsWith("<?xml") || text.startsWith("<svg")) return "SVG/XML";
|
|
514
|
+
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "JPEG";
|
|
515
|
+
if (text.startsWith("gif8")) return "GIF";
|
|
516
|
+
if (text.startsWith("riff") && text.slice(8, 12) === "webp") return "WebP";
|
|
517
|
+
return null;
|
|
518
|
+
}
|
|
519
|
+
function checkImage(probe, maxBytes) {
|
|
520
|
+
if (probe.status === null) {
|
|
521
|
+
return [{ id: "image-unreachable", level: "error", message: `image request failed: ${probe.error ?? "unknown error"}` }];
|
|
522
|
+
}
|
|
523
|
+
if (probe.status < 200 || probe.status > 299) {
|
|
524
|
+
return [{ id: "image-unreachable", level: "error", message: `image returned HTTP ${probe.status}` }];
|
|
525
|
+
}
|
|
526
|
+
const findings = [];
|
|
527
|
+
const contentType = (probe.contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
|
|
528
|
+
const format = checkFormat(contentType, probe.head, readPngHeader(probe.head) !== null);
|
|
529
|
+
const dimensions = readImageSize(probe.head);
|
|
530
|
+
if (format) {
|
|
531
|
+
findings.push(format);
|
|
532
|
+
}
|
|
533
|
+
const limit = Math.min(maxBytes, MAX_IMAGE_BYTES);
|
|
534
|
+
const size = `${probe.truncated ? "over " : ""}${formatBytes(probe.bytes)}`;
|
|
535
|
+
if (probe.bytes > limit || probe.truncated) {
|
|
536
|
+
findings.push({
|
|
537
|
+
id: "image-too-large",
|
|
538
|
+
level: "error",
|
|
539
|
+
message: `image is ${size}, above the ${formatBytes(limit)} limit${limit === MAX_IMAGE_BYTES ? " (X rejects images over 5 MB)" : ""}`
|
|
540
|
+
});
|
|
541
|
+
} else if (probe.bytes > HEAVY_IMAGE_BYTES) {
|
|
542
|
+
findings.push({
|
|
543
|
+
id: "image-heavy",
|
|
544
|
+
level: "warn",
|
|
545
|
+
message: `image is ${size}; WhatsApp drops the preview image above ~${formatBytes(HEAVY_IMAGE_BYTES)}`
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
if (dimensions) {
|
|
549
|
+
const sizeFinding = checkDimensions(dimensions);
|
|
550
|
+
if (sizeFinding) {
|
|
551
|
+
findings.push(sizeFinding);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
return findings;
|
|
555
|
+
}
|
|
556
|
+
function checkFormat(contentType, head, hasPngHeader) {
|
|
557
|
+
const sniffed = sniffContent(head);
|
|
558
|
+
const named = contentType || "no content-type";
|
|
559
|
+
if (!contentType.startsWith("image/")) {
|
|
560
|
+
return { id: "image-format", level: "error", message: `image is served as ${named}${sniffed ? ` and the body looks like ${sniffed}` : ""}, not an image` };
|
|
561
|
+
}
|
|
562
|
+
if (head.byteLength === 0) {
|
|
563
|
+
return { id: "image-format", level: "error", message: `image is served as ${contentType} but the body is empty` };
|
|
564
|
+
}
|
|
565
|
+
if (sniffed === "HTML" || sniffed === "SVG/XML") {
|
|
566
|
+
return { id: "image-format", level: "error", message: `image is served as ${contentType} but the body looks like ${sniffed}` };
|
|
567
|
+
}
|
|
568
|
+
if (RELIABLE_TYPES.includes(contentType)) {
|
|
569
|
+
if (hasPngSignature(head) && !hasPngHeader) {
|
|
570
|
+
return { id: "image-format", level: "error", message: `image is served as ${contentType}; the PNG signature is present but the IHDR header is missing or corrupt` };
|
|
571
|
+
}
|
|
572
|
+
if (!hasPngSignature(head) && sniffed !== "JPEG") {
|
|
573
|
+
return { id: "image-format", level: "error", message: `image is served as ${contentType} but the body is not PNG or JPEG data` };
|
|
574
|
+
}
|
|
575
|
+
return null;
|
|
576
|
+
}
|
|
577
|
+
if (PARTIAL_TYPES.includes(contentType)) {
|
|
578
|
+
return { id: "image-format", level: "warn", message: `image is ${contentType}; it renders on most scrapers but fails on some, WhatsApp in particular. Use PNG or JPEG` };
|
|
579
|
+
}
|
|
580
|
+
return { id: "image-format", level: "error", message: `image is ${contentType}; link previews render PNG and JPEG reliably, not this. Use PNG or JPEG` };
|
|
581
|
+
}
|
|
582
|
+
function checkDimensions({ width, height }) {
|
|
583
|
+
const aspect = width / height;
|
|
584
|
+
const shapeOff = Math.abs(aspect / IDEAL_ASPECT - 1) > ASPECT_TOLERANCE;
|
|
585
|
+
if (width >= IDEAL_WIDTH && !shapeOff) {
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
const dimensions = `${width}x${height}`;
|
|
589
|
+
const reason = shapeOff ? `${aspect.toFixed(2)}:1, not the 1.91:1 previews are cropped to` : `under ${IDEAL_WIDTH} wide`;
|
|
590
|
+
return {
|
|
591
|
+
id: "image-size",
|
|
592
|
+
level: "warn",
|
|
593
|
+
message: `image is ${dimensions} (${reason}); use ${IDEAL_WIDTH}x${IDEAL_HEIGHT} or a larger image of the same shape, such as 2400x1260 (${dimensions} is not fine)`
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
function formatBytes(bytes) {
|
|
597
|
+
if (bytes >= 1e6) {
|
|
598
|
+
return `${(bytes / 1e6).toFixed(1)} MB`;
|
|
599
|
+
}
|
|
600
|
+
if (bytes >= 1e3) {
|
|
601
|
+
return `${Math.round(bytes / 1e3)} KB`;
|
|
602
|
+
}
|
|
603
|
+
return `${bytes} B`;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// src/audit/checks.ts
|
|
607
|
+
var MAX_TITLE_LENGTH = 70;
|
|
608
|
+
var MAX_DESCRIPTION_LENGTH = 200;
|
|
609
|
+
var CHECKS = [
|
|
610
|
+
{ id: "page-unreachable", level: "error", summary: "page is not 2xx, or the fetch failed", fix: "make the page return 200 to a plain GET, or drop it from the sitemap" },
|
|
611
|
+
{ id: "image-missing", level: "error", summary: "no og:image", fix: "add an og:image meta tag with an absolute URL" },
|
|
612
|
+
{ id: "image-relative", level: "error", summary: "og:image is a relative URL", fix: "make og:image absolute, for example by setting metadataBase in Next.js" },
|
|
613
|
+
{ id: "image-unreachable", level: "error", summary: "og:image is not 2xx, or the fetch failed", fix: "make the og:image URL return 200 publicly, without auth or bot blocking" },
|
|
614
|
+
{ id: "image-format", level: "error", summary: "og:image is not PNG or JPEG (warn for WebP, GIF, AVIF)", fix: "serve a real PNG or JPEG with a matching content-type, not an HTML error page, SVG or WebP" },
|
|
615
|
+
{ id: "image-too-large", level: "error", summary: "og:image is over --max-bytes or 5 MB", fix: "shrink the image below 5 MB, ideally below 300 KB" },
|
|
616
|
+
{ id: "image-heavy", level: "warn", summary: "og:image is over 300 KB", fix: "compress the image below 300 KB so WhatsApp keeps the preview" },
|
|
617
|
+
{ id: "image-size", level: "warn", summary: "og:image is under 1200 wide or not the 1.91:1 shape", fix: "render the image at 1200x630, or a 2x/3x of it" },
|
|
618
|
+
{ id: "image-no-alt", level: "warn", summary: "no og:image:alt", fix: "add og:image:alt describing the image" },
|
|
619
|
+
{ id: "title-missing", level: "warn", summary: "no og:title", fix: "add an og:title meta tag" },
|
|
620
|
+
{ id: "title-long", level: "warn", summary: `og:title is over ${MAX_TITLE_LENGTH} characters`, fix: `shorten og:title to ${MAX_TITLE_LENGTH} characters or fewer` },
|
|
621
|
+
{ id: "description-missing", level: "warn", summary: "no og:description", fix: "add an og:description meta tag" },
|
|
622
|
+
{ id: "description-long", level: "warn", summary: `og:description is over ${MAX_DESCRIPTION_LENGTH} characters`, fix: `shorten og:description to ${MAX_DESCRIPTION_LENGTH} characters or fewer` },
|
|
623
|
+
{ id: "url-mismatch", level: "warn", summary: "og:url differs from the page URL", fix: "set og:url to the page's own canonical URL" },
|
|
624
|
+
{ id: "twitter-card-missing", level: "warn", summary: "no twitter:card", fix: 'add twitter:card, usually "summary_large_image"' },
|
|
625
|
+
{ id: "twitter-image-missing", level: "warn", summary: "summary_large_image with no twitter:image and no usable og:image", fix: "add twitter:image, or fix the og:image that X falls back to" },
|
|
626
|
+
{ id: "image-duplicate", level: "warn", summary: "the same og:image is used by several pages", fix: "give each page its own image, or accept a shared default on purpose" }
|
|
627
|
+
];
|
|
628
|
+
var IMAGE_PROBE_CHECKS = [
|
|
629
|
+
"image-unreachable",
|
|
630
|
+
"image-format",
|
|
631
|
+
"image-too-large",
|
|
632
|
+
"image-heavy",
|
|
633
|
+
"image-size",
|
|
634
|
+
"twitter-image-missing"
|
|
635
|
+
];
|
|
636
|
+
function fixFor(id) {
|
|
637
|
+
return CHECKS.find((check) => check.id === id)?.fix ?? "";
|
|
638
|
+
}
|
|
639
|
+
function checkPage(page, maxBytes) {
|
|
640
|
+
if (page.status === null) {
|
|
641
|
+
return [{ id: "page-unreachable", level: "error", message: `page request failed: ${page.error ?? "unknown error"}` }];
|
|
642
|
+
}
|
|
643
|
+
if (page.status < 200 || page.status > 299) {
|
|
644
|
+
return [{ id: "page-unreachable", level: "error", message: `page returned HTTP ${page.status}` }];
|
|
645
|
+
}
|
|
646
|
+
const findings = [];
|
|
647
|
+
const meta = page.meta;
|
|
648
|
+
if (!meta) {
|
|
649
|
+
return findings;
|
|
650
|
+
}
|
|
651
|
+
const rawImage = meta.get("og:image");
|
|
652
|
+
let usableOgImage = false;
|
|
653
|
+
if (!rawImage) {
|
|
654
|
+
findings.push({ id: "image-missing", level: "error", message: "no og:image meta tag" });
|
|
655
|
+
} else {
|
|
656
|
+
if (isRelativeUrl(rawImage)) {
|
|
657
|
+
findings.push({ id: "image-relative", level: "error", message: `og:image is relative (${rawImage}); crawlers need an absolute URL` });
|
|
658
|
+
}
|
|
659
|
+
const imageFindings = page.image ? checkImage(page.image, maxBytes) : [];
|
|
660
|
+
findings.push(...imageFindings);
|
|
661
|
+
usableOgImage = !isRelativeUrl(rawImage) && !imageFindings.some((finding) => finding.level === "error");
|
|
662
|
+
if (!meta.get("og:image:alt")) {
|
|
663
|
+
findings.push({ id: "image-no-alt", level: "warn", message: "no og:image:alt" });
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
const title = meta.get("og:title");
|
|
667
|
+
if (!title) {
|
|
668
|
+
findings.push({ id: "title-missing", level: "warn", message: "no og:title meta tag" });
|
|
669
|
+
} else if (characterCount(title) > MAX_TITLE_LENGTH) {
|
|
670
|
+
findings.push({ id: "title-long", level: "warn", message: `og:title is ${characterCount(title)} characters (max ${MAX_TITLE_LENGTH})` });
|
|
671
|
+
}
|
|
672
|
+
const description = meta.get("og:description");
|
|
673
|
+
if (!description) {
|
|
674
|
+
findings.push({ id: "description-missing", level: "warn", message: "no og:description meta tag" });
|
|
675
|
+
} else if (characterCount(description) > MAX_DESCRIPTION_LENGTH) {
|
|
676
|
+
findings.push({
|
|
677
|
+
id: "description-long",
|
|
678
|
+
level: "warn",
|
|
679
|
+
message: `og:description is ${characterCount(description)} characters (max ${MAX_DESCRIPTION_LENGTH})`
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
const ogUrl = meta.get("og:url");
|
|
683
|
+
if (ogUrl && !sameUrl(ogUrl, [page.url, page.finalUrl], page.finalUrl)) {
|
|
684
|
+
findings.push({ id: "url-mismatch", level: "warn", message: `og:url is ${ogUrl}, but the page is ${page.url}` });
|
|
685
|
+
}
|
|
686
|
+
const card = meta.get("twitter:card");
|
|
687
|
+
if (!card) {
|
|
688
|
+
findings.push({ id: "twitter-card-missing", level: "warn", message: "no twitter:card meta tag" });
|
|
689
|
+
} else if (card.toLowerCase() === "summary_large_image" && !meta.get("twitter:image") && !usableOgImage) {
|
|
690
|
+
findings.push({
|
|
691
|
+
id: "twitter-image-missing",
|
|
692
|
+
level: "warn",
|
|
693
|
+
message: "twitter:card is summary_large_image but there is no twitter:image, and no usable og:image for X to fall back to"
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
return findings;
|
|
697
|
+
}
|
|
698
|
+
function findDuplicateImages(pages) {
|
|
699
|
+
const groups = /* @__PURE__ */ new Map();
|
|
700
|
+
for (const page of pages) {
|
|
701
|
+
if (page.imageUrl) {
|
|
702
|
+
groups.set(page.imageUrl, [...groups.get(page.imageUrl) ?? [], page.url]);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
const findings = /* @__PURE__ */ new Map();
|
|
706
|
+
for (const [imageUrl, members] of groups) {
|
|
707
|
+
const [first, ...others] = members;
|
|
708
|
+
if (first && others.length > 0) {
|
|
709
|
+
findings.set(first, {
|
|
710
|
+
id: "image-duplicate",
|
|
711
|
+
level: "warn",
|
|
712
|
+
message: `${imageUrl} is used by ${members.length} pages`,
|
|
713
|
+
pages: others
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
return findings;
|
|
718
|
+
}
|
|
719
|
+
function isRelativeUrl(value) {
|
|
720
|
+
return !/^[a-z][a-z0-9+.-]*:/i.test(value);
|
|
721
|
+
}
|
|
722
|
+
function characterCount(value) {
|
|
723
|
+
return [...value].length;
|
|
724
|
+
}
|
|
725
|
+
function sameUrl(ogUrl, candidates, base) {
|
|
726
|
+
const target = normalizeUrl(ogUrl, base);
|
|
727
|
+
return candidates.some((candidate) => normalizeUrl(candidate, base) === target);
|
|
728
|
+
}
|
|
729
|
+
function normalizeUrl(value, base) {
|
|
730
|
+
try {
|
|
731
|
+
const url = new URL(value, base);
|
|
732
|
+
url.hash = "";
|
|
733
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}${url.search}`;
|
|
734
|
+
} catch {
|
|
735
|
+
return value.replace(/\/+$/, "");
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// src/audit/report.ts
|
|
740
|
+
var FIX_FIRST_SHOWN = 5;
|
|
741
|
+
function buildReport(input) {
|
|
742
|
+
const findings = input.pages.flatMap((page) => page.findings);
|
|
743
|
+
return {
|
|
744
|
+
tool: "og-route-kit",
|
|
745
|
+
schemaVersion: 1,
|
|
746
|
+
generatedAt: (input.now ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
747
|
+
source: input.source,
|
|
748
|
+
failOn: input.failOn,
|
|
749
|
+
summary: {
|
|
750
|
+
pages: input.pages.length,
|
|
751
|
+
pagesWithFindings: input.pages.filter((page) => page.findings.length > 0).length,
|
|
752
|
+
errors: findings.filter((finding) => finding.level === "error").length,
|
|
753
|
+
warnings: findings.filter((finding) => finding.level === "warn").length
|
|
754
|
+
},
|
|
755
|
+
fixFirst: buildFixFirst(findings),
|
|
756
|
+
pages: input.pages
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
function buildFixFirst(findings) {
|
|
760
|
+
const groups = /* @__PURE__ */ new Map();
|
|
761
|
+
for (const finding of findings) {
|
|
762
|
+
const key = `${finding.level}:${finding.id}`;
|
|
763
|
+
const hits = 1 + (finding.pages?.length ?? 0);
|
|
764
|
+
const existing = groups.get(key);
|
|
765
|
+
if (existing) {
|
|
766
|
+
existing.pages += hits;
|
|
767
|
+
} else {
|
|
768
|
+
groups.set(key, { id: finding.id, level: finding.level, pages: hits, fix: fixFor(finding.id) });
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return [...groups.values()].sort(
|
|
772
|
+
(a, b) => levelRank(a.level) - levelRank(b.level) || b.pages - a.pages || a.id.localeCompare(b.id)
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
function exitCodeFor(report) {
|
|
776
|
+
const { errors, warnings } = report.summary;
|
|
777
|
+
if (report.failOn === "never") {
|
|
778
|
+
return 0;
|
|
779
|
+
}
|
|
780
|
+
return errors > 0 || report.failOn === "warn" && warnings > 0 ? 1 : 0;
|
|
781
|
+
}
|
|
782
|
+
function summaryLine(report) {
|
|
783
|
+
const { pages, errors, warnings } = report.summary;
|
|
784
|
+
return [plural(pages, "page"), plural(errors, "error"), plural(warnings, "warning")].join(" \xB7 ");
|
|
785
|
+
}
|
|
786
|
+
function formatReport(report, options) {
|
|
787
|
+
const paint = painter(options.color);
|
|
788
|
+
const lines = [];
|
|
789
|
+
if (!options.quiet) {
|
|
790
|
+
for (const page of report.pages.filter((candidate) => candidate.findings.length > 0)) {
|
|
791
|
+
lines.push(paint.bold(page.url));
|
|
792
|
+
for (const finding of page.findings) {
|
|
793
|
+
const level = finding.level === "error" ? paint.red("error") : paint.yellow("warn ");
|
|
794
|
+
lines.push(` ${level} ${paint.dim(finding.id.padEnd(22))} ${finding.message}`);
|
|
795
|
+
for (const other of finding.pages?.slice(0, 3) ?? []) {
|
|
796
|
+
lines.push(`${" ".repeat(34)}${paint.dim(`also ${other}`)}`);
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
lines.push("");
|
|
800
|
+
}
|
|
801
|
+
const clean = report.summary.pages - report.summary.pagesWithFindings;
|
|
802
|
+
if (clean > 0) {
|
|
803
|
+
lines.push(`${plural(clean, "page")} with no findings`, "");
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
const { errors, warnings } = report.summary;
|
|
807
|
+
const summary = summaryLine(report);
|
|
808
|
+
lines.push(errors > 0 ? paint.red(summary) : warnings > 0 ? paint.yellow(summary) : paint.green(summary));
|
|
809
|
+
if (report.fixFirst.length > 0) {
|
|
810
|
+
lines.push("", paint.bold("What to fix first"));
|
|
811
|
+
report.fixFirst.slice(0, FIX_FIRST_SHOWN).forEach((entry, index) => {
|
|
812
|
+
const level = entry.level === "error" ? paint.red("error") : paint.yellow("warn ");
|
|
813
|
+
lines.push(` ${index + 1}. ${level} ${entry.id} on ${plural(entry.pages, "page")}: ${entry.fix}`);
|
|
814
|
+
});
|
|
815
|
+
if (report.fixFirst.length > FIX_FIRST_SHOWN) {
|
|
816
|
+
lines.push(` \u2026and ${report.fixFirst.length - FIX_FIRST_SHOWN} more`);
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
return `${lines.join("\n")}
|
|
820
|
+
`;
|
|
821
|
+
}
|
|
822
|
+
function levelRank(level) {
|
|
823
|
+
return level === "error" ? 0 : 1;
|
|
824
|
+
}
|
|
825
|
+
function plural(count, noun) {
|
|
826
|
+
return `${count} ${noun}${count === 1 ? "" : "s"}`;
|
|
827
|
+
}
|
|
828
|
+
function painter(enabled) {
|
|
829
|
+
const wrap = (open, close) => (text) => enabled ? `\x1B[${open}m${text}\x1B[${close}m` : text;
|
|
830
|
+
return { bold: wrap(1, 22), dim: wrap(2, 22), red: wrap(31, 39), yellow: wrap(33, 39), green: wrap(32, 39) };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// src/audit/run.ts
|
|
834
|
+
async function runAudit(config) {
|
|
835
|
+
const wants = (id) => !config.only || config.only.has(id);
|
|
836
|
+
const needsImage = IMAGE_PROBE_CHECKS.some(wants);
|
|
837
|
+
const images = /* @__PURE__ */ new Map();
|
|
838
|
+
let done = 0;
|
|
839
|
+
const probes = await mapPool(config.pages, config.concurrency, async (url) => {
|
|
840
|
+
const fetched = await probePage(url, config);
|
|
841
|
+
const meta = fetched.status === null ? null : parseMeta(fetched.html);
|
|
842
|
+
const rawImage = meta?.get("og:image");
|
|
843
|
+
const imageUrl = rawImage ? resolveUrl(rawImage, fetched.finalUrl) : null;
|
|
844
|
+
let image = null;
|
|
845
|
+
if (imageUrl && needsImage) {
|
|
846
|
+
const cached = images.get(imageUrl) ?? probeImage(imageUrl, config);
|
|
847
|
+
images.set(imageUrl, cached);
|
|
848
|
+
image = await cached;
|
|
849
|
+
}
|
|
850
|
+
config.onProgress?.(done += 1, config.pages.length);
|
|
851
|
+
const probe = { url, finalUrl: fetched.finalUrl, status: fetched.status, meta, imageUrl, image };
|
|
852
|
+
if (fetched.error) {
|
|
853
|
+
probe.error = fetched.error;
|
|
854
|
+
}
|
|
855
|
+
return probe;
|
|
856
|
+
});
|
|
857
|
+
const duplicates = wants("image-duplicate") ? findDuplicateImages(probes) : /* @__PURE__ */ new Map();
|
|
858
|
+
const pages = probes.map((probe) => {
|
|
859
|
+
const findings = [...checkPage(probe, config.maxBytes), ...duplicates.get(probe.url) ? [duplicates.get(probe.url)] : []];
|
|
860
|
+
const header = probe.image ? readImageSize(probe.image.head) : null;
|
|
861
|
+
return {
|
|
862
|
+
url: probe.url,
|
|
863
|
+
status: probe.status,
|
|
864
|
+
image: probe.image ? {
|
|
865
|
+
url: probe.image.url,
|
|
866
|
+
status: probe.image.status,
|
|
867
|
+
contentType: probe.image.contentType,
|
|
868
|
+
bytes: probe.image.bytes,
|
|
869
|
+
width: header?.width ?? null,
|
|
870
|
+
height: header?.height ?? null
|
|
871
|
+
} : null,
|
|
872
|
+
findings: findings.filter((finding) => wants(finding.id))
|
|
873
|
+
};
|
|
874
|
+
});
|
|
875
|
+
return buildReport({ source: config.source, failOn: config.failOn, pages });
|
|
876
|
+
}
|
|
877
|
+
function resolveUrl(value, base) {
|
|
878
|
+
try {
|
|
879
|
+
return new URL(value, base).href;
|
|
880
|
+
} catch {
|
|
881
|
+
return value;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// src/cli/audit.ts
|
|
886
|
+
var DEFAULT_CONCURRENCY = 4;
|
|
887
|
+
var MAX_CONCURRENCY = 8;
|
|
888
|
+
var FAIL_ON_VALUES = ["error", "warn", "never"];
|
|
889
|
+
function parseAuditFlags(flags) {
|
|
890
|
+
const sources = ["sitemap", "urls", "url"].filter((key) => flags[key] !== void 0);
|
|
891
|
+
const kind = sources[0];
|
|
892
|
+
if (sources.length !== 1 || !kind) {
|
|
893
|
+
throw new Error("Pass exactly one of --sitemap <url|path>, --urls <file|-> or --url <page-url>");
|
|
894
|
+
}
|
|
895
|
+
const value = flags[kind];
|
|
896
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
897
|
+
throw new Error(`Flag --${kind} requires a value`);
|
|
898
|
+
}
|
|
899
|
+
const notes = [];
|
|
900
|
+
const requested = optionalPositiveInteger(flags, "concurrency", DEFAULT_CONCURRENCY);
|
|
901
|
+
if (requested > MAX_CONCURRENCY) {
|
|
902
|
+
notes.push(`--concurrency ${requested} is above the cap; using ${MAX_CONCURRENCY}`);
|
|
903
|
+
}
|
|
904
|
+
const failOn = flags["fail-on"] ?? "error";
|
|
905
|
+
if (!FAIL_ON_VALUES.includes(failOn)) {
|
|
906
|
+
throw new Error(`Flag --fail-on must be one of ${FAIL_ON_VALUES.join(", ")}`);
|
|
907
|
+
}
|
|
908
|
+
const json = flags.json;
|
|
909
|
+
return {
|
|
910
|
+
source: { kind, value },
|
|
911
|
+
concurrency: Math.min(requested, MAX_CONCURRENCY),
|
|
912
|
+
timeoutMs: optionalPositiveInteger(flags, "timeout", DEFAULT_TIMEOUT_MS),
|
|
913
|
+
maxBytes: optionalPositiveInteger(flags, "max-bytes", DEFAULT_MAX_BYTES),
|
|
914
|
+
limit: flags.limit === void 0 ? void 0 : optionalPositiveInteger(flags, "limit", 1),
|
|
915
|
+
only: parseOnly(flags.only),
|
|
916
|
+
json: json === void 0 ? void 0 : typeof json === "string" ? json : "-",
|
|
917
|
+
failOn,
|
|
918
|
+
quiet: flags.quiet !== void 0,
|
|
919
|
+
notes
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
function parseOnly(value) {
|
|
923
|
+
if (value === void 0) {
|
|
924
|
+
return null;
|
|
925
|
+
}
|
|
926
|
+
const ids = typeof value === "string" ? value.split(",").map((id) => id.trim()).filter(Boolean) : [];
|
|
927
|
+
const unknown = ids.filter((id) => !CHECK_IDS.includes(id));
|
|
928
|
+
if (ids.length === 0 || unknown.length > 0) {
|
|
929
|
+
throw new Error(`Flag --only takes comma-separated check ids${unknown.length ? `; unknown: ${unknown.join(", ")}` : ""}. Known ids: ${CHECK_IDS.join(", ")}`);
|
|
930
|
+
}
|
|
931
|
+
return new Set(ids);
|
|
932
|
+
}
|
|
933
|
+
function parseUrlList(text) {
|
|
934
|
+
const urls = [];
|
|
935
|
+
for (const [index, raw] of text.split(/\r?\n/).entries()) {
|
|
936
|
+
const line = raw.trim();
|
|
937
|
+
if (!line || line.startsWith("#")) {
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
if (!/^https?:\/\//i.test(line) || !URL.canParse(line)) {
|
|
941
|
+
throw new Error(`Line ${index + 1} of the URL list is not an http(s) URL: ${line}`);
|
|
942
|
+
}
|
|
943
|
+
urls.push(line);
|
|
944
|
+
}
|
|
945
|
+
return urls;
|
|
946
|
+
}
|
|
947
|
+
async function runAuditCommand(flags, io = defaultIo(flags)) {
|
|
948
|
+
try {
|
|
949
|
+
const options = parseAuditFlags(flags);
|
|
950
|
+
const network = { timeoutMs: options.timeoutMs, maxBytes: options.maxBytes };
|
|
951
|
+
const notes = [...options.notes];
|
|
952
|
+
const pages = await resolvePages(options, io, notes, network);
|
|
953
|
+
for (const note of notes.slice(0, 5)) {
|
|
954
|
+
io.stderr(`note: ${note}
|
|
955
|
+
`);
|
|
956
|
+
}
|
|
957
|
+
if (notes.length > 5) {
|
|
958
|
+
io.stderr(`note: \u2026and ${notes.length - 5} more
|
|
959
|
+
`);
|
|
960
|
+
}
|
|
961
|
+
if (!options.quiet) {
|
|
962
|
+
io.stderr(`Auditing ${pages.length} page${pages.length === 1 ? "" : "s"} (concurrency ${options.concurrency})
|
|
963
|
+
`);
|
|
964
|
+
}
|
|
965
|
+
const report = await runAudit({
|
|
966
|
+
...network,
|
|
967
|
+
pages,
|
|
968
|
+
source: options.source,
|
|
969
|
+
failOn: options.failOn,
|
|
970
|
+
concurrency: options.concurrency,
|
|
971
|
+
only: options.only
|
|
972
|
+
});
|
|
973
|
+
const table = formatReport(report, { color: io.color && options.json === void 0, quiet: options.quiet });
|
|
974
|
+
if (options.json === void 0) {
|
|
975
|
+
io.stdout(table);
|
|
976
|
+
} else {
|
|
977
|
+
io.stderr(table);
|
|
978
|
+
const json = `${JSON.stringify(report, null, 2)}
|
|
979
|
+
`;
|
|
980
|
+
if (options.json === "-") {
|
|
981
|
+
io.stdout(json);
|
|
982
|
+
} else {
|
|
983
|
+
await mkdir(dirname(options.json), { recursive: true });
|
|
984
|
+
await writeFile(options.json, json);
|
|
985
|
+
io.stderr(`Wrote ${options.json}
|
|
986
|
+
`);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
return exitCodeFor(report);
|
|
990
|
+
} catch (error) {
|
|
991
|
+
io.stderr(`Audit failed: ${error instanceof Error ? error.message : String(error)}
|
|
992
|
+
`);
|
|
993
|
+
return 2;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
async function resolvePages(options, io, notes, network) {
|
|
997
|
+
const { kind, value } = options.source;
|
|
998
|
+
let pages;
|
|
999
|
+
if (kind === "url") {
|
|
1000
|
+
pages = parseUrlList(value);
|
|
1001
|
+
} else if (kind === "urls") {
|
|
1002
|
+
pages = parseUrlList(value === "-" ? await io.readStdin() : await readFile2(value, "utf8"));
|
|
1003
|
+
} else {
|
|
1004
|
+
pages = await collectSitemapUrls(value, {
|
|
1005
|
+
readSource: (source) => readSitemapSource(source, network),
|
|
1006
|
+
onNote: (note) => notes.push(note)
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
pages = [...new Set(pages)];
|
|
1010
|
+
if (options.limit !== void 0 && pages.length > options.limit) {
|
|
1011
|
+
notes.push(`Sampling ${options.limit} of ${pages.length} pages, evenly spread across the list`);
|
|
1012
|
+
pages = sampleEvenly(pages, options.limit);
|
|
1013
|
+
}
|
|
1014
|
+
if (pages.length === 0) {
|
|
1015
|
+
throw new Error("No page URLs to audit");
|
|
1016
|
+
}
|
|
1017
|
+
return pages;
|
|
1018
|
+
}
|
|
1019
|
+
function defaultIo(flags) {
|
|
1020
|
+
return {
|
|
1021
|
+
stdout: (text) => void process.stdout.write(text),
|
|
1022
|
+
stderr: (text) => void process.stderr.write(text),
|
|
1023
|
+
readStdin: async () => {
|
|
1024
|
+
const chunks = [];
|
|
1025
|
+
for await (const chunk of process.stdin) {
|
|
1026
|
+
chunks.push(Buffer.from(chunk));
|
|
1027
|
+
}
|
|
1028
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
1029
|
+
},
|
|
1030
|
+
color: Boolean(process.stdout.isTTY) && flags.json === void 0 && !process.env.NO_COLOR
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// src/cli/index.ts
|
|
1035
|
+
async function main() {
|
|
1036
|
+
const args = process.argv.slice(2);
|
|
1037
|
+
const command = args[0] ?? "help";
|
|
1038
|
+
const flags = parseFlags(args.slice(1));
|
|
1039
|
+
try {
|
|
1040
|
+
if (command === "export") {
|
|
1041
|
+
await exportImage(flags);
|
|
1042
|
+
} else if (command === "check") {
|
|
1043
|
+
await checkImage2(flags);
|
|
1044
|
+
} else if (command === "preview") {
|
|
1045
|
+
preview(flags);
|
|
1046
|
+
} else if (command === "audit") {
|
|
1047
|
+
process.exitCode = await runAuditCommand(flags);
|
|
1048
|
+
} else {
|
|
1049
|
+
help();
|
|
1050
|
+
}
|
|
1051
|
+
} catch (error) {
|
|
1052
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
1053
|
+
process.exitCode = 1;
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
async function exportImage(flags) {
|
|
1057
|
+
const url = requireString(flags, "url");
|
|
1058
|
+
const out = requireString(flags, "out");
|
|
1059
|
+
const maxBytes = optionalPositiveInteger(flags, "max-bytes", DEFAULT_MAX_BYTES);
|
|
1060
|
+
const timeoutMs = optionalPositiveInteger(flags, "timeout", DEFAULT_TIMEOUT_MS);
|
|
1061
|
+
let bytes;
|
|
1062
|
+
try {
|
|
1063
|
+
bytes = await fetchPng(url, { maxBytes, timeoutMs });
|
|
1064
|
+
} catch (error) {
|
|
1065
|
+
throw new Error(`Export failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1066
|
+
}
|
|
1067
|
+
await mkdir2(dirname2(out), { recursive: true });
|
|
1068
|
+
await writeFile2(out, bytes);
|
|
1069
|
+
console.log(`Wrote ${bytes.byteLength} bytes to ${out}`);
|
|
1070
|
+
}
|
|
1071
|
+
async function checkImage2(flags) {
|
|
1072
|
+
const url = requireString(flags, "url");
|
|
1073
|
+
const maxBytes = optionalPositiveInteger(flags, "max-bytes", DEFAULT_MAX_BYTES);
|
|
1074
|
+
const timeoutMs = optionalPositiveInteger(flags, "timeout", DEFAULT_TIMEOUT_MS);
|
|
1075
|
+
let bytes;
|
|
1076
|
+
try {
|
|
1077
|
+
bytes = await fetchPng(url, { maxBytes, timeoutMs });
|
|
1078
|
+
} catch (error) {
|
|
1079
|
+
throw new Error(`Check failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1080
|
+
}
|
|
1081
|
+
console.log(`OK 200 image/png ${bytes.byteLength} bytes`);
|
|
1082
|
+
}
|
|
1083
|
+
function preview(flags) {
|
|
1084
|
+
for (const line of buildPreviewUrls(flags)) {
|
|
1085
|
+
console.log(line);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
function help() {
|
|
1089
|
+
console.log(`og-route-kit
|
|
1090
|
+
|
|
1091
|
+
Commands:
|
|
1092
|
+
export --url <url> --out <path> [--max-bytes <n>] [--timeout <ms>]
|
|
1093
|
+
Fetch a PNG route and write it to disk
|
|
1094
|
+
check --url <url> [--max-bytes <n>] [--timeout <ms>]
|
|
1095
|
+
Verify a PNG route is healthy
|
|
1096
|
+
preview [--origin <url>] [--route <path>]
|
|
1097
|
+
Print local preview URLs
|
|
1098
|
+
audit (--sitemap <url|path> | --urls <file|-> | --url <page-url>)
|
|
1099
|
+
[--concurrency <n>] [--timeout <ms>] [--max-bytes <n>] [--limit <n>]
|
|
1100
|
+
[--only <check,check>] [--json [path|-]] [--fail-on <error|warn|never>] [--quiet]
|
|
1101
|
+
Audit og:image tags and the images they point at.
|
|
1102
|
+
Exit 0 clean, 1 findings, 2 usage or network failure
|
|
1103
|
+
`);
|
|
1104
|
+
}
|
|
1105
|
+
await main();
|
|
1106
|
+
//# sourceMappingURL=index.js.map
|