Skip to main content

rust_anything/
package.rs

1//! Step 6: turn a gated port into packages end users install, the way maturin and
2//! `@napi-rs/cli` lay them out. Writes files only: it never builds for other platforms (the
3//! generated GitHub Actions workflow does) and never publishes.
4//!
5//! - PyO3: a self-contained maturin project (abi3 wheel, importable under the original's module
6//!   name) and a workflow that builds wheels for macOS, Linux (manylinux) and Windows.
7//! - napi-rs: a main npm package whose loader picks `<name>-<platform>` from its
8//!   `optionalDependencies` and falls back to the original JS, one package per platform holding
9//!   one `.node`, and a workflow that builds and packs them.
10//! - wasm-bindgen: one npm package with the built `pkg/`, the same on every platform.
11//! - A CLI front door (`rust/app`) of an npm CLI: a main package whose command runs this
12//!   platform's front door binary, with the original pinned as a dependency for every case the
13//!   port does not cover, and one package per platform holding the binary (`cli.rs`).
14
15use std::path::{Component, Path, PathBuf};
16
17use anyhow::{Context, Result, bail};
18use serde::{Deserialize, Serialize};
19use serde_json::json;
20
21use crate::bridge::{Kind, Manifest};
22
23mod cli;
24
25/// Written into the output folder; lists what the last run wrote, so a rerun replaces only that.
26pub const STAMP: &str = "rust-anything-package.json";
27const STAMP_SCHEMA: &str = "rust-anything/package@1";
28
29pub struct Options<'a> {
30    pub crate_dir: &'a Path,
31    /// Package name on npm or PyPI; defaults to the crate name.
32    pub name: Option<String>,
33    /// Package version; defaults to the original package's.
34    pub version: Option<String>,
35    /// Output folder; defaults to `<crate>/package`.
36    pub out: Option<PathBuf>,
37    /// List what would be written, write nothing.
38    pub dry_run: bool,
39    /// napi: the module the loader requires when no binary fits the platform.
40    pub fallback: Option<String>,
41    /// CLI: the commands the package installs; defaults to the package name without its scope.
42    pub bin: Vec<String>,
43    /// CLI: the original npm package the front door falls back to, as `name@version`; defaults
44    /// to the one in `node_modules` of the repository the front door belongs to.
45    pub original: Option<String>,
46}
47
48/// What a package folder holds.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "lowercase")]
51pub enum Layout {
52    Napi,
53    Wasm,
54    Pyo3,
55    /// A front door's binary per platform behind an npm command.
56    Cli,
57}
58
59impl From<Kind> for Layout {
60    fn from(kind: Kind) -> Self {
61        match kind {
62            Kind::Wasm => Layout::Wasm,
63            Kind::Pyo3 => Layout::Pyo3,
64            _ => Layout::Napi,
65        }
66    }
67}
68
69#[derive(Debug, Serialize)]
70pub struct Outcome {
71    pub kind: Layout,
72    pub name: String,
73    pub version: String,
74    pub out: PathBuf,
75    /// Python: the module the wheel installs (`import <module>`).
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub module: Option<String>,
78    /// napi: the platform packages, `<name>-<key>`.
79    #[serde(skip_serializing_if = "Vec::is_empty")]
80    pub platforms: Vec<String>,
81    /// CLI: the commands the package installs.
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub bin: Vec<String>,
84    /// CLI: the original the package depends on, `name@version`.
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub original: Option<String>,
87    pub files: Vec<String>,
88    pub dry_run: bool,
89    pub notes: Vec<String>,
90}
91
92#[derive(Serialize, Deserialize)]
93struct Stamp {
94    schema: String,
95    kind: Layout,
96    name: String,
97    version: String,
98    files: Vec<String>,
99}
100
101enum Content {
102    Text(String),
103    Copy(PathBuf),
104}
105
106/// A platform a napi port ships a binary for: the npm key napi-rs uses, the Rust target, and
107/// the runner that builds it.
108pub struct Platform {
109    pub key: &'static str,
110    pub target: &'static str,
111    os: &'static str,
112    cpu: &'static str,
113    libc: Option<&'static str>,
114    runner: &'static str,
115    /// Whether the runner can load what it built (no cross-compiled check).
116    native: bool,
117}
118
119pub const PLATFORMS: &[Platform] = &[
120    Platform {
121        key: "darwin-arm64",
122        target: "aarch64-apple-darwin",
123        os: "darwin",
124        cpu: "arm64",
125        libc: None,
126        runner: "macos-latest",
127        native: true,
128    },
129    Platform {
130        key: "darwin-x64",
131        target: "x86_64-apple-darwin",
132        os: "darwin",
133        cpu: "x64",
134        libc: None,
135        runner: "macos-latest",
136        native: false,
137    },
138    Platform {
139        key: "linux-x64-gnu",
140        target: "x86_64-unknown-linux-gnu",
141        os: "linux",
142        cpu: "x64",
143        libc: Some("glibc"),
144        runner: "ubuntu-22.04",
145        native: true,
146    },
147    Platform {
148        key: "linux-arm64-gnu",
149        target: "aarch64-unknown-linux-gnu",
150        os: "linux",
151        cpu: "arm64",
152        libc: Some("glibc"),
153        runner: "ubuntu-22.04-arm",
154        native: true,
155    },
156    Platform {
157        key: "win32-x64-msvc",
158        target: "x86_64-pc-windows-msvc",
159        os: "win32",
160        cpu: "x64",
161        libc: None,
162        runner: "windows-latest",
163        native: true,
164    },
165];
166
167/// The napi key of the machine running rust-anything, if a package is built for it.
168pub fn host_key() -> Option<&'static str> {
169    let target = match (std::env::consts::OS, std::env::consts::ARCH) {
170        ("macos", "aarch64") => "aarch64-apple-darwin",
171        ("macos", "x86_64") => "x86_64-apple-darwin",
172        ("linux", "x86_64") if cfg!(target_env = "gnu") => "x86_64-unknown-linux-gnu",
173        ("linux", "aarch64") if cfg!(target_env = "gnu") => "aarch64-unknown-linux-gnu",
174        ("windows", "x86_64") if cfg!(target_env = "msvc") => "x86_64-pc-windows-msvc",
175        _ => return None,
176    };
177    PLATFORMS.iter().find(|p| p.target == target).map(|p| p.key)
178}
179
180pub fn package(opts: &Options) -> Result<Outcome> {
181    let crate_dir = std::path::absolute(opts.crate_dir)?;
182    if let Some(v) = &opts.version {
183        validate_version(v)?;
184    }
185    if cli::is_front_door(&crate_dir) {
186        return cli::package(&crate_dir, opts);
187    }
188    let manifest = Manifest::load(&crate_dir)?;
189    let kind_label = match manifest.kind {
190        Kind::Napi => "napi",
191        Kind::Wasm => "wasm",
192        Kind::Pyo3 => "PyO3",
193        Kind::CAbi | Kind::Ffi => {
194            let label = manifest
195                .kind
196                .label()
197                .trim_start_matches("a ")
198                .trim_start_matches("the ");
199            bail!(
200                "package covers napi-rs, wasm-bindgen and PyO3 crates; this one is a {} crate ({label})",
201                manifest.language.name()
202            );
203        }
204    };
205    if !opts.bin.is_empty() && opts.original.is_some() {
206        bail!(
207            "--bin and --original are for CLI front doors (`rust/app`); this is a {kind_label} crate"
208        );
209    } else if !opts.bin.is_empty() {
210        bail!("--bin is for CLI front doors (`rust/app`); this is a {kind_label} crate");
211    } else if opts.original.is_some() {
212        bail!("--original is for CLI front doors (`rust/app`); this is a {kind_label} crate");
213    }
214    if opts.fallback.is_some() && manifest.kind != Kind::Napi {
215        bail!("--fallback is for napi crates; this is a {kind_label} crate");
216    }
217    let out = match &opts.out {
218        Some(out) => std::path::absolute(out)?,
219        None => crate_dir.join("package"),
220    };
221    let name = match &opts.name {
222        Some(name) => name.clone(),
223        None => manifest.crate_name.clone(),
224    };
225    let mut notes = Vec::new();
226    let version = match &opts.version {
227        Some(v) => v.clone(),
228        None => original_version(&manifest).unwrap_or_else(|| {
229            let v = cargo_version(&crate_dir).unwrap_or_else(|| "0.1.0".into());
230            notes.push(format!(
231                "No version found in the original package; using {v}. Pass --version to set one."
232            ));
233            v
234        }),
235    };
236    let mut files: Vec<(String, Content)> = Vec::new();
237    let mut module = None;
238    let mut platforms = Vec::new();
239    match manifest.kind {
240        Kind::Pyo3 => {
241            let m = python_module(&manifest);
242            python_files(&crate_dir, &manifest, &name, &version, &m, &out, &mut files)?;
243            notes.push(format!(
244                "pip install {0} builds the wheel locally (maturin, from PyPI); `maturin build \
245                 --release` in {0} writes it to target/wheels. The wheel installs `import {m}`.",
246                out.display()
247            ));
248            module = Some(m);
249        }
250        Kind::Napi => {
251            validate_npm_name(&name)?;
252            platforms = PLATFORMS
253                .iter()
254                .map(|p| format!("{name}-{}", p.key))
255                .collect();
256            napi_files(
257                &crate_dir, &manifest, &name, &version, opts, &out, &mut files, &mut notes,
258            )?;
259        }
260        Kind::Wasm => {
261            validate_npm_name(&name)?;
262            wasm_files(&crate_dir, &manifest, &name, &version, &mut files)?;
263            notes.push(format!(
264                "npm pack {} gives one tarball that runs on every platform.",
265                out.display()
266            ));
267        }
268        Kind::CAbi | Kind::Ffi => unreachable!(),
269    }
270    if matches!(manifest.kind, Kind::Pyo3 | Kind::Napi) {
271        let (workflow, note) = workflow_file(&manifest, &name, &version, &crate_dir, &out)?;
272        files.push(workflow);
273        notes.push(note);
274    }
275    notes.push("Nothing was published.".into());
276    let listed: Vec<String> = files.iter().map(|(p, _)| p.clone()).collect();
277    if !opts.dry_run {
278        write(&out, manifest.kind.into(), &name, &version, files)?;
279    }
280    Ok(Outcome {
281        kind: manifest.kind.into(),
282        name,
283        version,
284        out,
285        module,
286        platforms,
287        bin: Vec::new(),
288        original: None,
289        files: listed,
290        dry_run: opts.dry_run,
291        notes,
292    })
293}
294
295fn write(
296    out: &Path,
297    kind: Layout,
298    name: &str,
299    version: &str,
300    files: Vec<(String, Content)>,
301) -> Result<()> {
302    let stamp_path = out.join(STAMP);
303    if stamp_path.exists() {
304        let text = std::fs::read_to_string(&stamp_path)?;
305        let old: Stamp = serde_json::from_str(&text)
306            .with_context(|| format!("parsing {}", stamp_path.display()))?;
307        for file in old.files {
308            let path = out.join(&file);
309            if safe_relative(&file) && path.is_file() {
310                std::fs::remove_file(&path)?;
311            }
312        }
313    } else if out.exists() && std::fs::read_dir(out)?.next().is_some() {
314        bail!(
315            "{} is not empty and was not written by `rust-anything package`; pass --out with an \
316             empty or new folder",
317            out.display()
318        );
319    }
320    for (path, content) in &files {
321        let target = out.join(path);
322        if let Some(parent) = target.parent() {
323            std::fs::create_dir_all(parent)?;
324        }
325        match content {
326            Content::Text(text) => std::fs::write(&target, text),
327            Content::Copy(from) => std::fs::copy(from, &target).map(|_| ()),
328        }
329        .with_context(|| format!("writing {}", target.display()))?;
330    }
331    let stamp = Stamp {
332        schema: STAMP_SCHEMA.into(),
333        kind,
334        name: name.into(),
335        version: version.into(),
336        files: files.into_iter().map(|(p, _)| p).collect(),
337    };
338    std::fs::write(&stamp_path, serde_json::to_string_pretty(&stamp)? + "\n")?;
339    Ok(())
340}
341
342fn safe_relative(path: &str) -> bool {
343    Path::new(path)
344        .components()
345        .all(|c| matches!(c, Component::Normal(_)))
346}
347
348fn validate_npm_name(name: &str) -> Result<()> {
349    // A scoped name is exactly `@scope/name`, and npm applies the `.`/`_` rule to each segment:
350    // `@x18n/.hidden`, `@x18n/_private`, `@x18n/fuzzy/extra`, `@x18n` and `@/fuzzy` are all
351    // refused at publish time, so they are refused here instead of in the generated package.
352    let (scope, bare) = match name.strip_prefix('@') {
353        Some(rest) => match rest.split_once('/') {
354            Some((scope, pkg)) => (Some(scope), pkg),
355            None => (None, ""),
356        },
357        None => (None, name),
358    };
359    let segment = |s: &str| !s.is_empty() && !s.starts_with(['.', '_']) && !s.contains(['/', '@']);
360    let ok = segment(bare)
361        && scope.is_none_or(segment)
362        && name.len() <= 214
363        && name.chars().all(|c| {
364            c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '.' | '_' | '@' | '/')
365        });
366    if !ok {
367        bail!("`{name}` is not a valid npm package name (lowercase, URL-safe); pass --name");
368    }
369    Ok(())
370}
371
372/// `MAJOR.MINOR.PATCH` with an optional `-prerelease`, as npm's semver takes it (and PyPI
373/// accepts): no whitespace, no leading zeros in a number.
374fn validate_version(version: &str) -> Result<()> {
375    let number = |s: &str| {
376        !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'))
377    };
378    let (core, pre) = match version.split_once('-') {
379        Some((core, pre)) => (core, Some(pre)),
380        None => (version, None),
381    };
382    let parts: Vec<&str> = core.split('.').collect();
383    let ok = parts.len() == 3
384        && parts.iter().all(|p| number(p))
385        && pre.is_none_or(|pre| {
386            pre.split('.').all(|id| {
387                !id.is_empty()
388                    && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
389                    && (!id.bytes().all(|b| b.is_ascii_digit()) || number(id))
390            })
391        });
392    if !ok {
393        bail!(
394            "`{version}` is not a valid package version (MAJOR.MINOR.PATCH, e.g. 1.2.0); pass --version"
395        );
396    }
397    Ok(())
398}
399
400/// The version of the package the unit belongs to: the nearest `package.json` for JS, the
401/// `pyproject.toml` (or `setup.cfg`, or `__version__`) for Python.
402pub fn original_version(manifest: &Manifest) -> Option<String> {
403    let root = &manifest.root;
404    let unit = root.join(manifest.unit.trim_end_matches('/'));
405    match manifest.language {
406        crate::lang::Lang::Python => python_version(root, &unit),
407        _ => {
408            let mut dir = unit.parent()?.to_path_buf();
409            loop {
410                let pkg = dir.join("package.json");
411                if let Ok(text) = std::fs::read_to_string(&pkg)
412                    && let Ok(value) = serde_json::from_str::<serde_json::Value>(&text)
413                    && let Some(v) = value["version"].as_str()
414                {
415                    return Some(v.to_string());
416                }
417                if dir == *root || !dir.pop() || !dir.starts_with(root) {
418                    return None;
419                }
420            }
421        }
422    }
423}
424
425fn python_version(root: &Path, unit: &Path) -> Option<String> {
426    if let Ok(text) = std::fs::read_to_string(root.join("pyproject.toml"))
427        && let Ok(doc) = text.parse::<toml_edit::DocumentMut>()
428    {
429        let v = doc
430            .get("project")
431            .and_then(|p| p.get("version"))
432            .or_else(|| {
433                doc.get("tool")
434                    .and_then(|t| t.get("poetry"))
435                    .and_then(|p| p.get("version"))
436            })
437            .and_then(|v| v.as_str());
438        if let Some(v) = v {
439            return Some(v.to_string());
440        }
441    }
442    if let Ok(text) = std::fs::read_to_string(root.join("setup.cfg")) {
443        let mut in_metadata = false;
444        for line in text.lines() {
445            let line = line.trim();
446            if line.starts_with('[') {
447                in_metadata = line == "[metadata]";
448            } else if in_metadata
449                && let Some((key, value)) = line.split_once('=')
450                && key.trim() == "version"
451                && !value.trim().starts_with("attr:")
452            {
453                return Some(value.trim().to_string());
454            }
455        }
456    }
457    let init = if unit.is_dir() {
458        unit.join("__init__.py")
459    } else {
460        unit.parent()?.join("__init__.py")
461    };
462    let text = std::fs::read_to_string(init).ok()?;
463    text.lines().find_map(|l| {
464        let rest = l.trim().strip_prefix("__version__")?.trim_start();
465        let rest = rest.strip_prefix('=')?.trim();
466        let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
467        rest[1..].split(quote).next().map(str::to_string)
468    })
469}
470
471fn cargo_version(crate_dir: &Path) -> Option<String> {
472    let text = std::fs::read_to_string(crate_dir.join("Cargo.toml")).ok()?;
473    let doc = text.parse::<toml_edit::DocumentMut>().ok()?;
474    Some(doc.get("package")?.get("version")?.as_str()?.to_string())
475}
476
477/// The dotted module the original unit is imported as: `src/textkit/` is `textkit`,
478/// `src/textkit/words.py` is `textkit.words`. Folders above count while they are packages
479/// (hold `__init__.py`); without the sources, a leading `src/` or `lib/` is dropped.
480pub fn python_module(manifest: &Manifest) -> String {
481    let unit = manifest.unit.trim_end_matches('/');
482    let unit = unit.strip_suffix("/__init__.py").unwrap_or(unit);
483    let unit = unit.strip_suffix(".py").unwrap_or(unit);
484    let parts: Vec<&str> = unit.split('/').filter(|p| !p.is_empty()).collect();
485    let root = &manifest.root;
486    let mut start = parts.len().saturating_sub(1);
487    if root.join(unit).exists() || root.join(format!("{unit}.py")).exists() {
488        while start > 0
489            && root
490                .join(parts[..start].join("/"))
491                .join("__init__.py")
492                .exists()
493        {
494            start -= 1;
495        }
496    } else {
497        start = usize::from(matches!(parts.first(), Some(&"src" | &"lib")) && parts.len() > 1);
498    }
499    parts[start..].join(".")
500}
501
502#[allow(clippy::too_many_arguments)]
503fn python_files(
504    crate_dir: &Path,
505    manifest: &Manifest,
506    name: &str,
507    version: &str,
508    module: &str,
509    out: &Path,
510    files: &mut Vec<(String, Content)>,
511) -> Result<()> {
512    if out.starts_with(crate_dir.join("src")) || out.starts_with(crate_dir.join("python")) {
513        bail!("--out cannot be inside the crate's src/ or python/ folder");
514    }
515    let (wrapper_dir, wrapper_name) = crate::harness_py::package(crate_dir, manifest);
516    let wrapper = wrapper_dir.join(&wrapper_name);
517    if !wrapper.join("__init__.py").exists() {
518        bail!(
519            "{} has no __init__.py; run `rust-anything refresh {}`",
520            wrapper.display(),
521            crate_dir.display()
522        );
523    }
524    let cargo =
525        std::fs::read_to_string(crate_dir.join("Cargo.toml")).context("reading Cargo.toml")?;
526    let mut doc: toml_edit::DocumentMut = cargo.parse().context("parsing Cargo.toml")?;
527    if !doc.contains_key("workspace") {
528        doc.insert("workspace", toml_edit::Item::Table(toml_edit::Table::new()));
529    }
530    files.push(("Cargo.toml".into(), Content::Text(doc.to_string())));
531    for extra in ["Cargo.lock", "build.rs"] {
532        if crate_dir.join(extra).exists() {
533            files.push((extra.into(), Content::Copy(crate_dir.join(extra))));
534        }
535    }
536    for file in tree(&crate_dir.join("src"))? {
537        files.push((
538            format!("src/{}", slash(&file)),
539            Content::Copy(crate_dir.join("src").join(&file)),
540        ));
541    }
542    let module_dir = format!("python/{}", module.replace('.', "/"));
543    for file in tree(&wrapper)? {
544        let file_name = file.file_name().unwrap_or_default().to_string_lossy();
545        if file_name.starts_with("_native.")
546            || file.components().any(|c| c.as_os_str() == "__pycache__")
547        {
548            continue;
549        }
550        files.push((
551            format!("{module_dir}/{}", slash(&file)),
552            Content::Copy(wrapper.join(&file)),
553        ));
554    }
555    files.push((
556        "pyproject.toml".into(),
557        Content::Text(pyproject(manifest, name, version, module)),
558    ));
559    files.push((
560        ".gitignore".into(),
561        Content::Text("target/\ndist/\n*.so\n*.pyd\n__pycache__/\n".into()),
562    ));
563    Ok(())
564}
565
566fn pyproject(manifest: &Manifest, name: &str, version: &str, module: &str) -> String {
567    format!(
568        "[build-system]\nrequires = [\"maturin>=1.7,<2\"]\nbuild-backend = \"maturin\"\n\n\
569         [project]\nname = \"{name}\"\nversion = \"{version}\"\n\
570         description = \"Rust port of `{unit}`, generated by rust-anything\"\n\
571         requires-python = \">=3.9\"\n\
572         classifiers = [\"Programming Language :: Rust\", \"Programming Language :: Python :: Implementation :: CPython\"]\n\n\
573         [tool.maturin]\nbindings = \"pyo3\"\nmodule-name = \"{module}._native\"\npython-source = \"python\"\n",
574        unit = manifest.unit
575    )
576}
577
578#[allow(clippy::too_many_arguments)]
579fn napi_files(
580    crate_dir: &Path,
581    manifest: &Manifest,
582    name: &str,
583    version: &str,
584    opts: &Options,
585    out: &Path,
586    files: &mut Vec<(String, Content)>,
587    notes: &mut Vec<String>,
588) -> Result<()> {
589    let lib = manifest.lib_name();
590    let index = std::fs::read_to_string(crate_dir.join("index.cjs")).with_context(|| {
591        format!(
592            "reading index.cjs (run `rust-anything refresh {}`)",
593            crate_dir.display()
594        )
595    })?;
596    let load = format!("require('./{lib}.node')");
597    if !index.contains(&load) {
598        bail!(
599            "index.cjs does not load `./{lib}.node`; run `rust-anything refresh {}` to regenerate it",
600            crate_dir.display()
601        );
602    }
603    files.push((
604        "binding.cjs".into(),
605        Content::Text(index.replacen(&load, "require('./native.cjs').load().binding", 1)),
606    ));
607    files.push(("native.cjs".into(), Content::Text(native_cjs(name, &lib))));
608
609    let mut shipped = vec!["index.cjs", "binding.cjs", "native.cjs"];
610    let fallback = match &opts.fallback {
611        Some(spec) => Some(spec.clone()),
612        None => match original_fallback(manifest) {
613            Ok((file, path)) => {
614                files.push((format!("fallback/{file}"), Content::Copy(path)));
615                shipped.push("fallback/");
616                Some(format!("./fallback/{file}"))
617            }
618            Err(why) => {
619                notes.push(format!(
620                    "No fallback: {why}. On a platform without a binary the package throws; pass \
621                     --fallback <module> (e.g. the original npm package) to load it instead."
622                ));
623                None
624            }
625        },
626    };
627    files.push((
628        "index.cjs".into(),
629        Content::Text(index_cjs(name, fallback.as_deref())),
630    ));
631
632    let mut optional = serde_json::Map::new();
633    for p in PLATFORMS {
634        let pkg = format!("{name}-{}", p.key);
635        optional.insert(pkg.clone(), json!(version));
636        let node = format!("{lib}.{}.node", p.key);
637        let mut platform = json!({
638            "name": pkg,
639            "version": version,
640            "description": format!("{} binary of {name}, generated by rust-anything", p.target),
641            "main": node,
642            "files": [node],
643            "os": [p.os],
644            "cpu": [p.cpu],
645        });
646        if let Some(libc) = p.libc {
647            platform["libc"] = json!([libc]);
648        }
649        files.push((
650            format!("npm/{}/package.json", p.key),
651            Content::Text(serde_json::to_string_pretty(&platform)? + "\n"),
652        ));
653    }
654    let main = json!({
655        "name": name,
656        "version": version,
657        "description": format!("Rust port of `{}`, generated by rust-anything", manifest.unit),
658        "main": "index.cjs",
659        "files": shipped,
660        "optionalDependencies": optional,
661    });
662    files.push((
663        "package.json".into(),
664        Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
665    ));
666    files.push((
667        ".gitignore".into(),
668        Content::Text("target/\ntarballs/\nnpm-built/\n*.node\n*.tgz\n".into()),
669    ));
670
671    let built = crate_dir.join(format!("{lib}.node"));
672    match host_key() {
673        Some(key) if built.exists() => {
674            files.push((
675                format!("npm/{key}/{lib}.{key}.node"),
676                Content::Copy(built.clone()),
677            ));
678            if crate::harness::sources_newer_than(crate_dir, &built) {
679                notes.push(format!(
680                    "{} is older than the crate's sources; run `rust-anything build {}` and \
681                     package again",
682                    built.display(),
683                    crate_dir.display()
684                ));
685            }
686            notes.push(format!(
687                "This machine's binary is in npm/{key}/. To try it: npm pack {0}/npm/{key} and \
688                 npm pack {0}, then npm install both tarballs.",
689                out.display()
690            ));
691        }
692        Some(_) => notes.push(format!(
693            "No {lib}.node in the crate: run `rust-anything build {}` and package again to try \
694             the package on this machine.",
695            crate_dir.display()
696        )),
697        None => {}
698    }
699    Ok(())
700}
701
702/// The original unit as a file the package can ship and require: one JS file that imports
703/// nothing.
704fn original_fallback(manifest: &Manifest) -> Result<(String, PathBuf), String> {
705    let path = manifest.root.join(&manifest.unit);
706    if !path.is_file() {
707        return Err(format!(
708            "the original `{}` is not a single file in {}",
709            manifest.unit,
710            manifest.root.display()
711        ));
712    }
713    let file = path
714        .file_name()
715        .map(|f| f.to_string_lossy().to_string())
716        .unwrap_or_default();
717    if ["ts", "mts", "cts", "tsx"]
718        .iter()
719        .any(|e| file.ends_with(&format!(".{e}")))
720    {
721        return Err(format!(
722            "`{file}` is TypeScript, and Node does not strip types under node_modules"
723        ));
724    }
725    if !["js", "cjs", "mjs"]
726        .iter()
727        .any(|e| file.ends_with(&format!(".{e}")))
728    {
729        return Err(format!("`{file}` is not a JS file"));
730    }
731    let text = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
732    let imports = text.lines().any(|l| {
733        let l = l.trim_start();
734        l.starts_with("import ")
735            || l.starts_with("import{")
736            || (l.starts_with("export ") && l.contains(" from "))
737            || l.contains("require(")
738            || l.contains("import(")
739    });
740    if imports {
741        return Err(format!("`{file}` imports other modules"));
742    }
743    Ok((file, path))
744}
745
746fn index_cjs(name: &str, fallback: Option<&str>) -> String {
747    let otherwise = match fallback {
748        Some(spec) => format!("  module.exports = require({})\n", js_string(spec)),
749        None => format!(
750            "  throw new Error(\n    `{name} has no Rust build for ${{key}} (built for: ${{supported.join(', ')}})` +\n      (errors.length ? `:\\n${{errors.join('\\n')}}` : '')\n  )\n"
751        ),
752    };
753    format!(
754        "'use strict'\n// Generated by `rust-anything package`: the Rust port for this platform, or the original.\n\
755         const {{ load, supported }} = require('./native.cjs')\nconst {{ binding, key, errors }} = load()\n\
756         if (binding && process.env.RUST_ANYTHING_MODE !== 'old') {{\n  module.exports = require('./binding.cjs')\n}} else {{\n{otherwise}}}\n"
757    )
758}
759
760fn native_cjs(name: &str, lib: &str) -> String {
761    let keys: Vec<String> = PLATFORMS.iter().map(|p| format!("'{}'", p.key)).collect();
762    format!(
763        r#"'use strict'
764// Generated by `rust-anything package`: finds the binary for this platform.
765const {{ platform, arch }} = process
766
767function abi() {{
768  if (platform === 'win32') return '-msvc'
769  if (platform !== 'linux') return ''
770  try {{
771    return process.report.getReport().header.glibcVersionRuntime ? '-gnu' : '-musl'
772  }} catch {{
773    return '-gnu'
774  }}
775}}
776
777const key = `${{platform}}-${{arch}}${{abi()}}`
778const supported = [{keys}]
779let loaded = null
780
781function load() {{
782  if (loaded) return loaded
783  const errors = []
784  let binding = null
785  if (supported.includes(key)) {{
786    for (const id of [`./npm/${{key}}/{lib}.${{key}}.node`, `{name}-${{key}}`]) {{
787      try {{
788        binding = require(id)
789        break
790      }} catch (e) {{
791        errors.push(`${{id}}: ${{e.message.split('\n')[0]}}`)
792      }}
793    }}
794  }}
795  loaded = {{ binding, key, errors }}
796  return loaded
797}}
798
799module.exports = {{ load, key, supported }}
800"#,
801        keys = keys.join(", ")
802    )
803}
804
805fn js_string(s: &str) -> String {
806    serde_json::to_string(s).unwrap_or_else(|_| "''".into())
807}
808
809fn wasm_files(
810    crate_dir: &Path,
811    manifest: &Manifest,
812    name: &str,
813    version: &str,
814    files: &mut Vec<(String, Content)>,
815) -> Result<()> {
816    let pkg = crate_dir.join("pkg");
817    let lib = manifest.lib_name();
818    if !pkg.join(format!("{lib}.js")).exists() {
819        bail!(
820            "no wasm build in {}; run `rust-anything build {}` first",
821            pkg.display(),
822            crate_dir.display()
823        );
824    }
825    files.push((
826        "index.cjs".into(),
827        Content::Copy(crate_dir.join("index.cjs")),
828    ));
829    for file in tree(&pkg)? {
830        let file_name = file.file_name().unwrap_or_default().to_string_lossy();
831        if file_name == ".gitignore" || file_name == "package.json" {
832            continue;
833        }
834        files.push((
835            format!("pkg/{}", slash(&file)),
836            Content::Copy(pkg.join(&file)),
837        ));
838    }
839    let main = json!({
840        "name": name,
841        "version": version,
842        "description": format!("Rust port of `{}` (WebAssembly), generated by rust-anything", manifest.unit),
843        "main": "index.cjs",
844        "types": format!("pkg/{lib}.d.ts"),
845        "files": ["index.cjs", "pkg/"],
846    });
847    files.push((
848        "package.json".into(),
849        Content::Text(serde_json::to_string_pretty(&main)? + "\n"),
850    ));
851    Ok(())
852}
853
854/// The GitHub Actions workflow, written inside the output folder; GitHub runs workflows only
855/// from the repository's `.github/workflows`, so the note says where to move it.
856fn workflow_file(
857    manifest: &Manifest,
858    name: &str,
859    version: &str,
860    crate_dir: &Path,
861    out: &Path,
862) -> Result<((String, Content), String)> {
863    let repo = git_root(out);
864    let out_rel = repo
865        .as_deref()
866        .and_then(|r| relative(r, out))
867        .unwrap_or_else(|| ".".into());
868    let slug: String = name
869        .trim_start_matches('@')
870        .chars()
871        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
872        .collect();
873    let (file, text) = match manifest.kind {
874        Kind::Pyo3 => (
875            format!("{slug}-wheels.yml"),
876            wheels_yml(name, version, &python_module(manifest), &out_rel),
877        ),
878        _ => {
879            let crate_rel = relative(out, crate_dir).context("relating the crate to --out")?;
880            (
881                format!("{slug}-npm.yml"),
882                npm_yml(name, version, &manifest.lib_name(), &out_rel, &crate_rel),
883            )
884        }
885    };
886    let path = format!(".github/workflows/{file}");
887    let note = match &repo {
888        Some(repo) => format!(
889            "CI: move {path} to {}/.github/workflows/ (GitHub runs workflows only from there); it \
890             builds every platform and uploads the packages as artifacts.",
891            repo.display()
892        ),
893        None => format!(
894            "CI: {path} assumes {} is the repository root; move it to the repository's \
895             .github/workflows/ and set `working-directory` to this folder.",
896            out.display()
897        ),
898    };
899    Ok(((path, Content::Text(text)), note))
900}
901
902fn wheels_yml(name: &str, version: &str, module: &str, dir: &str) -> String {
903    format!(
904        r#"# Generated by `rust-anything package`: abi3 wheels of {name} {version} (one per platform,
905# every CPython from 3.9 on) and an sdist, uploaded as artifacts. Nothing is published.
906name: {name} wheels
907
908on:
909  workflow_dispatch:
910  push:
911    tags: ['v*']
912
913defaults:
914  run:
915    shell: bash
916    working-directory: {dir}
917
918jobs:
919  wheels:
920    name: ${{{{ matrix.target }}}}
921    runs-on: ${{{{ matrix.os }}}}
922    strategy:
923      fail-fast: false
924      matrix:
925        include:
926          - {{ os: macos-latest, target: aarch64-apple-darwin, check: true }}
927          - {{ os: macos-latest, target: x86_64-apple-darwin, check: false }}
928          - {{ os: ubuntu-latest, target: x86_64-unknown-linux-gnu, check: true }}
929          - {{ os: ubuntu-latest, target: aarch64-unknown-linux-gnu, check: false }}
930          - {{ os: windows-latest, target: x86_64-pc-windows-msvc, check: true }}
931    steps:
932      - uses: actions/checkout@v4
933      - uses: actions/setup-python@v5
934        with:
935          python-version: '3.12'
936      - uses: PyO3/maturin-action@v1
937        with:
938          target: ${{{{ matrix.target }}}}
939          manylinux: auto
940          args: --release --out dist
941          working-directory: {dir}
942      - name: Import check
943        if: matrix.check
944        run: |
945          python -m pip install {name} --no-index --find-links dist --force-reinstall
946          python -c "import {module}"
947      - uses: actions/upload-artifact@v4
948        with:
949          name: wheel-${{{{ matrix.target }}}}
950          path: {dir}/dist
951
952  sdist:
953    runs-on: ubuntu-latest
954    steps:
955      - uses: actions/checkout@v4
956      - uses: PyO3/maturin-action@v1
957        with:
958          command: sdist
959          args: --out dist
960          working-directory: {dir}
961      - uses: actions/upload-artifact@v4
962        with:
963          name: sdist
964          path: {dir}/dist
965"#
966    )
967}
968
969fn npm_yml(name: &str, version: &str, lib: &str, dir: &str, crate_rel: &str) -> String {
970    let matrix: String = PLATFORMS
971        .iter()
972        .map(|p| {
973            let file = match p.os {
974                "darwin" => format!("lib{lib}.dylib"),
975                "linux" => format!("lib{lib}.so"),
976                _ => format!("{lib}.dll"),
977            };
978            format!(
979                "          - {{ key: {}, target: {}, os: {}, lib: {file}, check: {} }}\n",
980                p.key, p.target, p.runner, p.native
981            )
982        })
983        .collect();
984    format!(
985        r#"# Generated by `rust-anything package`: the {name} {version} npm packages (one per
986# platform, plus the main one), packed and uploaded as artifacts. Nothing is published.
987name: {name} npm packages
988
989on:
990  workflow_dispatch:
991  push:
992    tags: ['v*']
993
994defaults:
995  run:
996    shell: bash
997    working-directory: {dir}
998
999jobs:
1000  build:
1001    name: ${{{{ matrix.key }}}}
1002    runs-on: ${{{{ matrix.os }}}}
1003    strategy:
1004      fail-fast: false
1005      matrix:
1006        include:
1007{matrix}    steps:
1008      - uses: actions/checkout@v4
1009      - uses: actions/setup-node@v4
1010        with:
1011          node-version: 22
1012      - run: rustup target add ${{{{ matrix.target }}}}
1013      - run: cargo build --release --target ${{{{ matrix.target }}}} --manifest-path {crate_rel}/Cargo.toml --target-dir target
1014      - run: cp target/${{{{ matrix.target }}}}/release/${{{{ matrix.lib }}}} npm/${{{{ matrix.key }}}}/{lib}.${{{{ matrix.key }}}}.node
1015      - name: Load check
1016        if: matrix.check
1017        run: node -e "const r = require('./native.cjs').load(); if (!r.binding) throw new Error(r.errors.join('\n'))"
1018      - uses: actions/upload-artifact@v4
1019        with:
1020          name: npm-${{{{ matrix.key }}}}
1021          path: {dir}/npm/${{{{ matrix.key }}}}/*.node
1022
1023  pack:
1024    needs: build
1025    runs-on: ubuntu-latest
1026    steps:
1027      - uses: actions/checkout@v4
1028      - uses: actions/setup-node@v4
1029        with:
1030          node-version: 22
1031      - uses: actions/download-artifact@v4
1032        with:
1033          pattern: npm-*
1034          path: {dir}/npm-built
1035      - run: |
1036          for built in npm-built/npm-*; do cp "$built"/*.node "npm/${{built##*/npm-}}/"; done
1037          mkdir -p tarballs
1038          for platform in npm/*/; do npm pack "./$platform" --pack-destination tarballs; done
1039          npm pack --pack-destination tarballs
1040      - uses: actions/upload-artifact@v4
1041        with:
1042          name: npm-tarballs
1043          path: {dir}/tarballs
1044"#
1045    )
1046}
1047
1048fn git_root(from: &Path) -> Option<PathBuf> {
1049    let mut dir = from.to_path_buf();
1050    loop {
1051        if dir.join(".git").exists() {
1052            return Some(dir);
1053        }
1054        if !dir.pop() {
1055            return None;
1056        }
1057    }
1058}
1059
1060/// `to` relative to `from`, with `/` separators; `.` when they are the same folder.
1061fn relative(from: &Path, to: &Path) -> Option<String> {
1062    let from: Vec<Component> = from.components().collect();
1063    let to: Vec<Component> = to.components().collect();
1064    if from.first() != to.first() {
1065        return None;
1066    }
1067    let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
1068    let mut parts: Vec<String> = vec!["..".into(); from.len() - common];
1069    parts.extend(
1070        to[common..]
1071            .iter()
1072            .map(|c| c.as_os_str().to_string_lossy().to_string()),
1073    );
1074    Some(if parts.is_empty() {
1075        ".".into()
1076    } else {
1077        parts.join("/")
1078    })
1079}
1080
1081/// Every file under `dir`, relative to it, sorted.
1082fn tree(dir: &Path) -> Result<Vec<PathBuf>> {
1083    let mut out = Vec::new();
1084    let mut stack = vec![PathBuf::new()];
1085    while let Some(rel) = stack.pop() {
1086        let entries = std::fs::read_dir(dir.join(&rel))
1087            .with_context(|| format!("reading {}", dir.display()))?;
1088        for entry in entries {
1089            let entry = entry?;
1090            let path = rel.join(entry.file_name());
1091            if entry.file_type()?.is_dir() {
1092                stack.push(path);
1093            } else {
1094                out.push(path);
1095            }
1096        }
1097    }
1098    out.sort();
1099    Ok(out)
1100}
1101
1102fn slash(path: &Path) -> String {
1103    path.components()
1104        .map(|c| c.as_os_str().to_string_lossy())
1105        .collect::<Vec<_>>()
1106        .join("/")
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111    use super::*;
1112
1113    #[test]
1114    fn relative_paths() {
1115        assert_eq!(
1116            relative(Path::new("/r/a/package"), Path::new("/r/a")).as_deref(),
1117            Some("..")
1118        );
1119        assert_eq!(
1120            relative(Path::new("/r"), Path::new("/r/rust/x/package")).as_deref(),
1121            Some("rust/x/package")
1122        );
1123        assert_eq!(
1124            relative(Path::new("/r"), Path::new("/r")).as_deref(),
1125            Some(".")
1126        );
1127    }
1128
1129    #[test]
1130    fn npm_names() {
1131        assert!(validate_npm_name("fuzzy-rs").is_ok());
1132        assert!(validate_npm_name("@x18n/fuzzy").is_ok());
1133        assert!(validate_npm_name("Fuzzy").is_err());
1134        assert!(validate_npm_name("@x18n/").is_err());
1135        // npm applies the `.`/`_` rule to each segment, and a scope is `@scope/name` exactly.
1136        assert!(validate_npm_name("@x18n/.hidden").is_err());
1137        assert!(validate_npm_name("@x18n/_private").is_err());
1138        assert!(validate_npm_name("@x18n/fuzzy/extra").is_err());
1139        assert!(validate_npm_name("@x18n").is_err());
1140        assert!(validate_npm_name("@/fuzzy").is_err());
1141        assert!(validate_npm_name("fuzzy/extra").is_err());
1142        assert!(validate_npm_name("fuzzy@1").is_err());
1143        assert!(validate_npm_name("@x18n/fuzzy@1").is_err());
1144    }
1145
1146    #[test]
1147    fn package_versions() {
1148        for ok in ["1.2.3", "0.1.0", "1.2.3-beta.1", "10.0.0-rc-1", "1.0.0-0"] {
1149            assert!(validate_version(ok).is_ok(), "{ok}");
1150        }
1151        for bad in [
1152            "",
1153            "bogus",
1154            "1.0",
1155            " 1.0.0",
1156            "1.0.0 ",
1157            "1.2.3.4",
1158            "01.2.3",
1159            "1.2.3-",
1160            "1.2.3-beta..1",
1161            "1.2.3-01",
1162            "v1.2.3",
1163        ] {
1164            assert!(validate_version(bad).is_err(), "{bad:?}");
1165        }
1166    }
1167
1168    #[test]
1169    fn every_platform_has_a_unique_key() {
1170        let mut keys: Vec<&str> = PLATFORMS.iter().map(|p| p.key).collect();
1171        keys.sort_unstable();
1172        keys.dedup();
1173        assert_eq!(keys.len(), PLATFORMS.len());
1174    }
1175
1176    #[test]
1177    fn stamp_paths_stay_inside() {
1178        assert!(safe_relative("npm/darwin-arm64/package.json"));
1179        assert!(!safe_relative("../x"));
1180        assert!(!safe_relative("/etc/passwd"));
1181    }
1182}