fix: remove ineffective sandbox on home/support iframes (allow-scripts+allow-same-origin defeats sandbox per spec)
Browse filesCommits on Mar 25, 2026
fix: remove ineffective sandbox on home/support iframes (allow-scripts+allow-same-origin defeats sandbox per spec)
author
chahuadev1-byte
committed
19 minutes ago
·
fix: resolve all 24 silent errors (zombie listeners, empty catches, naked JSON.parse, floating promises, orphaned timer, await-in-loop, scope shadowing)
author
chahuadev1-byte
committed
25 minutes ago
·
fix: npmRebuild true + install-app-deps on linux build to fix node-pty ABI mismatch in AppImage
author
chahuadev1-byte
committed
38 minutes ago
·
feat: OS badge in header + dynamic mount protection (Linux /proc/mounts, macOS /Volumes)
author
chahuadev1-byte
committed
47 minutes ago
·
feat: separate platform runtime modules (win32/linux/darwin) + fix asarUnpack for node-pty
author
chahuadev1-byte
committed
1 hour ago
·
fix: sandbox terminal output, scopedBridge detection, output drain delay
author
chahuadev1-byte
committed
1 hour ago
·
Commits on Mar 24, 2026
feat: overhaul launcher runtime, popup terminals, and centralized build rewrites
author
chahuadev1-byte
committed
yesterday
chore: update support link allowlist and project metadata
author
chahuadev1-byte
committed
yesterday
feat: add support-the-project pages and support integration
author
chahuadev1-byte
committed
yesterday
Commits on Mar 23, 2026
chore: sync pending local changes
author
chahuadev1-byte
committed
2 days ago
Commits on Mar 22, 2026
first commit
chahuadev1
chahuadev1
committed
3 days ago
first commit
saharuthc-art
saharuthc-art
committed
3 days ago
Files changed (27)
- .gitattributes+1-1
- .gitignore+1-1
- README.md+1-1
- build-linux-wsl.sh+4-38
- index.html+11-83
- main.js+1076-417
- npm-runner.bat+2-2
- package.json+12-6
- packages/@chahuadev/dev-launcher/README.md+246-232
- packages/@chahuadev/dev-launcher/install.js+8-3
- packages/@chahuadev/dev-launcher/package.json+1-1
- packages/@chahuadev/dev-launcher/web/support-the-project.htmlAdded+365
- popup-preload.jsAdded+59
- preload.js+22-6
- runtime/platform-darwin.jsAdded+115
- runtime/platform-linux.jsAdded+128
- runtime/platform-win32.jsAdded+157
- runtime/platform.jsAdded+25
- scripts/before-pack-obfuscate.js+4-3
- scripts/build-v8-bytecode.js+13-124
- scripts/build-v8-external.jsAdded+265
- web/popup-terminal.cssAdded+162
- web/popup-terminal.htmlAdded+44
- web/popup-terminal.jsAdded+196
- web/r2-modal.js+2-1
- web/renderer.js+280-80
- web/styles.css+50
76 unmodified lines7778798076 unmodified linesengines/cs_scanner/bin/engines/cs_scanner/obj/*.pydicons/76 unmodified lines7778798076 unmodified linesengines/cs_scanner/bin/engines/cs_scanner/obj/*.pydicons/icons/icon.png filter=lfs diff=lfs merge=lfs -text
76 unmodified lines777879808176 unmodified linesengines/cs_scanner/bin/engines/cs_scanner/obj/*.pydicons/dev-launcher.exe76 unmodified lines777879808176 unmodified linesengines/cs_scanner/bin/engines/cs_scanner/obj/*.pyd/iconsdev-launcher.exe
45 unmodified lines4647484950515245 unmodified lines## Repository layout- `main.js`, `preload.js`, `index.html`, `web/`: Electron runtime + UI- `build-desktop.bat`, `build-linux-wsl.sh`: local build scripts- `dist/`: desktop build outputs- `packages/`: npm publish package workspace45 unmodified lines4647484950515245 unmodified lines## Repository layout- `main.js`, `preload.js`, `index.html`, `web/`: Electron runtime + UI- `build-desktop.bat`: local desktop build script (`build:linux` and `build:linux:wsl` are launcher-managed at runtime)- `dist/`: desktop build outputs- `packages/`: npm publish package workspace
28 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686921 unmodified lines91929394959697989928 unmodified lines}trap cleanup EXITretry_npm_install() {local max_try=3local n=1while [ "$n" -le "$max_try" ]; doecho " Attempt $n/$max_try ..."npm config set fetch-retries 5 >/dev/null 2>&1 || truenpm config set fetch-retry-factor 2 >/dev/null 2>&1 || truenpm config set fetch-retry-mintimeout 10000 >/dev/null 2>&1 || truenpm config set fetch-retry-maxtimeout 120000 >/dev/null 2>&1 || trueif [ -f package-lock.json ]; thenif npm ci; thenreturn 0fiecho " npm ci failed, trying npm install fallback..."if npm install; thenreturn 0fielseif npm install; thenreturn 0fifin=$((n + 1))if [ "$n" -le "$max_try" ]; thenecho " Network or registry error. Retrying in 8s..."sleep 8fidonereturn 1}echo "========================================================"echo "$APP_NAME - Linux Build on WSL (Native FS)"echo "========================================================"21 unmodified linesechoecho "[3/5] Installing dependencies..."cd "$WORK_DIR"if ! retry_npm_install; thenecho "ERROR: dependency install failed after retries"exit 1fiecho " OK - Dependencies installed"28 unmodified lines29303132333421 unmodified lines5657585960616263646528 unmodified lines}trap cleanup EXITecho "========================================================"echo "$APP_NAME - Linux Build on WSL (Native FS)"echo "========================================================"21 unmodified linesechoecho "[3/5] Installing dependencies..."cd "$WORK_DIR"if [ -f package-lock.json ]; thennpm cielsenpm installfiecho " OK - Dependencies installed"
31 unmodified lines323334353637383940415 unmodified lines474849505152532 unmodified lines56575859606121 unmodified lines838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117231 unmodified lines<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Run</button><button class="nav-tab" id="tab-r2"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l8 4v6c0 5-3.4 9.7-8 11-4.6-1.3-8-6-8-11V7l8-4z"/></svg>R2</button><button class="nav-tab" id="support-btn" title="Support the Project"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z"/></svg>Support the Project5 unmodified lines<!-- HOME PAGE (iframe) --><div class="page active" id="page-home"><iframe id="home-iframe" src="./web/home.html" sandbox="allow-scripts allow-same-origin" title="Home"></iframe></div><!-- RUN PAGE -->2 unmodified lines<!-- MAIN --><div id="main"><div id="cmd-panel"><div id="cmd-scroll"><div id="cmd-groups"></div></div>21 unmodified lines</div><!-- /page-run --><!-- R2 PAGE --><div class="page" id="page-r2"><iframe id="r2-iframe" src="./web/r2.html" sandbox="allow-scripts allow-same-origin" title="R2"></iframe></div><!-- SUPPORT PAGE --><div class="page" id="page-support"><iframe id="support-iframe" src="./web/support-the-project.html" sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox" title="Support the Project"></iframe></div></div><!-- /content-wrap --><div class="modal-backdrop" id="r2-config-backdrop"><div class="modal"><div class="modal-head"><div class="modal-title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3l8 4v6c0 5-3.4 9.7-8 11-4.6-1.3-8-6-8-11V7l8-4z"/></svg>R2 Configuration</div><button class="modal-close" id="btn-r2-config-close" aria-label="Close">×</button></div><div class="modal-body"><div class="modal-note">Credentials are saved in the local app profile for this machine.</div><div class="modal-field"><label class="modal-label">R2_ACCOUNT_ID</label><input class="modal-input" id="r2-account-id" type="text" autocomplete="off" spellcheck="false" /><div class="modal-hint" id="r2-account-hint"></div></div><div class="modal-field"><label class="modal-label">R2_BUCKET</label><input class="modal-input" id="r2-bucket" type="text" autocomplete="off" spellcheck="false" /><div class="modal-hint" id="r2-bucket-hint"></div></div><div class="modal-field"><label class="modal-label">R2_ACCESS_KEY_ID</label><input class="modal-input" id="r2-access-key" type="text" autocomplete="off" spellcheck="false" /><div class="modal-hint" id="r2-access-hint"></div></div><div class="modal-field"><label class="modal-label">R2_SECRET_ACCESS_KEY</label><input class="modal-input" id="r2-secret-key" type="password" autocomplete="off" spellcheck="false" /><div class="modal-hint">Enter full secret key to update.</div></div><div class="modal-status" id="r2-config-status"></div><div class="modal-foot"><button class="modal-btn danger" id="btn-r2-config-clear">Clear Saved</button><button class="modal-btn" id="btn-r2-config-cancel">Cancel</button><button class="modal-btn primary" id="btn-r2-config-save">Save</button></div></div></div></div><div class="modal-backdrop" id="r2-upload-backdrop"><div class="modal"><div class="modal-head"><div class="modal-title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>Upload Dist to R2</div><button class="modal-close" id="btn-r2-upload-close" aria-label="Close">×</button></div><div class="modal-body"><div class="modal-note" id="r2-upload-note"></div><div class="modal-field"><label class="modal-label">Target folder</label><input class="modal-input" id="r2-target-folder" type="text" autocomplete="off" spellcheck="false" /></div><div class="modal-hint">Choose from existing folders or type a new one.</div><div class="target-list" id="r2-target-list"></div><div class="modal-status" id="r2-upload-status"></div><div class="modal-foot"><button class="modal-btn" id="btn-r2-upload-cancel">Cancel</button><button class="modal-btn primary" id="btn-r2-upload-run">Start Upload</button></div></div></div></div><div class="modal-backdrop" id="security-block-backdrop"><div class="security-modal" role="dialog" aria-modal="true" aria-labelledby="security-block-title"><div class="security-modal-head">31 unmodified lines3233343536375 unmodified lines434445464748492 unmodified lines52535455565758596061626364656621 unmodified lines88899091929394959697989910031 unmodified lines<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>Run</button><button class="nav-tab" id="support-btn" title="Support the Project"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78L12 21.23l8.84-8.84a5.5 5.5 0 0 0 0-7.78z"/></svg>Support the Project5 unmodified lines<!-- HOME PAGE (iframe) --><div class="page active" id="page-home"><iframe id="home-iframe" src="./web/home.html" title="Home"></iframe></div><!-- RUN PAGE -->2 unmodified lines<!-- MAIN --><div id="main"><div id="cmd-panel"><div id="dev-quick-panel"><div id="dev-quick-title">DEV Tools</div><div id="dev-quick-actions"><button id="btn-dev-main-tools" class="dev-quick-btn" type="button">Main DevTools</button><button id="btn-dev-popup-tools" class="dev-quick-btn" type="button">Popup DevTools</button><button id="btn-dev-security-status" class="dev-quick-btn" type="button">Security Status</button></div><div id="dev-quick-note">Debug shortcuts and security diagnostics</div></div><div id="cmd-scroll"><div id="cmd-groups"></div></div>21 unmodified lines</div><!-- /page-run --><!-- SUPPORT PAGE --><div class="page" id="page-support"><iframe id="support-iframe" src="./web/support-the-project.html" allow="clipboard-read; clipboard-write" title="Support the Project"></iframe></div></div><!-- /content-wrap --><div class="modal-backdrop" id="security-block-backdrop"><div class="security-modal" role="dialog" aria-modal="true" aria-labelledby="security-block-title"><div class="security-modal-head">
1234567891016 unmodified lines2728293031323334353637383940414225 unmodified lines68697071727321 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314482 unmodified lines22722822923023123223318 unmodified lines25225325425525625725825926026126226326414 unmodified lines27928028128228328414 unmodified lines299300301302303304305306307308309310311312313314315316317318319124 unmodified lines4444454464474484494504514524534544554564574584594 unmodified lines4644654664674684694704714722 unmodified lines4754764774784794802 unmodified lines48348448548648748848910 unmodified lines50050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953072 unmodified lines603604605606607608609185 unmodified lines79579679779879980040 unmodified lines84184284384484584684784856 unmodified lines9059069079089099109119 unmodified lines9219229239249259269279289299 unmodified lines939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105122 unmodified lines1074107510761077107810796 unmodified lines1086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344'use strict'const { app, BrowserWindow, ipcMain, shell, dialog, safeStorage, session, Menu, Tray } = require('electron')const path = require('path')const fs = require('fs')const os = require('os')const { spawn, spawnSync } = require('child_process')let ptyModule = nullfunction getPtyModule() {16 unmodified lines}function configureRuntimeWritablePaths() {const candidates = []if (process.platform === 'win32') {const localAppData = process.env.LOCALAPPDATAif (localAppData) {candidates.push(path.join(localAppData, 'Chahuadev', 'Dev-Launcher'))}}candidates.push(path.join(os.tmpdir(), 'chahuadev-dev-launcher'))for (const basePath of candidates) {if (!isWritableDirectory(basePath)) continue25 unmodified lineslet tray = nulllet currentProc = nulllet currentProcKind = nullconst secureConfigPath = path.join(app.getPath('userData'), 'secure-r2-config.json')const auditLogPath = path.join(app.getPath('userData'), 'audit.log')const isDev = !app.isPackaged21 unmodified linesfunction getRestrictedPathReason(targetPath) {const resolved = path.resolve(String(targetPath || ''))const homeDir = path.resolve(os.homedir())if (process.platform === 'win32') {const systemDrive = String(process.env.SystemDrive || 'C:').toUpperCase()const driveRoot = `${systemDrive}\\`const protectedBases = [path.join(driveRoot, 'Windows'),path.join(driveRoot, 'Program Files'),path.join(driveRoot, 'Program Files (x86)'),path.join(driveRoot, 'ProgramData'),path.join(driveRoot, 'Users'),path.join(driveRoot, 'PerfLogs'),path.join(driveRoot, 'Recovery'),path.join(driveRoot, 'System Volume Information'),path.join(driveRoot, '$Recycle.Bin'),path.join(homeDir, 'AppData'),path.join(homeDir, 'Local Settings')]for (const p of protectedBases) {if (isPathUnder(resolved, p)) {return `Selection is blocked because the folder is inside a protected OS location: ${p}`}}return null}if (process.platform === 'darwin') {const protectedBases = ['/System', '/Library', '/Applications', '/private', '/usr', '/bin', '/sbin', '/var', '/etc', '/opt',path.join(homeDir, 'Library')]for (const p of protectedBases) {if (isPathUnder(resolved, p)) {return `Selection is blocked because the folder is inside a protected OS location: ${p}`}}return null}const protectedBases = ['/bin', '/sbin', '/lib', '/lib64', '/usr', '/var', '/etc', '/boot', '/proc', '/sys', '/dev', '/run', '/snap']for (const p of protectedBases) {if (isPathUnder(resolved, p)) {return `Selection is blocked because the folder is inside a protected OS location: ${p}`}}return null82 unmodified linescontextIsolation: true,nodeIntegration: false,sandbox: false,devTools: isDev},title: 'Dev Launcher',show: false18 unmodified linesif (!isDev) {// Block common DevTools shortcuts in production builds.win.webContents.on('before-input-event', (event, input) => {const key = String(input.key || '').toLowerCase()const openDevTools =key === 'f12' ||((input.control || input.meta) && input.shift && (key === 'i' || key === 'j' || key === 'c'))if (openDevTools) event.preventDefault()})}win.once('ready-to-show', () => {14 unmodified lineswin.hide()}})}function createTray() {14 unmodified lines{label: 'Quit',click: () => {tray.destroy()tray = nullkillCurrentProc()app.quit()}}])tray.setContextMenu(ctxMenu)tray.on('double-click', () => {if (win && !win.isDestroyed()) {win.show()win.focus()}})}async function chooseExternalProjectFolder(mode = 'full-project') {124 unmodified linessetTimeout(() => {if (!tray) createTray()}, 300)})app.on('window-all-closed', () => {// ถ้ายังมี tray อยู่ ให้แอปทำงานต่อใน backgroundif (!tray) {killCurrentProc()app.quit()}})function killCurrentProc() {if (!currentProc) returntry {4 unmodified linesif (currentProc && currentProc.pid) {spawn('taskkill', ['/pid', String(currentProc.pid), '/f', '/t'], { shell: false, windowsHide: true })}} catch {}currentProc = nullcurrentProcKind = null}function sendToRenderer(channel, data) {2 unmodified lines}}function writeAudit(event, meta = {}) {try {const safeMeta = { ...meta }2 unmodified linesdelete safeMeta.accountIdconst line = `${new Date().toISOString()} ${event} ${JSON.stringify(safeMeta)}\n`fs.appendFileSync(auditLogPath, line, 'utf8')} catch {}}function sanitizeExternalUrl(input) {10 unmodified lines}function normalizeExecName(cmd) {let c = String(cmd || '').trim()if (!c) return cif (process.platform !== 'win32') return cconst lc = c.toLowerCase()if (lc === 'npm') return 'npm.cmd'if (lc === 'npx') return 'npx.cmd'if (lc === 'pnpm') return 'pnpm.cmd'if (lc === 'yarn') return 'yarn.cmd'return c}function shouldUseShellForCommand(cmd) {const c = String(cmd || '').toLowerCase()return c.endsWith('.bat') || c.endsWith('.cmd')}function quoteWindowsArg(arg) {const s = String(arg || '')if (!s) return '""'if (!/[\s"]/g.test(s)) return sreturn `"${s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, '$1$1')}"`}function buildWindowsCommandLine(cmd, args) {return [cmd, ...(args || [])].map(quoteWindowsArg).join(' ')}function commandKey(cmd, args, cwd) {72 unmodified linesfunction loadSecureConfigRaw() {if (!fs.existsSync(secureConfigPath)) return nullreturn JSON.parse(fs.readFileSync(secureConfigPath, 'utf-8'))}function loadSecureR2Config() {185 unmodified linesreturn { type: primaryType, label, badgeClass }}function buildGroups(pkg, root, hasAndroid) {const d = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies }const has = (name) => !!d[name]40 unmodified lines// ── Electron ─────────────────────────────────────────────────────────────────const usedScripts = new Set()if (isElectron) {const buildKeys = ['build','build-win','build-exe','build-v8','build-nsis','build-msi','build:linux','build:linux:wsl','pack','dist']const foundKeys = buildKeys.filter(s => (pkg.scripts || {})[s])foundKeys.forEach(s => usedScripts.add(s))if (foundKeys.length) {groups.push({56 unmodified lines// ── IPC: get project info (returns processed data only — no raw pkg exposed) ──ipcMain.handle('get-project', () => {const root = getEffectiveProjectRoot()const pkgPath = path.join(root, 'package.json')try {const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))9 unmodified linestypeInfo, // { type, label, badgeClass }groups, // ready-to-render — no raw pkg sent to rendererisDev, // true only when running via bat/cmd (not packaged)}} catch (e) {return { ok: false, error: e.message, projectRoot: root }}})9 unmodified linesipcMain.handle('run-cmd', (event, { cmd, args, cwd, streamMode, cols, rows }) => {killCurrentProc()const normalizedCmd = normalizeExecName(cmd)const normalizedArgs = (args || []).map(x => String(x || ''))const effectiveRoot = getEffectiveProjectRoot()const normalizedCwd = path.resolve(String(cwd || effectiveRoot))const allowed = buildAllowedCommandSet(effectiveRoot)const directKey = commandKey(cmd, normalizedArgs, normalizedCwd)const normalizedKey = commandKey(normalizedCmd, normalizedArgs, normalizedCwd)if (!allowed.has(directKey) && !allowed.has(normalizedKey)) {const msg = `Command is not allowlisted: ${String(cmd || '')} ${(normalizedArgs || []).join(' ')}`writeAudit('blocked_command', { cmd: String(cmd || ''), args: normalizedArgs, cwd: normalizedCwd })sendToRenderer('proc-out', `\n[ERROR] ${msg}\n`)sendToRenderer('proc-done', 1)return { ok: false, error: msg }}const useShell = shouldUseShellForCommand(normalizedCmd)writeAudit('run_command', { cmd: normalizedCmd, args: normalizedArgs, cwd: normalizedCwd, shell: useShell })let ptyFile = normalizedCmdlet ptyArgs = normalizedArgsif (process.platform === 'win32' && useShell) {const comspec = process.env.COMSPEC || 'cmd.exe'ptyFile = comspecptyArgs = ['/d', '/s', '/c', buildWindowsCommandLine(normalizedCmd, normalizedArgs)]}let procconst ptyCols = Number.isFinite(Number(cols)) ? Math.max(20, Math.floor(Number(cols))) : 120const ptyRows = Number.isFinite(Number(rows)) ? Math.max(5, Math.floor(Number(rows))) : 30const procEnv = {...process.env,FORCE_COLOR: '1',CLICOLOR: '1',CLICOLOR_FORCE: '1',COLORTERM: 'truecolor',TERM: 'xterm-256color',npm_config_color: 'always',}try {const pty = getPtyModule()proc = pty.spawn(ptyFile, ptyArgs, {cwd: normalizedCwd,env: procEnv,cols: ptyCols,rows: ptyRows,name: 'xterm-256color',useConpty: true})} catch (err) {const message = err && err.message ? err.message : String(err || 'Unknown PTY error')sendToRenderer('proc-out', `\n[ERROR] Failed to start PTY: ${message}\n`)sendToRenderer('proc-done', 1)writeAudit('run_command_error', { cmd: normalizedCmd, cwd: normalizedCwd, error: message })return { ok: false, error: message }}currentProc = proccurrentProcKind = 'pty'const normalizedStreamMode = String(streamMode || 'realtime').toLowerCase() === 'stable'? 'stable': 'realtime'const stableFlushMs = 30function streamOutput(chunk) {const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')if (!text) returnsendToRenderer('proc-out', text)}let outputBuffer = ''let flushTimer = nullfunction flushBufferedOutput() {if (outputBuffer.length > 0) {sendToRenderer('proc-out', outputBuffer)outputBuffer = ''}flushTimer = null}function queueStableOutput(chunk) {const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')if (!text) returnoutputBuffer += textif (!flushTimer) {flushTimer = setTimeout(flushBufferedOutput, stableFlushMs)}}proc.onData(normalizedStreamMode === 'stable' ? queueStableOutput : streamOutput)proc.onExit(({ exitCode }) => {if (flushTimer) {clearTimeout(flushTimer)flushTimer = null}if (normalizedStreamMode === 'stable') {flushBufferedOutput()}currentProc = nullcurrentProcKind = nullwriteAudit('run_command_done', { cmd: normalizedCmd, cwd: normalizedCwd, code: exitCode, streamMode: normalizedStreamMode })setImmediate(() => sendToRenderer('proc-done', exitCode ?? 0))})return { ok: true, pid: proc.pid }})// ── IPC: kill current process ─────────────────────────────────────────────────22 unmodified lines}})ipcMain.handle('open-external', (_, url) => {const checked = sanitizeExternalUrl(url)if (!checked.ok) {6 unmodified lines})ipcMain.handle('r2-get-config-status', () => {if (!isEncryptionReady()) {return { ok: false, error: 'OS encryption is unavailable' }}try {const cfg = loadSecureR2Config()if (!cfg) return { ok: true, hasConfig: false }return {ok: true,hasConfig: true,accountIdMasked: maskMiddle(cfg.accountId, 4, 4),bucket: cfg.bucket,accessKeyMasked: maskMiddle(cfg.accessKeyId, 4, 4),}} catch (e) {return { ok: false, error: e.message }}})ipcMain.handle('r2-save-config', (_, cfg) => {if (!isEncryptionReady()) {return { ok: false, error: 'OS encryption is unavailable' }}const required = ['accountId', 'bucket', 'accessKeyId', 'secretAccessKey']for (const k of required) {if (!cfg || !String(cfg[k] || '').trim()) {return { ok: false, error: `Missing ${k}` }}}try {const normalized = {accountId: normalizeCredential(cfg.accountId),bucket: normalizeCredential(cfg.bucket),accessKeyId: normalizeCredential(cfg.accessKeyId),secretAccessKey: normalizeCredential(cfg.secretAccessKey),}saveSecureR2Config({accountId: normalized.accountId,bucket: normalized.bucket,accessKeyId: normalized.accessKeyId,secretAccessKey: normalized.secretAccessKey,})return { ok: true }} catch (e) {return { ok: false, error: e.message }}})ipcMain.handle('r2-test-config', (_, cfg) => {const required = ['accountId', 'bucket', 'accessKeyId', 'secretAccessKey']for (const k of required) {if (!cfg || !String(cfg[k] || '').trim()) {return { ok: false, error: `Missing ${k}` }}}const normalized = {accountId: normalizeCredential(cfg.accountId),bucket: normalizeCredential(cfg.bucket),accessKeyId: normalizeCredential(cfg.accessKeyId),secretAccessKey: normalizeCredential(cfg.secretAccessKey),}return testR2Config(normalized)})ipcMain.handle('r2-clear-config', () => {try {if (fs.existsSync(secureConfigPath)) {fs.unlinkSync(secureConfigPath)}writeAudit('r2_logout', { projectRoot })return { ok: true }} catch (e) {return { ok: false, error: e.message }}})ipcMain.handle('r2-suggest-target', () => {try {const cfg = loadSecureR2Config()if (!cfg) return { ok: false, error: 'R2 is not configured yet' }const root = getEffectiveProjectRoot()const pkgPath = path.join(root, 'package.json')const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))const appBase = deriveAppBase(pkg.name)const folders = listR2Folders(cfg)const target = chooseR2Target(folders, appBase)return { ok: true, target, appBase, folders, bucket: cfg.bucket }} catch (e) {return { ok: false, error: e.message }}})ipcMain.handle('r2-upload-dist', (_, { target }) => {try {const root = getEffectiveProjectRoot()const cfg = loadSecureR2Config()if (!cfg) {sendToRenderer('proc-out', '\n[ERROR] R2 is not configured yet\n')sendToRenderer('proc-done', 1)return { ok: false, error: 'R2 is not configured yet' }}const distPath = path.join(root, 'dist')if (!fs.existsSync(distPath)) {sendToRenderer('proc-out', '\n[ERROR] dist folder not found. Build first.\n')sendToRenderer('proc-done', 1)return { ok: false, error: 'dist folder not found' }}const pkgPath = path.join(root, 'package.json')const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))const appBase = deriveAppBase(pkg.name)const targetFolder = String(target || appBase).trim() || appBasekillCurrentProc()const endpoint = `https://${cfg.accountId}.r2.cloudflarestorage.com`const candidates = listR2UploadCandidates(distPath)const totalCandidates = candidates.lengthif (totalCandidates === 0) {sendToRenderer('proc-out', '\n[ERROR] No uploadable files found in dist (.exe, .msi, .AppImage)\n')sendToRenderer('proc-done', 1)return { ok: false, error: 'No uploadable files found in dist' }}const args = ['s3', 'sync', 'dist', `s3://${cfg.bucket}/${targetFolder}/`,'--endpoint-url', endpoint,'--exclude', '*','--include', '*.exe','--include', '*.msi','--include', '*.AppImage','--exclude', 'win-unpacked/*','--exclude', 'linux-unpacked/*','--exclude', 'mac/*','--exclude', '__pycache__/*']const proc = spawn(normalizeExecName('aws'), args, {cwd: root,shell: false,windowsHide: true,env: {...process.env,AWS_ACCESS_KEY_ID: cfg.accessKeyId,AWS_SECRET_ACCESS_KEY: cfg.secretAccessKey,AWS_DEFAULT_REGION: 'auto'}})currentProc = proccurrentProcKind = 'spawn'proc.stdout.setEncoding('utf8')proc.stderr.setEncoding('utf8')sendToRenderer('proc-out', `\n[INFO] Uploading to s3://${cfg.bucket}/${targetFolder}/\n`)sendToRenderer('proc-out', `[INFO] Found ${totalCandidates} file(s):\n`)// Show a near-complete preview for large builds (up to 10,000 lines).const previewLimit = 10000const preview = candidates.slice(0, previewLimit)for (const f of preview) {sendToRenderer('proc-out', ` - ${f.rel}\n`)}if (totalCandidates > preview.length) {sendToRenderer('proc-out', ` ... and ${totalCandidates - preview.length} more\n`)}sendToRenderer('proc-out', '[INFO] Upload progress: 0%\n')writeAudit('r2_upload_start', { bucket: cfg.bucket, target: targetFolder, projectRoot: root, totalCandidates })let uploadedCount = 0const uploadedSet = new Set()let stdoutBuffer = ''let stderrBuffer = ''function reportProgressLine(line) {const m = line.match(/upload:\s+(.+?)\s+to\s+s3:\/\//i)if (!m || !m[1]) return falseconst rawPath = String(m[1]).trim().replace(/\\/g, '/')const rel = rawPath.replace(/^dist\//i, '')if (uploadedSet.has(rel)) return trueuploadedSet.add(rel)uploadedCount += 1const pct = Math.max(0, Math.min(100, Math.round((uploadedCount / totalCandidates) * 100)))sendToRenderer('proc-out', `[INFO] [R2 ${uploadedCount}/${totalCandidates} ${pct}%] Uploaded: ${rel}\n`)return true}function flushChunk(bufferRef, chunk) {const combined = bufferRef.value + String(chunk || '')const parts = combined.split(/\r?\n/)bufferRef.value = parts.pop() || ''for (const line of parts) {if (!line) continueif (reportProgressLine(line)) continuesendToRenderer('proc-out', `${line}\n`)}}proc.stdout.on('data', (d) => flushChunk({ get value() { return stdoutBuffer }, set value(v) { stdoutBuffer = v } }, d))proc.stderr.on('data', (d) => flushChunk({ get value() { return stderrBuffer }, set value(v) { stderrBuffer = v } }, d))let closeCode = nulllet stdoutDone = falselet stderrDone = falsefunction tryFinish() {if (closeCode !== null && stdoutDone && stderrDone) {if (stdoutBuffer.trim()) {if (!reportProgressLine(stdoutBuffer.trim())) sendToRenderer('proc-out', `${stdoutBuffer.trim()}\n`)stdoutBuffer = ''}if (stderrBuffer.trim()) {if (!reportProgressLine(stderrBuffer.trim())) sendToRenderer('proc-out', `${stderrBuffer.trim()}\n`)stderrBuffer = ''}if (closeCode === 0) {const pct = Math.max(0, Math.min(100, Math.round((uploadedCount / totalCandidates) * 100)))sendToRenderer('proc-out', `[INFO] R2 upload completed: uploaded ${uploadedCount}/${totalCandidates} file(s) (${pct}%).\n`)if (uploadedCount < totalCandidates) {sendToRenderer('proc-out', '[INFO] Some files may already be up-to-date on R2 and were skipped by sync.\n')}}currentProc = nullcurrentProcKind = nullwriteAudit('r2_upload_done', { bucket: cfg.bucket, target: targetFolder, code: closeCode, uploadedCount, totalCandidates })setImmediate(() => sendToRenderer('proc-done', closeCode))}}proc.stdout.on('end', () => { stdoutDone = true; tryFinish() })proc.stderr.on('end', () => { stderrDone = true; tryFinish() })proc.on('close', (code) => { closeCode = code ?? 0; tryFinish() })proc.on('error', (err) => {sendToRenderer('proc-out', `\n[ERROR] ${err.message}\n`)sendToRenderer('proc-done', 1)writeAudit('r2_upload_error', { message: err.message, bucket: cfg.bucket, target: targetFolder })currentProc = nullcurrentProcKind = null})return { ok: true, target: targetFolder, bucket: cfg.bucket, pid: proc.pid }} catch (e) {sendToRenderer('proc-out', `\n[ERROR] ${e.message}\n`)sendToRenderer('proc-done', 1)return { ok: false, error: e.message }}})123456789101116 unmodified lines2829303132333425 unmodified lines606162636465666768697071727374757677787980818283848586878889909192939495969721 unmodified lines11912012112212312412512612782 unmodified lines21021121221321421521621718 unmodified lines23623723823924024124224324424524624724824925014 unmodified lines26526626726826927027127227327427527627727814 unmodified lines293294295296297298299300301302303304305306307308309310311312124 unmodified lines4374384394404414424434444454464474484494504514524534544554564574584594 unmodified lines4644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611372 unmodified lines114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211832 unmodified lines118611871188118911901191119210 unmodified lines1203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130672 unmodified lines13791380138113821383138413851386138713881389185 unmodified lines1575157615771578157915801581158215831584158515861587158840 unmodified lines162916301631163216331634163516361637163856 unmodified lines16951696169716981699170017011702170317041705170617071708170917101711171217139 unmodified lines17231724172517261727172817291730173117329 unmodified lines17421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191222 unmodified lines193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819696 unmodified lines1976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003'use strict'const { app, BrowserWindow, ipcMain, shell, dialog, safeStorage, session, Menu, Tray, screen } = require('electron')const path = require('path')const fs = require('fs')const os = require('os')const { spawn, spawnSync } = require('child_process')const platform = require('./runtime/platform')let ptyModule = nullfunction getPtyModule() {16 unmodified lines}function configureRuntimeWritablePaths() {const candidates = platform.getWritableCandidates('Dev-Launcher')for (const basePath of candidates) {if (!isWritableDirectory(basePath)) continue25 unmodified lineslet tray = nulllet currentProc = nulllet currentProcKind = nulllet currentMainCommandKey = nullconst popupRuns = new Map()let popupRunSeq = 0let metricsTimer = nulllet cpuSnapshot = nulllet popupClampGuard = falselet popupDockSeq = 0function popupChannel(runId, topic) {return `popup:${String(runId || '')}:${String(topic || '')}`}function popupLegacyChannel(topic) {const t = String(topic || '').trim().toLowerCase()if (t === 'meta') return 'popup-meta'if (t === 'out') return 'popup-out'if (t === 'done') return 'popup-done'if (t === 'metrics') return 'popup-metrics'return ''}function sendToPopup(ctx, topic, payload) {if (!ctx || !ctx.win || ctx.win.isDestroyed()) returnconst scopedChannel = popupChannel(ctx.runId, topic)ctx.win.webContents.send(scopedChannel, payload)// Backward compatibility for popup windows using the legacy preload bridge.const legacyChannel = popupLegacyChannel(topic)if (legacyChannel) {ctx.win.webContents.send(legacyChannel, payload)}}const secureConfigPath = path.join(app.getPath('userData'), 'secure-r2-config.json')const auditLogPath = path.join(app.getPath('userData'), 'audit.log')const isDev = !app.isPackaged21 unmodified linesfunction getRestrictedPathReason(targetPath) {const resolved = path.resolve(String(targetPath || ''))for (const base of platform.getProtectedPathBases()) {if (isPathUnder(resolved, base)) {return `Selection is blocked because the folder is inside a protected OS location: ${base}`}}return null82 unmodified linescontextIsolation: true,nodeIntegration: false,sandbox: false,// Packaged builds must not expose DevTools entry points.devTools: !!isDev},title: 'Dev Launcher',show: false18 unmodified linesif (!isDev) {// Block common DevTools shortcuts in production builds.const _blockDevToolsKeys = (event, input) => {const key = String(input.key || '').toLowerCase()const openDevTools =key === 'f12' ||((input.control || input.meta) && input.shift && (key === 'i' || key === 'j' || key === 'c'))if (openDevTools) event.preventDefault()}win.webContents.on('before-input-event', _blockDevToolsKeys)win.once('closed', () => win.webContents.removeListener('before-input-event', _blockDevToolsKeys))}win.once('ready-to-show', () => {14 unmodified lineswin.hide()}})const _onWinMove = () => layoutDockedPopups()win.on('move', _onWinMove)win.once('closed', () => win.removeListener('move', _onWinMove))win.on('resize', () => {layoutDockedPopups()})}function createTray() {14 unmodified lines{label: 'Quit',click: () => {tray.removeListener('double-click', _onTrayDblClick)tray.destroy()tray = nullkillAllRunningJobs()app.quit()}}])tray.setContextMenu(ctxMenu)const _onTrayDblClick = () => {if (win && !win.isDestroyed()) { win.show(); win.focus() }}tray.on('double-click', _onTrayDblClick)}async function chooseExternalProjectFolder(mode = 'full-project') {124 unmodified linessetTimeout(() => {if (!tray) createTray()}, 300)}).catch(err => {console.error('[app] startup error:', err)app.quit()})app.on('window-all-closed', () => {// ถ้ายังมี tray อยู่ ให้แอปทำงานต่อใน backgroundif (!tray) {killAllRunningJobs()app.quit()}})app.on('before-quit', () => {killAllRunningJobs()})function killCurrentProc() {if (!currentProc) returntry {4 unmodified linesif (currentProc && currentProc.pid) {spawn('taskkill', ['/pid', String(currentProc.pid), '/f', '/t'], { shell: false, windowsHide: true })}} catch (_e) { /* best-effort kill; ignore errors to avoid crash-on-cleanup */ }currentProc = nullcurrentProcKind = nullcurrentMainCommandKey = null}function killProcessObject(proc, kind) {if (!proc) returntry {if (kind === 'pty' && typeof proc.kill === 'function') {proc.kill()}if (proc && proc.pid) {spawn('taskkill', ['/pid', String(proc.pid), '/f', '/t'], { shell: false, windowsHide: true })}} catch (_e) { /* best-effort kill; ignore errors to avoid crash-on-cleanup */ }}function getCommandDisplayLine(cmd, args) {const normalizedArgs = (args || []).map(x => String(x || ''))return [String(cmd || ''), ...normalizedArgs].join(' ').trim()}function sanitizePopupTitle(raw) {return String(raw || 'Terminal').replace(/[<>:"/\\|?*]+/g, ' ').replace(/\s+/g, ' ').trim() || 'Terminal'}function buildPopupRunId() {popupRunSeq += 1return `popup-${Date.now()}-${popupRunSeq}`}function getCpuSnapshot() {const cpus = os.cpus() || []return cpus.map((cpu) => {const times = cpu && cpu.times ? cpu.times : {}return {user: Number(times.user || 0),nice: Number(times.nice || 0),sys: Number(times.sys || 0),idle: Number(times.idle || 0),irq: Number(times.irq || 0)}})}function computeCpuUsagePercent(prev, next) {if (!Array.isArray(prev) || !Array.isArray(next) || prev.length === 0 || next.length === 0) return nullconst count = Math.min(prev.length, next.length)let idleDelta = 0let totalDelta = 0for (let i = 0; i < count; i++) {const p = prev[i]const n = next[i]const pIdle = Number(p.idle || 0)const nIdle = Number(n.idle || 0)const pTotal = Number(p.user || 0) + Number(p.nice || 0) + Number(p.sys || 0) + pIdle + Number(p.irq || 0)const nTotal = Number(n.user || 0) + Number(n.nice || 0) + Number(n.sys || 0) + nIdle + Number(n.irq || 0)idleDelta += Math.max(0, nIdle - pIdle)totalDelta += Math.max(0, nTotal - pTotal)}if (totalDelta <= 0) return nullconst usage = Math.max(0, Math.min(100, ((totalDelta - idleDelta) / totalDelta) * 100))return Math.round(usage * 10) / 10}function collectSystemUsage() {const nextSnapshot = getCpuSnapshot()const cpuPercent = cpuSnapshot ? computeCpuUsagePercent(cpuSnapshot, nextSnapshot) : nullcpuSnapshot = nextSnapshotconst totalMem = Number(os.totalmem() || 0)const freeMem = Number(os.freemem() || 0)const usedMem = Math.max(0, totalMem - freeMem)const memPercent = totalMem > 0 ? Math.round(((usedMem / totalMem) * 100) * 10) / 10 : 0return {cpuPercent,memPercent,usedMem,totalMem}}function maybeStopMetricsTicker() {if (popupRuns.size > 0) returnif (metricsTimer) {clearInterval(metricsTimer)metricsTimer = null}cpuSnapshot = null}function ensureMetricsTicker() {if (metricsTimer) returncpuSnapshot = getCpuSnapshot()metricsTimer = setInterval(() => {const usage = collectSystemUsage()for (const ctx of popupRuns.values()) {if (!ctx || !ctx.win || ctx.win.isDestroyed()) continuesendToPopup(ctx, 'metrics', usage)}}, 1200)}function getClampedBounds(targetWin, proposedBounds) {const display = screen.getDisplayMatching(proposedBounds)const area = display && display.workArea ? display.workArea : { x: 0, y: 0, width: 1280, height: 720 }const [minWidth, minHeight] = targetWin.getMinimumSize()const safeWidth = Math.max(minWidth || 620, Math.min(proposedBounds.width, area.width))const safeHeight = Math.max(minHeight || 380, Math.min(proposedBounds.height, area.height))let x = proposedBounds.xlet y = proposedBounds.yconst maxX = area.x + area.width - safeWidthconst maxY = area.y + area.height - safeHeightif (x < area.x) x = area.xif (y < area.y) y = area.yif (x > maxX) x = maxXif (y > maxY) y = maxYreturn { x, y, width: safeWidth, height: safeHeight }}function clampWindowInsideDisplay(targetWin) {if (!targetWin || targetWin.isDestroyed()) returnif (targetWin.isMinimized() || targetWin.isMaximized() || targetWin.isFullScreen()) returnif (popupClampGuard) returnpopupClampGuard = truetry {const current = targetWin.getBounds()const clamped = getClampedBounds(targetWin, current)const changed =clamped.x !== current.x ||clamped.y !== current.y ||clamped.width !== current.width ||clamped.height !== current.heightif (changed) {targetWin.setBounds(clamped, false)}} finally {popupClampGuard = false}}function notifyPopupState(payload) {sendToRenderer('popup-run-state', payload)}function closePopupRunByKey(cmdKey) {const existing = popupRuns.get(cmdKey)if (!existing) return falsekillProcessObject(existing.proc, existing.procKind)try {if (existing.win && !existing.win.isDestroyed()) {existing.win.destroy()}} catch (_e) { /* BrowserWindow.destroy() error; window may already be gone */ }popupRuns.delete(cmdKey)layoutDockedPopups()maybeStopMetricsTicker()return true}function closeAllPopupRuns() {const keys = Array.from(popupRuns.keys())for (const key of keys) {closePopupRunByKey(key)}}function killAllRunningJobs() {closeAllPopupRuns()killCurrentProc()}function listDockedPopupContexts() {const docked = []for (const ctx of popupRuns.values()) {if (!ctx || !ctx.isDocked) continueif (!ctx.win || ctx.win.isDestroyed()) continuedocked.push(ctx)}docked.sort((a, b) => Number(a.dockOrder || 0) - Number(b.dockOrder || 0))return docked}function layoutDockedPopups() {if (!win || win.isDestroyed()) returnconst docked = listDockedPopupContexts()if (!docked.length) returnconst host = win.getBounds()const slotWidth = 230const slotHeight = 56const gap = 8const startX = host.x + 286const startY = host.y + 78const endX = host.x + host.width - 10const usableWidth = Math.max(slotWidth, endX - startX)const perRow = Math.max(1, Math.floor((usableWidth + gap) / (slotWidth + gap)))for (let i = 0; i < docked.length; i++) {const ctx = docked[i]const row = Math.floor(i / perRow)const col = i % perRowconst x = startX + (col * (slotWidth + gap))const y = startY + (row * (slotHeight + gap))const nextTitle = `#${i + 1} Sandbox Terminal - ${ctx.displayLabel}`if (ctx.win.getTitle() !== nextTitle) {ctx.win.setTitle(nextTitle)}ctx.win.setBounds({ x, y, width: slotWidth, height: slotHeight }, false)ctx.win.moveTop()}}function dockPopupWindow(ctx) {if (!ctx || !ctx.win || ctx.win.isDestroyed()) returnif (ctx.isDocked) {layoutDockedPopups()return}ctx.normalBounds = ctx.win.getBounds()ctx.isDocked = truepopupDockSeq += 1ctx.dockOrder = popupDockSeqtry {ctx.win.setAlwaysOnTop(true, 'floating')ctx.win.setResizable(false)ctx.win.setSkipTaskbar(true)} catch (_e) { /* dock window-state changes are best-effort */ }layoutDockedPopups()notifyPopupState({ cmdKey: ctx.cmdKey, status: 'docked', runId: ctx.runId })}function undockPopupWindow(ctx) {if (!ctx || !ctx.win || ctx.win.isDestroyed()) returnif (!ctx.isDocked) returnctx.isDocked = falsetry {ctx.win.setAlwaysOnTop(false)ctx.win.setResizable(true)ctx.win.setSkipTaskbar(false)ctx.win.setTitle(`Sandbox Terminal - ${ctx.displayLabel}`)if (ctx.normalBounds) {ctx.win.setBounds(getClampedBounds(ctx.win, ctx.normalBounds), false)}} catch (_e) { /* undock window-state changes are best-effort */ }layoutDockedPopups()notifyPopupState({ cmdKey: ctx.cmdKey, status: 'undocked', runId: ctx.runId })}function createPopupWindow(ctx) {const parentBounds = win && !win.isDestroyed() ? win.getBounds() : { x: 80, y: 80, width: 1080, height: 720 }const popupPreloadPath = fs.existsSync(path.join(__dirname, 'popup-preload.js'))? path.join(__dirname, 'popup-preload.js'): path.join(__dirname, 'preload.js')const popup = new BrowserWindow({width: 880,height: 520,minWidth: 620,minHeight: 380,x: parentBounds.x + 32,y: parentBounds.y + 32,resizable: true,movable: true,minimizable: true,maximizable: true,frame: true,backgroundColor: '#00101a',title: `Sandbox Terminal - ${ctx.displayLabel}`,parent: win && !win.isDestroyed() ? win : null,webPreferences: {preload: popupPreloadPath,contextIsolation: true,nodeIntegration: false,sandbox: true,devTools: !!isDev},show: false})popup.webContents.setWindowOpenHandler(() => ({ action: 'deny' }))popup.webContents.on('will-navigate', (e, url) => {if (!String(url || '').startsWith('file:')) {e.preventDefault()writeAudit('blocked_popup_navigation', { url: String(url || ''), runId: ctx.runId })}})popup.on('move', () => {if (ctx.isDocked) {layoutDockedPopups()return}clampWindowInsideDisplay(popup)})popup.on('resize', () => {if (ctx.isDocked) {layoutDockedPopups()return}clampWindowInsideDisplay(popup)})popup.on('minimize', (e) => {e.preventDefault()dockPopupWindow(ctx)})popup.on('focus', () => {const latest = popupRuns.get(ctx.cmdKey)if (!latest || latest.runId !== ctx.runId) returnif (latest.isDocked) {undockPopupWindow(latest)}})popup.once('ready-to-show', () => {clampWindowInsideDisplay(popup)popup.show()})popup.on('closed', () => {popup.removeAllListeners('move')const latest = popupRuns.get(ctx.cmdKey)if (!latest || latest.runId !== ctx.runId) returnkillProcessObject(latest.proc, latest.procKind)popupRuns.delete(ctx.cmdKey)maybeStopMetricsTicker()layoutDockedPopups()notifyPopupState({ cmdKey: ctx.cmdKey, status: 'closed' })})const htmlPath = path.join(__dirname, 'web', 'popup-terminal.html')popup.loadFile(htmlPath, { hash: encodeURIComponent(ctx.runId) })return popup}function validateAndNormalizeCommand(cmd, args, cwd) {const effectiveRoot = getEffectiveProjectRoot()const requestedCmd = normalizeExecName(cmd)const requestedArgs = (args || []).map(x => String(x || ''))const requestedCwd = path.resolve(String(cwd || effectiveRoot))const restrictedPathReason = getRestrictedPathReason(requestedCwd)if (restrictedPathReason) {return {ok: false,error: restrictedPathReason}}if (!isDev && isNpmRunDevCommand(requestedCmd, requestedArgs)) {return {ok: false,error: 'npm run dev is disabled in packaged builds'}}const allowed = buildAllowedCommandSet(effectiveRoot)const directKey = commandKey(cmd, requestedArgs, requestedCwd)const normalizedKey = commandKey(requestedCmd, requestedArgs, requestedCwd)if (!allowed.has(directKey) && !allowed.has(normalizedKey)) {return {ok: false,error: `Command is not allowlisted: ${String(cmd || '')} ${requestedArgs.join(' ')}`}}const runtime = resolveRuntimeCommand(requestedCmd, requestedArgs, requestedCwd)return {ok: true,normalizedCmd: runtime.normalizedCmd,normalizedArgs: runtime.normalizedArgs,normalizedCwd: runtime.normalizedCwd,commandHash: normalizedKey,originalCmd: requestedCmd,originalArgs: requestedArgs,originalCwd: requestedCwd,rewriteInfo: runtime.rewriteInfo,envOverrides: runtime.envOverrides || {}}}function isNpmRunDevCommand(cmd, args) {const normalizedCmd = String(cmd || '').trim().toLowerCase()const normalizedArgs = (args || []).map(x => String(x || '').trim().toLowerCase()).filter(Boolean)if (!(normalizedCmd === 'npm' || normalizedCmd === 'npm.cmd')) return falseif (normalizedArgs.length !== 2) return falsereturn normalizedArgs[0] === 'run' && normalizedArgs[1] === 'dev'}function readPopupCspStatus() {try {const html = fs.readFileSync(path.join(__dirname, 'web', 'popup-terminal.html'), 'utf8')return {hasUnsafeInlineStyle: /style-src[^\n>]*'unsafe-inline'/.test(html)}} catch {return {hasUnsafeInlineStyle: false}}}function getPreferredPopupContext() {let focused = nulllet latest = nullfor (const ctx of popupRuns.values()) {if (!ctx || !ctx.win || ctx.win.isDestroyed()) continueif (ctx.win.isFocused()) focused = ctxif (!latest || Number(ctx.startedAt || 0) > Number(latest.startedAt || 0)) {latest = ctx}}return focused || latest}function spawnPtyWithStreaming(options) {const {normalizedCmd,normalizedArgs,normalizedCwd,streamMode,cols,rows,onOutput,onDone,onError,onStarted,auditMeta,envOverrides,} = optionsconst useShell = shouldUseShellForCommand(normalizedCmd)let ptyFile = normalizedCmdlet ptyArgs = normalizedArgsif (useShell) {const shellSpawn = platform.buildShellSpawn(normalizedCmd, normalizedArgs)ptyFile = shellSpawn.fileptyArgs = shellSpawn.args}const ptyCols = Number.isFinite(Number(cols)) ? Math.max(20, Math.floor(Number(cols))) : 120const ptyRows = Number.isFinite(Number(rows)) ? Math.max(5, Math.floor(Number(rows))) : 30const procEnv = {...process.env,FORCE_COLOR: '1',CLICOLOR: '1',CLICOLOR_FORCE: '1',COLORTERM: 'truecolor',TERM: 'xterm-256color',npm_config_color: 'always',...(envOverrides || {}),}// platform.getPtySpawnOptions() returns {} on Linux/macOS, { useConpty:true } on Windows.const ptyExtra = platform.getPtySpawnOptions()let proctry {const pty = getPtyModule()proc = pty.spawn(ptyFile, ptyArgs, {cwd: normalizedCwd,env: procEnv,cols: ptyCols,rows: ptyRows,name: 'xterm-256color',...ptyExtra})} catch (err) {const message = err && err.message ? err.message : String(err || 'Unknown PTY error')onError(message)return null}onStarted(proc)const normalizedStreamMode = String(streamMode || 'realtime').toLowerCase() === 'stable'? 'stable': 'realtime'const stableFlushMs = 30let outputBuffer = ''let flushTimer = nullfunction flushBufferedOutput() {if (outputBuffer.length > 0) {onOutput(outputBuffer)outputBuffer = ''}flushTimer = null}function queueStableOutput(chunk) {const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')if (!text) returnoutputBuffer += textif (!flushTimer) {flushTimer = setTimeout(flushBufferedOutput, stableFlushMs)}}function streamOutput(chunk) {const text = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')if (!text) returnonOutput(text)}proc.onData(normalizedStreamMode === 'stable' ? queueStableOutput : streamOutput)proc.onExit(({ exitCode }) => {if (flushTimer) {clearTimeout(flushTimer)flushTimer = null}if (normalizedStreamMode === 'stable') flushBufferedOutput()writeAudit('run_command_done', {...(auditMeta || {}),cmd: normalizedCmd,cwd: normalizedCwd,code: exitCode,streamMode: normalizedStreamMode})// node-pty can fire onData callbacks after onExit in the same tick.// Delay onDone by two setTimeout passes so any queued onData events// (final output lines) are guaranteed to drain before the popup marks Done.setTimeout(() => setTimeout(() => onDone(exitCode ?? 0), 0), 0)})return {proc,kind: 'pty'}}function startPopupCommand(payload) {const validated = validateAndNormalizeCommand(payload.cmd, payload.args, payload.cwd)if (!validated.ok) {writeAudit('blocked_command', { cmd: String(payload.cmd || ''), args: payload.args || [], cwd: payload.cwd || '', mode: 'popup' })return { ok: false, error: validated.error }}const { normalizedCmd, normalizedArgs, normalizedCwd, commandHash } = validatedconst restarted = closePopupRunByKey(commandHash)const runId = buildPopupRunId()const displayLabel = sanitizePopupTitle(payload.label || getCommandDisplayLine(normalizedCmd, normalizedArgs))const commandLine = validated.rewriteInfo && validated.rewriteInfo.applied? getCommandDisplayLine(validated.originalCmd, validated.originalArgs): getCommandDisplayLine(normalizedCmd, normalizedArgs)const rawLogCapture = openRawLogCapture('popup', commandLine, runId)const ctx = {runId,cmdKey: commandHash,displayLabel,normalizedCmd,normalizedArgs,normalizedCwd,startedAt: Date.now(),proc: null,procKind: null,win: null}const popup = createPopupWindow(ctx)ctx.win = popuppopupRuns.set(commandHash, ctx)ensureMetricsTicker()popup.webContents.on('did-finish-load', () => {sendToPopup(ctx, 'meta', {runId,title: displayLabel,cwd: normalizedCwd,commandLine,streamMode: String(payload.streamMode || 'realtime')})sendToPopup(ctx, 'out', `▶ ${commandLine}\n${'─'.repeat(70)}\n`)if (rawLogCapture.filePath) {sendToPopup(ctx, 'out', `[INFO] Raw log file: ${rawLogCapture.filePath}\n`)}})writeAudit('run_command', {cmd: normalizedCmd,args: normalizedArgs,cwd: normalizedCwd,mode: 'popup',originalCmd: validated.originalCmd,originalArgs: validated.originalArgs,originalCwd: validated.originalCwd,rewrite: validated.rewriteInfo,runId,restarted})const started = spawnPtyWithStreaming({normalizedCmd,normalizedArgs,normalizedCwd,streamMode: payload.streamMode,cols: payload.cols,rows: payload.rows,onOutput: (text) => {const latest = popupRuns.get(commandHash)if (!latest || latest.runId !== runId || !latest.win || latest.win.isDestroyed()) returnrawLogCapture.append(text)sendToPopup(latest, 'out', text)},onDone: (exitCode) => {const latest = popupRuns.get(commandHash)if (!latest || latest.runId !== runId) returnrawLogCapture.close()latest.proc = nulllatest.procKind = nullif (latest.win && !latest.win.isDestroyed()) {sendToPopup(latest, 'done', exitCode)}notifyPopupState({ cmdKey: commandHash, status: 'done', exitCode })},onError: (message) => {const latest = popupRuns.get(commandHash)if (!latest || latest.runId !== runId) returnrawLogCapture.close()if (latest.win && !latest.win.isDestroyed()) {sendToPopup(latest, 'out', `\n[ERROR] Failed to start PTY: ${message}\n`)sendToPopup(latest, 'done', 1)}notifyPopupState({ cmdKey: commandHash, status: 'done', exitCode: 1 })writeAudit('run_command_error', { cmd: normalizedCmd, cwd: normalizedCwd, mode: 'popup', runId, error: message })},onStarted: (proc) => {const latest = popupRuns.get(commandHash)if (!latest || latest.runId !== runId) {killProcessObject(proc, 'pty')return}latest.proc = proclatest.procKind = 'pty'},auditMeta: { mode: 'popup', runId },envOverrides: validated.envOverrides})if (!started || !started.proc) {closePopupRunByKey(commandHash)return { ok: false, error: 'Failed to start popup command process' }}notifyPopupState({cmdKey: commandHash,status: restarted ? 'restarted' : 'started',runId,label: displayLabel,commandLine})return {ok: true,mode: 'popup',cmdKey: commandHash,runId,restarted}}function sendToRenderer(channel, data) {2 unmodified lines}}function sanitizeLogLabel(input) {return String(input || 'run').toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '') || 'run'}function openRawLogCapture(mode, cmd, runId) {try {const dir = path.join(app.getPath('userData'), 'raw-logs')fs.mkdirSync(dir, { recursive: true })const stamp = new Date().toISOString().replace(/[:.]/g, '-')const fileName = `${stamp}-${sanitizeLogLabel(mode)}-${sanitizeLogLabel(cmd)}-${sanitizeLogLabel(runId || process.pid)}.log`const filePath = path.join(dir, fileName)const stream = fs.createWriteStream(filePath, { flags: 'a' })return {filePath,append(text) {if (!stream || stream.destroyed) returnif (typeof text !== 'string' || text.length === 0) returnstream.write(text)},close() {if (!stream || stream.destroyed) returnstream.end()}}} catch {return {filePath: null,append() {},close() {}}}}function writeAudit(event, meta = {}) {try {const safeMeta = { ...meta }2 unmodified linesdelete safeMeta.accountIdconst line = `${new Date().toISOString()} ${event} ${JSON.stringify(safeMeta)}\n`fs.appendFileSync(auditLogPath, line, 'utf8')} catch (_e) { /* audit log write failure is non-fatal */ }}function sanitizeExternalUrl(input) {10 unmodified lines}function normalizeExecName(cmd) {return platform.normalizeExecName(cmd)}function resolveNodeRuntimeCommand() {return platform.resolveNodeRuntime()}function isNpmRunLauncherLinuxBuildCommand(cmd, args) {const normalizedCmd = String(cmd || '').trim().toLowerCase()const normalizedArgs = (args || []).map(x => String(x || '').trim().toLowerCase()).filter(Boolean)if (!(normalizedCmd === 'npm' || normalizedCmd === 'npm.cmd')) return falseif (normalizedArgs.length !== 2) return falseif (normalizedArgs[0] !== 'run') return falsereturn normalizedArgs[1] === 'build:linux:wsl' || normalizedArgs[1] === 'build:linux'}function isNpmRunBuildV8Command(cmd, args) {const normalizedCmd = String(cmd || '').trim().toLowerCase()const normalizedArgs = (args || []).map(x => String(x || '').trim().toLowerCase()).filter(Boolean)if (!(normalizedCmd === 'npm' || normalizedCmd === 'npm.cmd')) return falseif (normalizedArgs.length !== 2) return falsereturn normalizedArgs[0] === 'run' && normalizedArgs[1] === 'build-v8'}function materializeLauncherScript(relativePath) {const sourcePath = path.join(__dirname, relativePath)if (!fs.existsSync(sourcePath)) return null// External runtimes (bash/node) cannot execute scripts directly from app.asar.if (!/\.asar[\\/]/i.test(sourcePath)) {return sourcePath}const runtimeDir = path.join(app.getPath('userData'), 'runtime-scripts')fs.mkdirSync(runtimeDir, { recursive: true })const targetPath = path.join(runtimeDir, path.basename(relativePath))const buf = fs.readFileSync(sourcePath)fs.writeFileSync(targetPath, buf)if (process.platform !== 'win32') {try {fs.chmodSync(targetPath, 0o755)} catch (_e) { /* chmod may fail on some filesystems; not fatal */ }}return targetPath}function resolveRuntimeCommand(cmd, args, cwd) {const normalizedCmd = normalizeExecName(cmd)const normalizedArgs = (args || []).map(x => String(x || ''))const normalizedCwd = path.resolve(String(cwd || getEffectiveProjectRoot()))if (isNpmRunLauncherLinuxBuildCommand(normalizedCmd, normalizedArgs)) {const rewrite = platform.rewriteLinuxBuildCommand(normalizedCwd)return {normalizedCmd: rewrite.cmd,normalizedArgs: rewrite.args,normalizedCwd,rewriteInfo: rewrite.rewriteInfo,envOverrides: {}}}if (isNpmRunBuildV8Command(normalizedCmd, normalizedArgs)) {const launcherV8Script = materializeLauncherScript(path.join('scripts', 'build-v8-external.js'))if (launcherV8Script) {const nodeRuntimeCmd = resolveNodeRuntimeCommand()const runtimeScriptDir = path.dirname(launcherV8Script)return {normalizedCmd: nodeRuntimeCmd,normalizedArgs: [launcherV8Script, normalizedCwd],normalizedCwd: runtimeScriptDir,rewriteInfo: {applied: true,kind: 'launcher-build-v8',launcherScriptPath: launcherV8Script,nodeRuntimeCmd,targetProjectPath: normalizedCwd,},envOverrides: {}}}}return {normalizedCmd,normalizedArgs,normalizedCwd,rewriteInfo: {applied: false},envOverrides: {}}}function shouldUseShellForCommand(cmd) {return platform.shouldUseShell(cmd)}function commandKey(cmd, args, cwd) {72 unmodified linesfunction loadSecureConfigRaw() {if (!fs.existsSync(secureConfigPath)) return nulltry {return JSON.parse(fs.readFileSync(secureConfigPath, 'utf-8'))} catch {return null}}function loadSecureR2Config() {185 unmodified linesreturn { type: primaryType, label, badgeClass }}function getRuntimeOsStatus() {const p = String(process.platform || '').toLowerCase()if (p === 'win32') return { platform: p, label: 'Windows' }if (p === 'darwin') return { platform: p, label: 'macOS' }if (p === 'linux') return { platform: p, label: 'Linux' }return { platform: p || 'unknown', label: p || 'Unknown' }}function buildGroups(pkg, root, hasAndroid) {const d = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.peerDependencies }const has = (name) => !!d[name]40 unmodified lines// ── Electron ─────────────────────────────────────────────────────────────────const usedScripts = new Set()if (isElectron) {const launcherManagedBuildKeys = ['build-v8', 'build:linux', 'build:linux:wsl']const buildKeys = ['build','build-win','build-exe','build-v8','build-nsis','build-msi','build:linux','build:linux:wsl','pack','dist']const scriptedBuildKeys = buildKeys.filter(s => (pkg.scripts || {})[s])const foundKeys = Array.from(new Set([...launcherManagedBuildKeys, ...scriptedBuildKeys]))foundKeys.forEach(s => usedScripts.add(s))if (foundKeys.length) {groups.push({56 unmodified lines// ── IPC: get project info (returns processed data only — no raw pkg exposed) ──ipcMain.handle('get-project', () => {const runtimeOs = getRuntimeOsStatus()const root = getEffectiveProjectRoot()const blockedReason = getRestrictedPathReason(root)if (blockedReason) {return {ok: false,blocked: true,error: blockedReason,projectRoot: root,isDev,runtimeOs}}const pkgPath = path.join(root, 'package.json')try {const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))9 unmodified linestypeInfo, // { type, label, badgeClass }groups, // ready-to-render — no raw pkg sent to rendererisDev, // true only when running via bat/cmd (not packaged)runtimeOs,}} catch (e) {return { ok: false, error: e.message, projectRoot: root, isDev, runtimeOs }}})9 unmodified linesipcMain.handle('run-cmd', (event, { cmd, args, cwd, streamMode, cols, rows }) => {killCurrentProc()const validated = validateAndNormalizeCommand(cmd, args, cwd)if (!validated.ok) {writeAudit('blocked_command', { cmd: String(cmd || ''), args: args || [], cwd: cwd || '', mode: 'main' })const msg = validated.errorsendToRenderer('proc-out', `\n[ERROR] ${msg}\n`)sendToRenderer('proc-done', 1)return { ok: false, error: msg }}const normalizedCmd = validated.normalizedCmdconst normalizedArgs = validated.normalizedArgsconst normalizedCwd = validated.normalizedCwdcurrentMainCommandKey = validated.commandHashconst commandLine = validated.rewriteInfo && validated.rewriteInfo.applied? getCommandDisplayLine(validated.originalCmd, validated.originalArgs): getCommandDisplayLine(normalizedCmd, normalizedArgs)const rawLogCapture = openRawLogCapture('main', commandLine, currentMainCommandKey)if (validated.rewriteInfo && validated.rewriteInfo.applied) {sendToRenderer('proc-out', `[INFO] Rewriting ${validated.originalCmd} ${validated.originalArgs.join(' ')} via launcher (${validated.rewriteInfo.kind})\n`)if (validated.rewriteInfo.launcherScriptPath) {sendToRenderer('proc-out', `[INFO] Launcher script: ${validated.rewriteInfo.launcherScriptPath}\n`)}sendToRenderer('proc-out', `[INFO] Target project: ${validated.rewriteInfo.targetProjectPath}\n`)}if (rawLogCapture.filePath) {sendToRenderer('proc-out', `[INFO] Raw log file: ${rawLogCapture.filePath}\n`)}writeAudit('run_command', {cmd: normalizedCmd,args: normalizedArgs,cwd: normalizedCwd,mode: 'main',originalCmd: validated.originalCmd,originalArgs: validated.originalArgs,originalCwd: validated.originalCwd,rewrite: validated.rewriteInfo})const started = spawnPtyWithStreaming({normalizedCmd,normalizedArgs,normalizedCwd,streamMode,cols,rows,onOutput: (text) => {rawLogCapture.append(text)sendToRenderer('proc-out', text)},onDone: (exitCode) => {rawLogCapture.close()currentProc = nullcurrentProcKind = nullcurrentMainCommandKey = nullsetImmediate(() => sendToRenderer('proc-done', exitCode ?? 0))},onError: (message) => {rawLogCapture.close()sendToRenderer('proc-out', `\n[ERROR] Failed to start PTY: ${message}\n`)sendToRenderer('proc-done', 1)currentMainCommandKey = nullwriteAudit('run_command_error', { cmd: normalizedCmd, cwd: normalizedCwd, mode: 'main', error: message })},onStarted: (proc) => {currentProc = proccurrentProcKind = 'pty'},auditMeta: { mode: 'main' },envOverrides: validated.envOverrides})if (!started || !started.proc) {return { ok: false, error: 'Failed to start process' }}return { ok: true, pid: started.proc.pid, mode: 'main', cmdKey: currentMainCommandKey }})ipcMain.handle('run-cmd-popup', (_, payload) => {return startPopupCommand(payload || {})})ipcMain.handle('open-devtools-for-command', (_, payload) => {if (!isDev) {return { ok: false, error: 'DevTools are disabled in packaged builds' }}const cmd = payload && payload.cmdconst args = payload && payload.argsif (!isNpmRunDevCommand(cmd, args)) {return { ok: false, error: 'DevTools can only be opened for npm run dev' }}if (!win || win.isDestroyed()) {return { ok: false, error: 'Main window is not available' }}try {win.webContents.openDevTools({ mode: 'detach', activate: true })void writeAudit('open_devtools_for_command', { cmd: String(cmd || ''), args: args || [] })return { ok: true }} catch (e) {return { ok: false, error: e && e.message ? e.message : 'Failed to open DevTools' }}})ipcMain.handle('open-main-devtools', () => {if (!isDev) {return { ok: false, error: 'DevTools are disabled in packaged builds' }}if (!win || win.isDestroyed()) {return { ok: false, error: 'Main window is not available' }}try {win.webContents.openDevTools({ mode: 'detach', activate: true })return { ok: true }} catch (e) {return { ok: false, error: e && e.message ? e.message : 'Failed to open main DevTools' }}})ipcMain.handle('open-popup-devtools', () => {if (!isDev) {return { ok: false, error: 'DevTools are disabled in packaged builds' }}const ctx = getPreferredPopupContext()if (!ctx || !ctx.win || ctx.win.isDestroyed()) {return { ok: false, error: 'No active popup terminal' }}try {ctx.win.webContents.openDevTools({ mode: 'detach', activate: true })return { ok: true, runId: ctx.runId }} catch (e) {return { ok: false, error: e && e.message ? e.message : 'Failed to open popup DevTools' }}})ipcMain.handle('get-dev-security-status', () => {if (!isDev) {return {ok: true,appMode: 'packaged',requestGuardInstalled,externalRequestBlockActive: true,shortcutDevtoolsBlockedInProduction: true,mainWindowDevtoolsCapable: false,popupWindowDevtoolsCapable: false,popupCspInlineStyleAllowed: false,popupRunCount: 0,securityNote: 'Dev mode features are disabled in packaged builds.'}}const popupCsp = readPopupCspStatus()const activePopupCount = Array.from(popupRuns.values()).filter(ctx => ctx && ctx.win && !ctx.win.isDestroyed()).lengthreturn {ok: true,appMode: isDev ? 'dev' : 'packaged',requestGuardInstalled,externalRequestBlockActive: !isDev,shortcutDevtoolsBlockedInProduction: !isDev,mainWindowDevtoolsCapable: true,popupWindowDevtoolsCapable: true,popupCspInlineStyleAllowed: popupCsp.hasUnsafeInlineStyle,popupRunCount: activePopupCount,securityNote: 'DevTools open via button is allowed. Keyboard shortcuts remain blocked in production.'}})// ── IPC: kill current process ─────────────────────────────────────────────────22 unmodified lines}})ipcMain.handle('popup-kill', (_, { runId }) => {const rid = String(runId || '')for (const ctx of popupRuns.values()) {if (!ctx || ctx.runId !== rid) continuekillProcessObject(ctx.proc, ctx.procKind)return true}return false})ipcMain.handle('popup-resize', (_, { runId, cols, rows }) => {const rid = String(runId || '')const safeCols = Math.max(20, Math.floor(Number(cols || 0)))const safeRows = Math.max(5, Math.floor(Number(rows || 0)))if (!Number.isFinite(safeCols) || !Number.isFinite(safeRows)) return falsefor (const ctx of popupRuns.values()) {if (!ctx || ctx.runId !== rid) continueif (!ctx.proc || ctx.procKind !== 'pty' || typeof ctx.proc.resize !== 'function') return falsetry {ctx.proc.resize(safeCols, safeRows)return true} catch {return false}}return false})ipcMain.handle('open-external', (_, url) => {const checked = sanitizeExternalUrl(url)if (!checked.ok) {6 unmodified lines})ipcMain.handle('r2-get-config-status', () => {return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }})ipcMain.handle('r2-save-config', (_, cfg) => {return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }})ipcMain.handle('r2-test-config', (_, cfg) => {return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }})ipcMain.handle('r2-clear-config', () => {return { ok: true }})ipcMain.handle('r2-suggest-target', () => {return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }})ipcMain.handle('r2-upload-dist', (_, { target }) => {sendToRenderer('proc-out', '\n[ERROR] R2 moved to dedicated app: chahuadev-R2\n')sendToRenderer('proc-done', 1)return { ok: false, error: 'R2 moved to dedicated app: chahuadev-R2' }})
7 unmodified lines891011121314157 unmodified lines:MENUclsecho ╔════════════════════════════════════════════════════════════════════════════════╗echo ║ chahuadev-junk-sweeper NPM Runner ║echo ║ Version 1.0.0 ║echo ╚════════════════════════════════════════════════════════════════════════════════╝echo.echo.7 unmodified lines891011121314157 unmodified lines:MENUclsecho ╔════════════════════════════════════════════════════════════════════════════════╗echo ║ chahuadev-dev-launcher NPM Runner ║echo ║ Version 2.0.0 ║echo ╚════════════════════════════════════════════════════════════════════════════════╝echo.echo.
1234563 unmodified lines10111213141516171819205 unmodified lines2627282930313233343536373839404142{"name": "@chahuadev/dev-launcher","version": "2.0.3","description": "Universal Dev Command Launcher - drop into any project folder and run commands","main": "main.js","type": "commonjs",3 unmodified lines"build": "electron-builder --win","build-win": "electron-builder --win","build-exe": "electron-builder --win portable --x64","build-v8": "node scripts/build-v8-bytecode.js","build-nsis": "electron-builder --win nsis --x64","build-msi": "electron-builder --win msi --x64","build:linux": "electron-builder --linux AppImage --x64 --publish never","build:linux:wsl": "wsl bash build-linux-wsl.sh"},"devDependencies": {"electron": "^41.0.3",5 unmodified lines"productName": "Dev Launcher","artifactName": "dev-launcher.${ext}","icon": "icons/icon.png","npmRebuild": false,"directories": {"output": "dist"},"files": ["main.js","preload.js","*.jsc","index.html","splash.html","build-linux-wsl.sh","package.json","icons/**","web/**"1234563 unmodified lines10111213141516171819205 unmodified lines2627282930313233343536373839404142434445464748{"name": "@chahuadev/dev-launcher","version": "3.0.0","description": "Universal Dev Command Launcher - drop into any project folder and run commands","main": "main.js","type": "commonjs",3 unmodified lines"build": "electron-builder --win","build-win": "electron-builder --win","build-exe": "electron-builder --win portable --x64","build-v8": "node scripts/build-v8-external.js .","build-nsis": "electron-builder --win nsis --x64","build-msi": "electron-builder --win msi --x64","build:linux": "electron-builder install-app-deps && electron-builder --linux AppImage --x64 --publish never","build:linux:wsl": "electron-builder install-app-deps && electron-builder --linux AppImage --x64 --publish never"},"devDependencies": {"electron": "^41.0.3",5 unmodified lines"productName": "Dev Launcher","artifactName": "dev-launcher.${ext}","icon": "icons/icon.png","npmRebuild": true,"asarUnpack": ["node_modules/node-pty/**"],"directories": {"output": "dist"},"files": ["main.js","preload.js","popup-preload.js","*.jsc","scripts/build-v8-bytecode.js","scripts/build-v8-external.js","runtime/**","index.html","splash.html","package.json","icons/**","web/**"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232---license: otherlanguage:- entags:- code-analysis- static-analysis- javascript- electron- emoji-cleaner- junk-sweeper- plugin-management- desktop-app- electron-app- security---<div align="center"><p align="center"><img src="https://huggingface.co/datasets/chahuadev/chahuadev-png/resolve/main/chahuadev-dev-launcher.png" width="700" alt="Junk Sweeper — Main Dashboard"></p><p align="center"><a href="https://www.npmjs.com/package/@chahuadev/junk-sweeper-app"><img src="https://img.shields.io/npm/v/@chahuadev/dev-launcher?style=for-the-badge&color=blue" alt="NPM Version"></a><a href="https://www.npmjs.com/package/@chahuadev/dev-launcher"><img src="https://img.shields.io/npm/dt/@chahuadev/dev-launcher?style=for-the-badge&color=success" alt="NPM Downloads"></a><a href="https://huggingface.co/datasets/chahuadev/chahuadev-dev-launcher"><img src="https://img.shields.io/badge/%20HuggingFace-Dataset-yellow?style=for-the-badge" alt="HuggingFace Dataset"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-Non--Commercial-blue?style=for-the-badge" alt="Non-Commercial License"></a><img src="https://img.shields.io/badge/Electron-40+-47848F?style=for-the-badge&logo=electron&logoColor=white" alt="Electron 40+"><img src="https://img.shields.io/badge/Node.js-%E2%89%A522.0.0-339933?style=for-the-badge&logo=node.js&logoColor=white" alt="Node.js 22"><img src="https://img.shields.io/badge/Platform-Windows-0078D4?style=for-the-badge&logo=windows&logoColor=white" alt="Windows"><img src="https://img.shields.io/badge/Analysis-Read--Only%20%E2%9C%93-blue?style=for-the-badge" alt="Read-Only Analysis"><img src="https://img.shields.io/badge/Security-10--Layer%20Gateway-red?style=for-the-badge&logo=shield&logoColor=white" alt="7-Layer Security"></p># Chahuadev Dev LauncherPortable desktop command runner for development projects.## Purpose- Drop `dev-launcher.exe` inside a project folder.- Auto-detect project type from `package.json`.- Run grouped commands from one UI.- Manage Cloudflare R2 upload flow for build artifacts.## Repository layout- `main.js`, `preload.js`, `index.html`, `web/`: Electron runtime + UI- `build-desktop.bat`, `build-linux-wsl.sh`: local build scripts- `dist/`: desktop build outputs- `packages/`: npm publish package workspace## NPM publish packageThe npm-uploadable package lives in:- `packages/@chahuadev/dev-launcher/`This package is designed to:1. Download platform binary at install time (`postinstall`)2. Expose launcher CLI command (`dev-launcher`)3. Run downloaded binary from `bin/`See package docs here:- `packages/README.md`- `packages/@chahuadev/dev-launcher/README.md`## NPM Install Commands (Published Package)Global install on Windows:```bashnpm install -g @chahuadev/dev-launcher --foreground-scripts --force```Global install on Linux:```bashsudo npm install -g @chahuadev/dev-launcher --foreground-scripts --force```## Home Overview (Detailed)Dev Launcher focuses on a practical project-local flow:- Place the launcher in a project root.- Detect project type automatically from `package.json`.- Render grouped commands in the left panel.- Stream complete process output in the terminal panel.Recent major additions reflected in Home:- Simplified R2 flow with login/logout and gated actions.- Safer command execution and external URL controls.- Improved build support, including V8 command path and Linux WSL fallback.- Better command output visibility with progress-oriented terminal messages.## Features Snapshot- Auto project detection for Expo, React Native, Electron, Next.js, Vite, and plain npm projects.- One-click command groups for Metro, Gradle, ADB, Electron build scripts, and package scripts.- Real-time stdout/stderr streaming with ANSI color support.- Process-tree kill behavior for long-running child processes.- R2 configuration, target suggestion, and upload workflow in-app.## Security Snapshot- Context isolation enabled.- Node integration disabled in renderer.- Narrow IPC bridge via preload APIs.- External URL allowlist enforcement.- Command allowlist enforcement before spawn.- Request/navigation/popup restrictions in production mode.- Audit logging with sensitive field redaction.## NPM Commands (Repository Source)Install dependencies:```bashnpm install```Run locally:```bashnpm run start```Development run:```bashnpm run dev```Build commands:```bashnpm run buildnpm run build-winnpm run build-exenpm run build-v8npm run build-nsisnpm run build-msinpm run build:linuxnpm run build:linux:wsl```Run launcher command:```bashdev-launcher```## Home Content ExpansionThe Home page currently presents this product definition:- Open Source and Free Forever.- Portable command runner for project-local workflows.- Auto-detection from `package.json` with no manual project setup.Home stat strip values:- Project Types: 6- Terminal Output Coverage: 100%- Distribution Form: 1 portable executable- Configuration Required: Zero for baseline command usage## Home "What We Added" Details- Workflow: project-local runner model, no browse/open project switching dependency.- Security: stricter command allowlist and external URL host allowlist enforcement.- R2 UX: single login/logout flow with operation gating.- Build: V8 build path exposure and Linux WSL resilience improvements.## Home Feature Cards (Detailed)- Auto Project Detection- Detects framework/runtime profile from dependency graph and scripts.- One-Click Commands- Grouped left-panel actions for Expo, Gradle, ADB, Electron, and NPM scripts.- Full Terminal Output- Streams command output in real time, including stderr, without hidden buffering loss.- Portable Single EXE- Designed for drop-in usage directly in target project folder.- Command Group Generator- Generates command sets from project type and script inventory.- Process Tree Kill- Terminates parent and child command processes to prevent orphan runners.## Home Flow Section (Step-by-Step)1. Place executable in the project root (next to `package.json`).2. Launch app and allow automatic project detection.3. Select and execute command from grouped command panel.4. Monitor full output stream in the terminal pane.## Home Compatibility Matrix (Expanded)- Expo / React Native- Typical commands: `expo start`, `expo run:android`, `expo prebuild`- Android / Gradle- Typical commands: `installDebug`, `assembleRelease`, `clean`- Electron- Typical commands: `npm run build`, `npm run build-win`, `npm run build-nsis`, `npm run dist`- Next.js- Typical commands: `npm run dev`, `npm run build`, `npm run start`, `npm run lint`- Vite- Typical commands: `npm run dev`, `npm run build`, `npm run preview`- NPM Scripts- Additional scripts surfaced automatically from project `package.json`- ADB Utilities- Typical commands: `adb devices`, `adb logcat`, `adb reverse tcp:8081 tcp:8081`## Home Security Cards (Expanded)- Context Isolation enabled for renderer boundary hardening.- Node Integration disabled in renderer to reduce direct OS/runtime surface.- Main-process-only sensitive logic for command construction and execution.- Narrow preload bridge with explicit IPC methods.- External access constrained by protocol and host policy.- Strict shell policy and no inline handler dependency in host shell UI.- Popup/navigation/request guard behavior in production.- Controlled process spawn model with allowlist checks.- Build-time credential hygiene for saved R2 config lifecycle.## Notes For Teams- Home page documentation should be treated as the UX-level contract.- README is the implementation-facing mirror of that contract.- When Home sections change, update this README section set to match.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246---license: otherlanguage:- entags:- code-analysis- static-analysis- javascript- electron- emoji-cleaner- junk-sweeper- plugin-management- desktop-app- electron-app- security---<div align="center"><p align="center"><img src="https://huggingface.co/datasets/chahuadev/chahuadev-png/resolve/main/chahuadev-dev-launcher.png" width="700" alt="Junk Sweeper — Main Dashboard"></p><p align="center"><a href="https://www.npmjs.com/package/@chahuadev/junk-sweeper-app"><img src="https://img.shields.io/npm/v/@chahuadev/dev-launcher?style=for-the-badge&color=blue" alt="NPM Version"></a><a href="https://www.npmjs.com/package/@chahuadev/dev-launcher"><img src="https://img.shields.io/npm/dt/@chahuadev/dev-launcher?style=for-the-badge&color=success" alt="NPM Downloads"></a><a href="https://huggingface.co/datasets/chahuadev/chahuadev-dev-launcher"><img src="https://img.shields.io/badge/%20HuggingFace-Dataset-yellow?style=for-the-badge" alt="HuggingFace Dataset"></a><a href="LICENSE"><img src="https://img.shields.io/badge/License-Non--Commercial-blue?style=for-the-badge" alt="Non-Commercial License"></a><img src="https://img.shields.io/badge/Electron-40+-47848F?style=for-the-badge&logo=electron&logoColor=white" alt="Electron 40+"><img src="https://img.shields.io/badge/Node.js-%E2%89%A522.0.0-339933?style=for-the-badge&logo=node.js&logoColor=white" alt="Node.js 22"><img src="https://img.shields.io/badge/Platform-Windows-0078D4?style=for-the-badge&logo=windows&logoColor=white" alt="Windows"><img src="https://img.shields.io/badge/Analysis-Read--Only%20%E2%9C%93-blue?style=for-the-badge" alt="Read-Only Analysis"><img src="https://img.shields.io/badge/Security-10--Layer%20Gateway-red?style=for-the-badge&logo=shield&logoColor=white" alt="7-Layer Security"></p># Chahuadev Dev LauncherPortable desktop command runner for development projects.## Purpose- Drop `dev-launcher.exe` inside a project folder.- Auto-detect project type from `package.json` and scripts.- Run grouped commands from one UI with full terminal output.- Optionally switch project root from the top bar (`Select Project` / `Use Launcher Project`).- Manage Cloudflare R2 upload flow for build artifacts (dev mode only).## Repository layout- `main.js`, `preload.js`, `index.html`, `web/`: Electron runtime + UI- `build-desktop.bat`: local desktop build script (`build:linux` and `build:linux:wsl` are launcher-managed at runtime)- `dist/`: desktop build outputs- `packages/`: npm publish package workspace## NPM publish packageThe npm-uploadable package lives in:- `packages/@chahuadev/dev-launcher/`This package is designed to:1. Download platform binary at install time (`postinstall`)2. Expose launcher CLI command (`dev-launcher`)3. Run downloaded binary from `bin/`See package docs here:- `packages/README.md`- `packages/@chahuadev/dev-launcher/README.md`## NPM Install Commands (Published Package)Global install on Windows:```bashnpm install -g @chahuadev/dev-launcher --foreground-scripts --force```Global install on Linux:```bashsudo npm install -g @chahuadev/dev-launcher --foreground-scripts --force```## Home Overview (Detailed)Dev Launcher is now optimized for a fast Home-first workflow:- Home page renders immediately.- Project detection and command group loading run in the background.- Run tab is ready for command execution with real-time output.- Project root can be switched safely from header controls.Recent major additions reflected in Home:- Header controls for root switching (`Select Project`, `Use Launcher Project`).- Protected OS-folder blocking policy for external project selection.- Main-process audited block events surfaced to renderer notice modal.- Safer command execution and external URL controls.- Improved build support, including V8 command path and Linux WSL fallback.- Better startup responsiveness by deferring heavy initialization.## Features Snapshot- Auto project detection for Electron, Expo/React Native, Next.js, Vite, and script-based npm projects.- One-click command groups for Metro, Gradle, ADB, Electron build scripts, and package scripts.- Real-time stdout/stderr streaming with ANSI color support.- Process-tree kill behavior for long-running child processes.- Optional external project-root selection with security policy checks.- R2 configuration, target suggestion, and upload workflow in-app (hidden in production binaries).## Security Snapshot- Context isolation enabled.- Node integration disabled in renderer.- Narrow IPC bridge via preload APIs.- Protected OS-directory project roots are blocked.- External URL allowlist enforcement.- Command allowlist enforcement before spawn.- Request/navigation/popup restrictions in production mode.- Audit logging with sensitive field redaction.## NPM Commands (Repository Source)Install dependencies:```bashnpm install```Run locally:```bashnpm run start```Development run:```bashnpm run dev```Build commands:```bashnpm run buildnpm run build-winnpm run build-exenpm run build-v8npm run build-nsisnpm run build-msinpm run build:linuxnpm run build:linux:wsl```Run launcher command:```bashdev-launcher```## Home Content ExpansionThe Home page currently presents this product definition:- Open Source and Free Forever.- Portable command runner for project-local workflows.- Auto-detection from `package.json` with no manual project setup.- Optional safe root switching from the app header.Home stat strip values:- Project Types: 6- Terminal Output Coverage: 100%- Distribution Form: 1 portable executable- Configuration Required: Zero for baseline command usage## Home "What We Added" Details- Workflow: top-bar controls to select an external project root or return to launcher root.- Security: protected OS path blocking, audited block events, and stricter URL/command policy enforcement.- Startup: Home-first rendering with deferred background bootstrap.- Build: V8 build path exposure and Linux WSL resilience improvements.## Home Feature Cards (Detailed)- Auto Project Detection- Detects framework/runtime profile from dependency graph and scripts.- One-Click Commands- Grouped left-panel actions for Expo, Gradle, ADB, Electron, and NPM scripts.- Full Terminal Output- Streams command output in real time, including stderr, without hidden buffering loss.- Portable Single EXE- Designed for drop-in usage directly in target project folder.- Command Group Generator- Generates command sets from project type and script inventory.- Process Tree Kill- Terminates parent and child command processes to prevent orphan runners.## Home Flow Section (Step-by-Step)1. Place executable in the project root (next to `package.json`) and launch.2. Let Home render first while project data bootstraps in the background.3. Optionally switch root using `Select Project`, or return using `Use Launcher Project`.4. Select and execute commands from grouped panels and monitor full output stream.## Home Compatibility Matrix (Expanded)- Expo / React Native- Typical commands: `expo start`, `expo run:android`, `expo prebuild`- Android / Gradle- Typical commands: `installDebug`, `assembleRelease`, `clean`- React Native (Bare)- Typical behavior: Metro and Android Gradle groups when Android wrapper exists- Electron- Typical commands: `npm run build`, `npm run build-win`, `npm run build-nsis`, `npm run dist`- Next.js- Typical commands: `npm run dev`, `npm run build`, `npm run start`, `npm run lint`- Vite- Typical commands: `npm run dev`, `npm run build`, `npm run preview`- NPM Scripts- Additional scripts surfaced automatically from project `package.json`- ADB Utilities- Typical commands: `adb devices`, `adb logcat`, `adb reverse tcp:8081 tcp:8081`## Home Security Cards (Expanded)- Context Isolation enabled for renderer boundary hardening.- Node Integration disabled in renderer to reduce direct OS/runtime surface.- Main-process-only sensitive logic for command construction and execution.- Narrow preload bridge with explicit IPC methods for selection/run operations.- Protected OS path policy for project-root selection with formal user notice.- External access constrained by protocol and host policy.- Strict shell policy and no inline handler dependency in host shell UI.- Popup/navigation/request guard behavior in production.- Controlled process spawn model with allowlist checks.- Build-time credential hygiene for saved R2 config lifecycle.## Notes For Teams- Home page documentation should be treated as the UX-level contract.- README is the implementation-facing mirror of that contract.- When Home sections change, update this README section set to match.- Keep security policy statements aligned with `main.js` and `preload.js` IPC behavior.## 💖 Support the ProjectChahuadev tools are 100% free and open-source. If this project helped you save time, please consider buying me a coffee to help keep the servers running!<a href="https://www.buymeacoffee.com/chahuadevm" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
7 unmodified lines8910111213141516171846 unmodified lines6566676869707172737475767 unmodified linesconst platform = os.platform();const arch = os.arch();const BASE_URL = process.env.CHAHADEV_DEV_LAUNCHER_R2_BASE || 'https://pub-419d22521da042dfb27d1f404b3eb8a6.r2.dev/dev-launcher';function getAssetInfo() {if (platform === 'win32') return { fileName: 'dev-launcher.exe', url: `${BASE_URL}/dev-launcher.exe` };if (platform === 'linux') return { fileName: 'dev-launcher.AppImage', url: `${BASE_URL}/dev-launcher.AppImage` };return null;}46 unmodified linestry {await downloadFile(asset.url, filePath);process.stdout.write('\n');if (platform !== 'win32') fs.chmodSync(filePath, 0o755);console.log(`Saved: ${filePath}`);console.log('Run with: dev-launcher\n');} catch (err) {try { if (fs.existsSync(filePath)) fs.unlinkSync(filePath); } catch {}console.error(`\nDownload failed: ${err.message}`);process.exit(1);}7 unmodified lines89101112131415161718192021222346 unmodified lines7071727374757677787980817 unmodified linesconst platform = os.platform();const arch = os.arch();const BASE_URL = process.env.CHAHADEV_DEV_LAUNCHER_R2_BASE || 'https://r2.chahuadev.com/dev-launcher';function getAssetInfo() {if (platform === 'win32') return { fileName: 'dev-launcher.exe', url: `${BASE_URL}/dev-launcher.exe` };if (platform === 'linux') return { fileName: 'dev-launcher.AppImage', url: `${BASE_URL}/dev-launcher.AppImage` };if (platform === 'darwin') {const macArch = arch === 'arm64' ? 'arm64' : 'x64';const fileName = `dev-launcher-${macArch}.dmg`;return { fileName, url: `${BASE_URL}/${fileName}` };}return null;}46 unmodified linestry {await downloadFile(asset.url, filePath);console.log()if (platform !== 'win32') fs.chmodSync(filePath, 0o755);console.log(`Saved: ${filePath}`);console.log('Run with: dev-launcher\n');} catch (err) {try { if (fs.existsSync(filePath)) fs.unlinkSync(filePath); } catch (_e) { /* ignore cleanup error */ }console.error(`\nDownload failed: ${err.message}`);process.exit(1);}
123456{"name": "@chahuadev/dev-launcher","version": "1.0.0","description": "Chahuadev Dev Launcher binary package","main": "index.js","bin": {123456{"name": "@chahuadev/dev-launcher","version": "3.0.0","description": "Chahuadev Dev Launcher binary package","main": "index.js","bin": {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Support the Project</title>
<style>
:root {
--bg: #060b16;
--bg-2: #091225;
--glass: rgba(11, 21, 41, 0.62);
--glass-2: rgba(18, 35, 66, 0.45);
--line: rgba(123, 170, 255, 0.3);
--line-strong: rgba(123, 170, 255, 0.55);
--text: #ecf4ff;
--muted: #a9bfdd;
--accent: #7bb1ff;
--accent-2: #3f89ff;
--gold: #f4b43f;
--gold-2: #dc8f12;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
min-height: 100vh;
color: var(--text);
font-family: "Segoe UI", "Noto Sans", "Tahoma", sans-serif;
background:
radial-gradient(900px 500px at 15% 5%, rgba(63, 137, 255, 0.16), transparent 65%),
radial-gradient(900px 500px at 85% 95%, rgba(123, 177, 255, 0.12), transparent 70%),
linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%);
line-height: 1.7;
}
.page {
max-width: 1100px;
margin: 0 auto;
padding: 28px 20px 36px;
position: relative;
}
.topbar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 18px;
}
.top-title {
display: inline-flex;
align-items: center;
gap: 10px;
font-size: 13px;
letter-spacing: 0.09em;
text-transform: uppercase;
color: var(--accent);
}
.top-title-dot {
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--accent);
box-shadow: 0 0 14px rgba(123, 177, 255, 0.8);
}
.support-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 9px;
border: 1px solid rgba(244, 180, 63, 0.7);
background: linear-gradient(135deg, var(--gold), var(--gold-2));
color: #101624;
text-decoration: none;
border-radius: 12px;
padding: 12px 18px;
min-width: 220px;
font-size: 15px;
font-weight: 800;
box-shadow: 0 10px 24px rgba(244, 180, 63, 0.22);
transition: transform .2s ease, box-shadow .2s ease;
}
.support-btn:hover {
transform: translateY(-2px);
box-shadow: 0 14px 30px rgba(244, 180, 63, 0.3);
}
.hero {
border: 1px solid var(--line-strong);
border-radius: 18px;
padding: 24px;
background: linear-gradient(180deg, var(--glass) 0%, var(--glass-2) 100%);
backdrop-filter: blur(8px);
margin-bottom: 18px;
}
.hero h1 {
margin: 0 0 10px;
font-size: clamp(30px, 5vw, 48px);
line-height: 1.1;
letter-spacing: -0.02em;
}
.hero p {
margin: 0;
color: var(--muted);
font-size: 15px;
max-width: 900px;
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12px;
}
.lang-card {
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(7, 17, 33, 0.62);
padding: 15px 15px 13px;
}
.lang-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
margin-bottom: 8px;
}
.lang-code {
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--accent);
font-weight: 700;
}
.lang-name {
font-size: 12px;
color: #c9dcfa;
opacity: 0.9;
}
.lang-card p {
margin: 0;
color: #d9e7fb;
font-size: 14px;
white-space: pre-line;
}
.footer {
margin-top: 16px;
color: #99b4d8;
font-size: 12px;
text-align: center;
}
.footer-links {
margin-top: 6px;
display: inline-flex;
gap: 12px;
flex-wrap: wrap;
justify-content: center;
}
.footer-link {
color: #bcd5f8;
text-decoration: none;
border-bottom: 1px solid rgba(123, 170, 255, 0.4);
transition: color .2s ease, border-color .2s ease;
}
.footer-link:hover {
color: #e6f0ff;
border-color: rgba(123, 170, 255, 0.8);
}
@media (max-width: 860px) {
.grid { grid-template-columns: 1fr; }
.topbar {
flex-direction: column;
align-items: flex-start;
}
.support-btn {
width: 100%;
}
}
</style>
</head>
<body>
<main class="page">
<div class="topbar">
<div class="top-title"><span class="top-title-dot"></span>Support the Project</div>
<a class="support-btn" href="https://www.buymeacoffee.com/chahuadevm" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
</div>
<section class="hero">
<h1>Support the Project</h1>
<p>This page is available for everyone in the Chahuadev ecosystem. If these tools save your time, your support helps keep the project stable, maintained, and growing.</p>
</section>
<section class="grid">
<article class="lang-card">
<div class="lang-head"><div class="lang-code">EN</div><div class="lang-name">English</div></div>
<p>Building open-source tools to make developers' lives easier!
I'm the creator of Junk Sweeper and Dev Launcher. I believe in providing high-quality diagnostic tools completely for free.
If you find my projects helpful, you can support me here. Your contributions help cover the hidden costs of development (VPS, AI services, servers, and caffeine) and keep the chahuadev ecosystem growing. Cheers!</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">TH</div><div class="lang-name">Thai</div></div>
<p>เครื่องมือของ Chahuadev เปิดให้ใช้งานฟรี 100% ถ้าซอฟต์แวร์ตัวนี้ช่วยประหยัดเวลาการทำงานของคุณได้ คุณสามารถช่วยสมทบทุนค่าเซิร์ฟเวอร์และค่าไฟได้ ด้วยการ "เลี้ยงกาแฟผมสักแก้ว" เพื่อให้โปรเจกต์นี้พัฒนาต่อไปได้ครับ!</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">ES</div><div class="lang-name">Spanish</div></div>
<p>Estoy creando herramientas open-source para facilitar la vida de los desarrolladores.
Si mis proyectos te ayudan, puedes apoyarme aquí. Tu aporte cubre costos reales de desarrollo (VPS, servicios de IA, servidores y café) y ayuda a que el ecosistema de chahuadev siga creciendo.</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">FR</div><div class="lang-name">French</div></div>
<p>Je construis des outils open-source pour simplifier la vie des développeurs.
Si mes projets vous sont utiles, vous pouvez me soutenir ici. Vos contributions couvrent les coûts cachés du développement (VPS, services IA, serveurs et café) et permettent à l'écosystème chahuadev de continuer à grandir.</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">DE</div><div class="lang-name">German</div></div>
<p>Ich entwickle Open-Source-Tools, um den Alltag von Entwicklerinnen und Entwicklern zu erleichtern.
Wenn dir meine Projekte helfen, kannst du mich hier unterstützen. Dein Beitrag deckt versteckte Entwicklungskosten (VPS, KI-Dienste, Server und Kaffee) und hält das chahuadev-Ökosystem am Wachsen.</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">PT</div><div class="lang-name">Portuguese</div></div>
<p>Estou criando ferramentas open-source para facilitar a vida de desenvolvedores.
Se meus projetos ajudam você, pode me apoiar aqui. Sua contribuição cobre custos reais de desenvolvimento (VPS, serviços de IA, servidores e café) e mantém o ecossistema chahuadev em crescimento.</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">JA</div><div class="lang-name">Japanese</div></div>
<p>開発者の作業をもっと楽にするために、オープンソースツールを作っています。
プロジェクトが役に立ったら、ここから応援していただけるとうれしいです。ご支援は VPS、AI サービス、サーバー運用、そしてコーヒー代などの継続コストに使われ、chahuadev エコシステムの成長につながります。</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">ZH</div><div class="lang-name">Chinese</div></div>
<p>我正在构建开源工具,让开发者的工作更轻松。
如果这些项目对你有帮助,欢迎在这里支持我。你的支持将用于支付开发中的隐藏成本(VPS、AI 服务、服务器和咖啡),并帮助 chahuadev 生态持续成长。</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">KO</div><div class="lang-name">Korean</div></div>
<p>개발자의 일을 더 쉽게 만들기 위해 오픈소스 도구를 만들고 있습니다.
프로젝트가 도움이 되었다면 여기에서 후원해 주세요. 여러분의 후원은 VPS, AI 서비스, 서버 운영, 그리고 커피 같은 개발 비용을 충당하고 chahuadev 생��계의 성장을 돕습니다.</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">BN</div><div class="lang-name">Bengali</div></div>
<p>ডেভেলপারদের কাজ সহজ করতে আমি ওপেন-সোর্স টুল তৈরি করি।
আমার প্রজেক্টগুলো আপনার কাজে লাগলে এখানে সাপোর্ট করতে পারেন। আপনার সহায়তা VPS, AI সার্ভিস, সার্ভার এবং ডেভেলপমেন্টের লুকানো খরচ সামলাতে সাহায্য করে, আর chahuadev ইকোসিস্টেমকে এগিয়ে নেয়।</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">UR</div><div class="lang-name">Urdu</div></div>
<p>میں ڈویلپرز کی زندگی آسان بنانے کے لیے اوپن سورس ٹولز بناتا ہوں۔
اگر میرے پروجیکٹس آپ کے کام آئیں تو یہاں سپورٹ کریں۔ آپ کی مدد VPS، AI سروسز، سرورز اور دیگر اخراجات پورے کرنے میں مدد دیتی ہے، اور chahuadev ایکو سسٹم کو آگے بڑھاتی ہے۔</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">HI</div><div class="lang-name">Hindi</div></div>
<p>मैं डेवलपर्स की ज़िंदगी आसान बनाने के लिए ओपन-सोर्स टूल्स बनाता हूँ।
अगर मेरे प्रोजेक्ट आपके काम आते हैं, तो आप यहाँ सपोर्ट कर सकते हैं। आपका सहयोग VPS, AI सेवाओं, सर्वर और डेवलपमेंट की छिपी लागत को पूरा करने में मदद करता है और chahuadev इकोसिस्टम को आगे बढ़ाता है।</p>
</article>
<article class="lang-card">
<div class="lang-head"><div class="lang-code">AR</div><div class="lang-name">Arabic</div></div>
<p>أبني أدوات مفتوحة المصدر لتسهيل حياة المطورين.
إذا كانت مشاريعي مفيدة لك، يمكنك دعمي من هنا. مساهمتك تساعد في تغطية التكاليف الخفية للتطوير مثل VPS وخدمات الذكاء الاصطناعي والخوادم والقهوة، وتدعم نمو منظومة chahuadev.</p>
</article>
</section>
<div class="footer">
Chahuadev Support the Project
<div class="footer-links">
<a class="footer-link" href="https://www.chahuadev.com" target="_blank" rel="noopener noreferrer">Main Website</a>
<a class="footer-link" href="https://huggingface.co/chahuadev" target="_blank" rel="noopener noreferrer">Hugging Face</a>
</div>
</div>
</main>
<script>
(function () {
const ALLOWED_HOSTS = new Set([
'www.buymeacoffee.com',
'buymeacoffee.com',
'www.chahuadev.com',
'chahuadev.com',
'huggingface.co'
]);
function isAllowedExternalUrl(url) {
try {
const parsed = new URL(url);
return parsed.protocol === 'https:' && ALLOWED_HOSTS.has(parsed.hostname);
} catch (_) {
return false;
}
}
async function openViaBridge(url) {
const root = window.parent && window.parent !== window ? window.parent : window;
if (root.api && typeof root.api.openExternal === 'function') {
return root.api.openExternal(url);
}
if (root.electronAPI && typeof root.electronAPI.openExternal === 'function') {
return root.electronAPI.openExternal(url);
}
if (root.chahuadevHub && typeof root.chahuadevHub.openExternalUrl === 'function') {
return root.chahuadevHub.openExternalUrl(url);
}
if (root.chahuadev && typeof root.chahuadev.openExternalUrl === 'function') {
return root.chahuadev.openExternalUrl(url);
}
if (root.emojiCleanerAPI && typeof root.emojiCleanerAPI.openExternal === 'function') {
return root.emojiCleanerAPI.openExternal(url);
}
return false;
}
async function openExternalSafely(url) {
if (!isAllowedExternalUrl(url)) return;
try {
const result = await openViaBridge(url);
if (result === false) {
window.open(url, '_blank', 'noopener,noreferrer');
}
} catch (_) {
window.open(url, '_blank', 'noopener,noreferrer');
}
}
document.addEventListener('click', function (event) {
const anchor = event.target.closest('a[href]');
if (!anchor) return;
const href = anchor.getAttribute('href');
if (!href || !/^https?:\/\//i.test(href)) return;
event.preventDefault();
openExternalSafely(anchor.href);
});
})();
</script>
</body>
</html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859'use strict'
const { contextBridge, ipcRenderer } = require('electron')
function normalizeRunId(runId) {
return String(runId || '').trim()
}
function runScopedChannel(runId, topic) {
const rid = normalizeRunId(runId)
if (!rid) return ''
return `popup:${rid}:${topic}`
}
contextBridge.exposeInMainWorld('popupApi', {
isScoped: true,
popupKill: (runId) => ipcRenderer.invoke('popup-kill', { runId: normalizeRunId(runId) }),
popupResize: (payload) => ipcRenderer.invoke('popup-resize', {
...(payload || {}),
runId: normalizeRunId(payload && payload.runId)
}),
onMeta: (runId, cb) => {
const channel = runScopedChannel(runId, 'meta')
if (!channel || typeof cb !== 'function') return false
ipcRenderer.on(channel, (_, data) => cb(data))
return true
},
onOutput: (runId, cb) => {
const channel = runScopedChannel(runId, 'out')
if (!channel || typeof cb !== 'function') return false
ipcRenderer.on(channel, (_, data) => cb(data))
return true
},
onDone: (runId, cb) => {
const channel = runScopedChannel(runId, 'done')
if (!channel || typeof cb !== 'function') return false
ipcRenderer.on(channel, (_, code) => cb(code))
return true
},
onMetrics: (runId, cb) => {
const channel = runScopedChannel(runId, 'metrics')
if (!channel || typeof cb !== 'function') return false
ipcRenderer.on(channel, (_, metrics) => cb(metrics))
return true
},
offAll: () => {
// Keep this function backward-compatible; explicit per-run cleanup is preferred.
return true
},
offRun: (runId) => {
const rid = normalizeRunId(runId)
if (!rid) return false
ipcRenderer.removeAllListeners(runScopedChannel(rid, 'meta'))
ipcRenderer.removeAllListeners(runScopedChannel(rid, 'out'))
ipcRenderer.removeAllListeners(runScopedChannel(rid, 'done'))
ipcRenderer.removeAllListeners(runScopedChannel(rid, 'metrics'))
return true
}
})4 unmodified lines567891011121314151617181920212223242526272829304 unmodified linescontextBridge.exposeInMainWorld('api', {getProject: () => ipcRenderer.invoke('get-project'),runCmd: (opts) => ipcRenderer.invoke('run-cmd', opts),killProc: () => ipcRenderer.invoke('kill-proc'),resizeProcPty: (size) => ipcRenderer.invoke('resize-proc-pty', size),openExternal: (url) => ipcRenderer.invoke('open-external', url),r2GetConfigStatus: () => ipcRenderer.invoke('r2-get-config-status'),r2SaveConfig: (cfg) => ipcRenderer.invoke('r2-save-config', cfg),r2TestConfig: (cfg) => ipcRenderer.invoke('r2-test-config', cfg),r2ClearConfig: () => ipcRenderer.invoke('r2-clear-config'),r2SuggestTarget: () => ipcRenderer.invoke('r2-suggest-target'),r2UploadDist: (o) => ipcRenderer.invoke('r2-upload-dist', o),selectProjectFolder: (mode) => ipcRenderer.invoke('select-project-folder', mode),useLauncherProject: () => ipcRenderer.invoke('use-launcher-project'),onOutput: (cb) => ipcRenderer.on('proc-out', (_, data) => cb(data)),onDone: (cb) => ipcRenderer.on('proc-done', (_, code) => cb(code)),onProjectChanged: (cb) => ipcRenderer.on('project-root-changed', (_, data) => cb(data)),onProjectSelectionBlocked: (cb) => ipcRenderer.on('project-selection-blocked', (_, data) => cb(data)),offAll: () => {ipcRenderer.removeAllListeners('proc-out')ipcRenderer.removeAllListeners('proc-done')ipcRenderer.removeAllListeners('project-root-changed')ipcRenderer.removeAllListeners('project-selection-blocked')}})4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464 unmodified linescontextBridge.exposeInMainWorld('api', {getProject: () => ipcRenderer.invoke('get-project'),runCmd: (opts) => ipcRenderer.invoke('run-cmd', opts),runCmdPopup: (opts) => ipcRenderer.invoke('run-cmd-popup', opts),openDevToolsForCommand: (opts) => ipcRenderer.invoke('open-devtools-for-command', opts),openMainDevTools: () => ipcRenderer.invoke('open-main-devtools'),openPopupDevTools: () => ipcRenderer.invoke('open-popup-devtools'),getDevSecurityStatus: () => ipcRenderer.invoke('get-dev-security-status'),killProc: () => ipcRenderer.invoke('kill-proc'),resizeProcPty: (size) => ipcRenderer.invoke('resize-proc-pty', size),openExternal: (url) => ipcRenderer.invoke('open-external', url),selectProjectFolder: (mode) => ipcRenderer.invoke('select-project-folder', mode),useLauncherProject: () => ipcRenderer.invoke('use-launcher-project'),onOutput: (cb) => ipcRenderer.on('proc-out', (_, data) => cb(data)),onDone: (cb) => ipcRenderer.on('proc-done', (_, code) => cb(code)),onPopupRunState: (cb) => ipcRenderer.on('popup-run-state', (_, data) => cb(data)),onProjectChanged: (cb) => ipcRenderer.on('project-root-changed', (_, data) => cb(data)),onProjectSelectionBlocked: (cb) => ipcRenderer.on('project-selection-blocked', (_, data) => cb(data)),offAll: () => {ipcRenderer.removeAllListeners('proc-out')ipcRenderer.removeAllListeners('proc-done')ipcRenderer.removeAllListeners('popup-run-state')ipcRenderer.removeAllListeners('project-root-changed')ipcRenderer.removeAllListeners('project-selection-blocked')}})contextBridge.exposeInMainWorld('popupApi', {popupKill: (runId) => ipcRenderer.invoke('popup-kill', { runId }),popupResize: (payload) => ipcRenderer.invoke('popup-resize', payload),onMeta: (cb) => ipcRenderer.on('popup-meta', (_, data) => cb(data)),onOutput: (cb) => ipcRenderer.on('popup-out', (_, data) => cb(data)),onDone: (cb) => ipcRenderer.on('popup-done', (_, code) => cb(code)),onMetrics: (cb) => ipcRenderer.on('popup-metrics', (_, metrics) => cb(metrics)),offAll: () => {ipcRenderer.removeAllListeners('popup-meta')ipcRenderer.removeAllListeners('popup-out')ipcRenderer.removeAllListeners('popup-done')ipcRenderer.removeAllListeners('popup-metrics')}})
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115'use strict'
/**
* platform-darwin.js — macOS-specific runtime adapter
* Loaded exclusively when process.platform === 'darwin'
*/
const path = require('path')
const os = require('os')
const PLATFORM = 'darwin'
// ── Writable path candidates for app userData ─────────────────────────────────
function getWritableCandidates(appDirName) {
const candidates = []
candidates.push(path.join(os.homedir(), 'Library', 'Application Support', 'Chahuadev', appDirName))
candidates.push(path.join(os.tmpdir(), appDirName))
return candidates
}
// ── Command name normalization ────────────────────────────────────────────────
// macOS: no .cmd suffix — npm/npx/pnpm/yarn are native shell scripts.
function normalizeExecName(cmd) {
return String(cmd || '').trim()
}
// ── Shell wrapping ────────────────────────────────────────────────────────────
// macOS commands run directly via node-pty — no cmd.exe-style wrapping needed.
function shouldUseShell(cmd) { // eslint-disable-line no-unused-vars
return false
}
// Not called on macOS (shouldUseShell always false), but satisfies interface.
function buildShellSpawn(cmd, args) {
return { file: cmd, args: args || [] }
}
// ── node-pty spawn extra options ──────────────────────────────────────────────
// useConpty is Windows-only. macOS uses standard POSIX PTY.
function getPtySpawnOptions() {
return {}
}
// ── Node.js runtime path ──────────────────────────────────────────────────────
function resolveNodeRuntime() {
return 'node'
}
// ── Linux/macOS build command ─────────────────────────────────────────────────
function _quoteBash(s) {
return `'${String(s || '').replace(/'/g, `'"'"'`)}'`
}
function rewriteLinuxBuildCommand(cwd) {
const script = [
'set -euo pipefail',
`cd ${_quoteBash(cwd)}`,
'npm install',
'if npm run | grep -q "build:linux"; then npm run build:linux; else npx electron-builder --linux AppImage --x64 --publish never; fi'
].join('; ')
return {
cmd: 'bash',
args: ['-lc', script],
rewriteInfo: {
applied: true,
kind: 'launcher-linux-build-inline-bash',
targetProjectPath: cwd
}
}
}
// ── Protected OS path bases ───────────────────────────────────────────────────
// Base list covers standard macOS paths.
// We also scan /Volumes at runtime to protect externally mounted volumes
// (Time Machine disks, network shares, disk images, external drives, etc.)
function _readMacVolumes() {
try {
const fs = require('fs')
// /Volumes contains all mounted filesystems; the boot volume is a symlink → '/'
// Filter out symlinks to avoid double-protecting the root partition.
return fs.readdirSync('/Volumes').reduce((acc, name) => {
const full = `/Volumes/${name}`
try {
const stat = fs.lstatSync(full)
if (!stat.isSymbolicLink()) acc.push(full)
} catch { /* ignore vanished entries */ }
return acc
}, [])
} catch {
return []
}
}
function getProtectedPathBases() {
const homeDir = os.homedir()
return [
'/System', '/Library', '/Applications',
'/private', '/usr', '/bin', '/sbin',
'/var', '/etc', '/opt',
path.join(homeDir, 'Library'),
..._readMacVolumes()
]
}
module.exports = {
PLATFORM,
getWritableCandidates,
normalizeExecName,
shouldUseShell,
buildShellSpawn,
getPtySpawnOptions,
resolveNodeRuntime,
rewriteLinuxBuildCommand,
getProtectedPathBases
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128'use strict'
/**
* platform-linux.js — Linux-specific runtime adapter
* Loaded exclusively when process.platform === 'linux'
*/
const path = require('path')
const os = require('os')
const PLATFORM = 'linux'
// ── Writable path candidates for app userData ─────────────────────────────────
function getWritableCandidates(appDirName) {
const candidates = []
const xdgData = process.env.XDG_DATA_HOME
if (xdgData) {
candidates.push(path.join(xdgData, 'chahuadev', appDirName))
}
candidates.push(path.join(os.homedir(), '.local', 'share', 'chahuadev', appDirName))
candidates.push(path.join(os.tmpdir(), appDirName))
return candidates
}
// ── Command name normalization ────────────────────────────────────────────────
// Linux: no .cmd suffix needed — npm/npx/pnpm/yarn are native shell scripts.
function normalizeExecName(cmd) {
return String(cmd || '').trim()
}
// ── Shell wrapping ────────────────────────────────────────────────────────────
// Linux commands run directly via node-pty — no cmd.exe-style wrapping needed.
function shouldUseShell(cmd) { // eslint-disable-line no-unused-vars
return false
}
// Not called on Linux (shouldUseShell always false), but satisfies interface.
function buildShellSpawn(cmd, args) {
return { file: cmd, args: args || [] }
}
// ── node-pty spawn extra options ──────────────────────────────────────────────
// useConpty is a Windows-only (ConPTY) option. On Linux use standard PTY.
function getPtySpawnOptions() {
return {}
}
// ── Node.js runtime path ──────────────────────────────────────────────────────
function resolveNodeRuntime() {
return 'node'
}
// ── Linux build command ───────────────────────────────────────────────────────
// On Linux the AppImage runs natively — no WSL bridge required.
function _quoteBash(s) {
return `'${String(s || '').replace(/'/g, `'"'"'`)}'`
}
function rewriteLinuxBuildCommand(cwd) {
const script = [
'set -euo pipefail',
`cd ${_quoteBash(cwd)}`,
'npm install',
'if npm run | grep -q "build:linux"; then npm run build:linux; else npx electron-builder --linux AppImage --x64 --publish never; fi'
].join('; ')
return {
cmd: 'bash',
args: ['-lc', script],
rewriteInfo: {
applied: true,
kind: 'launcher-linux-build-inline-bash',
targetProjectPath: cwd
}
}
}
// ── Protected OS path bases ───────────────────────────────────────────────────
// Base list covers standard FHS paths.
// We also scan /proc/mounts at runtime to catch non-standard system-level
// mount points (e.g. bind mounts, external drives at /mnt/*, /media/*,
// or custom rootfs at depth-1 like /data, /storage).
// Only "system-ish" mounts are protected — /home and /tmp are intentionally left open.
const _OPEN_ROOTS = new Set(['home', 'tmp', 'root'])
function _readMountRoots() {
try {
const fs = require('fs')
const lines = fs.readFileSync('/proc/mounts', 'utf8').split('\n')
const extra = new Set()
for (const line of lines) {
const mountPoint = line.split(' ')[1]
if (!mountPoint || mountPoint === '/') continue
const parts = mountPoint.split('/').filter(Boolean)
// Protect any depth-1 non-user mount (e.g. /data, /storage)
if (parts.length === 1 && !_OPEN_ROOTS.has(parts[0])) {
extra.add(mountPoint)
}
// Protect anything under /mnt/* or /media/* (external drives, images)
if (parts.length === 2 && (parts[0] === 'mnt' || parts[0] === 'media')) {
extra.add(mountPoint)
}
}
return [...extra]
} catch {
return []
}
}
function getProtectedPathBases() {
return [
'/bin', '/sbin', '/lib', '/lib64',
'/usr', '/var', '/etc', '/boot',
'/proc', '/sys', '/dev', '/run', '/snap',
..._readMountRoots()
]
}
module.exports = {
PLATFORM,
getWritableCandidates,
normalizeExecName,
shouldUseShell,
buildShellSpawn,
getPtySpawnOptions,
resolveNodeRuntime,
rewriteLinuxBuildCommand,
getProtectedPathBases
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157'use strict'
/**
* platform-win32.js — Windows-specific runtime adapter
* Loaded exclusively when process.platform === 'win32'
*/
const path = require('path')
const os = require('os')
const { spawnSync } = require('child_process')
const PLATFORM = 'win32'
// ── Writable path candidates for app userData ─────────────────────────────────
function getWritableCandidates(appDirName) {
const candidates = []
const localAppData = process.env.LOCALAPPDATA
if (localAppData) {
candidates.push(path.join(localAppData, 'Chahuadev', appDirName))
}
candidates.push(path.join(os.tmpdir(), appDirName))
return candidates
}
// ── Command name normalization ────────────────────────────────────────────────
// Windows requires .cmd suffix for package manager shims in PATH.
function normalizeExecName(cmd) {
const c = String(cmd || '').trim()
if (!c) return c
const lc = c.toLowerCase()
if (lc === 'npm') return 'npm.cmd'
if (lc === 'npx') return 'npx.cmd'
if (lc === 'pnpm') return 'pnpm.cmd'
if (lc === 'yarn') return 'yarn.cmd'
return c
}
// ── Shell wrapping (for .bat / .cmd files) ────────────────────────────────────
function shouldUseShell(cmd) {
const c = String(cmd || '').toLowerCase()
return c.endsWith('.bat') || c.endsWith('.cmd')
}
function quoteArg(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 buildCmdLine(cmd, args) {
return [cmd, ...(args || [])].map(quoteArg).join(' ')
}
// Returns { file, args } ready for node-pty.spawn()
function buildShellSpawn(cmd, args) {
const comspec = process.env.COMSPEC || 'cmd.exe'
return {
file: comspec,
args: ['/d', '/s', '/c', buildCmdLine(cmd, args)]
}
}
// ── node-pty spawn extra options ──────────────────────────────────────────────
// useConpty enables Windows 10+ ConPTY backend — required on Windows for
// proper ANSI colour support in cmd.exe / PowerShell.
function getPtySpawnOptions() {
return { useConpty: true }
}
// ── Node.js runtime path ──────────────────────────────────────────────────────
function resolveNodeRuntime() {
try {
const r = spawnSync('where', ['node'], {
windowsHide: true,
encoding: 'utf8',
shell: false
})
if ((r.status ?? 1) === 0) {
const first = String(r.stdout || '')
.split(/\r?\n/)
.map(x => x.trim())
.find(Boolean)
if (first) return first
}
} catch (_e) { /* where.exe failed or node not found; fall through to default */ }
return 'node.exe'
}
// ── Linux build command rewrite (via WSL) ─────────────────────────────────────
function _quoteBash(s) {
return `'${String(s || '').replace(/'/g, `'"'"'`)}'`
}
function windowsPathToWsl(inputPath) {
const raw = String(inputPath || '')
const win = raw.replace(/\//g, '\\')
const m = win.match(/^([a-zA-Z]):\\(.*)$/)
if (!m) return raw.replace(/\\/g, '/')
const drive = String(m[1] || '').toLowerCase()
const tail = String(m[2] || '').replace(/\\/g, '/')
return `/mnt/${drive}/${tail}`
}
function rewriteLinuxBuildCommand(cwd) {
const wslTarget = windowsPathToWsl(cwd)
const script = [
'set -euo pipefail',
`cd ${_quoteBash(wslTarget)}`,
'npm install',
'if npm run | grep -q "build:linux"; then npm run build:linux; else npx electron-builder --linux AppImage --x64 --publish never; fi'
].join('; ')
return {
cmd: 'wsl.exe',
args: ['bash', '-lc', script],
rewriteInfo: {
applied: true,
kind: 'launcher-linux-build-inline-wsl',
targetProjectPath: cwd
}
}
}
// ── Protected OS path bases ───────────────────────────────────────────────────
function getProtectedPathBases() {
const homeDir = os.homedir()
const systemDrive = String(process.env.SystemDrive || 'C:').toUpperCase()
const driveRoot = `${systemDrive}\\`
return [
path.join(driveRoot, 'Windows'),
path.join(driveRoot, 'Program Files'),
path.join(driveRoot, 'Program Files (x86)'),
path.join(driveRoot, 'ProgramData'),
path.join(driveRoot, 'Users'),
path.join(driveRoot, 'PerfLogs'),
path.join(driveRoot, 'Recovery'),
path.join(driveRoot, 'System Volume Information'),
path.join(driveRoot, '$Recycle.Bin'),
path.join(homeDir, 'AppData'),
path.join(homeDir, 'Local Settings')
]
}
module.exports = {
PLATFORM,
getWritableCandidates,
normalizeExecName,
shouldUseShell,
buildShellSpawn,
getPtySpawnOptions,
resolveNodeRuntime,
rewriteLinuxBuildCommand,
getProtectedPathBases,
// Exported for tests / diagnostics
windowsPathToWsl,
quoteArg,
buildCmdLine
}12345678910111213141516171819202122232425'use strict'
/**
* platform.js — OS detector and platform adapter loader
*
* Returns the platform-specific adapter for the current OS.
* Each adapter exposes an identical interface so main.js can call
* platform.xxx() without any process.platform conditionals.
*
* Interface exported by every adapter:
* PLATFORM — string: 'win32' | 'linux' | 'darwin'
* getWritableCandidates(name) — writable userData path candidates
* normalizeExecName(cmd) — add .cmd on Windows, no-op elsewhere
* shouldUseShell(cmd) — true only for .bat/.cmd on Windows
* buildShellSpawn(cmd, args) — { file, args } for shell-wrapped spawn
* getPtySpawnOptions() — extra options for node-pty.spawn()
* resolveNodeRuntime() — absolute path / name of node executable
* rewriteLinuxBuildCommand(cwd) — { cmd, args, rewriteInfo }
* getProtectedPathBases() — OS-specific protected directory list
*/
const p = process.platform
if (p === 'win32') module.exports = require('./platform-win32')
else if (p === 'darwin') module.exports = require('./platform-darwin')
else module.exports = require('./platform-linux')133 unmodified lines134135136137138139140141142143144133 unmodified linesconst targets = []if (enableBytecode) {let compiled = 0for (const rel of ROOT_TARGETS) {if (await compileRootToBytecode(appDir, rel)) {compiled += 1console.log(`[bytecode] ${rel} -> ${path.parse(rel).name}.jsc`)}}console.log(`[bytecode] completed (${compiled} files)`)133 unmodified lines134135136137138139140141142143144145133 unmodified linesconst targets = []if (enableBytecode) {const bytecodeResults = await Promise.all(ROOT_TARGETS.map(rel => compileRootToBytecode(appDir, rel)))let compiled = 0for (const [i, ok] of bytecodeResults.entries()) {if (ok) {compiled += 1console.log(`[bytecode] ${ROOT_TARGETS[i]} -> ${path.parse(ROOT_TARGETS[i]).name}.jsc`)}}console.log(`[bytecode] completed (${compiled} files)`)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136'use strict'const fs = require('fs')const path = require('path')const { spawn } = require('child_process')const bytenode = require('bytenode')const FILES_TO_COMPILE = ['main.js', 'preload.js']const backups = new Map()const generatedJsc = new Set()let restoring = falseasync function backupAndCompile() {for (const file of FILES_TO_COMPILE) {const absPath = path.join(process.cwd(), file)if (!fs.existsSync(absPath)) continueconst backupPath = `${absPath}.backup`fs.copyFileSync(absPath, backupPath)backups.set(absPath, backupPath)const parsed = path.parse(absPath)const jscPath = path.join(parsed.dir, `${parsed.name}.jsc`)const existedBefore = fs.existsSync(jscPath)await bytenode.compileFile({filename: absPath,output: jscPath,electron: true,compileAsModule: true})if (!existedBefore) {generatedJsc.add(jscPath)}console.log(`[V8 Builder] Compiled ${file} -> ${path.basename(jscPath)}`)const relBase = path.parse(file).nameconst requireLine = file === 'main.js'? `module.exports = require('./${relBase}.jsc')`: `require('./${relBase}.jsc')`const loaderCode = ["'use strict'","require('bytenode')",requireLine,''].join('\n')fs.writeFileSync(absPath, loaderCode, 'utf8')}}function restoreFiles() {if (restoring) returnrestoring = trueconsole.log('\n[V8 Builder] Restoring original source files...')for (const [absPath, backupPath] of backups) {try {if (fs.existsSync(backupPath)) {fs.copyFileSync(backupPath, absPath)fs.unlinkSync(backupPath)console.log(`[V8 Builder] Restored ${path.basename(absPath)}`)}} catch (err) {console.error(`[V8 Builder] restore failed for ${path.basename(absPath)}: ${err.message}`)}}for (const jscPath of generatedJsc) {try {if (fs.existsSync(jscPath)) {fs.unlinkSync(jscPath)}} catch (err) {console.error(`[V8 Builder] cleanup failed for ${path.basename(jscPath)}: ${err.message}`)}}}process.on('SIGINT', () => {restoreFiles()process.exit(1)})process.on('uncaughtException', (err) => {console.error(err)restoreFiles()process.exit(1)})async function run() {try {console.log('=== Starting V8 Compilation and Build ===')await backupAndCompile()const builderCli = require.resolve('electron-builder/out/cli/cli.js')const extraArgs = process.argv.slice(2)const args = [builderCli,'--win','portable','--x64','--config.compression=maximum','--config.npmRebuild=false',...extraArgs]const child = spawn(process.execPath, args, {stdio: 'inherit',windowsHide: true,shell: false,env: {...process.env}})child.on('exit', (code) => {restoreFiles()process.exit(code ?? 1)})child.on('error', (err) => {console.error(`[V8 Builder] failed: ${err.message}`)restoreFiles()process.exit(1)})} catch (err) {console.error(`[V8 Builder] prebuild failed: ${err.message}`)restoreFiles()process.exit(1)}}run()12345678910111213141516171819202122232425'use strict'const path = require('path')const { spawn } = require('child_process')const externalScript = path.join(__dirname, 'build-v8-external.js')const forwardedArgs = process.argv.slice(2)const child = spawn(process.execPath, [externalScript, ...forwardedArgs], {stdio: 'inherit',shell: false,windowsHide: true,env: {...process.env}})child.on('error', (err) => {console.error(`[Launcher V8] Failed to start external builder: ${err && err.message ? err.message : err}`)process.exit(1)})child.on('exit', (code) => {process.exit(code ?? 1)})
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265'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)
})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162* { box-sizing: border-box; }
:root {
--glass: rgba(3, 20, 34, 0.88);
--glass-strong: rgba(2, 12, 21, 0.92);
--line: rgba(91, 169, 255, 0.28);
--text: #d3ecff;
--subtle: #85abd4;
--ok: #39d98a;
--err: #f16f7d;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family: "Segoe UI", "Trebuchet MS", sans-serif;
color: var(--text);
background:
radial-gradient(110% 130% at 10% 5%, rgba(38, 125, 220, 0.22), transparent 45%),
radial-gradient(95% 120% at 90% 90%, rgba(5, 43, 82, 0.35), transparent 48%),
#010812;
}
.window-shell {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background: linear-gradient(165deg, var(--glass), var(--glass-strong));
border: 1px solid var(--line);
}
.window-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
background: rgba(1, 16, 29, 0.74);
}
.title-wrap {
min-width: 0;
}
.title {
font-size: 13px;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.meta {
margin-top: 2px;
font-size: 11px;
color: var(--subtle);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.kill-btn {
border: 1px solid rgba(241, 111, 125, 0.5);
background: rgba(188, 46, 64, 0.2);
color: #ffd8dd;
padding: 6px 10px;
font: inherit;
font-size: 12px;
border-radius: 7px;
cursor: pointer;
}
.kill-btn:hover {
background: rgba(215, 60, 82, 0.4);
}
.terminal-wrap {
position: relative;
flex: 1;
min-height: 0;
padding: 10px 10px 8px;
overflow: hidden;
}
#terminal {
width: 100%;
height: 100%;
border: 1px solid rgba(95, 160, 255, 0.22);
border-radius: 10px;
overflow: hidden;
background: rgba(2, 10, 18, 0.82);
}
.monitor-card {
position: absolute;
right: 18px;
bottom: 18px;
min-width: 126px;
padding: 8px 10px;
border-radius: 8px;
border: 1px solid rgba(94, 173, 255, 0.34);
background: rgba(2, 17, 30, 0.82);
box-shadow: 0 8px 18px rgba(0, 0, 0, 0.35);
pointer-events: none;
}
.monitor-label {
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: #7eb7f1;
}
.monitor-grid {
margin-top: 5px;
display: grid;
grid-template-columns: 1fr auto;
gap: 3px 8px;
font-size: 11px;
}
.monitor-grid span {
color: #8ab4de;
}
.monitor-grid strong {
color: #e5f4ff;
}
.window-foot {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 12px;
border-top: 1px solid var(--line);
background: rgba(1, 16, 29, 0.7);
font-size: 12px;
color: var(--subtle);
}
#status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--ok);
box-shadow: 0 0 10px rgba(57, 217, 138, 0.6);
}
#status-dot.error {
background: var(--err);
box-shadow: 0 0 10px rgba(241, 111, 125, 0.65);
}
.xterm,
.xterm * {
user-select: text !important;
}1234567891011121314151617181920212223242526272829303132333435363738394041424344<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'">
<title>Sandbox Terminal</title>
<link rel="stylesheet" href="../node_modules/@xterm/xterm/css/xterm.css">
<link rel="stylesheet" href="./popup-terminal.css">
</head>
<body>
<div class="window-shell">
<header class="window-head">
<div class="title-wrap">
<div class="title" id="run-title">Sandbox Terminal</div>
<div class="meta" id="run-meta"></div>
</div>
<div class="head-actions">
<button id="btn-kill" class="kill-btn" type="button">Kill</button>
</div>
</header>
<main class="terminal-wrap">
<div id="terminal"></div>
<div class="monitor-card" id="monitor-card">
<div class="monitor-label">System</div>
<div class="monitor-grid">
<span>CPU</span><strong id="metric-cpu">--%</strong>
<span>RAM</span><strong id="metric-ram">--%</strong>
</div>
</div>
</main>
<footer class="window-foot">
<span id="status-dot"></span>
<span id="status-text">Running</span>
</footer>
</div>
<script src="../node_modules/@xterm/xterm/lib/xterm.js"></script>
<script src="../node_modules/@xterm/addon-fit/lib/addon-fit.js"></script>
<script src="./popup-terminal.js"></script>
</body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196'use strict'
;(() => {
const popupApi = window.popupApi
const runId = decodeURIComponent(String(window.location.hash || '').replace(/^#/, ''))
const hasBridge = !!(popupApi && typeof popupApi.onMeta === 'function' && typeof popupApi.onOutput === 'function')
// contextBridge wraps every function and strips .length, so .length >= 2 is ALWAYS false.
// Use an explicit `isScoped` flag set by popup-preload.js instead.
const scopedBridge = !!(popupApi && popupApi.isScoped === true)
const titleEl = document.getElementById('run-title')
const metaEl = document.getElementById('run-meta')
const statusDot = document.getElementById('status-dot')
const statusText = document.getElementById('status-text')
const metricCpu = document.getElementById('metric-cpu')
const metricRam = document.getElementById('metric-ram')
const killBtn = document.getElementById('btn-kill')
const termHost = document.getElementById('terminal')
let term = null
let fitAddon = null
let _termMousedownHandler = null
function initTerminal() {
if (!window.Terminal || !termHost) return
const FitCtor = window.FitAddon && window.FitAddon.FitAddon ? window.FitAddon.FitAddon : null
term = new window.Terminal({
cursorBlink: false,
disableStdin: true,
// Keep raw stream untouched and let xterm handle EOL visually.
convertEol: true,
scrollback: 100000,
fontFamily: 'Cascadia Code, Consolas, monospace',
fontSize: 12,
theme: {
background: '#020a12',
foreground: '#d9f2ff',
red: '#ff7785',
green: '#39d98a',
yellow: '#f8d77a',
blue: '#6eb8ff',
magenta: '#c08dff',
cyan: '#7ae7ff',
white: '#f4fcff'
}
})
if (FitCtor) {
fitAddon = new FitCtor()
term.loadAddon(fitAddon)
}
term.open(termHost)
if (fitAddon) fitAddon.fit()
notifyResize()
}
function notifyResize() {
if (!term || !popupApi) return
if (scopedBridge && !runId) return
const cols = Number(term.cols || 0)
const rows = Number(term.rows || 0)
if (!cols || !rows) return
if (scopedBridge) {
popupApi.popupResize({ runId, cols, rows })
return
}
popupApi.popupResize({ cols, rows })
}
function appendOutput(text) {
if (!term || typeof text !== 'string' || text.length === 0) return
term.write(text)
term.scrollToBottom()
}
async function copyTermSelection() {
if (!term || !term.hasSelection()) return false
const selected = term.getSelection()
if (!selected) return false
try {
if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
await navigator.clipboard.writeText(selected)
return true
}
const ta = document.createElement('textarea')
ta.value = selected
ta.setAttribute('readonly', 'readonly')
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.focus()
ta.select()
const ok = document.execCommand('copy')
document.body.removeChild(ta)
return !!ok
} catch {
return false
}
}
function installShortcuts() {
if (termHost) {
_termMousedownHandler = () => {
if (term && typeof term.focus === 'function') term.focus()
}
termHost.addEventListener('mousedown', _termMousedownHandler)
}
document.addEventListener('keydown', async (e) => {
const isCtrlOrMeta = e.ctrlKey || e.metaKey
if (!isCtrlOrMeta) return
const key = String(e.key || '').toLowerCase()
if (key === 'a') {
if (!term) return
e.preventDefault()
term.selectAll()
return
}
if (key === 'c') {
if (!term || !term.hasSelection()) return
e.preventDefault()
await copyTermSelection()
return
}
})
}
function markDone(code) {
const ok = Number(code) === 0
statusDot.classList.toggle('error', !ok)
statusText.textContent = ok ? 'Done' : `Exited (${code})`
killBtn.disabled = true
}
killBtn.addEventListener('click', async () => {
if (!popupApi) return
await popupApi.popupKill(runId)
})
window.addEventListener('resize', () => {
if (fitAddon) fitAddon.fit()
notifyResize()
})
if (!hasBridge) {
throw new Error('Popup bridge is unavailable')
}
if (scopedBridge && !runId) {
throw new Error('Popup runId is missing for scoped bridge')
}
const bindMeta = scopedBridge
? (cb) => popupApi.onMeta(runId, cb)
: (cb) => popupApi.onMeta(cb)
const bindOutput = scopedBridge
? (cb) => popupApi.onOutput(runId, cb)
: (cb) => popupApi.onOutput(cb)
const bindDone = scopedBridge
? (cb) => popupApi.onDone(runId, cb)
: (cb) => popupApi.onDone(cb)
const bindMetrics = scopedBridge
? (cb) => popupApi.onMetrics(runId, cb)
: (cb) => popupApi.onMetrics(cb)
bindMeta((meta) => {
if (!meta) return
titleEl.textContent = meta.title || 'Sandbox Terminal'
const mode = meta.streamMode ? ` [${meta.streamMode}]` : ''
metaEl.textContent = `${meta.commandLine || ''}${mode}`
})
bindOutput((data) => appendOutput(data))
bindDone((code) => markDone(code))
bindMetrics((metrics) => {
const cpu = metrics && Number.isFinite(Number(metrics.cpuPercent)) ? Number(metrics.cpuPercent).toFixed(1) : '--'
const ram = metrics && Number.isFinite(Number(metrics.memPercent)) ? Number(metrics.memPercent).toFixed(1) : '--'
metricCpu.textContent = `${cpu}%`
metricRam.textContent = `${ram}%`
})
window.addEventListener('beforeunload', () => {
if (_termMousedownHandler && termHost) {
termHost.removeEventListener('mousedown', _termMousedownHandler)
}
if (popupApi && typeof popupApi.offRun === 'function' && runId) {
popupApi.offRun(runId)
}
}, { once: true })
initTerminal()
installShortcuts()
})()100 unmodified lines101102103104105100 unmodified linesif (parent && typeof parent.r2OpenUpload === 'function') parent.r2OpenUpload()})setInterval(refresh, 3500)refresh()100 unmodified lines101102103104105106100 unmodified linesif (parent && typeof parent.r2OpenUpload === 'function') parent.r2OpenUpload()})const _refreshTimer = setInterval(refresh, 3500)window.addEventListener('beforeunload', () => clearInterval(_refreshTimer), { once: true })refresh()
15 unmodified lines161718192021222324252612 unmodified lines394041424344454647484950515217 unmodified lines707172737475767778798 unmodified lines8889909192939495969798991001011 unmodified line10310410510610710810952 unmodified lines1621631641651661671681 unmodified line17017117217317417530 unmodified lines206207208209210211212213214146 unmodified lines36136236336436536636736836937037137237337437537637715 unmodified lines39339439539639739811 unmodified lines41041141241341441585 unmodified lines50150250350450550614 unmodified lines5215225235245255266 unmodified lines5335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915924 unmodified lines5975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306312 unmodified lines6346356366376386396404 unmodified lines64564664764864965065165265365465565665765865966066166224 unmodified lines6876886896906916926 unmodified lines69970070170270370415 unmodified linesfunction showPage(name) {document.getElementById('page-home').classList.toggle('active', name === 'home')document.getElementById('page-run').classList.toggle('active', name === 'run')document.getElementById('page-r2').classList.toggle('active', name === 'r2')document.getElementById('page-support').classList.toggle('active', name === 'support')document.getElementById('tab-home').classList.toggle('active', name === 'home')document.getElementById('tab-run').classList.toggle('active', name === 'run')document.getElementById('tab-r2').classList.toggle('active', name === 'r2')document.getElementById('support-btn').classList.toggle('active', name === 'support')if (name === 'run') {12 unmodified lines// iframe pages call these parent functionswindow.showView = showPagewindow.r2OpenConfig = configureR2window.r2OpenUpload = uploadDistToR2window.r2OpenCloudflare = () => api.openExternal('https://dash.cloudflare.com/?to=/:account/r2')window.r2GetStatus = () => api.r2GetConfigStatus()window.r2Logout = () => api.r2ClearConfig()// ── State ─────────────────────────────────────────────────────────────────────let runningBtn = nullconst GROUP_COLOR_CLASS = {expo: 'group-color-expo',android: 'group-color-android',17 unmodified linesconst elDot = document.getElementById('status-dot')const elStatus = document.getElementById('status-text')const elRunning = document.getElementById('running-label')let term = nulllet fitAddon = nulllet resizeObserver = nulllet terminalInitialized = falsefunction ensureTerminalInitialized() {if (terminalInitialized) return8 unmodified linesreturn b.viewportY >= b.baseY}function normalizeForReadableTerminal(raw) {return String(raw || '')}function colorizeForDisplay(raw) {return String(raw || '')}function initTerminal() {if (!elOutput || !window.Terminal) return1 unmodified lineterm = new window.Terminal({cursorBlink: false,disableStdin: true,convertEol: false,scrollback: 100000,fontFamily: 'Cascadia Code, Consolas, monospace',fontSize: 12,52 unmodified linesconst selected = term.getSelection()if (!selected) return falsetry {await navigator.clipboard.writeText(selected)return true} catch {return false1 unmodified line}function installTerminalShortcuts() {document.addEventListener('keydown', async (e) => {const isCtrlOrMeta = e.ctrlKey || e.metaKeyif (!isCtrlOrMeta) return30 unmodified linesconst r2UploadBackdrop = document.getElementById('r2-upload-backdrop')function openModal(el) {el.classList.add('show')}function closeModal(el) {el.classList.remove('show')}146 unmodified lines// ── ANSI → HTML ───────────────────────────────────────────────────────────────// ── Terminal output ───────────────────────────────────────────────────────────function appendOutput(text) {const raw = normalizeForReadableTerminal(text)if (!raw) returnif (term) {const shouldFollow = isTermNearBottom()term.write(colorizeForDisplay(raw))if (shouldFollow) term.scrollToBottom()return}elOutput.appendChild(document.createTextNode(raw))elOutput.scrollTop = elOutput.scrollHeight}15 unmodified linesreturn false}function clearR2UiValues() {const ids = ['r2-account-id', 'r2-bucket', 'r2-access-key', 'r2-secret-key', 'r2-target-folder']ids.forEach(id => {11 unmodified linesif (list) list.innerHTML = ''}function buildCommandHint(cmdDef, group, typeInfo) {const label = String(cmdDef?.label || '').toLowerCase()const cmdLine = [cmdDef.cmd, ...(cmdDef.args || [])].join(' ')85 unmodified lines// ── Render command groups ─────────────────────────────────────────────────────function renderGroups(groups, typeInfo) {elGroups.innerHTML = ''groups.forEach(group => {const div = document.createElement('div')div.className = 'cmd-group'14 unmodified linesconst hint = buildCommandHint(cmdDef, group, typeInfo)btn.title = hintbtn.setAttribute('aria-label', hint)btn.addEventListener('click', () => runCommand(btn, cmdDef))div.appendChild(btn)})6 unmodified linesasync function runCommand(btn, cmdDef) {showPage('run')if (isBuildLikeCommandRenderer(cmdDef)) {await api.r2ClearConfig()clearR2UiValues()}ensureTerminalInitialized()if (runningBtn) {function bootstrapProjectInBackground() {// Wait until first paint so users can interact with Home immediately.requestAnimationFrame(() => {setTimeout(() => {loadProject().catch((e) => {elName.textContent = 'Failed to load project'elPath.textContent = e && e.message ? e.message : String(e || 'Unknown error')})}, 0)})}runningBtn.classList.remove('running')runningBtn = null}btn.classList.add('running')btn.classList.remove('done-ok', 'done-err')runningBtn = btnelKill.disabled = falseelDot.className = 'running'elStatus.textContent = 'Running'elRunning.textContent = btn.textContentconst streamMode = getSelectedStreamMode()elRunning.textContent = `${btn.textContent} [${streamMode}]`// Wait a moment for the Run page layout to settle before fitting and running.setTimeout(async () => {if (fitAddon) fitAddon.fit()notifyPtyResize()const realCols = term ? (term.cols || 120) : 120const realRows = term ? (term.rows || 30) : 30if (term) term.reset()await api.runCmd({cmd: cmdDef.cmd,args: cmdDef.args,cwd: cmdDef.cwd,streamMode,cols: realCols,rows: realRows,})}, 50)}// ── Load project ──────────────────────────────────────────────────────────────4 unmodified lineselGroups.innerHTML = ''const data = await api.getProject()if (!data.ok) {elName.textContent = 'No package.json found'elPath.textContent = data.projectRootelGroups.innerHTML = `<div id="error-msg">No <code>package.json</code> found in:<br><b>${data.projectRoot}</b><br><br>Place the launcher inside your project folder and restart.</div>`return}const { projectRoot, projectName, typeInfo, groups, isDev } = dataelName.textContent = projectName || 'Unnamed Project'elPath.textContent = projectRootelBadge.textContent = typeInfo.labelelBadge.className = `type-badge ${typeInfo.badgeClass}`document.title = `Dev Launcher — ${projectName || projectRoot}`// In production builds (exe/msi/linux): hide R2 tab — dev-only featureconst tabR2 = document.getElementById('tab-r2')const pageR2 = document.getElementById('page-r2')if (!isDev) {if (tabR2) tabR2.style.display = 'none'if (pageR2) pageR2.style.display = 'none'} else {if (tabR2) tabR2.style.display = ''if (pageR2) pageR2.style.display = ''}renderGroups(groups, typeInfo)2 unmodified lines// ── Events ────────────────────────────────────────────────────────────────────document.getElementById('tab-home').addEventListener('click', () => showPage('home'))document.getElementById('tab-run').addEventListener('click', () => showPage('run'))document.getElementById('tab-r2').addEventListener('click', () => showPage('r2'))document.getElementById('support-btn').addEventListener('click', () => {showPage('support')})4 unmodified linesawait api.useLauncherProject()})document.getElementById('btn-r2-config-close').addEventListener('click', () => closeModal(r2ConfigBackdrop))document.getElementById('btn-r2-config-cancel').addEventListener('click', () => closeModal(r2ConfigBackdrop))document.getElementById('btn-r2-config-clear').addEventListener('click', clearSavedR2Config)document.getElementById('btn-r2-config-save').addEventListener('click', saveR2FromModal)document.getElementById('btn-r2-upload-close').addEventListener('click', () => closeModal(r2UploadBackdrop))document.getElementById('btn-r2-upload-cancel').addEventListener('click', () => closeModal(r2UploadBackdrop))document.getElementById('btn-r2-upload-run').addEventListener('click', runR2UploadFromModal)document.getElementById('security-block-close').addEventListener('click', () => {const backdrop = document.getElementById('security-block-backdrop')if (backdrop) closeModal(backdrop)})document.addEventListener('keydown', (e) => {if (e.key !== 'Escape') returncloseModal(r2ConfigBackdrop)24 unmodified linesapi.onOutput((data) => appendOutput(data))api.onDone((code) => {elKill.disabled = trueelDot.className = code === 0 ? '' : 'error'elStatus.textContent = code === 0 ? 'Done ✓' : `Exited (${code})`6 unmodified lines}})api.onProjectChanged(() => {loadProject()})15 unmodified lines1617181920212223242526272812 unmodified lines41424344454647484950515253545556575817 unmodified lines7677787980818283848586878889908 unmodified lines991001011021031041 unmodified line10610710810911011111211352 unmodified lines1661671681691701711721731741751761771781791801811821831841851861 unmodified line18818919019119219319419519619719819920020120220330 unmodified lines234235236237238239240241242243244146 unmodified lines39139239339439539639739839940040140240340440540615 unmodified lines42242342442542642742842943043143243311 unmodified lines44544644744844945045145245345445545645745845946046146246346446546646746846947047147285 unmodified lines55855956056156256356414 unmodified lines5795805815825835845855865875885895905915925936 unmodified lines6006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986994 unmodified lines7047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627632 unmodified lines7667677687697707717727737747754 unmodified lines78078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483524 unmodified lines8608618628638648658668676 unmodified lines87487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390415 unmodified linesfunction showPage(name) {document.getElementById('page-home').classList.toggle('active', name === 'home')document.getElementById('page-run').classList.toggle('active', name === 'run')const pageR2 = document.getElementById('page-r2')if (pageR2) pageR2.classList.toggle('active', name === 'r2')document.getElementById('page-support').classList.toggle('active', name === 'support')document.getElementById('tab-home').classList.toggle('active', name === 'home')document.getElementById('tab-run').classList.toggle('active', name === 'run')const tabR2 = document.getElementById('tab-r2')if (tabR2) tabR2.classList.toggle('active', name === 'r2')document.getElementById('support-btn').classList.toggle('active', name === 'support')if (name === 'run') {12 unmodified lines// iframe pages call these parent functionswindow.showView = showPagewindow.r2OpenConfig = () => {}window.r2OpenUpload = () => {}window.r2OpenCloudflare = () => {}window.r2GetStatus = async () => ({ ok: false, error: 'R2 moved to chahuadev-R2 app' })window.r2Logout = async () => ({ ok: true })// ── State ─────────────────────────────────────────────────────────────────────let runningBtn = nulllet mainRunning = falselet currentMainCmdKey = nullconst popupRunningByCmd = new Map()const cmdButtonByKey = new Map()const GROUP_COLOR_CLASS = {expo: 'group-color-expo',android: 'group-color-android',17 unmodified linesconst elDot = document.getElementById('status-dot')const elStatus = document.getElementById('status-text')const elRunning = document.getElementById('running-label')const elDevQuickPanel = document.getElementById('dev-quick-panel')const elDevMainTools = document.getElementById('btn-dev-main-tools')const elDevPopupTools = document.getElementById('btn-dev-popup-tools')const elDevSecurityStatus = document.getElementById('btn-dev-security-status')let term = nulllet fitAddon = nulllet resizeObserver = nulllet terminalInitialized = falselet currentAppIsDev = falsefunction ensureTerminalInitialized() {if (terminalInitialized) return8 unmodified linesreturn b.viewportY >= b.baseY}function initTerminal() {if (!elOutput || !window.Terminal) return1 unmodified lineterm = new window.Terminal({cursorBlink: false,disableStdin: true,// Keep raw stream untouched and let xterm handle EOL visually.convertEol: true,scrollback: 100000,fontFamily: 'Cascadia Code, Consolas, monospace',fontSize: 12,52 unmodified linesconst selected = term.getSelection()if (!selected) return falsetry {if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {await navigator.clipboard.writeText(selected)return true}const ta = document.createElement('textarea')ta.value = selectedta.setAttribute('readonly', 'readonly')ta.style.position = 'fixed'ta.style.opacity = '0'document.body.appendChild(ta)ta.focus()ta.select()const ok = document.execCommand('copy')document.body.removeChild(ta)if (!ok) return falsereturn true} catch {return false1 unmodified line}function installTerminalShortcuts() {if (elOutput) {const _onTermMousedown = () => {if (term && typeof term.focus === 'function') term.focus()}elOutput.addEventListener('mousedown', _onTermMousedown)window.addEventListener('beforeunload', () => {elOutput.removeEventListener('mousedown', _onTermMousedown)}, { once: true })}document.addEventListener('keydown', async (e) => {const isCtrlOrMeta = e.ctrlKey || e.metaKeyif (!isCtrlOrMeta) return30 unmodified linesconst r2UploadBackdrop = document.getElementById('r2-upload-backdrop')function openModal(el) {if (!el) returnel.classList.add('show')}function closeModal(el) {if (!el) returnel.classList.remove('show')}146 unmodified lines// ── ANSI → HTML ───────────────────────────────────────────────────────────────// ── Terminal output ───────────────────────────────────────────────────────────function appendOutput(text) {if (typeof text !== 'string' || text.length === 0) returnif (term) {const shouldFollow = isTermNearBottom()term.write(text)if (shouldFollow) term.scrollToBottom()return}elOutput.appendChild(document.createTextNode(text))elOutput.scrollTop = elOutput.scrollHeight}15 unmodified linesreturn false}function isNpmRunDevRenderer(cmdDef) {const cmd = String(cmdDef && cmdDef.cmd ? cmdDef.cmd : '').trim().toLowerCase()const args = (cmdDef && cmdDef.args ? cmdDef.args : []).map(x => String(x || '').trim().toLowerCase())return (cmd === 'npm' || cmd === 'npm.cmd') && args.length === 2 && args[0] === 'run' && args[1] === 'dev'}function clearR2UiValues() {const ids = ['r2-account-id', 'r2-bucket', 'r2-access-key', 'r2-secret-key', 'r2-target-folder']ids.forEach(id => {11 unmodified linesif (list) list.innerHTML = ''}function appendSecurityStatusLines(status) {const lines = []lines.push('\n[DEV SECURITY STATUS]')lines.push(`mode=${status.appMode}`)lines.push(`requestGuardInstalled=${status.requestGuardInstalled}`)lines.push(`externalRequestBlockActive=${status.externalRequestBlockActive}`)lines.push(`shortcutDevtoolsBlockedInProduction=${status.shortcutDevtoolsBlockedInProduction}`)lines.push(`mainWindowDevtoolsCapable=${status.mainWindowDevtoolsCapable}`)lines.push(`popupWindowDevtoolsCapable=${status.popupWindowDevtoolsCapable}`)lines.push(`popupCspInlineStyleAllowed=${status.popupCspInlineStyleAllowed}`)lines.push(`popupRunCount=${status.popupRunCount}`)lines.push(`note=${status.securityNote}`)appendOutput(lines.join('\n') + '\n')}function commandButtonKey(cmdDef) {const cmd = String(cmdDef && cmdDef.cmd ? cmdDef.cmd : '').trim().toLowerCase()const args = (cmdDef && cmdDef.args ? cmdDef.args : []).map(x => String(x || '').trim().toLowerCase())const cwd = String(cmdDef && cmdDef.cwd ? cmdDef.cwd : '').trim().toLowerCase()return `${cmd}␟${args.join('␟')}␟${cwd}`}function buildCommandHint(cmdDef, group, typeInfo) {const label = String(cmdDef?.label || '').toLowerCase()const cmdLine = [cmdDef.cmd, ...(cmdDef.args || [])].join(' ')85 unmodified lines// ── Render command groups ─────────────────────────────────────────────────────function renderGroups(groups, typeInfo) {elGroups.innerHTML = ''cmdButtonByKey.clear()groups.forEach(group => {const div = document.createElement('div')div.className = 'cmd-group'14 unmodified linesconst hint = buildCommandHint(cmdDef, group, typeInfo)btn.title = hintbtn.setAttribute('aria-label', hint)const cmdKey = commandButtonKey(cmdDef)cmdButtonByKey.set(cmdKey, btn)if (popupRunningByCmd.has(cmdKey)) {btn.classList.add('running-popup')}if (mainRunning && currentMainCmdKey === cmdKey) {btn.classList.add('running')runningBtn = btn}btn.addEventListener('click', () => runCommand(btn, cmdDef))div.appendChild(btn)})6 unmodified linesasync function runCommand(btn, cmdDef) {showPage('run')if (currentAppIsDev && isNpmRunDevRenderer(cmdDef) && api && typeof api.openDevToolsForCommand === 'function') {await api.openDevToolsForCommand({ cmd: cmdDef.cmd, args: cmdDef.args || [] })}ensureTerminalInitialized()const cmdKey = commandButtonKey(cmdDef)const streamMode = getSelectedStreamMode()const preferPopup = isBuildLikeCommandRenderer(cmdDef)if (!preferPopup && (!mainRunning || currentMainCmdKey === cmdKey)) {if (runningBtn && runningBtn !== btn) {runningBtn.classList.remove('running')}btn.classList.remove('done-ok', 'done-err', 'running-popup')btn.classList.add('running')runningBtn = btnmainRunning = truecurrentMainCmdKey = cmdKeyelKill.disabled = falseelDot.className = 'running'elStatus.textContent = 'Running'elRunning.textContent = `${btn.textContent} [${streamMode}]`// Wait a moment for the Run page layout to settle before fitting and running.setTimeout(async () => {if (fitAddon) fitAddon.fit()notifyPtyResize()const _termCols = term ? (term.cols || 120) : 120const _termRows = term ? (term.rows || 30) : 30if (term) term.reset()const res = await api.runCmd({cmd: cmdDef.cmd,args: cmdDef.args,cwd: cmdDef.cwd,streamMode,cols: _termCols,rows: _termRows,})if (!res || !res.ok) {mainRunning = falsecurrentMainCmdKey = nullelKill.disabled = true}}, 50)return}if (preferPopup) {appendOutput(`\n[POPUP] Build-like command routed to Sandbox Terminal: ${btn.textContent}\n`)}btn.classList.remove('done-ok', 'done-err')btn.classList.add('running-popup')popupRunningByCmd.set(cmdKey, true)const realCols = term ? (term.cols || 120) : 120const realRows = term ? (term.rows || 30) : 30const popupRes = await api.runCmdPopup({cmd: cmdDef.cmd,args: cmdDef.args,cwd: cmdDef.cwd,label: btn.textContent,streamMode,cols: realCols,rows: realRows,})if (!popupRes || !popupRes.ok) {popupRunningByCmd.delete(cmdKey)btn.classList.remove('running-popup')btn.classList.add('done-err')appendOutput(`\n[POPUP ERROR] ${popupRes && popupRes.error ? popupRes.error : 'Failed to start popup'}\n`)return}appendOutput(`\n[POPUP] ${popupRes.restarted ? 'Restarted' : 'Started'}: ${btn.textContent}\n`)}function bootstrapProjectInBackground() {// Wait until first paint so users can interact with Home immediately.requestAnimationFrame(() => {setTimeout(() => {loadProject().catch((e) => {elName.textContent = 'Failed to load project'elPath.textContent = e && e.message ? e.message : String(e || 'Unknown error')})}, 0)})}// ── Load project ──────────────────────────────────────────────────────────────4 unmodified lineselGroups.innerHTML = ''const data = await api.getProject()currentAppIsDev = !!data?.isDevconst tabR2 = document.getElementById('tab-r2')const pageR2 = document.getElementById('page-r2')if (!currentAppIsDev) {if (tabR2) tabR2.style.display = 'none'if (pageR2) pageR2.style.display = 'none'if (elDevQuickPanel) elDevQuickPanel.style.display = 'none'} else {if (tabR2) tabR2.style.display = ''if (pageR2) pageR2.style.display = ''if (elDevQuickPanel) elDevQuickPanel.style.display = ''}if (!data.ok) {const blocked = !!data.blocked || /protected OS location/i.test(String(data.error || ''))elName.textContent = blocked ? 'Security policy blocked this location' : 'No package.json found'elPath.textContent = data.projectRootif (blocked) {elGroups.innerHTML = `<div id="error-msg">Project root is blocked by security policy:<br><b>${data.projectRoot}</b><br><br>Use <b>Select Project</b> to choose a safe project folder outside OS protected paths.</div>`} else {elGroups.innerHTML = `<div id="error-msg">No <code>package.json</code> found in:<br><b>${data.projectRoot}</b><br><br>Place the launcher inside your project folder and restart.</div>`}return}const { projectRoot, projectName, typeInfo, groups, isDev } = datacurrentAppIsDev = !!isDevconst osLabel = data && data.runtimeOs && data.runtimeOs.label? String(data.runtimeOs.label): 'Unknown OS'elName.textContent = projectName || 'Unnamed Project'elPath.textContent = projectRootelBadge.textContent = `${typeInfo.label} • ${osLabel}`elBadge.className = `type-badge ${typeInfo.badgeClass}`document.title = `Dev Launcher — ${projectName || projectRoot}`if (!isDev) {if (tabR2) tabR2.style.display = 'none'if (pageR2) pageR2.style.display = 'none'if (elDevQuickPanel) elDevQuickPanel.style.display = 'none'} else {if (tabR2) tabR2.style.display = ''if (pageR2) pageR2.style.display = ''if (elDevQuickPanel) elDevQuickPanel.style.display = ''}renderGroups(groups, typeInfo)2 unmodified lines// ── Events ────────────────────────────────────────────────────────────────────document.getElementById('tab-home').addEventListener('click', () => showPage('home'))document.getElementById('tab-run').addEventListener('click', () => showPage('run'))const tabR2Btn = document.getElementById('tab-r2')if (tabR2Btn) {tabR2Btn.addEventListener('click', () => showPage('r2'))}document.getElementById('support-btn').addEventListener('click', () => {showPage('support')})4 unmodified linesawait api.useLauncherProject()})const btnR2ConfigClose = document.getElementById('btn-r2-config-close')if (btnR2ConfigClose) btnR2ConfigClose.addEventListener('click', () => closeModal(r2ConfigBackdrop))const btnR2ConfigCancel = document.getElementById('btn-r2-config-cancel')if (btnR2ConfigCancel) btnR2ConfigCancel.addEventListener('click', () => closeModal(r2ConfigBackdrop))const btnR2ConfigClear = document.getElementById('btn-r2-config-clear')if (btnR2ConfigClear) btnR2ConfigClear.addEventListener('click', clearSavedR2Config)const btnR2ConfigSave = document.getElementById('btn-r2-config-save')if (btnR2ConfigSave) btnR2ConfigSave.addEventListener('click', saveR2FromModal)const btnR2UploadClose = document.getElementById('btn-r2-upload-close')if (btnR2UploadClose) btnR2UploadClose.addEventListener('click', () => closeModal(r2UploadBackdrop))const btnR2UploadCancel = document.getElementById('btn-r2-upload-cancel')if (btnR2UploadCancel) btnR2UploadCancel.addEventListener('click', () => closeModal(r2UploadBackdrop))const btnR2UploadRun = document.getElementById('btn-r2-upload-run')if (btnR2UploadRun) btnR2UploadRun.addEventListener('click', runR2UploadFromModal)document.getElementById('security-block-close').addEventListener('click', () => {const backdrop = document.getElementById('security-block-backdrop')if (backdrop) closeModal(backdrop)})if (elDevMainTools) {elDevMainTools.addEventListener('click', async () => {const res = await api.openMainDevTools()if (!res || !res.ok) {appendOutput(`\n[DEV] Main DevTools: ${res && res.error ? res.error : 'failed'}\n`)}})}if (elDevPopupTools) {elDevPopupTools.addEventListener('click', async () => {const res = await api.openPopupDevTools()if (!res || !res.ok) {appendOutput(`\n[DEV] Popup DevTools: ${res && res.error ? res.error : 'failed'}\n`)return}appendOutput(`\n[DEV] Popup DevTools opened (runId=${res.runId || 'unknown'})\n`)})}if (elDevSecurityStatus) {elDevSecurityStatus.addEventListener('click', async () => {const status = await api.getDevSecurityStatus()if (!status || !status.ok) {appendOutput(`\n[DEV] Security status unavailable\n`)return}appendSecurityStatusLines(status)})}document.addEventListener('keydown', (e) => {if (e.key !== 'Escape') returncloseModal(r2ConfigBackdrop)24 unmodified linesapi.onOutput((data) => appendOutput(data))api.onDone((code) => {mainRunning = falsecurrentMainCmdKey = nullelKill.disabled = trueelDot.className = code === 0 ? '' : 'error'elStatus.textContent = code === 0 ? 'Done ✓' : `Exited (${code})`6 unmodified lines}})api.onPopupRunState((state) => {if (!state || !state.cmdKey) returnconst btn = cmdButtonByKey.get(state.cmdKey)const status = String(state.status || '')if (status === 'started' || status === 'restarted') {popupRunningByCmd.set(state.cmdKey, true)if (btn) {btn.classList.remove('done-ok', 'done-err')btn.classList.add('running-popup')}return}if (status === 'done' || status === 'closed' || status === 'closed-restart') {popupRunningByCmd.delete(state.cmdKey)if (btn) {btn.classList.remove('running-popup')if (status === 'done') {btn.classList.add(Number(state.exitCode) === 0 ? 'done-ok' : 'done-err')}}}})api.onProjectChanged(() => {loadProject()})
176 unmodified lines17717817918018118264 unmodified lines247248249250251252176 unmodified linesoverflow: hidden;flex-shrink: 0;}#cmd-scroll {flex: 1;overflow-y: auto;64 unmodified linesborder-color: var(--accent);animation: pulse 1.5s infinite;}.cmd-btn.done-ok {background: color-mix(in srgb, var(--green) 18%, #080812);border-color: var(--green);176 unmodified lines17717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522664 unmodified lines291292293294295296297298299300301302176 unmodified linesoverflow: hidden;flex-shrink: 0;}#dev-quick-panel {padding: 8px 8px 6px;border-bottom: 1px solid var(--border);background: linear-gradient(180deg, rgba(17, 23, 48, 0.85), rgba(14, 18, 38, 0.82));}#dev-quick-title {font-size: 10px;font-weight: 700;text-transform: uppercase;letter-spacing: 0.09em;color: #99a7de;margin-bottom: 6px;}#dev-quick-actions {display: grid;grid-template-columns: 1fr;gap: 4px;}.dev-quick-btn {width: 100%;border: 1px solid rgba(93, 129, 250, 0.35);border-radius: 7px;background: rgba(45, 69, 158, 0.2);color: #c9d8ff;font: inherit;font-size: 11px;padding: 6px 8px;cursor: pointer;text-align: left;}.dev-quick-btn:hover {background: rgba(65, 96, 210, 0.45);color: #fff;}.dev-quick-btn:disabled {opacity: 0.5;cursor: default;}#dev-quick-note {margin-top: 6px;font-size: 10px;line-height: 1.3;color: #7888bf;}#cmd-scroll {flex: 1;overflow-y: auto;64 unmodified linesborder-color: var(--accent);animation: pulse 1.5s infinite;}.cmd-btn.running-popup {background: color-mix(in srgb, #2a86d9 58%, #071326);border-color: #4eb2ff;color: #e7f6ff;box-shadow: 0 0 0 1px rgba(82, 176, 255, 0.25) inset;}.cmd-btn.done-ok {background: color-mix(in srgb, var(--green) 18%, #080812);border-color: var(--green);