@shell-shock/core 0.14.5 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -942,6 +942,998 @@ function SpawnFunctionDeclaration() {
942
942
  })
943
943
  ];
944
944
  }
945
+ /**
946
+ * Generates the `resolveModule` function declaration, which is a utility for resolving file paths across different platforms.
947
+ */
948
+ function ResolveModuleFunctionDeclaration() {
949
+ const context = usePowerlines();
950
+ return [
951
+ createComponent(Spacing, {}),
952
+ createComponent(InterfaceDeclaration, {
953
+ name: "ResolveModuleOptions",
954
+ doc: "Options for the `resolve` handler function.",
955
+ get children() {
956
+ return [
957
+ createComponent(InterfaceMember, {
958
+ name: "parentURL",
959
+ optional: true,
960
+ type: "string",
961
+ doc: "The parent URL to use for resolving paths."
962
+ }),
963
+ createIntrinsic("hbr", {}),
964
+ createComponent(InterfaceMember, {
965
+ name: "conditions",
966
+ optional: true,
967
+ type: "string[]",
968
+ doc: "The conditions to use for resolving paths."
969
+ }),
970
+ createIntrinsic("hbr", {})
971
+ ];
972
+ }
973
+ }),
974
+ createComponent(Spacing, {}),
975
+ createComponent(InterfaceDeclaration, {
976
+ name: "PackageConfig",
977
+ doc: "Parsed package.json configuration for module resolution.",
978
+ get children() {
979
+ return [
980
+ createComponent(InterfaceMember, {
981
+ name: "pjsonPath",
982
+ type: "string",
983
+ doc: "The path to the package.json file."
984
+ }),
985
+ createIntrinsic("hbr", {}),
986
+ createComponent(InterfaceMember, {
987
+ name: "exists",
988
+ type: "boolean",
989
+ doc: "Whether the package.json file exists."
990
+ }),
991
+ createIntrinsic("hbr", {}),
992
+ createComponent(InterfaceMember, {
993
+ name: "main",
994
+ optional: true,
995
+ type: "string",
996
+ doc: "The main entry point of the package."
997
+ }),
998
+ createIntrinsic("hbr", {}),
999
+ createComponent(InterfaceMember, {
1000
+ name: "name",
1001
+ optional: true,
1002
+ type: "string",
1003
+ doc: "The name of the package."
1004
+ }),
1005
+ createIntrinsic("hbr", {}),
1006
+ createComponent(InterfaceMember, {
1007
+ name: "type",
1008
+ optional: true,
1009
+ type: `"commonjs" | "module" | "none"`,
1010
+ doc: "The module type of the package."
1011
+ }),
1012
+ createIntrinsic("hbr", {}),
1013
+ createComponent(InterfaceMember, {
1014
+ name: "exports",
1015
+ optional: true,
1016
+ type: "Record<string, unknown>",
1017
+ doc: "The exports map of the package."
1018
+ }),
1019
+ createIntrinsic("hbr", {}),
1020
+ createComponent(InterfaceMember, {
1021
+ name: "imports",
1022
+ optional: true,
1023
+ type: "Record<string, unknown>",
1024
+ doc: "The imports map of the package."
1025
+ })
1026
+ ];
1027
+ }
1028
+ }),
1029
+ createComponent(Spacing, {}),
1030
+ createComponent(VarDeclaration, {
1031
+ "const": true,
1032
+ name: "DEFAULT_CONDITIONS_SET",
1033
+ initializer: code`new Set(["node", "import"]);`
1034
+ }),
1035
+ createComponent(Spacing, {}),
1036
+ createComponent(VarDeclaration, {
1037
+ "const": true,
1038
+ name: "DEFAULT_EXTENSIONS",
1039
+ initializer: code`[".mjs", ".cjs", ".js", ".json", ".node"];`
1040
+ }),
1041
+ createComponent(Spacing, {}),
1042
+ createComponent(VarDeclaration, {
1043
+ "const": true,
1044
+ name: "invalidPackageNameRegEx",
1045
+ initializer: code`/^\\.|\\/|%/;`
1046
+ }),
1047
+ createComponent(Spacing, {}),
1048
+ createComponent(FunctionDeclaration, {
1049
+ name: "readPackageConfig",
1050
+ parameters: [{
1051
+ name: "jsonPath",
1052
+ type: "string"
1053
+ }],
1054
+ returnType: "PackageConfig",
1055
+ children: code`const result: PackageConfig = {
1056
+ pjsonPath: jsonPath,
1057
+ exists: false,
1058
+ main: undefined,
1059
+ name: undefined,
1060
+ type: "none",
1061
+ exports: undefined,
1062
+ imports: undefined
1063
+ };
1064
+
1065
+ let content: string;
1066
+ try {
1067
+ content = readFileSync(jsonPath, "utf8");
1068
+ } catch (err: any) {
1069
+ if (err?.code === "ENOENT") {
1070
+ return result;
1071
+ }
1072
+ throw err;
1073
+ }
1074
+
1075
+ let parsed: Record<string, unknown>;
1076
+ try {
1077
+ parsed = JSON.parse(content);
1078
+ } catch {
1079
+ return result;
1080
+ }
1081
+
1082
+ result.exists = true;
1083
+
1084
+ if (typeof parsed.name === "string") {
1085
+ result.name = parsed.name;
1086
+ }
1087
+ if (typeof parsed.main === "string") {
1088
+ result.main = parsed.main;
1089
+ }
1090
+ if (parsed.exports !== undefined && parsed.exports !== null) {
1091
+ result.exports = parsed.exports as Record<string, unknown>;
1092
+ }
1093
+ if (parsed.imports !== undefined && parsed.imports !== null) {
1094
+ result.imports = parsed.imports as Record<string, unknown>;
1095
+ }
1096
+ if (parsed.type === "commonjs" || parsed.type === "module") {
1097
+ result.type = parsed.type;
1098
+ }
1099
+
1100
+ return result;`
1101
+ }),
1102
+ createComponent(Spacing, {}),
1103
+ createComponent(FunctionDeclaration, {
1104
+ name: "getPackageScopeConfig",
1105
+ parameters: [{
1106
+ name: "resolved",
1107
+ type: "URL | string"
1108
+ }],
1109
+ returnType: "PackageConfig",
1110
+ children: code`let packageJSONUrl = new URL("package.json", resolved);
1111
+
1112
+ while (true) {
1113
+ const packageJSONPath = packageJSONUrl.pathname;
1114
+ if (packageJSONPath.endsWith("node_modules/package.json")) {
1115
+ break;
1116
+ }
1117
+
1118
+ const packageConfig = readPackageConfig(fileURLToPath(packageJSONUrl));
1119
+ if (packageConfig.exists) {
1120
+ return packageConfig;
1121
+ }
1122
+
1123
+ const lastPackageJSONUrl = packageJSONUrl;
1124
+ packageJSONUrl = new URL("../package.json", packageJSONUrl);
1125
+
1126
+ if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
1127
+ break;
1128
+ }
1129
+ }
1130
+
1131
+ return {
1132
+ pjsonPath: fileURLToPath(packageJSONUrl),
1133
+ exists: false,
1134
+ type: "none"
1135
+ };`
1136
+ }),
1137
+ createComponent(Spacing, {}),
1138
+ createComponent(FunctionDeclaration, {
1139
+ name: "isConditionalExportsMainSugar",
1140
+ parameters: [{
1141
+ name: "exports",
1142
+ type: "unknown"
1143
+ }],
1144
+ returnType: "boolean",
1145
+ children: code`if (typeof exports === "string" || Array.isArray(exports)) {
1146
+ return true;
1147
+ }
1148
+ if (typeof exports !== "object" || exports === null) {
1149
+ return false;
1150
+ }
1151
+
1152
+ const keys = Object.getOwnPropertyNames(exports);
1153
+ let isConditionalSugar = false;
1154
+
1155
+ for (let i = 0; i < keys.length; i++) {
1156
+ const key = keys[i]!;
1157
+ const currentIsConditionalSugar = key === "" || key[0] !== ".";
1158
+ if (i === 0) {
1159
+ isConditionalSugar = currentIsConditionalSugar;
1160
+ } else if (isConditionalSugar !== currentIsConditionalSugar) {
1161
+ throw new Error(
1162
+ '"exports" cannot contain some keys starting with \\'.\\' and some not.'
1163
+ );
1164
+ }
1165
+ }
1166
+
1167
+ return isConditionalSugar;`
1168
+ }),
1169
+ createComponent(Spacing, {}),
1170
+ createComponent(FunctionDeclaration, {
1171
+ name: "resolvePackageTarget",
1172
+ parameters: [
1173
+ {
1174
+ name: "packageJsonUrl",
1175
+ type: "URL"
1176
+ },
1177
+ {
1178
+ name: "target",
1179
+ type: "unknown"
1180
+ },
1181
+ {
1182
+ name: "subpath",
1183
+ type: "string"
1184
+ },
1185
+ {
1186
+ name: "packageSubpath",
1187
+ type: "string"
1188
+ },
1189
+ {
1190
+ name: "base",
1191
+ type: "URL"
1192
+ },
1193
+ {
1194
+ name: "pattern",
1195
+ type: "boolean"
1196
+ },
1197
+ {
1198
+ name: "internal",
1199
+ type: "boolean"
1200
+ },
1201
+ {
1202
+ name: "conditions",
1203
+ type: "Set<string>"
1204
+ }
1205
+ ],
1206
+ returnType: "URL | null | undefined",
1207
+ children: code`if (typeof target === "string") {
1208
+ if (!target.startsWith("./")) {
1209
+ if (internal && !target.startsWith("../") && !target.startsWith("/")) {
1210
+ let isURL = false;
1211
+ try {
1212
+ new URL(target);
1213
+ isURL = true;
1214
+ } catch {}
1215
+
1216
+ if (!isURL) {
1217
+ const exportTarget = pattern
1218
+ ? target.replace(/\\*/g, () => subpath)
1219
+ : target + subpath;
1220
+ return packageResolve(exportTarget, packageJsonUrl, conditions);
1221
+ }
1222
+ }
1223
+ return null;
1224
+ }
1225
+
1226
+ const resolved = new URL(target, packageJsonUrl);
1227
+ const resolvedPath = resolved.pathname;
1228
+ const packagePath = new URL(".", packageJsonUrl).pathname;
1229
+
1230
+ if (!resolvedPath.startsWith(packagePath)) {
1231
+ return null;
1232
+ }
1233
+
1234
+ if (subpath === "") {
1235
+ return resolved;
1236
+ }
1237
+
1238
+ if (pattern) {
1239
+ return new URL(resolved.href.replace(/\\*/g, () => subpath));
1240
+ }
1241
+
1242
+ return new URL(subpath, resolved);
1243
+ }
1244
+
1245
+ if (Array.isArray(target)) {
1246
+ if (target.length === 0) {
1247
+ return null;
1248
+ }
1249
+
1250
+ let lastException: Error | null | undefined;
1251
+ for (const targetItem of target) {
1252
+ let resolveResult: URL | null | undefined;
1253
+ try {
1254
+ resolveResult = resolvePackageTarget(
1255
+ packageJsonUrl, targetItem, subpath, packageSubpath,
1256
+ base, pattern, internal, conditions
1257
+ );
1258
+ } catch (error: any) {
1259
+ lastException = error;
1260
+ if (error?.code === "ERR_INVALID_PACKAGE_TARGET") {
1261
+ continue;
1262
+ }
1263
+ throw error;
1264
+ }
1265
+
1266
+ if (resolveResult === undefined) {
1267
+ continue;
1268
+ }
1269
+ if (resolveResult === null) {
1270
+ lastException = null;
1271
+ continue;
1272
+ }
1273
+ return resolveResult;
1274
+ }
1275
+
1276
+ if (lastException === undefined || lastException === null) {
1277
+ return null;
1278
+ }
1279
+ throw lastException;
1280
+ }
1281
+
1282
+ if (typeof target === "object" && target !== null) {
1283
+ const keys = Object.getOwnPropertyNames(target);
1284
+ for (const key of keys) {
1285
+ if (key === "default" || conditions.has(key)) {
1286
+ const conditionalTarget = (target as Record<string, unknown>)[key];
1287
+ const resolveResult = resolvePackageTarget(
1288
+ packageJsonUrl, conditionalTarget, subpath, packageSubpath,
1289
+ base, pattern, internal, conditions
1290
+ );
1291
+ if (resolveResult === undefined) {
1292
+ continue;
1293
+ }
1294
+ return resolveResult;
1295
+ }
1296
+ }
1297
+ return null;
1298
+ }
1299
+
1300
+ if (target === null) {
1301
+ return null;
1302
+ }
1303
+
1304
+ return null;`
1305
+ }),
1306
+ createComponent(Spacing, {}),
1307
+ createComponent(FunctionDeclaration, {
1308
+ name: "packageExportsResolve",
1309
+ parameters: [
1310
+ {
1311
+ name: "packageJsonUrl",
1312
+ type: "URL"
1313
+ },
1314
+ {
1315
+ name: "packageSubpath",
1316
+ type: "string"
1317
+ },
1318
+ {
1319
+ name: "packageConfig",
1320
+ type: "PackageConfig"
1321
+ },
1322
+ {
1323
+ name: "base",
1324
+ type: "URL"
1325
+ },
1326
+ {
1327
+ name: "conditions",
1328
+ type: "Set<string>"
1329
+ }
1330
+ ],
1331
+ returnType: "URL | null | undefined",
1332
+ children: code`let exports = packageConfig.exports;
1333
+ if (isConditionalExportsMainSugar(exports)) {
1334
+ exports = { ".": exports } as Record<string, unknown>;
1335
+ }
1336
+
1337
+ if (
1338
+ exports !== undefined &&
1339
+ exports !== null &&
1340
+ typeof exports === "object" &&
1341
+ Object.prototype.hasOwnProperty.call(exports, packageSubpath) &&
1342
+ !packageSubpath.includes("*") &&
1343
+ !packageSubpath.endsWith("/")
1344
+ ) {
1345
+ const target = (exports as Record<string, unknown>)[packageSubpath];
1346
+ const resolveResult = resolvePackageTarget(
1347
+ packageJsonUrl, target, "", packageSubpath,
1348
+ base, false, false, conditions
1349
+ );
1350
+ if (resolveResult === null || resolveResult === undefined) {
1351
+ const err = new Error(
1352
+ \`Package subpath '\${packageSubpath}' is not defined by "exports" in \${fileURLToPath(packageJsonUrl)}\`
1353
+ );
1354
+ (err as any).code = "ERR_PACKAGE_PATH_NOT_EXPORTED";
1355
+ throw err;
1356
+ }
1357
+ return resolveResult;
1358
+ }
1359
+
1360
+ let bestMatch = "";
1361
+ let bestMatchSubpath = "";
1362
+ const keys = exports ? Object.getOwnPropertyNames(exports) : [];
1363
+
1364
+ for (const key of keys) {
1365
+ const patternIndex = key.indexOf("*");
1366
+ if (
1367
+ patternIndex !== -1 &&
1368
+ packageSubpath.startsWith(key.slice(0, patternIndex))
1369
+ ) {
1370
+ const patternTrailer = key.slice(patternIndex + 1);
1371
+ if (
1372
+ packageSubpath.length >= key.length &&
1373
+ packageSubpath.endsWith(patternTrailer) &&
1374
+ patternKeyCompare(bestMatch, key) === 1 &&
1375
+ key.lastIndexOf("*") === patternIndex
1376
+ ) {
1377
+ bestMatch = key;
1378
+ bestMatchSubpath = packageSubpath.slice(
1379
+ patternIndex,
1380
+ packageSubpath.length - patternTrailer.length
1381
+ );
1382
+ }
1383
+ }
1384
+ }
1385
+
1386
+ if (bestMatch) {
1387
+ const target = (exports as Record<string, unknown>)[bestMatch];
1388
+ const resolveResult = resolvePackageTarget(
1389
+ packageJsonUrl, target, bestMatchSubpath, bestMatch,
1390
+ base, true, false, conditions
1391
+ );
1392
+ if (resolveResult === null || resolveResult === undefined) {
1393
+ const err = new Error(
1394
+ \`Package subpath '\${packageSubpath}' is not defined by "exports" in \${fileURLToPath(packageJsonUrl)}\`
1395
+ );
1396
+ (err as any).code = "ERR_PACKAGE_PATH_NOT_EXPORTED";
1397
+ throw err;
1398
+ }
1399
+ return resolveResult;
1400
+ }
1401
+
1402
+ const err = new Error(
1403
+ \`Package subpath '\${packageSubpath}' is not defined by "exports" in \${fileURLToPath(packageJsonUrl)}\`
1404
+ );
1405
+ (err as any).code = "ERR_PACKAGE_PATH_NOT_EXPORTED";
1406
+ throw err;`
1407
+ }),
1408
+ createComponent(Spacing, {}),
1409
+ createComponent(FunctionDeclaration, {
1410
+ name: "patternKeyCompare",
1411
+ parameters: [{
1412
+ name: "a",
1413
+ type: "string"
1414
+ }, {
1415
+ name: "b",
1416
+ type: "string"
1417
+ }],
1418
+ returnType: "number",
1419
+ children: code`const aPatternIndex = a.indexOf("*");
1420
+ const bPatternIndex = b.indexOf("*");
1421
+ const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
1422
+ const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
1423
+ if (baseLengthA > baseLengthB) return -1;
1424
+ if (baseLengthB > baseLengthA) return 1;
1425
+ if (aPatternIndex === -1) return 1;
1426
+ if (bPatternIndex === -1) return -1;
1427
+ if (a.length > b.length) return -1;
1428
+ if (b.length > a.length) return 1;
1429
+ return 0;`
1430
+ }),
1431
+ createComponent(Spacing, {}),
1432
+ createComponent(FunctionDeclaration, {
1433
+ name: "legacyMainResolve",
1434
+ parameters: [{
1435
+ name: "packageJsonUrl",
1436
+ type: "URL"
1437
+ }, {
1438
+ name: "packageConfig",
1439
+ type: "PackageConfig"
1440
+ }],
1441
+ returnType: "URL | undefined",
1442
+ children: code`let guess: URL | undefined;
1443
+ const tries: string[] = [];
1444
+
1445
+ if (packageConfig.main !== undefined) {
1446
+ tries.push(
1447
+ \`./\${packageConfig.main}\`,
1448
+ \`./\${packageConfig.main}.js\`,
1449
+ \`./\${packageConfig.main}.json\`,
1450
+ \`./\${packageConfig.main}.node\`,
1451
+ \`./\${packageConfig.main}/index.js\`,
1452
+ \`./\${packageConfig.main}/index.json\`,
1453
+ \`./\${packageConfig.main}/index.node\`
1454
+ );
1455
+ }
1456
+
1457
+ tries.push("./index.js", "./index.json", "./index.node");
1458
+
1459
+ for (const entry of tries) {
1460
+ guess = new URL(entry, packageJsonUrl);
1461
+ try {
1462
+ const s = statSync(fileURLToPath(guess));
1463
+ if (s.isFile()) {
1464
+ return guess;
1465
+ }
1466
+ } catch {}
1467
+ guess = undefined;
1468
+ }
1469
+
1470
+ return undefined;`
1471
+ }),
1472
+ createComponent(Spacing, {}),
1473
+ createComponent(FunctionDeclaration, {
1474
+ name: "parsePackageName",
1475
+ parameters: [{
1476
+ name: "specifier",
1477
+ type: "string"
1478
+ }, {
1479
+ name: "base",
1480
+ type: "URL"
1481
+ }],
1482
+ returnType: "{ packageName: string; packageSubpath: string; isScoped: boolean }",
1483
+ children: code`let separatorIndex = specifier.indexOf("/");
1484
+ let validPackageName = true;
1485
+ let isScoped = false;
1486
+
1487
+ if (specifier[0] === "@") {
1488
+ isScoped = true;
1489
+ if (separatorIndex === -1 || specifier.length === 0) {
1490
+ validPackageName = false;
1491
+ } else {
1492
+ separatorIndex = specifier.indexOf("/", separatorIndex + 1);
1493
+ }
1494
+ }
1495
+
1496
+ const packageName = separatorIndex === -1
1497
+ ? specifier
1498
+ : specifier.slice(0, separatorIndex);
1499
+
1500
+ if (invalidPackageNameRegEx.exec(packageName) !== null) {
1501
+ validPackageName = false;
1502
+ }
1503
+
1504
+ if (!validPackageName) {
1505
+ const err = new Error(
1506
+ \`Invalid module "\${specifier}" is not a valid package name imported from \${fileURLToPath(base)}\`
1507
+ );
1508
+ (err as any).code = "ERR_INVALID_MODULE_SPECIFIER";
1509
+ throw err;
1510
+ }
1511
+
1512
+ const packageSubpath = "." + (separatorIndex === -1
1513
+ ? ""
1514
+ : specifier.slice(separatorIndex));
1515
+
1516
+ return { packageName, packageSubpath, isScoped };`
1517
+ }),
1518
+ createComponent(Spacing, {}),
1519
+ createComponent(FunctionDeclaration, {
1520
+ name: "packageResolve",
1521
+ parameters: [
1522
+ {
1523
+ name: "specifier",
1524
+ type: "string"
1525
+ },
1526
+ {
1527
+ name: "base",
1528
+ type: "URL"
1529
+ },
1530
+ {
1531
+ name: "conditions",
1532
+ type: "Set<string>"
1533
+ }
1534
+ ],
1535
+ returnType: "URL",
1536
+ children: code`if (builtinModules.includes(specifier)) {
1537
+ return new URL("node:" + specifier);
1538
+ }
1539
+
1540
+ const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base);
1541
+
1542
+ // Self-resolution: check if the specifier matches the current package name
1543
+ const selfConfig = getPackageScopeConfig(base);
1544
+ if (
1545
+ selfConfig.exists &&
1546
+ selfConfig.name === packageName &&
1547
+ selfConfig.exports !== undefined &&
1548
+ selfConfig.exports !== null
1549
+ ) {
1550
+ const packageJsonUrl = pathToFileURL(selfConfig.pjsonPath);
1551
+ const result = packageExportsResolve(
1552
+ packageJsonUrl, packageSubpath, selfConfig, base, conditions
1553
+ );
1554
+ if (result) {
1555
+ return result;
1556
+ }
1557
+ }
1558
+
1559
+ let packageJsonUrl = new URL(
1560
+ "./node_modules/" + packageName + "/package.json",
1561
+ base
1562
+ );
1563
+ let packageJsonPath = fileURLToPath(packageJsonUrl);
1564
+ let lastPath: string;
1565
+
1566
+ do {
1567
+ let stat: ReturnType<typeof statSync> | undefined;
1568
+ try {
1569
+ stat = statSync(packageJsonPath.slice(0, -13));
1570
+ } catch {}
1571
+
1572
+ if (!stat || !stat.isDirectory()) {
1573
+ lastPath = packageJsonPath;
1574
+ packageJsonUrl = new URL(
1575
+ (isScoped ? "../../../../node_modules/" : "../../../node_modules/") +
1576
+ packageName +
1577
+ "/package.json",
1578
+ packageJsonUrl
1579
+ );
1580
+ packageJsonPath = fileURLToPath(packageJsonUrl);
1581
+ continue;
1582
+ }
1583
+
1584
+ const packageConfig = readPackageConfig(packageJsonPath);
1585
+
1586
+ if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
1587
+ const result = packageExportsResolve(
1588
+ packageJsonUrl, packageSubpath, packageConfig, base, conditions
1589
+ );
1590
+ if (result) {
1591
+ return result;
1592
+ }
1593
+ }
1594
+
1595
+ if (packageSubpath === ".") {
1596
+ const legacyResult = legacyMainResolve(packageJsonUrl, packageConfig);
1597
+ if (legacyResult) {
1598
+ return legacyResult;
1599
+ }
1600
+
1601
+ return new URL(".", packageJsonUrl);
1602
+ }
1603
+
1604
+ return new URL(packageSubpath, packageJsonUrl);
1605
+ } while (packageJsonPath.length !== lastPath!.length);
1606
+
1607
+ const err = new Error(
1608
+ \`Cannot find package '\${packageName}' imported from \${fileURLToPath(base)}\`
1609
+ );
1610
+ (err as any).code = "ERR_MODULE_NOT_FOUND";
1611
+ throw err;`
1612
+ }),
1613
+ createComponent(Spacing, {}),
1614
+ createComponent(FunctionDeclaration, {
1615
+ name: "finalizeResolution",
1616
+ parameters: [{
1617
+ name: "resolved",
1618
+ type: "URL"
1619
+ }, {
1620
+ name: "base",
1621
+ type: "URL"
1622
+ }],
1623
+ returnType: "URL",
1624
+ children: code`if (/%2f|%5c/i.test(resolved.pathname)) {
1625
+ const err = new Error(
1626
+ \`Invalid module "\${resolved.pathname}" must not include encoded "/" or "\\\\" characters imported from \${fileURLToPath(base)}\`
1627
+ );
1628
+ (err as any).code = "ERR_INVALID_MODULE_SPECIFIER";
1629
+ throw err;
1630
+ }
1631
+
1632
+ const filePath = fileURLToPath(resolved);
1633
+
1634
+ let stat: ReturnType<typeof statSync> | undefined;
1635
+ try {
1636
+ stat = statSync(filePath.endsWith("/") ? filePath.slice(0, -1) : filePath);
1637
+ } catch {}
1638
+
1639
+ if (stat && stat.isDirectory()) {
1640
+ const err = new Error(
1641
+ \`Directory import '\${filePath}' is not supported resolving ES modules imported from \${fileURLToPath(base)}\`
1642
+ );
1643
+ (err as any).code = "ERR_UNSUPPORTED_DIR_IMPORT";
1644
+ throw err;
1645
+ }
1646
+
1647
+ if (!stat || !stat.isFile()) {
1648
+ const err = new Error(
1649
+ \`Cannot find module '\${filePath}' imported from \${fileURLToPath(base)}\`
1650
+ );
1651
+ (err as any).code = "ERR_MODULE_NOT_FOUND";
1652
+ throw err;
1653
+ }
1654
+
1655
+ const real = realpathSync(filePath);
1656
+ const { search, hash } = resolved;
1657
+ const realUrl = pathToFileURL(real + (filePath.endsWith(sep) ? "/" : ""));
1658
+ realUrl.search = search;
1659
+ realUrl.hash = hash;
1660
+
1661
+ return realUrl;`
1662
+ }),
1663
+ createComponent(Spacing, {}),
1664
+ createComponent(FunctionDeclaration, {
1665
+ name: "moduleResolve",
1666
+ parameters: [
1667
+ {
1668
+ name: "specifier",
1669
+ type: "string"
1670
+ },
1671
+ {
1672
+ name: "base",
1673
+ type: "URL"
1674
+ },
1675
+ {
1676
+ name: "conditions",
1677
+ type: "Set<string>"
1678
+ }
1679
+ ],
1680
+ returnType: "URL",
1681
+ children: code`let resolved: URL | undefined;
1682
+
1683
+ if (
1684
+ specifier[0] === "/" ||
1685
+ (specifier[0] === "." &&
1686
+ (specifier.length === 1 ||
1687
+ specifier[1] === "/" ||
1688
+ (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/"))))
1689
+ ) {
1690
+ try {
1691
+ resolved = new URL(specifier, base);
1692
+ } catch (error_: any) {
1693
+ const err = new Error(
1694
+ \`Failed to resolve module specifier "\${specifier}" from "\${base}": Invalid relative URL or base scheme is not hierarchical.\`
1695
+ );
1696
+ err.cause = error_;
1697
+ throw err;
1698
+ }
1699
+ } else if (base.protocol === "file:" && specifier[0] === "#") {
1700
+ const packageConfig = getPackageScopeConfig(base);
1701
+ if (packageConfig.exists && packageConfig.imports) {
1702
+ const packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);
1703
+ const imports = packageConfig.imports;
1704
+ if (Object.prototype.hasOwnProperty.call(imports, specifier) && !specifier.includes("*")) {
1705
+ const resolveResult = resolvePackageTarget(
1706
+ packageJsonUrl, imports[specifier], "", specifier,
1707
+ base, false, true, conditions
1708
+ );
1709
+ if (resolveResult !== null && resolveResult !== undefined) {
1710
+ resolved = resolveResult;
1711
+ }
1712
+ }
1713
+
1714
+ if (!resolved) {
1715
+ let bestMatch = "";
1716
+ let bestMatchSubpath = "";
1717
+ const keys = Object.getOwnPropertyNames(imports);
1718
+
1719
+ for (const key of keys) {
1720
+ const patternIndex = key.indexOf("*");
1721
+ if (patternIndex !== -1 && specifier.startsWith(key.slice(0, -1))) {
1722
+ const patternTrailer = key.slice(patternIndex + 1);
1723
+ if (
1724
+ specifier.length >= key.length &&
1725
+ specifier.endsWith(patternTrailer) &&
1726
+ patternKeyCompare(bestMatch, key) === 1 &&
1727
+ key.lastIndexOf("*") === patternIndex
1728
+ ) {
1729
+ bestMatch = key;
1730
+ bestMatchSubpath = specifier.slice(
1731
+ patternIndex,
1732
+ specifier.length - patternTrailer.length
1733
+ );
1734
+ }
1735
+ }
1736
+ }
1737
+
1738
+ if (bestMatch) {
1739
+ const target = imports[bestMatch];
1740
+ const resolveResult = resolvePackageTarget(
1741
+ packageJsonUrl, target, bestMatchSubpath, bestMatch,
1742
+ base, true, true, conditions
1743
+ );
1744
+ if (resolveResult !== null && resolveResult !== undefined) {
1745
+ resolved = resolveResult;
1746
+ }
1747
+ }
1748
+ }
1749
+ }
1750
+
1751
+ if (!resolved) {
1752
+ const err = new Error(
1753
+ \`Package import specifier "\${specifier}" is not defined in package imported from \${fileURLToPath(base)}\`
1754
+ );
1755
+ (err as any).code = "ERR_PACKAGE_IMPORT_NOT_DEFINED";
1756
+ throw err;
1757
+ }
1758
+ } else {
1759
+ try {
1760
+ resolved = new URL(specifier);
1761
+ } catch {
1762
+ resolved = packageResolve(specifier, base, conditions);
1763
+ }
1764
+ }
1765
+
1766
+ if (resolved.protocol !== "file:") {
1767
+ return resolved;
1768
+ }
1769
+
1770
+ return finalizeResolution(resolved, base);`
1771
+ }),
1772
+ createComponent(Spacing, {}),
1773
+ createComponent(FunctionDeclaration, {
1774
+ name: "tryModuleResolve",
1775
+ parameters: [
1776
+ {
1777
+ name: "id",
1778
+ type: "string"
1779
+ },
1780
+ {
1781
+ name: "url",
1782
+ type: "URL"
1783
+ },
1784
+ {
1785
+ name: "conditions",
1786
+ type: "Set<string>"
1787
+ }
1788
+ ],
1789
+ returnType: "URL | undefined",
1790
+ children: code`try {
1791
+ return moduleResolve(id, url, conditions);
1792
+ } catch (error: any) {
1793
+ if (
1794
+ !(error as { code: string })?.code &&
1795
+ ![
1796
+ "ERR_MODULE_NOT_FOUND",
1797
+ "ERR_UNSUPPORTED_DIR_IMPORT",
1798
+ "MODULE_NOT_FOUND",
1799
+ "ERR_PACKAGE_PATH_NOT_EXPORTED"
1800
+ ].includes(error?.code)
1801
+ ) {
1802
+ throw error;
1803
+ }
1804
+ }`
1805
+ }),
1806
+ createComponent(Spacing, {}),
1807
+ createComponent(TSDoc, {
1808
+ heading: "A function to resolve module specifiers to URLs.",
1809
+ get children() {
1810
+ return [
1811
+ createComponent(TSDocParam, {
1812
+ name: "specifier",
1813
+ children: `The module specifier to resolve.`
1814
+ }),
1815
+ createComponent(TSDocParam, {
1816
+ name: "options",
1817
+ children: `The options for resolving the module. Defaults to an empty object.`
1818
+ }),
1819
+ createComponent(TSDocReturns, { children: `The result of the resolve operation.` })
1820
+ ];
1821
+ }
1822
+ }),
1823
+ createComponent(FunctionDeclaration, {
1824
+ async: true,
1825
+ name: "resolveModule",
1826
+ parameters: [{
1827
+ name: "specifier",
1828
+ type: "string"
1829
+ }, {
1830
+ name: "options",
1831
+ type: "ResolveModuleOptions",
1832
+ default: "{} as ResolveModuleOptions"
1833
+ }],
1834
+ returnType: "Promise<string>",
1835
+ get children() {
1836
+ return code`const parentURL = options.parentURL ? new URL(options.parentURL) : undefined;
1837
+ const conditionsSet = options.conditions?.length
1838
+ ? new Set(options.conditions)
1839
+ : DEFAULT_CONDITIONS_SET;
1840
+
1841
+ // Handle protocol-prefixed specifiers (node:, data:, http:, https:, ${context.config.framework}:)
1842
+ if (/^(?:node|data|https?|${context.config.framework}):/.test(specifier)) {
1843
+ return specifier;
1844
+ }
1845
+
1846
+ const bareSpecifier = specifier.replace(/^node:/, "");
1847
+ if (builtinModules.includes(bareSpecifier)) {
1848
+ return "node:" + bareSpecifier;
1849
+ }
1850
+
1851
+ if (specifier.startsWith("file://")) {
1852
+ return specifier;
1853
+ }
1854
+
1855
+ if (isAbsolute(specifier)) {
1856
+ try {
1857
+ const s = statSync(specifier);
1858
+ if (s.isFile()) {
1859
+ return pathToFileURL(realpathSync(specifier)).href;
1860
+ }
1861
+ } catch (err: any) {
1862
+ if (err?.code !== "ENOENT") {
1863
+ throw err;
1864
+ }
1865
+ }
1866
+ }
1867
+
1868
+ const roots = [parentURL ?? pathToFileURL(join(process.cwd(), "_"))];
1869
+
1870
+ const projectRootURL = pathToFileURL("${context.config.root}");
1871
+ if (!roots.some(root => root.href === projectRootURL.href)) {
1872
+ roots.push(projectRootURL);
1873
+ }
1874
+
1875
+ const workspaceRootURL = pathToFileURL("${context.workspaceConfig.workspaceRoot}");
1876
+ if (!roots.some(root => root.href === workspaceRootURL.href)) {
1877
+ roots.push(workspaceRootURL);
1878
+ }
1879
+
1880
+ let resolved: URL | undefined;
1881
+ for (const root of roots) {
1882
+ const _urls: URL[] = [];
1883
+ _urls.push(root);
1884
+ if (root.protocol === "file:") {
1885
+ _urls.push(
1886
+ new URL("./", root),
1887
+ new URL(join(root.pathname, "_index.js"), root),
1888
+ new URL("node_modules", root)
1889
+ );
1890
+ }
1891
+
1892
+ for (const url of _urls) {
1893
+ resolved = tryModuleResolve(specifier, url, conditionsSet);
1894
+ if (resolved) {
1895
+ break;
1896
+ }
1897
+
1898
+ for (const prefix of ["", "/index"]) {
1899
+ for (const extension of DEFAULT_EXTENSIONS) {
1900
+ resolved = tryModuleResolve(
1901
+ specifier + prefix + extension,
1902
+ url,
1903
+ conditionsSet
1904
+ );
1905
+ if (resolved) {
1906
+ break;
1907
+ }
1908
+ }
1909
+ if (resolved) {
1910
+ break;
1911
+ }
1912
+ }
1913
+ if (resolved) {
1914
+ break;
1915
+ }
1916
+ }
1917
+
1918
+ if (resolved) {
1919
+ break;
1920
+ }
1921
+ }
1922
+
1923
+ if (!resolved) {
1924
+ const err = new Error(
1925
+ \`Cannot find module \${specifier} imported from \${base.href}\`
1926
+ );
1927
+ (err as any).code = "ERR_MODULE_NOT_FOUND";
1928
+ throw err;
1929
+ }
1930
+
1931
+ return pathToFileURL(fileURLToPath(resolved)).href;
1932
+ `;
1933
+ }
1934
+ })
1935
+ ];
1936
+ }
945
1937
  function ContextUtilities() {
946
1938
  return code`
947
1939
  /**
@@ -1043,15 +2035,22 @@ function UtilsBuiltin(props) {
1043
2035
  "normalize",
1044
2036
  "join",
1045
2037
  "posix",
1046
- "sep"
2038
+ "sep",
2039
+ "dirname",
2040
+ "isAbsolute"
1047
2041
  ],
1048
2042
  "node:fs": [
1049
2043
  "openSync",
1050
2044
  "closeSync",
1051
- "read"
2045
+ "read",
2046
+ "readFileSync",
2047
+ "statSync",
2048
+ "realpathSync"
1052
2049
  ],
1053
2050
  "node:fs/promises": ["stat"],
1054
2051
  "node:util": ["promisify"],
2052
+ "node:url": ["fileURLToPath", "pathToFileURL"],
2053
+ "node:module": ["builtinModules"],
1055
2054
  "node:child_process": [{
1056
2055
  name: "spawn",
1057
2056
  alias: "_spawn"
@@ -1110,6 +2109,8 @@ function UtilsBuiltin(props) {
1110
2109
  createComponent(Spacing, {}),
1111
2110
  createComponent(SpawnFunctionDeclaration, {}),
1112
2111
  createComponent(Spacing, {}),
2112
+ createComponent(ResolveModuleFunctionDeclaration, {}),
2113
+ createComponent(Spacing, {}),
1113
2114
  createComponent(FindSuggestionsDeclaration, {}),
1114
2115
  createComponent(Spacing, {}),
1115
2116
  createComponent(Show, {
@@ -1124,5 +2125,5 @@ function UtilsBuiltin(props) {
1124
2125
  }
1125
2126
 
1126
2127
  //#endregion
1127
- export { ArgsUtilities, ColorSupportUtilities, ContextUtilities, EnvSupportUtilities, FindSuggestionsDeclaration, HyperlinkSupportUtilities, SpawnFunctionDeclaration, UtilsBuiltin };
2128
+ export { ArgsUtilities, ColorSupportUtilities, ContextUtilities, EnvSupportUtilities, FindSuggestionsDeclaration, HyperlinkSupportUtilities, ResolveModuleFunctionDeclaration, SpawnFunctionDeclaration, UtilsBuiltin };
1128
2129
  //# sourceMappingURL=utils-builtin.mjs.map