forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
import_map.rs
2068 lines (1882 loc) · 62.7 KB
/
import_map.rs
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
use deno_core::ErrBox;
use deno_core::ModuleSpecifier;
use indexmap::IndexMap;
use serde_json::Map;
use serde_json::Value;
use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::fs;
use std::io;
use url::Url;
#[derive(Debug)]
pub struct ImportMapError {
pub msg: String,
}
impl ImportMapError {
pub fn new(msg: &str) -> Self {
ImportMapError {
msg: msg.to_string(),
}
}
}
impl fmt::Display for ImportMapError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(&self.msg)
}
}
impl Error for ImportMapError {}
// NOTE: here is difference between deno and reference implementation - deno currently
// can't resolve URL with other schemes (eg. data:, about:, blob:)
const SUPPORTED_FETCH_SCHEMES: [&str; 3] = ["http", "https", "file"];
type SpecifierMap = IndexMap<String, Vec<ModuleSpecifier>>;
type ScopesMap = IndexMap<String, SpecifierMap>;
#[derive(Debug, Clone)]
pub struct ImportMap {
base_url: String,
imports: SpecifierMap,
scopes: ScopesMap,
}
impl ImportMap {
pub fn load(file_path: &str) -> Result<Self, ErrBox> {
let file_url = ModuleSpecifier::resolve_url_or_path(file_path)?.to_string();
let resolved_path = std::env::current_dir().unwrap().join(file_path);
debug!(
"Attempt to load import map: {}",
resolved_path.to_str().unwrap()
);
// Load the contents of import map
let json_string = fs::read_to_string(&resolved_path).map_err(|err| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"Error retrieving import map file at \"{}\": {}",
resolved_path.to_str().unwrap(),
err.to_string()
)
.as_str(),
)
})?;
// The URL of the import map is the base URL for its values.
ImportMap::from_json(&file_url, &json_string).map_err(ErrBox::from)
}
pub fn from_json(
base_url: &str,
json_string: &str,
) -> Result<Self, ImportMapError> {
let v: Value = match serde_json::from_str(json_string) {
Ok(v) => v,
Err(_) => {
return Err(ImportMapError::new("Unable to parse import map JSON"));
}
};
match v {
Value::Object(_) => {}
_ => {
return Err(ImportMapError::new("Import map JSON must be an object"));
}
}
let normalized_imports = match &v.get("imports") {
Some(imports_map) => {
if !imports_map.is_object() {
return Err(ImportMapError::new(
"Import map's 'imports' must be an object",
));
}
let imports_map = imports_map.as_object().unwrap();
ImportMap::parse_specifier_map(imports_map, base_url)
}
None => IndexMap::new(),
};
let normalized_scopes = match &v.get("scopes") {
Some(scope_map) => {
if !scope_map.is_object() {
return Err(ImportMapError::new(
"Import map's 'scopes' must be an object",
));
}
let scope_map = scope_map.as_object().unwrap();
ImportMap::parse_scope_map(scope_map, base_url)?
}
None => IndexMap::new(),
};
let import_map = ImportMap {
base_url: base_url.to_string(),
imports: normalized_imports,
scopes: normalized_scopes,
};
Ok(import_map)
}
fn try_url_like_specifier(specifier: &str, base: &str) -> Option<Url> {
// this should never fail
if specifier.starts_with('/')
|| specifier.starts_with("./")
|| specifier.starts_with("../")
{
let base_url = Url::parse(base).unwrap();
let url = base_url.join(specifier).unwrap();
return Some(url);
}
if let Ok(url) = Url::parse(specifier) {
if SUPPORTED_FETCH_SCHEMES.contains(&url.scheme()) {
return Some(url);
}
}
None
}
/// Parse provided key as import map specifier.
///
/// Specifiers must be valid URLs (eg. "https://deno.land/x/std/testing/asserts.ts")
/// or "bare" specifiers (eg. "moment").
// TODO: add proper error handling: https://github.com/WICG/import-maps/issues/100
fn normalize_specifier_key(
specifier_key: &str,
base_url: &str,
) -> Option<String> {
// ignore empty keys
if specifier_key.is_empty() {
return None;
}
if let Some(url) =
ImportMap::try_url_like_specifier(specifier_key, base_url)
{
return Some(url.to_string());
}
// "bare" specifier
Some(specifier_key.to_string())
}
/// Parse provided addresses as valid URLs.
///
/// Non-valid addresses are skipped.
fn normalize_addresses(
specifier_key: &str,
base_url: &str,
potential_addresses: Vec<String>,
) -> Vec<ModuleSpecifier> {
let mut normalized_addresses: Vec<ModuleSpecifier> = vec![];
for potential_address in potential_addresses {
let url =
match ImportMap::try_url_like_specifier(&potential_address, base_url) {
Some(url) => url,
None => continue,
};
let url_string = url.to_string();
if specifier_key.ends_with('/') && !url_string.ends_with('/') {
eprintln!(
"Invalid target address {:?} for package specifier {:?}.\
Package address targets must end with \"/\".",
url_string, specifier_key
);
continue;
}
normalized_addresses.push(url.into());
}
normalized_addresses
}
/// Convert provided JSON map to valid SpecifierMap.
///
/// From specification:
/// - order of iteration must be retained
/// - SpecifierMap's keys are sorted in longest and alphabetic order
fn parse_specifier_map(
json_map: &Map<String, Value>,
base_url: &str,
) -> SpecifierMap {
let mut normalized_map: SpecifierMap = SpecifierMap::new();
// Order is preserved because of "preserve_order" feature of "serde_json".
for (specifier_key, value) in json_map.iter() {
let normalized_specifier_key =
match ImportMap::normalize_specifier_key(specifier_key, base_url) {
Some(s) => s,
None => continue,
};
let potential_addresses: Vec<String> = match value {
Value::String(address) => vec![address.to_string()],
Value::Array(address_array) => {
let mut string_addresses: Vec<String> = vec![];
for address in address_array {
match address {
Value::String(address) => {
string_addresses.push(address.to_string())
}
_ => continue,
}
}
string_addresses
}
Value::Null => vec![],
_ => vec![],
};
let normalized_address_array = ImportMap::normalize_addresses(
&normalized_specifier_key,
base_url,
potential_addresses,
);
debug!(
"normalized specifier {:?}; {:?}",
normalized_specifier_key, normalized_address_array
);
normalized_map.insert(normalized_specifier_key, normalized_address_array);
}
// Sort in longest and alphabetical order.
normalized_map.sort_by(|k1, _v1, k2, _v2| match k1.cmp(&k2) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => k2.cmp(k1),
});
normalized_map
}
/// Convert provided JSON map to valid ScopeMap.
///
/// From specification:
/// - order of iteration must be retained
/// - ScopeMap's keys are sorted in longest and alphabetic order
fn parse_scope_map(
scope_map: &Map<String, Value>,
base_url: &str,
) -> Result<ScopesMap, ImportMapError> {
let mut normalized_map: ScopesMap = ScopesMap::new();
// Order is preserved because of "preserve_order" feature of "serde_json".
for (scope_prefix, potential_specifier_map) in scope_map.iter() {
if !potential_specifier_map.is_object() {
return Err(ImportMapError::new(&format!(
"The value for the {:?} scope prefix must be an object",
scope_prefix
)));
}
let potential_specifier_map =
potential_specifier_map.as_object().unwrap();
let scope_prefix_url =
match Url::parse(base_url).unwrap().join(scope_prefix) {
Ok(url) => {
if !SUPPORTED_FETCH_SCHEMES.contains(&url.scheme()) {
eprintln!(
"Invalid scope {:?}. Scope URLs must have a valid fetch scheme.",
url.to_string()
);
continue;
}
url.to_string()
}
_ => continue,
};
let norm_map =
ImportMap::parse_specifier_map(potential_specifier_map, base_url);
normalized_map.insert(scope_prefix_url, norm_map);
}
// Sort in longest and alphabetical order.
normalized_map.sort_by(|k1, _v1, k2, _v2| match k1.cmp(&k2) {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equal => k2.cmp(k1),
});
Ok(normalized_map)
}
pub fn resolve_scopes_match(
scopes: &ScopesMap,
normalized_specifier: &str,
referrer: &str,
) -> Result<Option<ModuleSpecifier>, ImportMapError> {
// exact-match
if let Some(scope_imports) = scopes.get(referrer) {
if let Ok(scope_match) =
ImportMap::resolve_imports_match(scope_imports, normalized_specifier)
{
// Return only if there was actual match (not None).
if scope_match.is_some() {
return Ok(scope_match);
}
}
}
for (normalized_scope_key, scope_imports) in scopes.iter() {
if normalized_scope_key.ends_with('/')
&& referrer.starts_with(normalized_scope_key)
{
if let Ok(scope_match) =
ImportMap::resolve_imports_match(scope_imports, normalized_specifier)
{
// Return only if there was actual match (not None).
if scope_match.is_some() {
return Ok(scope_match);
}
}
}
}
Ok(None)
}
// TODO: https://github.com/WICG/import-maps/issues/73#issuecomment-439327758
// for some more optimized candidate implementations.
pub fn resolve_imports_match(
imports: &SpecifierMap,
normalized_specifier: &str,
) -> Result<Option<ModuleSpecifier>, ImportMapError> {
// exact-match
if let Some(address_vec) = imports.get(normalized_specifier) {
if address_vec.is_empty() {
return Err(ImportMapError::new(&format!(
"Specifier {:?} was mapped to no addresses.",
normalized_specifier
)));
} else if address_vec.len() == 1 {
let address = address_vec.first().unwrap();
debug!(
"Specifier {:?} was mapped to {:?}.",
normalized_specifier, address
);
return Ok(Some(address.clone()));
} else {
return Err(ImportMapError::new(
"Multi-address mappings are not yet supported",
));
}
}
// package-prefix match
// "most-specific wins", i.e. when there are multiple matching keys,
// choose the longest.
// https://github.com/WICG/import-maps/issues/102
for (specifier_key, address_vec) in imports.iter() {
if specifier_key.ends_with('/')
&& normalized_specifier.starts_with(specifier_key)
{
if address_vec.is_empty() {
return Err(ImportMapError::new(&format!("Specifier {:?} was mapped to no addresses (via prefix specifier key {:?}).", normalized_specifier, specifier_key)));
} else if address_vec.len() == 1 {
let address = address_vec.first().unwrap();
let after_prefix = &normalized_specifier[specifier_key.len()..];
let base_url = address.as_url();
if let Ok(url) = base_url.join(after_prefix) {
debug!("Specifier {:?} was mapped to {:?} (via prefix specifier key {:?}).", normalized_specifier, url, address);
return Ok(Some(ModuleSpecifier::from(url)));
}
unreachable!();
} else {
return Err(ImportMapError::new(
"Multi-address mappings are not yet supported",
));
}
}
}
debug!(
"Specifier {:?} was not mapped in import map.",
normalized_specifier
);
Ok(None)
}
// TODO: add support for built-in modules
/// Currently we support two types of specifiers: URL (http:https://, https://, file:https://)
/// and "bare" (moment, jquery, lodash)
///
/// Scenarios:
/// 1. import resolved using import map -> String
/// 2. import restricted by import map -> ImportMapError
/// 3. import not mapped -> None
pub fn resolve(
&self,
specifier: &str,
referrer: &str,
) -> Result<Option<ModuleSpecifier>, ImportMapError> {
let resolved_url: Option<Url> =
ImportMap::try_url_like_specifier(specifier, referrer);
let normalized_specifier = match &resolved_url {
Some(url) => url.to_string(),
None => specifier.to_string(),
};
let scopes_match = ImportMap::resolve_scopes_match(
&self.scopes,
&normalized_specifier,
&referrer.to_string(),
)?;
// match found in scopes map
if scopes_match.is_some() {
return Ok(scopes_match);
}
let imports_match =
ImportMap::resolve_imports_match(&self.imports, &normalized_specifier)?;
// match found in import map
if imports_match.is_some() {
return Ok(imports_match);
}
// no match in import map but we got resolvable URL
if let Some(resolved_url) = resolved_url {
return Ok(Some(ModuleSpecifier::from(resolved_url)));
}
Err(ImportMapError::new(&format!(
"Unmapped bare specifier {:?}",
normalized_specifier
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn load_nonexistent() {
let file_path = "nonexistent_import_map.json";
assert!(ImportMap::load(file_path).is_err());
}
#[test]
fn from_json_1() {
let base_url = "https://deno.land";
// empty JSON
assert!(ImportMap::from_json(base_url, "{}").is_ok());
let non_object_strings = vec!["null", "true", "1", "\"foo\"", "[]"];
// invalid JSON
for non_object in non_object_strings.to_vec() {
assert!(ImportMap::from_json(base_url, non_object).is_err());
}
// invalid schema: 'imports' is non-object
for non_object in non_object_strings.to_vec() {
assert!(ImportMap::from_json(
base_url,
&format!("{{\"imports\": {}}}", non_object),
)
.is_err());
}
// invalid schema: 'scopes' is non-object
for non_object in non_object_strings.to_vec() {
assert!(ImportMap::from_json(
base_url,
&format!("{{\"scopes\": {}}}", non_object),
)
.is_err());
}
}
#[test]
fn from_json_2() {
let json_map = r#"{
"imports": {
"foo": "https://example.com/1",
"bar": ["https://example.com/2"],
"fizz": null
}
}"#;
let result = ImportMap::from_json("https://deno.land", json_map);
assert!(result.is_ok());
}
#[test]
fn parse_specifier_keys_relative() {
// Should absolutize strings prefixed with ./, ../, or / into the corresponding URLs..
let json_map = r#"{
"imports": {
"./foo": "/dotslash",
"../foo": "/dotdotslash",
"/foo": "/slash"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map
.imports
.get("https://base.example/path1/path2/foo")
.unwrap()[0],
"https://base.example/dotslash".to_string()
);
assert_eq!(
import_map
.imports
.get("https://base.example/path1/foo")
.unwrap()[0],
"https://base.example/dotdotslash".to_string()
);
assert_eq!(
import_map.imports.get("https://base.example/foo").unwrap()[0],
"https://base.example/slash".to_string()
);
// Should absolutize the literal strings ./, ../, or / with no suffix..
let json_map = r#"{
"imports": {
"./": "/dotslash/",
"../": "/dotdotslash/",
"/": "/slash/"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map
.imports
.get("https://base.example/path1/path2/")
.unwrap()[0],
"https://base.example/dotslash/".to_string()
);
assert_eq!(
import_map
.imports
.get("https://base.example/path1/")
.unwrap()[0],
"https://base.example/dotdotslash/".to_string()
);
assert_eq!(
import_map.imports.get("https://base.example/").unwrap()[0],
"https://base.example/slash/".to_string()
);
// Should treat percent-encoded variants of ./, ../, or / as bare specifiers..
let json_map = r#"{
"imports": {
"%2E/": "/dotSlash1/",
"%2E%2E/": "/dotDotSlash1/",
".%2F": "/dotSlash2",
"..%2F": "/dotDotSlash2",
"%2F": "/slash2",
"%2E%2F": "/dotSlash3",
"%2E%2E%2F": "/dotDotSlash3"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map.imports.get("%2E/").unwrap()[0],
"https://base.example/dotSlash1/".to_string()
);
assert_eq!(
import_map.imports.get("%2E%2E/").unwrap()[0],
"https://base.example/dotDotSlash1/".to_string()
);
assert_eq!(
import_map.imports.get(".%2F").unwrap()[0],
"https://base.example/dotSlash2".to_string()
);
assert_eq!(
import_map.imports.get("..%2F").unwrap()[0],
"https://base.example/dotDotSlash2".to_string()
);
assert_eq!(
import_map.imports.get("%2F").unwrap()[0],
"https://base.example/slash2".to_string()
);
assert_eq!(
import_map.imports.get("%2E%2F").unwrap()[0],
"https://base.example/dotSlash3".to_string()
);
assert_eq!(
import_map.imports.get("%2E%2E%2F").unwrap()[0],
"https://base.example/dotDotSlash3".to_string()
);
}
#[test]
fn parse_specifier_keys_absolute() {
// Should only accept absolute URL specifier keys with fetch schemes,.
// treating others as bare specifiers.
let json_map = r#"{
"imports": {
"file:https:///good": "/file",
"http:https://good/": "/http/",
"https://good/": "/https/",
"about:bad": "/about",
"blob:bad": "/blob",
"data:bad": "/data",
"filesystem:bad": "/filesystem",
"ftp:https://bad/": "/ftp/",
"import:bad": "/import",
"mailto:bad": "/mailto",
"javascript:bad": "/javascript",
"wss:bad": "/wss"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map.imports.get("http:https://good/").unwrap()[0],
"https://base.example/http/".to_string()
);
assert_eq!(
import_map.imports.get("https://good/").unwrap()[0],
"https://base.example/https/".to_string()
);
assert_eq!(
import_map.imports.get("file:https:///good").unwrap()[0],
"https://base.example/file".to_string()
);
assert_eq!(
import_map.imports.get("http:https://good/").unwrap()[0],
"https://base.example/http/".to_string()
);
assert_eq!(
import_map.imports.get("import:bad").unwrap()[0],
"https://base.example/import".to_string()
);
assert_eq!(
import_map.imports.get("mailto:bad").unwrap()[0],
"https://base.example/mailto".to_string()
);
assert_eq!(
import_map.imports.get("javascript:bad").unwrap()[0],
"https://base.example/javascript".to_string()
);
assert_eq!(
import_map.imports.get("wss:bad").unwrap()[0],
"https://base.example/wss".to_string()
);
assert_eq!(
import_map.imports.get("about:bad").unwrap()[0],
"https://base.example/about".to_string()
);
assert_eq!(
import_map.imports.get("blob:bad").unwrap()[0],
"https://base.example/blob".to_string()
);
assert_eq!(
import_map.imports.get("data:bad").unwrap()[0],
"https://base.example/data".to_string()
);
// Should parse absolute URLs, treating unparseable ones as bare specifiers..
let json_map = r#"{
"imports": {
"https://ex ample.org/": "/unparseable1/",
"https://example.com:demo": "/unparseable2",
"http:https://[www.example.com]/": "/unparseable3/",
"https:example.org": "/invalidButParseable1/",
"https://///example.com///": "/invalidButParseable2/",
"https://example.net": "/prettyNormal/",
"https://ex%41mple.com/": "/percentDecoding/",
"https://example.com/%41": "/noPercentDecoding"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map.imports.get("https://ex ample.org/").unwrap()[0],
"https://base.example/unparseable1/".to_string()
);
assert_eq!(
import_map.imports.get("https://example.com:demo").unwrap()[0],
"https://base.example/unparseable2".to_string()
);
assert_eq!(
import_map.imports.get("http:https://[www.example.com]/").unwrap()[0],
"https://base.example/unparseable3/".to_string()
);
assert_eq!(
import_map.imports.get("https://example.org/").unwrap()[0],
"https://base.example/invalidButParseable1/".to_string()
);
assert_eq!(
import_map.imports.get("https://example.com///").unwrap()[0],
"https://base.example/invalidButParseable2/".to_string()
);
assert_eq!(
import_map.imports.get("https://example.net/").unwrap()[0],
"https://base.example/prettyNormal/".to_string()
);
assert_eq!(
import_map.imports.get("https://example.com/").unwrap()[0],
"https://base.example/percentDecoding/".to_string()
);
assert_eq!(
import_map.imports.get("https://example.com/%41").unwrap()[0],
"https://base.example/noPercentDecoding".to_string()
);
}
#[test]
fn parse_scope_keys_relative() {
// Should work with no prefix..
let json_map = r#"{
"scopes": {
"foo": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/foo"));
// Should work with ./, ../, and / prefixes..
let json_map = r#"{
"scopes": {
"./foo": {},
"../foo": {},
"/foo": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/foo"));
assert!(import_map
.scopes
.contains_key("https://base.example/path1/foo"));
assert!(import_map.scopes.contains_key("https://base.example/foo"));
// Should work with /s, ?s, and #s..
let json_map = r#"{
"scopes": {
"foo/bar?baz#qux": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/foo/bar?baz#qux"));
// Should work with an empty string scope key..
let json_map = r#"{
"scopes": {
"": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/path3"));
// Should work with / suffixes..
let json_map = r#"{
"scopes": {
"foo/": {},
"./foo/": {},
"../foo/": {},
"/foo/": {},
"/foo//": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/foo/"));
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/foo/"));
assert!(import_map
.scopes
.contains_key("https://base.example/path1/foo/"));
assert!(import_map.scopes.contains_key("https://base.example/foo/"));
assert!(import_map.scopes.contains_key("https://base.example/foo//"));
// Should deduplicate based on URL parsing rules..
let json_map = r#"{
"scopes": {
"foo/\\": {},
"foo//": {},
"foo\\\\": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/foo//"));
assert_eq!(import_map.scopes.len(), 1);
}
#[test]
fn parse_scope_keys_absolute() {
// Should only accept absolute URL scope keys with fetch schemes..
let json_map = r#"{
"scopes": {
"http:https://good/": {},
"https://good/": {},
"file:https:///good": {},
"about:bad": {},
"blob:bad": {},
"data:bad": {},
"filesystem:bad": {},
"ftp:https://bad/": {},
"import:bad": {},
"mailto:bad": {},
"javascript:bad": {},
"wss:bad": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map.scopes.contains_key("http:https://good/"));
assert!(import_map.scopes.contains_key("https://good/"));
assert!(import_map.scopes.contains_key("file:https:///good"));
assert_eq!(import_map.scopes.len(), 3);
// Should parse absolute URL scope keys, ignoring unparseable ones..
let json_map = r#"{
"scopes": {
"https://ex ample.org/": {},
"https://example.com:demo": {},
"http:https://[www.example.com]/": {},
"https:example.org": {},
"https://///example.com///": {},
"https://example.net": {},
"https://ex%41mple.com/foo/": {},
"https://example.com/%41": {}
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
// tricky case! remember we have a base URL
assert!(import_map
.scopes
.contains_key("https://base.example/path1/path2/example.org"));
assert!(import_map.scopes.contains_key("https://example.com///"));
assert!(import_map.scopes.contains_key("https://example.net/"));
assert!(import_map.scopes.contains_key("https://example.com/foo/"));
assert!(import_map.scopes.contains_key("https://example.com/%41"));
assert_eq!(import_map.scopes.len(), 5);
}
#[test]
fn parse_addresses_relative_url_like() {
// Should accept strings prefixed with ./, ../, or /..
let json_map = r#"{
"imports": {
"dotSlash": "./foo",
"dotDotSlash": "../foo",
"slash": "/foo"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map.imports.get("dotSlash").unwrap(),
&vec!["https://base.example/path1/path2/foo".to_string()]
);
assert_eq!(
import_map.imports.get("dotDotSlash").unwrap(),
&vec!["https://base.example/path1/foo".to_string()]
);
assert_eq!(
import_map.imports.get("slash").unwrap(),
&vec!["https://base.example/foo".to_string()]
);
// Should accept the literal strings ./, ../, or / with no suffix..
let json_map = r#"{
"imports": {
"dotSlash": "./",
"dotDotSlash": "../",
"slash": "/"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert_eq!(
import_map.imports.get("dotSlash").unwrap(),
&vec!["https://base.example/path1/path2/".to_string()]
);
assert_eq!(
import_map.imports.get("dotDotSlash").unwrap(),
&vec!["https://base.example/path1/".to_string()]
);
assert_eq!(
import_map.imports.get("slash").unwrap(),
&vec!["https://base.example/".to_string()]
);
// Should ignore percent-encoded variants of ./, ../, or /..
let json_map = r#"{
"imports": {
"dotSlash1": "%2E/",
"dotDotSlash1": "%2E%2E/",
"dotSlash2": ".%2F",
"dotDotSlash2": "..%2F",
"slash2": "%2F",
"dotSlash3": "%2E%2F",
"dotDotSlash3": "%2E%2E%2F"
}
}"#;
let import_map =
ImportMap::from_json("https://base.example/path1/path2/path3", json_map)
.unwrap();
assert!(import_map.imports.get("dotSlash1").unwrap().is_empty());
assert!(import_map.imports.get("dotDotSlash1").unwrap().is_empty());
assert!(import_map.imports.get("dotSlash2").unwrap().is_empty());
assert!(import_map.imports.get("dotDotSlash2").unwrap().is_empty());
assert!(import_map.imports.get("slash2").unwrap().is_empty());
assert!(import_map.imports.get("dotSlash3").unwrap().is_empty());
assert!(import_map.imports.get("dotDotSlash3").unwrap().is_empty());
}
#[test]
fn parse_addresses_absolute_with_fetch_schemes() {
// Should only accept absolute URL addresses with fetch schemes..
let json_map = r#"{
"imports": {
"http": "http:https://good/",
"https": "https://good/",
"file": "file:https:///good",
"about": "about:bad",
"blob": "blob:bad",
"data": "data:bad",
"filesystem": "filesystem:bad",
"ftp": "ftp:https://good/",
"import": "import:bad",
"mailto": "mailto:bad",
"javascript": "javascript:bad",