forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsnapshot.rs
More file actions
1616 lines (1494 loc) · 49.2 KB
/
snapshot.rs
File metadata and controls
1616 lines (1494 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2026 the Deno authors. MIT license.
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::VecDeque;
use std::collections::hash_map;
use std::sync::Arc;
use deno_error::JsError;
use deno_lockfile::Lockfile;
use deno_semver::StackString;
use deno_semver::VersionReq;
use deno_semver::package::PackageName;
use deno_semver::package::PackageNv;
use deno_semver::package::PackageReq;
use futures::StreamExt;
use futures::stream::FuturesOrdered;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
use super::NpmPackageVersionNotFound;
use super::UnmetPeerDepDiagnostic;
use super::common::NpmVersionResolver;
use super::graph::Graph;
use super::graph::GraphDependencyResolver;
use super::graph::NpmResolutionError;
use crate::NpmPackageCacheFolderId;
use crate::NpmPackageExtraInfo;
use crate::NpmPackageId;
use crate::NpmPackageIdDeserializationError;
use crate::NpmResolutionPackage;
use crate::NpmResolutionPackageSystemInfo;
use crate::NpmSystemInfo;
use crate::registry::NpmPackageInfo;
use crate::registry::NpmPackageVersionDistInfo;
use crate::registry::NpmPackageVersionInfo;
use crate::registry::NpmRegistryApi;
use crate::registry::NpmRegistryPackageInfoLoadError;
use crate::resolution::Reporter;
use crate::resolution::graph::GraphDependencyResolverOptions;
#[derive(Debug, Error, Clone, JsError)]
#[class(type)]
#[error("Could not find '{}' in the list of packages.", self.0.as_serialized())]
pub struct PackageIdNotFoundError(pub NpmPackageId);
#[derive(Debug, Error, Clone, JsError)]
#[class(type)]
#[error("Could not find constraint '{0}' in the list of packages.")]
pub struct PackageReqNotFoundError(pub PackageReq);
#[derive(Debug, Error, Clone, JsError)]
#[class(type)]
#[error("Could not find '{0}' in the list of packages.")]
pub struct PackageNvNotFoundError(pub PackageNv);
#[derive(Debug, Error, Clone, JsError)]
#[class(type)]
#[error("Could not find package folder id '{0}' in the list of packages.")]
pub struct PackageCacheFolderIdNotFoundError(pub NpmPackageCacheFolderId);
#[derive(Debug, Error, Clone, JsError)]
#[class(type)]
pub enum PackageNotFoundFromReferrerError {
#[error("Could not find referrer npm package '{0}'.")]
Referrer(NpmPackageCacheFolderId),
#[error("Could not find npm package '{name}' referenced by '{referrer}'.")]
Package {
name: String,
referrer: NpmPackageCacheFolderId,
},
}
/// Packages partitioned by if they are "copy" packages or not.
pub struct NpmPackagesPartitioned {
pub packages: Vec<NpmResolutionPackage>,
/// Since peer dependency resolution occurs based on ancestors and ancestor
/// siblings, this may sometimes cause the same package (name and version)
/// to have different dependencies based on where it appears in the tree.
/// For these packages, we create a "copy package" or duplicate of the package
/// whose dependencies are that of where in the tree they've resolved to.
pub copy_packages: Vec<NpmResolutionPackage>,
}
impl NpmPackagesPartitioned {
pub fn iter_all(&self) -> impl Iterator<Item = &NpmResolutionPackage> {
self.packages.iter().chain(self.copy_packages.iter())
}
}
/// A serialized snapshot that has been verified to be non-corrupt
/// and valid.
#[derive(Debug, Default, Clone)]
pub struct ValidSerializedNpmResolutionSnapshot(
// keep private -- once verified the caller
// shouldn't be able to modify it
SerializedNpmResolutionSnapshot,
);
impl ValidSerializedNpmResolutionSnapshot {
pub fn as_serialized(&self) -> &SerializedNpmResolutionSnapshot {
&self.0
}
pub fn into_serialized(self) -> SerializedNpmResolutionSnapshot {
self.0
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SerializedNpmResolutionSnapshotPackage {
pub id: NpmPackageId,
#[serde(flatten)]
pub system: NpmResolutionPackageSystemInfo,
pub dist: Option<NpmPackageVersionDistInfo>,
/// Key is what the package refers to the other package as,
/// which could be different from the package name.
pub dependencies: HashMap<StackString, NpmPackageId>,
pub optional_dependencies: HashSet<StackString>,
pub optional_peer_dependencies: HashSet<StackString>,
#[serde(flatten)]
pub extra: Option<NpmPackageExtraInfo>,
pub is_deprecated: bool,
pub has_bin: bool,
pub has_scripts: bool,
}
#[derive(Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SerializedNpmResolutionSnapshot {
/// Resolved npm specifiers to package id mappings.
pub root_packages: HashMap<PackageReq, NpmPackageId>,
/// Collection of resolved packages in the dependency graph.
pub packages: Vec<SerializedNpmResolutionSnapshotPackage>,
}
impl SerializedNpmResolutionSnapshot {
/// Marks the serialized snapshot as valid, if able.
///
/// Snapshots from serialized sources might be invalid due to tampering
/// by the user. For example, this could be populated from a lockfile
/// that the user modified.
pub fn into_valid(
self,
) -> Result<ValidSerializedNpmResolutionSnapshot, PackageIdNotFoundError> {
let mut verify_ids = HashSet::with_capacity(self.packages.len());
// collect the specifiers to version mappings
verify_ids.extend(self.root_packages.values());
// then the packages
let mut package_ids = HashSet::with_capacity(self.packages.len());
for package in &self.packages {
package_ids.insert(&package.id);
verify_ids.extend(package.dependencies.values());
}
// verify that all these ids exist in packages
for id in verify_ids {
if !package_ids.contains(&id) {
return Err(PackageIdNotFoundError(id.clone()));
}
}
Ok(ValidSerializedNpmResolutionSnapshot(self))
}
/// Trusts that the serialized snapshot is valid and skips runtime verification
/// that is done in `into_valid`.
///
/// Note: It will still do the verification in debug.
pub fn into_valid_unsafe(self) -> ValidSerializedNpmResolutionSnapshot {
if cfg!(debug_assertions) {
self.into_valid().unwrap()
} else {
ValidSerializedNpmResolutionSnapshot(self)
}
}
}
impl std::fmt::Debug for SerializedNpmResolutionSnapshot {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// do a custom debug implementation that creates deterministic output for the tests
f.debug_struct("SerializedNpmResolutionSnapshot")
.field(
"root_packages",
&self.root_packages.iter().collect::<BTreeMap<_, _>>(),
)
.field("packages", &self.packages)
.finish()
}
}
#[derive(Debug, Clone)]
pub struct AddPkgReqsOptions<'a> {
pub package_reqs: &'a [PackageReq],
pub version_resolver: &'a NpmVersionResolver,
/// If a deduplication pass should be done on the final graph.
///
/// This should never be done after code execution occurs (ex. this
/// should NOT be done when resolving a dynamically resolved npm dependency),
/// but is recommended for most other actions as it will create a smaller npm
/// dependency graph.
pub should_dedup: bool,
}
#[derive(Debug)]
pub struct AddPkgReqsResult {
/// Results from adding the individual packages.
///
/// The indexes of the results correspond to the indexes of the provided
/// package requirements.
pub results: Vec<Result<PackageNv, NpmResolutionError>>,
/// The result of resolving the entire dependency graph after the initial
/// reqs were resolved to nvs.
///
/// If a resolution error occurs, this will contain the first error.
pub dep_graph_result: Result<NpmResolutionSnapshot, NpmResolutionError>,
/// Diagnostics that were found during resolution. These should be
/// displayed as warnings.
pub unmet_peer_diagnostics: Vec<UnmetPeerDepDiagnostic>,
}
impl AddPkgReqsResult {
pub fn into_result(
self,
) -> Result<NpmResolutionSnapshot, NpmResolutionError> {
self.dep_graph_result
}
}
#[derive(Debug, Default, Clone)]
pub struct NpmResolutionSnapshot {
/// The unique package requirements map to a single npm package name and version.
pub(super) package_reqs: HashMap<PackageReq, PackageNv>,
// Each root level npm package name and version maps to an exact npm package node id.
pub(super) root_packages: HashMap<PackageNv, NpmPackageId>,
pub(super) packages_by_name: HashMap<StackString, Vec<NpmPackageId>>,
pub(super) packages: HashMap<NpmPackageId, NpmResolutionPackage>,
}
impl NpmResolutionSnapshot {
pub fn new(snapshot: ValidSerializedNpmResolutionSnapshot) -> Self {
let snapshot = snapshot.0;
let mut package_reqs = HashMap::<PackageReq, PackageNv>::with_capacity(
snapshot.root_packages.len(),
);
let mut root_packages = HashMap::<PackageNv, NpmPackageId>::with_capacity(
snapshot.root_packages.len(),
);
let mut packages_by_name =
HashMap::<StackString, Vec<NpmPackageId>>::with_capacity(
snapshot.packages.len(),
); // close enough
let mut packages =
HashMap::<NpmPackageId, NpmResolutionPackage>::with_capacity(
snapshot.packages.len(),
);
let mut copy_index_resolver =
SnapshotPackageCopyIndexResolver::with_capacity(snapshot.packages.len());
// collect the specifiers to version mappings
for (req, id) in snapshot.root_packages {
package_reqs.insert(req, id.nv.clone());
root_packages.insert(id.nv.clone(), id.clone());
}
// then the packages
for package in snapshot.packages {
packages_by_name
.entry(package.id.nv.name.clone())
.or_default()
.push(package.id.clone());
let copy_index = copy_index_resolver.resolve(&package.id);
packages.insert(
package.id.clone(),
NpmResolutionPackage {
id: package.id,
copy_index,
system: package.system,
dependencies: package.dependencies,
optional_dependencies: package.optional_dependencies,
optional_peer_dependencies: package.optional_peer_dependencies,
dist: package.dist,
extra: package.extra,
is_deprecated: package.is_deprecated,
has_bin: package.has_bin,
has_scripts: package.has_scripts,
},
);
}
Self {
package_reqs,
root_packages,
packages_by_name,
packages,
}
}
/// Resolves the provided package requirements adding them to the snapshot.
pub async fn add_pkg_reqs(
self,
api: &impl NpmRegistryApi,
options: AddPkgReqsOptions<'_>,
reporter: Option<&dyn Reporter>,
) -> AddPkgReqsResult {
enum InfoOrNv {
InfoResult(Result<Arc<NpmPackageInfo>, NpmRegistryPackageInfoLoadError>),
Nv(PackageNv),
}
// convert the snapshot to a traversable graph
let mut graph = Graph::from_snapshot(self);
let reqs_with_in_graph = options
.package_reqs
.iter()
.map(|req| (req, graph.get_req_nv(req).map(|r| r.as_ref().clone())));
let mut top_level_packages = FuturesOrdered::from_iter({
reqs_with_in_graph.map(|(req, maybe_nv)| async move {
let maybe_info = if let Some(nv) = maybe_nv {
InfoOrNv::Nv(nv)
} else {
InfoOrNv::InfoResult(api.package_info(&req.name).await)
};
(req, maybe_info)
})
});
// go over the top level package names first (npm package reqs and pending unresolved),
// then down the tree one level at a time through all the branches
let mut resolver = GraphDependencyResolver::new(
&mut graph,
api,
options.version_resolver,
reporter,
GraphDependencyResolverOptions {
should_dedup: options.should_dedup,
},
);
// The package reqs and ids should already be sorted
// in the order they should be resolved in.
let mut results = Vec::with_capacity(options.package_reqs.len());
let mut first_resolution_error = None;
while let Some(result) = top_level_packages.next().await {
let (req, info_or_nv) = result;
match info_or_nv {
InfoOrNv::InfoResult(info_result) => {
match info_result
.map_err(|err| err.into())
.and_then(|info| resolver.add_package_req(req, &info))
{
Ok(nv) => {
results.push(Ok(nv.as_ref().clone()));
}
Err(err) => {
if first_resolution_error.is_none() {
first_resolution_error = Some(err.clone());
}
results.push(Err(err));
}
}
}
InfoOrNv::Nv(nv) => {
results.push(Ok(nv));
}
}
}
drop(top_level_packages); // stop borrow of api
let mut unmet_peer_diagnostics = Vec::new();
let dep_graph_result = match first_resolution_error {
Some(err) => Err(err),
None => match resolver.resolve_pending().await {
Ok(()) => {
unmet_peer_diagnostics = resolver.take_unmet_peer_diagnostics();
graph
.into_snapshot(api, &options.version_resolver.link_packages)
.await
}
Err(err) => Err(err),
},
};
AddPkgReqsResult {
results,
dep_graph_result,
unmet_peer_diagnostics,
}
}
/// Returns a new snapshot made from a subset of this snapshot's package reqs.
/// Requirements not present in this snapshot will be ignored.
pub fn subset(&self, package_reqs: &[PackageReq]) -> Self {
let mut new_package_reqs = HashMap::with_capacity(package_reqs.len());
let mut packages = HashMap::with_capacity(package_reqs.len() * 2);
let mut packages_by_name: HashMap<StackString, Vec<NpmPackageId>> =
HashMap::with_capacity(package_reqs.len());
let mut root_packages = HashMap::with_capacity(package_reqs.len());
let mut visited = HashSet::with_capacity(packages.len());
let mut stack = Vec::new();
for req in package_reqs {
let Some(nv) = self.package_reqs.get(req) else {
continue;
};
let Some(id) = self.root_packages.get(nv) else {
continue;
};
new_package_reqs.insert(req.clone(), nv.clone());
root_packages.insert(nv.clone(), id.clone());
visited.insert(id);
stack.push(id);
}
while let Some(id) = stack.pop() {
let Some(package) = self.package_from_id(id) else {
continue;
};
packages_by_name
.entry(package.id.nv.name.clone())
.or_default()
.push(package.id.clone());
let Some(package) = self.package_from_id(id) else {
continue;
};
packages.insert(id.clone(), package.clone());
for dep in package.dependencies.values() {
if visited.insert(dep) {
stack.push(dep);
}
}
}
Self {
package_reqs: new_package_reqs,
packages,
packages_by_name,
root_packages,
}
}
/// Gets the snapshot as a valid serialized snapshot.
pub fn as_valid_serialized(&self) -> ValidSerializedNpmResolutionSnapshot {
ValidSerializedNpmResolutionSnapshot(SerializedNpmResolutionSnapshot {
root_packages: self
.package_reqs
.iter()
.map(|(req, nv)| {
let id = self.root_packages.get(nv).unwrap();
(req.clone(), id.clone())
})
.collect(),
packages: self
.packages
.values()
.map(|package| package.as_serialized())
.collect(),
})
}
/// Filters out any optional dependencies that don't match for the
/// given system. The resulting valid serialized snapshot will then not
/// have any optional dependencies that don't match the given system.
pub fn as_valid_serialized_for_system(
&self,
system_info: &NpmSystemInfo,
) -> ValidSerializedNpmResolutionSnapshot {
let mut final_packages = Vec::with_capacity(self.packages.len());
let mut pending = VecDeque::with_capacity(self.packages.len());
let mut visited_nvs = HashSet::with_capacity(self.packages.len());
// add the root packages
for pkg_id in self.root_packages.values() {
if visited_nvs.insert(&pkg_id.nv) {
pending.push_back(&pkg_id.nv);
}
}
while let Some(nv) = pending.pop_front() {
for id in self.package_ids_for_nv(nv) {
let pkg = self.packages.get(id).unwrap();
let mut new_pkg = SerializedNpmResolutionSnapshotPackage {
id: pkg.id.clone(),
dependencies: HashMap::with_capacity(pkg.dependencies.len()),
optional_peer_dependencies: pkg.optional_peer_dependencies.clone(),
// the fields below are stripped from the output
system: Default::default(),
optional_dependencies: Default::default(),
extra: pkg.extra.clone(),
dist: pkg.dist.clone(),
is_deprecated: pkg.is_deprecated,
has_bin: pkg.has_bin,
has_scripts: pkg.has_scripts,
};
for (key, dep_id) in &pkg.dependencies {
let dep = self.packages.get(dep_id).unwrap();
let matches_system = !pkg.optional_dependencies.contains(key)
|| dep.system.matches_system(system_info);
if matches_system {
new_pkg.dependencies.insert(key.clone(), dep_id.clone());
if visited_nvs.insert(&dep_id.nv) {
pending.push_back(&dep_id.nv);
}
}
}
final_packages.push(new_pkg);
}
}
ValidSerializedNpmResolutionSnapshot(SerializedNpmResolutionSnapshot {
packages: final_packages,
// the root packages are always included since they're
// what the user imports
root_packages: self
.package_reqs
.iter()
.map(|(req, nv)| {
let id = self.root_packages.get(nv).unwrap();
(req.clone(), id.clone())
})
.collect(),
})
}
/// Gets if this snapshot is empty.
pub fn is_empty(&self) -> bool {
self.packages.is_empty()
}
/// Converts the snapshot into an empty snapshot.
pub fn into_empty(self) -> Self {
// this is `into_empty()` instead of something like `clear()` in order
// to reduce the chance of a mistake forgetting to clear a collection
Self {
package_reqs: Default::default(),
root_packages: Default::default(),
packages_by_name: Default::default(),
packages: Default::default(),
}
}
/// Resolve a package from a package requirement.
pub fn resolve_pkg_from_pkg_req(
&self,
req: &PackageReq,
) -> Result<&NpmResolutionPackage, PackageReqNotFoundError> {
let package_nv = self.package_reqs.get(req).or_else(|| {
// fallback to iterating over the versions
req
.version_req
.tag()
.is_none()
.then(|| self.packages_by_name.get(&req.name))
.flatten()
.and_then(|ids| {
ids
.iter()
.filter(|id| req.version_req.matches(&id.nv.version))
.map(|id| &id.nv)
.max_by_key(|nv| &nv.version)
})
});
match package_nv {
Some(nv) => self
.resolve_package_from_deno_module(nv)
// ignore the nv not found error and return a req not found
.map_err(|_| PackageReqNotFoundError(req.clone())),
None => Err(PackageReqNotFoundError(req.clone())),
}
}
/// Resolve a package from a package cache folder id.
pub fn resolve_pkg_from_pkg_cache_folder_id(
&self,
pkg_cache_folder_id: &NpmPackageCacheFolderId,
) -> Result<&NpmResolutionPackage, PackageCacheFolderIdNotFoundError> {
self
.packages_by_name
.get(&pkg_cache_folder_id.nv.name)
.and_then(|ids| {
for id in ids {
if id.nv == pkg_cache_folder_id.nv
&& let Some(pkg) = self.packages.get(id)
&& pkg.copy_index == pkg_cache_folder_id.copy_index
{
return Some(pkg);
}
}
None
})
.map(Ok)
.unwrap_or_else(|| {
Err(PackageCacheFolderIdNotFoundError(
pkg_cache_folder_id.clone(),
))
})
}
/// Resolve a package id from a deno module.
pub fn resolve_package_id_from_deno_module(
&self,
nv: &PackageNv,
) -> Result<&NpmPackageId, PackageNvNotFoundError> {
match self.root_packages.get(nv) {
Some(id) => Ok(id),
None => Err(PackageNvNotFoundError(nv.clone())),
}
}
/// Resolve a package from a deno module.
pub fn resolve_package_from_deno_module(
&self,
nv: &PackageNv,
) -> Result<&NpmResolutionPackage, PackageNvNotFoundError> {
self
.resolve_package_id_from_deno_module(nv)
.map(|id| self.packages.get(id).unwrap())
}
pub fn top_level_packages(
&self,
) -> hash_map::Values<'_, PackageNv, NpmPackageId> {
self.root_packages.values()
}
pub fn package_reqs(&self) -> &HashMap<PackageReq, PackageNv> {
&self.package_reqs
}
pub fn package_from_id(
&self,
id: &NpmPackageId,
) -> Option<&NpmResolutionPackage> {
self.packages.get(id)
}
pub fn resolve_package_from_package(
&self,
name: &str,
referrer: &NpmPackageCacheFolderId,
) -> Result<&NpmResolutionPackage, Box<PackageNotFoundFromReferrerError>> {
// todo(dsherret): do we need an additional hashmap to get this quickly?
let referrer_package = self
.packages_by_name
.get(&referrer.nv.name)
.and_then(|packages| {
packages
.iter()
.filter(|p| p.nv.version == referrer.nv.version)
.filter_map(|node_id| {
let package = self.packages.get(node_id)?;
if package.copy_index == referrer.copy_index {
Some(package)
} else {
None
}
})
.next()
})
.ok_or_else(|| {
Box::new(PackageNotFoundFromReferrerError::Referrer(referrer.clone()))
})?;
let name = crate::package_name_without_subpath(name);
if let Some(id) = referrer_package.dependencies.get(name) {
return Ok(self.packages.get(id).unwrap());
}
if referrer_package.id.nv.name == name {
return Ok(referrer_package);
}
// TODO(bartlomieju): this should use a reverse lookup table in the
// snapshot instead of resolving best version again.
let any_version_req = VersionReq::parse_from_npm("*").unwrap();
if let Some(id) = self.resolve_best_package_id(name, &any_version_req)
&& let Some(pkg) = self.packages.get(&id)
{
return Ok(pkg);
}
Err(Box::new(PackageNotFoundFromReferrerError::Package {
name: name.to_string(),
referrer: referrer.clone(),
}))
}
/// Gets all the packages found in the snapshot regardless of
/// whether they are supported on the current system.
pub fn all_packages_for_every_system(
&self,
) -> impl Iterator<Item = &NpmResolutionPackage> {
// NOTE: This method intentionally has a verbose name
// to discourage its use.
self.packages.values()
}
pub fn all_system_packages(
&self,
system_info: &NpmSystemInfo,
) -> Vec<NpmResolutionPackage> {
let mut packages = Vec::with_capacity(self.packages.len());
let mut pending = VecDeque::with_capacity(self.packages.len());
let mut visited_nvs = HashSet::with_capacity(self.packages.len());
for pkg_id in self.root_packages.values() {
if visited_nvs.insert(&pkg_id.nv) {
pending.push_back(&pkg_id.nv);
}
}
while let Some(nv) = pending.pop_front() {
for pkg_id in self.package_ids_for_nv(nv) {
let pkg = self.packages.get(pkg_id).unwrap();
packages.push(pkg.clone());
for (key, dep_id) in &pkg.dependencies {
let dep = self.packages.get(dep_id).unwrap();
let matches_system = !pkg.optional_dependencies.contains(key)
|| dep.system.matches_system(system_info);
if matches_system && visited_nvs.insert(&dep_id.nv) {
pending.push_back(&dep.id.nv);
}
}
}
}
packages
}
pub fn all_system_packages_partitioned(
&self,
system_info: &NpmSystemInfo,
) -> NpmPackagesPartitioned {
let mut packages = self.all_system_packages(system_info);
// in most scenarios, there won't ever be any copy packages so skip
// the extra allocations if so
let copy_packages = if packages.iter().any(|p| p.copy_index > 0) {
let mut copy_packages = Vec::with_capacity(packages.len() / 2); // at most 1 copy for every package
let copy_index_zero_nvs = packages
.iter()
.filter(|p| p.copy_index == 0)
.map(|p| p.id.nv.clone())
.collect::<HashSet<_>>();
// partition out any packages that are "copy" packages
for i in (0..packages.len()).rev() {
if packages[i].copy_index > 0
// the system might not have resolved the package with a
// copy_index of 0, so we also need to check that
&& copy_index_zero_nvs.contains(&packages[i].id.nv)
{
copy_packages.push(packages.swap_remove(i));
}
}
copy_packages
} else {
Vec::new()
};
NpmPackagesPartitioned {
packages,
copy_packages,
}
}
pub fn resolve_best_package_id(
&self,
name: &str,
version_req: &VersionReq,
) -> Option<NpmPackageId> {
// todo(dsherret): this is not exactly correct because some ids
// will be better than others due to peer dependencies
let mut maybe_best_id: Option<&NpmPackageId> = None;
if let Some(node_ids) = self.packages_by_name.get(name) {
for node_id in node_ids.iter() {
if version_req.matches(&node_id.nv.version) {
let is_best_version = maybe_best_id
.as_ref()
.map(|best_id| best_id.nv.version.cmp(&node_id.nv.version).is_lt())
.unwrap_or(true);
if is_best_version {
maybe_best_id = Some(node_id);
}
}
}
}
maybe_best_id.cloned()
}
pub fn package_ids_for_nv<'a>(
&'a self,
nv: &'a PackageNv,
) -> impl Iterator<Item = &'a NpmPackageId> {
self
.packages_by_name
.get(&nv.name)
.map(|p| p.iter().filter(|p| p.nv == *nv))
.into_iter()
.flatten()
}
}
pub struct SnapshotPackageCopyIndexResolver {
packages_to_copy_index: HashMap<NpmPackageId, u8>,
package_name_version_to_copy_count: HashMap<PackageNv, u8>,
}
impl SnapshotPackageCopyIndexResolver {
pub fn with_capacity(capacity: usize) -> Self {
Self {
packages_to_copy_index: HashMap::with_capacity(capacity),
package_name_version_to_copy_count: HashMap::with_capacity(capacity), // close enough
}
}
pub fn from_map_with_capacity(
mut packages_to_copy_index: HashMap<NpmPackageId, u8>,
capacity: usize,
) -> Self {
let mut package_name_version_to_copy_count =
HashMap::with_capacity(capacity); // close enough
if capacity > packages_to_copy_index.len() {
packages_to_copy_index.reserve(capacity - packages_to_copy_index.len());
}
for (node_id, index) in &packages_to_copy_index {
let entry = package_name_version_to_copy_count
.entry(node_id.nv.clone())
.or_insert(0);
if *entry < *index {
*entry = *index;
}
}
Self {
packages_to_copy_index,
package_name_version_to_copy_count,
}
}
pub fn resolve(&mut self, node_id: &NpmPackageId) -> u8 {
if let Some(index) = self.packages_to_copy_index.get(node_id) {
*index
} else {
let index = *self
.package_name_version_to_copy_count
.entry(node_id.nv.clone())
.and_modify(|count| {
*count += 1;
})
.or_insert(0);
self.packages_to_copy_index.insert(node_id.clone(), index);
index
}
}
}
#[derive(Debug, Error, Clone, JsError)]
pub enum SnapshotFromLockfileError {
#[error("Could not find '{}' specified in the lockfile.", .source.0)]
#[class(inherit)]
VersionNotFound {
#[from]
source: NpmPackageVersionNotFound,
},
#[error("The lockfile is corrupt. Remove the lockfile to regenerate it.")]
#[class(inherit)]
PackageIdNotFound(#[from] PackageIdNotFoundError),
#[error(transparent)]
#[class(inherit)]
PackageIdDeserialization(#[from] NpmPackageIdDeserializationError),
}
pub struct SnapshotFromLockfileParams<'a> {
pub link_packages: &'a HashMap<PackageName, Vec<NpmPackageVersionInfo>>,
pub lockfile: &'a Lockfile,
pub default_tarball_url: &'a dyn DefaultTarballUrlProvider,
}
pub trait DefaultTarballUrlProvider {
fn default_tarball_url(&self, nv: &PackageNv) -> String;
}
impl Default for &dyn DefaultTarballUrlProvider {
fn default() -> Self {
&NpmRegistryDefaultTarballUrlProvider
}
}
/// `DefaultTarballUrlProvider` that uses the url of the real npm registry.
#[derive(Debug, Default, Clone)]
pub struct NpmRegistryDefaultTarballUrlProvider;
impl DefaultTarballUrlProvider for NpmRegistryDefaultTarballUrlProvider {
fn default_tarball_url(
&self,
nv: &deno_semver::package::PackageNv,
) -> String {
let scope = nv.scope();
let package_name = if let Some(scope) = scope {
nv.name
.strip_prefix(scope)
.unwrap_or(&nv.name)
.trim_start_matches('/')
} else {
&nv.name
};
format!(
"https://registry.npmjs.org/{}/-/{}-{}.tgz",
nv.name, package_name, nv.version
)
}
}
fn dist_from_incomplete_package_info(
id: &PackageNv,
integrity: Option<&str>,
tarball: Option<&str>,
default_tarball_url: &dyn DefaultTarballUrlProvider,
) -> NpmPackageVersionDistInfo {
let (shasum, integrity) = if let Some(integrity) = integrity {
if integrity.contains('-') {
(None, Some(integrity.to_string()))
} else {
(Some(integrity.to_string()), None)
}
} else {
(None, None)
};
NpmPackageVersionDistInfo {
tarball: tarball
.map(|t| t.to_string())
.unwrap_or_else(|| default_tarball_url.default_tarball_url(id)),
shasum,
integrity,
}
}
#[derive(Debug, Error, Clone, JsError)]
pub enum IncompleteSnapshotFromLockfileError {
#[error(transparent)]
#[class(inherit)]
PackageIdDeserialization(#[from] NpmPackageIdDeserializationError),
}
/// Constructs [`ValidSerializedNpmResolutionSnapshot`] from the given [`Lockfile`].
#[allow(clippy::needless_lifetimes)] // clippy bug
pub fn snapshot_from_lockfile(
params: SnapshotFromLockfileParams<'_>,
) -> Result<ValidSerializedNpmResolutionSnapshot, SnapshotFromLockfileError> {
let default_tarball_url = params.default_tarball_url;
let lockfile = params.lockfile;
let mut root_packages = HashMap::<PackageReq, NpmPackageId>::with_capacity(
lockfile.content.packages.specifiers.len(),
);
let link_package_ids = params
.link_packages
.iter()
.flat_map(|(name, info_vec)| {
info_vec.iter().map(move |info| {
StackString::from_string(format!("{}@{}", name, info.version))
})
})
.collect::<HashSet<_>>();
// collect the specifiers to version mappings
for (key, value) in &lockfile.content.packages.specifiers {
match key.kind {
deno_semver::package::PackageKind::Npm => {
let package_id = NpmPackageId::from_serialized(&format!(
"{}@{}",
key.req.name, value
))?;
root_packages.insert(key.req.clone(), package_id);
}
deno_semver::package::PackageKind::Jsr => {}
}
}
// now fill the packages except for the dist information
let mut packages = Vec::with_capacity(lockfile.content.packages.npm.len());
for (key, package) in &lockfile.content.packages.npm {
let id = NpmPackageId::from_serialized(key)?;
// collect the dependencies
let mut dependencies = HashMap::with_capacity(package.dependencies.len());
for (name, specifier) in &package.dependencies {
let dep_id = NpmPackageId::from_serialized(specifier)?;
dependencies.insert(name.clone(), dep_id);
}
let mut optional_dependencies =
HashMap::with_capacity(package.optional_dependencies.len());