/
next_import_map.rs
792 lines (730 loc) · 27.4 KB
/
next_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
use std::collections::{BTreeMap, HashMap};
use anyhow::{Context, Result};
use turbo_tasks::{Value, Vc};
use turbopack_binding::{
turbo::tasks_fs::{glob::Glob, FileSystem, FileSystemPath},
turbopack::{
core::{
resolve::{
options::{ConditionValue, ImportMap, ImportMapping, ResolveOptions, ResolvedMap},
parse::Request,
pattern::Pattern,
resolve, AliasPattern, ResolveAliasMap, SubpathValue,
},
source::Source,
},
node::execution_context::ExecutionContext,
turbopack::{resolve_options, resolve_options_context::ResolveOptionsContext},
},
};
use crate::{
embed_js::{next_js_fs, VIRTUAL_PACKAGE_NAME},
mode::NextMode,
next_client::context::ClientContextType,
next_config::NextConfig,
next_font::{
google::{NextFontGoogleCssModuleReplacer, NextFontGoogleReplacer},
local::{NextFontLocalCssModuleReplacer, NextFontLocalReplacer},
},
next_server::context::ServerContextType,
util::NextRuntime,
};
// Make sure to not add any external requests here.
/// Computes the Next-specific client import map.
#[turbo_tasks::function]
pub async fn get_next_client_import_map(
project_path: Vc<FileSystemPath>,
ty: Value<ClientContextType>,
mode: NextMode,
next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty();
insert_next_shared_aliases(
&mut import_map,
project_path,
execution_context,
next_config,
mode,
)
.await?;
insert_alias_option(
&mut import_map,
project_path,
next_config.resolve_alias_options(),
["browser"],
)
.await?;
match ty.into_value() {
ClientContextType::Pages { pages_dir } => {
insert_alias_to_alternatives(
&mut import_map,
format!("{VIRTUAL_PACKAGE_NAME}/pages/_app"),
vec![
request_to_import_mapping(pages_dir, "./_app"),
request_to_import_mapping(pages_dir, "next/app"),
],
);
insert_alias_to_alternatives(
&mut import_map,
format!("{VIRTUAL_PACKAGE_NAME}/pages/_document"),
vec![
request_to_import_mapping(pages_dir, "./_document"),
request_to_import_mapping(pages_dir, "next/document"),
],
);
insert_alias_to_alternatives(
&mut import_map,
format!("{VIRTUAL_PACKAGE_NAME}/pages/_error"),
vec![
request_to_import_mapping(pages_dir, "./_error"),
request_to_import_mapping(pages_dir, "next/error"),
],
);
}
ClientContextType::App { app_dir } => {
import_map.insert_exact_alias(
"react",
request_to_import_mapping(app_dir, "next/dist/compiled/react"),
);
import_map.insert_wildcard_alias(
"react/",
request_to_import_mapping(app_dir, "next/dist/compiled/react/*"),
);
import_map.insert_exact_alias(
"react-dom",
request_to_import_mapping(app_dir, "next/dist/compiled/react-dom"),
);
import_map.insert_wildcard_alias(
"react-dom/",
request_to_import_mapping(app_dir, "next/dist/compiled/react-dom/*"),
);
import_map.insert_wildcard_alias(
"react-server-dom-webpack/",
request_to_import_mapping(app_dir, "next/dist/compiled/react-server-dom-webpack/*"),
);
import_map.insert_exact_alias(
"next/dynamic",
request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"),
);
}
ClientContextType::Fallback => {}
ClientContextType::Other => {}
}
match ty.into_value() {
ClientContextType::Pages { .. }
| ClientContextType::App { .. }
| ClientContextType::Fallback => {
for (original, alias) in NEXT_ALIASES {
import_map.insert_exact_alias(
format!("node:{original}"),
request_to_import_mapping(project_path, alias),
);
}
}
ClientContextType::Other => {}
}
insert_turbopack_dev_alias(&mut import_map);
Ok(import_map.cell())
}
/// Computes the Next-specific client import map.
#[turbo_tasks::function]
pub fn get_next_build_import_map() -> Vc<ImportMap> {
let mut import_map = ImportMap::empty();
insert_package_alias(
&mut import_map,
&format!("{VIRTUAL_PACKAGE_NAME}/"),
next_js_fs().root(),
);
let external = ImportMapping::External(None).cell();
import_map.insert_exact_alias("next", external);
import_map.insert_wildcard_alias("next/", external);
import_map.insert_exact_alias("styled-jsx", external);
import_map.insert_wildcard_alias("styled-jsx/", external);
import_map.cell()
}
/// Computes the Next-specific client fallback import map, which provides
/// polyfills to Node.js externals.
#[turbo_tasks::function]
pub fn get_next_client_fallback_import_map(ty: Value<ClientContextType>) -> Vc<ImportMap> {
let mut import_map = ImportMap::empty();
match ty.into_value() {
ClientContextType::Pages {
pages_dir: context_dir,
}
| ClientContextType::App {
app_dir: context_dir,
} => {
for (original, alias) in NEXT_ALIASES {
import_map
.insert_exact_alias(original, request_to_import_mapping(context_dir, alias));
}
}
ClientContextType::Fallback => {}
ClientContextType::Other => {}
}
insert_turbopack_dev_alias(&mut import_map);
import_map.cell()
}
/// Computes the Next-specific server-side import map.
#[turbo_tasks::function]
pub async fn get_next_server_import_map(
project_path: Vc<FileSystemPath>,
ty: Value<ServerContextType>,
mode: NextMode,
next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty();
insert_next_shared_aliases(
&mut import_map,
project_path,
execution_context,
next_config,
mode,
)
.await?;
insert_alias_option(
&mut import_map,
project_path,
next_config.resolve_alias_options(),
[],
)
.await?;
let ty = ty.into_value();
insert_next_server_special_aliases(
&mut import_map,
project_path,
ty,
mode,
NextRuntime::NodeJs,
)
.await?;
let external: Vc<ImportMapping> = ImportMapping::External(None).cell();
import_map.insert_exact_alias("next/dist/server/require-hook", external);
match ty {
ServerContextType::Pages { .. } | ServerContextType::PagesData { .. } => {
import_map.insert_exact_alias("react", external);
import_map.insert_wildcard_alias("react/", external);
import_map.insert_exact_alias("react-dom", external);
import_map.insert_wildcard_alias("react-dom/", external);
import_map.insert_exact_alias("styled-jsx", external);
import_map.insert_wildcard_alias("styled-jsx/", external);
import_map.insert_wildcard_alias("react-server-dom-webpack/", external);
// TODO: we should not bundle next/dist/build/utils in the pages renderer at all
import_map.insert_wildcard_alias("next/dist/build/utils", external);
}
ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } => {
match mode {
NextMode::Build => {
import_map.insert_wildcard_alias("next/dist/server/", external);
import_map.insert_wildcard_alias("next/dist/shared/", external);
}
NextMode::DevServer => {
// The sandbox can't be bundled and needs to be external
import_map.insert_exact_alias("next/dist/server/web/sandbox", external);
}
NextMode::Development => {}
}
import_map.insert_exact_alias(
"next/head",
request_to_import_mapping(project_path, "next/dist/client/components/noop-head"),
);
import_map.insert_exact_alias(
"next/dynamic",
request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"),
);
}
ServerContextType::Middleware => {}
}
Ok(import_map.cell())
}
/// Computes the Next-specific edge-side import map.
#[turbo_tasks::function]
pub async fn get_next_edge_import_map(
project_path: Vc<FileSystemPath>,
ty: Value<ServerContextType>,
mode: NextMode,
next_config: Vc<NextConfig>,
execution_context: Vc<ExecutionContext>,
) -> Result<Vc<ImportMap>> {
let mut import_map = ImportMap::empty();
insert_next_shared_aliases(
&mut import_map,
project_path,
execution_context,
next_config,
mode,
)
.await?;
insert_alias_option(
&mut import_map,
project_path,
next_config.resolve_alias_options(),
[],
)
.await?;
let ty = ty.into_value();
insert_next_server_special_aliases(&mut import_map, project_path, ty, mode, NextRuntime::Edge)
.await?;
match ty {
ServerContextType::Pages { .. } | ServerContextType::PagesData { .. } => {}
ServerContextType::AppSSR { .. }
| ServerContextType::AppRSC { .. }
| ServerContextType::AppRoute { .. } => {
import_map.insert_exact_alias(
"next/head",
request_to_import_mapping(project_path, "next/dist/client/components/noop-head"),
);
import_map.insert_exact_alias(
"next/dynamic",
request_to_import_mapping(project_path, "next/dist/shared/lib/app-dynamic"),
);
}
ServerContextType::Middleware => {}
}
Ok(import_map.cell())
}
pub fn get_next_client_resolved_map(
context: Vc<FileSystemPath>,
root: Vc<FileSystemPath>,
mode: NextMode,
) -> Vc<ResolvedMap> {
let glob_mappings = if mode == NextMode::Development {
vec![]
} else {
vec![
// Temporary hack to replace the hot reloader until this is passable by props in
// next.js
(
context.root(),
Glob::new(
"**/next/dist/client/components/react-dev-overlay/hot-reloader-client.js"
.to_string(),
),
ImportMapping::PrimaryAlternative(
"@vercel/turbopack-next/dev/hot-reloader.tsx".to_string(),
Some(root),
)
.into(),
),
]
};
ResolvedMap {
by_glob: glob_mappings,
}
.cell()
}
static NEXT_ALIASES: [(&str, &str); 23] = [
("assert", "next/dist/compiled/assert"),
("buffer", "next/dist/compiled/buffer"),
("constants", "next/dist/compiled/constants-browserify"),
("crypto", "next/dist/compiled/crypto-browserify"),
("domain", "next/dist/compiled/domain-browser"),
("http", "next/dist/compiled/stream-http"),
("https", "next/dist/compiled/https-browserify"),
("os", "next/dist/compiled/os-browserify"),
("path", "next/dist/compiled/path-browserify"),
("punycode", "next/dist/compiled/punycode"),
("process", "next/dist/build/polyfills/process"),
("querystring", "next/dist/compiled/querystring-es3"),
("stream", "next/dist/compiled/stream-browserify"),
("string_decoder", "next/dist/compiled/string_decoder"),
("sys", "next/dist/compiled/util"),
("timers", "next/dist/compiled/timers-browserify"),
("tty", "next/dist/compiled/tty-browserify"),
("url", "next/dist/compiled/native-url"),
("util", "next/dist/compiled/util"),
("vm", "next/dist/compiled/vm-browserify"),
("zlib", "next/dist/compiled/browserify-zlib"),
("events", "next/dist/compiled/events"),
("setImmediate", "next/dist/compiled/setimmediate"),
];
async fn insert_next_server_special_aliases(
import_map: &mut ImportMap,
project_path: Vc<FileSystemPath>,
ty: ServerContextType,
mode: NextMode,
runtime: NextRuntime,
) -> Result<()> {
let external_if_node = move |context_dir: Vc<FileSystemPath>, request: &str| match runtime {
NextRuntime::Edge => request_to_import_mapping(context_dir, request),
NextRuntime::NodeJs => external_request_to_import_mapping(request),
};
let passthrough_external_if_node =
move |context_dir: Vc<FileSystemPath>, request: &str| match runtime {
NextRuntime::Edge => request_to_import_mapping(context_dir, request),
NextRuntime::NodeJs => ImportMapping::External(None).cell(),
};
match (mode, ty) {
(_, ServerContextType::Pages { pages_dir }) => {
import_map.insert_exact_alias(
"@opentelemetry/api",
// TODO(WEB-625) this actually need to prefer the local version of
// @opentelemetry/api
external_if_node(pages_dir, "next/dist/compiled/@opentelemetry/api"),
);
insert_alias_to_alternatives(
import_map,
format!("{VIRTUAL_PACKAGE_NAME}/pages/_app"),
vec![
request_to_import_mapping(pages_dir, "./_app"),
external_if_node(pages_dir, "next/app"),
],
);
insert_alias_to_alternatives(
import_map,
format!("{VIRTUAL_PACKAGE_NAME}/pages/_document"),
vec![
request_to_import_mapping(pages_dir, "./_document"),
external_if_node(pages_dir, "next/document"),
],
);
insert_alias_to_alternatives(
import_map,
format!("{VIRTUAL_PACKAGE_NAME}/pages/_error"),
vec![
request_to_import_mapping(pages_dir, "./_error"),
external_if_node(pages_dir, "next/error"),
],
);
}
(_, ServerContextType::PagesData { .. }) => {}
// In development, we *always* use the bundled version of React, even in
// SSR, since we're bundling Next.js alongside it.
(NextMode::DevServer, ServerContextType::AppSSR { app_dir }) => {
import_map.insert_exact_alias(
"@opentelemetry/api",
// TODO(WEB-625) this actually need to prefer the local version of
// @opentelemetry/api
request_to_import_mapping(app_dir, "next/dist/compiled/@opentelemetry/api"),
);
import_map.insert_exact_alias(
"react",
passthrough_external_if_node(app_dir, "next/dist/compiled/react"),
);
import_map.insert_wildcard_alias(
"react/",
passthrough_external_if_node(app_dir, "next/dist/compiled/react/*"),
);
import_map.insert_exact_alias(
"react-dom",
passthrough_external_if_node(
app_dir,
"next/dist/compiled/react-dom/server-rendering-stub.js",
),
);
import_map.insert_wildcard_alias(
"react-dom/",
passthrough_external_if_node(app_dir, "next/dist/compiled/react-dom/*"),
);
import_map.insert_exact_alias(
"styled-jsx",
passthrough_external_if_node(app_dir, "next/dist/compiled/styled-jsx"),
);
import_map.insert_wildcard_alias(
"styled-jsx/",
passthrough_external_if_node(app_dir, "next/dist/compiled/styled-jsx/*"),
);
import_map.insert_wildcard_alias(
"react-server-dom-webpack/",
passthrough_external_if_node(
app_dir,
"next/dist/compiled/react-server-dom-webpack/*",
),
);
}
// NOTE(alexkirsz) This logic maps loosely to
// `next.js/packages/next/src/build/webpack-config.ts`, where:
//
// ## RSC
//
// * always bundles
// * maps react -> react/shared-subset (through the "react-server" exports condition)
// * maps react-dom -> react-dom/server-rendering-stub
// * passes through (react|react-dom|react-server-dom-webpack)/(.*) to
// next/dist/compiled/$1/$2
(
NextMode::Build | NextMode::Development | NextMode::DevServer,
ServerContextType::AppRSC { app_dir, .. } | ServerContextType::AppRoute { app_dir },
) => {
import_map.insert_exact_alias(
"@opentelemetry/api",
// TODO(WEB-625) this actually need to prefer the local version of
// @opentelemetry/api
request_to_import_mapping(app_dir, "next/dist/compiled/@opentelemetry/api"),
);
if matches!(ty, ServerContextType::AppRSC { .. }) {
import_map.insert_exact_alias(
"react",
request_to_import_mapping(
app_dir,
"next/dist/compiled/react/react.shared-subset",
),
);
} else {
import_map.insert_exact_alias(
"react",
request_to_import_mapping(app_dir, "next/dist/compiled/react"),
);
}
import_map.insert_exact_alias(
"react-dom",
request_to_import_mapping(
app_dir,
"next/dist/compiled/react-dom/server-rendering-stub",
),
);
for (wildcard_alias, request) in [
("react/", "next/dist/compiled/react/*"),
("react-dom/", "next/dist/compiled/react-dom/*"),
(
"react-server-dom-webpack/",
"next/dist/compiled/react-server-dom-webpack/*",
),
] {
import_map.insert_wildcard_alias(
wildcard_alias,
request_to_import_mapping(app_dir, request),
);
}
}
// ## SSR
//
// * always uses externals, to ensure we're using the same React instance as the Next.js
// runtime
// * maps react-dom -> react-dom/server-rendering-stub
// * passes through react and (react|react-dom|react-server-dom-webpack)/(.*) to
// next/dist/compiled/react and next/dist/compiled/$1/$2 resp.
(NextMode::Build | NextMode::Development, ServerContextType::AppSSR { app_dir }) => {
import_map.insert_exact_alias(
"react",
external_if_node(app_dir, "next/dist/compiled/react"),
);
import_map.insert_exact_alias(
"react-dom",
external_if_node(
app_dir,
"next/dist/compiled/react-dom/server-rendering-stub",
),
);
for (wildcard_alias, request) in [
("react/", "next/dist/compiled/react/*"),
("react-dom/", "next/dist/compiled/react-dom/*"),
(
"react-server-dom-webpack/",
"next/dist/compiled/react-server-dom-webpack/*",
),
] {
let import_mapping = external_if_node(app_dir, request);
import_map.insert_wildcard_alias(wildcard_alias, import_mapping);
}
}
(_, ServerContextType::Middleware) => {}
}
import_map.insert_exact_alias(
"@vercel/og",
external_if_node(
project_path,
"next/dist/server/web/spec-extension/image-response",
),
);
Ok(())
}
pub fn mdx_import_source_file() -> String {
format!("{VIRTUAL_PACKAGE_NAME}/mdx-import-source")
}
// Make sure to not add any external requests here.
pub async fn insert_next_shared_aliases(
import_map: &mut ImportMap,
project_path: Vc<FileSystemPath>,
execution_context: Vc<ExecutionContext>,
next_config: Vc<NextConfig>,
mode: NextMode,
) -> Result<()> {
let package_root = next_js_fs().root();
if *next_config.mdx_rs().await? {
insert_alias_to_alternatives(
import_map,
mdx_import_source_file(),
vec![
request_to_import_mapping(project_path, "./mdx-components"),
request_to_import_mapping(project_path, "./src/mdx-components"),
request_to_import_mapping(project_path, "@mdx-js/react"),
],
);
}
if mode != NextMode::Development {
// we use the next.js hydration code, so we replace the error overlay with our
// own
import_map.insert_exact_alias(
"next/dist/compiled/@next/react-dev-overlay/dist/client",
request_to_import_mapping(package_root, "./overlay/client.ts"),
);
}
insert_package_alias(
import_map,
&format!("{VIRTUAL_PACKAGE_NAME}/"),
package_root,
);
import_map.insert_alias(
// Request path from js via next-font swc transform
AliasPattern::exact("next/font/google/target.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontGoogleReplacer::new(project_path))).into(),
);
import_map.insert_alias(
// Request path from js via next-font swc transform
AliasPattern::exact("@next/font/google/target.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontGoogleReplacer::new(project_path))).into(),
);
import_map.insert_alias(
AliasPattern::exact("@vercel/turbopack-next/internal/font/google/cssmodule.module.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontGoogleCssModuleReplacer::new(
project_path,
execution_context,
)))
.into(),
);
import_map.insert_alias(
// Request path from js via next-font swc transform
AliasPattern::exact("next/font/local/target.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalReplacer::new(project_path))).into(),
);
import_map.insert_alias(
// Request path from js via next-font swc transform
AliasPattern::exact("@next/font/local/target.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalReplacer::new(project_path))).into(),
);
import_map.insert_alias(
AliasPattern::exact("@vercel/turbopack-next/internal/font/local/cssmodule.module.css"),
ImportMapping::Dynamic(Vc::upcast(NextFontLocalCssModuleReplacer::new(
project_path,
)))
.into(),
);
import_map.insert_singleton_alias("@swc/helpers", get_next_package(project_path));
import_map.insert_singleton_alias("styled-jsx", get_next_package(project_path));
import_map.insert_singleton_alias("next", project_path);
import_map.insert_singleton_alias("react", project_path);
import_map.insert_singleton_alias("react-dom", project_path);
insert_turbopack_dev_alias(import_map);
insert_package_alias(
import_map,
"@vercel/turbopack-node/",
turbopack_binding::turbopack::node::embed_js::embed_fs().root(),
);
Ok(())
}
#[turbo_tasks::function]
async fn package_lookup_resolve_options(
project_path: Vc<FileSystemPath>,
) -> Result<Vc<ResolveOptions>> {
Ok(resolve_options(
project_path,
ResolveOptionsContext {
enable_node_modules: Some(project_path.root().resolve().await?),
enable_node_native_modules: true,
custom_conditions: vec!["development".to_string()],
..Default::default()
}
.cell(),
))
}
#[turbo_tasks::function]
pub async fn get_next_package(context_directory: Vc<FileSystemPath>) -> Result<Vc<FileSystemPath>> {
let result = resolve(
context_directory,
Request::parse(Value::new(Pattern::Constant(
"next/package.json".to_string(),
))),
package_lookup_resolve_options(context_directory),
);
let source = result
.first_source()
.await?
.context("Next.js package not found")?;
Ok(source.ident().path().parent())
}
pub async fn insert_alias_option<const N: usize>(
import_map: &mut ImportMap,
project_path: Vc<FileSystemPath>,
alias_options: Vc<ResolveAliasMap>,
conditions: [&'static str; N],
) -> Result<()> {
let conditions = BTreeMap::from(conditions.map(|c| (c.to_string(), ConditionValue::Set)));
for (alias, value) in &alias_options.await? {
if let Some(mapping) = export_value_to_import_mapping(value, &conditions, project_path) {
import_map.insert_alias(alias, mapping);
}
}
Ok(())
}
fn export_value_to_import_mapping(
value: &SubpathValue,
conditions: &BTreeMap<String, ConditionValue>,
project_path: Vc<FileSystemPath>,
) -> Option<Vc<ImportMapping>> {
let mut result = Vec::new();
value.add_results(
conditions,
&ConditionValue::Unset,
&mut HashMap::new(),
&mut result,
);
if result.is_empty() {
None
} else {
Some(if result.len() == 1 {
ImportMapping::PrimaryAlternative(result[0].to_string(), Some(project_path)).cell()
} else {
ImportMapping::Alternatives(
result
.iter()
.map(|m| {
ImportMapping::PrimaryAlternative(m.to_string(), Some(project_path)).cell()
})
.collect(),
)
.cell()
})
}
}
/// Inserts an alias to an alternative of import mappings into an import map.
fn insert_alias_to_alternatives<'a>(
import_map: &mut ImportMap,
alias: impl Into<String> + 'a,
alternatives: Vec<Vc<ImportMapping>>,
) {
import_map.insert_exact_alias(alias, ImportMapping::Alternatives(alternatives).into());
}
/// Inserts an alias to an import mapping into an import map.
fn insert_package_alias(
import_map: &mut ImportMap,
prefix: &str,
package_root: Vc<FileSystemPath>,
) {
import_map.insert_wildcard_alias(
prefix,
ImportMapping::PrimaryAlternative("./*".to_string(), Some(package_root)).cell(),
);
}
/// Inserts an alias to @vercel/turbopack-dev into an import map.
fn insert_turbopack_dev_alias(import_map: &mut ImportMap) {
insert_package_alias(
import_map,
"@vercel/turbopack-ecmascript-runtime/",
turbopack_binding::turbopack::ecmascript_runtime::embed_fs().root(),
);
}
/// Creates a direct import mapping to the result of resolving a request
/// in a context.
fn request_to_import_mapping(context_path: Vc<FileSystemPath>, request: &str) -> Vc<ImportMapping> {
ImportMapping::PrimaryAlternative(request.to_string(), Some(context_path)).cell()
}
/// Creates a direct import mapping to the result of resolving an external
/// request.
fn external_request_to_import_mapping(request: &str) -> Vc<ImportMapping> {
ImportMapping::External(Some(request.to_string())).into()
}