|
| 1 | +/* eslint-disable no-console */ |
| 2 | +const fs = require('node:fs'); |
| 3 | +const path = require('node:path'); |
| 4 | +const { execFileSync } = require('node:child_process'); |
| 5 | + |
| 6 | +const CACHE_DIR = '/home/puppeteer-cache'; |
| 7 | +const LOCK_FILE = path.join(CACHE_DIR, 'install.lock'); |
| 8 | + |
| 9 | +function ensureChromeInstalled() { |
| 10 | + if (!fs.existsSync(CACHE_DIR)) { |
| 11 | + fs.mkdirSync(CACHE_DIR, { recursive: true }); |
| 12 | + } |
| 13 | + |
| 14 | + const chromeBase = path.join(CACHE_DIR, 'chrome'); |
| 15 | + |
| 16 | + let isInstalled = false; |
| 17 | + |
| 18 | + if (fs.existsSync(chromeBase)) { |
| 19 | + const folders = fs.readdirSync(chromeBase); |
| 20 | + isInstalled = folders.length > 0; |
| 21 | + } |
| 22 | + |
| 23 | + if (!isInstalled) { |
| 24 | + if (fs.existsSync(LOCK_FILE)) { |
| 25 | + console.log('Chrome installation already in progress...'); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + fs.writeFileSync(LOCK_FILE, 'installing'); |
| 30 | + |
| 31 | + try { |
| 32 | + console.log('Installing Chrome...'); |
| 33 | + execFileSync('npx', ['puppeteer', 'browsers', 'install', 'chrome'], { |
| 34 | + stdio: 'inherit', |
| 35 | + env: { |
| 36 | + ...process.env, |
| 37 | + PUPPETEER_CACHE_DIR: CACHE_DIR, |
| 38 | + }, |
| 39 | + }); |
| 40 | + console.log('Chrome installed'); |
| 41 | + } catch (err) { |
| 42 | + console.error('Chrome installation failed:', err); |
| 43 | + } finally { |
| 44 | + if (fs.existsSync(LOCK_FILE)) { |
| 45 | + fs.unlinkSync(LOCK_FILE); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +function getChromeExecutable() { |
| 52 | + ensureChromeInstalled(); |
| 53 | + |
| 54 | + const chromeBase = path.join(CACHE_DIR, 'chrome'); |
| 55 | + |
| 56 | + if (!fs.existsSync(chromeBase)) { |
| 57 | + throw new Error('Chrome base directory not found'); |
| 58 | + } |
| 59 | + |
| 60 | + const folders = fs.readdirSync(chromeBase); |
| 61 | + |
| 62 | + if (!folders.length) { |
| 63 | + throw new Error('No Chrome installation found'); |
| 64 | + } |
| 65 | + |
| 66 | + const latest = folders.sort().reverse()[0]; |
| 67 | + |
| 68 | + const chromePath = path.join(chromeBase, latest, 'chrome-linux64', 'chrome'); |
| 69 | + |
| 70 | + console.log('Using Chrome at:', chromePath); |
| 71 | + |
| 72 | + return chromePath; |
| 73 | +} |
| 74 | + |
| 75 | +module.exports = { getChromeExecutable }; |
0 commit comments