@nasti-toolchain/nasti 1.3.1 → 1.3.3

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.
package/dist/cli.cjs CHANGED
@@ -725,6 +725,13 @@ async function transformRequest(url, ctx) {
725
725
  if (!filePath || !import_node_fs4.default.existsSync(filePath)) return null;
726
726
  const mod = await moduleGraph.ensureEntryFromUrl(url);
727
727
  moduleGraph.registerModule(mod, filePath);
728
+ const cleanReqUrl = url.split("?")[0];
729
+ if (cleanReqUrl.startsWith("/@modules/")) {
730
+ const code2 = await bundlePackageAsEsm(filePath);
731
+ const transformResult2 = { code: code2 };
732
+ mod.transformResult = transformResult2;
733
+ return transformResult2;
734
+ }
728
735
  let code = import_node_fs4.default.readFileSync(filePath, "utf-8");
729
736
  const pluginResult = await pluginContainer.transform(code, filePath);
730
737
  if (pluginResult) {
@@ -749,6 +756,67 @@ async function transformRequest(url, ctx) {
749
756
  mod.transformResult = transformResult;
750
757
  return transformResult;
751
758
  }
759
+ async function bundlePackageAsEsm(entryFile) {
760
+ if (!esmBundleCache.has(entryFile)) {
761
+ esmBundleCache.set(entryFile, doBundlePackage(entryFile));
762
+ }
763
+ return esmBundleCache.get(entryFile);
764
+ }
765
+ async function doBundlePackage(entryFile) {
766
+ const { rolldown: rolldown2 } = await import("rolldown");
767
+ const bundle = await rolldown2({
768
+ input: entryFile,
769
+ // 仅将其他 npm 包外部化;相对路径(包内部文件)全部内联打包
770
+ external: (id) => {
771
+ if (id.startsWith(".") || id.startsWith("/") || /^[A-Za-z]:\\/.test(id)) return false;
772
+ return true;
773
+ },
774
+ define: {
775
+ // CJS 包(如 react)通过 process.env.NODE_ENV 判断环境,需在打包时替换
776
+ "process.env.NODE_ENV": '"development"'
777
+ }
778
+ });
779
+ const result = await bundle.generate({ format: "esm", exports: "named" });
780
+ await bundle.close();
781
+ let code = result.output[0].code;
782
+ code = code.replace(/process\.env\.NODE_ENV/g, '"development"');
783
+ code = code.replace(
784
+ /^(import\b[^;'"]*?\bfrom\s+)(['"])([^'"./][^'"]*)(\2)/gm,
785
+ (_, prefix, q, spec) => `${prefix}${q}/@modules/${spec}${q}`
786
+ ).replace(
787
+ /^(export\b[^;'"]*?\bfrom\s+)(['"])([^'"./][^'"]*)(\2)/gm,
788
+ (_, prefix, q, spec) => `${prefix}${q}/@modules/${spec}${q}`
789
+ ).replace(
790
+ /^(import\s+)(['"])([^'"./][^'"]*)(\2)/gm,
791
+ (_, prefix, q, spec) => `${prefix}${q}/@modules/${spec}${q}`
792
+ );
793
+ if (code.includes("__commonJSMin")) {
794
+ code = await injectCjsNamedExports(code, entryFile);
795
+ }
796
+ return code;
797
+ }
798
+ async function injectCjsNamedExports(code, entryFile) {
799
+ try {
800
+ const { createRequire: createRequire2 } = await import("module");
801
+ const req = createRequire2(entryFile);
802
+ const cjsExports = req(entryFile);
803
+ if (!cjsExports || typeof cjsExports !== "object" || Array.isArray(cjsExports)) return code;
804
+ const namedKeys = Object.keys(cjsExports).filter(
805
+ (k) => k !== "__esModule" && k !== "default" && VALID_IDENT.test(k)
806
+ );
807
+ if (namedKeys.length === 0) return code;
808
+ return code.replace(
809
+ /^export default (\w+\(\));?\s*$/m,
810
+ (_, call) => [
811
+ `const __cjsMod = ${call};`,
812
+ `export default __cjsMod;`,
813
+ ...namedKeys.map((k) => `export const ${k} = __cjsMod[${JSON.stringify(k)}];`)
814
+ ].join("\n")
815
+ );
816
+ } catch {
817
+ return code;
818
+ }
819
+ }
752
820
  function rewriteImports(code, _config) {
753
821
  return code.replace(
754
822
  /\bfrom\s+(['"])([^'"./][^'"]*)\1/g,
@@ -769,16 +837,92 @@ function rewriteImports(code, _config) {
769
837
  }
770
838
  );
771
839
  }
840
+ function resolveNodeModule(root, moduleName) {
841
+ let pkgName;
842
+ let subpath;
843
+ if (moduleName.startsWith("@")) {
844
+ const parts = moduleName.split("/");
845
+ pkgName = parts.slice(0, 2).join("/");
846
+ subpath = parts.slice(2).join("/");
847
+ } else {
848
+ const slash = moduleName.indexOf("/");
849
+ pkgName = slash === -1 ? moduleName : moduleName.slice(0, slash);
850
+ subpath = slash === -1 ? "" : moduleName.slice(slash + 1);
851
+ }
852
+ let pkgDir = null;
853
+ let dir = root;
854
+ for (; ; ) {
855
+ const candidate = import_node_path4.default.join(dir, "node_modules", pkgName);
856
+ if (import_node_fs4.default.existsSync(candidate)) {
857
+ pkgDir = candidate;
858
+ break;
859
+ }
860
+ const parent = import_node_path4.default.dirname(dir);
861
+ if (parent === dir) break;
862
+ dir = parent;
863
+ }
864
+ if (!pkgDir) return null;
865
+ const pkgJsonPath = import_node_path4.default.join(pkgDir, "package.json");
866
+ if (!import_node_fs4.default.existsSync(pkgJsonPath)) return null;
867
+ let pkg;
868
+ try {
869
+ pkg = JSON.parse(import_node_fs4.default.readFileSync(pkgJsonPath, "utf-8"));
870
+ } catch {
871
+ return null;
872
+ }
873
+ if (pkg.exports) {
874
+ const exportKey = subpath ? `./${subpath}` : ".";
875
+ const resolved = resolvePackageExports(pkg.exports, exportKey, pkgDir);
876
+ if (resolved) return resolved;
877
+ }
878
+ if (subpath) {
879
+ const direct = import_node_path4.default.join(pkgDir, subpath);
880
+ if (import_node_fs4.default.existsSync(direct) && import_node_fs4.default.statSync(direct).isFile()) return direct;
881
+ for (const ext of RESOLVE_EXTENSIONS) {
882
+ if (import_node_fs4.default.existsSync(direct + ext)) return direct + ext;
883
+ }
884
+ return null;
885
+ }
886
+ for (const field of ["module", "jsnext:main", "jsnext", "main"]) {
887
+ if (typeof pkg[field] === "string") {
888
+ const entry = import_node_path4.default.join(pkgDir, pkg[field]);
889
+ if (import_node_fs4.default.existsSync(entry)) return entry;
890
+ }
891
+ }
892
+ return null;
893
+ }
894
+ function resolvePackageExports(exports2, key, pkgDir) {
895
+ if (typeof exports2 === "string") {
896
+ return key === "." ? import_node_path4.default.join(pkgDir, exports2) : null;
897
+ }
898
+ const entry = exports2[key];
899
+ if (entry === void 0) return null;
900
+ return resolveExportValue(entry, pkgDir);
901
+ }
902
+ function resolveExportValue(value, pkgDir) {
903
+ if (typeof value === "string") return import_node_path4.default.join(pkgDir, value);
904
+ if (Array.isArray(value)) {
905
+ for (const item of value) {
906
+ const r = resolveExportValue(item, pkgDir);
907
+ if (r) return r;
908
+ }
909
+ return null;
910
+ }
911
+ if (value && typeof value === "object") {
912
+ for (const cond of ESM_CONDITIONS) {
913
+ if (cond in value) {
914
+ const r = resolveExportValue(value[cond], pkgDir);
915
+ if (r) return r;
916
+ }
917
+ }
918
+ }
919
+ return null;
920
+ }
772
921
  function resolveUrlToFile(url, root) {
773
922
  const cleanUrl = url.split("?")[0];
774
923
  if (cleanUrl.startsWith("/@modules/")) {
775
924
  const moduleName = cleanUrl.slice("/@modules/".length);
776
- try {
777
- const req = (0, import_node_module.createRequire)(import_node_path4.default.resolve(root, "package.json"));
778
- return req.resolve(moduleName);
779
- } catch {
780
- return null;
781
- }
925
+ return resolveNodeModule(root, moduleName);
782
926
  }
783
927
  const filePath = import_node_path4.default.resolve(root, cleanUrl.replace(/^\//, ""));
784
928
  if (import_node_fs4.default.existsSync(filePath) && import_node_fs4.default.statSync(filePath).isFile()) {
@@ -899,17 +1043,19 @@ if (!window.__nasti_hot_map) window.__nasti_hot_map = new Map();
899
1043
  window.__NASTI_HMR__ = { createHotContext };
900
1044
  `;
901
1045
  }
902
- var import_node_path4, import_node_fs4, import_node_module, RESOLVE_EXTENSIONS;
1046
+ var import_node_path4, import_node_fs4, esmBundleCache, VALID_IDENT, RESOLVE_EXTENSIONS, ESM_CONDITIONS;
903
1047
  var init_middleware = __esm({
904
1048
  "src/server/middleware.ts"() {
905
1049
  "use strict";
906
1050
  import_node_path4 = __toESM(require("path"), 1);
907
1051
  import_node_fs4 = __toESM(require("fs"), 1);
908
- import_node_module = require("module");
909
1052
  init_transformer();
910
1053
  init_html();
911
1054
  init_env();
1055
+ esmBundleCache = /* @__PURE__ */ new Map();
1056
+ VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
912
1057
  RESOLVE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".json", ".vue"];
1058
+ ESM_CONDITIONS = ["import", "browser", "module", "default"];
913
1059
  }
914
1060
  });
915
1061
 
@@ -973,7 +1119,7 @@ var init_hmr = __esm({
973
1119
  // src/plugins/resolve.ts
974
1120
  function resolvePlugin(config) {
975
1121
  const { alias, extensions } = config.resolve;
976
- const require2 = (0, import_node_module2.createRequire)(import_node_path6.default.resolve(config.root, "package.json"));
1122
+ const require2 = (0, import_node_module.createRequire)(import_node_path6.default.resolve(config.root, "package.json"));
977
1123
  return {
978
1124
  name: "nasti:resolve",
979
1125
  enforce: "pre",
@@ -1039,13 +1185,13 @@ function tryResolveFile(file, extensions) {
1039
1185
  }
1040
1186
  return null;
1041
1187
  }
1042
- var import_node_path6, import_node_fs6, import_node_module2;
1188
+ var import_node_path6, import_node_fs6, import_node_module;
1043
1189
  var init_resolve = __esm({
1044
1190
  "src/plugins/resolve.ts"() {
1045
1191
  "use strict";
1046
1192
  import_node_path6 = __toESM(require("path"), 1);
1047
1193
  import_node_fs6 = __toESM(require("fs"), 1);
1048
- import_node_module2 = require("module");
1194
+ import_node_module = require("module");
1049
1195
  }
1050
1196
  });
1051
1197
 
@@ -1246,7 +1392,7 @@ async function createServer(inlineConfig = {}) {
1246
1392
  const localUrl = `http://localhost:${actualPort}`;
1247
1393
  const networkUrl = host === "0.0.0.0" ? `http://${getNetworkAddress()}:${actualPort}` : null;
1248
1394
  console.log();
1249
- console.log(import_picocolors.default.cyan(" nasti dev server") + import_picocolors.default.dim(` v${"1.3.1"}`));
1395
+ console.log(import_picocolors.default.cyan(" nasti dev server") + import_picocolors.default.dim(` v${"1.3.3"}`));
1250
1396
  console.log();
1251
1397
  console.log(` ${import_picocolors.default.green(">")} Local: ${import_picocolors.default.cyan(localUrl)}`);
1252
1398
  if (networkUrl) {
@@ -1324,7 +1470,7 @@ __export(build_exports, {
1324
1470
  async function build(inlineConfig = {}) {
1325
1471
  const config = await resolveConfig(inlineConfig, "build");
1326
1472
  const startTime = performance.now();
1327
- console.log(import_picocolors2.default.cyan("\n\u{1F528} nasti build") + import_picocolors2.default.dim(` v${"1.3.1"}`));
1473
+ console.log(import_picocolors2.default.cyan("\n\u{1F528} nasti build") + import_picocolors2.default.dim(` v${"1.3.3"}`));
1328
1474
  console.log(import_picocolors2.default.dim(` root: ${config.root}`));
1329
1475
  console.log(import_picocolors2.default.dim(` mode: ${config.mode}`));
1330
1476
  const outDir = import_node_path10.default.resolve(config.root, config.build.outDir);
@@ -1549,6 +1695,6 @@ cli.command("preview [root]", "Preview production build").option("--port <port>"
1549
1695
  }
1550
1696
  });
1551
1697
  cli.help();
1552
- cli.version("1.3.1");
1698
+ cli.version("1.3.3");
1553
1699
  cli.parse();
1554
1700
  //# sourceMappingURL=cli.cjs.map