on_Snapshot__24_responses.bg.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. #!/usr/bin/env node
  2. /**
  3. * Archive all network responses during page load.
  4. *
  5. * This hook sets up CDP listeners BEFORE chrome_navigate loads the page,
  6. * then waits for navigation to complete. The listeners capture all network
  7. * responses during the navigation.
  8. *
  9. * Usage: on_Snapshot__24_responses.js --url=<url> --snapshot-id=<uuid>
  10. * Output: Creates responses/ directory with index.jsonl
  11. */
  12. const fs = require('fs');
  13. const path = require('path');
  14. const crypto = require('crypto');
  15. // Add NODE_MODULES_DIR to module resolution paths if set
  16. if (process.env.NODE_MODULES_DIR) module.paths.unshift(process.env.NODE_MODULES_DIR);
  17. const puppeteer = require('puppeteer-core');
  18. // Import shared utilities from chrome_utils.js
  19. const {
  20. getEnv,
  21. getEnvBool,
  22. getEnvInt,
  23. parseArgs,
  24. connectToPage,
  25. waitForPageLoaded,
  26. } = require('../chrome/chrome_utils.js');
  27. const PLUGIN_NAME = 'responses';
  28. const OUTPUT_DIR = '.';
  29. const CHROME_SESSION_DIR = '../chrome';
  30. let browser = null;
  31. let page = null;
  32. let responseCount = 0;
  33. let shuttingDown = false;
  34. // Resource types to capture (by default, capture everything)
  35. const DEFAULT_TYPES = ['document', 'script', 'stylesheet', 'font', 'image', 'media', 'xhr', 'websocket'];
  36. function getExtensionFromMimeType(mimeType) {
  37. const mimeMap = {
  38. 'text/html': 'html',
  39. 'text/css': 'css',
  40. 'text/javascript': 'js',
  41. 'application/javascript': 'js',
  42. 'application/x-javascript': 'js',
  43. 'application/json': 'json',
  44. 'application/xml': 'xml',
  45. 'text/xml': 'xml',
  46. 'image/png': 'png',
  47. 'image/jpeg': 'jpg',
  48. 'image/gif': 'gif',
  49. 'image/svg+xml': 'svg',
  50. 'image/webp': 'webp',
  51. 'font/woff': 'woff',
  52. 'font/woff2': 'woff2',
  53. 'font/ttf': 'ttf',
  54. 'font/otf': 'otf',
  55. 'application/font-woff': 'woff',
  56. 'application/font-woff2': 'woff2',
  57. 'video/mp4': 'mp4',
  58. 'video/webm': 'webm',
  59. 'audio/mpeg': 'mp3',
  60. 'audio/ogg': 'ogg',
  61. };
  62. const mimeBase = (mimeType || '').split(';')[0].trim().toLowerCase();
  63. return mimeMap[mimeBase] || '';
  64. }
  65. function getExtensionFromUrl(url) {
  66. try {
  67. const pathname = new URL(url).pathname;
  68. const match = pathname.match(/\.([a-z0-9]+)$/i);
  69. return match ? match[1].toLowerCase() : '';
  70. } catch (e) {
  71. return '';
  72. }
  73. }
  74. function sanitizeFilename(str, maxLen = 200) {
  75. return str
  76. .replace(/[^a-zA-Z0-9._-]/g, '_')
  77. .slice(0, maxLen);
  78. }
  79. async function createSymlink(target, linkPath) {
  80. try {
  81. const dir = path.dirname(linkPath);
  82. if (!fs.existsSync(dir)) {
  83. fs.mkdirSync(dir, { recursive: true });
  84. }
  85. if (fs.existsSync(linkPath)) {
  86. fs.unlinkSync(linkPath);
  87. }
  88. const relativePath = path.relative(dir, target);
  89. fs.symlinkSync(relativePath, linkPath);
  90. } catch (e) {
  91. // Ignore symlink errors
  92. }
  93. }
  94. async function setupListener() {
  95. const timeout = getEnvInt('RESPONSES_TIMEOUT', 30) * 1000;
  96. const typesStr = getEnv('RESPONSES_TYPES', DEFAULT_TYPES.join(','));
  97. const typesToSave = typesStr.split(',').map(t => t.trim().toLowerCase());
  98. // Create subdirectories
  99. const allDir = path.join(OUTPUT_DIR, 'all');
  100. if (!fs.existsSync(allDir)) {
  101. fs.mkdirSync(allDir, { recursive: true });
  102. }
  103. const indexPath = path.join(OUTPUT_DIR, 'index.jsonl');
  104. fs.writeFileSync(indexPath, '');
  105. // Connect to Chrome page using shared utility
  106. const { browser, page } = await connectToPage({
  107. chromeSessionDir: CHROME_SESSION_DIR,
  108. timeoutMs: timeout,
  109. puppeteer,
  110. });
  111. // Set up response listener
  112. page.on('response', async (response) => {
  113. try {
  114. const request = response.request();
  115. const url = response.url();
  116. const resourceType = request.resourceType().toLowerCase();
  117. const method = request.method();
  118. const status = response.status();
  119. // Skip redirects and errors
  120. if (status >= 300 && status < 400) return;
  121. if (status >= 400 && status < 600) return;
  122. // Check if we should save this resource type
  123. if (typesToSave.length && !typesToSave.includes(resourceType)) {
  124. return;
  125. }
  126. // Get response body
  127. let bodyBuffer = null;
  128. try {
  129. bodyBuffer = await response.buffer();
  130. } catch (e) {
  131. return;
  132. }
  133. if (!bodyBuffer || bodyBuffer.length === 0) {
  134. return;
  135. }
  136. // Determine file extension
  137. const mimeType = response.headers()['content-type'] || '';
  138. let extension = getExtensionFromMimeType(mimeType) || getExtensionFromUrl(url);
  139. // Create timestamp-based unique filename
  140. const timestamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '');
  141. const urlHash = sanitizeFilename(encodeURIComponent(url).slice(0, 64));
  142. const uniqueFilename = `${timestamp}__${method}__${urlHash}${extension ? '.' + extension : ''}`;
  143. const uniquePath = path.join(allDir, uniqueFilename);
  144. // Save to unique file
  145. fs.writeFileSync(uniquePath, bodyBuffer);
  146. // Create URL-organized symlink
  147. try {
  148. const urlObj = new URL(url);
  149. const hostname = urlObj.hostname;
  150. const pathname = urlObj.pathname || '/';
  151. const filename = path.basename(pathname) || 'index' + (extension ? '.' + extension : '');
  152. const dirPathRaw = path.dirname(pathname);
  153. const dirPath = dirPathRaw === '.' ? '' : dirPathRaw.replace(/^\/+/, '');
  154. const symlinkDir = path.join(OUTPUT_DIR, resourceType, hostname, dirPath);
  155. const symlinkPath = path.join(symlinkDir, filename);
  156. await createSymlink(uniquePath, symlinkPath);
  157. // Also create a site-style symlink without resource type for easy browsing
  158. const siteDir = path.join(OUTPUT_DIR, hostname, dirPath);
  159. const sitePath = path.join(siteDir, filename);
  160. await createSymlink(uniquePath, sitePath);
  161. } catch (e) {
  162. // URL parsing or symlink creation failed, skip
  163. }
  164. // Calculate SHA256
  165. const sha256 = crypto.createHash('sha256').update(bodyBuffer).digest('hex');
  166. const urlSha256 = crypto.createHash('sha256').update(url).digest('hex');
  167. // Write to index
  168. const indexEntry = {
  169. ts: timestamp,
  170. method,
  171. url: method === 'DATA' ? url.slice(0, 128) : url,
  172. urlSha256,
  173. status,
  174. resourceType,
  175. mimeType: mimeType.split(';')[0],
  176. responseSha256: sha256,
  177. path: './' + path.relative(OUTPUT_DIR, uniquePath),
  178. extension,
  179. };
  180. fs.appendFileSync(indexPath, JSON.stringify(indexEntry) + '\n');
  181. responseCount += 1;
  182. } catch (e) {
  183. // Ignore errors
  184. }
  185. });
  186. return { browser, page };
  187. }
  188. function emitResult(status = 'succeeded') {
  189. if (shuttingDown) return;
  190. shuttingDown = true;
  191. const outputStr = responseCount > 0
  192. ? `responses/ (${responseCount} responses)`
  193. : 'responses/';
  194. console.log(JSON.stringify({
  195. type: 'ArchiveResult',
  196. status,
  197. output_str: outputStr,
  198. }));
  199. }
  200. async function handleShutdown(signal) {
  201. console.error(`\nReceived ${signal}, emitting final results...`);
  202. emitResult('succeeded');
  203. if (browser) {
  204. try {
  205. browser.disconnect();
  206. } catch (e) {}
  207. }
  208. process.exit(0);
  209. }
  210. async function main() {
  211. const args = parseArgs();
  212. const url = args.url;
  213. const snapshotId = args.snapshot_id;
  214. if (!url || !snapshotId) {
  215. console.error('Usage: on_Snapshot__24_responses.js --url=<url> --snapshot-id=<uuid>');
  216. process.exit(1);
  217. }
  218. if (!getEnvBool('RESPONSES_ENABLED', true)) {
  219. console.error('Skipping (RESPONSES_ENABLED=False)');
  220. console.log(JSON.stringify({type: 'ArchiveResult', status: 'skipped', output_str: 'RESPONSES_ENABLED=False'}));
  221. process.exit(0);
  222. }
  223. try {
  224. // Set up listener BEFORE navigation
  225. const connection = await setupListener();
  226. browser = connection.browser;
  227. page = connection.page;
  228. // Register signal handlers for graceful shutdown
  229. process.on('SIGTERM', () => handleShutdown('SIGTERM'));
  230. process.on('SIGINT', () => handleShutdown('SIGINT'));
  231. // Wait for chrome_navigate to complete (non-fatal)
  232. try {
  233. const timeout = getEnvInt('RESPONSES_TIMEOUT', 30) * 1000;
  234. await waitForPageLoaded(CHROME_SESSION_DIR, timeout * 4, 1000);
  235. } catch (e) {
  236. console.error(`WARN: ${e.message}`);
  237. }
  238. // console.error('Responses listener active, waiting for cleanup signal...');
  239. await new Promise(() => {}); // Keep alive until SIGTERM
  240. return;
  241. } catch (e) {
  242. const error = `${e.name}: ${e.message}`;
  243. console.error(`ERROR: ${error}`);
  244. console.log(JSON.stringify({
  245. type: 'ArchiveResult',
  246. status: 'failed',
  247. output_str: error,
  248. }));
  249. process.exit(1);
  250. }
  251. }
  252. main().catch(e => {
  253. console.error(`Fatal error: ${e.message}`);
  254. process.exit(1);
  255. });