droid1.28.07.7 kB
#!/usr/bin/env node
/**
* postinstall script for @factory/cli
*
* This script optimizes the installed package by replacing the JavaScript shim
* with a hard link to the actual binary executable. This avoids the overhead
* of launching another Node.js process when using the "droid" command.
*
* Based on esbuild's approach: https://github.com/evanw/esbuild/pull/1621
* and Sentry's guide: https://sentry.engineering/blog/publishing-binaries-on-npm
*
* On Unix: replaces bin/droid with hard link to the platform binary
* On Windows: keeps JS shim (Windows requires .exe extension)
* With --ignore-scripts: keeps the JS shim, which runs the platform package's
* binary
*
* It makes no network request and starts no package manager: the binary comes
* only from the platform package the user's package manager installed.
*/
const fs = require('fs');
const path = require('path');
const child_process = require('child_process');
const {
PACKAGE,
getBinaryPath,
getMissingBinaryMessage,
} = require('./platform.js');
function isYarn2OrAbove() {
const { npm_config_user_agent } = process.env;
if (npm_config_user_agent) {
const match = npm_config_user_agent.match(/yarn\/(\d+)/);
if (match && match[1]) {
return parseInt(match[1], 10) >= 2;
}
}
return false;
}
function validateBinaryVersion(binaryPath) {
try {
const result = child_process.execFileSync(binaryPath, ['--version'], {
encoding: 'utf8',
timeout: 10000,
});
const version = result.trim().split('\n')[0];
// Version format might be "droid 0.50.0" or just "0.50.0"
if (PACKAGE.version !== '0.0.0' && !version.includes(PACKAGE.version)) {
console.warn(
`Warning: Binary version mismatch. Expected ${PACKAGE.version}, got ${version}`
);
}
} catch (e) {
// Version check is optional, don't fail install
}
}
/**
* Check if this is a global npm install by looking at the npm_config_global
* environment variable that npm sets during installation. npm sets it to an
* empty string for a local install that overrides a global setting
* (`--no-global`).
*/
function isGlobalInstall() {
return process.env.npm_config_global === 'true';
}
/**
* The npm global bin directory, from the global prefix npm passes to install
* scripts: <prefix>/bin on POSIX, the prefix itself on Windows.
*/
function getNpmGlobalBinDir() {
const prefix = process.env.npm_config_global_prefix;
if (!prefix) return null;
return process.platform === 'win32' ? prefix : path.join(prefix, 'bin');
}
/**
* Check if a directory is already present in the current PATH.
* Uses path.resolve() to normalize slashes and handles case-insensitive
* comparison on Windows.
*/
function isDirInPath(dir) {
const envPath = process.env.PATH || '';
const sep = process.platform === 'win32' ? ';' : ':';
const normalize = (d) => path.resolve(d);
const normalizedDir = normalize(dir);
const dirs = envPath.split(sep).map(normalize);
if (process.platform === 'win32') {
return dirs.some((d) => d.toLowerCase() === normalizedDir.toLowerCase());
}
return dirs.includes(normalizedDir);
}
/**
* Detect the user's shell and suggest the appropriate profile file.
*/
function getShellProfileHint() {
const shell = process.env.SHELL || '';
const shellName = path.basename(shell);
if (shellName === 'zsh') return '~/.zshrc';
if (shellName === 'bash') {
return process.platform === 'darwin' ? '~/.bash_profile' : '~/.bashrc';
}
if (shellName === 'fish') return '~/.config/fish/config.fish';
return null;
}
/**
* Print a warning if the npm global bin directory is not in the user's PATH.
* Only runs for global installs. Does NOT modify any files.
*/
function warnIfNotInPath() {
try {
if (process.env.CI || process.env.CONTINUOUS_INTEGRATION) return;
if (!isGlobalInstall()) return;
const binDir = getNpmGlobalBinDir();
if (!binDir) return;
if (isDirInPath(binDir)) return;
const profileHint = getShellProfileHint();
if (process.platform === 'win32') {
console.log(
'\n' +
'Note: The "droid" command may not be available in your terminal.\n' +
`The npm global bin directory is not in your PATH:\n` +
` ${binDir}\n\n` +
'To fix for this session, run:\n' +
` set PATH=%PATH%;${binDir}\n\n` +
'To fix permanently (PowerShell):\n' +
` [Environment]::SetEnvironmentVariable('Path', $env:PATH + ';${binDir}', 'User')\n\n` +
'Then restart your terminal.\n'
);
} else if (profileHint) {
const exportLine =
profileHint === '~/.config/fish/config.fish'
? `fish_add_path "${binDir}"`
: `export PATH="${binDir}:$PATH"`;
console.log(
'\n' +
'Note: The "droid" command may not be available in your terminal.\n' +
`The npm global bin directory is not in your PATH:\n` +
` ${binDir}\n\n` +
`To fix, run:\n` +
` echo '${exportLine}' >> ${profileHint} && source ${profileHint}\n`
);
} else {
console.log(
'\n' +
'Note: The "droid" command may not be available in your terminal.\n' +
`The npm global bin directory is not in your PATH:\n` +
` ${binDir}\n\n` +
'To fix, add the following to your shell profile (~/.bashrc, ~/.zshrc, etc.):\n' +
` export PATH="${binDir}:$PATH"\n\n` +
'Then restart your terminal.\n'
);
}
} catch (e) {
// PATH check is best-effort; never fail the install
}
}
function main() {
const shimPath = path.join(__dirname, 'bin', 'droid');
const binaryPath = getBinaryPath();
if (!binaryPath) {
console.log(getMissingBinaryMessage());
return;
}
// On Windows, we can't replace the shim with the binary due to .exe requirement
// On Yarn 2+, PnP mode has issues with binary modules
if (process.platform === 'win32' || isYarn2OrAbove()) {
validateBinaryVersion(binaryPath);
console.log('Using JavaScript shim for droid command.');
return;
}
// On Unix, replace the JavaScript shim with a hard link to the binary
// First, backup the shim in case linking fails
const shimBackupPath = shimPath + '.backup';
let shimBackedUp = false;
try {
// Backup the existing shim
if (fs.existsSync(shimPath)) {
fs.copyFileSync(shimPath, shimBackupPath);
shimBackedUp = true;
}
// Remove the existing shim
fs.unlinkSync(shimPath);
// Create a hard link to the binary
fs.linkSync(binaryPath, shimPath);
// Clean up backup
if (shimBackedUp) {
fs.unlinkSync(shimBackupPath);
}
validateBinaryVersion(shimPath);
console.log(
'Optimized: droid command now runs the native binary directly.'
);
} catch (e) {
// If hard link fails (e.g., cross-device), try symlink
try {
fs.symlinkSync(binaryPath, shimPath);
// Clean up backup
if (shimBackedUp) {
fs.unlinkSync(shimBackupPath);
}
console.log('Optimized: droid command linked to native binary.');
} catch (e2) {
// Restore the shim from backup
if (shimBackedUp) {
try {
fs.renameSync(shimBackupPath, shimPath);
console.log(
'Using JavaScript shim for droid command (optimization failed).'
);
} catch (e3) {
console.error(
'Failed to restore shim. Please reinstall the package.'
);
}
} else {
console.log(
'Using JavaScript shim for droid command (optimization failed).'
);
}
}
}
}
try {
main();
warnIfNotInPath();
} catch (e) {
// A failed postinstall must not fail the user's whole install.
console.error('postinstall error:', e.message);
}
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.