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
|
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use std::collections::BTreeMap;
use deno_ast::LineAndColumnIndex;
use deno_ast::ModuleSpecifier;
use deno_ast::SourceTextInfo;
use deno_core::serde_json;
use deno_graph::Module;
use deno_graph::ModuleGraph;
use deno_graph::Position;
use deno_graph::Range;
use deno_graph::Resolved;
use serde::Serialize;
use super::mappings::Mappings;
use super::specifiers::is_remote_specifier;
use super::specifiers::is_remote_specifier_text;
#[derive(Serialize)]
struct SerializableImportMap {
imports: BTreeMap<String, String>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
scopes: BTreeMap<String, BTreeMap<String, String>>,
}
struct ImportMapBuilder<'a> {
mappings: &'a Mappings,
imports: ImportsBuilder<'a>,
scopes: BTreeMap<String, ImportsBuilder<'a>>,
}
impl<'a> ImportMapBuilder<'a> {
pub fn new(mappings: &'a Mappings) -> Self {
ImportMapBuilder {
mappings,
imports: ImportsBuilder::new(mappings),
scopes: Default::default(),
}
}
pub fn scope(
&mut self,
base_specifier: &ModuleSpecifier,
) -> &mut ImportsBuilder<'a> {
self
.scopes
.entry(
self
.mappings
.relative_specifier_text(self.mappings.output_dir(), base_specifier),
)
.or_insert_with(|| ImportsBuilder::new(self.mappings))
}
pub fn into_serializable(self) -> SerializableImportMap {
SerializableImportMap {
imports: self.imports.imports,
scopes: self
.scopes
.into_iter()
.map(|(key, value)| (key, value.imports))
.collect(),
}
}
pub fn into_file_text(self) -> String {
let mut text =
serde_json::to_string_pretty(&self.into_serializable()).unwrap();
text.push('\n');
text
}
}
struct ImportsBuilder<'a> {
mappings: &'a Mappings,
imports: BTreeMap<String, String>,
}
impl<'a> ImportsBuilder<'a> {
pub fn new(mappings: &'a Mappings) -> Self {
Self {
mappings,
imports: Default::default(),
}
}
pub fn add(&mut self, key: String, specifier: &ModuleSpecifier) {
self.imports.insert(
key,
self
.mappings
.relative_specifier_text(self.mappings.output_dir(), specifier),
);
}
}
pub fn build_import_map(
graph: &ModuleGraph,
modules: &[&Module],
mappings: &Mappings,
) -> String {
let mut import_map = ImportMapBuilder::new(mappings);
visit_modules(graph, modules, mappings, &mut import_map);
for base_specifier in mappings.base_specifiers() {
import_map
.imports
.add(base_specifier.to_string(), base_specifier);
}
import_map.into_file_text()
}
fn visit_modules(
graph: &ModuleGraph,
modules: &[&Module],
mappings: &Mappings,
import_map: &mut ImportMapBuilder,
) {
for module in modules {
let text_info = match &module.maybe_parsed_source {
Some(source) => source.source(),
None => continue,
};
let source_text = match &module.maybe_source {
Some(source) => source,
None => continue,
};
for dep in module.dependencies.values() {
visit_maybe_resolved(
&dep.maybe_code,
graph,
import_map,
&module.specifier,
mappings,
text_info,
source_text,
);
visit_maybe_resolved(
&dep.maybe_type,
graph,
import_map,
&module.specifier,
mappings,
text_info,
source_text,
);
}
if let Some((_, maybe_resolved)) = &module.maybe_types_dependency {
visit_maybe_resolved(
maybe_resolved,
graph,
import_map,
&module.specifier,
mappings,
text_info,
source_text,
);
}
}
}
fn visit_maybe_resolved(
maybe_resolved: &Resolved,
graph: &ModuleGraph,
import_map: &mut ImportMapBuilder,
referrer: &ModuleSpecifier,
mappings: &Mappings,
text_info: &SourceTextInfo,
source_text: &str,
) {
if let Resolved::Ok {
specifier, range, ..
} = maybe_resolved
{
let text = text_from_range(text_info, source_text, range);
// if the text is empty then it's probably an x-TypeScript-types
if !text.is_empty() {
handle_dep_specifier(
text, specifier, graph, import_map, referrer, mappings,
);
}
}
}
fn handle_dep_specifier(
text: &str,
unresolved_specifier: &ModuleSpecifier,
graph: &ModuleGraph,
import_map: &mut ImportMapBuilder,
referrer: &ModuleSpecifier,
mappings: &Mappings,
) {
let specifier = graph.resolve(unresolved_specifier);
// do not handle specifiers pointing at local modules
if !is_remote_specifier(&specifier) {
return;
}
let base_specifier = mappings.base_specifier(&specifier);
if is_remote_specifier_text(text) {
if !text.starts_with(base_specifier.as_str()) {
panic!("Expected {} to start with {}", text, base_specifier);
}
let sub_path = &text[base_specifier.as_str().len()..];
let expected_relative_specifier_text =
mappings.relative_path(base_specifier, &specifier);
if expected_relative_specifier_text == sub_path {
return;
}
import_map.imports.add(text.to_string(), &specifier);
} else {
let expected_relative_specifier_text =
mappings.relative_specifier_text(referrer, &specifier);
if expected_relative_specifier_text == text {
return;
}
let key = if text.starts_with("./") || text.starts_with("../") {
// resolve relative specifier key
let mut local_base_specifier = mappings.local_uri(base_specifier);
local_base_specifier.set_query(unresolved_specifier.query());
local_base_specifier = local_base_specifier
.join(&unresolved_specifier.path()[1..])
.unwrap_or_else(|_| {
panic!(
"Error joining {} to {}",
unresolved_specifier.path(),
local_base_specifier
)
});
local_base_specifier.set_query(unresolved_specifier.query());
mappings
.relative_specifier_text(mappings.output_dir(), &local_base_specifier)
} else {
// absolute (`/`) or bare specifier should be left as-is
text.to_string()
};
let imports = import_map.scope(base_specifier);
imports.add(key, &specifier);
}
}
fn text_from_range<'a>(
text_info: &SourceTextInfo,
text: &'a str,
range: &Range,
) -> &'a str {
let result = &text[byte_range(text_info, range)];
if result.starts_with('"') || result.starts_with('\'') {
// remove the quotes
&result[1..result.len() - 1]
} else {
result
}
}
fn byte_range(
text_info: &SourceTextInfo,
range: &Range,
) -> std::ops::Range<usize> {
let start = byte_index(text_info, &range.start);
let end = byte_index(text_info, &range.end);
start..end
}
fn byte_index(text_info: &SourceTextInfo, pos: &Position) -> usize {
// todo(https://github.com/denoland/deno_graph/issues/79): use byte indexes all the way down
text_info
.byte_index(LineAndColumnIndex {
line_index: pos.line,
column_index: pos.character,
})
.0 as usize
}
|