lib_deno_resolver 0.10.0

Deno resolution algorithm
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
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

#![deny(clippy::print_stderr)]
#![deny(clippy::print_stdout)]

use std::path::PathBuf;
use std::sync::Arc;

use boxed_error::Boxed;
use deno_config::workspace::MappedResolution;
use deno_config::workspace::MappedResolutionDiagnostic;
use deno_config::workspace::MappedResolutionError;
use deno_config::workspace::WorkspaceResolvePkgJsonFolderError;
use deno_config::workspace::WorkspaceResolver;
use deno_package_json::PackageJsonDepValue;
use deno_package_json::PackageJsonDepValueParseError;
use deno_semver::npm::NpmPackageReqReference;
use fs::DenoResolverFs;
use lib_node_resolver::env::NodeResolverEnv;
use lib_node_resolver::errors::NodeResolveError;
use lib_node_resolver::errors::PackageSubpathResolveError;
use lib_node_resolver::InNpmPackageChecker;
use lib_node_resolver::NodeModuleKind;
use lib_node_resolver::NodeResolution;
use lib_node_resolver::NodeResolutionMode;
use lib_node_resolver::NodeResolver;
use npm::MissingPackageNodeModulesFolderError;
use npm::NodeModulesOutOfDateError;
use npm::NpmReqResolver;
use npm::ResolveIfForNpmPackageErrorKind;
use npm::ResolvePkgFolderFromDenoReqError;
use npm::ResolveReqWithSubPathErrorKind;
use sloppy_imports::SloppyImportResolverFs;
use sloppy_imports::SloppyImportsResolutionMode;
use sloppy_imports::SloppyImportsResolver;
use thiserror::Error;
use url::Url;

pub mod cjs;
pub mod fs;
pub mod npm;
pub mod sloppy_imports;

#[derive(Debug, Clone)]
pub struct DenoResolution {
  pub url: Url,
  pub maybe_diagnostic: Option<Box<MappedResolutionDiagnostic>>,
  pub found_package_json_dep: bool,
}

#[derive(Debug, Boxed)]
pub struct DenoResolveError(pub Box<DenoResolveErrorKind>);

#[derive(Debug, Error)]
pub enum DenoResolveErrorKind {
  #[error("Importing from the vendor directory is not permitted. Use a remote specifier instead or disable vendoring.")]
  InvalidVendorFolderImport,
  #[error(transparent)]
  MappedResolution(#[from] MappedResolutionError),
  #[error(transparent)]
  MissingPackageNodeModulesFolder(#[from] MissingPackageNodeModulesFolderError),
  #[error(transparent)]
  Node(#[from] NodeResolveError),
  #[error(transparent)]
  NodeModulesOutOfDate(#[from] NodeModulesOutOfDateError),
  #[error(transparent)]
  PackageJsonDepValueParse(#[from] PackageJsonDepValueParseError),
  #[error(transparent)]
  PackageJsonDepValueUrlParse(url::ParseError),
  #[error(transparent)]
  PackageSubpathResolve(#[from] PackageSubpathResolveError),
  #[error(transparent)]
  ResolvePkgFolderFromDenoReq(#[from] ResolvePkgFolderFromDenoReqError),
  #[error(transparent)]
  WorkspaceResolvePkgJsonFolder(#[from] WorkspaceResolvePkgJsonFolderError),
}

#[derive(Debug)]
pub struct NodeAndNpmReqResolver<
  Fs: DenoResolverFs,
  TNodeResolverEnv: NodeResolverEnv,
> {
  pub lib_node_resolver: Arc<NodeResolver<TNodeResolverEnv>>,
  pub npm_req_resolver: Arc<NpmReqResolver<Fs, TNodeResolverEnv>>,
}

pub struct DenoResolverOptions<
  'a,
  Fs: DenoResolverFs,
  TNodeResolverEnv: NodeResolverEnv,
  TSloppyImportResolverFs: SloppyImportResolverFs,
> {
  pub in_npm_pkg_checker: Arc<dyn InNpmPackageChecker>,
  pub node_and_req_resolver:
    Option<NodeAndNpmReqResolver<Fs, TNodeResolverEnv>>,
  pub sloppy_imports_resolver:
    Option<Arc<SloppyImportsResolver<TSloppyImportResolverFs>>>,
  pub workspace_resolver: Arc<WorkspaceResolver>,
  /// Whether "bring your own node_modules" is enabled where Deno does not
  /// setup the node_modules directories automatically, but instead uses
  /// what already exists on the file system.
  pub is_byonm: bool,
  pub maybe_vendor_dir: Option<&'a PathBuf>,
}

/// A resolver that takes care of resolution, taking into account loaded
/// import map, JSX settings.
#[derive(Debug)]
pub struct DenoResolver<
  Fs: DenoResolverFs,
  TNodeResolverEnv: NodeResolverEnv,
  TSloppyImportResolverFs: SloppyImportResolverFs,
> {
  in_npm_pkg_checker: Arc<dyn InNpmPackageChecker>,
  node_and_npm_resolver: Option<NodeAndNpmReqResolver<Fs, TNodeResolverEnv>>,
  sloppy_imports_resolver:
    Option<Arc<SloppyImportsResolver<TSloppyImportResolverFs>>>,
  workspace_resolver: Arc<WorkspaceResolver>,
  is_byonm: bool,
  maybe_vendor_specifier: Option<Url>,
}

impl<
    Fs: DenoResolverFs,
    TNodeResolverEnv: NodeResolverEnv,
    TSloppyImportResolverFs: SloppyImportResolverFs,
  > DenoResolver<Fs, TNodeResolverEnv, TSloppyImportResolverFs>
{
  pub fn new(
    options: DenoResolverOptions<Fs, TNodeResolverEnv, TSloppyImportResolverFs>,
  ) -> Self {
    Self {
      in_npm_pkg_checker: options.in_npm_pkg_checker,
      node_and_npm_resolver: options.node_and_req_resolver,
      sloppy_imports_resolver: options.sloppy_imports_resolver,
      workspace_resolver: options.workspace_resolver,
      is_byonm: options.is_byonm,
      maybe_vendor_specifier: options
        .maybe_vendor_dir
        .and_then(|v| deno_path_util::url_from_directory_path(v).ok()),
    }
  }

  pub fn resolve(
    &self,
    raw_specifier: &str,
    referrer: &Url,
    referrer_kind: NodeModuleKind,
    mode: NodeResolutionMode,
  ) -> Result<DenoResolution, DenoResolveError> {
    let mut found_package_json_dep = false;
    let mut maybe_diagnostic = None;
    // Use node resolution if we're in an npm package
    if let Some(node_and_npm_resolver) = self.node_and_npm_resolver.as_ref() {
      let lib_node_resolver = &node_and_npm_resolver.lib_node_resolver;
      if referrer.scheme() == "file"
        && self.in_npm_pkg_checker.in_npm_package(referrer)
      {
        return lib_node_resolver
          .resolve(raw_specifier, referrer, referrer_kind, mode)
          .map(|res| DenoResolution {
            url: res.into_url(),
            found_package_json_dep,
            maybe_diagnostic,
          })
          .map_err(|e| e.into());
      }
    }

    // Attempt to resolve with the workspace resolver
    let result: Result<_, DenoResolveError> = self
      .workspace_resolver
      .resolve(raw_specifier, referrer)
      .map_err(|err| err.into());
    let result = match result {
      Ok(resolution) => match resolution {
        MappedResolution::Normal {
          specifier,
          maybe_diagnostic: current_diagnostic,
        }
        | MappedResolution::ImportMap {
          specifier,
          maybe_diagnostic: current_diagnostic,
        } => {
          maybe_diagnostic = current_diagnostic;
          // do sloppy imports resolution if enabled
          if let Some(sloppy_imports_resolver) = &self.sloppy_imports_resolver {
            Ok(
              sloppy_imports_resolver
                .resolve(
                  &specifier,
                  match mode {
                    NodeResolutionMode::Execution => {
                      SloppyImportsResolutionMode::Execution
                    }
                    NodeResolutionMode::Types => {
                      SloppyImportsResolutionMode::Types
                    }
                  },
                )
                .map(|s| s.into_specifier())
                .unwrap_or(specifier),
            )
          } else {
            Ok(specifier)
          }
        }
        MappedResolution::WorkspaceJsrPackage { specifier, .. } => {
          Ok(specifier)
        }
        MappedResolution::WorkspaceNpmPackage {
          target_pkg_json: pkg_json,
          sub_path,
          ..
        } => self
          .node_and_npm_resolver
          .as_ref()
          .unwrap()
          .lib_node_resolver
          .resolve_package_subpath_from_deno_module(
            pkg_json.dir_path(),
            sub_path.as_deref(),
            Some(referrer),
            referrer_kind,
            mode,
          )
          .map_err(|e| e.into()),
        MappedResolution::PackageJson {
          dep_result,
          alias,
          sub_path,
          ..
        } => {
          // found a specifier in the package.json, so mark that
          // we need to do an "npm install" later
          found_package_json_dep = true;

          dep_result
            .as_ref()
            .map_err(|e| {
              DenoResolveErrorKind::PackageJsonDepValueParse(e.clone())
                .into_box()
            })
            .and_then(|dep| match dep {
              // todo(dsherret): it seems bad that we're converting this
              // to a url because the req might not be a valid url.
              PackageJsonDepValue::Req(req) => Url::parse(&format!(
                "npm:{}{}",
                req,
                sub_path.map(|s| format!("/{}", s)).unwrap_or_default()
              ))
              .map_err(|e| {
                DenoResolveErrorKind::PackageJsonDepValueUrlParse(e).into_box()
              }),
              PackageJsonDepValue::Workspace(version_req) => self
                .workspace_resolver
                .resolve_workspace_pkg_json_folder_for_pkg_json_dep(
                  alias,
                  version_req,
                )
                .map_err(|e| {
                  DenoResolveErrorKind::WorkspaceResolvePkgJsonFolder(e)
                    .into_box()
                })
                .and_then(|pkg_folder| {
                  self
                    .node_and_npm_resolver
                    .as_ref()
                    .unwrap()
                    .lib_node_resolver
                    .resolve_package_subpath_from_deno_module(
                      pkg_folder,
                      sub_path.as_deref(),
                      Some(referrer),
                      referrer_kind,
                      mode,
                    )
                    .map_err(|e| {
                      DenoResolveErrorKind::PackageSubpathResolve(e).into_box()
                    })
                }),
            })
        }
      },
      Err(err) => Err(err),
    };

    // When the user is vendoring, don't allow them to import directly from the vendor/ directory
    // as it might cause them confusion or duplicate dependencies. Additionally, this folder has
    // special treatment in the language server so it will definitely cause issues/confusion there
    // if they do this.
    if let Some(vendor_specifier) = &self.maybe_vendor_specifier {
      if let Ok(specifier) = &result {
        if specifier.as_str().starts_with(vendor_specifier.as_str()) {
          return Err(
            DenoResolveErrorKind::InvalidVendorFolderImport.into_box(),
          );
        }
      }
    }

    let Some(NodeAndNpmReqResolver {
      lib_node_resolver,
      npm_req_resolver,
    }) = &self.node_and_npm_resolver
    else {
      return Ok(DenoResolution {
        url: result?,
        maybe_diagnostic,
        found_package_json_dep,
      });
    };

    match result {
      Ok(specifier) => {
        if let Ok(npm_req_ref) =
          NpmPackageReqReference::from_specifier(&specifier)
        {
          // check if the npm specifier resolves to a workspace member
          if let Some(pkg_folder) = self
            .workspace_resolver
            .resolve_workspace_pkg_json_folder_for_npm_specifier(
              npm_req_ref.req(),
            )
          {
            return lib_node_resolver
              .resolve_package_subpath_from_deno_module(
                pkg_folder,
                npm_req_ref.sub_path(),
                Some(referrer),
                referrer_kind,
                mode,
              )
              .map(|url| DenoResolution {
                url,
                maybe_diagnostic,
                found_package_json_dep,
              })
              .map_err(|e| e.into());
          }

          // do npm resolution for byonm
          if self.is_byonm {
            return npm_req_resolver
              .resolve_req_reference(
                &npm_req_ref,
                referrer,
                referrer_kind,
                mode,
              )
              .map(|url| DenoResolution {
                url,
                maybe_diagnostic,
                found_package_json_dep,
              })
              .map_err(|err| {
                match err.into_kind() {
                ResolveReqWithSubPathErrorKind::MissingPackageNodeModulesFolder(
                  err,
                ) => err.into(),
                ResolveReqWithSubPathErrorKind::ResolvePkgFolderFromDenoReq(
                  err,
                ) => err.into(),
                ResolveReqWithSubPathErrorKind::PackageSubpathResolve(err) => {
                  err.into()
                }
              }
              });
          }
        }

        Ok(DenoResolution {
          url: lib_node_resolver
            .handle_if_in_node_modules(&specifier)
            .unwrap_or(specifier),
          maybe_diagnostic,
          found_package_json_dep,
        })
      }
      Err(err) => {
        // If byonm, check if the bare specifier resolves to an npm package
        if self.is_byonm && referrer.scheme() == "file" {
          let maybe_resolution = npm_req_resolver
            .resolve_if_for_npm_pkg(
              raw_specifier,
              referrer,
              referrer_kind,
              mode,
            )
            .map_err(|e| match e.into_kind() {
              ResolveIfForNpmPackageErrorKind::NodeResolve(e) => {
                DenoResolveErrorKind::Node(e).into_box()
              }
              ResolveIfForNpmPackageErrorKind::NodeModulesOutOfDate(e) => {
                e.into()
              }
            })?;
          if let Some(res) = maybe_resolution {
            match res {
              NodeResolution::Module(url) => {
                return Ok(DenoResolution {
                  url,
                  maybe_diagnostic,
                  found_package_json_dep,
                })
              }
              NodeResolution::BuiltIn(_) => {
                // don't resolve bare specifiers for built-in modules via node resolution
              }
            }
          }
        }

        Err(err)
      }
    }
  }
}