use anyhow::Result;
use super::{GeneratedFile, Mechanism, MechanismContext, StepResult};
pub struct Npm;
impl Mechanism for Npm {
fn id(&self) -> &'static str {
"npm"
}
fn description(&self) -> &'static str {
"packaging/npm — postinstall downloads Release binary"
}
fn generate(&self, ctx: &MechanismContext<'_>) -> Result<StepResult> {
let p = &ctx.config.project;
let bin = &p.binary_name;
let version = &p.version;
let owner = &p.github_owner;
let repo = &p.github_repo;
let npm_org = ctx
.config
.org
.npm_org
.clone()
.unwrap_or_else(|| owner.clone());
let pkg = ctx
.config
.org
.npm_package
.clone()
.unwrap_or_else(|| format!("@{npm_org}/{bin}"));
let package_json = format!(
r#"{{
"name": "{pkg}",
"version": "{version}",
"description": {desc},
"license": "{license}",
"repository": {{
"type": "git",
"url": "git+https://github.com/{owner}/{repo}.git",
"directory": "packaging/npm"
}},
"homepage": "https://github.com/{owner}/{repo}",
"bin": {{
"{bin}": "bin/{bin}.js"
}},
"scripts": {{
"postinstall": "node scripts/install.js"
}},
"engines": {{
"node": ">=18"
}},
"files": ["bin/", "scripts/", "README.md"],
"publishConfig": {{
"access": "public"
}}
}}
"#,
desc = serde_json::to_string(&p.description)?,
license = p.license,
);
let wrapper = format!(
r#"#!/usr/bin/env node
"use strict";
const {{ spawnSync }} = require("child_process");
const path = require("path");
const fs = require("fs");
const bin = process.platform === "win32" ? "{bin}.exe" : "{bin}";
const candidate = path.join(__dirname, "..", "vendor", bin);
if (!fs.existsSync(candidate)) {{
console.error("{bin}: binary missing; re-run npm install (postinstall downloads it)");
process.exit(1);
}}
const r = spawnSync(candidate, process.argv.slice(2), {{ stdio: "inherit" }});
process.exit(r.status === null ? 1 : r.status);
"#
);
let install_js = format!(
r#"#!/usr/bin/env node
"use strict";
const {{ execSync }} = require("child_process");
const fs = require("fs");
const path = require("path");
const owner = "{owner}";
const repo = "{repo}";
const version = process.env.{env}_VERSION || "v{version}";
const tag = version.startsWith("v") ? version : `v${{version}}`;
const binName = process.platform === "win32" ? "{bin}.exe" : "{bin}";
function platform() {{
const os =
process.platform === "darwin"
? "macos"
: process.platform === "win32"
? "windows"
: "linux";
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
return `${{os}}-${{arch}}`;
}}
const plat = platform();
const ext = plat.startsWith("windows") ? "zip" : "tar.gz";
const asset = `{bin}-${{tag}}-${{plat}}.${{ext}}`;
const url = `https://github.com/${{owner}}/${{repo}}/releases/download/${{tag}}/${{asset}}`;
const vendor = path.join(__dirname, "..", "vendor");
fs.mkdirSync(vendor, {{ recursive: true }});
const archive = path.join(vendor, asset);
console.log("{bin}: downloading", url);
execSync(`curl -fsSL "${{url}}" -o "${{archive}}"`, {{ stdio: "inherit" }});
if (ext === "tar.gz") {{
execSync(`tar -xzf "${{archive}}" -C "${{vendor}}"`, {{ stdio: "inherit" }});
}} else {{
execSync(`unzip -qo "${{archive}}" -d "${{vendor}}"`, {{ stdio: "inherit" }});
}}
try {{
fs.chmodSync(path.join(vendor, binName), 0o755);
}} catch (_) {{}}
try {{
fs.unlinkSync(archive);
}} catch (_) {{}}
"#,
env = bin.to_uppercase().replace('-', "_"),
);
let readme = format!(
"# `{pkg}`\n\nDownloads `{bin}` from GitHub Releases on `postinstall`.\n\n```bash\nnpm install --save-dev {pkg}\nnpx {bin} --version\n```\n\nPublish via `NPM_TOKEN` (granular + bypass 2FA). See project publishing docs.\n"
);
let release_snippet = format!(
r#"# Add to .github/workflows/release.yml after github-release:
# publish-npm:
# needs: github-release
# runs-on: ubuntu-latest
# defaults:
# run:
# working-directory: packaging/npm
# steps:
# - uses: actions/checkout@v4
# - uses: actions/setup-node@v4
# with:
# node-version: "20"
# registry-url: https://registry.npmjs.org
# scope: "@{npm_org}"
# - run: |
# VERSION="${{GITHUB_REF_NAME#v}}"
# node -e "const fs=require('fs');const p=JSON.parse(fs.readFileSync('package.json','utf8'));p.version=process.env.VERSION;fs.writeFileSync('package.json',JSON.stringify(p,null,2)+'\n')"
# npm publish --access public
# env:
# NODE_AUTH_TOKEN: ${{{{ secrets.NPM_TOKEN }}}}
# VERSION: ${{{{ github.ref_name }}}}
"#
);
let base = format!(
"{}/npm",
ctx.config.paths.packaging_dir.trim_end_matches('/')
);
Ok(StepResult {
files: vec![
GeneratedFile {
relative_path: format!("{base}/package.json"),
contents: package_json,
executable: false,
},
GeneratedFile {
relative_path: format!("{base}/bin/{bin}.js"),
contents: wrapper,
executable: true,
},
GeneratedFile {
relative_path: format!("{base}/scripts/install.js"),
contents: install_js,
executable: true,
},
GeneratedFile {
relative_path: format!("{base}/README.md"),
contents: readme,
executable: false,
},
GeneratedFile {
relative_path: format!("{base}/.gitignore"),
contents: "vendor/\nnode_modules/\n*.tgz\n.npmrc\n".into(),
executable: false,
},
GeneratedFile {
relative_path: format!("{base}/CI_SNIPPET.md"),
contents: release_snippet,
executable: false,
},
],
notes: vec![
"Set GitHub secret NPM_TOKEN (granular Automation token, bypass 2FA).".into(),
format!("Package name: {pkg}"),
],
})
}
}