Skip to content

feat: add deno x (alias dx) for conveniently running binaries from packages - #31138

Merged
nathanwhit merged 28 commits into
denoland:mainfrom
nathanwhit:deno-x
Dec 9, 2025
Merged

nathanwhit merged 28 commits into
denoland:mainfrom
nathanwhit:deno-x

Conversation

@nathanwhit

@nathanwhit nathanwhit commented Oct 29, 2025 •

Copy link
Copy Markdown
Member

an equivalent to npx, for conveniently running binaries from packages

available as deno x, and you can install an alias via deno x --install-alias (defaults to dx but can be specified)

Used like deno x rolldown, or dx rolldown with the alias

  • defaults to allow-all, unless another permission flag is passed
  • prompts when you first run a package
  • runs lifecycle scripts if you accept the prompt
  • defaults to npm: unless otherwise specified
  • errors if you try to use it to run a file

@coderabbitai

coderabbitai Bot commented Nov 20, 2025 •

Copy link
Copy Markdown

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a top-level x subcommand with parsing types (DenoXShimName, XFlagsKind, XCommandFlags, XFlags), parsers, and wiring into clap and DenoSubcommand::X. Adds cli/tools/x with a public async run entrypoint implementing install-alias, listing, autoinstall, and execution paths. Changes node_resolver to introduce and re-export BinValue (JsFile | Executable) and update resolver APIs and trait bounds; implements BaseFsOpen delegation in cache. Canonicalizes current executable paths in the task runner, makes set_npm_user_agent public, and adds tests and npm/jsr fixtures for x.

Sequence Diagram(s)

sequenceDiagram
    rect rgb(245,250,255)
    participant User as User CLI
    participant ArgParse as Arg Parser (clap)
    participant Dispatcher as Main Dispatch
    participant XTool as cli/tools/x
    participant Resolver as node_resolver
    participant Runtime as Deno / OS
    end

    User->>ArgParse: invoke "x ..." (or via dx/denox)
    alt dx/denox alias
        ArgParse->>ArgParse: inject "x" subcommand
    end
    ArgParse->>Dispatcher: produce DenoSubcommand::X(XFlags)
    Dispatcher->>XTool: run(flags, x_flags, runtime, roots)

    alt InstallAlias
        XTool->>XTool: generate shim (install-alias) -> exit
    else Print
        XTool->>Resolver: list local bins
        Resolver-->>XTool: BTreeMap<String, BinValue>
        XTool->>User: print available commands -> exit
    else Command
        XTool->>Resolver: resolve bin for input
        alt not found
            XTool->>XTool: autoinstall to temp pkg -> update resolver
            XTool->>Resolver: re-resolve
        end
        Resolver-->>XTool: BinValue (JsFile | Executable)
        alt JsFile
            XTool->>Runtime: spawn Deno to run module
        else Executable
            XTool->>Runtime: spawn executable process
        end
        Runtime-->>User: propagate exit code
    end
Loading

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add deno x (alias dx) for conveniently running binaries from packages' clearly and concisely describes the main feature being added—a new deno x command with an optional dx alias for running package binaries.
Description check ✅ Passed The description accurately explains the feature, its usage patterns, default behaviors (npm: namespace, allow-all permissions), and key behaviors like prompting and lifecycle scripts, all of which align with the changeset.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bbcbc57 and c1e1625.

📒 Files selected for processing (1)
  • tests/specs/x/native_bin_with_postinstall/__test__.jsonc (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/specs/x/native_bin_with_postinstall/test.jsonc
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test release linux-x86_64
  • GitHub Check: lint debug linux-x86_64
  • GitHub Check: build libs
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: lint debug windows-x86_64

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nathanwhit
nathanwhit marked this pull request as ready for review November 20, 2025 01:12
Copilot AI review requested due to automatic review settings November 20, 2025 01:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR introduces the deno x command (with aliases dx and denox) as an npx-like tool for executing binaries from npm and JSR packages. The feature allows running package binaries without installing them globally, with automatic package installation and caching.

Key changes:

  • Added deno x subcommand with support for running npm and JSR package binaries
  • Implemented automatic package installation with user confirmation
  • Enhanced BinValue enum to distinguish between JavaScript files and native executables
  • Added shim installation for dx and denox aliases with configurable default permissions

Reviewed Changes

Copilot reviewed 29 out of 30 changed files in this pull request and generated 10 comments.

Show a summary per file
File Description
cli/tools/x.rs Core implementation of the deno x command including binary resolution, package installation, and execution logic
cli/args/flags.rs Added command-line argument parsing for the x subcommand and automatic alias detection for dx/denox executables
cli/main.rs Integrated the x subcommand into the main CLI dispatcher
cli/tools/mod.rs Exported the new x module
cli/tools/run/mod.rs Exposed set_npm_user_agent function for use by the x command
cli/task_runner.rs Updated to use BinValue type and canonicalize current executable paths
cli/lib/worker.rs Updated binary resolution to handle BinValue enum
cli/tools/bundle/mod.rs Updated to pattern match on BinValue::JsFile variant
libs/node_resolver/lib.rs Exported BinValue type for public use
libs/node_resolver/resolution.rs Implemented BinValue enum to differentiate JS files from native executables, enhanced binary detection to identify npx shims
libs/node_resolver/cache.rs Added FsOpen trait implementation for cached file system operations
tests/specs/x/* Added integration tests for various deno x scenarios including npm/JSR packages, local bins, and ambiguous binaries
tests/registry/npm/@denotest/deno/1.0.0/* Added test package with postinstall scripts for native binary testing
tests/registry/jsr/@denotest/bin/meta.json Added JSR test package metadata

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread cli/task_runner.rs Resolved
Comment thread cli/tools/x.rs Resolved
Comment thread cli/tools/x.rs Resolved
Comment thread cli/tools/x.rs Resolved
Comment thread cli/args/flags.rs Resolved
Comment thread cli/args/flags.rs Resolved
Comment thread cli/tools/x.rs Resolved
Comment thread cli/tools/x.rs Resolved
Comment thread libs/node_resolver/resolution.rs Resolved
Comment thread cli/task_runner.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
cli/tools/x.rs (2)

105-119: Refactor: Eliminate duplicate command name normalization.

The command name normalization logic (stripping "@scope/" prefix) is duplicated on lines 105-109 and 113-117. Extract this into a helper function or consolidate the logic.

Apply this diff:

+  let normalized_command = if command.starts_with("@") && command.contains("/") {
+    command.rsplit('/').next().unwrap()
+  } else {
+    command
+  };
+
   let bins = resolve_local_bins(node_resolver, npm_resolver)?;
-  let command = if command.starts_with("@") && command.contains("/") {
-    command.split("/").last().unwrap()
-  } else {
-    command
-  };
-  let bin_value = if let Some(bin_value) = bins.get(command) {
+  let bin_value = if let Some(bin_value) = bins.get(normalized_command) {
     bin_value
-  } else if let Some(bin_value) = {
-    let command = if command.starts_with("@") && command.contains("/") {
-      command.split("/").last().unwrap()
-    } else {
-      command
-    };
-    bins.get(command)
-  } {
-    bin_value
   } else {
     return Ok(None);
   };

Note: Using rsplit('/') instead of split('/') is more efficient for getting the last segment.


303-307: Consider: Document file-like detection heuristic.

The file-like detection logic (lines 303-307) uses a heuristic based on path characters and extensions. Consider adding a comment explaining this heuristic, as it's a critical decision point that affects whether the input is treated as a file path or a package specifier.

+  // Detect if the command looks like a file path (starts with ./ ~/ / or has an extension)
+  // rather than a package specifier. This helps disambiguate `dx main.ts` from `dx main`.
   let is_file_like = command_flags.command.starts_with('.')
     || command_flags.command.starts_with('/')
     || command_flags.command.starts_with('~')
     || command_flags.command.starts_with('\\')
     || Path::new(&command_flags.command).extension().is_some();
libs/node_resolver/resolution.rs (1)

2605-2613: Test helper doesn't reflect actual detection logic.

The resolve_bins helper unconditionally wraps all bins as BinValue::JsFile, but the actual runtime code at lines 803-820 reads files to distinguish between JS files and executables. This means tests won't catch bugs in the BinValue::Executable path or the shim detection logic. Consider:

  • Either mock files in tests so the actual detection logic runs
  • Or add separate tests that specifically exercise the detection logic
cli/args/flags.rs (1)

1573-1585: Tighten dx/denox alias detection to avoid surprises and improve Windows support

The current check:

if !args.is_empty() && args[0].as_encoded_bytes().ends_with(b"dx")
  || args[0].as_encoded_bytes().ends_with(b"denox")

will:

  • Treat any binary whose full path ends with "dx" or "denox" as the dx/denox shim (e.g. mydx, /usr/local/bin/mydx), and
  • Not match typical Windows names like dx.exe / denox.exe.

That’s both a potential false positive (accidentally rewriting argv for unrelated binaries ending in dx) and a false negative on common platforms.

You can make this more precise and cross‑platform by matching on the file stem instead:

-  let args = if !args.is_empty() && args[0].as_encoded_bytes().ends_with(b"dx")
-    || args[0].as_encoded_bytes().ends_with(b"denox")
-  {
-    let mut new_args = Vec::with_capacity(args.len() + 1);
-    new_args.push(args[0].clone());
-    new_args.push(OsString::from("x"));
-    if args.len() >= 2 {
-      new_args.extend(args.into_iter().skip(1));
-    }
-    new_args
-  } else {
-    args
-  };
+  let args = if !args.is_empty() {
+    let binary_stem = std::path::Path::new(&args[0])
+      .file_stem()
+      .and_then(|s| s.to_str());
+
+    if matches!(binary_stem, Some("dx" | "denox")) {
+      let mut new_args = Vec::with_capacity(args.len() + 1);
+      new_args.push(args[0].clone());
+      new_args.push(OsString::from("x"));
+      if args.len() >= 2 {
+        new_args.extend(args.into_iter().skip(1));
+      }
+      new_args
+    } else {
+      args
+    }
+  } else {
+    args
+  };

This confines the behavior to actual dx/denox binaries (regardless of extension) and avoids interfering with unrelated commands.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5421a29 and 49b5d03.

⛔ Files ignored due to path filters (8)
  • tests/specs/x/ambiguous/ambiguous.out is excluded by !**/*.out
  • tests/specs/x/native_bin_with_postinstall/x.out is excluded by !**/*.out
  • tests/specs/x/print_available/print.out is excluded by !**/*.out
  • tests/specs/x/print_no_local/print.out is excluded by !**/*.out
  • tests/specs/x/run_jsr_package/run.out is excluded by !**/*.out
  • tests/specs/x/run_local_bin/run_local.out is excluded by !**/*.out
  • tests/specs/x/run_npm_package/run.out is excluded by !**/*.out
  • tests/specs/x/run_npm_prefixless/run.out is excluded by !**/*.out
📒 Files selected for processing (22)
  • cli/args/flags.rs (7 hunks)
  • cli/lib/worker.rs (1 hunks)
  • cli/main.rs (1 hunks)
  • cli/task_runner.rs (6 hunks)
  • cli/tools/bundle/mod.rs (1 hunks)
  • cli/tools/mod.rs (1 hunks)
  • cli/tools/run/mod.rs (1 hunks)
  • cli/tools/x.rs (1 hunks)
  • libs/node_resolver/cache.rs (2 hunks)
  • libs/node_resolver/lib.rs (1 hunks)
  • libs/node_resolver/resolution.rs (21 hunks)
  • tests/registry/jsr/@denotest/bin/meta.json (1 hunks)
  • tests/registry/npm/@denotest/deno/1.0.0/package.json (1 hunks)
  • tests/registry/npm/@denotest/deno/1.0.0/setup.js (1 hunks)
  • tests/specs/x/ambiguous/__test__.jsonc (1 hunks)
  • tests/specs/x/native_bin_with_postinstall/__test__.jsonc (1 hunks)
  • tests/specs/x/print_available/__test__.jsonc (1 hunks)
  • tests/specs/x/print_no_local/__test__.jsonc (1 hunks)
  • tests/specs/x/run_jsr_package/__test__.jsonc (1 hunks)
  • tests/specs/x/run_local_bin/__test__.jsonc (1 hunks)
  • tests/specs/x/run_npm_package/__test__.jsonc (1 hunks)
  • tests/specs/x/run_npm_prefixless/__test__.jsonc (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
libs/node_resolver/cache.rs (1)
cli/tsc/dts/lib.deno.ns.d.ts (1)
  • OpenOptions (2507-2553)
cli/tools/bundle/mod.rs (4)
cli/lsp/resolver.rs (1)
  • node_resolver (1178-1204)
libs/resolver/factory.rs (1)
  • node_resolver (993-1014)
cli/factory.rs (1)
  • node_resolver (739-742)
cli/lib/worker.rs (1)
  • main_module (822-824)
cli/main.rs (1)
cli/tools/x.rs (1)
  • run (253-410)
cli/tools/x.rs (6)
runtime/permissions/lib.rs (9)
  • std (4135-4135)
  • new (620-622)
  • new (645-653)
  • new (1250-1281)
  • new (1433-1438)
  • new (2163-2169)
  • new (2204-2206)
  • new (3699-3707)
  • from (402-408)
libs/node_resolver/resolution.rs (5)
  • path (2583-2588)
  • new (102-139)
  • new (320-363)
  • bins (2287-2298)
  • map (2531-2573)
cli/args/flags.rs (30)
  • args (5898-5898)
  • args (6420-6420)
  • name (416-422)
  • matches (1625-1625)
  • matches (1634-1634)
  • matches (5190-5190)
  • matches (5331-5331)
  • matches (5370-5371)
  • matches (5407-5407)
  • matches (5427-5427)
  • matches (5436-5436)
  • matches (5476-5476)
  • matches (5483-5483)
  • matches (5488-5488)
  • matches (5491-5491)
  • matches (5514-5514)
  • matches (5515-5515)
  • matches (5516-5516)
  • matches (5525-5526)
  • f (5477-5479)
  • f (5527-5527)
  • f (5613-5613)
  • f (5617-5617)
  • f (5701-5703)
  • f (5854-5856)
  • f (6159-6161)
  • f (6445-6447)
  • f (7070-7071)
  • f (7094-7095)
  • f (7115-7116)
cli/args/mod.rs (1)
  • preload_modules (640-651)
cli/tools/run/mod.rs (2)
  • set_npm_user_agent (45-56)
  • maybe_npm_install (266-289)
cli/tools/pm/cache_deps.rs (1)
  • cache_top_level_deps (26-222)
libs/node_resolver/resolution.rs (2)
cli/task_runner.rs (1)
  • resolve_npm_commands_from_bin_dir (461-478)
libs/package_json/lib.rs (2)
  • resolve_bins (547-580)
  • dir_path (508-510)
cli/args/flags.rs (1)
runtime/permissions/lib.rs (9)
  • default (819-825)
  • default (890-898)
  • new (620-622)
  • new (645-653)
  • new (1250-1281)
  • new (1433-1438)
  • new (2163-2169)
  • new (2204-2206)
  • new (3699-3707)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: CodeQL analysis (javascript-typescript)
  • GitHub Check: Agent
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test release linux-x86_64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test release macos-x86_64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: lint debug linux-x86_64
  • GitHub Check: build libs
  • GitHub Check: lint debug windows-x86_64
🔇 Additional comments (25)
tests/specs/x/ambiguous/__test__.jsonc (1)

1-6: No issues found—test is correctly structured.

The output file exists and contains the expected error message for the ambiguous binary scenario. The -y flag doesn't prevent the error because binary resolution failure occurs before any prompts would be presented. The test correctly expects exit code 1 and documents the three conflicting binaries in the package.

tests/specs/x/print_no_local/__test__.jsonc (1)

1-5: No issues found. Test spec is properly configured.

The print.out file exists and contains the expected output "No local commands found", which correctly aligns with the test scenario where deno x runs in a temporary directory with no local binaries. The test specification is valid and complete.

cli/task_runner.rs (1)

248-250: LGTM! Canonical paths improve reliability.

The canonicalization of executable paths ensures absolute, symlink-resolved paths across all command implementations. The adaptation to BinValue (via .path().to_path_buf()) in the bin resolution functions is correct. These changes make path handling more robust.

Also applies to: 279-281, 330-335, 430-432, 471-474, 492-494

tests/specs/x/native_bin_with_postinstall/__test__.jsonc (1)

1-5: Test specification is valid and properly configured.

All supporting test infrastructure verified:

  • ✓ @denotest/deno mock package exists with postinstall script at ./tests/registry/npm/@denotest/deno/1.0.0/
  • ✓ Expected output file (x.out) contains correct postinstall execution output
  • ✓ Autoinstall implementation (autoinstall_package in x.rs) supports the -y flag
  • ✓ Test spec structure is correct and references match actual artifacts

The test file is complete and functional—no changes needed.

tests/registry/jsr/@denotest/bin/meta.json (1)

1-7: LGTM!

Test metadata file is well-formed and appropriate for the test registry.

cli/lib/worker.rs (1)

742-742: LGTM!

Correctly adapts to the new BinValue API by calling .path() to extract the PathBuf.

cli/tools/mod.rs (1)

25-25: LGTM!

Module declaration follows the existing pattern and properly exposes the new x subcommand functionality.

libs/node_resolver/lib.rs (1)

30-30: LGTM!

Properly exposes BinValue from the resolution module, extending the public API as needed for the x subcommand functionality.

tests/specs/x/run_local_bin/__test__.jsonc (1)

1-13: LGTM!

Test specification correctly exercises local bin execution after installation.

tests/specs/x/run_npm_prefixless/__test__.jsonc (1)

1-5: LGTM!

Test correctly validates the default npm: registry behavior when no explicit prefix is provided.

tests/specs/x/run_npm_package/__test__.jsonc (1)

1-5: LGTM!

Test specification appropriately covers explicit npm: registry prefix usage.

tests/specs/x/run_jsr_package/__test__.jsonc (1)

1-5: LGTM!

Test specification properly validates JSR registry support for the x subcommand.

cli/tools/run/mod.rs (1)

45-45: LGTM: Visibility change supports new x subcommand.

Making set_npm_user_agent() public allows the new x tool to properly set npm user agent when executing npm packages.

cli/tools/bundle/mod.rs (1)

1727-1732: LGTM: Correctly filters for JS entrypoints only.

The change appropriately narrows bin resolution to accept only BinValue::JsFile, filtering out native executables which cannot be bundled. This aligns with the bundler's requirement to process JavaScript entrypoints.

cli/main.rs (1)

249-251: LGTM: X subcommand properly integrated.

The new DenoSubcommand::X variant is correctly wired to tools::x::run, following the established pattern for other subcommands.

libs/node_resolver/cache.rs (1)

202-212: LGTM: BaseFsOpen implementation follows established pattern.

The implementation correctly delegates to the underlying sys layer, consistent with other trait implementations in this file.

cli/tools/x.rs (1)

238-244: Verify Windows shim consistency with Unix behavior.

The Windows .cmd shim (line 242) runs ./deno.exe x %* without the --default-allow-all flag, while the custom Unix shim on line 218 includes it. Verify whether this difference is intentional or if both should use the same flag pattern.

If they should match, apply this diff:

     let out_path = out_dir.join(format!("{}.cmd", shim_name.name()));
     std::fs::write(
       out_path,
       r##"@echo off
-./deno.exe x %*
+./deno.exe x --default-allow-all %*
 exit /b %ERRORLEVEL%
 "##
         .to_string()
tests/registry/npm/@denotest/deno/1.0.0/setup.js (1)

1-23: Verify test environment Node.js version support.

The review comment correctly identifies that import.meta.dirname requires Node.js 20.11.0 or newer. However, whether this is an issue depends on your test environment's configuration. You need to confirm that your test runner and CI environment are configured to use Node.js 20.11.0 or later, or switch to the alternative approach mentioned if broader compatibility is required.

libs/node_resolver/resolution.rs (4)

6-7: LGTM!

The new imports support reading bin file contents to detect npx shims.

Also applies to: 27-27, 30-30


272-272: LGTM!

Adding FsOpen to the trait bounds is necessary for the bin detection logic.


2576-2589: LGTM!

The BinValue enum cleanly distinguishes JS files from executables with a convenient path() accessor.


760-760: LGTM!

Method signatures properly updated to return BinValue instead of PathBuf. The relevant code snippet shows consumers correctly use .path() to extract the underlying path when needed.

Also applies to: 769-769, 775-775, 785-785, 827-827, 836-839, 853-853, 2248-2250

cli/args/flags.rs (3)

407-442: X flag data structures look consistent

The DenoXShimName, XFlagsKind, XCommandFlags, and XFlags types are minimal, coherent, and match existing patterns in this module. No changes needed here.


610-611: X subcommand wiring is consistent with existing CLI patterns

The addition of DenoSubcommand::X(XFlags), its dispatch in the subcommand match, registration via x_subcommand() in clap_root, and the deno_x_shim_name_parser/x_subcommand definitions all match how other subcommands are modeled in this file. The use of runtime_args(..) for x keeps behavior aligned with run/test/bench.

Also applies to: 1767-1768, 2029-2031, 3476-3514


6610-6637: The review comment is factually incorrect about the scope of the allow_all logic.

The allow_all assignment on line 6633 is not unconditional—it sits inside an if statement:

if !flags.permissions.has_permission() && flags.permission_set.is_none() {
  flags.permissions.allow_all = true;
}

This block only executes when:

  1. The user hasn't specified any permission flags (!flags.permissions.has_permission())
  2. AND no permission set is configured (flags.permission_set.is_none())

The review comment incorrectly claims the logic is "unconditional" and "applies to all paths," suggesting it forces allow_all regardless of user input. In reality, it's a conditional fallback that only triggers when the user provides no explicit permission configuration.

If the design concern is whether deno x should default to allow_all when no permissions are explicitly set (as opposed to defaulting to sandbox like deno run), that's a valid design question—but it requires clarifying with the maintainers whether this default was intentional or if it conflicts with the stated security model. The current code does exactly what the conditional logic indicates: sandbox by default only if the user specifies permission flags; otherwise, allow_all.

Likely an incorrect or invalid review comment.

Comment thread cli/tools/x.rs Resolved
Comment thread libs/node_resolver/resolution.rs Resolved
Comment thread libs/node_resolver/resolution.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
cli/tools/x.rs (3)

106-121: Simplify duplicate command extraction logic.

The logic for extracting the command from a scoped package is duplicated. This can be refactored to extract once and use consistently.

Apply this diff:

-  let bins = resolve_local_bins(node_resolver, npm_resolver)?;
-  let command = if command.starts_with("@") && command.contains("/") {
-    command.split("/").last().unwrap()
-  } else {
-    command
-  };
-  let bin_value = if let Some(bin_value) = bins.get(command) {
+  let bins = resolve_local_bins(node_resolver, npm_resolver)?;
+  let normalized_command = if command.starts_with("@") && command.contains("/") {
+    command.split("/").last().unwrap()
+  } else {
+    command
+  };
+  let bin_value = if let Some(bin_value) = bins.get(normalized_command) {
     bin_value
-  } else if let Some(bin_value) = {
-    let command = if command.starts_with("@") && command.contains("/") {
-      command.split("/").last().unwrap()
-    } else {
-      command
-    };
-    bins.get(command)
-  } {
-    bin_value
   } else {
     return Ok(None);
   };

242-254: Windows shim should handle DenoXShimName::Other case.

The Windows shim always writes the same batch file regardless of the shim name variant. When DenoXShimName::Other is used (which includes --default-allow-all on Unix), the Windows batch file should also include that flag for consistency.

Apply this diff:

   #[cfg(windows)]
   {
     let out_path = out_dir.join(format!("{}.cmd", shim_name.name()));
-    std::fs::write(
-      out_path,
-      r##"@echo off
+    if let DenoXShimName::Other(_) = shim_name {
+      std::fs::write(
+        out_path,
+        r##"@echo off
+./deno.exe x --default-allow-all %*
+exit /b %ERRORLEVEL%
+"##
+          .as_bytes(),
+      )?;
+    } else {
+      std::fs::write(
+        out_path,
+        r##"@echo off
 ./deno.exe x %*
 exit /b %ERRORLEVEL%
 "##
-        .to_string()
-        .as_bytes(),
-    )?;
+          .as_bytes(),
+      )?;
+    }
   }

267-268: Handle missing parent directory for executable path.

The .unwrap() will panic if the executable path has no parent directory (e.g., at filesystem root).

Apply this diff:

       let exe = std::env::current_exe()?;
-      let out_dir = exe.parent().unwrap();
+      let out_dir = exe.parent()
+        .ok_or_else(|| anyhow::anyhow!("Executable path has no parent directory"))?;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 49b5d03 and 28e9845.

📒 Files selected for processing (1)
  • cli/tools/x.rs (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
cli/tools/x.rs (4)
runtime/permissions/lib.rs (12)
  • new (620-622)
  • new (645-653)
  • new (1250-1281)
  • new (1433-1438)
  • new (2163-2169)
  • new (2204-2206)
  • new (3699-3707)
  • parse (2413-2435)
  • parse (2576-2609)
  • parse (2664-2672)
  • parse (2700-2734)
  • parse (2751-2765)
libs/node_resolver/resolution.rs (5)
  • path (2583-2588)
  • new (102-139)
  • new (320-363)
  • bins (2287-2298)
  • map (2531-2573)
cli/util/console.rs (1)
  • confirm (86-160)
cli/tools/run/mod.rs (1)
  • maybe_npm_install (266-289)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: test release macos-aarch64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test release linux-x86_64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: build libs
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: lint debug windows-x86_64
  • GitHub Check: lint debug linux-x86_64
🔇 Additional comments (2)
cli/tools/x.rs (2)

309-317: Remove file-error suggestion – file inputs are intentionally supported. Tests and implementation confirm that local paths and files are resolved to URLs and executed via run_js_file, matching existing behavior.

Likely an incorrect or invalid review comment.


354-357: No issues found – the mode switch is intentional and correct.

The code pattern is sound:

  • autoinstall_package() installs the package in a temporary directory with Auto mode (line 428)
  • After successful installation, the execution phase switches to Manual mode (lines 355-356)
  • Manual is the proper mode for running installed Node packages with package.json, preventing unnecessary node_modules recreation on each run

This is a deliberate design: Auto for the setup phase, Manual for the stable execution phase. No changes needed.

Comment thread cli/tools/x.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (4)
cli/tools/x.rs (4)

36-40: Handle missing root node_modules path gracefully.

The .unwrap() on line 38 will panic if the Byonm resolver returns None. Replace with proper error handling.

     deno_resolver::npm::NpmResolver::Byonm(npm_resolver) => {
-      let node_modules_dir = npm_resolver.root_node_modules_path().unwrap();
+      let node_modules_dir = npm_resolver.root_node_modules_path()
+        .ok_or_else(|| anyhow::anyhow!("Byonm resolver has no root node_modules path"))?;
       let bin_dir = node_modules_dir.join(".bin");

244-254: Windows shim missing --default-allow-all for custom shim names.

On Unix, DenoXShimName::Other(_) includes --default-allow-all in the shim script. The Windows batch file should match this behavior for consistency.

   #[cfg(windows)]
   {
     let out_path = out_dir.join(format!("{}.cmd", shim_name.name()));
-    std::fs::write(
-      out_path,
-      r##"@echo off
+    let content = if let DenoXShimName::Other(_) = shim_name {
+      r##"@echo off
+./deno.exe x --default-allow-all %*
+exit /b %ERRORLEVEL%
+"##
+    } else {
+      r##"@echo off
 ./deno.exe x %*
 exit /b %ERRORLEVEL%
-"##,
-    )?;
+"##
+    };
+    std::fs::write(out_path, content)?;
   }

266-270: Handle missing parent directory for executable path.

The .unwrap() on exe.parent() could panic if the executable path has no parent (e.g., at filesystem root). Use proper error handling.

     XFlagsKind::InstallAlias(shim_name) => {
       let exe = std::env::current_exe()?;
-      let out_dir = exe.parent().unwrap();
+      let out_dir = exe.parent()
+        .ok_or_else(|| anyhow::anyhow!("Executable path has no parent directory"))?;
       write_shim(out_dir, shim_name)?;

108-126: Remove dead code: duplicate scoped package extraction.

The command is already normalized on lines 108-111. The second extraction block (lines 116-120) is dead code since command can no longer start with @ and contain / after the first transformation.

   let bins = resolve_local_bins(node_resolver, npm_resolver)?;
   let command = if command.starts_with("@") && command.contains("/") {
     command.split("/").last().unwrap()
   } else {
     command
   };
-  let bin_value = if let Some(bin_value) = bins.get(command) {
-    bin_value
-  } else if let Some(bin_value) = {
-    let command = if command.starts_with("@") && command.contains("/") {
-      command.split("/").last().unwrap()
-    } else {
-      command
-    };
-    bins.get(command)
-  } {
-    bin_value
-  } else {
+  let bin_value = if let Some(bin_value) = bins.get(command) {
+    bin_value
+  } else {
     return Ok(None);
   };
🧹 Nitpick comments (1)
cli/tools/x.rs (1)

405-408: Redundant URL parsing for JSR reference.

Parsing jsr_package_req_reference.to_string() back to a URL seems wasteful. The reference should already contain the information needed. Consider if there's a more direct way to obtain the URL.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7d3fc22 and 4ad0a30.

📒 Files selected for processing (2)
  • cli/tools/x.rs (1 hunks)
  • tests/registry/npm/@denotest/deno/1.0.0/setup.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/registry/npm/@denotest/deno/1.0.0/setup.js
🧰 Additional context used
📓 Path-based instructions (2)
cli/tools/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

CLI tools should be implemented in cli/tools/<tool> or cli/tools/<tool>/mod.rs

Files:

  • cli/tools/x.rs
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: For debugging Rust code, set breakpoints in IDE debuggers (VS Code with rust-analyzer, IntelliJ IDEA) or use lldb directly
Use eprintln!() or dbg!() macros for debug prints in Rust code

Files:

  • cli/tools/x.rs
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/args/flags.rs : CLI flag parsing should be defined in `cli/args/flags.rs`
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/tools/**/*.rs : CLI tools should be implemented in `cli/tools/<tool>` or `cli/tools/<tool>/mod.rs`

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/module_loader.rs : Module loading and resolution is handled in `cli/module_loader.rs`

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/args/flags.rs : CLI flag parsing should be defined in `cli/args/flags.rs`

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/main.rs : Main CLI entry point is in `cli/main.rs` and should handle command routing

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to runtime/permissions.rs : Permission system is implemented in `runtime/permissions.rs`

Applied to files:

  • cli/tools/x.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test release linux-x86_64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: lint debug windows-x86_64
  • GitHub Check: lint debug linux-x86_64
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: build libs
🔇 Additional comments (1)
cli/tools/x.rs (1)

58-94: LGTM for helper functions and autoinstall logic.

The run_js_file, XTempDir, create_package_temp_dir, autoinstall_package, and ReqRef implementations are well-structured with appropriate error handling and clear separation of concerns.

Also applies to: 156-167, 169-208, 423-511, 513-540

Comment thread cli/tools/x.rs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (4)
cli/tools/x.rs (4)

38-38: Handle missing root node_modules path gracefully.

The .unwrap() will panic if the Byonm resolver returns None.

-      let node_modules_dir = npm_resolver.root_node_modules_path().unwrap();
+      let node_modules_dir = npm_resolver.root_node_modules_path()
+        .ok_or_else(|| anyhow::anyhow!("Byonm resolver has no root node_modules path"))?;

108-126: The else-if branch at lines 115-123 is unreachable/redundant.

The command is already normalized at lines 108-112, so the second normalization at lines 116-120 produces the exact same value. The bins.get(command) at line 121 will always return the same result as line 113.

   let command = if command.starts_with("@") && command.contains("/") {
     command.split("/").last().unwrap()
   } else {
     command
   };
-  let bin_value = if let Some(bin_value) = bins.get(command) {
-    bin_value
-  } else if let Some(bin_value) = {
-    let command = if command.starts_with("@") && command.contains("/") {
-      command.split("/").last().unwrap()
-    } else {
-      command
-    };
-    bins.get(command)
-  } {
-    bin_value
-  } else {
+  let bin_value = if let Some(bin_value) = bins.get(command) {
+    bin_value
+  } else {
     return Ok(None);
   };

244-254: Windows shim missing --default-allow-all for Other variant.

The Unix block correctly adds --default-allow-all for DenoXShimName::Other(_), but the Windows block doesn't. This creates inconsistent behavior across platforms.

   #[cfg(windows)]
   {
     let out_path = out_dir.join(format!("{}.cmd", shim_name.name()));
-    std::fs::write(
-      out_path,
-      r##"@echo off
+    let content = if let DenoXShimName::Other(_) = shim_name {
+      r##"@echo off
+./deno.exe x --default-allow-all %*
+exit /b %ERRORLEVEL%
+"##
+    } else {
+      r##"@echo off
 ./deno.exe x %*
 exit /b %ERRORLEVEL%
-"##,
-    )?;
+"##
+    };
+    std::fs::write(out_path, content)?;
   }

266-271: Handle missing parent directory gracefully.

The .unwrap() on exe.parent() at line 268 can panic if the executable path has no parent.

       let exe = std::env::current_exe()?;
-      let out_dir = exe.parent().unwrap();
+      let out_dir = exe.parent()
+        .ok_or_else(|| anyhow::anyhow!("Executable path has no parent directory"))?;
       write_shim(out_dir, shim_name)?;
🧹 Nitpick comments (1)
cli/tools/x.rs (1)

308-317: Consider clarifying the file detection heuristic.

The extension().is_some() check at line 312 will match npm packages with dots (e.g., easytimer.js). While these won't error (since is_file() returns false), the intent could be clearer by checking for known script extensions instead.

-  let is_file_like = command_flags.command.starts_with('.')
+  let has_path_prefix = command_flags.command.starts_with('.')
     || command_flags.command.starts_with('/')
     || command_flags.command.starts_with('~')
-    || command_flags.command.starts_with('\\')
-    || Path::new(&command_flags.command).extension().is_some();
-  if is_file_like && Path::new(&command_flags.command).is_file() {
+    || command_flags.command.starts_with('\\');
+  if has_path_prefix && Path::new(&command_flags.command).is_file() {

This removes the extension check since the path-prefix checks already catch relative/absolute file paths.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4ad0a30 and bc93ff2.

📒 Files selected for processing (1)
  • cli/tools/x.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
cli/tools/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

CLI tools should be implemented in cli/tools/<tool> or cli/tools/<tool>/mod.rs

Files:

  • cli/tools/x.rs
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: For debugging Rust code, set breakpoints in IDE debuggers (VS Code with rust-analyzer, IntelliJ IDEA) or use lldb directly
Use eprintln!() or dbg!() macros for debug prints in Rust code

Files:

  • cli/tools/x.rs
🧠 Learnings (5)
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/tools/**/*.rs : CLI tools should be implemented in `cli/tools/<tool>` or `cli/tools/<tool>/mod.rs`

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/module_loader.rs : Module loading and resolution is handled in `cli/module_loader.rs`

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/args/flags.rs : CLI flag parsing should be defined in `cli/args/flags.rs`

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to cli/main.rs : Main CLI entry point is in `cli/main.rs` and should handle command routing

Applied to files:

  • cli/tools/x.rs
📚 Learning: 2025-11-24T16:19:37.798Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.798Z
Learning: Applies to runtime/permissions.rs : Permission system is implemented in `runtime/permissions.rs`

Applied to files:

  • cli/tools/x.rs
🧬 Code graph analysis (1)
cli/tools/x.rs (1)
libs/node_resolver/resolution.rs (1)
  • path (2583-2588)
🔇 Additional comments (5)
cli/tools/x.rs (5)

1-31: LGTM on imports and module setup.

The Unix-specific import has been correctly moved inside the #[cfg(unix)] block (line 216), addressing the previous cross-platform compilation issue.


58-94: LGTM!

Proper error propagation and telemetry integration for failure reporting.


156-208: LGTM!

Cache directory management with proper invalidation on reload and lockfile absence.


433-433: Security note: All package scripts are enabled by default.

PackagesAllowedScripts::All allows arbitrary install/build scripts to run. This aligns with the PR's design discussion but is worth confirming as intended behavior.


507-540: LGTM!

Clean helper types for abstracting over npm/jsr references.

@bartlomieju

Copy link
Copy Markdown
Member

Please update the PR description to reflect the latest state of changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
libs/node_resolver/resolution.rs (2)

804-844: Bin entries are silently skipped when file opening fails.

Line 808 uses .ok()? which silently filters out bin entries when fs_open fails. This hides bins that might have temporary permission issues or other transient errors. Consider either:

  1. Add debug logging when skipping (similar to the logging on line 813 for read failures), or
  2. Return BinValue::Executable(path) as a defensive fallback when file operations fail

Based on past review comments, this issue was previously flagged but remains unaddressed.


891-906: Bin entries are silently skipped when file opening fails.

Line 891 uses .ok()? which silently filters out bin entries when fs_open fails. The debug logging at lines 899-903 only captures successful resolutions, not skipped entries. Consider adding debug logging when a bin is skipped due to file open errors, or return BinValue::Executable(path) as a defensive fallback.

Based on past review comments, this issue was previously flagged but remains unaddressed.

🧹 Nitpick comments (2)
cli/args/flags.rs (2)

3520-3550: X subcommand wiring and permission default behavior

x_subcommand() reuses runtime_args(.., include_perms=true, include_inspector=true, include_allow_scripts=true) and script_arg().trailing_var_arg(true), and x_parse() only falls back to allow_all when neither CLI permission flags nor a permission-set were provided, so explicit permission config can’t be silently overridden. That matches the PR’s “default allow‑all unless flags are passed” intent and keeps behavior aligned with other subcommands’ permission parsing. The only gap I see is test coverage: given how extensively other subcommands are exercised in this file, it would be good to add a couple of focused tests for deno x <cmd> / deno x --install-alias flag parsing and the allow_all fallback.

Also applies to: 613-613, 6746-6773


2047-2048: Expose x in top‑level help text

You register x_subcommand() with clap, but DENO_HELP’s static help template still doesn’t list x under “Commands”, so deno --help users won’t easily discover it. Consider adding an x entry (probably under “Execution” or “Dependency management”) to keep the custom help output aligned with the actual subcommand set.

Also applies to: 1527-1579

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 64b39cf and 4a8ee92.

📒 Files selected for processing (2)
  • cli/args/flags.rs (7 hunks)
  • libs/node_resolver/resolution.rs (21 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: For debugging Rust code, set breakpoints in IDE debuggers (VS Code with rust-analyzer, IntelliJ IDEA) or use lldb directly
Use eprintln!() or dbg!() macros for debug prints in Rust code

Files:

  • libs/node_resolver/resolution.rs
  • cli/args/flags.rs
cli/args/flags.rs

📄 CodeRabbit inference engine (CLAUDE.md)

CLI flag parsing should be defined in cli/args/flags.rs

Files:

  • cli/args/flags.rs
🧠 Learnings (2)
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/args/flags.rs : CLI flag parsing should be defined in `cli/args/flags.rs`

Applied to files:

  • cli/args/flags.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/main.rs : Main CLI entry point is in `cli/main.rs` and should handle command routing

Applied to files:

  • cli/args/flags.rs
🧬 Code graph analysis (1)
libs/node_resolver/resolution.rs (1)
libs/package_json/lib.rs (2)
  • resolve_bins (547-580)
  • dir_path (508-510)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: build libs
  • GitHub Check: lint debug windows-x86_64
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: lint debug linux-x86_64
🔇 Additional comments (2)
cli/args/flags.rs (2)

410-445: X shim types and parser look consistent and future‑proof

The DenoXShimName/XFlags* modeling plus deno_x_shim_name_parser cleanly separate “dx/denox” from arbitrary aliases and integrate with clap’s typed value parsing without surprises. I don’t see any correctness or ergonomics issues here.

Also applies to: 3512-3518


1590-1603: dx/denox argv normalization is now safe and minimal

The reordered condition with parentheses avoids the earlier precedence bug and ensures we only inspect args[0] when non‑empty, then inject a single "x" in the right position. Behavior for normal deno … and other shims is preserved.

Comment thread cli/tools/x.rs
Comment on lines +308 to +313
let is_file_like = command_flags.command.starts_with('.')
|| command_flags.command.starts_with('/')
|| command_flags.command.starts_with('~')
|| command_flags.command.starts_with('\\')
|| Path::new(&command_flags.command).extension().is_some();
if is_file_like && Path::new(&command_flags.command).is_file() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you unit test this bit?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a8ee92 and b258276.

📒 Files selected for processing (1)
  • libs/node_resolver/resolution.rs (22 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: For debugging Rust code, set breakpoints in IDE debuggers (VS Code with rust-analyzer, IntelliJ IDEA) or use lldb directly
Use eprintln!() or dbg!() macros for debug prints in Rust code

Files:

  • libs/node_resolver/resolution.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: bench release linux-x86_64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: build libs
  • GitHub Check: test release macos-x86_64
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: lint debug windows-x86_64
  • GitHub Check: lint debug linux-x86_64
🔇 Additional comments (3)
libs/node_resolver/resolution.rs (3)

270-305: NodeResolverSys now requires FsOpen – confirm external implementors are updated

Extending NodeResolverSys to FsCanonicalize + FsMetadata + FsRead + FsReadDir + FsOpen changes the public trait surface. Any external implementors of NodeResolverSys will now need to implement FsOpen too. If this trait is considered part of the public embedding API, this is a breaking change and should be explicitly called out (release notes / changelog) or gated behind a new trait. If it’s internal-only, that’s fine but worth double‑checking usage across crates.


756-812: BinValue plumbing for npm bins looks consistent and preserves existing selection semantics

The shift from PathBuf to BinValue in:

  • resolve_binary_export (Result<BinValue, _>)
  • resolve_npm_binary_commands_for_package(_with_pkg_json) (BTreeMap<String, BinValue>)
  • resolve_npm_commands_from_bin_dir / resolve_bin_dir_entry_command
  • resolve_bin_entry_value using &BTreeMap<String, BinValue>

is wired through cleanly:

  • resolve_bin_entry_value still enforces the same bin-selection rules and only uses .path() at call sites, so behavior is preserved.
  • Directory and inline bin declarations both consistently flow through bin_value_from_file, giving JsFile vs Executable classification to downstream consumers (e.g. deno x).
  • The equality check bins.values().all(|bin| bin == first) still works as before, since classification for identical paths is deterministic.

I don’t see functional regressions in this pipeline; the richer BinValue surface should be safe for callers relying on previous behavior.

Also applies to: 814-858, 2258-2321


2587-2631: BinValue + binary detection + tests look correct for intended deno x usage

  • BinValue (JsFile | Executable) with the path() accessor is straightforward and keeps call‑sites clean.
  • is_binary + is_elf/is_macho/is_pe heuristics are minimal but sufficient for distinguishing obvious native binaries from text/npx shims; misclassification safely degrades to treating the file as Executable.
  • Test helper resolve_bins wrapping paths in BinValue::JsFile is appropriate, since resolve_bin_entry_value only cares about relative equality and final .path(), not whether the entry is JS vs native. The adapted assertions using .path() maintain the previous guarantees about which bin gets chosen and what error strings look like.

Given the above, the new representation and tests look solid for the npm bin resolution flow.

Also applies to: 2647-2655, 2670-2809

Comment on lines +2186 to +2219
fn bin_value_from_file<TSys: FsOpen>(
path: &Path,
sys: &NodeResolutionSys<TSys>,
) -> Option<BinValue> {
let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;
let mut buf = [0; 4];
let (is_binary, buf): (bool, &[u8]) = {
let result = file.read_exact(&mut buf);
if let Err(err) = result {
log::debug!("Failed to read binary file '{}': {:#}", path.display(), err);
// safer fallback to assume it's a binary
(false, &[])
} else {
(is_binary(&buf), &buf[..])
}
};

if is_binary {
return Some(BinValue::Executable(path.to_path_buf()));
}
let mut buf_read = BufReader::new(file);
let mut contents = Vec::new();
contents.extend_from_slice(buf);
if let Ok(len) = buf_read.read_to_end(&mut contents)
&& len > 0
&& let Ok(contents) = String::from_utf8(contents)
&& let Some(path) =
resolve_execution_path_from_npx_shim(Cow::Borrowed(path), &contents)
{
return Some(BinValue::JsFile(path));
}

Some(BinValue::Executable(path.to_path_buf()))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n libs/node_resolver/resolution.rs | sed -n '2186,2219p'

Repository: denoland/deno

Length of output: 170


🌐 Web query:

Deno node_resolver bin_value_from_file EACCES execute-only binary

💡 Result:

Short answer: that error means Deno's node resolver tried to open a native/npm CLI file but the OS denied read access because the file is "execute‑only" (no read permission) or otherwise not readable — fix by making the binary readable (or placing a readable copy) and ensuring Deno has permission to run subprocesses.

What to check and fix (quick):

  1. Confirm file permissions: run ls -l /path/to/bin — if mode shows x but not r (e.g. --x--x--x), add read: chmod a+r /path/to/bin.
  2. If the file lives on a restrictive mount (snap/readonly/execute-only) or macOS quarantine/immuatable flags, copy it to a normal location (e.g. /usr/local/bin or /tmp) and chmod +r.
  3. Ensure Deno is allowed to spawn/run subprocesses when relevant (Deno flags): use --allow-run when running/compiling if your code spawns child processes. See Deno permissions docs. [1][2]
  4. If the problem is with a compiled Deno binary invoking an npm package/bin, try running the npm binary directly to reproduce; if it fails with EACCES or “Exec format” also check architecture (arm64 vs x64) and shebang handling. See related Deno issues about running npm/native CLI from Deno. [3][4]

References:

  • Deno permissions / allow-run and file I/O docs. [1]
  • Deno forum thread about failing to execute npm binary / compiled binary issues. [3]
  • Deno compile / exec format / binary execution issues on GitHub. [4]

If you want, paste the exact error text and ls -l output for the binary and I’ll give the precise chmod/copy command.

Sources:
[1] Deno security & permissions docs.
[2] Deno docs — permissions overview (run/read/write/ffi/subprocess).
[3] Deno forum: “deno run fail to execute npm binary file in 2.0”.
[4] denoland/deno GitHub issues (cannot execute binary / exec format error).


Fall back to Executable when fs_open fails instead of silently dropping bins

bin_value_from_file currently returns None if fs_open fails:

let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;

This silently drops the bin from the resulting map when fs_open encounters errors (e.g., EACCES on execute-only binaries or transient FS errors). On Unix, execute-only files (mode --x--x--x) are valid and executable, but the current code hides them from deno x entirely.

The codebase already logs and falls back to treating files as executable when header reads fail; applying the same principle to open failures prevents valid commands from disappearing:

 fn bin_value_from_file<TSys: FsOpen>(
   path: &Path,
   sys: &NodeResolutionSys<TSys>,
 ) -> Option<BinValue> {
-  let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;
+  let mut file = match sys.fs_open(path, OpenOptions::new().read()) {
+    Ok(file) => file,
+    Err(err) => {
+      log::debug!(
+        "Failed to open bin file '{}': {:#}; treating as executable",
+        path.display(),
+        err,
+      );
+      return Some(BinValue::Executable(path.to_path_buf()));
+    }
+  };
   let mut buf = [0; 4];
   let (is_binary, buf): (bool, &[u8]) = {
     let result = file.read_exact(&mut buf);
     if let Err(err) = result {
       log::debug!("Failed to read binary file '{}': {:#}", path.display(), err);
       (false, &[])
     } else {
       (is_binary(&buf), &buf[..])
     }
   };
   // ...
 }

This preserves the current logging and fallback strategy while ensuring bins are never silently dropped due to permission or transient errors.

🤖 Prompt for AI Agents
In libs/node_resolver/resolution.rs around lines 2186 to 2219, the early return
on fs_open failure (using .ok()?) causes bins to be silently dropped; change the
opening logic to handle the error explicitly: match sys.fs_open(path,
OpenOptions::new().read()) and on Ok(file) proceed as before, but on Err(err)
emit a debug log with the error and immediately return
Some(BinValue::Executable(path.to_path_buf())) so we preserve execute-only or
transiently-unopenable files instead of returning None.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cli/args/flags.rs (1)

1536-1589: Expose deno x in the top‑level --help text

x_subcommand() is registered with clap, but the hard‑coded DENO_HELP template doesn’t list x under “Commands”, so deno --help won’t surface the new command even though it exists.

Recommend adding an entry for x (e.g. under “Execution” or “Tooling”) to keep the built‑in help authoritative for available subcommands.

Also applies to: 2059-2060

♻️ Duplicate comments (1)
libs/node_resolver/resolution.rs (1)

781-812: fs_open failures still silently drop bins; prefer logging + Executable fallback

bin_value_from_file currently does:

let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;

so any fs_open error (e.g. EACCES on execute‑only binaries, transient FS errors) causes this function to return None. Because callers use filter_map (resolve_npm_binary_commands_for_package_with_pkg_json, resolve_npm_commands_from_bin_dir, resolve_bin_dir_entry_command), those bins are silently omitted from the resulting command map.

That means valid commands can disappear with no diagnostics if the bin isn’t readable, even though it might still be executable by the OS.

Consider explicitly handling the open error and preserving the bin as an Executable (and logging), for example:

 fn bin_value_from_file<TSys: FsOpen>(
   path: &Path,
   sys: &NodeResolutionSys<TSys>,
 ) -> Option<BinValue> {
-  let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;
+  let mut file = match sys.fs_open(path, OpenOptions::new().read()) {
+    Ok(file) => file,
+    Err(err) => {
+      log::debug!(
+        "Failed to open bin file '{}': {:#}; treating as executable",
+        path.display(),
+        err,
+      );
+      return Some(BinValue::Executable(path.to_path_buf()));
+    }
+  };
   let mut buf = [0; 4];
   let (is_binary, buf): (bool, &[u8]) = {
     let result = file.read_exact(&mut buf);
     if let Err(err) = result {
       log::debug!("Failed to read binary file '{}': {:#}", path.display(), err);
-      // safer fallback to assume it's a binary
-      (false, &[])
+      // fall back to treating as an executable when header read fails
+      (true, &[])
     } else {
       (is_binary(&buf), &buf[..])
     }
   };
   // ... rest unchanged ...
 }

This keeps the “drop on analysis failure” behaviour only for truly unreadable contents, but no longer hides bins due to open failures.

Also applies to: 814-858, 2186-2219

🧹 Nitpick comments (3)
cli/lib/worker.rs (1)

737-767: BinValue handling in resolve_npm_binary_entrypoint is consistent, but variant is ignored

Using bin_value.path() keeps behavior aligned with the previous PathBuf-based API. However, the BinValue variant (JsFile vs Executable) is discarded here, so callers still can’t distinguish JS bins from native executables. If this entrypoint is ever used for non-JS binaries, consider either:

  • Restricting this method to JsFile only and erroring on Executable, or
  • Returning BinValue directly so the caller can choose how to execute it.
cli/tools/bundle/mod.rs (1)

1734-1765: Only treating JsFile bins as bundle roots makes sense

Restricting npm bin resolution in resolve_roots to BinValue::JsFile avoids trying to bundle native executables, which is correct for deno bundle. When resolve_binary_export returns an Executable or errors, you silently fall back to the original npm: URL and continue.

If debugging odd bundling behavior for some CLIs becomes an issue, consider adding a debug log in the else branch to surface why a bin wasn’t used as the root.

cli/args/flags.rs (1)

1600-1613: dx/denox normalization is correct; consider Windows behavior

The precedence/empty-args issue noted earlier is now fixed by guarding the compound condition and grouping the suffix checks; the normalization to ... "x" <rest> is safe.

One thing to double-check: on Windows, common launchers are dx.exe / dx.cmd / denox.cmd, so ends_with(b"dx") / ends_with(b"denox") won’t match those names. If the Windows alias installer intends to rely on this path (for example via a symlinked dx.exe), you may want to extend the check to account for *.exe/*.cmd suffixes; if installers instead call deno x directly, then the current logic is fine.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b258276 and b2594d7.

📒 Files selected for processing (5)
  • cli/args/flags.rs (7 hunks)
  • cli/lib/worker.rs (1 hunks)
  • cli/main.rs (1 hunks)
  • cli/tools/bundle/mod.rs (1 hunks)
  • libs/node_resolver/resolution.rs (22 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: For debugging Rust code, set breakpoints in IDE debuggers (VS Code with rust-analyzer, IntelliJ IDEA) or use lldb directly
Use eprintln!() or dbg!() macros for debug prints in Rust code

Files:

  • cli/main.rs
  • cli/lib/worker.rs
  • cli/tools/bundle/mod.rs
  • libs/node_resolver/resolution.rs
  • cli/args/flags.rs
cli/main.rs

📄 CodeRabbit inference engine (CLAUDE.md)

Main CLI entry point is in cli/main.rs and should handle command routing

Files:

  • cli/main.rs
cli/tools/**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

CLI tools should be implemented in cli/tools/<tool> or cli/tools/<tool>/mod.rs

Files:

  • cli/tools/bundle/mod.rs
cli/args/flags.rs

📄 CodeRabbit inference engine (CLAUDE.md)

CLI flag parsing should be defined in cli/args/flags.rs

Files:

  • cli/args/flags.rs
🧠 Learnings (4)
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/args/flags.rs : CLI flag parsing should be defined in `cli/args/flags.rs`

Applied to files:

  • cli/main.rs
  • cli/args/flags.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to runtime/worker.rs : Worker and runtime initialization is implemented in `runtime/worker.rs`

Applied to files:

  • cli/lib/worker.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/module_loader.rs : Module loading and resolution is handled in `cli/module_loader.rs`

Applied to files:

  • cli/tools/bundle/mod.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/main.rs : Main CLI entry point is in `cli/main.rs` and should handle command routing

Applied to files:

  • cli/args/flags.rs
🧬 Code graph analysis (2)
cli/main.rs (2)
cli/tools/x.rs (1)
  • run (259-415)
cli/lsp/language_server.rs (1)
  • roots (1038-1043)
libs/node_resolver/resolution.rs (1)
libs/package_json/lib.rs (2)
  • resolve_bins (547-580)
  • dir_path (508-510)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (13)
  • GitHub Check: test release macos-aarch64
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test release linux-aarch64
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test release windows-x86_64
  • GitHub Check: test release linux-x86_64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: lint debug windows-x86_64
  • GitHub Check: lint debug linux-x86_64
  • GitHub Check: lint debug macos-x86_64
  • GitHub Check: build libs
🔇 Additional comments (5)
libs/node_resolver/resolution.rs (2)

24-31: Extending NodeResolverSys with FsOpen and wiring BinValue through the API looks correct

Adding FsOpen to NodeResolverSys and introducing BinValue-based signatures (resolve_binary_export, resolve_npm_binary_commands_for_package*, resolve_npm_commands_from_bin_dir) are consistent with the new bin-classification logic and keep the resolver surface coherent. No functional issues spotted here.

Also applies to: 270-305


2257-2322: resolve_bin_entry_value and updated tests correctly generalize over BinValue

The refactor of resolve_bin_entry_value to operate on BTreeMap<String, BinValue> keeps the original selection semantics (explicit name, default bin, “all values equal” shortcut, single-bin fallback) while making the function agnostic to whether a bin is a JS file or an executable.

The new resolve_bins test helper that wraps paths as BinValue::JsFile maintains the existing test expectations, and the assertions using .path() still validate the resolved underlying paths.

No issues here; the behavior remains clear and well covered by tests.

Also applies to: 2647-2655, 2670-2682, 2711-2724, 2737-2743, 2755-2761, 2771-2783, 2795-2808, 2819-2833

cli/main.rs (1)

114-118: DenoSubcommand::X is wired consistently with other runtime-consuming subcommands

The new DenoSubcommand::X branch delegates to tools::x::run(flags, x_flags, unconfigured_runtime, roots) via spawn_subcommand, mirroring how Run and Serve use unconfigured_runtime and LibWorkerFactoryRoots. Ownership and cloning patterns look correct; no further changes needed here.

Also applies to: 252-256

cli/args/flags.rs (2)

405-440: New x flag types and subcommand wiring look consistent

DenoXShimName, XFlagsKind, XCommandFlags, XFlags, and the DenoSubcommand::X(XFlags) variant are minimal and align with existing patterns for other subcommands. No issues from a parsing or data-modelling perspective.

Also applies to: 573-610


3560-3598: x subcommand definition matches runtime patterns

The x command’s clap definition follows existing conventions:

  • Reuses runtime_args(..., include_perms = true, include_inspector = true, include_allow_scripts = true).
  • Uses script_arg().trailing_var_arg(true) for the “package + args” tail.
  • --yes conflicts with --install-alias, and --install-alias conflicts with script_arg, which cleanly separates “alias install” vs “execute package” modes.
  • deno_x_shim_name_parser is a straightforward parser for the alias name.

No functional issues here.

Comment thread cli/args/flags.rs Resolved
Comment thread libs/node_resolver/resolution.rs Resolved
@bartlomieju

Copy link
Copy Markdown
Member

Once this lands we should update https://github.com/denoland/deno_install to automatically run deno x --install-alias

@bartlomieju

This comment was marked as off-topic.

@bartlomieju

bartlomieju commented Dec 3, 2025 •

Copy link
Copy Markdown
Member

Add the banner for 2.6.0 to include instruction how to enable it and/or add a script that ensures this command has been installed

@bartlomieju

Copy link
Copy Markdown
Member

Figure out how this would work with brew

@bartlomieju

Copy link
Copy Markdown
Member

Update https://docs.deno.com/ as well. We could check in the update checker if dx has been installed

@nathanwhit

Copy link
Copy Markdown
Member Author

latest status is windows test failures blocked on #31494

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (3)
libs/node_resolver/resolution.rs (2)

6-7: Don’t silently drop bins when fs_open fails; fall back to Executable instead

bin_value_from_file currently does:

let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;

So when fs_open fails (permissions, transient FS error, execute‑only binaries, etc.), it returns None. Because callers use it in filter_map / ?:

  • resolve_npm_binary_commands_for_package_with_pkg_json (for "bin" objects)
  • resolve_bin_dir_entry_command / resolve_npm_commands_from_bin_dir (for bin dirs)

those commands are silently omitted from the resulting BTreeMap<String, BinValue>, making valid CLIs simply disappear from deno x with no clear signal. This is the same issue that was raised previously and is still present here.

You already have a safe fallback to BinValue::Executable when header reads or shim parsing fail; applying the same idea to open failures keeps behavior robust while preserving the new BinValue plumbing.

A concrete fix:

-fn bin_value_from_file<TSys: FsOpen>(
-  path: &Path,
-  sys: &NodeResolutionSys<TSys>,
-) -> Option<BinValue> {
-  let mut file = sys.fs_open(path, OpenOptions::new().read()).ok()?;
+fn bin_value_from_file<TSys: FsOpen>(
+  path: &Path,
+  sys: &NodeResolutionSys<TSys>,
+) -> Option<BinValue> {
+  let mut file = match sys.fs_open(path, OpenOptions::new().read()) {
+    Ok(file) => file,
+    Err(err) => {
+      log::debug!(
+        "Failed to open bin file '{}': {:#}; treating as executable",
+        path.display(),
+        err,
+      );
+      return Some(BinValue::Executable(path.to_path_buf()));
+    }
+  };
   let mut buf = [0; 4];
   let (is_binary, buf): (bool, &[u8]) = {
     let result = file.read_exact(&mut buf);
     if let Err(err) = result {
       log::debug!("Failed to read binary file '{}': {:#}", path.display(), err);
       // safer fallback to assume it's a binary
       (false, &[])
     } else {
       (is_binary(&buf), &buf[..])
     }
   };
   // ...
 }

This keeps the new BinValue API and logging, but ensures we never lose a bin purely because we couldn’t open it for reading.

Also applies to: 27-31, 270-273, 756-770, 775-779, 781-812, 814-838, 840-858, 2216-2249


2645-2675: Fix Mach‑O magic check endianness in is_macho

is_macho currently does:

let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
magic == 0xfeedfacf;

0xFEEDFACF is the big‑endian 64‑bit Mach‑O magic; reading the header with from_le_bytes and then comparing to the big‑endian constant will never match a real Mach‑O file. That makes the Mach‑O branch of is_binary effectively dead, so Mach‑O binaries always go through the slower “treat as text, then fall back to Executable” path.

Minimal correction:

fn is_macho(data: &[u8]) -> bool {
  if data.len() < 4 {
    return false;
  }
- let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
- magic == 0xfeedfacf
+ let magic = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
+ magic == 0xfeedfacf
}

(If you want broader coverage, you could also check the other Mach‑O magics like 0xfeedface, 0xcefaedfe, 0xcffaedfe.)

cli/args/flags.rs (1)

6856-6883: Runtime/config/permission flags are ignored for deno x --install-alias, and allow_all applies to non-execution modes

Two behavioral issues here:

  1. --install-alias silently discards all runtime flags

    x_subcommand() exposes runtime/config/permission/allow-scripts flags, but x_parse only calls runtime_args_parse in the Command branch. For:

    • deno x --install-alias --env-file=.env --allow-net=example.com
    • deno x --install-alias --permission-set=my-set

    those flags are accepted by clap but never reflected into Flags (env, permissions, permission_set, etc.), which is inconsistent with other subcommands like install and run. This is the same concern already raised in an earlier review.

  2. allow_all is being applied even when no package is executed

    The unconditional fallback:

    if !flags.permissions.has_permission() && flags.permission_set.is_none() {
      flags.permissions.allow_all = true;
    }

    also runs for InstallAlias and Print modes. That means:

    • deno x --install-alias ends up with allow_all set even though no package is executed.
    • A plain deno x (print/listing behavior) likewise flips allow_all, which is unnecessary and potentially confusing if higher layers inspect Flags.permissions uniformly.

    The intended “default allow-all” semantics are only needed when actually running a package command.

A localized fix that keeps the intended semantics while honoring runtime flags for all modes would be:

 fn x_parse(
   flags: &mut Flags,
   matches: &mut ArgMatches,
 ) -> clap::error::Result<()> {
-  let kind = if let Some(shim_name) =
-    matches.remove_one::<DenoXShimName>("install-alias")
-  {
-    XFlagsKind::InstallAlias(shim_name)
-  } else if let Some(mut script_arg) =
-    matches.remove_many::<String>("script_arg")
-  {
-    if let Some(command) = script_arg.next() {
-      let yes = matches.get_flag("yes");
-      flags.argv.extend(script_arg);
-      runtime_args_parse(flags, matches, true, true, true)?;
-      XFlagsKind::Command(XCommandFlags { yes, command })
-    } else {
-      XFlagsKind::Print
-    }
-  } else {
-    XFlagsKind::Print
-  };
-  if !flags.permissions.has_permission() && flags.permission_set.is_none() {
-    flags.permissions.allow_all = true;
-  }
+  // Parse runtime-level flags up front so they work for both `x <pkg>`
+  // and `x --install-alias`.
+  runtime_args_parse(flags, matches, true, true, true)?;
+
+  let kind = if let Some(shim_name) =
+    matches.remove_one::<DenoXShimName>("install-alias")
+  {
+    XFlagsKind::InstallAlias(shim_name)
+  } else if let Some(mut script_arg) =
+    matches.remove_many::<String>("script_arg")
+  {
+    if let Some(command) = script_arg.next() {
+      let yes = matches.get_flag("yes");
+      flags.argv.extend(script_arg);
+      XFlagsKind::Command(XCommandFlags { yes, command })
+    } else {
+      XFlagsKind::Print
+    }
+  } else {
+    XFlagsKind::Print
+  };
+
+  // Default to allow-all only when actually executing a package and the
+  // user did not opt into any explicit permission set or flags.
+  if matches!(kind, XFlagsKind::Command(_))
+    && !flags.permissions.has_permission()
+    && flags.permission_set.is_none()
+  {
+    flags.allow_all();
+  }
   flags.subcommand = DenoSubcommand::X(XFlags { kind });
   Ok(())
 }

This:

  • Makes --env-file, --allow-*, --deny-*, --permission-set, etc. effective for both x <pkg> and x --install-alias.
  • Restricts the allow_all default to the Command case, which matches the “run a package binary with all permissions by default” intent without leaking it into non-execution modes.
🧹 Nitpick comments (3)
cli/args/flags.rs (3)

1624-1637: dx/denox argv normalization is correct; add a small regression test

The new normalization:

  • Correctly guards args[0] behind !args.is_empty().
  • Fixes the earlier precedence bug that could access args[0] when empty.
  • Produces the expected shape ["dx", "x", …] / ["denox", "x", …] for symlink/renamed binaries.

Given how central flags_from_vec_with_initial_cwd is, I’d add a focused test to lock this in, for example:

@@
   #[test]
   fn has_permission_in_argv() {
@@
     assert_eq!(r.unwrap().has_permission_in_argv(), false);
   }
+
+  #[test]
+  fn dx_alias_normalizes_to_x_subcommand() {
+    let r = flags_from_vec(svec!["dx", "rolldown"]);
+    assert_eq!(
+      r.unwrap(),
+      Flags {
+        subcommand: DenoSubcommand::X(XFlags {
+          kind: XFlagsKind::Command(XCommandFlags {
+            yes: false,
+            command: "rolldown".to_string(),
+          }),
+        }),
+        permissions: PermissionFlags {
+          allow_all: true,
+          ..Default::default()
+        },
+        ..Flags::default()
+      }
+    );
+  }

1560-1613: Consider exposing deno x in the top-level help banner

x_subcommand() is now registered at the top level, but the static DENO_HELP template doesn’t mention x, so deno --help won’t advertise it even though it’s available.

Consider adding a brief line for x under an appropriate section (Execution or Tooling) in DENO_HELP so users can discover the new command without reading external docs.

Also applies to: 2083-2084, 3612-3642


7444-7460: Add minimal tests for deno x parsing and dx/denox normalization

Given how comprehensively this file is already tested, it’s worth adding a couple of small tests for the new X paths:

  • deno x <pkg> → DenoSubcommand::X(XFlagsKind::Command { yes, command }) with allow_all defaulted.
  • dx <pkg> / denox <pkg> → same as above, exercising the argv normalization logic.
  • deno x --install-alias → XFlagsKind::InstallAlias(DenoXShimName::Dx) without forcing allow_all (after the refactor above).

Example tests:

@@
   macro_rules! svec {
     ($($x:expr),* $(,)?) => (vec![$($x.to_string().into()),*]);
   }
@@
   fn has_permission_in_argv() {
@@
     assert_eq!(r.unwrap().has_permission_in_argv(), false);
   }
+
+  #[test]
+  fn x_subcommand_basic() {
+    let r = flags_from_vec(svec!["deno", "x", "rolldown"]);
+    assert_eq!(
+      r.unwrap(),
+      Flags {
+        subcommand: DenoSubcommand::X(XFlags {
+          kind: XFlagsKind::Command(XCommandFlags {
+            yes: false,
+            command: "rolldown".to_string(),
+          }),
+        }),
+        permissions: PermissionFlags {
+          allow_all: true,
+          ..Default::default()
+        },
+        ..Flags::default()
+      }
+    );
+  }
+
+  #[test]
+  fn dx_alias_normalizes_to_x() {
+    let r = flags_from_vec(svec!["dx", "rolldown"]);
+    assert_eq!(
+      r.unwrap(),
+      Flags {
+        subcommand: DenoSubcommand::X(XFlags {
+          kind: XFlagsKind::Command(XCommandFlags {
+            yes: false,
+            command: "rolldown".to_string(),
+          }),
+        }),
+        permissions: PermissionFlags {
+          allow_all: true,
+          ..Default::default()
+        },
+        ..Flags::default()
+      }
+    );
+  }
+
+  #[test]
+  fn x_install_alias_defaults_to_dx() {
+    let r = flags_from_vec(svec!["deno", "x", "--install-alias"]);
+    assert_eq!(
+      r.unwrap(),
+      Flags {
+        subcommand: DenoSubcommand::X(XFlags {
+          kind: XFlagsKind::InstallAlias(DenoXShimName::Dx),
+        }),
+        ..Flags::default()
+      }
+    );
+  }

These will catch regressions in both the new parse logic and the dx/denox argv rewriting without adding much maintenance burden.

Also applies to: 6856-6883, 1624-1637

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b2594d7 and ec74513.

📒 Files selected for processing (4)
  • cli/args/flags.rs (7 hunks)
  • cli/main.rs (1 hunks)
  • libs/node_resolver/lib.rs (1 hunks)
  • libs/node_resolver/resolution.rs (22 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.rs

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.rs: For debugging Rust code, set breakpoints in IDE debuggers (VS Code with rust-analyzer, IntelliJ IDEA) or use lldb directly
Use eprintln!() or dbg!() macros for debug prints in Rust code

Files:

  • libs/node_resolver/resolution.rs
  • cli/main.rs
  • libs/node_resolver/lib.rs
  • cli/args/flags.rs

⚙️ CodeRabbit configuration file

Don't worry about coverage of Rust docstrings. Don't be nitpicky about it. Leave it to the author's judgement if such a documentation is necessary.

Files:

  • libs/node_resolver/resolution.rs
  • cli/main.rs
  • libs/node_resolver/lib.rs
  • cli/args/flags.rs
cli/main.rs

📄 CodeRabbit inference engine (CLAUDE.md)

Main CLI entry point is in cli/main.rs and should handle command routing

Files:

  • cli/main.rs
cli/args/flags.rs

📄 CodeRabbit inference engine (CLAUDE.md)

CLI flag parsing should be defined in cli/args/flags.rs

Files:

  • cli/args/flags.rs
🧠 Learnings (4)
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/args/flags.rs : CLI flag parsing should be defined in `cli/args/flags.rs`

Applied to files:

  • cli/main.rs
  • cli/args/flags.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/module_loader.rs : Module loading and resolution is handled in `cli/module_loader.rs`

Applied to files:

  • libs/node_resolver/lib.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to runtime/permissions.rs : Permission system is implemented in `runtime/permissions.rs`

Applied to files:

  • cli/args/flags.rs
📚 Learning: 2025-11-24T16:19:37.808Z
Learnt from: CR
Repo: denoland/deno PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-24T16:19:37.808Z
Learning: Applies to cli/main.rs : Main CLI entry point is in `cli/main.rs` and should handle command routing

Applied to files:

  • cli/args/flags.rs
🧬 Code graph analysis (1)
cli/main.rs (1)
cli/tools/x.rs (1)
  • run (259-415)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: test debug linux-aarch64
  • GitHub Check: test debug windows-x86_64
  • GitHub Check: test debug linux-x86_64
  • GitHub Check: test debug macos-aarch64
  • GitHub Check: test release linux-x86_64
  • GitHub Check: test debug macos-x86_64
  • GitHub Check: lint debug linux-x86_64
  • GitHub Check: build libs
  • GitHub Check: lint debug windows-x86_64
  • GitHub Check: lint debug macos-x86_64
🔇 Additional comments (7)
libs/node_resolver/lib.rs (1)

30-30: Re-exporting BinValue at crate root is appropriate

This matches how other resolver types are surfaced and lets downstream code handle JS vs executable bins without reaching into resolution. No further changes needed.

libs/node_resolver/resolution.rs (1)

2631-2644: BinValue abstraction and test updates look good

Representing bins as BinValue::{JsFile, Executable} with a path() accessor cleanly separates behavior from storage, and the updates to resolve_bin_entry_value and the tests via resolve_bins preserve the previous semantics while making callers more explicit. No issues spotted in this wiring.

Also applies to: 2691-2699, 2714-2726, 2755-2768, 2781-2787, 2799-2805, 2815-2827, 2839-2853, 2863-2877

cli/main.rs (1)

260-262: DenoSubcommand::X dispatch is correctly integrated

The new X arm cleanly wires into run_subcommand: types line up with tools::x::run, async move + spawn_subcommand matches existing patterns (e.g. Run/Serve), and it correctly threads flags, unconfigured_runtime, and roots without introducing parsing logic into main.rs. Based on learnings, this keeps flag parsing confined to cli/args/flags.rs and uses main.rs only for routing.

cli/args/flags.rs (4)

420-455: X flag data model and shim name handling look solid

The DenoXShimName, XFlagsKind, XCommandFlags, and XFlags types cleanly capture the new subcommand’s surface (command vs install-alias vs print), and DenoXShimName::name() provides the expected stable string form. No changes needed here.


587-625: DenoSubcommand::X variant is wired in consistently

Adding X(XFlags) to DenoSubcommand integrates cleanly with existing helpers (watch_flags, needs_test, npm_system_info, Default), and it doesn’t accidentally opt into any watch/test behavior. This part looks correct.


3604-3610: Shim name parser is minimal and flexible

deno_x_shim_name_parser correctly maps the built‑in aliases (dx, denox) to enum variants and treats everything else as an opaque Other(String). This is simple and future‑proof if more aliases are added later.


3612-3642: x_subcommand CLI surface is well-shaped

The x subcommand:

  • Reuses runtime_args(cmd, true, true, true) so it gets the full runtime/config/permission/allow-scripts surface.
  • Treats the first script_arg as the command and the rest as args via trailing_var_arg(true).
  • Makes --yes incompatible with --install-alias, which matches expectations.

This CLI definition looks correct and consistent with other subcommands.

@bartlomieju bartlomieju left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@nathanwhit
nathanwhit merged commit 861f62a into denoland:main Dec 9, 2025
@nathanwhit
nathanwhit deleted the deno-x branch December 9, 2025 23:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants