-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
198 lines (168 loc) · 5.63 KB
/
index.js
File metadata and controls
198 lines (168 loc) · 5.63 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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env node
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const https = require('https');
const readline = require('readline');
const colors = {
reset: '\x1b[0m',
info: '\x1b[38;2;120;220;255m',
warn: '\x1b[38;2;255;200;87m',
success: '\x1b[38;2;0;255;170m',
error: '\x1b[38;2;255;120;140m',
highlight: '\x1b[38;2;220;180;255m',
};
const tags = {
info: '[INFO]',
warn: '[WARN]',
success: '[DONE]',
error: '[FAIL]',
missing: '[MISSING]',
};
const pendingDownloads = new Set();
const logger = {
info(message) {
console.log(`${colors.info}${tags.info} ${message}${colors.reset}`);
},
warn(message) {
console.warn(`${colors.warn}${tags.warn} ${message}${colors.reset}`);
},
success(message) {
console.log(`${colors.success}${tags.success} ${message}${colors.reset}`);
},
error(message) {
console.error(`${colors.error}${tags.error} ${message}${colors.reset}`);
},
missing(file, url, destination) {
console.log(`${colors.highlight}${tags.missing} ${file}${colors.reset}`);
console.log(`${colors.info}Source URL: ${url}${colors.reset}`);
console.log(`${colors.info}Save To: ${destination}${colors.reset}`);
},
};
const promptArrow = '\x1b[38;2;0;200;255m\u2192\x1b[0m';
const promptLabel = '\x1b[37m';
const promptValue = '\x1b[38;2;0;255;255m';
const userInputReader = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let port = parseInt(process.argv[2] || '4000', 10);
if (isNaN(port) || port < 1 || port > 65535) {
logger.warn('Invalid port number. Using default port 4000');
port = 4000;
}
logger.info(`Local server running at http://127.0.0.1:${port}`);
function streamDownload(url, filePath) {
return new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream(filePath);
const request = https.get(url, (response) => {
if (response.statusCode !== 200) {
fs.unlink(filePath, () => {});
reject(new Error(`HTTP ${response.statusCode}`));
return;
}
response.pipe(fileStream);
});
fileStream.on('finish', () => {
fileStream.close(() => {
try {
const stats = fs.statSync(filePath);
if (stats.size === 0) {
fs.unlink(filePath, () => {});
reject(new Error('received empty file'));
} else {
resolve(stats.size);
}
} catch (err) {
reject(new Error(`stat error: ${err.message}`));
}
});
});
request.on('error', (err) => {
fs.unlink(filePath, () => {});
reject(new Error(`request error: ${err.message}`));
});
fileStream.on('error', (err) => {
fs.unlink(filePath, () => {});
reject(new Error(`file stream error: ${err.message}`));
});
});
}
async function downloadFileWithRetries(url, filePath, maxRetries = 3) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
if (fs.existsSync(filePath)) {
logger.info(`Skip download, file already exists → ${filePath}`);
return true;
}
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const fileSize = await streamDownload(url, filePath);
logger.success(`Downloaded ${filePath} (${fileSize} bytes)`);
return true;
} catch (error) {
if (attempt < maxRetries) {
logger.warn(`Retry ${attempt}/${maxRetries} → ${filePath}`);
} else {
logger.error(`Failed after ${maxRetries} retries → ${filePath}`);
}
}
}
return false;
}
userInputReader.question(
`${promptArrow}${promptLabel}请输入资源所在的根 URL: \x1b[0m`,
(baseUrl) => {
logger.info(`根 URL 已设置为: ${baseUrl}`);
userInputReader.close();
const divider = '─'.repeat(56);
const introLines = [
'监控已启动',
`下一步: 打开 http://127.0.0.1:${port}`,
`缺失的资源会自动从 ${baseUrl} 拉取`,
];
console.log();
logger.info(divider);
introLines.forEach((line) => logger.info(line));
logger.info(divider);
console.log();
const httpServerProcess = spawn('npx', ['http-server', '-p', String(port)]);
httpServerProcess.stdout.on('data', async (data) => {
const output = data.toString();
const missingFileRegex = /"GET (\/.*?)" Error \(404\):/g;
const matches = [...output.matchAll(missingFileRegex)];
if (matches.length === 0) {
return;
}
const ignoreList = ['/.well-known/appspecific/com.chrome.devtools.json'];
for (const match of matches) {
const encodedPath = match[1].replace(/"/g, '');
const decodedPath = decodeURIComponent(encodedPath);
if (ignoreList.includes(decodedPath)) {
continue;
}
const localFilePath = path.join(process.cwd(), decodedPath);
const remoteFileUrl = `${baseUrl}${encodedPath}`;
if (pendingDownloads.has(localFilePath)) {
logger.warn(`Skip duplicate request → ${decodedPath}`);
continue;
}
pendingDownloads.add(localFilePath);
logger.missing(decodedPath, remoteFileUrl, localFilePath);
try {
await downloadFileWithRetries(remoteFileUrl, localFilePath);
} finally {
pendingDownloads.delete(localFilePath);
}
}
});
httpServerProcess.stderr.on('data', (data) => {
logger.error(`http-server stderr: ${data.toString().trim()}`);
});
httpServerProcess.on('error', (err) => {
logger.error(`Unable to start http-server: ${err.message}`);
});
httpServerProcess.on('close', (code) => {
logger.info(`http-server process exited with code ${code}`);
});
},
);