Something went wrong. Try again.
A reusable desktop shell: your sidecar, your index, safe APIs, installers for every platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263// Choosing the sidecar's port, finding the user's PATH, and resolving the// sidecar's command. No Electron in here, so the tests use it as well.import { execFile } from 'node:child_process';import { createServer } from 'node:net';import { isAbsolute, resolve } from 'node:path';
export function freePort (port = 0) { return new Promise((res, rej) => { const server = createServer(); server.unref(); server.on('error', rej); server.listen(port, '127.0.0.1', () => { const { port: bound } = server.address(); server.close(() => res(bound)); }); });}
export const isFree = (port) => freePort(port).then(() => true, () => false);
// True when something at `url` answers at all.export async function answers (url, timeout = 700) { try { await fetch(url, { signal: AbortSignal.timeout(timeout) }); return true; } catch { return false; }}
// The port for the sidecar and whether to start one. A configured port is// required: if it is busy, either a sidecar that answers `ready` is already// there and `attach` lets us use it, or this is an error. Without one, the// port used last time is reused when free, so the page keeps its origin (and// with it localStorage and the like) from one launch to the next.export async function choosePort ({ sidecar, remembered, readyUrl }) { if (sidecar?.port) { if (sidecar.attach && await answers(readyUrl(sidecar.port))) return { port: sidecar.port, attach: true }; if (await isFree(sidecar.port)) return { port: sidecar.port, attach: false }; throw new Error(`Port ${sidecar.port} is taken by another program${sidecar.attach ? ' that does not answer like this app\'s server' : ''}.`); } if (remembered && await isFree(remembered)) return { port: remembered, attach: false }; return { port: await freePort(), attach: false };}
// The PATH a terminal would have. Apps started from the Finder or at login get// a bare one (/usr/bin:/bin:…), so a sidecar that runs `deno` or `git` would// not find them.export function loginPath ({ shell = process.env.SHELL || '/bin/zsh', timeout = 4000 } = {}) { if (process.platform === 'win32') return Promise.resolve(null); const marker = '__MOLLUSC_PATH__'; return new Promise((res) => { execFile(shell, ['-ilc', `printf '${marker}%s${marker}' "$PATH"`], { timeout, env: { ...process.env, TERM: 'dumb' } }, (err, stdout) => { const m = !err && String(stdout).match(new RegExp(`${marker}(.*)${marker}`)); res(m ? m[1] : null); }); });}
// A command with a slash in it is a path in the app, like `bin/server`.export function resolveCommand (command, appDir) { return !isAbsolute(command) && /[\\/]/.test(command) ? resolve(appDir, command) : command;}