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