snappy-prerender 2.6.0 → 2.7.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 +51 -0
- package/README.md +122 -101
- package/docs/limitations.md +58 -0
- package/docs/react-snap-migration.md +45 -0
- package/docs/report.md +102 -0
- package/package.json +2 -1
- package/src/cli-init.js +205 -0
- package/src/cli.js +73 -168
- package/src/core/artifacts.js +2 -0
- package/src/core/audit/index.js +114 -0
- package/src/core/audit/links.js +63 -0
- package/src/core/audit/metadata.js +88 -0
- package/src/core/audit/sitemap.js +39 -0
- package/src/core/config.js +129 -5
- package/src/core/crawl.js +300 -0
- package/src/core/csp.js +127 -0
- package/src/core/frameworks.js +94 -0
- package/src/core/hydration-diff.js +93 -0
- package/src/core/init.js +143 -30
- package/src/core/normalize.js +7 -0
- package/src/core/page-meta.js +108 -0
- package/src/core/preload-links.js +120 -0
- package/src/core/render.js +87 -5
- package/src/core/report.js +108 -0
- package/src/core/resources.js +5 -1
- package/src/core/route-config.js +17 -0
- package/src/core/route-sources.js +209 -0
- package/src/core/run.js +68 -113
- package/src/core/sitemap.js +90 -14
- package/src/core/verify.js +92 -48
- package/src/core/write.js +92 -7
- package/src/head/index.js +2 -2
- package/src/head/manager.js +54 -13
- package/src/head/tags.js +52 -6
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { renderRoute } from './render.js';
|
|
4
|
+
import { resolveRouteConfig } from './route-config.js';
|
|
5
|
+
import {
|
|
6
|
+
crawlRoots,
|
|
7
|
+
filterRoutes,
|
|
8
|
+
isIncludedRoute,
|
|
9
|
+
matchesPattern,
|
|
10
|
+
normaliseRoute,
|
|
11
|
+
withinDepth,
|
|
12
|
+
} from './routes.js';
|
|
13
|
+
import { createPool, mapLimit } from './scheduler.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Runs the crawl and render pool. Each rendered page contributes its output, any new
|
|
17
|
+
* same-origin routes, and the resources recorded for the link-hint features.
|
|
18
|
+
*/
|
|
19
|
+
export async function renderAllRoutes({
|
|
20
|
+
browser,
|
|
21
|
+
server,
|
|
22
|
+
config,
|
|
23
|
+
log,
|
|
24
|
+
report,
|
|
25
|
+
outputDir,
|
|
26
|
+
sourceSeeds = [],
|
|
27
|
+
}) {
|
|
28
|
+
const visited = new Set();
|
|
29
|
+
const scheduled = new Set();
|
|
30
|
+
const rendered = new Map();
|
|
31
|
+
const cap = config.maxRoutes ?? Number.POSITIVE_INFINITY;
|
|
32
|
+
let nextOrder = 0;
|
|
33
|
+
|
|
34
|
+
// Queues routes up to maxRoutes, recording exactly which candidates did not fit.
|
|
35
|
+
// A seed used only to reach wildcard routes is given output: false and is rendered
|
|
36
|
+
// for its links without being written.
|
|
37
|
+
const accept = (routes, outputFor = () => true) => {
|
|
38
|
+
const accepted = [];
|
|
39
|
+
const dropped = [];
|
|
40
|
+
for (const route of routes) {
|
|
41
|
+
if (scheduled.has(route)) continue;
|
|
42
|
+
if (scheduled.size >= cap) {
|
|
43
|
+
dropped.push(route);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
scheduled.add(route);
|
|
47
|
+
accepted.push({ route, output: outputFor(route), order: nextOrder });
|
|
48
|
+
nextOrder += 1;
|
|
49
|
+
}
|
|
50
|
+
if (dropped.length > 0) {
|
|
51
|
+
const previous = report.truncated?.droppedRoutes ?? [];
|
|
52
|
+
report.truncated = {
|
|
53
|
+
limit: config.maxRoutes,
|
|
54
|
+
routes: scheduled.size,
|
|
55
|
+
droppedRoutes: [...new Set([...previous, ...dropped])].sort(),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
return accepted;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const renderOne = async ({ route, output, depth = 0, order = null }) => {
|
|
62
|
+
if (visited.has(route)) return null;
|
|
63
|
+
visited.add(route);
|
|
64
|
+
log.debug(`rendering ${route}${output ? '' : ' as a crawl seed'}`);
|
|
65
|
+
const routeConfig = resolveRouteConfig(config, route);
|
|
66
|
+
const result = await renderWithRetries({
|
|
67
|
+
browser,
|
|
68
|
+
server,
|
|
69
|
+
route,
|
|
70
|
+
routeConfig,
|
|
71
|
+
config,
|
|
72
|
+
log,
|
|
73
|
+
report,
|
|
74
|
+
outputDir,
|
|
75
|
+
screenshot: config.saveAs !== 'html',
|
|
76
|
+
});
|
|
77
|
+
if (!result) return null;
|
|
78
|
+
result.depth = depth;
|
|
79
|
+
result.order = order;
|
|
80
|
+
try {
|
|
81
|
+
const notFoundRoute = config.notFoundRoute ? normaliseRoute(config.notFoundRoute) : null;
|
|
82
|
+
const isNotFoundRoute = notFoundRoute !== null && route === notFoundRoute;
|
|
83
|
+
if (result.statusCode === 404 && !isNotFoundRoute) {
|
|
84
|
+
report.errors.push({ route, message: 'returned 404' });
|
|
85
|
+
log.error(` route ${route} returned 404`);
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
if (isNotFoundRoute) {
|
|
89
|
+
result.notFound = true;
|
|
90
|
+
if (!report.notFoundRoutes.includes(route)) report.notFoundRoutes.push(route);
|
|
91
|
+
if (result.statusCode !== null && result.statusCode !== 404) {
|
|
92
|
+
log.warn(` ignored unknown prerender-status-code ${result.statusCode} on ${route}`);
|
|
93
|
+
}
|
|
94
|
+
} else if (result.statusCode !== null) {
|
|
95
|
+
log.warn(` ignored unknown prerender-status-code ${result.statusCode} on ${route}`);
|
|
96
|
+
}
|
|
97
|
+
if (output && result.empty) {
|
|
98
|
+
report.emptyPages.push(route);
|
|
99
|
+
if (config.failOnEmptyPage) {
|
|
100
|
+
report.errors.push({ route, message: 'rendered an empty page' });
|
|
101
|
+
log.error(` empty page ${route}: no app content was found`);
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
log.warn(` empty page ${route}: no app content was found`);
|
|
105
|
+
}
|
|
106
|
+
if (output) {
|
|
107
|
+
rendered.set(route, result);
|
|
108
|
+
report.routes.push(route);
|
|
109
|
+
for (const to of result.links) report.links.push({ from: route, to });
|
|
110
|
+
}
|
|
111
|
+
for (const message of result.pageErrors) {
|
|
112
|
+
report.pageErrors.push({ route, message });
|
|
113
|
+
log.warn(` page error on ${route}: ${message}`);
|
|
114
|
+
}
|
|
115
|
+
for (const message of result.consoleErrors) {
|
|
116
|
+
report.consoleErrors.push({ route, message });
|
|
117
|
+
}
|
|
118
|
+
if (result.consoleErrors.length > 0) {
|
|
119
|
+
log.debug(` console error on ${route}: ${result.consoleErrors[0]}`);
|
|
120
|
+
if (config.failOnConsoleError) {
|
|
121
|
+
report.errors.push({ route, message: `console error: ${result.consoleErrors[0]}` });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
for (const failure of result.failedRequests) {
|
|
125
|
+
report.failedRequests.push({ route, ...failure });
|
|
126
|
+
const detail = failure.status ? `HTTP ${failure.status}` : failure.error;
|
|
127
|
+
log.warn(` failed request on ${route}: ${failure.url} (${detail})`);
|
|
128
|
+
}
|
|
129
|
+
if (result.failedRequests.length > 0 && config.failOnFailedRequest) {
|
|
130
|
+
const first = result.failedRequests[0];
|
|
131
|
+
report.errors.push({
|
|
132
|
+
route,
|
|
133
|
+
message: `failed request: ${first.url}${first.status ? ` (HTTP ${first.status})` : ''}`,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return { result, routeConfig };
|
|
137
|
+
} catch (error) {
|
|
138
|
+
report.errors.push({ route, message: error.message });
|
|
139
|
+
log.error(` failed ${route}: ${error.message}`);
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
const outputFor = (route) => !config.includeProvided || isIncludedRoute(route, config.include);
|
|
145
|
+
const candidates = [];
|
|
146
|
+
if (sourceSeeds.length > 0) candidates.push(...sourceSeeds);
|
|
147
|
+
if (sourceSeeds.length === 0 || config.includeProvided) {
|
|
148
|
+
candidates.push(...crawlRoots(config));
|
|
149
|
+
}
|
|
150
|
+
const roots = accept([...new Set(sortRoutes(candidates, config))], outputFor);
|
|
151
|
+
|
|
152
|
+
const deterministic = config.maxRoutes !== null || config.routePriority.length > 0;
|
|
153
|
+
if (deterministic) {
|
|
154
|
+
await renderWaves({ config, accept, renderOne, roots, report, log });
|
|
155
|
+
} else {
|
|
156
|
+
const pool = createPool({
|
|
157
|
+
concurrency: config.concurrency,
|
|
158
|
+
handler: async ({ route, depth, output, order }) => {
|
|
159
|
+
const renderedRoute = await renderOne({ route, output, depth, order });
|
|
160
|
+
if (!renderedRoute) return;
|
|
161
|
+
const { result, routeConfig } = renderedRoute;
|
|
162
|
+
if (routeConfig.crawl && withinDepth(depth + 1, routeConfig.maxDepth)) {
|
|
163
|
+
const discovered = filterRoutes(result.links, {
|
|
164
|
+
include: config.includeProvided ? config.include : [],
|
|
165
|
+
exclude: config.exclude,
|
|
166
|
+
}).filter((candidate) => !scheduled.has(candidate));
|
|
167
|
+
const accepted = accept(sortRoutes(discovered, config));
|
|
168
|
+
pool.push(accepted.map((item) => ({ ...item, depth: depth + 1 })));
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
pool.push(roots.map((item) => ({ ...item, depth: 0 })));
|
|
173
|
+
const { errors } = await pool.run();
|
|
174
|
+
for (const { item, error } of errors) {
|
|
175
|
+
report.errors.push({ route: item.route, message: error.message });
|
|
176
|
+
log.error(` pool error on ${item.route}: ${error.message}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return rendered;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Renders one route with the configured retry policy. A retryable failure is retried
|
|
184
|
+
* after retryDelay; the final failure records the attempt count and, when traceOnError
|
|
185
|
+
* is on, a Playwright trace written under the output directory.
|
|
186
|
+
*/
|
|
187
|
+
async function renderWithRetries({
|
|
188
|
+
browser,
|
|
189
|
+
server,
|
|
190
|
+
route,
|
|
191
|
+
routeConfig,
|
|
192
|
+
config,
|
|
193
|
+
log,
|
|
194
|
+
report,
|
|
195
|
+
outputDir,
|
|
196
|
+
screenshot,
|
|
197
|
+
}) {
|
|
198
|
+
const attempts = config.retries + 1;
|
|
199
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
200
|
+
const traceFile =
|
|
201
|
+
config.traceOnError && !config.dryRun && attempt === attempts
|
|
202
|
+
? await prepareTraceFile(outputDir, route, attempt)
|
|
203
|
+
: null;
|
|
204
|
+
try {
|
|
205
|
+
const result = await renderRoute({
|
|
206
|
+
browser,
|
|
207
|
+
origin: server.origin,
|
|
208
|
+
route,
|
|
209
|
+
config: routeConfig,
|
|
210
|
+
screenshot,
|
|
211
|
+
traceFile,
|
|
212
|
+
});
|
|
213
|
+
if (attempt > 1) log.info(` ${route}: succeeded on attempt ${attempt}`);
|
|
214
|
+
result.attempts = attempt;
|
|
215
|
+
return result;
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (error.tracePath) {
|
|
218
|
+
report.traces.push({ route, attempt, file: error.tracePath });
|
|
219
|
+
log.warn(` trace for ${route}: ${error.tracePath}`);
|
|
220
|
+
}
|
|
221
|
+
if (error.retryable !== false && attempt < attempts) {
|
|
222
|
+
log.warn(
|
|
223
|
+
` attempt ${attempt}/${attempts} failed for ${route}: ${error.message}; retrying`,
|
|
224
|
+
);
|
|
225
|
+
await delay(config.retryDelay);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
report.errors.push({ route, message: error.message, attempts: attempt });
|
|
229
|
+
log.error(` failed ${route} after ${attempt} attempt(s): ${error.message}`);
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Creates the trace directory and returns the archive path for one failed attempt.
|
|
237
|
+
async function prepareTraceFile(outputDir, route, attempt) {
|
|
238
|
+
const slug = route
|
|
239
|
+
.replace(/^\/+|\/+$/g, '')
|
|
240
|
+
.replace(/[^a-z0-9._-]+/gi, '-')
|
|
241
|
+
.toLowerCase();
|
|
242
|
+
const dir = path.join(outputDir, 'snappy-traces');
|
|
243
|
+
await fs.mkdir(dir, { recursive: true });
|
|
244
|
+
return path.join(dir, `${slug || 'root'}-${attempt}.zip`);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Waits between retry attempts.
|
|
248
|
+
function delay(ms) {
|
|
249
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Deterministic BFS crawl used when maxRoutes or routePriority is set. Each depth level
|
|
254
|
+
* is sorted, capped and rendered as a wave, so the accepted set never depends on which
|
|
255
|
+
* concurrent page happened to finish first.
|
|
256
|
+
*/
|
|
257
|
+
async function renderWaves({ config, accept, renderOne, roots, report, log }) {
|
|
258
|
+
let frontier = roots.map((item) => ({ ...item, depth: 0 }));
|
|
259
|
+
let depth = 0;
|
|
260
|
+
while (frontier.length > 0) {
|
|
261
|
+
const { results, errors } = await mapLimit(frontier, config.concurrency, async (item) => ({
|
|
262
|
+
item,
|
|
263
|
+
rendered: await renderOne(item),
|
|
264
|
+
}));
|
|
265
|
+
for (const { item, error } of errors) {
|
|
266
|
+
report.errors.push({ route: item.route, message: error.message });
|
|
267
|
+
log.error(` pool error on ${item.route}: ${error.message}`);
|
|
268
|
+
}
|
|
269
|
+
const discovered = [];
|
|
270
|
+
for (const { rendered: renderedRoute } of results) {
|
|
271
|
+
if (!renderedRoute) continue;
|
|
272
|
+
if (!renderedRoute.routeConfig.crawl) continue;
|
|
273
|
+
if (!withinDepth(depth + 1, config.maxDepth)) continue;
|
|
274
|
+
discovered.push(
|
|
275
|
+
...filterRoutes(renderedRoute.result.links, {
|
|
276
|
+
include: config.includeProvided ? config.include : [],
|
|
277
|
+
exclude: config.exclude,
|
|
278
|
+
}),
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
if (!withinDepth(depth + 1, config.maxDepth)) break;
|
|
282
|
+
const next = accept(sortRoutes(discovered, config));
|
|
283
|
+
frontier = next.map((item) => ({ ...item, depth: depth + 1 }));
|
|
284
|
+
depth += 1;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Orders routes by routePriority first, then by path for a stable frontier.
|
|
289
|
+
function sortRoutes(routes, config) {
|
|
290
|
+
return [...routes].sort((a, b) => sortRoute(a, b, config));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function sortRoute(a, b, config) {
|
|
294
|
+
const rank = (route) => {
|
|
295
|
+
const index = config.routePriority.findIndex((pattern) => matchesPattern(route, pattern));
|
|
296
|
+
return index === -1 ? Number.MAX_SAFE_INTEGER : index;
|
|
297
|
+
};
|
|
298
|
+
const difference = rank(a) - rank(b);
|
|
299
|
+
return difference === 0 ? a.localeCompare(b) : difference;
|
|
300
|
+
}
|
package/src/core/csp.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { parse, serialize } from 'parse5';
|
|
3
|
+
|
|
4
|
+
// Types that execute as JavaScript. A script with any other type is data, not code.
|
|
5
|
+
const EXECUTABLE_TYPES = new Set([
|
|
6
|
+
'',
|
|
7
|
+
'text/javascript',
|
|
8
|
+
'application/javascript',
|
|
9
|
+
'application/ecmascript',
|
|
10
|
+
'text/ecmascript',
|
|
11
|
+
'module',
|
|
12
|
+
]);
|
|
13
|
+
const CSP_MARKER = 'data-snappy-csp';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Adds a hash-based Content-Security-Policy meta tag covering every inline script and
|
|
17
|
+
* style in the final document. A policy this function wrote on an earlier run is
|
|
18
|
+
* replaced; a policy the app wrote is kept untouched, so the prerenderer never merges
|
|
19
|
+
* two policies silently.
|
|
20
|
+
*/
|
|
21
|
+
export function applyCspHashes(html) {
|
|
22
|
+
const document = parse(html);
|
|
23
|
+
const head = findHead(document);
|
|
24
|
+
if (!head) return { html, hashedScripts: 0, hashedStyles: 0, existingPolicy: false };
|
|
25
|
+
removeGeneratedPolicy(head);
|
|
26
|
+
const existing = findPolicyMeta(head);
|
|
27
|
+
if (existing) return { html, hashedScripts: 0, hashedStyles: 0, existingPolicy: true };
|
|
28
|
+
|
|
29
|
+
const scriptHashes = [];
|
|
30
|
+
const styleHashes = [];
|
|
31
|
+
walk(document, (node) => {
|
|
32
|
+
if (node.tagName === 'script' && isExecutableInline(node)) {
|
|
33
|
+
scriptHashes.push(hashOf(textContent(node)));
|
|
34
|
+
}
|
|
35
|
+
if (node.tagName === 'style') {
|
|
36
|
+
styleHashes.push(hashOf(textContent(node)));
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const directives = [
|
|
41
|
+
`script-src 'self'${hashList(scriptHashes)}`,
|
|
42
|
+
`style-src 'self'${hashList(styleHashes)}`,
|
|
43
|
+
];
|
|
44
|
+
head.childNodes.unshift(metaNode(directives.join('; ')));
|
|
45
|
+
return {
|
|
46
|
+
html: serialize(document),
|
|
47
|
+
hashedScripts: scriptHashes.length,
|
|
48
|
+
hashedStyles: styleHashes.length,
|
|
49
|
+
existingPolicy: false,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// A script is executable inline code when it has no src and no data type.
|
|
54
|
+
function isExecutableInline(node) {
|
|
55
|
+
if (attribute(node, 'src').length > 0) return false;
|
|
56
|
+
const type = attribute(node, 'type').trim().toLowerCase();
|
|
57
|
+
return EXECUTABLE_TYPES.has(type);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Renders the hash list, deduplicated and in document order.
|
|
61
|
+
function hashList(hashes) {
|
|
62
|
+
return [...new Set(hashes)].map((hash) => ` '${hash}'`).join('');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Base64 SHA-256, the form a CSP hash source uses.
|
|
66
|
+
function hashOf(text) {
|
|
67
|
+
return `sha256-${createHash('sha256').update(text).digest('base64')}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function findHead(document) {
|
|
71
|
+
const html = (document.childNodes ?? []).find((node) => node.tagName === 'html');
|
|
72
|
+
return (html?.childNodes ?? []).find((node) => node.tagName === 'head') ?? null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function findPolicyMeta(head) {
|
|
76
|
+
return (head.childNodes ?? []).some(
|
|
77
|
+
(node) =>
|
|
78
|
+
node.tagName === 'meta' &&
|
|
79
|
+
attribute(node, 'http-equiv').toLowerCase() === 'content-security-policy' &&
|
|
80
|
+
!hasAttribute(node, CSP_MARKER),
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Removes the policy this prerenderer wrote on an earlier run, so it is recomputed against
|
|
85
|
+
// the current document instead of being mistaken for an app-owned policy.
|
|
86
|
+
function removeGeneratedPolicy(head) {
|
|
87
|
+
head.childNodes = (head.childNodes ?? []).filter(
|
|
88
|
+
(node) => !(node.tagName === 'meta' && hasAttribute(node, CSP_MARKER)),
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function metaNode(content) {
|
|
93
|
+
return {
|
|
94
|
+
nodeName: 'meta',
|
|
95
|
+
tagName: 'meta',
|
|
96
|
+
attrs: [
|
|
97
|
+
{ name: 'http-equiv', value: 'Content-Security-Policy' },
|
|
98
|
+
{ name: 'content', value: content },
|
|
99
|
+
{ name: CSP_MARKER, value: '' },
|
|
100
|
+
],
|
|
101
|
+
namespaceURI: 'http://www.w3.org/1999/xhtml',
|
|
102
|
+
childNodes: [],
|
|
103
|
+
parentNode: null,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function walk(node, visit) {
|
|
108
|
+
visit(node);
|
|
109
|
+
for (const child of node.childNodes ?? []) walk(child, visit);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function textContent(node) {
|
|
113
|
+
let text = '';
|
|
114
|
+
for (const child of node.childNodes ?? []) {
|
|
115
|
+
if (child.nodeName === '#text') text += child.value;
|
|
116
|
+
else text += textContent(child);
|
|
117
|
+
}
|
|
118
|
+
return text;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function attribute(node, name) {
|
|
122
|
+
return node.attrs?.find((entry) => entry.name === name)?.value ?? '';
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function hasAttribute(node, name) {
|
|
126
|
+
return Boolean(node.attrs?.some((entry) => entry.name === name));
|
|
127
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
const REACT = (container) =>
|
|
2
|
+
Object.keys(container).some(
|
|
3
|
+
(key) => key.startsWith('__reactContainer') || key === '_reactRootContainer',
|
|
4
|
+
);
|
|
5
|
+
const VUE = (container) =>
|
|
6
|
+
Boolean(
|
|
7
|
+
container.__vue_app__ ||
|
|
8
|
+
container.__vueParentComponent ||
|
|
9
|
+
container._vnode ||
|
|
10
|
+
container.__vue__,
|
|
11
|
+
);
|
|
12
|
+
const PREACT = (container) =>
|
|
13
|
+
Boolean(
|
|
14
|
+
container.__k ||
|
|
15
|
+
container._children ||
|
|
16
|
+
container.firstElementChild?.__k ||
|
|
17
|
+
container.firstElementChild?._children,
|
|
18
|
+
);
|
|
19
|
+
const SVELTE = (container) =>
|
|
20
|
+
Boolean(container.__svelte_meta || container.querySelector?.('[data-svelte-h]'));
|
|
21
|
+
|
|
22
|
+
const DETECTORS = { react: REACT, vue: VUE, preact: PREACT, svelte: SVELTE };
|
|
23
|
+
const AUTO_ORDER = ['react', 'vue', 'preact', 'svelte'];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Detects the framework that mounted into a container from its DOM markers. This is
|
|
27
|
+
* observation only: no framework is imported or executed by the prerenderer.
|
|
28
|
+
*/
|
|
29
|
+
export function detectFramework(container, requested = 'auto') {
|
|
30
|
+
if (!container) return { name: null, mounted: false };
|
|
31
|
+
if (requested !== 'auto') {
|
|
32
|
+
return { name: requested, mounted: Boolean(DETECTORS[requested]?.(container)) };
|
|
33
|
+
}
|
|
34
|
+
const markers = {
|
|
35
|
+
react: REACT(container),
|
|
36
|
+
vue: VUE(container),
|
|
37
|
+
preact: PREACT(container),
|
|
38
|
+
svelte: SVELTE(container),
|
|
39
|
+
};
|
|
40
|
+
return frameworkFromMarkers(markers, requested);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Selects a framework from a plain marker map produced inside the page, where DOM
|
|
45
|
+
* object identity is not available to Node.
|
|
46
|
+
*/
|
|
47
|
+
export function frameworkFromMarkers(markers, requested = 'auto') {
|
|
48
|
+
if (requested !== 'auto') {
|
|
49
|
+
return { name: requested, mounted: markers?.[requested] === true };
|
|
50
|
+
}
|
|
51
|
+
for (const name of AUTO_ORDER) {
|
|
52
|
+
if (markers?.[name] === true) return { name, mounted: true };
|
|
53
|
+
}
|
|
54
|
+
return { name: null, mounted: false };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const COMMON_PATTERNS = [
|
|
58
|
+
/react\.dev\/errors\/(418|419|421|422|423|424|425)/i,
|
|
59
|
+
/Minified React error #(418|419|421|422|423|424|425)\b/i,
|
|
60
|
+
];
|
|
61
|
+
|
|
62
|
+
const FRAMEWORK_PATTERNS = {
|
|
63
|
+
react: [
|
|
64
|
+
...COMMON_PATTERNS,
|
|
65
|
+
/hydrat/i,
|
|
66
|
+
/text content did not match/i,
|
|
67
|
+
/prop [`"].+?[`"] did not match/i,
|
|
68
|
+
/server-rendered HTML/i,
|
|
69
|
+
/did not expect server HTML/i,
|
|
70
|
+
/expected server HTML to contain/i,
|
|
71
|
+
],
|
|
72
|
+
preact: [
|
|
73
|
+
...COMMON_PATTERNS,
|
|
74
|
+
/hydrat/i,
|
|
75
|
+
/text content did not match/i,
|
|
76
|
+
/did not expect server HTML/i,
|
|
77
|
+
],
|
|
78
|
+
vue: [/hydration (?:node|text|children) mismatch/i, /hydration-mismatch/i, /hydrat/i],
|
|
79
|
+
svelte: [/hydration_mismatch/i, /hydration failed/i],
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Classifies a console or page error as a hydration failure for the detected framework.
|
|
84
|
+
* Patterns stay narrow so an unrelated application error is not treated as a build gate.
|
|
85
|
+
* With `auto`, every framework set is tried because the framework was not established.
|
|
86
|
+
*/
|
|
87
|
+
export function isHydrationError(message, framework = 'auto') {
|
|
88
|
+
const text = String(message);
|
|
89
|
+
const patterns =
|
|
90
|
+
framework === 'auto'
|
|
91
|
+
? Object.values(FRAMEWORK_PATTERNS).flat()
|
|
92
|
+
: [...(FRAMEWORK_PATTERNS[framework] ?? [])];
|
|
93
|
+
return patterns.some((pattern) => pattern.test(text));
|
|
94
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { parse } from 'parse5';
|
|
2
|
+
|
|
3
|
+
const CONTAINER_IDS = new Set(['root', 'app', '__next']);
|
|
4
|
+
const STABLE_ATTRIBUTES = ['id', 'class', 'href', 'src', 'type', 'role', 'name'];
|
|
5
|
+
const MAX_NODES = 5000;
|
|
6
|
+
const MAX_DEPTH = 20;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Finds the first meaningful difference between the prerendered document and the live
|
|
10
|
+
* post-boot container. Bounded so a large app cannot turn verification into a memory
|
|
11
|
+
* problem.
|
|
12
|
+
*/
|
|
13
|
+
export function compareContainers(expectedHtml, liveHtml) {
|
|
14
|
+
const expected = containerOf(parse(expectedHtml));
|
|
15
|
+
const actual = containerOf(parse(liveHtml));
|
|
16
|
+
if (!expected || !actual) return null;
|
|
17
|
+
const state = { visited: 0 };
|
|
18
|
+
return diffNode(expected, actual, 'body', 0, state);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Finds the app container in a parsed document, falling back to the body's first child.
|
|
22
|
+
function containerOf(document) {
|
|
23
|
+
const html = (document.childNodes ?? []).find((node) => node.tagName === 'html');
|
|
24
|
+
const body = (html?.childNodes ?? []).find((node) => node.tagName === 'body');
|
|
25
|
+
if (!body) return null;
|
|
26
|
+
const container = (body.childNodes ?? []).find(
|
|
27
|
+
(node) => node.tagName && CONTAINER_IDS.has(attribute(node, 'id')),
|
|
28
|
+
);
|
|
29
|
+
return container ?? (body.childNodes ?? []).find((node) => node.tagName) ?? null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Compares one node pair and descends into the first differing child.
|
|
33
|
+
function diffNode(expected, actual, path, depth, state) {
|
|
34
|
+
if (state.visited > MAX_NODES || depth > MAX_DEPTH) return null;
|
|
35
|
+
state.visited += 1;
|
|
36
|
+
const here = `${path}>${expected.tagName ?? expected.nodeName}`;
|
|
37
|
+
if (!actual || expected.tagName !== actual.tagName) {
|
|
38
|
+
return {
|
|
39
|
+
path,
|
|
40
|
+
kind: 'tag',
|
|
41
|
+
expected: expected.tagName ?? expected.nodeName,
|
|
42
|
+
actual: actual?.tagName ?? actual?.nodeName ?? null,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
for (const name of STABLE_ATTRIBUTES) {
|
|
46
|
+
const left = attribute(expected, name);
|
|
47
|
+
const right = attribute(actual, name);
|
|
48
|
+
if (left !== right)
|
|
49
|
+
return { path: here, kind: 'attribute', name, expected: left, actual: right };
|
|
50
|
+
}
|
|
51
|
+
const expectedChildren = elementChildren(expected);
|
|
52
|
+
const actualChildren = elementChildren(actual);
|
|
53
|
+
for (let index = 0; index < expectedChildren.length; index += 1) {
|
|
54
|
+
const child = expectedChildren[index];
|
|
55
|
+
const other = actualChildren[index];
|
|
56
|
+
if (!other) {
|
|
57
|
+
return {
|
|
58
|
+
path: here,
|
|
59
|
+
kind: 'missing',
|
|
60
|
+
expected: child.tagName ?? child.nodeName,
|
|
61
|
+
actual: null,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
const difference = diffNode(child, other, `${here}[${index}]`, depth + 1, state);
|
|
65
|
+
if (difference) return difference;
|
|
66
|
+
}
|
|
67
|
+
if (actualChildren.length > expectedChildren.length) {
|
|
68
|
+
const extra = actualChildren[expectedChildren.length];
|
|
69
|
+
return { path: here, kind: 'extra', expected: null, actual: extra.tagName ?? extra.nodeName };
|
|
70
|
+
}
|
|
71
|
+
const expectedText = directText(expected);
|
|
72
|
+
const actualText = directText(actual);
|
|
73
|
+
if (expectedText !== actualText) {
|
|
74
|
+
return { path: here, kind: 'text', expected: expectedText, actual: actualText };
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function elementChildren(node) {
|
|
80
|
+
return (node.childNodes ?? []).filter((child) => child.tagName);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function directText(node) {
|
|
84
|
+
return (node.childNodes ?? [])
|
|
85
|
+
.filter((child) => child.nodeName === '#text')
|
|
86
|
+
.map((child) => child.value)
|
|
87
|
+
.join('')
|
|
88
|
+
.trim();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function attribute(node, name) {
|
|
92
|
+
return node.attrs?.find((entry) => entry.name === name)?.value ?? '';
|
|
93
|
+
}
|