use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail, ensure};
use serde_json::json;
use super::{
Content, Layout, Options, Outcome, PLATFORMS, git_root, host_key, js_string, relative, write,
};
const FRONT_DOOR_SCHEMA: &str = "rust-anything/front-door@1";
pub(super) fn is_front_door(dir: &Path) -> bool {
std::fs::read_to_string(dir.join(crate::front_door::STATE_FILE))
.ok()
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
.is_some_and(|v| v["schema"] == FRONT_DOOR_SCHEMA)
}
struct Original {
name: String,
version: String,
bin: String,
license: Option<String>,
}
pub(super) fn package(app: &Path, opts: &Options) -> Result<Outcome> {
let state: crate::front_door::State = serde_json::from_str(&std::fs::read_to_string(
app.join(crate::front_door::STATE_FILE),
)?)?;
ensure!(
state.kind == crate::front_door::AppKind::Cli,
"package covers CLI front doors; {} is a {:?} front door",
state.name,
state.kind
);
ensure!(
opts.fallback.is_none(),
"--fallback is for napi ports; a CLI package falls back to the original it depends on \
(--original)"
);
let binary = binary_name(app)?;
let original = original(app, opts.original.as_deref())?;
let name = opts
.name
.clone()
.unwrap_or_else(|| format!("{}-rs", state.name));
super::validate_npm_name(&name)?;
let version = opts
.version
.clone()
.unwrap_or_else(|| original.version.clone());
let bins = if opts.bin.is_empty() {
vec![name.rsplit('/').next().unwrap_or(&name).to_string()]
} else {
opts.bin.clone()
};
for bin in &bins {
ensure!(
!bin.is_empty()
&& bin
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || "-._".contains(c)),
"`{bin}` is not a command name (lowercase letters, digits, `-`, `.` and `_`)"
);
}
let out = match &opts.out {
Some(out) => std::path::absolute(out)?,
None => app.join("package"),
};
ensure!(
!app.starts_with(&out),
"--out cannot hold the front door it packages"
);
let mut notes = Vec::new();
let mut files: Vec<(String, Content)> = Vec::new();
let licenses = license_files(app)?;
let license = original.license.clone().or_else(|| cargo_license(app));
if license.is_none() {
notes.push(
"No license found in the original's package.json or the front door's Cargo.toml; \
add `license` to the package.json files before publishing."
.into(),
);
}
let mut optional = serde_json::Map::new();
let mut platforms = Vec::new();
for p in PLATFORMS {
let pkg = format!("{name}-{}", p.key);
platforms.push(pkg.clone());
optional.insert(pkg.clone(), json!(version));
let mut platform = json!({
"name": pkg,
"version": version,
"description": format!("The {} front door binary of {name}, generated by rust-anything", p.target),
"files": ["bin/"],
"os": [p.os],
"cpu": [p.cpu],
"preferUnplugged": true,
});
if let Some(libc) = p.libc {
platform["libc"] = json!([libc]);
}
if let Some(license) = &license {
platform["license"] = json!(license);
}
if name.starts_with('@') {
platform["publishConfig"] = json!({ "access": "public" });
}
let mut listed = vec![json!("bin/")];
for (file, path) in &licenses {
files.push((format!("npm/{}/{file}", p.key), Content::Copy(path.clone())));
listed.push(json!(file));
}
platform["files"] = json!(listed);
files.push((
format!("npm/{}/package.json", p.key),
Content::Text(serde_json::to_string_pretty(&platform)? + "\n"),
));
files.push((
format!("npm/{}/README.md", p.key),
Content::Text(format!(
"# {pkg}\n\nThe {} binary of [`{name}`](https://www.npmjs.com/package/{name}). \
Install `{name}`, not this package.\n",
p.target
)),
));
}
let launcher = format!("bin/{binary}");
let mut main_files = vec![json!("bin/"), json!("lib/")];
for (file, path) in &licenses {
files.push((file.clone(), Content::Copy(path.clone())));
main_files.push(json!(file));
}
let mut bin_map = serde_json::Map::new();
for bin in &bins {
bin_map.insert(bin.clone(), json!(launcher));
}
let mut main = json!({
"name": name,
"version": version,
"description": format!(
"{} {} with a Rust front door, generated by rust-anything: what the port covers runs in Rust, byte-identical to {}; the rest runs {} itself",
original.name, original.version, original.name, original.name
),
"bin": bin_map,
"files": main_files,
"scripts": { "postinstall": "node lib/install.cjs" },
"dependencies": { original.name.clone(): original.version },
"optionalDependencies": optional,
});
if let Some(license) = &license {
main["license"] = json!(license);
}
if name.starts_with('@') {
main["publishConfig"] = json!({ "access": "public" });
}
files.push((
"package.json".into(),
Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
));
files.push((launcher.clone(), Content::Text(launcher_js())));
files.push((
"lib/native.cjs".into(),
Content::Text(native_js(&name, &binary, &original)),
));
files.push(("lib/install.cjs".into(), Content::Text(install_js(&binary))));
files.push((
"README.md".into(),
Content::Text(readme(&name, &bins, &original, &state)),
));
files.push((
".gitignore".into(),
Content::Text("npm/*/bin/\ntarballs/\nnpm-built/\nnode_modules/\n*.tgz\n".into()),
));
let built = app
.join("target/release")
.join(exe_name(&binary, std::env::consts::OS));
match host_key() {
Some(key) if built.is_file() => {
let os = PLATFORMS.iter().find(|p| p.key == key).map_or("", |p| p.os);
files.push((
format!("npm/{key}/bin/{}", exe_name(&binary, os)),
Content::Copy(built.clone()),
));
if crate::harness::sources_newer_than(app, &built) {
notes.push(format!(
"{} is older than the front door's sources; run `cargo build --release` in {} \
and package again",
built.display(),
app.display()
));
}
notes.push(format!(
"This machine's binary is in npm/{key}/bin/. To try it: npm pack {0}/npm/{key} and \
npm pack {0}, then install both tarballs together (npm i -g a.tgz b.tgz).",
out.display()
));
}
Some(_) => notes.push(format!(
"No {} yet: run `cargo build --release` in {} and package again to try the package on \
this machine.",
built.display(),
app.display()
)),
None => {}
}
let (workflow, note) = workflow(&name, &version, &binary, app, &out)?;
files.push(workflow);
notes.push(note);
notes.push(format!(
"{} {} is pinned as a dependency: every case the front door hands back runs it.",
original.name, original.version
));
notes.push("Nothing was published.".into());
let listed: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();
if !opts.dry_run {
write(&out, Layout::Cli, &name, &version, files)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut paths = vec![out.join(&launcher)];
if let Some(key) = host_key() {
paths.push(out.join(format!("npm/{key}/bin/{binary}")));
}
for path in paths.into_iter().filter(|p| p.is_file()) {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755))?;
}
}
}
Ok(Outcome {
kind: Layout::Cli,
name,
version,
out,
module: None,
platforms,
bin: bins,
original: Some(format!("{}@{}", original.name, original.version)),
files: listed,
dry_run: opts.dry_run,
notes,
})
}
fn exe_name(binary: &str, os: &str) -> String {
if os == "win32" || os == "windows" {
format!("{binary}.exe")
} else {
binary.to_string()
}
}
fn binary_name(app: &Path) -> Result<String> {
let text = std::fs::read_to_string(app.join("Cargo.toml")).context("reading Cargo.toml")?;
let doc: toml_edit::DocumentMut = text.parse().context("parsing Cargo.toml")?;
doc.get("bin")
.and_then(|b| b.as_array_of_tables())
.and_then(|b| b.iter().next())
.and_then(|b| b.get("name"))
.or_else(|| doc.get("package").and_then(|p| p.get("name")))
.and_then(|n| n.as_str())
.map(str::to_string)
.context("no [[bin]] or [package] name in the front door's Cargo.toml")
}
fn cargo_license(app: &Path) -> Option<String> {
let text = std::fs::read_to_string(app.join("Cargo.toml")).ok()?;
let doc: toml_edit::DocumentMut = text.parse().ok()?;
Some(doc.get("package")?.get("license")?.as_str()?.to_string())
}
fn license_files(app: &Path) -> Result<Vec<(String, PathBuf)>> {
let mut found: Vec<(String, PathBuf)> = Vec::new();
for dir in [Some(app), app.parent()].into_iter().flatten() {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
let mut here: Vec<(String, PathBuf)> = entries
.filter_map(|e| e.ok())
.filter(|e| e.path().is_file())
.map(|e| (e.file_name().to_string_lossy().to_string(), e.path()))
.filter(|(n, _)| n.starts_with("LICENSE") || n.starts_with("LICENCE"))
.filter(|(n, _)| !found.iter().any(|(f, _)| f == n))
.collect();
here.sort();
found.extend(here);
}
Ok(found)
}
fn run_words(app: &Path) -> Result<Vec<String>> {
const HEAD: &str = "const RUN: &[&str] = &[";
let path = app.join("src/original.rs");
let text =
std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
let start = text
.find(HEAD)
.with_context(|| format!("no `const RUN` in {}", path.display()))?
+ HEAD.len();
let rest = &text[start..];
let mut end = None;
let mut in_string = false;
let mut chars = rest.char_indices();
while let Some((i, c)) = chars.next() {
if in_string {
match c {
'\\' => {
chars.next();
}
'"' => in_string = false,
_ => {}
}
continue;
}
match c {
'"' => in_string = true,
']' => {
end = Some(i);
break;
}
_ => {}
}
}
let end = end.with_context(|| format!("no `const RUN` in {}", path.display()))?;
let list = rest[..end]
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect::<Vec<_>>()
.join(" ");
let list = list.trim_end_matches(',').trim_end();
serde_json::from_str(&format!("[{list}]"))
.with_context(|| format!("reading `const RUN` in {}", path.display()))
}
fn original(app: &Path, spec: Option<&str>) -> Result<Original> {
let words = run_words(app)?;
let node = words.first().map(|w| {
Path::new(w)
.file_stem()
.map(|s| s.to_string_lossy().to_lowercase())
.unwrap_or_default()
});
let entry = words.iter().find_map(|w| w.strip_prefix("node_modules/"));
let (Some("node"), Some(entry)) = (node.as_deref(), entry) else {
bail!(
"package lays out npm packages for front doors of Node CLIs run as `node \
node_modules/<package>/<file>`; this one runs `{}`",
words.join(" ")
);
};
let parts: Vec<&str> = entry.split('/').collect();
let take = if entry.starts_with('@') { 2 } else { 1 };
ensure!(
parts.len() > take,
"`{entry}` names no file inside a package"
);
let name = parts[..take].join("/");
let bin = parts[take..].join("/");
let repo = match std::env::var_os(crate::front_door::REPO_ENV) {
Some(repo) => PathBuf::from(repo),
None => app.join("../.."),
};
let installed: Option<serde_json::Value> =
std::fs::read_to_string(repo.join("node_modules").join(&name).join("package.json"))
.ok()
.and_then(|t| serde_json::from_str(&t).ok());
let version = match spec {
Some(spec) => {
let (spec_name, version) = spec
.rsplit_once('@')
.filter(|(n, _)| !n.is_empty())
.with_context(|| format!("--original takes <package>@<version>, not `{spec}`"))?;
ensure!(
spec_name == name,
"the front door runs `{name}`, not `{spec_name}`"
);
version.to_string()
}
None => installed
.as_ref()
.and_then(|p| p["version"].as_str())
.map(str::to_string)
.with_context(|| {
format!(
"no {name} in {}: pass --original {name}@<the recorded version>",
repo.join("node_modules").display()
)
})?,
};
ensure!(
version.starts_with(|c: char| c.is_ascii_digit())
&& version
.chars()
.all(|c| c.is_ascii_alphanumeric() || ".-+".contains(c)),
"`{version}` is not an exact version: the package pins the version that was recorded"
);
let license = installed
.as_ref()
.filter(|p| p["version"].as_str() == Some(&version))
.and_then(|p| p["license"].as_str())
.map(str::to_string);
Ok(Original {
name,
version,
bin,
license,
})
}
fn launcher_js() -> String {
r#"#!/usr/bin/env node
'use strict'
// Generated by `rust-anything package`: runs the Rust front door for this platform, or the
// original where there is none. lib/install.cjs replaces this file with the binary itself where
// it can, so the command does not start Node first.
const { spawnSync } = require('node:child_process')
const { binary, original, BASE } = require('../lib/native.cjs')
const args = process.argv.slice(2)
const orig = original()
const exe = process.env.RUST_ANYTHING_MODE === 'old' ? null : binary()
let run
if (exe) {
const env = { ...process.env }
if (orig) env[BASE] = orig.base
run = spawnSync(exe, args, { stdio: 'inherit', env })
} else if (orig) {
run = spawnSync(process.execPath, [orig.bin, ...args], { stdio: 'inherit' })
} else {
console.error(require('../lib/native.cjs').missing())
process.exit(127)
}
if (run.error) {
console.error(run.error.message)
process.exit(127)
}
if (run.signal) process.kill(process.pid, run.signal)
process.exit(run.status ?? 1)
"#
.to_string()
}
fn native_js(name: &str, binary: &str, original: &Original) -> String {
let keys: Vec<String> = PLATFORMS.iter().map(|p| format!("'{}'", p.key)).collect();
format!(
r#"'use strict'
// Generated by `rust-anything package`: where this platform's front door binary and the
// pinned original are.
const fs = require('node:fs')
const path = require('node:path')
const NAME = {name}
const BINARY = {binary}
const ORIGINAL = {orig}
const ORIGINAL_VERSION = {version}
const ORIGINAL_BIN = {bin}
const BASE = 'RUST_ANYTHING_ORIGINAL_BASE'
const supported = [{keys}]
function abi() {{
if (process.platform === 'win32') return '-msvc'
if (process.platform !== 'linux') return ''
try {{
return process.report.getReport().header.glibcVersionRuntime ? '-gnu' : '-musl'
}} catch {{
return '-gnu'
}}
}}
const key = `${{process.platform}}-${{process.arch}}${{abi()}}`
const exe = process.platform === 'win32' ? `${{BINARY}}.exe` : BINARY
function binary() {{
if (!supported.includes(key)) return null
const local = path.join(__dirname, '..', 'npm', key, 'bin', exe)
if (fs.existsSync(local)) return local
try {{
return require.resolve(`${{NAME}}-${{key}}/bin/${{exe}}`)
}} catch {{
return null
}}
}}
function original() {{
for (const dir of require.resolve.paths(ORIGINAL) || []) {{
const pkg = path.join(dir, ORIGINAL, 'package.json')
try {{
if (JSON.parse(fs.readFileSync(pkg, 'utf8')).version !== ORIGINAL_VERSION) continue
}} catch {{
continue
}}
return {{ base: path.dirname(dir), bin: path.join(dir, ORIGINAL, ORIGINAL_BIN) }}
}}
return null
}}
function missing() {{
return `${{NAME}}: ${{ORIGINAL}}@${{ORIGINAL_VERSION}} is not installed beside it and there is no binary for ${{key}}; reinstall ${{NAME}}`
}}
module.exports = {{ binary, original, missing, key, supported, BASE }}
"#,
name = js_string(name),
binary = js_string(binary),
orig = js_string(&original.name),
version = js_string(&original.version),
bin = js_string(&original.bin),
keys = keys.join(", ")
)
}
fn install_js(binary: &str) -> String {
format!(
r#"'use strict'
// Generated by `rust-anything package`: postinstall. Outside Windows, puts this platform's
// binary where the launcher was, so the command runs it directly. Any failure keeps the launcher,
// which works the same and only starts Node first.
const fs = require('node:fs')
const path = require('node:path')
function main() {{
if (process.platform === 'win32') return
if (!__dirname.split(path.sep).includes('node_modules')) return
if (!require('./native.cjs').original()) return
const exe = require('./native.cjs').binary()
if (!exe) return
const launcher = path.join(__dirname, '..', 'bin', {binary})
const temp = `${{launcher}}.${{process.pid}}`
try {{
fs.copyFileSync(exe, temp)
fs.chmodSync(temp, 0o755)
fs.renameSync(temp, launcher)
}} catch {{
try {{
fs.unlinkSync(temp)
}} catch {{}}
}}
}}
main()
"#,
binary = js_string(binary)
)
}
fn readme(
name: &str,
bins: &[String],
original: &Original,
state: &crate::front_door::State,
) -> String {
let units: Vec<String> = state
.units
.iter()
.map(|u| format!("`{}` (`{}`)", u.name, u.crate_name))
.collect();
let units = if units.is_empty() {
"the glue in the front door".to_string()
} else {
units.join(", ")
};
format!(
"# {name}\n\n\
[{orig}](https://www.npmjs.com/package/{orig}) {version} behind a Rust front door, made with \
[rust-anything](https://github.com/erkamyaman/rust-anything). Each run of `{bin}` goes to \
the Rust port when it covers the arguments and the input ({units}), and to {orig} \
{version} otherwise. {orig} {version} is a dependency of this package, so what falls back \
runs the exact version the port was recorded against, and the output is the same \
either way.\n\n\
```sh\nnpm install -g {name}\n{bin} --help\n```\n\n\
The Rust binary comes from `{name}-<platform>` (macOS arm64 and x64, Linux x64 and arm64 \
with glibc, Windows x64). Elsewhere, or with `RUST_ANYTHING_MODE=old`, `{bin}` runs \
{orig} itself. Outside Windows, the install script puts the binary in place of the Node \
launcher; with install scripts turned off the launcher stays and starts Node first.\n",
orig = original.name,
version = original.version,
bin = bins[0],
)
}
fn workflow(
name: &str,
version: &str,
binary: &str,
app: &Path,
out: &Path,
) -> Result<((String, Content), String)> {
let repo = git_root(out);
let dir = repo
.as_deref()
.and_then(|r| relative(r, out))
.unwrap_or_else(|| ".".into());
let app_rel = relative(out, app).context("relating the front door to --out")?;
let slug: String = name
.trim_start_matches('@')
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let matrix: String = PLATFORMS
.iter()
.map(|p| {
format!(
" - {{ key: {}, target: {}, os: {}, exe: {} }}\n",
p.key,
p.target,
p.runner,
exe_name(binary, p.os)
)
})
.collect();
let text = format!(
r#"# Generated by `rust-anything package`: the {name} {version} npm packages (the front door
# binary per platform, plus the main one), packed and uploaded as artifacts. Nothing is published.
name: {name} npm packages
on:
workflow_dispatch:
push:
tags: ['{name}-v*']
defaults:
run:
shell: bash
working-directory: {dir}
jobs:
build:
name: ${{{{ matrix.key }}}}
runs-on: ${{{{ matrix.os }}}}
strategy:
fail-fast: false
matrix:
include:
{matrix} steps:
- uses: actions/checkout@v4
- run: rustup target add ${{{{ matrix.target }}}}
- run: cargo build --release --locked --target ${{{{ matrix.target }}}} --manifest-path {app_rel}/Cargo.toml --target-dir target
- run: |
mkdir -p npm/${{{{ matrix.key }}}}/bin
cp target/${{{{ matrix.target }}}}/release/${{{{ matrix.exe }}}} npm/${{{{ matrix.key }}}}/bin/
- uses: actions/upload-artifact@v4
with:
name: bin-${{{{ matrix.key }}}}
path: {dir}/npm/${{{{ matrix.key }}}}/bin
pack:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- uses: actions/download-artifact@v4
with:
pattern: bin-*
path: {dir}/npm-built
- run: |
for built in npm-built/bin-*; do
key="${{built##*/bin-}}"
mkdir -p "npm/$key/bin"
cp "$built"/* "npm/$key/bin/"
chmod +x "npm/$key/bin/"*
done
mkdir -p tarballs
for platform in npm/*/; do npm pack "./$platform" --pack-destination tarballs; done
npm pack --pack-destination tarballs
- uses: actions/upload-artifact@v4
with:
name: npm-tarballs
path: {dir}/tarballs
"#
);
let path = format!(".github/workflows/{slug}-npm.yml");
let note = match &repo {
Some(repo) => format!(
"CI: move {path} to {}/.github/workflows/ (GitHub runs workflows only from there); it \
builds the binary on every platform and uploads the packed tarballs as artifacts.",
repo.display()
),
None => format!(
"CI: {path} assumes {} is the repository root; move it to the repository's \
.github/workflows/ and set `working-directory` to this folder.",
out.display()
),
};
Ok(((path, Content::Text(text)), note))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_original_from_run() {
let dir = std::env::temp_dir().join(format!("ra-pkg-cli-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("src/original.rs"),
"const RUN: &[&str] = &[\"node\", \"node_modules/@scope/tool/bin/tool.js\"];\n",
)
.unwrap();
let o = original(&dir, Some("@scope/tool@1.2.3")).unwrap();
assert_eq!(o.name, "@scope/tool");
assert_eq!(o.bin, "bin/tool.js");
assert_eq!(o.version, "1.2.3");
assert!(original(&dir, Some("@scope/tool@^1.2.3")).is_err());
assert!(original(&dir, Some("other@1.2.3")).is_err());
std::fs::write(
dir.join("src/original.rs"),
"const RUN: &[&str] = &[\"python3\", \"tool.py\"];\n",
)
.unwrap();
assert!(original(&dir, Some("tool@1.0.0")).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn reads_the_original_from_a_run_list_rustfmt_wrapped() {
let dir = std::env::temp_dir().join(format!("ra-pkg-cli-fmt-{}", std::process::id()));
std::fs::create_dir_all(dir.join("src")).unwrap();
std::fs::write(
dir.join("src/original.rs"),
"const RUN: &[&str] = &[\n \"node\",\n \
\"node_modules/@acme/some-quite-long-package-name/bin/cli.js\",\n \"--flag\",\n \
\"a value with spaces\",\n \"]\",\n];\n",
)
.unwrap();
let o = original(&dir, Some("@acme/some-quite-long-package-name@2.0.0")).unwrap();
assert_eq!(o.bin, "bin/cli.js");
assert_eq!(o.version, "2.0.0");
let words = run_words(&dir).unwrap();
assert_eq!(
words,
[
"node",
"node_modules/@acme/some-quite-long-package-name/bin/cli.js",
"--flag",
"a value with spaces",
"]",
]
);
let _ = std::fs::remove_dir_all(&dir);
}
}