-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
182 lines (159 loc) · 5.78 KB
/
server.js
File metadata and controls
182 lines (159 loc) · 5.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import prerender from 'prerender';
import memoryCache from 'prerender-memory-cache';
const server = prerender({
chromeLocation: '/usr/bin/chromium',
chromeFlags: [
'--no-sandbox',
'--headless=new',
'--disable-gpu',
'--remote-debugging-port=9222',
'--hide-scrollbars',
'--disable-dev-shm-usage',
'--ignore-certificate-errors',
'--allow-insecure-localhost',
'--disable-background-networking',
'--disable-default-apps',
'--disable-extensions',
'--disable-sync',
'--disable-translate',
'--disable-software-rasterizer',
'--metrics-recording-only',
'--no-first-run',
'--safebrowsing-disable-auto-update'
],
pageLoadTimeout: 20000,
waitAfterLastRequest: 1500,
pageDoneCheckInterval: 300,
chromeRefreshRate: 100
});
process.env.CACHE_MAXSIZE = process.env.CACHE_MAXSIZE || 1000;
process.env.CACHE_TTL = process.env.CACHE_TTL || 43200;
// Block requests that typically hang and prevent page from finishing
const BLOCKED_PATTERNS = [
/google-analytics\.com/,
/googletagmanager\.com/,
/facebook\.net/,
/facebook\.com\/tr/,
/hotjar\.com/,
/intercom\.io/,
/crisp\.chat/,
/sentry\.io/,
/segment\.com/,
/mixpanel\.com/,
/amplitude\.com/,
/clarity\.ms/,
/doubleclick\.net/,
/\.woff2?(\?|$)/,
/\.ttf(\?|$)/,
/fonts\.googleapis\.com/,
/fonts\.gstatic\.com/,
/ws:\/\//,
/wss:\/\//,
/\/socket\.io\//,
/\/sockjs-node\//,
/\/hub\?/,
/eventsource/i,
/livereload/,
];
// Patterns for requests that should be ignored in requestsInFlight count
// (they bypass Fetch interception and hang forever)
const IGNORE_INFLIGHT_PATTERNS = [
/^blob:/,
/^data:/,
];
server.use({
tabCreated: (req, res, next) => {
const tab = req.prerender.tab;
if (tab) {
tab.Console.enable();
tab.Network.enable();
const pendingRequests = new Map();
// Use Fetch domain to block unwanted network requests
tab.Fetch.enable({ patterns: [{ requestStage: 'Request' }] });
tab.Fetch.requestPaused((params) => {
const url = params.request.url;
const blocked = BLOCKED_PATTERNS.some(p => p.test(url));
if (blocked) {
console.log('🚫 Blocked:', url);
tab.Fetch.failRequest({
requestId: params.requestId,
errorReason: 'Aborted'
});
} else {
tab.Fetch.continueRequest({ requestId: params.requestId });
}
});
tab.Network.requestWillBeSent((params) => {
const url = params.request.url;
// blob: URLs bypass Fetch interception and hang forever.
// Prerender already incremented numRequestsInFlight before our handler,
// so we decrement it back and skip tracking.
if (IGNORE_INFLIGHT_PATTERNS.some(p => p.test(url))) {
tab.prerender.numRequestsInFlight--;
console.log('⏭️ Ignored from inflight:', url);
return;
}
pendingRequests.set(params.requestId, { url, time: Date.now() });
});
tab.Network.loadingFinished((params) => {
pendingRequests.delete(params.requestId);
});
tab.Network.loadingFailed((params) => {
const info = pendingRequests.get(params.requestId);
if (info) {
console.log('🔴 Network Failed:', params.errorText, info.url);
pendingRequests.delete(params.requestId);
}
});
tab.Console.messageAdded((params) => {
console.log('🟡 Browser log:', params.message.text);
});
tab.Runtime.enable();
tab.Runtime.exceptionThrown((exception) => {
console.log('💥 JS Exception:', exception.exceptionDetails.text);
});
const intervalStart = Date.now();
const interval = setInterval(() => {
// Safety: kill interval after 30s max to prevent leaks
if (Date.now() - intervalStart > 20000 || pendingRequests.size === 0) {
clearInterval(interval);
return;
}
const now = Date.now();
console.log(`⏳ Pending requests (${pendingRequests.size}), inflight=${tab.prerender.numRequestsInFlight}:`);
pendingRequests.forEach(({ url, time }) => {
console.log(` - ${((now - time) / 1000).toFixed(1)}s ${url}`);
});
}, 3000);
}
next();
}
});
server.use({
beforeSend: (req, res, next) => {
if (req.prerender.res) {
const body = req.prerender.res.body || '';
req.prerender.res.headers = {
'content-type': 'text/html; charset=utf-8',
'content-length': Buffer.byteLength(body, 'utf8'),
};
}
next();
}
});
server.use(prerender.removeScriptTags());
server.use(memoryCache);
const RESTART_INTERVAL = 24 * 60 * 60 * 1000;
const startedAt = Date.now();
setTimeout(() => {
console.log('♻️ Scheduled restart after 24 hours');
process.exit(0);
}, RESTART_INTERVAL);
setInterval(() => {
const remaining = RESTART_INTERVAL - (Date.now() - startedAt);
const hours = Math.floor(remaining / 3600000);
const minutes = Math.floor((remaining % 3600000) / 60000);
console.log(`🕐 Restart in ${hours}h ${minutes}m`);
}, 60 * 60 * 1000);
console.log('Prerender on Node 24 is starting...');
server.start();