sublime_standard_tools 0.0.15

A collection of utilities for working with Node.js projects from Rust applications
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! # Node.js Package Manager Abstractions
//!
//! ## What
//! This file defines the fundamental types and abstractions for working with
//! Node.js package managers. It provides the `PackageManagerKind` enum that
//! represents different package manager implementations and the `PackageManager`
//! struct that encapsulates package manager detection and functionality.
//!
//! ## How
//! The module defines types that model the various Node.js package managers
//! available in the ecosystem (npm, yarn, pnpm, bun, jsr). Each package manager
//! has specific characteristics like lock files, commands, and configuration
//! formats that are captured in these abstractions. The types are designed
//! to be generic and reusable across all Node.js project types.
//!
//! ## Why
//! Previously, package manager types were incorrectly placed in the monorepo
//! module, creating conceptual dependencies where simple projects needed to
//! import monorepo-specific logic. This module provides the correct location
//! for these fundamental Node.js concepts, enabling clean separation of concerns
//! and reusability across all project types.

use crate::error::{Error, MonorepoError, Result};
use std::path::{Path, PathBuf};

/// Represents the type of package manager used in a Node.js project.
///
/// Different package managers have different characteristics including lock files,
/// command syntax, workspace configurations, and performance characteristics.
/// This enum captures these variations to enable package-manager-specific
/// processing and functionality.
///
/// # Examples
///
/// ```
/// use sublime_standard_tools::node::PackageManagerKind;
///
/// let npm = PackageManagerKind::Npm;
/// assert_eq!(npm.command(), "npm");
/// assert_eq!(npm.lock_file(), "package-lock.json");
///
/// let yarn = PackageManagerKind::Yarn;
/// assert_eq!(yarn.command(), "yarn");
/// assert_eq!(yarn.lock_file(), "yarn.lock");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
pub enum PackageManagerKind {
    /// npm package manager (default for Node.js)
    ///
    /// The standard package manager that comes with Node.js installations.
    /// Uses package-lock.json for dependency locking and npm-shrinkwrap.json
    /// for publishing. Supports workspaces since version 7.
    Npm,

    /// Yarn package manager
    ///
    /// A fast, reliable, and secure dependency management tool created by
    /// Facebook. Uses yarn.lock for dependency locking and has built-in
    /// workspace support. Available in both v1 (Classic) and v2+ (Berry).
    Yarn,

    /// pnpm package manager (performance-oriented)
    ///
    /// A fast, disk space efficient package manager that uses hard links
    /// and symlinks to save disk space. Uses pnpm-lock.yaml for dependency
    /// locking and has excellent monorepo/workspace support.
    Pnpm,

    /// Bun package manager and runtime
    ///
    /// A fast all-in-one JavaScript runtime, bundler, test runner, and
    /// package manager. Uses bun.lockb (binary format) for dependency
    /// locking and provides npm-compatible API.
    Bun,

    /// Jsr package manager and runtime
    ///
    /// A modern package registry and runtime for TypeScript and JavaScript.
    /// Designed for modern JavaScript development with native TypeScript
    /// support and web-standard APIs.
    Jsr,
}

impl PackageManagerKind {
    /// Returns the command name for this package manager.
    ///
    /// This is the executable name that would be used in shell commands
    /// to invoke the package manager.
    ///
    /// # Returns
    ///
    /// The command string for the package manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::PackageManagerKind;
    ///
    /// assert_eq!(PackageManagerKind::Npm.command(), "npm");
    /// assert_eq!(PackageManagerKind::Yarn.command(), "yarn");
    /// assert_eq!(PackageManagerKind::Pnpm.command(), "pnpm");
    /// assert_eq!(PackageManagerKind::Bun.command(), "bun");
    /// assert_eq!(PackageManagerKind::Jsr.command(), "jsr");
    /// ```
    #[must_use]
    pub fn command(&self) -> &'static str {
        match self {
            Self::Npm => "npm",
            Self::Yarn => "yarn",
            Self::Pnpm => "pnpm",
            Self::Bun => "bun",
            Self::Jsr => "jsr",
        }
    }

    /// Returns the lock file name for this package manager.
    ///
    /// Lock files contain the exact versions of all dependencies and
    /// are used to ensure reproducible installations across environments.
    ///
    /// # Returns
    ///
    /// The lock file name for the package manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::PackageManagerKind;
    ///
    /// assert_eq!(PackageManagerKind::Npm.lock_file(), "package-lock.json");
    /// assert_eq!(PackageManagerKind::Yarn.lock_file(), "yarn.lock");
    /// assert_eq!(PackageManagerKind::Pnpm.lock_file(), "pnpm-lock.yaml");
    /// assert_eq!(PackageManagerKind::Bun.lock_file(), "bun.lockb");
    /// assert_eq!(PackageManagerKind::Jsr.lock_file(), "jsr.json");
    /// ```
    #[must_use]
    pub fn lock_file(&self) -> &'static str {
        match self {
            Self::Npm => "package-lock.json",
            Self::Yarn => "yarn.lock",
            Self::Pnpm => "pnpm-lock.yaml",
            Self::Bun => "bun.lockb",
            Self::Jsr => "jsr.json",
        }
    }

    /// Returns a human-readable name for this package manager.
    ///
    /// This provides a consistent display name that can be used in
    /// user interfaces, logging, and error messages.
    ///
    /// # Returns
    ///
    /// A human-readable name for the package manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::PackageManagerKind;
    ///
    /// assert_eq!(PackageManagerKind::Npm.name(), "npm");
    /// assert_eq!(PackageManagerKind::Yarn.name(), "yarn");
    /// assert_eq!(PackageManagerKind::Pnpm.name(), "pnpm");
    /// assert_eq!(PackageManagerKind::Bun.name(), "bun");
    /// assert_eq!(PackageManagerKind::Jsr.name(), "jsr");
    /// ```
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Npm => "npm",
            Self::Yarn => "yarn",
            Self::Pnpm => "pnpm",
            Self::Bun => "bun",
            Self::Jsr => "jsr",
        }
    }

    /// Checks if this package manager supports workspaces natively.
    ///
    /// Workspace support enables monorepo functionality where multiple
    /// packages can be managed within a single repository with shared
    /// dependencies and cross-package linking.
    ///
    /// # Returns
    ///
    /// `true` if the package manager supports workspaces, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::PackageManagerKind;
    ///
    /// assert!(PackageManagerKind::Npm.supports_workspaces());
    /// assert!(PackageManagerKind::Yarn.supports_workspaces());
    /// assert!(PackageManagerKind::Pnpm.supports_workspaces());
    /// assert!(PackageManagerKind::Bun.supports_workspaces());
    /// assert!(!PackageManagerKind::Jsr.supports_workspaces()); // Not primarily a workspace manager
    /// ```
    #[must_use]
    pub fn supports_workspaces(&self) -> bool {
        match self {
            Self::Npm | Self::Yarn | Self::Pnpm | Self::Bun => true,
            Self::Jsr => false,
        }
    }

    /// Returns the workspace configuration file for this package manager.
    ///
    /// Different package managers use different files to configure workspace
    /// behavior and define which directories contain packages.
    ///
    /// # Returns
    ///
    /// * `Some(&str)` - The workspace configuration file name
    /// * `None` - If the package manager doesn't support workspaces or uses package.json
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::PackageManagerKind;
    ///
    /// assert_eq!(PackageManagerKind::Npm.workspace_config_file(), None); // Uses package.json
    /// assert_eq!(PackageManagerKind::Yarn.workspace_config_file(), None); // Uses package.json
    /// assert_eq!(PackageManagerKind::Pnpm.workspace_config_file(), Some("pnpm-workspace.yaml"));
    /// assert_eq!(PackageManagerKind::Bun.workspace_config_file(), None); // Uses package.json
    /// assert_eq!(PackageManagerKind::Jsr.workspace_config_file(), None);
    /// ```
    #[must_use]
    pub fn workspace_config_file(&self) -> Option<&'static str> {
        match self {
            Self::Npm | Self::Yarn | Self::Bun | Self::Jsr => None, // Uses package.json workspaces field or doesn't support workspaces
            Self::Pnpm => Some("pnpm-workspace.yaml"),
        }
    }
}

// Custom deserialization implementation for case-insensitive parsing
impl<'de> serde::Deserialize<'de> for PackageManagerKind {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.to_lowercase().as_str() {
            "npm" => Ok(PackageManagerKind::Npm),
            "yarn" => Ok(PackageManagerKind::Yarn),
            "pnpm" => Ok(PackageManagerKind::Pnpm),
            "bun" => Ok(PackageManagerKind::Bun),
            "jsr" => Ok(PackageManagerKind::Jsr),
            _ => Err(serde::de::Error::unknown_variant(&s, &["npm", "yarn", "pnpm", "bun", "jsr"])),
        }
    }
}

/// Represents a package manager detected in a Node.js project.
///
/// This struct encapsulates information about a detected package manager
/// including its type and the root directory where it was found. It provides
/// methods for accessing package manager properties and performing common
/// operations.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
///
/// // Create a package manager representation
/// let manager = PackageManager::new(PackageManagerKind::Npm, "/project/root");
/// assert_eq!(manager.kind(), PackageManagerKind::Npm);
/// assert_eq!(manager.root(), Path::new("/project/root"));
/// assert_eq!(manager.command(), "npm");
/// ```
#[derive(Debug, Clone)]
pub struct PackageManager {
    /// The type of package manager
    pub(crate) kind: PackageManagerKind,
    /// The root directory where the package manager was detected
    pub(crate) root: PathBuf,
}

impl PackageManager {
    /// Creates a new PackageManager instance.
    ///
    /// # Arguments
    ///
    /// * `kind` - The type of package manager
    /// * `root` - The root directory path where the package manager is used
    ///
    /// # Returns
    ///
    /// A new PackageManager instance configured with the specified type and root.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let manager = PackageManager::new(PackageManagerKind::Yarn, "/path/to/project");
    /// assert_eq!(manager.kind(), PackageManagerKind::Yarn);
    /// ```
    #[must_use]
    pub fn new(kind: PackageManagerKind, root: impl Into<PathBuf>) -> Self {
        Self { kind, root: root.into() }
    }

    /// Detects which package manager is being used in the specified path using default configuration.
    ///
    /// Uses the default detection order: Bun, pnpm, Yarn, npm, JSR.
    ///
    /// # Arguments
    ///
    /// * `path` - The directory path to check for package manager lock files
    ///
    /// # Errors
    ///
    /// Returns a [`MonorepoError::ManagerNotFound`] if no package manager
    /// lock files are found in the specified path.
    ///
    /// # Returns
    ///
    /// * `Ok(PackageManager)` - If a package manager is detected
    /// * `Err(Error)` - If no package manager could be detected
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    /// use sublime_standard_tools::node::PackageManager;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let project_dir = Path::new(".");
    /// let package_manager = PackageManager::detect(project_dir)?;
    /// println!("Detected package manager: {:?}", package_manager.kind());
    /// # Ok(())
    /// # }
    /// ```
    pub fn detect(path: impl AsRef<Path>) -> Result<Self> {
        let default_config = crate::config::PackageManagerConfig::default();
        Self::detect_with_config(path, &default_config)
    }

    /// Detects which package manager is being used in the specified path using custom configuration.
    ///
    /// Uses the detection order and settings specified in the configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - The directory path to check for package manager lock files
    /// * `config` - The package manager configuration specifying detection order and settings
    ///
    /// # Errors
    ///
    /// Returns a [`MonorepoError::ManagerNotFound`] if no package manager
    /// lock files are found in the specified path.
    ///
    /// # Returns
    ///
    /// * `Ok(PackageManager)` - If a package manager is detected
    /// * `Err(Error)` - If no package manager could be detected
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    /// use sublime_standard_tools::config::PackageManagerConfig;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let project_dir = Path::new(".");
    /// let config = PackageManagerConfig {
    ///     detection_order: vec![PackageManagerKind::Npm, PackageManagerKind::Yarn],
    ///     ..PackageManagerConfig::default()
    /// };
    /// let package_manager = PackageManager::detect_with_config(project_dir, &config)?;
    /// println!("Detected package manager: {:?}", package_manager.kind());
    /// # Ok(())
    /// # }
    /// ```
    pub fn detect_with_config(
        path: impl AsRef<Path>,
        config: &crate::config::PackageManagerConfig,
    ) -> Result<Self> {
        let path = path.as_ref();

        // Check for environment variable preference if configured
        if config.detect_from_env
            && let Ok(env_manager) = std::env::var(&config.env_var_name)
        {
            let kind = match env_manager.to_lowercase().as_str() {
                "npm" => Some(PackageManagerKind::Npm),
                "yarn" => Some(PackageManagerKind::Yarn),
                "pnpm" => Some(PackageManagerKind::Pnpm),
                "bun" => Some(PackageManagerKind::Bun),
                "jsr" => Some(PackageManagerKind::Jsr),
                _ => None,
            };

            if let Some(kind) = kind {
                // Verify the preferred manager actually has a lock file
                let lock_file = if let Some(custom_lock) = config.custom_lock_files.get(&kind) {
                    custom_lock.as_str()
                } else {
                    kind.lock_file()
                };

                if path.join(lock_file).exists() {
                    return Ok(Self::new(kind, path));
                }
            }
        }

        // Check lock files in configured order
        for &kind in &config.detection_order {
            let lock_file = if let Some(custom_lock) = config.custom_lock_files.get(&kind) {
                custom_lock.as_str()
            } else {
                kind.lock_file()
            };

            // Handle npm's special case with npm-shrinkwrap.json
            if kind == PackageManagerKind::Npm {
                if path.join(lock_file).exists() || path.join("npm-shrinkwrap.json").exists() {
                    return Ok(Self::new(kind, path));
                }
            } else if path.join(lock_file).exists() {
                return Ok(Self::new(kind, path));
            }
        }

        // Try fallback if configured
        if let Some(fallback_kind) = config.fallback {
            let fallback_lock =
                if let Some(custom_lock) = config.custom_lock_files.get(&fallback_kind) {
                    custom_lock.as_str()
                } else {
                    fallback_kind.lock_file()
                };

            if path.join(fallback_lock).exists() {
                return Ok(Self::new(fallback_kind, path));
            }
        }

        Err(Error::Monorepo(MonorepoError::ManagerNotFound))
    }

    /// Returns the package manager kind.
    ///
    /// # Returns
    ///
    /// The `PackageManagerKind` representing the type of package manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let manager = PackageManager::new(PackageManagerKind::Pnpm, "/project");
    /// assert_eq!(manager.kind(), PackageManagerKind::Pnpm);
    /// ```
    #[must_use]
    pub fn kind(&self) -> PackageManagerKind {
        self.kind
    }

    /// Returns the root directory path.
    ///
    /// # Returns
    ///
    /// A reference to the Path representing the root directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::Path;
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let manager = PackageManager::new(PackageManagerKind::Bun, "/project/root");
    /// assert_eq!(manager.root(), Path::new("/project/root"));
    /// ```
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Returns the command name for this package manager.
    ///
    /// This is a convenience method that delegates to the kind's command method.
    ///
    /// # Returns
    ///
    /// The command string for the package manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let manager = PackageManager::new(PackageManagerKind::Yarn, "/project");
    /// assert_eq!(manager.command(), "yarn");
    /// ```
    #[must_use]
    pub fn command(&self) -> &'static str {
        self.kind.command()
    }

    /// Returns the lock file name for this package manager.
    ///
    /// This is a convenience method that delegates to the kind's lock_file method.
    ///
    /// # Returns
    ///
    /// The lock file name for the package manager.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let manager = PackageManager::new(PackageManagerKind::Pnpm, "/project");
    /// assert_eq!(manager.lock_file(), "pnpm-lock.yaml");
    /// ```
    #[must_use]
    pub fn lock_file(&self) -> &'static str {
        self.kind.lock_file()
    }

    /// Returns the full path to the lock file.
    ///
    /// This combines the root directory with the lock file name to provide
    /// the complete path where the lock file should be located. For npm,
    /// this handles the special case where both package-lock.json and
    /// npm-shrinkwrap.json might exist.
    ///
    /// # Returns
    ///
    /// A PathBuf representing the full path to the lock file.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let manager = PackageManager::new(PackageManagerKind::Npm, "/project");
    /// let expected = PathBuf::from("/project/package-lock.json");
    /// assert_eq!(manager.lock_file_path(), expected);
    /// ```
    #[must_use]
    pub fn lock_file_path(&self) -> PathBuf {
        // Handle npm's alternative lock file if necessary, though detect prioritizes package-lock.json
        let lock_file = if self.kind == PackageManagerKind::Npm
            && !self.root.join(PackageManagerKind::Npm.lock_file()).exists()
            && self.root.join("npm-shrinkwrap.json").exists()
        {
            "npm-shrinkwrap.json"
        } else {
            self.kind.lock_file()
        };
        self.root.join(lock_file)
    }

    /// Checks if this package manager supports workspaces.
    ///
    /// This is a convenience method that delegates to the kind's supports_workspaces method.
    ///
    /// # Returns
    ///
    /// `true` if the package manager supports workspaces, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let npm_manager = PackageManager::new(PackageManagerKind::Npm, "/project");
    /// assert!(npm_manager.supports_workspaces());
    ///
    /// let jsr_manager = PackageManager::new(PackageManagerKind::Jsr, "/project");
    /// assert!(!jsr_manager.supports_workspaces());
    /// ```
    #[must_use]
    pub fn supports_workspaces(&self) -> bool {
        self.kind.supports_workspaces()
    }

    /// Returns the workspace configuration file path if applicable.
    ///
    /// For package managers that use a separate workspace configuration file
    /// (like pnpm with pnpm-workspace.yaml), this returns the full path to
    /// that file. For package managers that use package.json for workspace
    /// configuration, this returns None.
    ///
    /// # Returns
    ///
    /// * `Some(PathBuf)` - If the package manager uses a separate workspace config file
    /// * `None` - If the package manager uses package.json or doesn't support workspaces
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::PathBuf;
    /// use sublime_standard_tools::node::{PackageManager, PackageManagerKind};
    ///
    /// let npm_manager = PackageManager::new(PackageManagerKind::Npm, "/project");
    /// assert_eq!(npm_manager.workspace_config_path(), None);
    ///
    /// let pnpm_manager = PackageManager::new(PackageManagerKind::Pnpm, "/project");
    /// let expected = Some(PathBuf::from("/project/pnpm-workspace.yaml"));
    /// assert_eq!(pnpm_manager.workspace_config_path(), expected);
    /// ```
    #[must_use]
    pub fn workspace_config_path(&self) -> Option<PathBuf> {
        self.kind.workspace_config_file().map(|file| self.root.join(file))
    }
}