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