chahuadev-dev-launcher / scripts /build-v8-external.js
chahuadev's picture
fix: remove ineffective sandbox on home/support iframes (allow-scripts+allow-same-origin defeats sandbox per spec)
b92316a verified
'use strict'
const fs = require('fs')
const path = require('path')
const os = require('os')
const { spawn } = require('child_process')
const { createRequire } = require('module')
const FILES_TO_COMPILE = ['main.js']
const VENDORED_BYTENODE_DIR = '__launcher_bytenode__'
function normalizeExec(cmd) {
const c = String(cmd || '').trim()
if (process.platform !== 'win32') return c
const lc = c.toLowerCase()
if (lc === 'npm') return 'npm.cmd'
if (lc === 'npx') return 'npx.cmd'
return c
}
function quoteWindowsArg(arg) {
const s = String(arg || '')
if (!s) return '""'
if (!(/[\s"]/g).test(s)) return s
return `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, '$1$1')}"`
}
function buildWindowsCommandLine(cmd, args) {
return [cmd, ...(args || [])].map(quoteWindowsArg).join(' ')
}
function runCommand(cmd, args, cwd) {
return new Promise((resolve, reject) => {
const normalizedCmd = normalizeExec(cmd)
const normalizedArgs = (args || []).map(x => String(x || ''))
const isWindowsShellCommand = process.platform === 'win32' &&
(normalizedCmd.toLowerCase().endsWith('.cmd') || normalizedCmd.toLowerCase().endsWith('.bat'))
const spawnFile = isWindowsShellCommand
? (process.env.COMSPEC || 'cmd.exe')
: normalizedCmd
const spawnArgs = isWindowsShellCommand
? ['/d', '/s', '/c', buildWindowsCommandLine(normalizedCmd, normalizedArgs)]
: normalizedArgs
const child = spawn(spawnFile, spawnArgs, {
cwd,
stdio: 'inherit',
shell: false,
windowsHide: true,
env: {
...process.env
}
})
child.on('error', reject)
child.on('close', (code) => {
if ((code ?? 1) === 0) {
resolve()
} else {
reject(new Error(`${cmd} exited with code ${code}`))
}
})
})
}
function copyProject(source, target) {
fs.cpSync(source, target, {
recursive: true,
force: true,
filter: (src) => {
const rel = path.relative(source, src)
if (!rel) return true
const top = rel.split(path.sep)[0]
if (top === '.git' || top === 'node_modules' || top === 'dist' || top === '.next') return false
return true
}
})
}
function ensureBytenodeDependency(workDir) {
const pkgPath = path.join(workDir, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
const deps = {
...(pkg.dependencies || {})
}
const devDeps = {
...(pkg.devDependencies || {})
}
if (typeof deps.bytenode === 'string' || typeof devDeps.bytenode === 'string') {
return false
}
deps.bytenode = '^1.5.7'
pkg.dependencies = deps
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8')
console.log('[Launcher V8] Injected bytenode dependency in temp workspace')
return true
}
function vendorBytenodeRuntime(workDir) {
const bytenodePkgPath = path.join(workDir, 'node_modules', 'bytenode', 'package.json')
if (!fs.existsSync(bytenodePkgPath)) {
throw new Error(`bytenode package not found in temp workspace: ${bytenodePkgPath}`)
}
const bytenodeRoot = path.dirname(bytenodePkgPath)
const targetDir = path.join(workDir, VENDORED_BYTENODE_DIR)
fs.rmSync(targetDir, { recursive: true, force: true })
fs.cpSync(bytenodeRoot, targetDir, { recursive: true, force: true })
console.log(`[Launcher V8] Vendored bytenode runtime -> ${VENDORED_BYTENODE_DIR}`)
}
function ensureJscBuildConfig(workDir) {
const pkgPath = path.join(workDir, 'package.json')
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
const build = {
...(pkg.build || {})
}
const files = Array.isArray(build.files) ? [...build.files] : null
const asarUnpack = Array.isArray(build.asarUnpack) ? [...build.asarUnpack] : null
let changed = false
if (Array.isArray(files)) {
const mustInclude = ['*.jsc', `${VENDORED_BYTENODE_DIR}/**/*`]
for (const pattern of mustInclude) {
if (!files.includes(pattern)) {
files.push(pattern)
changed = true
}
}
build.files = files
}
if (Array.isArray(asarUnpack) && !asarUnpack.includes('*.jsc')) {
asarUnpack.unshift('*.jsc')
build.asarUnpack = asarUnpack
changed = true
}
if (changed) {
pkg.build = build
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n', 'utf8')
console.log('[Launcher V8] Updated build config to include *.jsc artifacts')
}
}
async function installDependencies(workDir) {
// Temp workspace mutates package.json (bytenode/build files), so npm ci can fail on lock mismatch.
await runCommand('npm', ['install'], workDir)
}
async function compileBytecode(workDir) {
const bytenodeEntry = path.join(workDir, 'node_modules', 'bytenode')
if (!fs.existsSync(bytenodeEntry)) {
throw new Error(`bytenode runtime missing in temp workspace: ${bytenodeEntry}`)
}
const requireFromWorkDir = createRequire(path.join(workDir, 'package.json'))
const bytenode = requireFromWorkDir('bytenode')
const compiled = []
for (const relFile of FILES_TO_COMPILE) {
const absPath = path.join(workDir, relFile)
if (!fs.existsSync(absPath)) continue
const parsed = path.parse(absPath)
const jscPath = path.join(parsed.dir, `${parsed.name}.jsc`)
await bytenode.compileFile({
filename: absPath,
output: jscPath,
electron: true,
compileAsModule: true
})
const loaderLine = relFile === 'main.js'
? `module.exports = require('./${parsed.name}.jsc')`
: `require('./${parsed.name}.jsc')`
const loaderCode = [
"'use strict'",
`require('./${VENDORED_BYTENODE_DIR}')`,
loaderLine,
''
].join('\n')
fs.writeFileSync(absPath, loaderCode, 'utf8')
compiled.push(relFile)
console.log(`[Launcher V8] Compiled ${relFile} -> ${path.basename(jscPath)}`)
}
if (!compiled.length) {
throw new Error('No compile targets found (main.js)')
}
}
async function runElectronBuilder(workDir) {
const extraBuilderArgs = process.argv.slice(3)
await runCommand('npx', [
'electron-builder',
'--win',
'portable',
'--x64',
'--config.compression=maximum',
'--config.npmRebuild=false',
...extraBuilderArgs
], workDir)
}
function copyDistArtifacts(workDir, targetProject) {
const srcDist = path.join(workDir, 'dist')
if (!fs.existsSync(srcDist)) {
throw new Error('dist folder not found after build')
}
const outDist = path.join(targetProject, 'dist')
fs.mkdirSync(outDist, { recursive: true })
fs.cpSync(srcDist, outDist, {
recursive: true,
force: true
})
}
async function main() {
const requestedTarget = String(process.argv[2] || '').trim()
const targetProject = path.resolve(requestedTarget || process.cwd())
const packageJsonPath = path.join(targetProject, 'package.json')
if (!fs.existsSync(packageJsonPath)) {
throw new Error(`package.json not found in ${targetProject}`)
}
const tempBase = fs.mkdtempSync(path.join(os.tmpdir(), 'chahuadev-v8-build-'))
const workDir = path.join(tempBase, 'project')
console.log('[Launcher V8] Preparing isolated build workspace...')
try {
copyProject(targetProject, workDir)
ensureBytenodeDependency(workDir)
ensureJscBuildConfig(workDir)
console.log('[Launcher V8] Installing dependencies...')
await installDependencies(workDir)
// Vendored runtime is bundled into final artifact for reliable loader resolution.
vendorBytenodeRuntime(workDir)
console.log('[Launcher V8] Compiling bytecode targets...')
await compileBytecode(workDir)
console.log('[Launcher V8] Running electron-builder...')
await runElectronBuilder(workDir)
console.log('[Launcher V8] Copying dist artifacts back to target project...')
copyDistArtifacts(workDir, targetProject)
console.log('[Launcher V8] Success')
} finally {
try {
fs.rmSync(tempBase, { recursive: true, force: true })
} catch {}
}
}
main().catch((err) => {
console.error(`[Launcher V8] Failed: ${err && err.message ? err.message : err}`)
process.exit(1)
})