fallow-core 3.36.0

Internal detector backend for fallow-engine and fallow-api
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! napi-rs native package plugin.
//!
//! napi-rs packages publish platform-specific prebuilt binaries as optional
//! dependencies. Their generated loader selects the matching package at runtime,
//! so source imports do not show those packages as statically used.
//!
//! `napi prepublish` adds the platform packages to `optionalDependencies` only
//! at publish time, so a source repository has none. The plugin therefore
//! activates on the `napi` field and its `targets`, and credits the imports of the
//! generated loader and WASI worker.
//!
//! The loader can sit in a direct subdirectory of the package when the build
//! runs with `--cwd` or `--output-dir`. The WASI workers and `browser.js` of
//! that directory count as generated too.
//!
//! The generated loader and `browser.js` are support entry points. Their
//! exports mirror the Rust bindings, so a hand-written wrapper that reuses a
//! binding name is not a duplicate export, and an unused binding is not an
//! unused export of the generated file.

use std::io::Read;
use std::path::Path;

use fallow_config::{NapiConfig, PackageJson};
use rustc_hash::FxHashSet;

use super::{Plugin, PluginResult, ProvidedDependencyRule};

/// The header comment that `napi build` writes at the top of the loader.
const LOADER_HEADER: &str = "auto-generated by NAPI-RS";

/// How many leading bytes of a candidate file to read for the header.
const LOADER_HEADER_SCAN_BYTES: u64 = 512;

/// The extensions that `napi build` uses for the JavaScript loader.
const LOADER_EXTENSIONS: &[&str] = &["js", "cjs", "mjs"];

/// The child directories that never hold the loader of the package itself:
/// installed packages, the Cargo build output, and bundler output.
const SKIPPED_LOADER_DIRS: &[&str] = &["node_modules", "target", "dist", "build", "out"];

/// The most script files that a child directory can hold and still be read
/// for a loader. A build output directory holds few files, and the limit keeps
/// a large source directory from costing one file read per script.
const MAX_SUBDIR_LOADER_CANDIDATES: usize = 32;

/// The WASI workers that `napi build` generates for the `wasm32-wasi*` targets.
const WASI_WORKERS: &str = "wasi-worker*.mjs";

/// The runtime that the generated WASI code imports. The published
/// `<pkg>-wasm32-wasi` package declares it, not the source package.
const WASM_RUNTIME: &str = "@napi-rs/wasm-runtime";

/// The suffixes of the build artifacts that the generated loader requires:
/// the native addons `<binaryName>.<platform>.node` and the WASI loaders
/// `<binaryName>.wasi.cjs` and `<binaryName>.wasi-browser.js`. The build
/// writes them next to the loader, and a source repository usually ignores
/// them in git.
const GENERATED_BUILD_ARTIFACTS: &[&str] = &[".node", ".wasi.cjs", ".wasi-browser"];

/// The browser entry that `napi build` writes for a `wasm32-wasi*` target. It
/// has no header: its only content is a re-export of `<pkg>-wasm32-wasi`.
const BROWSER_ENTRY: &str = "browser.js";

/// The package suffix that the generated browser entry re-exports.
const WASM32_WASI_SUFFIX: &str = "wasm32-wasi";

const ALWAYS_USED: &[&str] = &[WASI_WORKERS];

pub struct NapiRsPlugin;

impl Plugin for NapiRsPlugin {
    fn name(&self) -> &'static str {
        "napi-rs"
    }

    fn is_enabled_with_package_json(&self, pkg: &PackageJson, _root: &Path) -> bool {
        pkg.napi
            .as_ref()
            .is_some_and(|napi| package_base(pkg, napi).is_some() && !napi.targets.is_empty())
    }

    fn always_used(&self) -> &'static [&'static str] {
        ALWAYS_USED
    }

    fn generated_import_patterns(&self) -> &'static [&'static str] {
        GENERATED_BUILD_ARTIFACTS
    }

    fn package_json_referenced_dependencies(&self, pkg: &PackageJson, _root: &Path) -> Vec<String> {
        referenced_optional_dependencies(pkg)
    }

    fn resolve_package_json(&self, pkg: &PackageJson, root: &Path) -> PluginResult {
        let Some(base) = pkg.napi.as_ref().and_then(|napi| package_base(pkg, napi)) else {
            return PluginResult::default();
        };
        let mut result = PluginResult::default();
        let loaders = generated_loaders(root);
        let mut output_dirs: Vec<&str> = loaders.iter().map(|loader| loader_dir(loader)).collect();
        output_dirs.push("");
        output_dirs.sort_unstable();
        output_dirs.dedup();
        for dir in output_dirs {
            let workers = format!("{dir}{WASI_WORKERS}");
            if !dir.is_empty() {
                result.always_used_files.push(workers.clone());
            }
            result
                .provided_dependencies
                .push(ProvidedDependencyRule::new(
                    workers,
                    [WASM_RUNTIME],
                    [format!("{WASM_RUNTIME}/")],
                ));
            let browser_entry = format!("{dir}{BROWSER_ENTRY}");
            if is_generated_browser_entry(&root.join(&browser_entry), base) {
                result.push_entry_pattern(browser_entry.clone());
                result
                    .provided_dependencies
                    .push(ProvidedDependencyRule::new(
                        browser_entry,
                        [format!("{base}-{WASM32_WASI_SUFFIX}")],
                        std::iter::empty::<String>(),
                    ));
            }
        }
        let platform_prefix = format!("{base}-");
        for loader in loaders {
            result.push_entry_pattern(loader.clone());
            result
                .provided_dependencies
                .push(ProvidedDependencyRule::new(
                    loader,
                    [WASM_RUNTIME.to_string()],
                    [platform_prefix.clone(), format!("{WASM_RUNTIME}/")],
                ));
        }
        result
    }
}

/// The directory part of a loader path, with its trailing `/`.
fn loader_dir(loader: &str) -> &str {
    loader.rfind('/').map_or("", |slash| &loader[..=slash])
}

/// Whether `path` holds only the one-line re-export that `napi build` writes
/// to `browser.js`, so a hand-written browser entry stays checked.
fn is_generated_browser_entry(path: &Path, base: &str) -> bool {
    let Ok(source) = std::fs::read_to_string(path) else {
        return false;
    };
    let Some(specifier) = source
        .trim()
        .strip_prefix("export * from ")
        .map(|rest| rest.trim_end_matches(';').trim())
    else {
        return false;
    };
    let expected = format!("{base}-{WASM32_WASI_SUFFIX}");
    ['\'', '"'].iter().any(|quote| {
        specifier
            .strip_prefix(*quote)
            .and_then(|rest| rest.strip_suffix(*quote))
            == Some(expected.as_str())
    })
}

/// The paths of the generated loaders, relative to the package directory.
///
/// `napi build` writes the loader next to `package.json` by default.
/// `--cwd <dir>` and `--output-dir <dir>` write it to a subdirectory, so the
/// search also reads each direct child directory, except installed packages,
/// the Cargo build output and hidden directories. A file counts as a loader
/// only when its header names NAPI-RS, so a hand-written file that imports a
/// platform package stays checked.
fn generated_loaders(root: &Path) -> Vec<String> {
    let mut loaders = loaders_in(root, "", usize::MAX);
    let Ok(entries) = std::fs::read_dir(root) else {
        return loaders;
    };
    for entry in entries.filter_map(Result::ok) {
        if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
            continue;
        }
        let Ok(name) = entry.file_name().into_string() else {
            continue;
        };
        if name.starts_with('.') || SKIPPED_LOADER_DIRS.contains(&name.as_str()) {
            continue;
        }
        loaders.extend(loaders_in(
            &entry.path(),
            &format!("{name}/"),
            MAX_SUBDIR_LOADER_CANDIDATES,
        ));
    }
    loaders.sort();
    loaders
}

/// The loaders directly in `dir`, each with `prefix` before its file name.
/// A directory with more than `max_candidates` script files gives none.
fn loaders_in(dir: &Path, prefix: &str, max_candidates: usize) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let candidates: Vec<String> = entries
        .filter_map(Result::ok)
        .filter_map(|entry| entry.file_name().into_string().ok())
        .filter(|name| {
            Path::new(name)
                .extension()
                .and_then(|ext| ext.to_str())
                .is_some_and(|ext| LOADER_EXTENSIONS.contains(&ext))
        })
        .take(max_candidates.saturating_add(1))
        .collect();
    if candidates.len() > max_candidates {
        return Vec::new();
    }
    candidates
        .into_iter()
        .filter(|name| {
            let path = dir.join(name);
            path.is_file() && has_loader_header(&path)
        })
        .map(|name| format!("{prefix}{name}"))
        .collect()
}

fn has_loader_header(path: &Path) -> bool {
    let Ok(file) = std::fs::File::open(path) else {
        return false;
    };
    let mut head = Vec::new();
    if file
        .take(LOADER_HEADER_SCAN_BYTES)
        .read_to_end(&mut head)
        .is_err()
    {
        return false;
    }
    String::from_utf8_lossy(&head).contains(LOADER_HEADER)
}

fn package_base<'a>(pkg: &'a PackageJson, napi: &'a NapiConfig) -> Option<&'a str> {
    napi.package_name
        .as_deref()
        .or(pkg.name.as_deref())
        .map(str::trim)
        .filter(|name| !name.is_empty())
}

fn referenced_optional_dependencies(pkg: &PackageJson) -> Vec<String> {
    let Some(napi) = &pkg.napi else {
        return Vec::new();
    };
    let Some(base) = package_base(pkg, napi) else {
        return Vec::new();
    };
    let optional_dependencies: FxHashSet<String> =
        pkg.optional_dependency_names().into_iter().collect();
    if optional_dependencies.is_empty() {
        return Vec::new();
    }

    let mut referenced: Vec<String> = napi
        .targets
        .iter()
        .filter_map(|target| target_suffix(target))
        .map(|suffix| format!("{base}-{suffix}"))
        .filter(|dependency| optional_dependencies.contains(dependency))
        .collect();
    referenced.sort();
    referenced.dedup();
    referenced
}

fn target_suffix(target: &str) -> Option<&'static str> {
    match target.trim() {
        "aarch64-apple-darwin" => Some("darwin-arm64"),
        "x86_64-apple-darwin" => Some("darwin-x64"),
        "aarch64-linux-android" => Some("android-arm64"),
        "armv7-linux-androideabi" => Some("android-arm-eabi"),
        "i686-linux-android" => Some("android-ia32"),
        "x86_64-linux-android" => Some("android-x64"),
        "aarch64-pc-windows-msvc" => Some("win32-arm64-msvc"),
        "i686-pc-windows-msvc" => Some("win32-ia32-msvc"),
        "x86_64-pc-windows-msvc" => Some("win32-x64-msvc"),
        "aarch64-unknown-freebsd" => Some("freebsd-arm64"),
        "x86_64-unknown-freebsd" => Some("freebsd-x64"),
        "aarch64-unknown-linux-gnu" => Some("linux-arm64-gnu"),
        "aarch64-unknown-linux-musl" => Some("linux-arm64-musl"),
        "armv7-unknown-linux-gnueabihf" => Some("linux-arm-gnueabihf"),
        "x86_64-unknown-linux-gnu" => Some("linux-x64-gnu"),
        "x86_64-unknown-linux-musl" => Some("linux-x64-musl"),
        "wasm32-wasi" | "wasm32-wasip1" => Some("wasm32-wasi"),
        "wasm32-wasi-preview1-threads" | "wasm32-wasip1-threads" => {
            Some("wasm32-wasi-singlethreaded")
        }
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn pkg(raw: &str) -> PackageJson {
        serde_json::from_str(raw).expect("package json")
    }

    fn resolve(raw: &str) -> Vec<String> {
        referenced_optional_dependencies(&pkg(raw))
    }

    #[test]
    fn maps_common_targets_to_napi_package_suffixes() {
        for (target, suffix) in [
            ("aarch64-apple-darwin", "darwin-arm64"),
            ("x86_64-apple-darwin", "darwin-x64"),
            ("aarch64-unknown-linux-gnu", "linux-arm64-gnu"),
            ("aarch64-unknown-linux-musl", "linux-arm64-musl"),
            ("x86_64-unknown-linux-gnu", "linux-x64-gnu"),
            ("x86_64-unknown-linux-musl", "linux-x64-musl"),
            ("aarch64-pc-windows-msvc", "win32-arm64-msvc"),
            ("x86_64-pc-windows-msvc", "win32-x64-msvc"),
            ("wasm32-wasip1", "wasm32-wasi"),
            ("wasm32-wasip1-threads", "wasm32-wasi-singlethreaded"),
        ] {
            assert_eq!(target_suffix(target), Some(suffix));
        }
    }

    #[test]
    fn credits_scoped_optional_packages_from_package_name() {
        let referenced = resolve(
            r#"{
                "name": "@srcmap/codec",
                "optionalDependencies": {
                    "@srcmap/codec-darwin-arm64": "1.0.0",
                    "@srcmap/codec-linux-x64-gnu": "1.0.0",
                    "unused-optional-pkg": "1.0.0"
                },
                "napi": {
                    "binaryName": "srcmap-codec",
                    "targets": [
                        "aarch64-apple-darwin",
                        "x86_64-unknown-linux-gnu"
                    ]
                }
            }"#,
        );

        assert_eq!(
            referenced,
            vec![
                "@srcmap/codec-darwin-arm64".to_string(),
                "@srcmap/codec-linux-x64-gnu".to_string()
            ]
        );
    }

    #[test]
    fn package_name_overrides_manifest_name() {
        let referenced = resolve(
            r#"{
                "name": "development-helper",
                "optionalDependencies": {
                    "@oxc-coverage-instrument/binding-win32-arm64-msvc": "1.0.0",
                    "@oxc-coverage-instrument/binding-wasm32-wasi": "1.0.0",
                    "@oxc-coverage-instrument/binding-wasm32-wasi-singlethreaded": "1.0.0"
                },
                "napi": {
                    "packageName": "@oxc-coverage-instrument/binding",
                    "targets": [
                        "aarch64-pc-windows-msvc",
                        "wasm32-wasip1",
                        "wasm32-wasip1-threads"
                    ]
                }
            }"#,
        );

        assert_eq!(
            referenced,
            vec![
                "@oxc-coverage-instrument/binding-wasm32-wasi".to_string(),
                "@oxc-coverage-instrument/binding-wasm32-wasi-singlethreaded".to_string(),
                "@oxc-coverage-instrument/binding-win32-arm64-msvc".to_string()
            ]
        );
    }

    #[test]
    fn credits_unscoped_optional_packages() {
        let referenced = resolve(
            r#"{
                "name": "snappy",
                "optionalDependencies": {
                    "snappy-linux-x64-gnu": "1.0.0"
                },
                "napi": {
                    "targets": ["x86_64-unknown-linux-gnu"]
                }
            }"#,
        );

        assert_eq!(referenced, vec!["snappy-linux-x64-gnu"]);
    }

    #[test]
    fn does_not_credit_binary_name_as_package_base() {
        let referenced = resolve(
            r#"{
                "optionalDependencies": {
                    "srcmap-codec-darwin-arm64": "1.0.0"
                },
                "napi": {
                    "binaryName": "srcmap-codec",
                    "targets": ["aarch64-apple-darwin"]
                }
            }"#,
        );

        assert!(referenced.is_empty());
    }

    #[test]
    fn ignores_missing_optional_dependencies_and_unknown_targets() {
        let referenced = resolve(
            r#"{
                "name": "@scope/native",
                "optionalDependencies": {
                    "@scope/native-linux-x64-gnu": "1.0.0"
                },
                "napi": {
                    "targets": [
                        "x86_64-unknown-linux-gnu",
                        "unknown-target"
                    ]
                }
            }"#,
        );

        assert_eq!(referenced, vec!["@scope/native-linux-x64-gnu"]);
    }

    #[test]
    fn activates_without_optional_dependencies() {
        let root = Path::new("/");
        let source_repo = pkg(r#"{
                "name": "@scope/native",
                "napi": { "targets": ["x86_64-unknown-linux-gnu"] }
            }"#);
        let no_targets = pkg(r#"{ "name": "@scope/native", "napi": { "binaryName": "native" } }"#);

        assert!(NapiRsPlugin.is_enabled_with_package_json(&source_repo, root));
        assert!(!NapiRsPlugin.is_enabled_with_package_json(&no_targets, root));
    }

    #[test]
    fn only_files_with_the_napi_header_are_loaders() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        std::fs::write(
            root.join("index.js"),
            "// prettier-ignore\n/* auto-generated by NAPI-RS */\nrequire('x')\n",
        )
        .expect("write loader");
        std::fs::write(
            root.join("browser.cjs"),
            "/* auto-generated by NAPI-RS */\n",
        )
        .expect("write browser loader");
        std::fs::write(
            root.join("manual.js"),
            "require('@scope/native-linux-x64-gnu')\n",
        )
        .expect("write hand-written file");
        std::fs::write(root.join("index.d.ts"), "/* auto-generated by NAPI-RS */\n")
            .expect("write declarations");

        assert_eq!(generated_loaders(root), ["browser.cjs", "index.js"]);
    }

    #[test]
    fn loaders_in_direct_subdirectories_are_found() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path();
        for sub in [
            "binding",
            "binding/deep",
            "node_modules/dep",
            "target",
            "dist",
            ".cache",
            "src",
        ] {
            std::fs::create_dir_all(root.join(sub)).expect("create dir");
            std::fs::write(
                root.join(sub).join("index.cjs"),
                "/* auto-generated by NAPI-RS */\n",
            )
            .expect("write loader");
        }
        std::fs::write(
            root.join("binding/index.js"),
            "export * from './index.cjs'\n",
        )
        .expect("write wrapper");
        for index in 0..MAX_SUBDIR_LOADER_CANDIDATES {
            std::fs::write(root.join(format!("src/file{index}.js")), "export {}\n")
                .expect("write source file");
        }

        assert_eq!(generated_loaders(root), ["binding/index.cjs"]);
        assert_eq!(loader_dir("binding/index.cjs"), "binding/");
        assert_eq!(loader_dir("index.js"), "");
    }

    #[test]
    fn only_the_generated_browser_reexport_is_a_browser_entry() {
        let dir = tempfile::tempdir().expect("temp dir");
        let entry = dir.path().join(BROWSER_ENTRY);

        std::fs::write(&entry, "export * from '@scope/native-wasm32-wasi'\n")
            .expect("write browser entry");
        assert!(is_generated_browser_entry(&entry, "@scope/native"));
        assert!(!is_generated_browser_entry(&entry, "@scope/other"));

        std::fs::write(&entry, "export * from \"@scope/native-wasm32-wasi\";\n")
            .expect("write browser entry");
        assert!(is_generated_browser_entry(&entry, "@scope/native"));

        std::fs::write(
            &entry,
            "export * from '@scope/native-wasm32-wasi'\nexport const x = 1\n",
        )
        .expect("write hand-written entry");
        assert!(!is_generated_browser_entry(&entry, "@scope/native"));
    }

    #[test]
    fn malformed_napi_config_is_ignored_by_package_parser() {
        let referenced = resolve(
            r#"{
                "name": "native",
                "optionalDependencies": {
                    "native-linux-x64-gnu": "1.0.0"
                },
                "napi": true
            }"#,
        );

        assert!(referenced.is_empty());
    }
}