Skip to main content

fallow_config/workspace/
package_json.rs

1use std::collections::BTreeMap;
2
3use serde::{
4    Deserialize, Deserializer, Serialize,
5    de::{Error, IgnoredAny, MapAccess, Visitor},
6};
7
8use super::pnpm_catalog::PnpmCatalogData;
9
10/// Type alias for standard `HashMap` used in serde-deserialized structs.
11/// `rustc-hash` v2 does not have a `serde` feature, so fields deserialized
12/// from JSON must use `std::collections::HashMap`.
13#[expect(
14    clippy::disallowed_types,
15    reason = "rustc-hash v2 lacks serde feature — JSON deserialization needs std HashMap"
16)]
17type StdHashMap<K, V> = std::collections::HashMap<K, V>;
18
19fn deserialize_optional_bool_lenient<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
20where
21    D: Deserializer<'de>,
22{
23    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
24    Ok(match value {
25        Some(serde_json::Value::Bool(value)) => Some(value),
26        _ => None,
27    })
28}
29
30fn deserialize_string_array_lenient<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
31where
32    D: Deserializer<'de>,
33{
34    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
35    Ok(match value {
36        Some(serde_json::Value::Array(values)) => values
37            .into_iter()
38            .filter_map(|value| value.as_str().map(str::to_owned))
39            .collect(),
40        _ => Vec::new(),
41    })
42}
43
44fn deserialize_optional_string_lenient<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
45where
46    D: Deserializer<'de>,
47{
48    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
49    Ok(match value {
50        Some(serde_json::Value::String(value)) if !value.trim().is_empty() => Some(value),
51        _ => None,
52    })
53}
54
55fn deserialize_optional_napi_config<'de, D>(deserializer: D) -> Result<Option<NapiConfig>, D::Error>
56where
57    D: Deserializer<'de>,
58{
59    let value = Option::<serde_json::Value>::deserialize(deserializer)?;
60    match value {
61        Some(serde_json::Value::Object(map)) => {
62            serde_json::from_value(serde_json::Value::Object(map))
63                .map(Some)
64                .map_err(D::Error::custom)
65        }
66        _ => Ok(None),
67    }
68}
69
70/// The text of a manifest such as `package.json` or `deno.json`. The file
71/// must be a regular file with a size limit, at a location that
72/// [`manifest_location_allowed`] accepts.
73fn read_manifest(path: &std::path::Path) -> Result<String, String> {
74    read_manifest_in(None, path)
75}
76
77/// [`read_manifest`] with the project scope base `scope` (see
78/// [`crate::project_scope_base`]). `None` takes the scope base from the
79/// location of the manifest.
80pub(super) fn read_manifest_in(
81    scope: Option<&std::path::Path>,
82    path: &std::path::Path,
83) -> Result<String, String> {
84    if path.symlink_metadata().is_ok() && !manifest_location_allowed(scope, path) {
85        return Err(format!(
86            "refusing to read {}: it resolves to a location outside its package",
87            path.display()
88        ));
89    }
90    fallow_types::read_guard::read_to_string_bounded(
91        path,
92        fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
93    )
94    .map_err(|e| e.to_string())
95}
96
97/// Whether the manifest at `path` resolves to an allowed place. A relative
98/// `path` is taken relative to the current directory.
99///
100/// - Below a `node_modules` directory, the resolved directory that holds the
101///   first such segment and the resolved file must both be inside the
102///   project scope base `scope`. That covers the `.pnpm` and `.bun` stores
103///   of the project, a pnpm link from a workspace package into the store at
104///   the root, and a workspace link such as
105///   `node_modules/@x/pkg -> ../packages/pkg`. A store outside the project,
106///   such as a global store, and a `node_modules` directory above the scope
107///   base are refused.
108/// - Elsewhere, the resolved file must be in the resolved directory of
109///   `path`. When that directory is a link, it must resolve inside `scope`
110///   or inside the directory that holds the link.
111///
112/// When `scope` is `None`, the scope base is the one of the directory that
113/// holds the first `node_modules` segment, or of the directory that holds
114/// the package directory.
115fn manifest_location_allowed(scope: Option<&std::path::Path>, path: &std::path::Path) -> bool {
116    use std::path::Component;
117    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
118    let lexical = fallow_types::path_guard::lexically_normalized(&absolute);
119    let scope_base = |dir: &std::path::Path| {
120        scope.map_or_else(
121            || crate::project_scope_base(dir),
122            std::path::Path::to_path_buf,
123        )
124    };
125    let mut prefix = std::path::PathBuf::new();
126    for component in lexical.components() {
127        if matches!(component, Component::Normal(name) if name == "node_modules") {
128            let base = scope_base(&prefix);
129            return dunce::canonicalize(path).is_ok_and(|target| target.starts_with(&base))
130                && dunce::canonicalize(&prefix).is_ok_and(|holder| holder.starts_with(&base));
131        }
132        prefix.push(component);
133    }
134    let Some(dir) = lexical.parent() else {
135        return false;
136    };
137    let is_plain = |path: &std::path::Path, want_dir: bool| {
138        path.symlink_metadata().is_ok_and(|meta| {
139            !meta.file_type().is_symlink()
140                && if want_dir {
141                    meta.is_dir()
142                } else {
143                    meta.is_file()
144                }
145        })
146    };
147    // A plain file in a plain directory resolves to its own name in the
148    // resolved directory, so the checks below would pass. Two `lstat` calls
149    // answer that case, which is the case of each member manifest. A `..`
150    // component can pass through a link, so then the lexical path can name
151    // another file, and the full check runs.
152    let has_parent_dir = path
153        .components()
154        .any(|component| matches!(component, Component::ParentDir));
155    if !has_parent_dir && is_plain(&lexical, false) && is_plain(dir, true) {
156        return true;
157    }
158    let Ok(target) = dunce::canonicalize(path) else {
159        return false;
160    };
161    let Ok(canonical_dir) = dunce::canonicalize(dir) else {
162        return false;
163    };
164    if target.parent() != Some(canonical_dir.as_path()) {
165        return false;
166    }
167    let dir_is_link = dir
168        .symlink_metadata()
169        .is_ok_and(|meta| meta.file_type().is_symlink());
170    if !dir_is_link {
171        return true;
172    }
173    dir.parent().is_some_and(|holder| {
174        target.starts_with(scope_base(holder))
175            || dunce::canonicalize(holder).is_ok_and(|holder| target.starts_with(holder))
176    })
177}
178
179/// The `package.json` keys that hold the inline config of a built-in plugin
180/// ([`PackageJson::inline_tool_config`]).
181pub const INLINE_TOOL_CONFIG_KEYS: &[&str] = &[
182    "babel",
183    "commit-and-tag-version",
184    "eslintConfig",
185    "graphql",
186    "jest",
187    "mocha",
188    "nodemonConfig",
189    "prettier",
190    "release-it",
191    "stylelint",
192    "textlint",
193    "tsd",
194    "tsdown",
195    "tsup",
196];
197
198/// Keeps the value of each [`INLINE_TOOL_CONFIG_KEYS`] key raw. A repeated key
199/// keeps its last value, as `JSON.parse` does, and any value is accepted, so
200/// these keys never fail manifest parsing.
201fn deserialize_inline_tool_configs<'de, D>(
202    deserializer: D,
203) -> Result<BTreeMap<&'static str, serde_json::Value>, D::Error>
204where
205    D: Deserializer<'de>,
206{
207    struct InlineToolConfigs;
208
209    impl<'de> Visitor<'de> for InlineToolConfigs {
210        type Value = BTreeMap<&'static str, serde_json::Value>;
211
212        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213            formatter.write_str("a package.json object")
214        }
215
216        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
217        where
218            A: MapAccess<'de>,
219        {
220            let mut configs = BTreeMap::new();
221            while let Some(key) = map.next_key::<String>()? {
222                match INLINE_TOOL_CONFIG_KEYS.iter().find(|known| **known == key) {
223                    Some(known) => {
224                        configs.insert(*known, map.next_value()?);
225                    }
226                    None => {
227                        map.next_value::<IgnoredAny>()?;
228                    }
229                }
230            }
231            Ok(configs)
232        }
233    }
234
235    deserializer.deserialize_map(InlineToolConfigs)
236}
237
238#[derive(Debug, Clone, Default, Deserialize, Serialize)]
239pub struct PeerDependencyMeta {
240    #[serde(default)]
241    pub optional: bool,
242}
243
244/// The NAPI-RS `napi` block of a `package.json`, used to recognize the
245/// per-platform artifact packages a native addon generates so they are not
246/// reported as unused dependencies. All fields deserialize leniently: a
247/// wrong-typed value becomes `None`/empty instead of failing manifest parsing.
248#[derive(Debug, Clone, Default, Deserialize, Serialize)]
249pub struct NapiConfig {
250    /// The `binaryName` field: basename of the generated `.node` binary.
251    #[serde(
252        default,
253        rename = "binaryName",
254        deserialize_with = "deserialize_optional_string_lenient"
255    )]
256    pub binary_name: Option<String>,
257    /// The `packageName` field: base npm package name from which per-platform
258    /// artifact package names (`<name>-<triple>`) are derived.
259    #[serde(
260        default,
261        rename = "packageName",
262        deserialize_with = "deserialize_optional_string_lenient"
263    )]
264    pub package_name: Option<String>,
265    /// The `targets` field: platform triples the addon is built for.
266    #[serde(default, deserialize_with = "deserialize_string_array_lenient")]
267    pub targets: Vec<String>,
268}
269
270/// Parsed package.json with fields relevant to fallow.
271#[derive(Debug, Clone, Default, Deserialize, Serialize)]
272pub struct PackageJson {
273    /// The `name` field: the package's npm name, used to identify workspace
274    /// packages and match `public_packages` config entries.
275    #[serde(default)]
276    pub name: Option<String>,
277    /// The `private` field. Non-boolean values become `None` rather than
278    /// failing manifest parsing.
279    #[serde(default, deserialize_with = "deserialize_optional_bool_lenient")]
280    pub private: Option<bool>,
281    /// The `main` field: CommonJS entry-point path, seeded as an entry point.
282    #[serde(default)]
283    pub main: Option<String>,
284    /// The `module` field: ESM entry-point path, seeded as an entry point.
285    #[serde(default)]
286    pub module: Option<String>,
287    /// The `types` field: type-declaration entry-point path.
288    #[serde(default)]
289    pub types: Option<String>,
290    /// The `typings` field: legacy spelling of `types`.
291    #[serde(default)]
292    pub typings: Option<String>,
293    /// The `source` field: unbundled source entry point used by bundler-based
294    /// packages (Parcel convention).
295    #[serde(default)]
296    pub source: Option<String>,
297    /// The `files` field: publish allowlist patterns. Non-array values become
298    /// empty rather than failing manifest parsing.
299    #[serde(default, deserialize_with = "deserialize_string_array_lenient")]
300    pub files: Vec<String>,
301    /// The `browser` field, kept raw because it is either a string entry point
302    /// or a path-remap object.
303    #[serde(default)]
304    pub browser: Option<serde_json::Value>,
305    /// The `bin` field, kept raw because it is either a string path or a
306    /// name-to-path object; every referenced file is an entry point.
307    #[serde(default)]
308    pub bin: Option<serde_json::Value>,
309    /// The `typescript` field, kept raw. Its `contentMapper.exec` command
310    /// names a script that TypeScript runs.
311    #[serde(default)]
312    pub typescript: Option<serde_json::Value>,
313    /// The `exports` field, kept raw because of its many shapes (string,
314    /// conditions object, subpath map); referenced files are entry points and
315    /// the map drives subpath resolution.
316    #[serde(default)]
317    pub exports: Option<serde_json::Value>,
318    /// The `imports` field (`#`-prefixed internal subpath map), kept raw and
319    /// consumed by the module resolver.
320    #[serde(default)]
321    pub imports: Option<serde_json::Value>,
322    /// The `dependencies` map (package name to version range), the base set
323    /// for unused/unlisted-dependency accounting.
324    #[serde(default)]
325    pub dependencies: Option<StdHashMap<String, String>>,
326    /// The `devDependencies` map, checked by `unused-dev-dependencies` and
327    /// `dev-dependency-in-production`.
328    #[serde(default, rename = "devDependencies")]
329    pub dev_dependencies: Option<StdHashMap<String, String>>,
330    /// The `peerDependencies` map. Peers are provided by the consumer, so
331    /// they are exempt from unused-dependency reporting.
332    #[serde(default, rename = "peerDependencies")]
333    pub peer_dependencies: Option<StdHashMap<String, String>>,
334    /// The `peerDependenciesMeta` map, marking which peers are optional.
335    #[serde(default, rename = "peerDependenciesMeta")]
336    pub peer_dependencies_meta: Option<StdHashMap<String, PeerDependencyMeta>>,
337    /// The `optionalDependencies` map, checked by
338    /// `unused-optional-dependencies`.
339    #[serde(default, rename = "optionalDependencies")]
340    pub optional_dependencies: Option<StdHashMap<String, String>>,
341    /// The `scripts` map, scanned so packages invoked from scripts count as
342    /// used tooling dependencies.
343    #[serde(default)]
344    pub scripts: Option<StdHashMap<String, String>>,
345    /// The NAPI-RS `napi` block; see [`NapiConfig`]. Non-object values become
346    /// `None` rather than failing manifest parsing.
347    #[serde(default, deserialize_with = "deserialize_optional_napi_config")]
348    pub napi: Option<NapiConfig>,
349    /// The `workspaces` field, kept raw because it is either a pattern array
350    /// or an object with a `packages` array; drives workspace discovery.
351    #[serde(default)]
352    pub workspaces: Option<serde_json::Value>,
353    /// The `packageManager` field (e.g. `"pnpm@9.1.0"`), used to determine
354    /// the canonical package manager for the project.
355    #[serde(
356        default,
357        rename = "packageManager",
358        deserialize_with = "deserialize_optional_string_lenient"
359    )]
360    pub package_manager: Option<String>,
361    /// The Egg.js `egg` block (for example `framework` and `tscompiler`),
362    /// kept raw so that an unexpected shape does not fail manifest parsing.
363    #[serde(default)]
364    pub egg: Option<serde_json::Value>,
365    /// The Egg.js `eggPlugin` block of a plugin package, kept raw.
366    #[serde(default, rename = "eggPlugin")]
367    pub egg_plugin: Option<serde_json::Value>,
368    /// The tegg `eggModule` block of a module package, kept raw.
369    #[serde(default, rename = "eggModule")]
370    pub egg_module: Option<serde_json::Value>,
371    /// The `n8n` block of an n8n node package (`nodes` and `credentials`),
372    /// kept raw so that an unexpected shape does not fail manifest parsing.
373    #[serde(default)]
374    pub n8n: Option<serde_json::Value>,
375    /// The value of each [`INLINE_TOOL_CONFIG_KEYS`] key that the manifest
376    /// has, kept raw. See [`PackageJson::inline_tool_config`].
377    #[serde(default, flatten, deserialize_with = "deserialize_inline_tool_configs")]
378    pub inline_tool_configs: BTreeMap<&'static str, serde_json::Value>,
379}
380
381/// The package.json field that declares an entry point.
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub enum PackageEntryField {
384    /// The `main` field.
385    Main,
386    /// The `module` field.
387    Module,
388    /// The `types` field.
389    Types,
390    /// The `typings` field.
391    Typings,
392    /// The `source` field.
393    Source,
394    /// The `browser` field, as a string or as a map of replacement paths.
395    Browser,
396    /// The `bin` field, as a string or as a map of command names.
397    Bin,
398    /// The `exports` field, at any depth of conditions and subpaths.
399    Exports,
400}
401
402impl From<PackageEntryField> for fallow_types::discover::EntryPointSource {
403    fn from(field: PackageEntryField) -> Self {
404        match field {
405            PackageEntryField::Main => Self::PackageJsonMain,
406            PackageEntryField::Module => Self::PackageJsonModule,
407            PackageEntryField::Types => Self::PackageJsonTypes,
408            PackageEntryField::Typings => Self::PackageJsonTypings,
409            PackageEntryField::Source => Self::PackageJsonSource,
410            PackageEntryField::Browser => Self::PackageJsonBrowser,
411            PackageEntryField::Bin => Self::PackageJsonBin,
412            PackageEntryField::Exports => Self::PackageJsonExports,
413        }
414    }
415}
416
417/// Collects the paths of a field that holds one string or a map of strings.
418/// `keep_map_value` filters the map values: a `browser` map also holds bare
419/// package names, which are not files of the package.
420fn push_string_values(
421    entries: &mut Vec<(PackageEntryField, String)>,
422    field: PackageEntryField,
423    value: &serde_json::Value,
424    keep_map_value: impl Fn(&str) -> bool,
425) {
426    match value {
427        serde_json::Value::String(path) => entries.push((field, path.clone())),
428        serde_json::Value::Object(map) => {
429            let paths = map
430                .values()
431                .filter_map(serde_json::Value::as_str)
432                .filter(|path| keep_map_value(path));
433            entries.extend(paths.map(|path| (field, path.to_owned())));
434        }
435        _ => {}
436    }
437}
438
439impl PackageJson {
440    /// The raw value of the tool config key `key`, such as `prettier` or
441    /// `nodemonConfig`. Returns `None` when the manifest has no such key, or
442    /// when `key` is not in [`INLINE_TOOL_CONFIG_KEYS`].
443    #[must_use]
444    pub fn inline_tool_config(&self, key: &str) -> Option<&serde_json::Value> {
445        self.inline_tool_configs.get(key)
446    }
447
448    /// Load from a package.json file.
449    ///
450    /// # Errors
451    ///
452    /// Returns an error string when the file cannot be read or parsed as JSON.
453    ///
454    /// The file must be a regular file of at most
455    /// [`fallow_types::read_guard::DEFAULT_MAX_READ_BYTES`]. A `package.json`
456    /// that is a link must resolve to a file in its own directory or in a
457    /// `node_modules` directory. The parse error names the position, not the
458    /// bad value.
459    pub fn load(path: &std::path::Path) -> Result<Self, String> {
460        let content = read_manifest(path)?;
461        Self::parse_named(path, &content)
462    }
463
464    /// [`Self::load`] for a manifest that dependency resolution finds, such
465    /// as `node_modules/<name>/package.json`, with the project scope base
466    /// `scope` from [`crate::project_scope_base`]. A manifest below
467    /// `node_modules` may resolve anywhere inside `scope`.
468    ///
469    /// # Errors
470    ///
471    /// Returns the same errors as [`Self::load`].
472    pub fn load_in_scope(scope: &std::path::Path, path: &std::path::Path) -> Result<Self, String> {
473        let content = read_manifest_in(Some(scope), path)?;
474        Self::parse_named(path, &content)
475    }
476
477    /// [`Self::load`] for a manifest of the project, for example the root
478    /// `package.json` or the one of a workspace member: the file must
479    /// resolve inside `root`.
480    ///
481    /// # Errors
482    ///
483    /// Returns an error string when the file resolves outside `root`, cannot
484    /// be read, or does not parse.
485    pub fn load_inside(root: &std::path::Path, path: &std::path::Path) -> Result<Self, String> {
486        let content = fallow_types::read_guard::read_to_string_inside(
487            root,
488            path,
489            fallow_types::read_guard::DEFAULT_MAX_READ_BYTES,
490        )
491        .map_err(|e| e.to_string())?;
492        Self::parse_named(path, &content)
493    }
494
495    fn parse_named(path: &std::path::Path, content: &str) -> Result<Self, String> {
496        Self::parse(content).map_err(|e| {
497            format!(
498                "Failed to parse {}: {}",
499                path.display(),
500                crate::parse_error::describe_json(&e)
501            )
502        })
503    }
504
505    /// Read the text of a package.json file without a leading UTF-8 byte
506    /// order mark, for a parser that reads the raw JSON. The mark sits on
507    /// line 1, so line numbers do not change. The read has the same file
508    /// checks as [`Self::load`].
509    ///
510    /// # Errors
511    ///
512    /// Returns the I/O error when the file cannot be read as UTF-8 text, or
513    /// a `PermissionDenied` error when a check refuses the file.
514    pub fn read_source(path: &std::path::Path) -> std::io::Result<String> {
515        Self::read_source_in(None, path)
516    }
517
518    /// [`Self::read_source`] with the project scope base `scope`, as
519    /// [`Self::load_in_scope`] takes it.
520    ///
521    /// # Errors
522    ///
523    /// Returns the same errors as [`Self::read_source`].
524    pub fn read_source_in_scope(
525        scope: &std::path::Path,
526        path: &std::path::Path,
527    ) -> std::io::Result<String> {
528        Self::read_source_in(Some(scope), path)
529    }
530
531    fn read_source_in(
532        scope: Option<&std::path::Path>,
533        path: &std::path::Path,
534    ) -> std::io::Result<String> {
535        let mut source = read_manifest_in(scope, path).map_err(|message| {
536            if path.symlink_metadata().is_err() {
537                std::io::Error::new(std::io::ErrorKind::NotFound, message)
538            } else {
539                std::io::Error::new(std::io::ErrorKind::PermissionDenied, message)
540            }
541        })?;
542        if source.starts_with('\u{FEFF}') {
543            source.drain(..'\u{FEFF}'.len_utf8());
544        }
545        Ok(source)
546    }
547
548    /// Parse package.json source text. A leading UTF-8 byte order mark is
549    /// ignored, as npm and Node.js do.
550    ///
551    /// # Errors
552    ///
553    /// Returns the JSON error when the text is not a valid manifest.
554    pub fn parse(source: &str) -> Result<Self, serde_json::Error> {
555        serde_json::from_str(source.trim_start_matches('\u{FEFF}'))
556    }
557
558    /// Get all dependency names (production + dev + peer + optional).
559    #[must_use]
560    pub fn all_dependency_names(&self) -> Vec<String> {
561        let mut deps = Vec::new();
562        if let Some(d) = &self.dependencies {
563            deps.extend(d.keys().cloned());
564        }
565        if let Some(d) = &self.dev_dependencies {
566            deps.extend(d.keys().cloned());
567        }
568        if let Some(d) = &self.peer_dependencies {
569            deps.extend(d.keys().cloned());
570        }
571        if let Some(d) = &self.optional_dependencies {
572            deps.extend(d.keys().cloned());
573        }
574        deps
575    }
576
577    /// Get production dependency names only.
578    #[must_use]
579    pub fn production_dependency_names(&self) -> Vec<String> {
580        self.dependencies
581            .as_ref()
582            .map(|d| d.keys().cloned().collect())
583            .unwrap_or_default()
584    }
585
586    /// Get dev dependency names only.
587    #[must_use]
588    pub fn dev_dependency_names(&self) -> Vec<String> {
589        self.dev_dependencies
590            .as_ref()
591            .map(|d| d.keys().cloned().collect())
592            .unwrap_or_default()
593    }
594
595    /// Get optional dependency names only.
596    #[must_use]
597    pub fn optional_dependency_names(&self) -> Vec<String> {
598        self.optional_dependencies
599            .as_ref()
600            .map(|d| d.keys().cloned().collect())
601            .unwrap_or_default()
602    }
603
604    /// Get every peer dependency name, required or optional.
605    #[must_use]
606    pub fn peer_dependency_names(&self) -> Vec<String> {
607        self.peer_dependencies
608            .as_ref()
609            .map(|deps| deps.keys().cloned().collect())
610            .unwrap_or_default()
611    }
612
613    /// Whether `peerDependenciesMeta` marks the peer `dep` as optional.
614    #[must_use]
615    pub fn peer_dependency_is_optional(&self, dep: &str) -> bool {
616        self.peer_dependencies_meta
617            .as_ref()
618            .and_then(|meta| meta.get(dep))
619            .is_some_and(|meta| meta.optional)
620    }
621
622    /// Extract entry points from package.json fields.
623    #[must_use]
624    pub fn entry_points(&self) -> Vec<String> {
625        self.entry_points_by_field()
626            .into_iter()
627            .map(|(_, entry)| entry)
628            .collect()
629    }
630
631    /// Extract entry points from package.json fields, each with the field
632    /// that declares it, in field order: `main`, `module`, `types`,
633    /// `typings`, `source`, `browser`, `bin`, `exports`.
634    #[must_use]
635    pub fn entry_points_by_field(&self) -> Vec<(PackageEntryField, String)> {
636        let mut entries = Vec::new();
637
638        for (field, value) in [
639            (PackageEntryField::Main, &self.main),
640            (PackageEntryField::Module, &self.module),
641            (PackageEntryField::Types, &self.types),
642            (PackageEntryField::Typings, &self.typings),
643            (PackageEntryField::Source, &self.source),
644        ] {
645            if let Some(entry) = value {
646                entries.push((field, entry.clone()));
647            }
648        }
649
650        if let Some(browser) = &self.browser {
651            // Like `exports`, a `browser` path with a `..` segment is never
652            // followed out of the package.
653            push_string_values(&mut entries, PackageEntryField::Browser, browser, |path| {
654                path.starts_with("./")
655            });
656            entries.retain(|(field, path)| {
657                *field != PackageEntryField::Browser || !has_dot_dot_segment(path)
658            });
659        }
660
661        if let Some(bin) = &self.bin {
662            push_string_values(&mut entries, PackageEntryField::Bin, bin, |_| true);
663        }
664
665        if let Some(exports) = &self.exports {
666            let mut exported = Vec::new();
667            extract_exports_entries(exports, &mut exported);
668            entries.extend(
669                exported
670                    .into_iter()
671                    .map(|entry| (PackageEntryField::Exports, entry)),
672            );
673        }
674
675        entries
676    }
677
678    /// Extract unique subdirectory names referenced by the `exports` field keys.
679    ///
680    /// For exports like `"./compat": { ... }`, `"./hooks/client": { ... }`,
681    /// this returns `["compat", "hooks"]`. Used to discover sub-packages in
682    /// projects that define their internal package structure via the exports map
683    /// (e.g., preact with `compat/`, `hooks/`, `debug/` sub-packages).
684    #[must_use]
685    pub fn exports_subdirectories(&self) -> Vec<String> {
686        self.exports
687            .as_ref()
688            .map_or_else(Vec::new, extract_exports_subdirectories)
689    }
690
691    /// Extract workspace patterns from package.json.
692    #[must_use]
693    pub fn workspace_patterns(&self) -> Vec<String> {
694        match &self.workspaces {
695            Some(serde_json::Value::Array(arr)) => arr
696                .iter()
697                .filter_map(|v| v.as_str().map(String::from))
698                .collect(),
699            Some(serde_json::Value::Object(obj)) => obj
700                .get("packages")
701                .and_then(|v| v.as_array())
702                .map(|arr| {
703                    arr.iter()
704                        .filter_map(|v| v.as_str().map(String::from))
705                        .collect()
706                })
707                .unwrap_or_default(),
708            _ => Vec::new(),
709        }
710    }
711
712    /// Dependencies with a `link:` or `file:` spec in `dependencies`,
713    /// `devDependencies` or `optionalDependencies`, as `(name, target)` pairs
714    /// sorted by name.
715    ///
716    /// The target is the path as written, relative to this manifest's
717    /// directory. The caller decides which targets are real package
718    /// directories.
719    #[must_use]
720    pub fn local_link_dependencies(&self) -> Vec<(String, String)> {
721        let mut links: Vec<(String, String)> = [
722            &self.dependencies,
723            &self.dev_dependencies,
724            &self.optional_dependencies,
725        ]
726        .into_iter()
727        .flatten()
728        .flatten()
729        .filter_map(|(name, spec)| {
730            let target = spec
731                .strip_prefix("link:")
732                .or_else(|| spec.strip_prefix("file:"))?
733                .trim();
734            (!target.is_empty()).then(|| (name.clone(), target.to_string()))
735        })
736        .collect();
737        links.sort_unstable();
738        links.dedup();
739        links
740    }
741
742    /// The workspace package that the dependency `name` is an alias of.
743    ///
744    /// pnpm installs `"vite": "workspace:@scope/core@*"` as the workspace
745    /// package `@scope/core` under the name `vite`. A `workspace:` spec with
746    /// only a range (`workspace:*`, `workspace:^1.0.0`) or a path
747    /// (`workspace:../core`) is not an alias.
748    #[must_use]
749    pub fn workspace_alias_target(&self, name: &str) -> Option<&str> {
750        [
751            &self.dependencies,
752            &self.dev_dependencies,
753            &self.optional_dependencies,
754            &self.peer_dependencies,
755        ]
756        .into_iter()
757        .flatten()
758        .find_map(|deps| deps.get(name))
759        .and_then(|spec| workspace_alias_name(spec))
760    }
761
762    /// Every dependency that the manifest installs under an npm alias, as
763    /// `(alias, aliased package)` pairs.
764    ///
765    /// `"@typescript/native": "npm:typescript@~7.0.2"` installs the package
766    /// `typescript` in `node_modules/@typescript/native`, so the alias
767    /// provides the binaries of `typescript`.
768    #[must_use]
769    pub fn npm_aliases(&self) -> Vec<(String, String)> {
770        self.npm_aliases_with_catalogs(None)
771    }
772
773    /// Every npm alias of the manifest, as [`Self::npm_aliases`] gives, plus
774    /// every alias that a `catalog:` reference gets from `catalogs`.
775    ///
776    /// `"@typescript/native": "catalog:"` with the catalog entry
777    /// `"@typescript/native": npm:typescript@~7.0.2` installs `typescript`
778    /// under the alias, the same as the inline spec.
779    #[must_use]
780    pub fn npm_aliases_with_catalogs(
781        &self,
782        catalogs: Option<&PnpmCatalogData>,
783    ) -> Vec<(String, String)> {
784        let mut aliases: Vec<(String, String)> = [
785            &self.dependencies,
786            &self.dev_dependencies,
787            &self.optional_dependencies,
788            &self.peer_dependencies,
789        ]
790        .into_iter()
791        .flatten()
792        .flat_map(|deps| deps.iter())
793        .filter_map(|(name, spec)| {
794            let spec = catalogs
795                .and_then(|data| data.resolve_reference(name, spec))
796                .unwrap_or(spec);
797            let target = npm_alias_name(spec)?;
798            (target != name).then(|| (name.clone(), target.to_string()))
799        })
800        .collect();
801        aliases.sort_unstable();
802        aliases.dedup();
803        aliases
804    }
805}
806
807/// The package name in a `workspace:<name>@<range>` dependency spec.
808fn workspace_alias_name(spec: &str) -> Option<&str> {
809    let rest = spec.trim().strip_prefix("workspace:")?;
810    let separator = if let Some(scoped) = rest.strip_prefix('@') {
811        scoped.find('@')? + 1
812    } else {
813        rest.find('@')?
814    };
815    valid_package_name(&rest[..separator])
816}
817
818/// The package name in an `npm:<name>@<range>` or `npm:<name>` dependency
819/// spec.
820fn npm_alias_name(spec: &str) -> Option<&str> {
821    let rest = spec.trim().strip_prefix("npm:")?;
822    let separator = if let Some(scoped) = rest.strip_prefix('@') {
823        scoped.find('@').map_or(rest.len(), |at| at + 1)
824    } else {
825        rest.find('@').unwrap_or(rest.len())
826    };
827    valid_package_name(&rest[..separator])
828}
829
830/// `name` when it has the shape of a package name: `name` or `@scope/name`.
831fn valid_package_name(name: &str) -> Option<&str> {
832    let is_package_name = !name.is_empty()
833        && !name.starts_with('.')
834        && match name.strip_prefix('@') {
835            Some(scoped) => scoped
836                .split_once('/')
837                .is_some_and(|(scope, base)| !scope.is_empty() && !base.is_empty()),
838            None => !name.contains('/'),
839        };
840    is_package_name.then_some(name)
841}
842
843/// True when `name` is exactly one normal path component on every platform.
844fn is_plain_dir_name(name: &str) -> bool {
845    !name.is_empty()
846        && !name.contains(['\\', ':'])
847        && matches!(
848            std::path::Path::new(name)
849                .components()
850                .collect::<Vec<_>>()
851                .as_slice(),
852            [std::path::Component::Normal(_)]
853        )
854}
855
856/// True when a `/` or `\\` separated path has a `..` segment.
857fn has_dot_dot_segment(path: &str) -> bool {
858    path.split(['/', '\\']).any(|segment| segment == "..")
859}
860
861fn extract_exports_subdirectories(exports: &serde_json::Value) -> Vec<String> {
862    let Some(map) = exports.as_object() else {
863        return Vec::new();
864    };
865
866    let skip_dirs = ["dist", "build", "out", "esm", "cjs", "lib", "node_modules"];
867    let mut dirs = rustc_hash::FxHashSet::default();
868
869    for key in map.keys().filter(|key| !has_dot_dot_segment(key)) {
870        // A subpath key starts with `./`. The first segment must be one plain
871        // directory name: no `\`, no `:`, and not empty.
872        let Some(stripped) = key.strip_prefix("./") else {
873            continue;
874        };
875        if let Some(first_segment) = stripped.split('/').next()
876            && is_plain_dir_name(first_segment)
877            && first_segment != "package.json"
878            && !skip_dirs.contains(&first_segment)
879        {
880            dirs.insert(first_segment.to_owned());
881        }
882    }
883
884    dirs.into_iter().collect()
885}
886
887/// Recursively extract file paths from package.json exports field.
888///
889/// Node.js accepts only `./` targets without a `..` segment, so a target
890/// that is `../x` or has a `..` segment is skipped, and so is the value of a
891/// key with a `..` segment. Such a path is never followed out of the
892/// package.
893fn extract_exports_entries(value: &serde_json::Value, entries: &mut Vec<String>) {
894    match value {
895        serde_json::Value::String(s) if s.starts_with("./") && !has_dot_dot_segment(s) => {
896            entries.push(s.clone());
897        }
898        serde_json::Value::Object(map) => {
899            for (key, v) in map {
900                if !has_dot_dot_segment(key) {
901                    extract_exports_entries(v, entries);
902                }
903            }
904        }
905        serde_json::Value::Array(arr) => {
906            for v in arr {
907                extract_exports_entries(v, entries);
908            }
909        }
910        _ => {}
911    }
912}
913
914#[cfg(test)]
915mod tests {
916    use super::*;
917
918    #[cfg(unix)]
919    #[test]
920    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
921    fn a_dependency_link_to_another_node_modules_dir_is_refused() {
922        let dir = tempfile::tempdir().unwrap();
923        crate::project_read::set_test_ceiling(&dunce::canonicalize(dir.path()).unwrap());
924        let other = dir.path().join("other/node_modules/pkg");
925        std::fs::create_dir_all(&other).unwrap();
926        std::fs::write(other.join("package.json"), r#"{"name": "pkg"}"#).unwrap();
927        let project = dir.path().join("project");
928        std::fs::create_dir_all(project.join("node_modules")).unwrap();
929        std::os::unix::fs::symlink(&other, project.join("node_modules/pkg")).unwrap();
930        assert!(PackageJson::load(&project.join("node_modules/pkg/package.json")).is_err());
931    }
932
933    #[cfg(unix)]
934    #[test]
935    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
936    fn a_package_dir_link_out_of_its_parent_is_refused() {
937        let dir = tempfile::tempdir().unwrap();
938        crate::project_read::set_test_ceiling(&dunce::canonicalize(dir.path()).unwrap());
939        let outside = dir.path().join("outside");
940        std::fs::create_dir(&outside).unwrap();
941        std::fs::write(outside.join("package.json"), r#"{"name": "x"}"#).unwrap();
942        let project = dir.path().join("project");
943        std::fs::create_dir_all(project.join("packages")).unwrap();
944        std::os::unix::fs::symlink(&outside, project.join("packages/x")).unwrap();
945        assert!(PackageJson::load(&project.join("packages/x/package.json")).is_err());
946    }
947
948    /// A `..` after a directory link names the file next to the link target,
949    /// not the plain file that the same text names without the link.
950    #[cfg(unix)]
951    #[test]
952    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
953    fn a_dot_dot_through_a_link_out_of_the_scope_is_refused() {
954        let dir = tempfile::tempdir().unwrap();
955        let outside = dir.path().join("outside");
956        std::fs::create_dir_all(outside.join("inner")).unwrap();
957        std::fs::create_dir_all(outside.join("pkg")).unwrap();
958        std::fs::write(outside.join("pkg/package.json"), r#"{"name": "out"}"#).unwrap();
959        let project = dir.path().join("project");
960        std::fs::create_dir_all(project.join("packages/pkg")).unwrap();
961        std::fs::write(
962            project.join("packages/pkg/package.json"),
963            r#"{"name": "in"}"#,
964        )
965        .unwrap();
966        std::os::unix::fs::symlink(outside.join("inner"), project.join("packages/link")).unwrap();
967        let scope = dunce::canonicalize(&project).unwrap();
968        let through_link = project.join("packages/link/../pkg/package.json");
969        assert!(read_manifest_in(Some(&scope), &through_link).is_err());
970        let plain = project.join("packages/pkg/package.json");
971        assert!(read_manifest_in(Some(&scope), &plain).is_ok_and(|text| text.contains("in")));
972    }
973
974    #[cfg(unix)]
975    #[test]
976    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
977    fn a_manifest_link_in_its_own_dir_and_a_plain_manifest_load() {
978        let dir = tempfile::tempdir().unwrap();
979        std::fs::write(dir.path().join("package.base.json"), r#"{"name": "a"}"#).unwrap();
980        std::os::unix::fs::symlink("package.base.json", dir.path().join("package.json")).unwrap();
981        assert!(PackageJson::load(&dir.path().join("package.json")).is_ok());
982        std::fs::create_dir(dir.path().join("b")).unwrap();
983        std::fs::write(dir.path().join("b/package.json"), r#"{"name": "b"}"#).unwrap();
984        assert!(PackageJson::load(&dir.path().join("b/package.json")).is_ok());
985    }
986
987    #[test]
988    fn exports_subdirectories_take_one_plain_first_segment() {
989        let pkg: PackageJson = serde_json::from_str(
990            r#"{"exports": {
991                "./ok/x": "./ok/x.js",
992                "plain/x": "./plain.js",
993                "./back\\slash/x": "./b.js",
994                "./c:d/x": "./c.js",
995                ".//abs/x": "./e.js",
996                "./": "./f.js",
997                "./g": "./g.js"
998            }}"#,
999        )
1000        .unwrap();
1001        let mut dirs = pkg.exports_subdirectories();
1002        dirs.sort();
1003        assert_eq!(dirs, vec!["g", "ok"]);
1004    }
1005
1006    #[test]
1007    fn browser_paths_with_dot_dot_segments_are_not_followed() {
1008        let pkg: PackageJson = serde_json::from_str(
1009            r#"{"browser": {
1010                "./a.js": "./a.browser.js",
1011                "./b.js": "../outside/b.js",
1012                "./c.js": "./x/../../c.js"
1013            }}"#,
1014        )
1015        .unwrap();
1016        let entries: Vec<String> = pkg
1017            .entry_points_by_field()
1018            .into_iter()
1019            .map(|(_, entry)| entry)
1020            .collect();
1021        assert_eq!(entries, vec!["./a.browser.js"]);
1022    }
1023
1024    #[test]
1025    fn exports_with_dot_dot_segments_are_not_followed() {
1026        let pkg: PackageJson = serde_json::from_str(
1027            r#"{"exports": {
1028                ".": "./src/index.ts",
1029                "./../outside": "./src/a.ts",
1030                "./a": "../outside/a.ts",
1031                "./b": "./src/../../outside/b.ts",
1032                "./c": { "import": "./src/c.ts", "default": "./x/../../y.ts" }
1033            }}"#,
1034        )
1035        .unwrap();
1036        let entries: Vec<String> = pkg
1037            .entry_points_by_field()
1038            .into_iter()
1039            .map(|(_, entry)| entry)
1040            .collect();
1041        assert_eq!(entries, vec!["./src/index.ts", "./src/c.ts"]);
1042        let mut dirs = pkg.exports_subdirectories();
1043        dirs.sort();
1044        assert_eq!(dirs, vec!["a", "b", "c"]);
1045    }
1046
1047    #[cfg(unix)]
1048    #[test]
1049    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1050    fn a_manifest_link_out_of_its_package_is_refused() {
1051        let dir = tempfile::tempdir().unwrap();
1052        let project = dir.path().join("project");
1053        std::fs::create_dir(&project).unwrap();
1054        std::fs::write(dir.path().join("outside.json"), r#"{"name": "outside"}"#).unwrap();
1055        std::os::unix::fs::symlink(
1056            dir.path().join("outside.json"),
1057            project.join("package.json"),
1058        )
1059        .unwrap();
1060        assert!(PackageJson::load(&project.join("package.json")).is_err());
1061        assert!(PackageJson::read_source(&project.join("package.json")).is_err());
1062        assert!(PackageJson::load_inside(&project, &project.join("package.json")).is_err());
1063    }
1064
1065    #[cfg(unix)]
1066    #[test]
1067    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1068    fn a_dependency_manifest_in_a_node_modules_store_loads() {
1069        let dir = tempfile::tempdir().unwrap();
1070        let store = dir
1071            .path()
1072            .join("node_modules/.pnpm/pkg@1.0.0/node_modules/pkg");
1073        std::fs::create_dir_all(&store).unwrap();
1074        std::fs::write(store.join("package.json"), r#"{"name": "pkg"}"#).unwrap();
1075        let linked = dir.path().join("node_modules/pkg");
1076        std::os::unix::fs::symlink(&store, &linked).unwrap();
1077        let pkg = PackageJson::load(&linked.join("package.json")).unwrap();
1078        assert_eq!(pkg.name.as_deref(), Some("pkg"));
1079    }
1080
1081    #[cfg(unix)]
1082    fn store_package(root: &std::path::Path, store: &str, name: &str) -> std::path::PathBuf {
1083        let dir = root.join(format!(
1084            "node_modules/{store}/{name}@1.0.0/node_modules/{name}"
1085        ));
1086        std::fs::create_dir_all(&dir).unwrap();
1087        std::fs::write(dir.join("package.json"), format!(r#"{{"name": "{name}"}}"#)).unwrap();
1088        dir
1089    }
1090
1091    #[cfg(unix)]
1092    #[test]
1093    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1094    fn workspace_package_links_into_the_root_store_load() {
1095        for store in [".pnpm", ".bun"] {
1096            let dir = tempfile::tempdir().unwrap();
1097            let root = dunce::canonicalize(dir.path()).unwrap();
1098            let stored = store_package(&root, store, "react-dom");
1099            let member = root.join("packages/a/node_modules");
1100            std::fs::create_dir_all(&member).unwrap();
1101            std::os::unix::fs::symlink(&stored, member.join("react-dom")).unwrap();
1102            let manifest = member.join("react-dom/package.json");
1103
1104            let pkg = PackageJson::load_in_scope(&root, &manifest).unwrap();
1105            assert_eq!(pkg.name.as_deref(), Some("react-dom"), "{store}");
1106            std::fs::create_dir(root.join(".git")).unwrap();
1107            assert!(PackageJson::load(&manifest).is_ok(), "{store}");
1108        }
1109    }
1110
1111    #[cfg(unix)]
1112    #[test]
1113    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1114    fn a_workspace_link_in_node_modules_loads() {
1115        let dir = tempfile::tempdir().unwrap();
1116        let root = dunce::canonicalize(dir.path()).unwrap();
1117        std::fs::create_dir_all(root.join("packages/pkg")).unwrap();
1118        std::fs::write(
1119            root.join("packages/pkg/package.json"),
1120            r#"{"name": "@x/pkg"}"#,
1121        )
1122        .unwrap();
1123        std::fs::create_dir_all(root.join("node_modules/@x")).unwrap();
1124        std::os::unix::fs::symlink("../../packages/pkg", root.join("node_modules/@x/pkg")).unwrap();
1125        let manifest = root.join("node_modules/@x/pkg/package.json");
1126
1127        let pkg = PackageJson::load_in_scope(&root, &manifest).unwrap();
1128        assert_eq!(pkg.name.as_deref(), Some("@x/pkg"));
1129        std::fs::create_dir(root.join(".git")).unwrap();
1130        assert!(PackageJson::load(&manifest).is_ok());
1131    }
1132
1133    #[test]
1134    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1135    fn a_relative_manifest_path_loads() {
1136        // A unit test runs in the directory of its crate, two levels below
1137        // the `package.json` of the repository.
1138        let pkg = PackageJson::load(std::path::Path::new("../../package.json")).unwrap();
1139        assert!(pkg.name.is_some());
1140
1141        // A relative path with a leading `..` before `node_modules`.
1142        let dir = tempfile::tempdir().unwrap();
1143        let root = dunce::canonicalize(dir.path()).unwrap();
1144        std::fs::create_dir_all(root.join("node_modules/x")).unwrap();
1145        std::fs::write(root.join("node_modules/x/package.json"), r#"{"name": "x"}"#).unwrap();
1146        let cwd = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
1147        let prefix = |path: &std::path::Path| {
1148            path.components()
1149                .find(|part| matches!(part, std::path::Component::Prefix(_)))
1150                .map(|part| part.as_os_str().to_owned())
1151        };
1152        // A relative path cannot change the drive, so the check needs the
1153        // temp dir on the drive of the crate.
1154        if prefix(&cwd) == prefix(&root) {
1155            let mut relative = std::path::PathBuf::new();
1156            for part in cwd.components() {
1157                if matches!(part, std::path::Component::Normal(_)) {
1158                    relative.push("..");
1159                }
1160            }
1161            for part in root.components() {
1162                if let std::path::Component::Normal(name) = part {
1163                    relative.push(name);
1164                }
1165            }
1166            relative.push("node_modules/x/package.json");
1167            let pkg = PackageJson::load(&relative).unwrap();
1168            assert_eq!(pkg.name.as_deref(), Some("x"));
1169        }
1170    }
1171
1172    /// A workspace without a `.git` entry, with the member `packages/a` and
1173    /// the root file `manifest` that lists it.
1174    #[cfg(unix)]
1175    fn workspace_without_git(manifest: (&str, &str)) -> (tempfile::TempDir, std::path::PathBuf) {
1176        let dir = tempfile::tempdir().unwrap();
1177        let root = dunce::canonicalize(dir.path()).unwrap();
1178        crate::project_read::set_test_ceiling(&root);
1179        std::fs::create_dir_all(root.join("packages/a/node_modules")).unwrap();
1180        std::fs::write(root.join(manifest.0), manifest.1).unwrap();
1181        (dir, root)
1182    }
1183
1184    #[cfg(unix)]
1185    #[test]
1186    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1187    fn a_member_root_without_git_loads_the_manifests_of_the_workspace() {
1188        // pnpm: the member links into the store at the workspace root.
1189        let (_dir, root) =
1190            workspace_without_git(("pnpm-workspace.yaml", "packages:\n  - packages/*\n"));
1191        let stored = store_package(&root, ".pnpm", "react");
1192        let member = root.join("packages/a");
1193        std::os::unix::fs::symlink(&stored, member.join("node_modules/react")).unwrap();
1194        let scope = crate::project_scope_base(&member);
1195        let pkg =
1196            PackageJson::load_in_scope(&scope, &member.join("node_modules/react/package.json"));
1197        assert_eq!(pkg.unwrap().name.as_deref(), Some("react"));
1198
1199        // npm: the package is in the `node_modules` of the workspace root.
1200        let (_dir, root) =
1201            workspace_without_git(("package.json", r#"{"workspaces": ["packages/*"]}"#));
1202        std::fs::create_dir_all(root.join("node_modules/react")).unwrap();
1203        std::fs::write(
1204            root.join("node_modules/react/package.json"),
1205            r#"{"name": "react"}"#,
1206        )
1207        .unwrap();
1208        let scope = crate::project_scope_base(&root.join("packages/a"));
1209        let pkg = PackageJson::load_in_scope(&scope, &root.join("node_modules/react/package.json"));
1210        assert_eq!(pkg.unwrap().name.as_deref(), Some("react"));
1211    }
1212
1213    #[test]
1214    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1215    fn a_node_modules_dir_outside_the_scope_is_refused() {
1216        let dir = tempfile::tempdir().unwrap();
1217        let outer = dunce::canonicalize(dir.path()).unwrap();
1218        let root = outer.join("project");
1219        std::fs::create_dir_all(root.join(".git")).unwrap();
1220        std::fs::create_dir_all(outer.join("node_modules/x")).unwrap();
1221        std::fs::write(
1222            outer.join("node_modules/x/package.json"),
1223            r#"{"name": "x"}"#,
1224        )
1225        .unwrap();
1226        let manifest = outer.join("node_modules/x/package.json");
1227
1228        assert!(PackageJson::load_in_scope(&root, &manifest).is_err());
1229        assert!(PackageJson::load_in_scope(&outer, &manifest).is_ok());
1230    }
1231
1232    #[cfg(unix)]
1233    #[test]
1234    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1235    fn a_node_modules_link_out_of_the_scope_is_refused() {
1236        let dir = tempfile::tempdir().unwrap();
1237        let outer = dunce::canonicalize(dir.path()).unwrap();
1238        let elsewhere = outer.join("elsewhere/node_modules/x");
1239        std::fs::create_dir_all(&elsewhere).unwrap();
1240        std::fs::write(elsewhere.join("package.json"), r#"{"name": "x"}"#).unwrap();
1241        let root = outer.join("project");
1242        std::fs::create_dir_all(root.join(".git")).unwrap();
1243        std::fs::create_dir_all(root.join("node_modules")).unwrap();
1244        std::os::unix::fs::symlink(&elsewhere, root.join("node_modules/x")).unwrap();
1245        let manifest = root.join("node_modules/x/package.json");
1246
1247        assert!(PackageJson::load_in_scope(&root, &manifest).is_err());
1248        assert!(PackageJson::load(&manifest).is_err());
1249        assert!(PackageJson::read_source_in_scope(&root, &manifest).is_err());
1250    }
1251
1252    #[test]
1253    #[cfg_attr(miri, ignore = "tempdir is blocked by Miri isolation")]
1254    fn manifest_parse_errors_name_the_position_only() {
1255        let dir = tempfile::tempdir().unwrap();
1256        let path = dir.path().join("package.json");
1257        std::fs::write(&path, "{\n  \"dependencies\": {\"a\": 7654321}\n}").unwrap();
1258        let err = PackageJson::load(&path).unwrap_err();
1259        assert!(!err.contains("7654321"), "{err}");
1260        assert!(err.contains("line 2"), "{err}");
1261    }
1262
1263    #[test]
1264    fn inline_tool_config_keeps_the_last_value_of_a_repeated_key() {
1265        let pkg: PackageJson = serde_json::from_str(
1266            r#"{"name": "app", "jest": {}, "devDependencies": {"jest": "1"}, "jest": {"x": 1}}"#,
1267        )
1268        .unwrap();
1269        assert_eq!(
1270            pkg.inline_tool_config("jest"),
1271            Some(&serde_json::json!({ "x": 1 }))
1272        );
1273        assert_eq!(pkg.name.as_deref(), Some("app"));
1274        assert_eq!(pkg.dev_dependency_names(), vec!["jest"]);
1275    }
1276
1277    #[test]
1278    fn repeated_unknown_key_parses() {
1279        let pkg: PackageJson =
1280            serde_json::from_str(r#"{"name": "app", "custom": 1, "custom": {"y": 2}}"#).unwrap();
1281        assert_eq!(pkg.name.as_deref(), Some("app"));
1282        assert!(pkg.inline_tool_configs.is_empty());
1283    }
1284
1285    #[test]
1286    fn inline_tool_config_keeps_any_value_shape() {
1287        let pkg: PackageJson = serde_json::from_str(
1288            r#"{"prettier": "@acme/prettier-config", "jest": 5, "mocha": null, "tsup": [1, "a"]}"#,
1289        )
1290        .unwrap();
1291        assert_eq!(
1292            pkg.inline_tool_config("prettier"),
1293            Some(&serde_json::json!("@acme/prettier-config"))
1294        );
1295        assert_eq!(pkg.inline_tool_config("jest"), Some(&serde_json::json!(5)));
1296        assert_eq!(
1297            pkg.inline_tool_config("mocha"),
1298            Some(&serde_json::Value::Null)
1299        );
1300        assert_eq!(
1301            pkg.inline_tool_config("tsup"),
1302            Some(&serde_json::json!([1, "a"]))
1303        );
1304        assert_eq!(pkg.inline_tool_config("custom"), None);
1305    }
1306
1307    #[test]
1308    fn package_json_workspace_patterns_array() {
1309        let pkg: PackageJson =
1310            serde_json::from_str(r#"{"workspaces": ["packages/*", "apps/*"]}"#).unwrap();
1311        let patterns = pkg.workspace_patterns();
1312        assert_eq!(patterns, vec!["packages/*", "apps/*"]);
1313    }
1314
1315    #[test]
1316    fn read_source_strips_a_leading_byte_order_mark() {
1317        let dir = tempfile::tempdir().expect("tempdir");
1318        let path = dir.path().join("package.json");
1319        std::fs::write(&path, "\u{FEFF}{\"name\":\"a\"}\n").expect("write");
1320        assert_eq!(
1321            PackageJson::read_source(&path).expect("read"),
1322            "{\"name\":\"a\"}\n"
1323        );
1324    }
1325
1326    #[test]
1327    fn parse_ignores_a_leading_byte_order_mark() {
1328        let pkg = PackageJson::parse("\u{FEFF}{\"dependencies\":{\"react\":\"^18.0.0\"}}")
1329            .expect("a BOM-prefixed manifest is valid");
1330        assert_eq!(pkg.all_dependency_names(), ["react"]);
1331    }
1332
1333    #[test]
1334    fn package_json_workspace_patterns_object() {
1335        let pkg: PackageJson =
1336            serde_json::from_str(r#"{"workspaces": {"packages": ["packages/*"]}}"#).unwrap();
1337        let patterns = pkg.workspace_patterns();
1338        assert_eq!(patterns, vec!["packages/*"]);
1339    }
1340
1341    #[test]
1342    fn package_json_workspace_patterns_none() {
1343        let pkg: PackageJson = serde_json::from_str(r#"{"name": "test"}"#).unwrap();
1344        let patterns = pkg.workspace_patterns();
1345        assert!(patterns.is_empty());
1346    }
1347
1348    #[test]
1349    fn package_json_workspace_patterns_empty_array() {
1350        let pkg: PackageJson = serde_json::from_str(r#"{"workspaces": []}"#).unwrap();
1351        let patterns = pkg.workspace_patterns();
1352        assert!(patterns.is_empty());
1353    }
1354
1355    #[test]
1356    fn package_json_load_valid() {
1357        let temp_dir = std::env::temp_dir().join("fallow-test-pkg-json");
1358        let _ = std::fs::create_dir_all(&temp_dir);
1359        let pkg_path = temp_dir.join("package.json");
1360        std::fs::write(&pkg_path, r#"{"name": "test", "main": "index.js"}"#).unwrap();
1361
1362        let pkg = PackageJson::load(&pkg_path).unwrap();
1363        assert_eq!(pkg.name, Some("test".to_string()));
1364        assert_eq!(pkg.main, Some("index.js".to_string()));
1365
1366        let _ = std::fs::remove_dir_all(&temp_dir);
1367    }
1368
1369    #[test]
1370    fn package_json_private_non_bool_values_are_ignored() {
1371        for raw in [
1372            r#"{"private": "true"}"#,
1373            r#"{"private": 1}"#,
1374            r#"{"private": null}"#,
1375        ] {
1376            let pkg: PackageJson = serde_json::from_str(raw).unwrap();
1377            assert_eq!(pkg.private, None);
1378        }
1379
1380        let pkg: PackageJson = serde_json::from_str(r#"{"private": true}"#).unwrap();
1381        assert_eq!(pkg.private, Some(true));
1382
1383        let pkg: PackageJson = serde_json::from_str(r#"{"private": false}"#).unwrap();
1384        assert_eq!(pkg.private, Some(false));
1385    }
1386
1387    #[test]
1388    fn package_json_files_preserves_string_array_values() {
1389        let pkg: PackageJson =
1390            serde_json::from_str(r#"{"files": ["index.js", "template-*", "dist"]}"#).unwrap();
1391        assert_eq!(pkg.files, vec!["index.js", "template-*", "dist"]);
1392    }
1393
1394    #[test]
1395    fn package_json_files_missing_or_unexpected_shapes_are_ignored() {
1396        let pkg: PackageJson = serde_json::from_str(r#"{"name": "pkg"}"#).unwrap();
1397        assert!(pkg.files.is_empty());
1398
1399        let pkg: PackageJson = serde_json::from_str(r#"{"files": "dist"}"#).unwrap();
1400        assert!(pkg.files.is_empty());
1401
1402        let pkg: PackageJson =
1403            serde_json::from_str(r#"{"files": ["template-*", 42, false, null]}"#).unwrap();
1404        assert_eq!(pkg.files, vec!["template-*"]);
1405    }
1406
1407    #[test]
1408    fn package_json_napi_config_preserves_current_string_fields() {
1409        let pkg: PackageJson = serde_json::from_str(
1410            r#"{
1411                "napi": {
1412                    "binaryName": "srcmap-codec",
1413                    "packageName": "@srcmap/codec",
1414                    "targets": [
1415                        "aarch64-apple-darwin",
1416                        "x86_64-unknown-linux-gnu"
1417                    ]
1418                }
1419            }"#,
1420        )
1421        .unwrap();
1422
1423        let napi = pkg.napi.expect("napi config");
1424        assert_eq!(napi.binary_name.as_deref(), Some("srcmap-codec"));
1425        assert_eq!(napi.package_name.as_deref(), Some("@srcmap/codec"));
1426        assert_eq!(
1427            napi.targets,
1428            vec![
1429                "aarch64-apple-darwin".to_string(),
1430                "x86_64-unknown-linux-gnu".to_string()
1431            ]
1432        );
1433    }
1434
1435    #[test]
1436    fn package_json_napi_config_ignores_unexpected_shapes() {
1437        let pkg: PackageJson = serde_json::from_str(r#"{"napi": "enabled"}"#).unwrap();
1438        assert!(pkg.napi.is_none());
1439
1440        let pkg: PackageJson = serde_json::from_str(
1441            r#"{
1442                "napi": {
1443                    "binaryName": 42,
1444                    "packageName": "",
1445                    "targets": ["x86_64-apple-darwin", false, null]
1446                }
1447            }"#,
1448        )
1449        .unwrap();
1450
1451        let napi = pkg.napi.expect("napi config");
1452        assert!(napi.binary_name.is_none());
1453        assert!(napi.package_name.is_none());
1454        assert_eq!(napi.targets, vec!["x86_64-apple-darwin"]);
1455    }
1456
1457    #[test]
1458    fn package_json_load_missing_file() {
1459        let result = PackageJson::load(std::path::Path::new("/nonexistent/package.json"));
1460        assert!(result.is_err());
1461    }
1462
1463    #[test]
1464    fn package_json_entry_points_combined() {
1465        let pkg: PackageJson = serde_json::from_str(
1466            r#"{
1467            "main": "dist/index.js",
1468            "module": "dist/index.mjs",
1469            "types": "dist/index.d.ts",
1470            "typings": "dist/types.d.ts"
1471        }"#,
1472        )
1473        .unwrap();
1474        let entries = pkg.entry_points();
1475        assert_eq!(entries.len(), 4);
1476        assert!(entries.contains(&"dist/index.js".to_string()));
1477        assert!(entries.contains(&"dist/index.mjs".to_string()));
1478        assert!(entries.contains(&"dist/index.d.ts".to_string()));
1479        assert!(entries.contains(&"dist/types.d.ts".to_string()));
1480    }
1481
1482    #[test]
1483    fn package_json_exports_nested() {
1484        let pkg: PackageJson = serde_json::from_str(
1485            r#"{
1486            "exports": {
1487                ".": {
1488                    "import": "./dist/index.mjs",
1489                    "require": "./dist/index.cjs"
1490                },
1491                "./utils": {
1492                    "import": "./dist/utils.mjs"
1493                }
1494            }
1495        }"#,
1496        )
1497        .unwrap();
1498        let entries = pkg.entry_points();
1499        assert!(entries.contains(&"./dist/index.mjs".to_string()));
1500        assert!(entries.contains(&"./dist/index.cjs".to_string()));
1501        assert!(entries.contains(&"./dist/utils.mjs".to_string()));
1502    }
1503
1504    #[test]
1505    fn package_json_exports_array() {
1506        let pkg: PackageJson = serde_json::from_str(
1507            r#"{
1508            "exports": {
1509                ".": ["./dist/index.mjs", "./dist/index.cjs"]
1510            }
1511        }"#,
1512        )
1513        .unwrap();
1514        let entries = pkg.entry_points();
1515        assert!(entries.contains(&"./dist/index.mjs".to_string()));
1516        assert!(entries.contains(&"./dist/index.cjs".to_string()));
1517    }
1518
1519    #[test]
1520    fn extract_exports_ignores_non_relative() {
1521        let pkg: PackageJson = serde_json::from_str(
1522            r#"{
1523            "exports": {
1524                ".": "not-a-relative-path"
1525            }
1526        }"#,
1527        )
1528        .unwrap();
1529        let entries = pkg.entry_points();
1530        assert!(entries.is_empty());
1531    }
1532
1533    #[test]
1534    fn package_json_source_field() {
1535        let pkg: PackageJson = serde_json::from_str(
1536            r#"{
1537            "main": "dist/index.js",
1538            "source": "src/index.ts"
1539        }"#,
1540        )
1541        .unwrap();
1542        let entries = pkg.entry_points();
1543        assert!(entries.contains(&"src/index.ts".to_string()));
1544        assert!(entries.contains(&"dist/index.js".to_string()));
1545    }
1546
1547    #[test]
1548    fn package_json_browser_field_string() {
1549        let pkg: PackageJson = serde_json::from_str(
1550            r#"{
1551            "browser": "./dist/browser.js"
1552        }"#,
1553        )
1554        .unwrap();
1555        let entries = pkg.entry_points();
1556        assert!(entries.contains(&"./dist/browser.js".to_string()));
1557    }
1558
1559    #[test]
1560    fn package_json_browser_field_object() {
1561        let pkg: PackageJson = serde_json::from_str(
1562            r#"{
1563            "browser": {
1564                "./server.js": "./browser.js",
1565                "module-name": false
1566            }
1567        }"#,
1568        )
1569        .unwrap();
1570        let entries = pkg.entry_points();
1571        assert!(entries.contains(&"./browser.js".to_string()));
1572        assert_eq!(entries.len(), 1);
1573    }
1574
1575    #[test]
1576    fn package_json_exports_string() {
1577        let pkg: PackageJson = serde_json::from_str(r#"{"exports": "./dist/index.js"}"#).unwrap();
1578        let entries = pkg.entry_points();
1579        assert_eq!(entries, vec!["./dist/index.js"]);
1580    }
1581
1582    #[test]
1583    fn package_json_workspace_patterns_object_with_nohoist() {
1584        let pkg: PackageJson = serde_json::from_str(
1585            r#"{
1586            "workspaces": {
1587                "packages": ["packages/*", "apps/*"],
1588                "nohoist": ["**/react-native"]
1589            }
1590        }"#,
1591        )
1592        .unwrap();
1593        let patterns = pkg.workspace_patterns();
1594        assert_eq!(patterns, vec!["packages/*", "apps/*"]);
1595    }
1596
1597    #[test]
1598    fn package_json_missing_optional_fields() {
1599        let pkg: PackageJson = serde_json::from_str(r"{}").unwrap();
1600        assert!(pkg.name.is_none());
1601        assert!(pkg.main.is_none());
1602        assert!(pkg.module.is_none());
1603        assert!(pkg.types.is_none());
1604        assert!(pkg.typings.is_none());
1605        assert!(pkg.source.is_none());
1606        assert!(pkg.browser.is_none());
1607        assert!(pkg.bin.is_none());
1608        assert!(pkg.exports.is_none());
1609        assert!(pkg.dependencies.is_none());
1610        assert!(pkg.dev_dependencies.is_none());
1611        assert!(pkg.peer_dependencies.is_none());
1612        assert!(pkg.peer_dependencies_meta.is_none());
1613        assert!(pkg.optional_dependencies.is_none());
1614        assert!(pkg.scripts.is_none());
1615        assert!(pkg.workspaces.is_none());
1616        assert!(pkg.entry_points().is_empty());
1617        assert!(pkg.workspace_patterns().is_empty());
1618        assert!(pkg.all_dependency_names().is_empty());
1619    }
1620
1621    #[test]
1622    fn package_json_all_dependency_names() {
1623        let pkg: PackageJson = serde_json::from_str(
1624            r#"{
1625            "dependencies": {"react": "^18", "react-dom": "^18"},
1626            "devDependencies": {"typescript": "^5"},
1627            "peerDependencies": {"node": ">=18"},
1628            "optionalDependencies": {"fsevents": "^2"}
1629        }"#,
1630        )
1631        .unwrap();
1632        let deps = pkg.all_dependency_names();
1633        assert_eq!(deps.len(), 5);
1634        assert!(deps.contains(&"react".to_string()));
1635        assert!(deps.contains(&"react-dom".to_string()));
1636        assert!(deps.contains(&"typescript".to_string()));
1637        assert!(deps.contains(&"node".to_string()));
1638        assert!(deps.contains(&"fsevents".to_string()));
1639    }
1640
1641    #[test]
1642    fn package_json_production_dependency_names() {
1643        let pkg: PackageJson = serde_json::from_str(
1644            r#"{
1645            "dependencies": {"react": "^18"},
1646            "devDependencies": {"typescript": "^5"}
1647        }"#,
1648        )
1649        .unwrap();
1650        let prod = pkg.production_dependency_names();
1651        assert_eq!(prod, vec!["react"]);
1652        let dev = pkg.dev_dependency_names();
1653        assert_eq!(dev, vec!["typescript"]);
1654    }
1655
1656    #[test]
1657    fn package_json_bin_field_string() {
1658        let pkg: PackageJson = serde_json::from_str(r#"{"bin": "./cli.js"}"#).unwrap();
1659        let entries = pkg.entry_points();
1660        assert!(entries.contains(&"./cli.js".to_string()));
1661    }
1662
1663    #[test]
1664    fn package_json_bin_field_object() {
1665        let pkg: PackageJson = serde_json::from_str(
1666            r#"{"bin": {"my-cli": "./bin/cli.js", "my-tool": "./bin/tool.js"}}"#,
1667        )
1668        .unwrap();
1669        let entries = pkg.entry_points();
1670        assert!(entries.contains(&"./bin/cli.js".to_string()));
1671        assert!(entries.contains(&"./bin/tool.js".to_string()));
1672    }
1673
1674    #[test]
1675    fn package_json_exports_deeply_nested() {
1676        let pkg: PackageJson = serde_json::from_str(
1677            r#"{
1678            "exports": {
1679                ".": {
1680                    "node": {
1681                        "import": "./dist/node.mjs",
1682                        "require": "./dist/node.cjs"
1683                    },
1684                    "browser": {
1685                        "import": "./dist/browser.mjs"
1686                    }
1687                }
1688            }
1689        }"#,
1690        )
1691        .unwrap();
1692        let entries = pkg.entry_points();
1693        assert_eq!(entries.len(), 3);
1694        assert!(entries.contains(&"./dist/node.mjs".to_string()));
1695        assert!(entries.contains(&"./dist/node.cjs".to_string()));
1696        assert!(entries.contains(&"./dist/browser.mjs".to_string()));
1697    }
1698
1699    #[test]
1700    fn package_json_peer_deps_only() {
1701        let pkg: PackageJson =
1702            serde_json::from_str(r#"{"peerDependencies": {"react": "^18", "react-dom": "^18"}}"#)
1703                .unwrap();
1704        let all = pkg.all_dependency_names();
1705        assert_eq!(all.len(), 2);
1706        assert!(all.contains(&"react".to_string()));
1707        assert!(all.contains(&"react-dom".to_string()));
1708
1709        assert!(pkg.production_dependency_names().is_empty());
1710        assert!(pkg.dev_dependency_names().is_empty());
1711    }
1712
1713    #[test]
1714    fn package_json_peer_dependency_names_include_optional_peers() {
1715        let pkg: PackageJson = serde_json::from_str(
1716            r#"{
1717            "peerDependencies": {"react": "^18", "typescript": "^5"},
1718            "peerDependenciesMeta": {"typescript": {"optional": true}}
1719        }"#,
1720        )
1721        .unwrap();
1722        let mut names = pkg.peer_dependency_names();
1723        names.sort_unstable();
1724        assert_eq!(names, vec!["react", "typescript"]);
1725    }
1726
1727    #[test]
1728    fn package_json_optional_deps_in_all_names() {
1729        let pkg: PackageJson =
1730            serde_json::from_str(r#"{"optionalDependencies": {"fsevents": "^2"}}"#).unwrap();
1731        let all = pkg.all_dependency_names();
1732        assert!(all.contains(&"fsevents".to_string()));
1733    }
1734
1735    #[test]
1736    fn package_json_browser_array_ignored() {
1737        let pkg: PackageJson =
1738            serde_json::from_str(r#"{"browser": ["./a.js", "./b.js"]}"#).unwrap();
1739        let entries = pkg.entry_points();
1740        assert!(
1741            entries.is_empty(),
1742            "array browser field should not produce entries"
1743        );
1744    }
1745
1746    #[test]
1747    fn package_json_browser_object_non_relative_skipped() {
1748        let pkg: PackageJson = serde_json::from_str(
1749            r#"{"browser": {"crypto": false, "./local.js": "./browser-local.js"}}"#,
1750        )
1751        .unwrap();
1752        let entries = pkg.entry_points();
1753        assert_eq!(entries.len(), 1);
1754        assert!(entries.contains(&"./browser-local.js".to_string()));
1755    }
1756
1757    #[test]
1758    fn package_json_exports_null_value() {
1759        let pkg: PackageJson =
1760            serde_json::from_str(r#"{"exports": {".": "./dist/index.js", "./internal": null}}"#)
1761                .unwrap();
1762        let entries = pkg.entry_points();
1763        assert_eq!(entries.len(), 1);
1764        assert!(entries.contains(&"./dist/index.js".to_string()));
1765    }
1766
1767    #[test]
1768    fn package_json_exports_empty_object() {
1769        let pkg: PackageJson = serde_json::from_str(r#"{"exports": {}}"#).unwrap();
1770        let entries = pkg.entry_points();
1771        assert!(entries.is_empty());
1772    }
1773
1774    #[test]
1775    fn package_json_workspace_patterns_string_value_ignored() {
1776        let pkg: PackageJson = serde_json::from_str(r#"{"workspaces": "packages/*"}"#).unwrap();
1777        let patterns = pkg.workspace_patterns();
1778        assert!(patterns.is_empty());
1779    }
1780
1781    #[test]
1782    fn package_json_workspace_patterns_object_missing_packages() {
1783        let pkg: PackageJson =
1784            serde_json::from_str(r#"{"workspaces": {"nohoist": ["**/react-native"]}}"#).unwrap();
1785        let patterns = pkg.workspace_patterns();
1786        assert!(patterns.is_empty());
1787    }
1788
1789    #[test]
1790    fn package_json_load_invalid_json() {
1791        let temp_dir = std::env::temp_dir().join("fallow-test-invalid-pkg-json");
1792        let _ = std::fs::create_dir_all(&temp_dir);
1793        let pkg_path = temp_dir.join("package.json");
1794        std::fs::write(&pkg_path, "{ not valid json }").unwrap();
1795
1796        let result = PackageJson::load(&pkg_path);
1797        assert!(result.is_err());
1798        let err = result.unwrap_err();
1799        assert!(err.contains("Failed to parse"), "got: {err}");
1800
1801        let _ = std::fs::remove_dir_all(&temp_dir);
1802    }
1803
1804    #[test]
1805    fn package_json_bin_object_non_string_values_skipped() {
1806        let pkg: PackageJson =
1807            serde_json::from_str(r#"{"bin": {"cli": "./bin/cli.js", "bad": 42}}"#).unwrap();
1808        let entries = pkg.entry_points();
1809        assert_eq!(entries.len(), 1);
1810        assert!(entries.contains(&"./bin/cli.js".to_string()));
1811    }
1812
1813    #[test]
1814    fn package_json_default() {
1815        let pkg = PackageJson::default();
1816        assert!(pkg.name.is_none());
1817        assert!(pkg.main.is_none());
1818        assert!(pkg.entry_points().is_empty());
1819        assert!(pkg.all_dependency_names().is_empty());
1820        assert!(pkg.workspace_patterns().is_empty());
1821    }
1822
1823    #[test]
1824    fn exports_subdirectories_preact_style() {
1825        let pkg: PackageJson = serde_json::from_str(
1826            r#"{
1827            "exports": {
1828                ".": "./dist/index.js",
1829                "./compat": { "import": "./compat/dist/compat.mjs" },
1830                "./hooks": { "import": "./hooks/dist/hooks.mjs" },
1831                "./debug": { "import": "./debug/dist/debug.mjs" },
1832                "./jsx-runtime": { "import": "./jsx-runtime/dist/jsx.mjs" },
1833                "./package.json": "./package.json"
1834            }
1835        }"#,
1836        )
1837        .unwrap();
1838        let mut dirs = pkg.exports_subdirectories();
1839        dirs.sort();
1840        assert_eq!(dirs, vec!["compat", "debug", "hooks", "jsx-runtime"]);
1841    }
1842
1843    #[test]
1844    fn exports_subdirectories_skips_dist_dirs() {
1845        let pkg: PackageJson = serde_json::from_str(
1846            r#"{
1847            "exports": {
1848                "./dist/index.js": "./dist/index.js",
1849                "./build/bundle.js": "./build/bundle.js",
1850                "./lib/utils": "./lib/utils.js",
1851                "./compat": "./compat/index.js"
1852            }
1853        }"#,
1854        )
1855        .unwrap();
1856        let dirs = pkg.exports_subdirectories();
1857        assert_eq!(dirs, vec!["compat"]);
1858    }
1859
1860    #[test]
1861    fn exports_subdirectories_no_exports() {
1862        let pkg: PackageJson = serde_json::from_str(r#"{"main": "index.js"}"#).unwrap();
1863        assert!(pkg.exports_subdirectories().is_empty());
1864    }
1865
1866    #[test]
1867    fn exports_subdirectories_dot_only() {
1868        let pkg: PackageJson =
1869            serde_json::from_str(r#"{"exports": {".": "./dist/index.js"}}"#).unwrap();
1870        assert!(pkg.exports_subdirectories().is_empty());
1871    }
1872
1873    #[test]
1874    fn npm_aliases_read_the_aliased_package_name() {
1875        let pkg: PackageJson = serde_json::from_str(
1876            r#"{
1877                "dependencies": {"plain": "npm:left-pad@^1.3.0", "range": "^1.0.0"},
1878                "devDependencies": {
1879                    "@typescript/native": "npm:typescript@~7.0.2",
1880                    "typescript": "npm:@typescript/typescript6@^6.0.2",
1881                    "bare": "npm:eslint",
1882                    "same": "npm:same@1.0.0",
1883                    "path": "npm:./local",
1884                    "bad-scope": "npm:@scope@1.0.0",
1885                    "workspace": "workspace:@scope/core@*"
1886                }
1887            }"#,
1888        )
1889        .unwrap();
1890        assert_eq!(
1891            pkg.npm_aliases(),
1892            [
1893                ("@typescript/native", "typescript"),
1894                ("bare", "eslint"),
1895                ("plain", "left-pad"),
1896                ("typescript", "@typescript/typescript6"),
1897            ]
1898            .map(|(alias, target)| (alias.to_string(), target.to_string()))
1899        );
1900    }
1901
1902    #[test]
1903    fn npm_aliases_with_catalogs_resolves_catalog_references() {
1904        let catalogs = super::super::pnpm_catalog::parse_pnpm_catalog_data(
1905            "catalog:\n  \"@typescript/native\": npm:typescript@~7.0.2\n  react: ^18.2.0\ncatalogs:\n  tools:\n    vite-next: npm:vite@^7.0.0\n",
1906        )
1907        .unwrap();
1908        let pkg: PackageJson = serde_json::from_str(
1909            r#"{
1910                "devDependencies": {
1911                    "@typescript/native": "catalog:",
1912                    "react": "catalog:default",
1913                    "vite-next": "catalog:tools",
1914                    "missing": "catalog:tools",
1915                    "inline": "npm:left-pad@1"
1916                }
1917            }"#,
1918        )
1919        .unwrap();
1920        assert_eq!(
1921            pkg.npm_aliases_with_catalogs(Some(&catalogs)),
1922            [
1923                ("@typescript/native", "typescript"),
1924                ("inline", "left-pad"),
1925                ("vite-next", "vite"),
1926            ]
1927            .map(|(alias, target)| (alias.to_string(), target.to_string()))
1928        );
1929        assert_eq!(
1930            pkg.npm_aliases(),
1931            [("inline".to_string(), "left-pad".to_string())]
1932        );
1933    }
1934
1935    #[test]
1936    fn workspace_alias_target_reads_the_aliased_package_name() {
1937        let pkg: PackageJson = serde_json::from_str(
1938            r#"{
1939                "dependencies": {
1940                    "vite": "workspace:@scope/core@*",
1941                    "plain": "workspace:other@^1.0.0",
1942                    "range": "workspace:*",
1943                    "caret": "workspace:^1.0.0",
1944                    "path": "workspace:../core",
1945                    "npm": "npm:@scope/core@1.0.0",
1946                    "bad-scope": "workspace:@scope@1.0.0"
1947                },
1948                "devDependencies": {"tool": "workspace:@scope/tool@workspace:*"}
1949            }"#,
1950        )
1951        .unwrap();
1952        assert_eq!(pkg.workspace_alias_target("vite"), Some("@scope/core"));
1953        assert_eq!(pkg.workspace_alias_target("plain"), Some("other"));
1954        assert_eq!(pkg.workspace_alias_target("tool"), Some("@scope/tool"));
1955        for name in ["range", "caret", "path", "npm", "bad-scope", "missing"] {
1956            assert_eq!(pkg.workspace_alias_target(name), None, "{name}");
1957        }
1958    }
1959}