File size: 60,323 Bytes
1e92f2d |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 |
use std::{borrow::Cow, io::Write, path::PathBuf, sync::Arc, thread, time::Duration};
use anyhow::{Context, Result, anyhow, bail};
use futures_util::TryFutureExt;
use napi::{
Env, JsFunction, JsObject, Status,
bindgen_prelude::{External, within_runtime_if_available},
threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode},
};
use next_api::{
entrypoints::Entrypoints,
module_graph_snapshot::{ModuleGraphSnapshot, get_module_graph_snapshot},
operation::{
EntrypointsOperation, InstrumentationOperation, MiddlewareOperation, OptionEndpoint,
RouteOperation,
},
project::{
DefineEnv, DraftModeOptions, PartialProjectOptions, Project, ProjectContainer,
ProjectOptions, WatchOptions,
},
route::Endpoint,
};
use next_core::tracing_presets::{
TRACING_NEXT_OVERVIEW_TARGETS, TRACING_NEXT_TARGETS, TRACING_NEXT_TURBO_TASKS_TARGETS,
TRACING_NEXT_TURBOPACK_TARGETS,
};
use once_cell::sync::Lazy;
use rand::Rng;
use serde::{Deserialize, Serialize};
use tokio::{io::AsyncWriteExt, time::Instant};
use tracing::Instrument;
use tracing_subscriber::{Registry, layer::SubscriberExt, util::SubscriberInitExt};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, Effects, FxIndexSet, NonLocalValue, OperationValue, OperationVc, ReadRef,
ResolvedVc, TaskInput, TransientInstance, TryJoinIterExt, TurboTasksApi, UpdateInfo, Vc,
get_effects,
message_queue::{CompilationEvent, Severity, TimingEvent},
trace::TraceRawVcs,
};
use turbo_tasks_backend::{BackingStorage, db_invalidation::invalidation_reasons};
use turbo_tasks_fs::{
DiskFileSystem, FileContent, FileSystem, FileSystemPath, get_relative_path_to,
util::uri_from_file,
};
use turbopack_core::{
PROJECT_FILESYSTEM_NAME, SOURCE_URL_PROTOCOL,
diagnostics::PlainDiagnostic,
error::PrettyPrintError,
issue::PlainIssue,
output::{OutputAsset, OutputAssets},
source_map::{OptionStringifiedSourceMap, SourceMap, Token},
version::{PartialUpdate, TotalUpdate, Update, VersionState},
};
use turbopack_ecmascript_hmr_protocol::{ClientUpdateInstruction, Issue, ResourceIdentifier};
use turbopack_trace_utils::{
exit::{ExitHandler, ExitReceiver},
filter_layer::FilterLayer,
raw_trace::RawTraceLayer,
trace_writer::TraceWriter,
};
use url::Url;
use crate::{
next_api::{
endpoint::ExternalEndpoint,
module_graph::NapiModuleGraphSnapshot,
turbopack_ctx::{
NapiNextTurbopackCallbacks, NapiNextTurbopackCallbacksJsObject, NextTurboTasks,
NextTurbopackContext, create_turbo_tasks,
},
utils::{
DetachedVc, NapiDiagnostic, NapiIssue, RootTask, TurbopackResult, get_diagnostics,
get_issues, strongly_consistent_catch_collectables, subscribe,
},
},
register,
util::DhatProfilerGuard,
};
/// Used by [`benchmark_file_io`]. This is a noisy benchmark, so set the
/// threshold high.
const SLOW_FILESYSTEM_THRESHOLD: Duration = Duration::from_millis(100);
static SOURCE_MAP_PREFIX: Lazy<String> = Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///"));
static SOURCE_MAP_PREFIX_PROJECT: Lazy<String> =
Lazy::new(|| format!("{SOURCE_URL_PROTOCOL}///[{PROJECT_FILESYSTEM_NAME}]/"));
#[napi(object)]
#[derive(Clone, Debug)]
pub struct NapiEnvVar {
pub name: RcStr,
pub value: RcStr,
}
#[napi(object)]
#[derive(Clone, Debug)]
pub struct NapiOptionEnvVar {
pub name: RcStr,
pub value: Option<RcStr>,
}
#[napi(object)]
pub struct NapiDraftModeOptions {
pub preview_mode_id: RcStr,
pub preview_mode_encryption_key: RcStr,
pub preview_mode_signing_key: RcStr,
}
impl From<NapiDraftModeOptions> for DraftModeOptions {
fn from(val: NapiDraftModeOptions) -> Self {
DraftModeOptions {
preview_mode_id: val.preview_mode_id,
preview_mode_encryption_key: val.preview_mode_encryption_key,
preview_mode_signing_key: val.preview_mode_signing_key,
}
}
}
#[napi(object)]
pub struct NapiWatchOptions {
/// Whether to watch the filesystem for file changes.
pub enable: bool,
/// Enable polling at a certain interval if the native file watching doesn't work (e.g.
/// docker).
pub poll_interval_ms: Option<f64>,
}
#[napi(object)]
pub struct NapiProjectOptions {
/// An absolute root path (Unix or Windows path) from which all files must be nested under.
/// Trying to access a file outside this root will fail, so think of this as a chroot.
/// E.g. `/home/user/projects/my-repo`.
pub root_path: RcStr,
/// A path which contains the app/pages directories, relative to [`Project::root_path`], always
/// Unix path. E.g. `apps/my-app`
pub project_path: RcStr,
/// A path where to emit the build outputs, relative to [`Project::project_path`], always Unix
/// path. Corresponds to next.config.js's `distDir`.
/// E.g. `.next`
pub dist_dir: RcStr,
/// Filesystem watcher options.
pub watch: NapiWatchOptions,
/// The contents of next.config.js, serialized to JSON.
pub next_config: RcStr,
/// The contents of ts/config read by load-jsconfig, serialized to JSON.
pub js_config: RcStr,
/// A map of environment variables to use when compiling code.
pub env: Vec<NapiEnvVar>,
/// A map of environment variables which should get injected at compile
/// time.
pub define_env: NapiDefineEnv,
/// The mode in which Next.js is running.
pub dev: bool,
/// The server actions encryption key.
pub encryption_key: RcStr,
/// The build id.
pub build_id: RcStr,
/// Options for draft mode.
pub preview_props: NapiDraftModeOptions,
/// The browserslist query to use for targeting browsers.
pub browserslist_query: RcStr,
/// When the code is minified, this opts out of the default mangling of
/// local names for variables, functions etc., which can be useful for
/// debugging/profiling purposes.
pub no_mangling: bool,
/// The version of Node.js that is available/currently running.
pub current_node_js_version: RcStr,
}
/// [NapiProjectOptions] with all fields optional.
#[napi(object)]
pub struct NapiPartialProjectOptions {
/// An absolute root path (Unix or Windows path) from which all files must be nested under.
/// Trying to access a file outside this root will fail, so think of this as a chroot.
/// E.g. `/home/user/projects/my-repo`.
pub root_path: Option<RcStr>,
/// A path which contains the app/pages directories, relative to [`Project::root_path`], always
/// a Unix path.
/// E.g. `apps/my-app`
pub project_path: Option<RcStr>,
/// A path where to emit the build outputs, relative to [`Project::project_path`], always a
/// Unix path. Corresponds to next.config.js's `distDir`.
/// E.g. `.next`
pub dist_dir: Option<Option<RcStr>>,
/// Filesystem watcher options.
pub watch: Option<NapiWatchOptions>,
/// The contents of next.config.js, serialized to JSON.
pub next_config: Option<RcStr>,
/// The contents of ts/config read by load-jsconfig, serialized to JSON.
pub js_config: Option<RcStr>,
/// A map of environment variables to use when compiling code.
pub env: Option<Vec<NapiEnvVar>>,
/// A map of environment variables which should get injected at compile
/// time.
pub define_env: Option<NapiDefineEnv>,
/// The mode in which Next.js is running.
pub dev: Option<bool>,
/// The server actions encryption key.
pub encryption_key: Option<RcStr>,
/// The build id.
pub build_id: Option<RcStr>,
/// Options for draft mode.
pub preview_props: Option<NapiDraftModeOptions>,
/// The browserslist query to use for targeting browsers.
pub browserslist_query: Option<RcStr>,
/// When the code is minified, this opts out of the default mangling of
/// local names for variables, functions etc., which can be useful for
/// debugging/profiling purposes.
pub no_mangling: Option<bool>,
}
#[napi(object)]
#[derive(Clone, Debug)]
pub struct NapiDefineEnv {
pub client: Vec<NapiOptionEnvVar>,
pub edge: Vec<NapiOptionEnvVar>,
pub nodejs: Vec<NapiOptionEnvVar>,
}
#[napi(object)]
pub struct NapiTurboEngineOptions {
/// Use the new backend with persistent caching enabled.
pub persistent_caching: Option<bool>,
/// An upper bound of memory that turbopack will attempt to stay under.
pub memory_limit: Option<f64>,
/// Track dependencies between tasks. If false, any change during build will error.
pub dependency_tracking: Option<bool>,
/// Whether the project is running in a CI environment.
pub is_ci: Option<bool>,
}
impl From<NapiWatchOptions> for WatchOptions {
fn from(val: NapiWatchOptions) -> Self {
WatchOptions {
enable: val.enable,
poll_interval: val
.poll_interval_ms
.filter(|interval| !interval.is_nan() && interval.is_finite() && *interval > 0.0)
.map(|interval| Duration::from_secs_f64(interval / 1000.0)),
}
}
}
impl From<NapiProjectOptions> for ProjectOptions {
fn from(val: NapiProjectOptions) -> Self {
ProjectOptions {
root_path: val.root_path,
project_path: val.project_path,
watch: val.watch.into(),
next_config: val.next_config,
js_config: val.js_config,
env: val
.env
.into_iter()
.map(|var| (var.name, var.value))
.collect(),
define_env: val.define_env.into(),
dev: val.dev,
encryption_key: val.encryption_key,
build_id: val.build_id,
preview_props: val.preview_props.into(),
browserslist_query: val.browserslist_query,
no_mangling: val.no_mangling,
current_node_js_version: val.current_node_js_version,
}
}
}
impl From<NapiPartialProjectOptions> for PartialProjectOptions {
fn from(val: NapiPartialProjectOptions) -> Self {
PartialProjectOptions {
root_path: val.root_path,
project_path: val.project_path,
watch: val.watch.map(From::from),
next_config: val.next_config,
js_config: val.js_config,
env: val
.env
.map(|env| env.into_iter().map(|var| (var.name, var.value)).collect()),
define_env: val.define_env.map(|env| env.into()),
dev: val.dev,
encryption_key: val.encryption_key,
build_id: val.build_id,
preview_props: val.preview_props.map(|props| props.into()),
}
}
}
impl From<NapiDefineEnv> for DefineEnv {
fn from(val: NapiDefineEnv) -> Self {
DefineEnv {
client: val
.client
.into_iter()
.map(|var| (var.name, var.value))
.collect(),
edge: val
.edge
.into_iter()
.map(|var| (var.name, var.value))
.collect(),
nodejs: val
.nodejs
.into_iter()
.map(|var| (var.name, var.value))
.collect(),
}
}
}
pub struct ProjectInstance {
turbopack_ctx: NextTurbopackContext,
container: ResolvedVc<ProjectContainer>,
exit_receiver: tokio::sync::Mutex<Option<ExitReceiver>>,
}
#[napi(ts_return_type = "Promise<{ __napiType: \"Project\" }>")]
pub fn project_new(
env: Env,
options: NapiProjectOptions,
turbo_engine_options: NapiTurboEngineOptions,
napi_callbacks: NapiNextTurbopackCallbacksJsObject,
) -> napi::Result<JsObject> {
let napi_callbacks = NapiNextTurbopackCallbacks::from_js(napi_callbacks)?;
env.spawn_future(async move {
register();
let (exit, exit_receiver) = ExitHandler::new_receiver();
if let Some(dhat_profiler) = DhatProfilerGuard::try_init() {
exit.on_exit(async move {
tokio::task::spawn_blocking(move || drop(dhat_profiler))
.await
.unwrap()
});
}
let mut trace = std::env::var("NEXT_TURBOPACK_TRACING")
.ok()
.filter(|v| !v.is_empty());
if cfg!(feature = "tokio-console") && trace.is_none() {
// ensure `trace` is set to *something* so that the `tokio-console` feature works,
// otherwise you just get empty output from `tokio-console`, which can be
// confusing.
trace = Some("overview".to_owned());
}
if let Some(mut trace) = trace {
// Trace presets
match trace.as_str() {
"overview" | "1" => {
trace = TRACING_NEXT_OVERVIEW_TARGETS.join(",");
}
"next" => {
trace = TRACING_NEXT_TARGETS.join(",");
}
"turbopack" => {
trace = TRACING_NEXT_TURBOPACK_TARGETS.join(",");
}
"turbo-tasks" => {
trace = TRACING_NEXT_TURBO_TASKS_TARGETS.join(",");
}
_ => {}
}
let subscriber = Registry::default();
if cfg!(feature = "tokio-console") {
trace = format!("{trace},tokio=trace,runtime=trace");
}
#[cfg(feature = "tokio-console")]
let subscriber = subscriber.with(console_subscriber::spawn());
let subscriber = subscriber.with(FilterLayer::try_new(&trace).unwrap());
let internal_dir = PathBuf::from(&options.root_path)
.join(&options.project_path)
.join(&options.dist_dir);
std::fs::create_dir_all(&internal_dir)
.context("Unable to create .next directory")
.unwrap();
let trace_file = internal_dir.join("trace-turbopack");
let trace_writer = std::fs::File::create(trace_file.clone()).unwrap();
let (trace_writer, trace_writer_guard) = TraceWriter::new(trace_writer);
let subscriber = subscriber.with(RawTraceLayer::new(trace_writer));
exit.on_exit(async move {
tokio::task::spawn_blocking(move || drop(trace_writer_guard))
.await
.unwrap();
});
let trace_server = std::env::var("NEXT_TURBOPACK_TRACE_SERVER").ok();
if trace_server.is_some() {
thread::spawn(move || {
turbopack_trace_server::start_turbopack_trace_server(trace_file);
});
println!("Turbopack trace server started. View trace at https://trace.nextjs.org");
}
subscriber.init();
}
let memory_limit = turbo_engine_options
.memory_limit
.map(|m| m as usize)
.unwrap_or(usize::MAX);
let persistent_caching = turbo_engine_options.persistent_caching.unwrap_or_default();
let dependency_tracking = turbo_engine_options.dependency_tracking.unwrap_or(true);
let is_ci = turbo_engine_options.is_ci.unwrap_or(false);
let turbo_tasks = create_turbo_tasks(
PathBuf::from(&options.dist_dir),
persistent_caching,
memory_limit,
dependency_tracking,
is_ci,
)?;
let turbopack_ctx = NextTurbopackContext::new(turbo_tasks.clone(), napi_callbacks);
let stats_path = std::env::var_os("NEXT_TURBOPACK_TASK_STATISTICS");
if let Some(stats_path) = stats_path {
let task_stats = turbo_tasks.task_statistics().enable().clone();
exit.on_exit(async move {
tokio::task::spawn_blocking(move || {
let mut file = std::fs::File::create(&stats_path)
.with_context(|| format!("failed to create or open {stats_path:?}"))?;
serde_json::to_writer(&file, &task_stats)
.context("failed to serialize or write task statistics")?;
file.flush().context("failed to flush file")
})
.await
.unwrap()
.unwrap();
});
}
let options: ProjectOptions = options.into();
let container = turbo_tasks
.run_once(async move {
let project = ProjectContainer::new(rcstr!("next.js"), options.dev);
let project = project.to_resolved().await?;
project.initialize(options).await?;
Ok(project)
})
.or_else(|e| turbopack_ctx.throw_turbopack_internal_result(&e))
.await?;
turbo_tasks.spawn_once_task({
let tt = turbo_tasks.clone();
async move {
benchmark_file_io(tt, container.project().node_root().owned().await?)
.await
.inspect_err(|err| tracing::warn!(%err, "failed to benchmark file IO"))
}
});
Ok(External::new(ProjectInstance {
turbopack_ctx,
container,
exit_receiver: tokio::sync::Mutex::new(Some(exit_receiver)),
}))
})
}
#[derive(Debug, Clone, Serialize)]
struct SlowFilesystemEvent {
directory: String,
duration_ms: u128,
}
impl CompilationEvent for SlowFilesystemEvent {
fn type_name(&self) -> &'static str {
"SlowFilesystemEvent"
}
fn severity(&self) -> Severity {
Severity::Warning
}
fn message(&self) -> String {
format!(
"Slow filesystem detected. The benchmark took {}ms. If {} is a network drive, \
consider moving it to a local folder. If you have an antivirus enabled, consider \
excluding your project directory.",
self.duration_ms, self.directory
)
}
fn to_json(&self) -> String {
serde_json::to_string(self).unwrap()
}
}
/// A very simple and low-overhead, but potentially noisy benchmark to detect
/// very slow disk IO. Warns the user (via `println!`) if the benchmark takes
/// more than `SLOW_FILESYSTEM_THRESHOLD`.
///
/// This idea is copied from Bun:
/// - https://x.com/jarredsumner/status/1637549427677364224
/// - https://github.com/oven-sh/bun/blob/06a9aa80c38b08b3148bfeabe560/src/install/install.zig#L3038
#[tracing::instrument(skip(turbo_tasks))]
async fn benchmark_file_io(
turbo_tasks: NextTurboTasks,
directory: FileSystemPath,
) -> Result<Vc<Completion>> {
// try to get the real file path on disk so that we can use it with tokio
let fs = Vc::try_resolve_downcast_type::<DiskFileSystem>(directory.fs())
.await?
.context(anyhow!(
"expected node_root to be a DiskFileSystem, cannot benchmark"
))?
.await?;
let directory = fs.to_sys_path(directory).await?;
let temp_path = directory.join(format!(
"tmp_file_io_benchmark_{:x}",
rand::random::<u128>()
));
let mut random_buffer = [0u8; 512];
rand::rng().fill(&mut random_buffer[..]);
// perform IO directly with tokio (skipping `tokio_tasks_fs`) to avoid the
// additional noise/overhead of tasks caching, invalidation, file locks,
// etc.
let start = Instant::now();
async move {
for _ in 0..3 {
// create a new empty file
let mut file = tokio::fs::File::create(&temp_path).await?;
file.write_all(&random_buffer).await?;
file.sync_all().await?;
drop(file);
// remove the file
tokio::fs::remove_file(&temp_path).await?;
}
anyhow::Ok(())
}
.instrument(tracing::info_span!("benchmark file IO (measurement)"))
.await?;
let duration = Instant::now().duration_since(start);
if duration > SLOW_FILESYSTEM_THRESHOLD {
turbo_tasks.send_compilation_event(Arc::new(SlowFilesystemEvent {
directory: directory.to_string_lossy().into(),
duration_ms: duration.as_millis(),
}));
}
Ok(Completion::new())
}
#[napi]
pub async fn project_update(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
options: NapiPartialProjectOptions,
) -> napi::Result<()> {
let ctx = &project.turbopack_ctx;
let options = options.into();
let container = project.container;
ctx.turbo_tasks()
.run_once(async move {
container.update(options).await?;
Ok(())
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e))
.await
}
/// Invalidates the persistent cache so that it will be deleted next time that a turbopack project
/// is created with persistent caching enabled.
#[napi]
pub async fn project_invalidate_persistent_cache(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) -> napi::Result<()> {
tokio::task::spawn_blocking(move || {
// TODO: Let the JS caller specify a reason? We need to limit the reasons to ones we know
// how to generate a message for on the Rust side of the FFI.
project
.turbopack_ctx
.turbo_tasks()
.backend()
.backing_storage()
.invalidate(invalidation_reasons::USER_REQUEST)
})
.await
.context("panicked while invalidating persistent cache")??;
Ok(())
}
/// Runs exit handlers for the project registered using the [`ExitHandler`] API.
///
/// This is called by `project_shutdown`, so if you're calling that API, you shouldn't call this
/// one.
#[napi]
pub async fn project_on_exit(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) {
project_on_exit_internal(&project).await
}
async fn project_on_exit_internal(project: &ProjectInstance) {
let exit_receiver = project.exit_receiver.lock().await.take();
exit_receiver
.expect("`project.onExitSync` must only be called once")
.run_exit_handler()
.await;
}
/// Runs `project_on_exit`, and then waits for turbo_tasks to gracefully shut down.
///
/// This is used in builds where it's important that we completely persist turbo-tasks to disk, but
/// it's skipped in the development server (`project_on_exit` is used instead with a short timeout),
/// where we prioritize fast exit and user responsiveness over all else.
#[napi]
pub async fn project_shutdown(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) {
project.turbopack_ctx.turbo_tasks().stop_and_wait().await;
project_on_exit_internal(&project).await;
}
#[napi(object)]
#[derive(Default)]
pub struct AppPageNapiRoute {
/// The relative path from project_path to the route file
pub original_name: Option<RcStr>,
pub html_endpoint: Option<External<ExternalEndpoint>>,
pub rsc_endpoint: Option<External<ExternalEndpoint>>,
}
#[napi(object)]
#[derive(Default)]
pub struct NapiRoute {
/// The router path
pub pathname: String,
/// The relative path from project_path to the route file
pub original_name: Option<RcStr>,
/// The type of route, eg a Page or App
pub r#type: &'static str,
pub pages: Option<Vec<AppPageNapiRoute>>,
// Different representations of the endpoint
pub endpoint: Option<External<ExternalEndpoint>>,
pub html_endpoint: Option<External<ExternalEndpoint>>,
pub rsc_endpoint: Option<External<ExternalEndpoint>>,
pub data_endpoint: Option<External<ExternalEndpoint>>,
}
impl NapiRoute {
fn from_route(
pathname: String,
value: RouteOperation,
turbopack_ctx: &NextTurbopackContext,
) -> Self {
let convert_endpoint = |endpoint: OperationVc<OptionEndpoint>| {
Some(External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
endpoint,
))))
};
match value {
RouteOperation::Page {
html_endpoint,
data_endpoint,
} => NapiRoute {
pathname,
r#type: "page",
html_endpoint: convert_endpoint(html_endpoint),
data_endpoint: convert_endpoint(data_endpoint),
..Default::default()
},
RouteOperation::PageApi { endpoint } => NapiRoute {
pathname,
r#type: "page-api",
endpoint: convert_endpoint(endpoint),
..Default::default()
},
RouteOperation::AppPage(pages) => NapiRoute {
pathname,
r#type: "app-page",
pages: Some(
pages
.into_iter()
.map(|page_route| AppPageNapiRoute {
original_name: Some(page_route.original_name),
html_endpoint: convert_endpoint(page_route.html_endpoint),
rsc_endpoint: convert_endpoint(page_route.rsc_endpoint),
})
.collect(),
),
..Default::default()
},
RouteOperation::AppRoute {
original_name,
endpoint,
} => NapiRoute {
pathname,
original_name: Some(original_name),
r#type: "app-route",
endpoint: convert_endpoint(endpoint),
..Default::default()
},
RouteOperation::Conflict => NapiRoute {
pathname,
r#type: "conflict",
..Default::default()
},
}
}
}
#[napi(object)]
pub struct NapiMiddleware {
pub endpoint: External<ExternalEndpoint>,
}
impl NapiMiddleware {
fn from_middleware(
value: &MiddlewareOperation,
turbopack_ctx: &NextTurbopackContext,
) -> Result<Self> {
Ok(NapiMiddleware {
endpoint: External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
value.endpoint,
))),
})
}
}
#[napi(object)]
pub struct NapiInstrumentation {
pub node_js: External<ExternalEndpoint>,
pub edge: External<ExternalEndpoint>,
}
impl NapiInstrumentation {
fn from_instrumentation(
value: &InstrumentationOperation,
turbopack_ctx: &NextTurbopackContext,
) -> Result<Self> {
Ok(NapiInstrumentation {
node_js: External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
value.node_js,
))),
edge: External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
value.edge,
))),
})
}
}
#[napi(object)]
pub struct NapiEntrypoints {
pub routes: Vec<NapiRoute>,
pub middleware: Option<NapiMiddleware>,
pub instrumentation: Option<NapiInstrumentation>,
pub pages_document_endpoint: External<ExternalEndpoint>,
pub pages_app_endpoint: External<ExternalEndpoint>,
pub pages_error_endpoint: External<ExternalEndpoint>,
}
impl NapiEntrypoints {
fn from_entrypoints_op(
entrypoints: &EntrypointsOperation,
turbopack_ctx: &NextTurbopackContext,
) -> Result<Self> {
let routes = entrypoints
.routes
.iter()
.map(|(k, v)| NapiRoute::from_route(k.to_string(), v.clone(), turbopack_ctx))
.collect();
let middleware = entrypoints
.middleware
.as_ref()
.map(|m| NapiMiddleware::from_middleware(m, turbopack_ctx))
.transpose()?;
let instrumentation = entrypoints
.instrumentation
.as_ref()
.map(|i| NapiInstrumentation::from_instrumentation(i, turbopack_ctx))
.transpose()?;
let pages_document_endpoint = External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
entrypoints.pages_document_endpoint,
)));
let pages_app_endpoint = External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
entrypoints.pages_app_endpoint,
)));
let pages_error_endpoint = External::new(ExternalEndpoint(DetachedVc::new(
turbopack_ctx.clone(),
entrypoints.pages_error_endpoint,
)));
Ok(NapiEntrypoints {
routes,
middleware,
instrumentation,
pages_document_endpoint,
pages_app_endpoint,
pages_error_endpoint,
})
}
}
#[turbo_tasks::value(serialization = "none")]
struct EntrypointsWithIssues {
entrypoints: ReadRef<EntrypointsOperation>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[turbo_tasks::function(operation)]
async fn get_entrypoints_with_issues_operation(
container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<EntrypointsWithIssues>> {
let entrypoints_operation =
EntrypointsOperation::new(project_container_entrypoints_operation(container));
let entrypoints = entrypoints_operation.read_strongly_consistent().await?;
let issues = get_issues(entrypoints_operation).await?;
let diagnostics = get_diagnostics(entrypoints_operation).await?;
let effects = Arc::new(get_effects(entrypoints_operation).await?);
Ok(EntrypointsWithIssues {
entrypoints,
issues,
diagnostics,
effects,
}
.cell())
}
#[turbo_tasks::function(operation)]
fn project_container_entrypoints_operation(
// the container is a long-lived object with internally mutable state, there's no risk of it
// becoming stale
container: ResolvedVc<ProjectContainer>,
) -> Vc<Entrypoints> {
container.entrypoints()
}
#[turbo_tasks::value(serialization = "none")]
struct AllWrittenEntrypointsWithIssues {
entrypoints: Option<ReadRef<Entrypoints>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[napi]
pub async fn project_write_all_entrypoints_to_disk(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
app_dir_only: bool,
) -> napi::Result<TurbopackResult<NapiEntrypoints>> {
let ctx = &project.turbopack_ctx;
let container = project.container;
let tt = ctx.turbo_tasks();
let tt_clone = tt.clone();
let (entrypoints, issues, diags) = tt
.run_once(async move {
let entrypoints_with_issues_op =
get_all_written_entrypoints_with_issues_operation(container, app_dir_only);
// Read and compile the files
let EntrypointsWithIssues {
entrypoints,
issues,
diagnostics,
effects,
} = &*entrypoints_with_issues_op
.read_strongly_consistent()
.await?;
// Start timing writing the files to disk
let now = Instant::now();
// Write the files to disk
effects.apply().await?;
// Send a compilation event to indicate that the files have been written to disk
tt_clone.send_compilation_event(Arc::new(TimingEvent::new(
"Finished writing to disk".to_owned(),
now.elapsed(),
)));
Ok((entrypoints.clone(), issues.clone(), diagnostics.clone()))
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e))
.await?;
Ok(TurbopackResult {
result: NapiEntrypoints::from_entrypoints_op(&entrypoints, &project.turbopack_ctx)?,
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
diagnostics: diags.iter().map(|d| NapiDiagnostic::from(d)).collect(),
})
}
#[turbo_tasks::function(operation)]
async fn get_all_written_entrypoints_with_issues_operation(
container: ResolvedVc<ProjectContainer>,
app_dir_only: bool,
) -> Result<Vc<EntrypointsWithIssues>> {
let entrypoints_operation = EntrypointsOperation::new(all_entrypoints_write_to_disk_operation(
container,
app_dir_only,
));
let entrypoints = entrypoints_operation.read_strongly_consistent().await?;
let issues = get_issues(entrypoints_operation).await?;
let diagnostics = get_diagnostics(entrypoints_operation).await?;
let effects = Arc::new(get_effects(entrypoints_operation).await?);
Ok(EntrypointsWithIssues {
entrypoints,
issues,
diagnostics,
effects,
}
.cell())
}
#[turbo_tasks::function(operation)]
pub async fn all_entrypoints_write_to_disk_operation(
project: ResolvedVc<ProjectContainer>,
app_dir_only: bool,
) -> Result<Vc<Entrypoints>> {
project
.project()
.emit_all_output_assets(output_assets_operation(project, app_dir_only))
.as_side_effect()
.await?;
Ok(project.entrypoints())
}
#[turbo_tasks::function(operation)]
async fn output_assets_operation(
container: ResolvedVc<ProjectContainer>,
app_dir_only: bool,
) -> Result<Vc<OutputAssets>> {
let endpoint_assets = container
.project()
.get_all_endpoints(app_dir_only)
.await?
.iter()
.map(|endpoint| async move { endpoint.output().await?.output_assets.await })
.try_join()
.await?;
let output_assets: FxIndexSet<ResolvedVc<Box<dyn OutputAsset>>> = endpoint_assets
.iter()
.flat_map(|assets| assets.iter().copied())
.collect();
Ok(Vc::cell(output_assets.into_iter().collect()))
}
#[napi]
pub async fn project_entrypoints(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) -> napi::Result<TurbopackResult<NapiEntrypoints>> {
let container = project.container;
let (entrypoints, issues, diags) = project
.turbopack_ctx
.turbo_tasks()
.run_once(async move {
let entrypoints_with_issues_op = get_entrypoints_with_issues_operation(container);
// Read and compile the files
let EntrypointsWithIssues {
entrypoints,
issues,
diagnostics,
effects: _,
} = &*entrypoints_with_issues_op
.read_strongly_consistent()
.await?;
Ok((entrypoints.clone(), issues.clone(), diagnostics.clone()))
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(TurbopackResult {
result: NapiEntrypoints::from_entrypoints_op(&entrypoints, &project.turbopack_ctx)?,
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
diagnostics: diags.iter().map(|d| NapiDiagnostic::from(d)).collect(),
})
}
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_entrypoints_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
func: JsFunction,
) -> napi::Result<External<RootTask>> {
let turbopack_ctx = project.turbopack_ctx.clone();
let container = project.container;
subscribe(
turbopack_ctx.clone(),
func,
move || {
async move {
let entrypoints_with_issues_op = get_entrypoints_with_issues_operation(container);
let EntrypointsWithIssues {
entrypoints,
issues,
diagnostics,
effects,
} = &*entrypoints_with_issues_op
.read_strongly_consistent()
.await?;
effects.apply().await?;
Ok((entrypoints.clone(), issues.clone(), diagnostics.clone()))
}
.instrument(tracing::info_span!("entrypoints subscription"))
},
move |ctx| {
let (entrypoints, issues, diags) = ctx.value;
Ok(vec![TurbopackResult {
result: NapiEntrypoints::from_entrypoints_op(&entrypoints, &turbopack_ctx)?,
issues: issues
.iter()
.map(|issue| NapiIssue::from(&**issue))
.collect(),
diagnostics: diags.iter().map(|d| NapiDiagnostic::from(d)).collect(),
}])
},
)
}
#[turbo_tasks::value(serialization = "none")]
struct HmrUpdateWithIssues {
update: ReadRef<Update>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[turbo_tasks::function(operation)]
async fn hmr_update_with_issues_operation(
project: ResolvedVc<Project>,
identifier: RcStr,
state: ResolvedVc<VersionState>,
) -> Result<Vc<HmrUpdateWithIssues>> {
let update_op = project_hmr_update_operation(project, identifier, state);
let update = update_op.read_strongly_consistent().await?;
let issues = get_issues(update_op).await?;
let diagnostics = get_diagnostics(update_op).await?;
let effects = Arc::new(get_effects(update_op).await?);
Ok(HmrUpdateWithIssues {
update,
issues,
diagnostics,
effects,
}
.cell())
}
#[turbo_tasks::function(operation)]
fn project_hmr_update_operation(
project: ResolvedVc<Project>,
identifier: RcStr,
state: ResolvedVc<VersionState>,
) -> Vc<Update> {
project.hmr_update(identifier, *state)
}
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_events(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
identifier: RcStr,
func: JsFunction,
) -> napi::Result<External<RootTask>> {
let container = project.container;
let session = TransientInstance::new(());
subscribe(
project.turbopack_ctx.clone(),
func,
{
let outer_identifier = identifier.clone();
let session = session.clone();
move || {
let identifier: RcStr = outer_identifier.clone();
let session = session.clone();
async move {
let project = container.project().to_resolved().await?;
let state = project
.hmr_version_state(identifier.clone(), session)
.to_resolved()
.await?;
let update_op =
hmr_update_with_issues_operation(project, identifier.clone(), state);
let update = update_op.read_strongly_consistent().await?;
let HmrUpdateWithIssues {
update,
issues,
diagnostics,
effects,
} = &*update;
effects.apply().await?;
match &**update {
Update::Missing | Update::None => {}
Update::Total(TotalUpdate { to }) => {
state.set(to.clone()).await?;
}
Update::Partial(PartialUpdate { to, .. }) => {
state.set(to.clone()).await?;
}
}
Ok((Some(update.clone()), issues.clone(), diagnostics.clone()))
}
.instrument(tracing::info_span!(
"HMR subscription",
identifier = %outer_identifier
))
}
},
move |ctx| {
let (update, issues, diags) = ctx.value;
let napi_issues = issues
.iter()
.map(|issue| NapiIssue::from(&**issue))
.collect();
let update_issues = issues
.iter()
.map(|issue| Issue::from(&**issue))
.collect::<Vec<_>>();
let identifier = ResourceIdentifier {
path: identifier.clone(),
headers: None,
};
let update = match update.as_deref() {
None | Some(Update::Missing) | Some(Update::Total(_)) => {
ClientUpdateInstruction::restart(&identifier, &update_issues)
}
Some(Update::Partial(update)) => ClientUpdateInstruction::partial(
&identifier,
&update.instruction,
&update_issues,
),
Some(Update::None) => ClientUpdateInstruction::issues(&identifier, &update_issues),
};
Ok(vec![TurbopackResult {
result: ctx.env.to_js_value(&update)?,
issues: napi_issues,
diagnostics: diags.iter().map(|d| NapiDiagnostic::from(d)).collect(),
}])
},
)
}
#[napi(object)]
struct HmrIdentifiers {
pub identifiers: Vec<RcStr>,
}
#[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues {
identifiers: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[turbo_tasks::function(operation)]
async fn get_hmr_identifiers_with_issues_operation(
container: ResolvedVc<ProjectContainer>,
) -> Result<Vc<HmrIdentifiersWithIssues>> {
let hmr_identifiers_op = project_container_hmr_identifiers_operation(container);
let hmr_identifiers = hmr_identifiers_op.read_strongly_consistent().await?;
let issues = get_issues(hmr_identifiers_op).await?;
let diagnostics = get_diagnostics(hmr_identifiers_op).await?;
let effects = Arc::new(get_effects(hmr_identifiers_op).await?);
Ok(HmrIdentifiersWithIssues {
identifiers: hmr_identifiers,
issues,
diagnostics,
effects,
}
.cell())
}
#[turbo_tasks::function(operation)]
fn project_container_hmr_identifiers_operation(
container: ResolvedVc<ProjectContainer>,
) -> Vc<Vec<RcStr>> {
container.hmr_identifiers()
}
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_identifiers_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
func: JsFunction,
) -> napi::Result<External<RootTask>> {
let container = project.container;
subscribe(
project.turbopack_ctx.clone(),
func,
move || async move {
let hmr_identifiers_with_issues_op =
get_hmr_identifiers_with_issues_operation(container);
let HmrIdentifiersWithIssues {
identifiers,
issues,
diagnostics,
effects,
} = &*hmr_identifiers_with_issues_op
.read_strongly_consistent()
.await?;
effects.apply().await?;
Ok((identifiers.clone(), issues.clone(), diagnostics.clone()))
},
move |ctx| {
let (identifiers, issues, diagnostics) = ctx.value;
Ok(vec![TurbopackResult {
result: HmrIdentifiers {
identifiers: ReadRef::into_owned(identifiers),
},
issues: issues
.iter()
.map(|issue| NapiIssue::from(&**issue))
.collect(),
diagnostics: diagnostics
.iter()
.map(|d| NapiDiagnostic::from(d))
.collect(),
}])
},
)
}
pub enum UpdateMessage {
Start,
End(UpdateInfo),
}
#[napi(object)]
struct NapiUpdateMessage {
pub update_type: &'static str,
pub value: Option<NapiUpdateInfo>,
}
impl From<UpdateMessage> for NapiUpdateMessage {
fn from(update_message: UpdateMessage) -> Self {
match update_message {
UpdateMessage::Start => NapiUpdateMessage {
update_type: "start",
value: None,
},
UpdateMessage::End(info) => NapiUpdateMessage {
update_type: "end",
value: Some(info.into()),
},
}
}
}
#[napi(object)]
struct NapiUpdateInfo {
pub duration: u32,
pub tasks: u32,
}
impl From<UpdateInfo> for NapiUpdateInfo {
fn from(update_info: UpdateInfo) -> Self {
Self {
duration: update_info.duration.as_millis() as u32,
tasks: update_info.tasks as u32,
}
}
}
/// Subscribes to lifecycle events of the compilation.
///
/// Emits an [UpdateMessage::Start] event when any computation starts.
/// Emits an [UpdateMessage::End] event when there was no computation for the
/// specified time (`aggregation_ms`). The [UpdateMessage::End] event contains
/// information about the computations that happened since the
/// [UpdateMessage::Start] event. It contains the duration of the computation
/// (excluding the idle time that was spend waiting for `aggregation_ms`), and
/// the number of tasks that were executed.
///
/// The signature of the `func` is `(update_message: UpdateMessage) => void`.
#[napi]
pub fn project_update_info_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
aggregation_ms: u32,
func: JsFunction,
) -> napi::Result<()> {
let func: ThreadsafeFunction<UpdateMessage> = func.create_threadsafe_function(0, |ctx| {
let message = ctx.value;
Ok(vec![NapiUpdateMessage::from(message)])
})?;
tokio::spawn(async move {
let tt = project.turbopack_ctx.turbo_tasks();
loop {
let update_info = tt
.aggregated_update_info(Duration::ZERO, Duration::ZERO)
.await;
func.call(
Ok(UpdateMessage::Start),
ThreadsafeFunctionCallMode::NonBlocking,
);
let update_info = match update_info {
Some(update_info) => update_info,
None => {
tt.get_or_wait_aggregated_update_info(Duration::from_millis(
aggregation_ms.into(),
))
.await
}
};
let status = func.call(
Ok(UpdateMessage::End(update_info)),
ThreadsafeFunctionCallMode::NonBlocking,
);
if !matches!(status, Status::Ok) {
let error = anyhow!("Error calling JS function: {}", status);
eprintln!("{error}");
break;
}
}
});
Ok(())
}
/// Subscribes to all compilation events that are not cached like timing and progress information.
#[napi]
pub fn project_compilation_events_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
func: JsFunction,
event_types: Option<Vec<String>>,
) -> napi::Result<()> {
let tsfn: ThreadsafeFunction<Arc<dyn CompilationEvent>> =
func.create_threadsafe_function(0, |ctx| {
let event: Arc<dyn CompilationEvent> = ctx.value;
let env = ctx.env;
let mut obj = env.create_object()?;
obj.set_named_property("typeName", event.type_name())?;
obj.set_named_property("severity", event.severity().to_string())?;
obj.set_named_property("message", event.message())?;
let external = env.create_external(event, None);
obj.set_named_property("eventData", external)?;
Ok(vec![obj])
})?;
tokio::spawn(async move {
let tt = project.turbopack_ctx.turbo_tasks();
let mut receiver = tt.subscribe_to_compilation_events(event_types);
while let Some(msg) = receiver.recv().await {
let status = tsfn.call(Ok(msg), ThreadsafeFunctionCallMode::Blocking);
if status != Status::Ok {
break;
}
}
});
Ok(())
}
#[napi(object)]
#[derive(
Clone,
Debug,
Deserialize,
Eq,
Hash,
NonLocalValue,
OperationValue,
PartialEq,
Serialize,
TaskInput,
TraceRawVcs,
)]
pub struct StackFrame {
pub is_server: bool,
pub is_internal: Option<bool>,
pub original_file: Option<RcStr>,
pub file: RcStr,
/// 1-indexed, unlike source map tokens
pub line: Option<u32>,
/// 1-indexed, unlike source map tokens
pub column: Option<u32>,
pub method_name: Option<RcStr>,
}
#[turbo_tasks::value(transparent)]
#[derive(Clone)]
pub struct OptionStackFrame(Option<StackFrame>);
#[turbo_tasks::function]
pub async fn get_source_map_rope(
container: Vc<ProjectContainer>,
file_path: RcStr,
) -> Result<Vc<OptionStringifiedSourceMap>> {
let (file, module) = match Url::parse(&file_path) {
Ok(url) => match url.scheme() {
"file" => {
let path = urlencoding::decode(url.path())?.to_string();
let module = url.query_pairs().find(|(k, _)| k == "id");
(
path,
match module {
Some(module) => Some(urlencoding::decode(&module.1)?.into_owned().into()),
None => None,
},
)
}
_ => bail!("Unknown url scheme '{}'", url.scheme()),
},
Err(_) => (file_path.to_string(), None),
};
let Some(chunk_base) =
file.strip_prefix(container.project().dist_dir_absolute().await?.as_str())
else {
// File doesn't exist within the dist dir
return Ok(OptionStringifiedSourceMap::none());
};
let server_path = container.project().node_root().await?.join(chunk_base)?;
let client_path = container
.project()
.client_relative_path()
.await?
.join(chunk_base)?;
let mut map = container.get_source_map(server_path, module.clone());
if map.await?.is_none() {
// If the chunk doesn't exist as a server chunk, try a client chunk.
// TODO: Properly tag all server chunks and use the `isServer` query param.
// Currently, this is inaccurate as it does not cover RSC server
// chunks.
map = container.get_source_map(client_path, module);
if map.await?.is_none() {
bail!("chunk/module '{}' is missing a sourcemap", file_path);
}
}
Ok(map)
}
#[turbo_tasks::function(operation)]
pub fn get_source_map_rope_operation(
container: ResolvedVc<ProjectContainer>,
file_path: RcStr,
) -> Vc<OptionStringifiedSourceMap> {
get_source_map_rope(*container, file_path)
}
#[turbo_tasks::function(operation)]
pub async fn project_trace_source_operation(
container: ResolvedVc<ProjectContainer>,
frame: StackFrame,
current_directory_file_url: RcStr,
) -> Result<Vc<OptionStackFrame>> {
let Some(map) =
&*SourceMap::new_from_rope_cached(get_source_map_rope(*container, frame.file)).await?
else {
return Ok(Vc::cell(None));
};
let Some(line) = frame.line else {
return Ok(Vc::cell(None));
};
let token = map
.lookup_token(
line.saturating_sub(1),
frame.column.unwrap_or(1).saturating_sub(1),
)
.await?;
let (original_file, line, column, method_name) = match token {
Token::Original(token) => (
match urlencoding::decode(&token.original_file)? {
Cow::Borrowed(_) => token.original_file,
Cow::Owned(original_file) => RcStr::from(original_file),
},
// JS stack frames are 1-indexed, source map tokens are 0-indexed
Some(token.original_line + 1),
Some(token.original_column + 1),
token.name,
),
Token::Synthetic(token) => {
let Some(original_file) = token.guessed_original_file else {
return Ok(Vc::cell(None));
};
(original_file, None, None, None)
}
};
let project_root_uri =
uri_from_file(container.project().project_root_path().owned().await?, None).await? + "/";
let (file, original_file, is_internal) =
if let Some(source_file) = original_file.strip_prefix(&project_root_uri) {
// Client code uses file://
(
RcStr::from(
get_relative_path_to(¤t_directory_file_url, &original_file)
// TODO(sokra) remove this to include a ./ here to make it a relative path
.trim_start_matches("./"),
),
Some(RcStr::from(source_file)),
false,
)
} else if let Some(source_file) = original_file.strip_prefix(&*SOURCE_MAP_PREFIX_PROJECT) {
// Server code uses turbopack:///[project]
// TODO should this also be file://?
(
RcStr::from(
get_relative_path_to(
¤t_directory_file_url,
&format!("{project_root_uri}{source_file}"),
)
// TODO(sokra) remove this to include a ./ here to make it a relative path
.trim_start_matches("./"),
),
Some(RcStr::from(source_file)),
false,
)
} else if let Some(source_file) = original_file.strip_prefix(&*SOURCE_MAP_PREFIX) {
// All other code like turbopack:///[turbopack] is internal code
// TODO(veil): Should the protocol be preserved?
(RcStr::from(source_file), None, true)
} else {
bail!(
"Original file ({}) outside project ({})",
original_file,
project_root_uri
)
};
Ok(Vc::cell(Some(StackFrame {
file,
original_file,
method_name,
line,
column,
is_server: frame.is_server,
is_internal: Some(is_internal),
})))
}
#[napi]
pub async fn project_trace_source(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
frame: StackFrame,
current_directory_file_url: String,
) -> napi::Result<Option<StackFrame>> {
let container = project.container;
let ctx = &project.turbopack_ctx;
ctx.turbo_tasks()
.run_once(async move {
let traced_frame = project_trace_source_operation(
container,
frame,
RcStr::from(current_directory_file_url),
)
.read_strongly_consistent()
.await?;
Ok(ReadRef::into_owned(traced_frame))
})
// HACK: Don't use `TurbopackInternalError`, this function is race-condition prone (the
// source files may have changed or been deleted), so these probably aren't internal errors?
// Ideally we should differentiate.
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))
}
#[napi]
pub async fn project_get_source_for_asset(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
file_path: RcStr,
) -> napi::Result<Option<String>> {
let container = project.container;
let ctx = &project.turbopack_ctx;
ctx.turbo_tasks()
.run_once(async move {
let source_content = &*container
.project()
.project_path()
.await?
.fs()
.root()
.await?
.join(&file_path)?
.read()
.await?;
let FileContent::Content(source_content) = source_content else {
bail!("Cannot find source for asset {}", file_path);
};
Ok(Some(source_content.content().to_str()?.into_owned()))
})
// HACK: Don't use `TurbopackInternalError`, this function is race-condition prone (the
// source files may have changed or been deleted), so these probably aren't internal errors?
// Ideally we should differentiate.
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))
}
#[napi]
pub async fn project_get_source_map(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
file_path: RcStr,
) -> napi::Result<Option<String>> {
let container = project.container;
let ctx = &project.turbopack_ctx;
ctx.turbo_tasks()
.run_once(async move {
let Some(map) = &*get_source_map_rope_operation(container, file_path)
.read_strongly_consistent()
.await?
else {
return Ok(None);
};
Ok(Some(map.to_str()?.to_string()))
})
// HACK: Don't use `TurbopackInternalError`, this function is race-condition prone (the
// source files may have changed or been deleted), so these probably aren't internal errors?
// Ideally we should differentiate.
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))
}
#[napi]
pub fn project_get_source_map_sync(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
file_path: RcStr,
) -> napi::Result<Option<String>> {
within_runtime_if_available(|| {
tokio::runtime::Handle::current().block_on(project_get_source_map(project, file_path))
})
}
#[napi]
pub async fn project_module_graph(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
) -> napi::Result<TurbopackResult<NapiModuleGraphSnapshot>> {
let container = project.container;
let (module_graph, issues, diagnostics) = project
.turbopack_ctx
.turbo_tasks()
.run_once(async move {
let module_graph_op = get_module_graph_with_issues_operation(container);
let ModuleGraphWithIssues {
module_graph,
issues,
diagnostics,
effects: _,
} = &*module_graph_op.connect().await?;
Ok((module_graph.clone(), issues.clone(), diagnostics.clone()))
})
.await
.map_err(|e| napi::Error::from_reason(PrettyPrintError(&e).to_string()))?;
Ok(TurbopackResult {
result: module_graph.map_or_else(NapiModuleGraphSnapshot::default, |m| {
NapiModuleGraphSnapshot::from(&*m)
}),
issues: issues.iter().map(|i| NapiIssue::from(&**i)).collect(),
diagnostics: diagnostics
.iter()
.map(|d| NapiDiagnostic::from(d))
.collect(),
})
}
#[turbo_tasks::value(serialization = "none")]
struct ModuleGraphWithIssues {
module_graph: Option<ReadRef<ModuleGraphSnapshot>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[turbo_tasks::function(operation)]
async fn get_module_graph_with_issues_operation(
project: ResolvedVc<ProjectContainer>,
) -> Result<Vc<ModuleGraphWithIssues>> {
let module_graph_op = get_module_graph_operation(project);
let (module_graph, issues, diagnostics, effects) =
strongly_consistent_catch_collectables(module_graph_op).await?;
Ok(ModuleGraphWithIssues {
module_graph,
issues,
diagnostics,
effects,
}
.cell())
}
#[turbo_tasks::function(operation)]
async fn get_module_graph_operation(
project: ResolvedVc<ProjectContainer>,
) -> Result<Vc<ModuleGraphSnapshot>> {
let project = project.project();
let graph = project.whole_app_module_graphs().await?.full;
let snapshot = get_module_graph_snapshot(*graph, None).resolve().await?;
Ok(snapshot)
}
|