weapp-vite 5.6.3 → 5.7.1

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.mjs CHANGED
@@ -1,24 +1,23 @@
1
1
  import {
2
2
  createCompilerContext
3
- } from "./chunk-7EOV7C3M.mjs";
3
+ } from "./chunk-AXUA33LJ.mjs";
4
4
  import {
5
5
  DEFAULT_MP_PLATFORM,
6
+ SHARED_CHUNK_VIRTUAL_PREFIX,
6
7
  VERSION,
7
8
  checkRuntime,
9
+ createSharedBuildConfig,
8
10
  logger_default,
9
11
  normalizeMiniPlatform,
10
12
  resolveMiniPlatform,
11
13
  resolveWeappConfigFile
12
- } from "./chunk-LE4PAGI5.mjs";
14
+ } from "./chunk-O4FBXXL3.mjs";
13
15
  import {
14
16
  init_esm_shims
15
17
  } from "./chunk-SSQGJIB5.mjs";
16
18
 
17
19
  // src/cli.ts
18
20
  init_esm_shims();
19
- import process3 from "process";
20
- import { createProject, initConfig } from "@weapp-core/init";
21
- import { defu as defu2 } from "@weapp-core/shared";
22
21
 
23
22
  // ../../node_modules/.pnpm/cac@6.7.14/node_modules/cac/dist/index.mjs
24
23
  init_esm_shims();
@@ -123,7 +122,7 @@ var findAllBrackets = (v) => {
123
122
  const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
124
123
  const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
125
124
  const res = [];
126
- const parse2 = (match) => {
125
+ const parse3 = (match) => {
127
126
  let variadic = false;
128
127
  let value = match[1];
129
128
  if (value.startsWith("...")) {
@@ -138,11 +137,11 @@ var findAllBrackets = (v) => {
138
137
  };
139
138
  let angledMatch;
140
139
  while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
141
- res.push(parse2(angledMatch));
140
+ res.push(parse3(angledMatch));
142
141
  }
143
142
  let squareMatch;
144
143
  while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
145
- res.push(parse2(squareMatch));
144
+ res.push(parse3(squareMatch));
146
145
  }
147
146
  return res;
148
147
  };
@@ -606,360 +605,529 @@ var CAC = class extends EventEmitter {
606
605
  };
607
606
  var cac = (name = "") => new CAC(name);
608
607
 
609
- // ../../node_modules/.pnpm/package-manager-detector@1.5.0/node_modules/package-manager-detector/dist/commands.mjs
608
+ // src/cli/commands/analyze.ts
610
609
  init_esm_shims();
611
- function dashDashArg(agent, agentCommand) {
612
- return (args) => {
613
- if (args.length > 1) {
614
- return [agent, agentCommand, args[0], "--", ...args.slice(1)];
615
- } else {
616
- return [agent, agentCommand, args[0]];
617
- }
610
+ import process3 from "process";
611
+ import fs2 from "fs-extra";
612
+ import path2 from "pathe";
613
+
614
+ // src/analyze/subpackages.ts
615
+ init_esm_shims();
616
+ import { Buffer } from "buffer";
617
+ import { posix as path } from "pathe";
618
+ import { build } from "vite";
619
+ var VIRTUAL_MODULE_INDICATOR = "\0";
620
+ var VIRTUAL_PREFIX = `${SHARED_CHUNK_VIRTUAL_PREFIX}/`;
621
+ function isPathInside(parent, candidate) {
622
+ if (!parent) {
623
+ return false;
624
+ }
625
+ const relative = path.relative(parent, candidate);
626
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
627
+ }
628
+ function ensurePackage(packages, classification) {
629
+ const existing = packages.get(classification.id);
630
+ if (existing) {
631
+ return existing;
632
+ }
633
+ const created = {
634
+ ...classification,
635
+ files: /* @__PURE__ */ new Map()
618
636
  };
637
+ packages.set(classification.id, created);
638
+ return created;
619
639
  }
620
- function denoExecute() {
621
- return (args) => {
622
- return ["deno", "run", `npm:${args[0]}`, ...args.slice(1)];
640
+ function ensureModule(modules, id, source, sourceType) {
641
+ const existing = modules.get(id);
642
+ if (existing) {
643
+ return existing;
644
+ }
645
+ const created = {
646
+ id,
647
+ source,
648
+ sourceType,
649
+ packages: /* @__PURE__ */ new Map()
623
650
  };
651
+ modules.set(id, created);
652
+ return created;
624
653
  }
625
- var npm = {
626
- "agent": ["npm", 0],
627
- "run": dashDashArg("npm", "run"),
628
- "install": ["npm", "i", 0],
629
- "frozen": ["npm", "ci", 0],
630
- "global": ["npm", "i", "-g", 0],
631
- "add": ["npm", "i", 0],
632
- "upgrade": ["npm", "update", 0],
633
- "upgrade-interactive": null,
634
- "dedupe": ["npm", "dedupe", 0],
635
- "execute": ["npx", 0],
636
- "execute-local": ["npx", 0],
637
- "uninstall": ["npm", "uninstall", 0],
638
- "global_uninstall": ["npm", "uninstall", "-g", 0]
639
- };
640
- var yarn = {
641
- "agent": ["yarn", 0],
642
- "run": ["yarn", "run", 0],
643
- "install": ["yarn", "install", 0],
644
- "frozen": ["yarn", "install", "--frozen-lockfile", 0],
645
- "global": ["yarn", "global", "add", 0],
646
- "add": ["yarn", "add", 0],
647
- "upgrade": ["yarn", "upgrade", 0],
648
- "upgrade-interactive": ["yarn", "upgrade-interactive", 0],
649
- "dedupe": null,
650
- "execute": ["npx", 0],
651
- "execute-local": dashDashArg("yarn", "exec"),
652
- "uninstall": ["yarn", "remove", 0],
653
- "global_uninstall": ["yarn", "global", "remove", 0]
654
- };
655
- var yarnBerry = {
656
- ...yarn,
657
- "frozen": ["yarn", "install", "--immutable", 0],
658
- "upgrade": ["yarn", "up", 0],
659
- "upgrade-interactive": ["yarn", "up", "-i", 0],
660
- "dedupe": ["yarn", "dedupe", 0],
661
- "execute": ["yarn", "dlx", 0],
662
- "execute-local": ["yarn", "exec", 0],
663
- // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821
664
- "global": ["npm", "i", "-g", 0],
665
- "global_uninstall": ["npm", "uninstall", "-g", 0]
666
- };
667
- var pnpm = {
668
- "agent": ["pnpm", 0],
669
- "run": ["pnpm", "run", 0],
670
- "install": ["pnpm", "i", 0],
671
- "frozen": ["pnpm", "i", "--frozen-lockfile", 0],
672
- "global": ["pnpm", "add", "-g", 0],
673
- "add": ["pnpm", "add", 0],
674
- "upgrade": ["pnpm", "update", 0],
675
- "upgrade-interactive": ["pnpm", "update", "-i", 0],
676
- "dedupe": ["pnpm", "dedupe", 0],
677
- "execute": ["pnpm", "dlx", 0],
678
- "execute-local": ["pnpm", "exec", 0],
679
- "uninstall": ["pnpm", "remove", 0],
680
- "global_uninstall": ["pnpm", "remove", "--global", 0]
681
- };
682
- var bun = {
683
- "agent": ["bun", 0],
684
- "run": ["bun", "run", 0],
685
- "install": ["bun", "install", 0],
686
- "frozen": ["bun", "install", "--frozen-lockfile", 0],
687
- "global": ["bun", "add", "-g", 0],
688
- "add": ["bun", "add", 0],
689
- "upgrade": ["bun", "update", 0],
690
- "upgrade-interactive": ["bun", "update", "-i", 0],
691
- "dedupe": null,
692
- "execute": ["bun", "x", 0],
693
- "execute-local": ["bun", "x", 0],
694
- "uninstall": ["bun", "remove", 0],
695
- "global_uninstall": ["bun", "remove", "-g", 0]
696
- };
697
- var deno = {
698
- "agent": ["deno", 0],
699
- "run": ["deno", "task", 0],
700
- "install": ["deno", "install", 0],
701
- "frozen": ["deno", "install", "--frozen", 0],
702
- "global": ["deno", "install", "-g", 0],
703
- "add": ["deno", "add", 0],
704
- "upgrade": ["deno", "outdated", "--update", 0],
705
- "upgrade-interactive": ["deno", "outdated", "--update", 0],
706
- "dedupe": null,
707
- "execute": denoExecute(),
708
- "execute-local": ["deno", "task", "--eval", 0],
709
- "uninstall": ["deno", "remove", 0],
710
- "global_uninstall": ["deno", "uninstall", "-g", 0]
711
- };
712
- var COMMANDS = {
713
- "npm": npm,
714
- "yarn": yarn,
715
- "yarn@berry": yarnBerry,
716
- "pnpm": pnpm,
717
- // pnpm v6.x or below
718
- "pnpm@6": {
719
- ...pnpm,
720
- run: dashDashArg("pnpm", "run")
721
- },
722
- "bun": bun,
723
- "deno": deno
724
- };
725
- function resolveCommand(agent, command, args) {
726
- const value = COMMANDS[agent][command];
727
- return constructCommand(value, args);
654
+ function registerModuleInPackage(modules, moduleId, source, sourceType, packageId, fileName) {
655
+ const moduleEntry = ensureModule(modules, moduleId, source, sourceType);
656
+ const files = moduleEntry.packages.get(packageId) ?? /* @__PURE__ */ new Set();
657
+ files.add(fileName);
658
+ moduleEntry.packages.set(packageId, files);
728
659
  }
729
- function constructCommand(value, args) {
730
- if (value == null)
731
- return null;
732
- const list = typeof value === "function" ? value(args) : value.flatMap((v) => {
733
- if (typeof v === "number")
734
- return args;
735
- return [v];
736
- });
660
+ function classifyPackage(fileName, origin, context) {
661
+ if (fileName.startsWith(VIRTUAL_PREFIX)) {
662
+ const combination = fileName.slice(VIRTUAL_PREFIX.length).split("/")[0] || "shared";
663
+ return {
664
+ id: `virtual:${combination}`,
665
+ label: `\u5171\u4EAB\u865A\u62DF\u5305 ${combination}`,
666
+ type: "virtual"
667
+ };
668
+ }
669
+ const segments = fileName.split("/");
670
+ const rootCandidate = segments[0] ?? "";
671
+ if (rootCandidate && context.subPackageRoots.has(rootCandidate)) {
672
+ const isIndependent = context.independentRoots.has(rootCandidate);
673
+ return {
674
+ id: rootCandidate,
675
+ label: `${isIndependent ? "\u72EC\u7ACB\u5206\u5305" : "\u5206\u5305"} ${rootCandidate}`,
676
+ type: isIndependent || origin === "independent" ? "independent" : "subPackage"
677
+ };
678
+ }
737
679
  return {
738
- command: list[0],
739
- args: list.slice(1)
680
+ id: "__main__",
681
+ label: "\u4E3B\u5305",
682
+ type: "main"
740
683
  };
741
684
  }
742
-
743
- // src/cli.ts
744
- import path2 from "pathe";
745
- import { loadConfigFromFile } from "vite";
746
- import { parse } from "weapp-ide-cli";
747
-
748
- // src/schematics.ts
749
- init_esm_shims();
750
- import process2 from "process";
751
- import { generateJs, generateJson, generateWxml, generateWxss } from "@weapp-core/schematics";
752
- import { defu } from "@weapp-core/shared";
753
- import fs from "fs-extra";
754
- import path from "pathe";
755
- function composePath(outDir, filename) {
756
- return `${outDir}${outDir ? "/" : ""}${filename}`;
757
- }
758
- var defaultExtensions = {
759
- js: "js",
760
- json: "json",
761
- wxml: "wxml",
762
- wxss: "wxss"
763
- };
764
- function resolveExtension(extension) {
765
- return extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
766
- }
767
- async function readTemplateFile(templatePath, context) {
768
- const absolutePath = path.isAbsolute(templatePath) ? templatePath : path.resolve(context.cwd, templatePath);
769
- return fs.readFile(absolutePath, "utf8");
770
- }
771
- async function loadTemplate(template, context) {
772
- if (template === void 0) {
685
+ function normalizeModuleId(id) {
686
+ if (!id || id.includes(VIRTUAL_MODULE_INDICATOR)) {
773
687
  return void 0;
774
688
  }
775
- if (typeof template === "function") {
776
- const result = await template(context);
777
- return result == null ? void 0 : String(result);
689
+ if (!path.isAbsolute(id)) {
690
+ return void 0;
778
691
  }
779
- if (typeof template === "string") {
780
- return readTemplateFile(template, context);
692
+ return path.normalize(id);
693
+ }
694
+ function resolveModuleSourceType(absoluteId, ctx) {
695
+ const { configService } = ctx;
696
+ const isNodeModule = absoluteId.includes("/node_modules/") || absoluteId.includes("\\node_modules\\");
697
+ const pluginRoot = configService.absolutePluginRoot;
698
+ const srcRoot = configService.absoluteSrcRoot;
699
+ const inSrc = isPathInside(srcRoot, absoluteId);
700
+ const inPlugin = pluginRoot ? isPathInside(pluginRoot, absoluteId) : false;
701
+ let sourceType;
702
+ if (isNodeModule) {
703
+ sourceType = "node_modules";
704
+ } else if (inSrc) {
705
+ sourceType = "src";
706
+ } else if (inPlugin) {
707
+ sourceType = "plugin";
708
+ } else {
709
+ sourceType = "workspace";
781
710
  }
782
- if ("content" in template && typeof template.content === "string") {
783
- return template.content;
711
+ return {
712
+ source: configService.relativeAbsoluteSrcRoot(absoluteId),
713
+ sourceType
714
+ };
715
+ }
716
+ function resolveAssetSource(fileName, ctx) {
717
+ const { configService } = ctx;
718
+ const normalized = path.normalize(fileName);
719
+ const srcCandidate = path.resolve(configService.absoluteSrcRoot, normalized);
720
+ if (isPathInside(configService.absoluteSrcRoot, srcCandidate)) {
721
+ return {
722
+ absolute: srcCandidate,
723
+ source: configService.relativeAbsoluteSrcRoot(srcCandidate),
724
+ sourceType: "src"
725
+ };
784
726
  }
785
- if ("path" in template && typeof template.path === "string") {
786
- return readTemplateFile(template.path, context);
727
+ const pluginRoot = configService.absolutePluginRoot;
728
+ if (pluginRoot) {
729
+ const pluginBase = path.basename(pluginRoot);
730
+ if (normalized === pluginBase || normalized.startsWith(`${pluginBase}/`)) {
731
+ const relative = normalized === pluginBase ? "" : normalized.slice(pluginBase.length + 1);
732
+ const absolute = path.resolve(pluginRoot, relative);
733
+ if (isPathInside(pluginRoot, absolute)) {
734
+ return {
735
+ absolute,
736
+ source: configService.relativeAbsoluteSrcRoot(absolute),
737
+ sourceType: "plugin"
738
+ };
739
+ }
740
+ }
787
741
  }
788
- return void 0;
789
742
  }
790
- function resolveTemplate(templates, type, fileType) {
791
- const scoped = templates?.[type]?.[fileType];
792
- if (scoped !== void 0) {
793
- return scoped;
794
- }
795
- return templates?.shared?.[fileType];
743
+ function toArray(value) {
744
+ return Array.from(value);
796
745
  }
797
- async function generate(options) {
798
- let { fileName, outDir, extensions, type, cwd, templates } = defu(options, {
799
- type: "component",
800
- extensions: {
801
- ...defaultExtensions
802
- },
803
- cwd: process2.cwd(),
804
- templates: void 0
805
- });
806
- if (fileName === void 0) {
807
- fileName = path.basename(outDir);
746
+ function getAssetSize(asset) {
747
+ if (typeof asset.source === "string") {
748
+ return Buffer.byteLength(asset.source, "utf8");
808
749
  }
809
- const basepath = path.resolve(cwd, outDir);
810
- const targetFileTypes = type === "app" ? ["js", "wxss", "json"] : ["js", "wxss", "json", "wxml"];
811
- const files = [];
812
- for (const fileType of targetFileTypes) {
813
- const configuredExt = extensions[fileType] ?? defaultExtensions[fileType];
814
- let resolvedExt = configuredExt;
815
- let defaultCode;
816
- if (fileType === "js") {
817
- defaultCode = generateJs(type);
818
- } else if (fileType === "wxss") {
819
- defaultCode = generateWxss();
820
- } else if (fileType === "wxml") {
821
- defaultCode = generateWxml(path.join(outDir, fileName));
822
- } else if (fileType === "json") {
823
- defaultCode = generateJson(type, configuredExt);
824
- if (configuredExt === "js" || configuredExt === "ts") {
825
- resolvedExt = `json.${configuredExt}`;
826
- }
750
+ if (asset.source instanceof Uint8Array) {
751
+ return asset.source.byteLength;
752
+ }
753
+ }
754
+ function processChunk(chunk, origin, ctx, classifierContext, packages, modules) {
755
+ const classification = classifyPackage(chunk.fileName, origin, classifierContext);
756
+ const packageEntry = ensurePackage(packages, classification);
757
+ const chunkEntry = {
758
+ file: chunk.fileName,
759
+ type: "chunk",
760
+ from: origin,
761
+ size: typeof chunk.code === "string" ? Buffer.byteLength(chunk.code, "utf8") : void 0,
762
+ isEntry: chunk.isEntry,
763
+ modules: []
764
+ };
765
+ const moduleEntries = Object.entries(chunk.modules ?? {});
766
+ for (const [rawModuleId, info] of moduleEntries) {
767
+ const absoluteId = normalizeModuleId(rawModuleId);
768
+ if (!absoluteId) {
769
+ continue;
827
770
  }
828
- const context = {
829
- type,
830
- fileType,
831
- fileName,
832
- outDir,
833
- extension: resolvedExt,
834
- cwd,
835
- defaultCode
771
+ const { source, sourceType } = resolveModuleSourceType(absoluteId, ctx);
772
+ const moduleEntry = {
773
+ id: absoluteId,
774
+ source,
775
+ sourceType,
776
+ bytes: info?.renderedLength
836
777
  };
837
- const template = resolveTemplate(templates, type, fileType);
838
- const customCode = await loadTemplate(template, context);
839
- const finalCode = customCode ?? defaultCode;
840
- if (finalCode !== void 0) {
841
- files.push({
842
- fileName: `${fileName}${resolveExtension(resolvedExt)}`,
843
- code: finalCode
844
- });
778
+ if (typeof info?.code === "string") {
779
+ moduleEntry.originalBytes = Buffer.byteLength(info.code, "utf8");
845
780
  }
781
+ chunkEntry.modules.push(moduleEntry);
782
+ registerModuleInPackage(
783
+ modules,
784
+ absoluteId,
785
+ source,
786
+ sourceType,
787
+ classification.id,
788
+ chunk.fileName
789
+ );
846
790
  }
847
- for (const { code, fileName: fileName2 } of files) {
848
- if (code !== void 0) {
849
- await fs.outputFile(path.resolve(basepath, fileName2), code, "utf8");
850
- logger_default.success(`${composePath(outDir, fileName2)} \u521B\u5EFA\u6210\u529F\uFF01`);
851
- }
791
+ if (chunkEntry.modules) {
792
+ chunkEntry.modules.sort((a, b) => a.source.localeCompare(b.source));
852
793
  }
794
+ packageEntry.files.set(chunk.fileName, chunkEntry);
853
795
  }
854
-
855
- // src/cli.ts
856
- var cli = cac("weapp-vite");
857
- try {
858
- checkRuntime({
859
- bun: "0.0.0",
860
- deno: "0.0.0",
861
- node: "20.19.0"
862
- });
863
- } catch {
796
+ function processAsset(asset, origin, ctx, classifierContext, packages, modules) {
797
+ const classification = classifyPackage(asset.fileName, origin, classifierContext);
798
+ const packageEntry = ensurePackage(packages, classification);
799
+ const entry = {
800
+ file: asset.fileName,
801
+ type: "asset",
802
+ from: origin,
803
+ size: getAssetSize(asset)
804
+ };
805
+ const assetSource = resolveAssetSource(asset.fileName, ctx);
806
+ if (assetSource) {
807
+ entry.source = assetSource.source;
808
+ registerModuleInPackage(
809
+ modules,
810
+ assetSource.absolute,
811
+ assetSource.source,
812
+ assetSource.sourceType,
813
+ classification.id,
814
+ asset.fileName
815
+ );
816
+ }
817
+ packageEntry.files.set(asset.fileName, entry);
864
818
  }
865
- async function loadConfig(configFile) {
866
- const cwd = process3.cwd();
867
- let resolvedConfigFile = configFile;
868
- if (resolvedConfigFile && !path2.isAbsolute(resolvedConfigFile)) {
869
- resolvedConfigFile = path2.resolve(cwd, resolvedConfigFile);
819
+ function processOutput(output, origin, ctx, classifierContext, packages, modules) {
820
+ if (!output) {
821
+ return;
870
822
  }
871
- const configEnv = {
872
- command: "serve",
873
- mode: "development"
823
+ for (const item of output.output ?? []) {
824
+ if (item.type === "chunk") {
825
+ processChunk(item, origin, ctx, classifierContext, packages, modules);
826
+ } else if (item.type === "asset") {
827
+ processAsset(item, origin, ctx, classifierContext, packages, modules);
828
+ }
829
+ }
830
+ }
831
+ function summarizePackages(packages) {
832
+ const order = {
833
+ main: 0,
834
+ subPackage: 1,
835
+ independent: 2,
836
+ virtual: 3
874
837
  };
875
- const loaded = await loadConfigFromFile(configEnv, resolvedConfigFile, cwd);
876
- const weappConfigFilePath = await resolveWeappConfigFile({
877
- root: cwd,
878
- specified: resolvedConfigFile
838
+ const reports = toArray(packages.values()).map((pkg) => {
839
+ const files = toArray(pkg.files.values());
840
+ files.sort((a, b) => a.file.localeCompare(b.file));
841
+ return {
842
+ id: pkg.id,
843
+ label: pkg.label,
844
+ type: pkg.type,
845
+ files
846
+ };
879
847
  });
880
- let weappLoaded;
881
- if (weappConfigFilePath) {
882
- const normalizedWeappPath = path2.resolve(weappConfigFilePath);
883
- const normalizedLoadedPath = loaded?.path ? path2.resolve(loaded.path) : void 0;
884
- if (normalizedLoadedPath && normalizedLoadedPath === normalizedWeappPath) {
885
- weappLoaded = loaded;
886
- } else {
887
- weappLoaded = await loadConfigFromFile(configEnv, weappConfigFilePath, cwd);
848
+ reports.sort((a, b) => {
849
+ const delta = order[a.type] - order[b.type];
850
+ if (delta !== 0) {
851
+ return delta;
852
+ }
853
+ if (a.id === "__main__") {
854
+ return -1;
855
+ }
856
+ if (b.id === "__main__") {
857
+ return 1;
858
+ }
859
+ return a.id.localeCompare(b.id);
860
+ });
861
+ return reports;
862
+ }
863
+ function summarizeModules(modules) {
864
+ const usage = toArray(modules.values()).map((module) => {
865
+ const packages = toArray(module.packages.entries()).map(([packageId, files]) => {
866
+ const sortedFiles = toArray(files).sort((a, b) => a.localeCompare(b));
867
+ return {
868
+ packageId,
869
+ files: sortedFiles
870
+ };
871
+ }).sort((a, b) => {
872
+ if (a.packageId === b.packageId) {
873
+ return 0;
874
+ }
875
+ if (a.packageId === "__main__") {
876
+ return -1;
877
+ }
878
+ if (b.packageId === "__main__") {
879
+ return 1;
880
+ }
881
+ return a.packageId.localeCompare(b.packageId);
882
+ });
883
+ return {
884
+ id: module.id,
885
+ source: module.source,
886
+ sourceType: module.sourceType,
887
+ packages
888
+ };
889
+ });
890
+ usage.sort((a, b) => a.source.localeCompare(b.source));
891
+ return usage;
892
+ }
893
+ function expandVirtualModulePlacements(modules, packages, context) {
894
+ for (const moduleEntry of modules.values()) {
895
+ const virtualEntries = Array.from(moduleEntry.packages.entries()).filter(([packageId]) => packageId.startsWith("virtual:"));
896
+ if (!virtualEntries.length) {
897
+ continue;
898
+ }
899
+ const virtualFileBases = /* @__PURE__ */ new Map();
900
+ for (const [virtualPackageId, files] of virtualEntries) {
901
+ const combination = virtualPackageId.slice("virtual:".length);
902
+ if (!combination) {
903
+ continue;
904
+ }
905
+ const segments = combination.split(/[_+]/).map((segment) => segment.trim()).filter(Boolean);
906
+ if (!segments.length) {
907
+ continue;
908
+ }
909
+ let matchingBases = virtualFileBases.get(virtualPackageId);
910
+ if (!matchingBases) {
911
+ matchingBases = Array.from(files).map((file) => path.basename(file));
912
+ virtualFileBases.set(virtualPackageId, matchingBases);
913
+ }
914
+ for (const root of segments) {
915
+ if (!context.subPackageRoots.has(root)) {
916
+ continue;
917
+ }
918
+ const targetPackage = packages.get(root);
919
+ if (!targetPackage) {
920
+ continue;
921
+ }
922
+ const moduleFiles = moduleEntry.packages.get(root) ?? /* @__PURE__ */ new Set();
923
+ const targetFiles = Array.from(targetPackage.files.values()).filter((fileEntry) => {
924
+ if (!matchingBases?.length) {
925
+ return true;
926
+ }
927
+ const base = path.basename(fileEntry.file);
928
+ return matchingBases.includes(base);
929
+ }).map((fileEntry) => fileEntry.file);
930
+ if (targetFiles.length === 0) {
931
+ const fallback = targetPackage.files.values().next().value;
932
+ if (fallback) {
933
+ moduleFiles.add(fallback.file);
934
+ }
935
+ } else {
936
+ for (const fileName of targetFiles) {
937
+ moduleFiles.add(fileName);
938
+ }
939
+ }
940
+ if (moduleFiles.size > 0) {
941
+ moduleEntry.packages.set(root, moduleFiles);
942
+ }
943
+ }
888
944
  }
889
945
  }
890
- if (!loaded && !weappLoaded) {
891
- return void 0;
892
- }
893
- const config = loaded?.config ?? (weappLoaded?.config ?? {});
894
- if (weappLoaded?.config?.weapp) {
895
- config.weapp = defu2(
896
- weappLoaded.config.weapp,
897
- config.weapp ?? {}
898
- );
899
- }
900
- const dependencySet = /* @__PURE__ */ new Set();
901
- for (const dependency of loaded?.dependencies ?? []) {
902
- dependencySet.add(dependency);
903
- }
904
- for (const dependency of weappLoaded?.dependencies ?? []) {
905
- dependencySet.add(dependency);
946
+ }
947
+ function summarizeSubPackages(metas) {
948
+ const descriptors = metas.map((meta) => {
949
+ const root = meta.subPackage.root ?? "";
950
+ return {
951
+ root,
952
+ independent: Boolean(meta.subPackage.independent),
953
+ name: meta.subPackage.name
954
+ };
955
+ }).filter((descriptor) => descriptor.root);
956
+ descriptors.sort((a, b) => a.root.localeCompare(b.root));
957
+ return descriptors;
958
+ }
959
+ async function analyzeSubpackages(ctx) {
960
+ const { configService, scanService, buildService } = ctx;
961
+ if (!configService || !scanService || !buildService) {
962
+ throw new Error("analyzeSubpackages requires configService, scanService and buildService to be initialized");
963
+ }
964
+ await scanService.loadAppEntry();
965
+ const subPackageMetas = scanService.loadSubPackages();
966
+ const subPackageRoots = /* @__PURE__ */ new Set();
967
+ const independentRoots = /* @__PURE__ */ new Set();
968
+ for (const meta of subPackageMetas) {
969
+ const root = meta.subPackage.root;
970
+ if (root) {
971
+ subPackageRoots.add(root);
972
+ if (meta.subPackage.independent) {
973
+ independentRoots.add(root);
974
+ }
975
+ }
906
976
  }
977
+ const classifierContext = {
978
+ subPackageRoots,
979
+ independentRoots
980
+ };
981
+ const analysisConfig = configService.merge(
982
+ void 0,
983
+ createSharedBuildConfig(configService, scanService),
984
+ {
985
+ build: {
986
+ write: false,
987
+ watch: null
988
+ }
989
+ }
990
+ );
991
+ const mainResult = await build(analysisConfig);
992
+ const mainOutputs = Array.isArray(mainResult) ? mainResult : [mainResult];
993
+ const packages = /* @__PURE__ */ new Map();
994
+ const modules = /* @__PURE__ */ new Map();
995
+ for (const output of mainOutputs) {
996
+ processOutput(output, "main", ctx, classifierContext, packages, modules);
997
+ }
998
+ for (const root of independentRoots) {
999
+ const output = buildService.getIndependentOutput(root);
1000
+ processOutput(output, "independent", ctx, classifierContext, packages, modules);
1001
+ }
1002
+ expandVirtualModulePlacements(modules, packages, classifierContext);
907
1003
  return {
908
- config,
909
- path: weappLoaded?.path ?? loaded?.path ?? resolvedConfigFile,
910
- dependencies: Array.from(dependencySet)
1004
+ packages: summarizePackages(packages),
1005
+ modules: summarizeModules(modules),
1006
+ subPackages: summarizeSubPackages(subPackageMetas)
911
1007
  };
912
1008
  }
913
- var logBuildAppFinishOnlyShowOnce = false;
914
- function logBuildAppFinish(configService, webServer, options = {}) {
915
- if (logBuildAppFinishOnlyShowOnce) {
916
- return;
1009
+
1010
+ // src/cli/analyze/dashboard.ts
1011
+ init_esm_shims();
1012
+ import { dirname, resolve } from "path";
1013
+ import process2 from "process";
1014
+ import { fileURLToPath } from "url";
1015
+ import fs from "fs-extra";
1016
+ import { createServer } from "vite";
1017
+ var __filename2 = fileURLToPath(import.meta.url);
1018
+ var __dirname2 = dirname(__filename2);
1019
+ var PACKAGE_ROOT = resolve(__dirname2, "../../..");
1020
+ var BUILD_DASHBOARD_ROOT = resolve(PACKAGE_ROOT, "modules/analyze-dashboard");
1021
+ var ANALYZE_GLOBAL_KEY = "__WEAPP_VITE_ANALYZE_RESULT__";
1022
+ function resolveDashboardRoot() {
1023
+ if (fs.existsSync(BUILD_DASHBOARD_ROOT)) {
1024
+ return {
1025
+ root: BUILD_DASHBOARD_ROOT
1026
+ };
917
1027
  }
918
- const { skipMini = false, skipWeb = false } = options;
919
- if (skipMini) {
920
- if (webServer) {
921
- const urls = webServer.resolvedUrls;
922
- const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
923
- if (candidates.length > 0) {
924
- logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A");
925
- for (const url of candidates) {
926
- logger_default.info(` \u279C ${url}`);
927
- }
928
- } else {
929
- logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
930
- }
931
- } else {
932
- logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1028
+ throw new Error(
1029
+ "[weapp-vite analyze] \u672A\u627E\u5230\u4EEA\u8868\u76D8\u4EA7\u7269\uFF0C\u8BF7\u5148\u6267\u884C `pnpm --filter weapp-vite run build:dashboard` \u751F\u6210\u3002"
1030
+ );
1031
+ }
1032
+ function createAnalyzeHtmlPlugin(state, onServerInstance) {
1033
+ return {
1034
+ name: "weapp-vite-analyze-html",
1035
+ transformIndexHtml(html) {
1036
+ return {
1037
+ html,
1038
+ tags: [
1039
+ {
1040
+ tag: "script",
1041
+ children: `window.${ANALYZE_GLOBAL_KEY} = ${JSON.stringify(state.current)}`,
1042
+ injectTo: "head-prepend"
1043
+ }
1044
+ ]
1045
+ };
1046
+ },
1047
+ configureServer(server) {
1048
+ onServerInstance(server);
933
1049
  }
934
- logBuildAppFinishOnlyShowOnce = true;
935
- return;
936
- }
937
- const { command, args } = resolveCommand(
938
- configService.packageManager.agent,
939
- "run",
940
- ["open"]
941
- ) ?? {
942
- command: "npm",
943
- args: ["run", "open"]
944
1050
  };
945
- const devCommand = `${command} ${args.join(" ")}`;
946
- logger_default.success("\u5E94\u7528\u6784\u5EFA\u5B8C\u6210\uFF01\u9884\u89C8\u65B9\u5F0F ( `2` \u79CD\u9009\u5176\u4E00\u5373\u53EF)\uFF1A");
947
- logger_default.info(`\u6267\u884C \`${devCommand}\` \u53EF\u4EE5\u76F4\u63A5\u5728 \`\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\` \u91CC\u6253\u5F00\u5F53\u524D\u5E94\u7528`);
948
- logger_default.info("\u6216\u624B\u52A8\u6253\u5F00\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\uFF0C\u5BFC\u5165\u6839\u76EE\u5F55(`project.config.json` \u6587\u4EF6\u6240\u5728\u7684\u76EE\u5F55)\uFF0C\u5373\u53EF\u9884\u89C8\u6548\u679C");
949
- if (!skipWeb && webServer) {
950
- const urls = webServer.resolvedUrls;
951
- const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
952
- if (candidates.length > 0) {
953
- logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A");
954
- for (const url of candidates) {
955
- logger_default.info(` \u279C ${url}`);
1051
+ }
1052
+ async function waitForServerExit(server) {
1053
+ let resolved = false;
1054
+ const cleanup = async () => {
1055
+ if (resolved) {
1056
+ return;
1057
+ }
1058
+ resolved = true;
1059
+ try {
1060
+ await server.close();
1061
+ } catch (error) {
1062
+ logger_default.error(error);
1063
+ }
1064
+ };
1065
+ const signals = ["SIGINT", "SIGTERM"];
1066
+ await new Promise((resolvePromise) => {
1067
+ const resolveOnce = async () => {
1068
+ await cleanup();
1069
+ signals.forEach((signal) => {
1070
+ process2.removeListener(signal, resolveOnce);
1071
+ });
1072
+ resolvePromise();
1073
+ };
1074
+ signals.forEach((signal) => {
1075
+ process2.once(signal, resolveOnce);
1076
+ });
1077
+ server.httpServer?.once("close", resolveOnce);
1078
+ });
1079
+ }
1080
+ async function startAnalyzeDashboard(result, options) {
1081
+ const { root } = resolveDashboardRoot();
1082
+ const state = { current: result };
1083
+ let serverRef;
1084
+ const plugins = [
1085
+ createAnalyzeHtmlPlugin(state, (server2) => {
1086
+ serverRef = server2;
1087
+ })
1088
+ ];
1089
+ const server = await createServer({
1090
+ root,
1091
+ clearScreen: false,
1092
+ appType: "spa",
1093
+ publicDir: false,
1094
+ plugins,
1095
+ server: {
1096
+ host: "127.0.0.1",
1097
+ port: 0
1098
+ },
1099
+ logLevel: "error"
1100
+ });
1101
+ await server.listen();
1102
+ serverRef ??= server;
1103
+ server.printUrls();
1104
+ logger_default.info("\u5206\u6790\u4EEA\u8868\u76D8\u5DF2\u542F\u52A8\uFF08\u4F7F\u7528\u9884\u6784\u5EFA\u8D44\u6E90\uFF09\uFF0C\u6309 Ctrl+C \u9000\u51FA\u3002");
1105
+ const waitPromise = waitForServerExit(server);
1106
+ const handle = {
1107
+ async update(nextResult) {
1108
+ state.current = nextResult;
1109
+ if (serverRef) {
1110
+ serverRef.ws.send({
1111
+ type: "custom",
1112
+ event: "weapp-analyze:update",
1113
+ data: nextResult
1114
+ });
956
1115
  }
957
- } else {
958
- logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1116
+ },
1117
+ waitForExit: () => waitPromise,
1118
+ close: async () => {
1119
+ await server.close();
959
1120
  }
1121
+ };
1122
+ if (options?.watch) {
1123
+ void waitPromise;
1124
+ return handle;
960
1125
  }
961
- logBuildAppFinishOnlyShowOnce = true;
1126
+ await waitPromise;
962
1127
  }
1128
+
1129
+ // src/cli/options.ts
1130
+ init_esm_shims();
963
1131
  function filterDuplicateOptions(options) {
964
1132
  for (const [key, value] of Object.entries(options)) {
965
1133
  if (Array.isArray(value)) {
@@ -975,19 +1143,40 @@ function resolveConfigFile(options) {
975
1143
  return options.c;
976
1144
  }
977
1145
  }
978
- function convertBase(v) {
979
- if (v === 0) {
1146
+ function convertBase(value) {
1147
+ if (value === 0) {
980
1148
  return "";
981
1149
  }
982
- return v;
1150
+ return value;
983
1151
  }
984
- async function openIde() {
985
- try {
986
- await parse(["open", "-p"]);
987
- } catch (error) {
988
- logger_default.error(error);
1152
+ function coerceBooleanOption(value) {
1153
+ if (value === void 0) {
1154
+ return void 0;
1155
+ }
1156
+ if (typeof value === "boolean") {
1157
+ return value;
1158
+ }
1159
+ if (typeof value === "string") {
1160
+ const normalized = value.trim().toLowerCase();
1161
+ if (normalized === "") {
1162
+ return true;
1163
+ }
1164
+ if (normalized === "false" || normalized === "0" || normalized === "off" || normalized === "no") {
1165
+ return false;
1166
+ }
1167
+ if (normalized === "true" || normalized === "1" || normalized === "on" || normalized === "yes") {
1168
+ return true;
1169
+ }
1170
+ return true;
989
1171
  }
1172
+ if (typeof value === "number") {
1173
+ return value !== 0;
1174
+ }
1175
+ return Boolean(value);
990
1176
  }
1177
+
1178
+ // src/cli/runtime.ts
1179
+ init_esm_shims();
991
1180
  function logRuntimeTarget(targets) {
992
1181
  logger_default.info(`\u76EE\u6807\u5E73\u53F0\uFF1A${targets.label}`);
993
1182
  }
@@ -1045,134 +1234,706 @@ function createInlineConfig(mpPlatform) {
1045
1234
  }
1046
1235
  };
1047
1236
  }
1048
- cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, {
1049
- type: [convertBase]
1050
- }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
1051
- cli.command("[root]", "start dev server").alias("serve").alias("dev").option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).action(async (root, options) => {
1052
- filterDuplicateOptions(options);
1053
- const configFile = resolveConfigFile(options);
1054
- const targets = resolveRuntimeTargets(options);
1055
- logRuntimeTarget(targets);
1056
- const inlineConfig = createInlineConfig(targets.mpPlatform);
1057
- const { buildService, configService, webService } = await createCompilerContext({
1058
- cwd: root,
1059
- mode: options.mode ?? "development",
1060
- isDev: true,
1061
- configFile,
1062
- inlineConfig
1063
- });
1064
- if (targets.runMini) {
1065
- await buildService.build(options);
1237
+
1238
+ // src/cli/commands/analyze.ts
1239
+ function printAnalysisSummary(result) {
1240
+ const packageLabelMap = /* @__PURE__ */ new Map();
1241
+ const packageModuleSet = /* @__PURE__ */ new Map();
1242
+ for (const pkg of result.packages) {
1243
+ packageLabelMap.set(pkg.id, pkg.label);
1244
+ }
1245
+ for (const module of result.modules) {
1246
+ for (const pkgRef of module.packages) {
1247
+ const set = packageModuleSet.get(pkgRef.packageId) ?? /* @__PURE__ */ new Set();
1248
+ set.add(module.id);
1249
+ packageModuleSet.set(pkgRef.packageId, set);
1250
+ }
1066
1251
  }
1067
- let webServer;
1068
- if (targets.runWeb) {
1069
- try {
1070
- webServer = await webService?.startDevServer();
1071
- } catch (error) {
1072
- logger_default.error(error);
1073
- throw error;
1252
+ logger_default.success("\u5206\u5305\u5206\u6790\u5B8C\u6210");
1253
+ for (const pkg of result.packages) {
1254
+ const chunkCount = pkg.files.filter((file) => file.type === "chunk").length;
1255
+ const assetCount = pkg.files.length - chunkCount;
1256
+ const moduleCount = packageModuleSet.get(pkg.id)?.size ?? 0;
1257
+ logger_default.info(`- ${pkg.label}\uFF1A${chunkCount} \u4E2A\u6A21\u5757\u4EA7\u7269\uFF0C${assetCount} \u4E2A\u8D44\u6E90\uFF0C\u8986\u76D6 ${moduleCount} \u4E2A\u6E90\u7801\u6A21\u5757`);
1258
+ }
1259
+ if (result.subPackages.length > 0) {
1260
+ logger_default.info("\u5206\u5305\u914D\u7F6E\uFF1A");
1261
+ for (const descriptor of result.subPackages) {
1262
+ const segments = [descriptor.root];
1263
+ if (descriptor.name) {
1264
+ segments.push(`\u522B\u540D\uFF1A${descriptor.name}`);
1265
+ }
1266
+ if (descriptor.independent) {
1267
+ segments.push("\u72EC\u7ACB\u6784\u5EFA");
1268
+ }
1269
+ logger_default.info(`- ${segments.join("\uFF0C")}`);
1074
1270
  }
1075
1271
  }
1076
- if (targets.runMini) {
1077
- logBuildAppFinish(configService, webServer, { skipWeb: !targets.runWeb });
1078
- } else if (targets.runWeb) {
1079
- logBuildAppFinish(configService, webServer, { skipMini: true });
1272
+ const duplicates = result.modules.filter((module) => module.packages.length > 1);
1273
+ if (duplicates.length === 0) {
1274
+ logger_default.info("\u672A\u68C0\u6D4B\u5230\u8DE8\u5305\u590D\u7528\u7684\u6E90\u7801\u6A21\u5757\u3002");
1275
+ return;
1080
1276
  }
1081
- if (options.open && targets.runMini) {
1082
- await openIde();
1277
+ logger_default.info(`\u8DE8\u5305\u590D\u7528/\u590D\u5236\u6E90\u7801\u5171 ${duplicates.length} \u9879\uFF1A`);
1278
+ const limit = 10;
1279
+ const entries = duplicates.slice(0, limit);
1280
+ for (const module of entries) {
1281
+ const placements = module.packages.map((pkgRef) => {
1282
+ const label = packageLabelMap.get(pkgRef.packageId) ?? pkgRef.packageId;
1283
+ return `${label} \u2192 ${pkgRef.files.join(", ")}`;
1284
+ }).join("\uFF1B");
1285
+ logger_default.info(`- ${module.source} (${module.sourceType})\uFF1A${placements}`);
1083
1286
  }
1084
- });
1085
- cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option(
1086
- "--sourcemap [output]",
1087
- `[boolean | "inline" | "hidden"] output source maps for build (default: false)`
1088
- ).option(
1089
- "--minify [minifier]",
1090
- `[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)`
1091
- ).option(
1092
- "--emptyOutDir",
1093
- `[boolean] force empty outDir when it's outside of root`
1094
- ).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).action(async (root, options) => {
1095
- filterDuplicateOptions(options);
1096
- const configFile = resolveConfigFile(options);
1097
- const targets = resolveRuntimeTargets(options);
1098
- logRuntimeTarget(targets);
1099
- const inlineConfig = createInlineConfig(targets.mpPlatform);
1100
- const { buildService, configService, webService } = await createCompilerContext({
1101
- cwd: root,
1102
- mode: options.mode ?? "production",
1103
- configFile,
1104
- inlineConfig
1105
- });
1106
- if (targets.runMini) {
1107
- await buildService.build(options);
1287
+ if (duplicates.length > limit) {
1288
+ logger_default.info(`- \u2026\u5176\u4F59 ${duplicates.length - limit} \u9879\u8BF7\u4F7F\u7528 \`weapp-vite analyze --json\` \u67E5\u770B`);
1108
1289
  }
1109
- const webConfig = configService.weappWebConfig;
1110
- if (targets.runWeb && webConfig?.enabled) {
1290
+ }
1291
+ function registerAnalyzeCommand(cli2) {
1292
+ cli2.command("analyze [root]", "analyze \u4E24\u7AEF\u5305\u4F53\u4E0E\u6E90\u7801\u6620\u5C04").option("--json", `[boolean] \u8F93\u51FA JSON \u7ED3\u679C`).option("--output <file>", `[string] \u5C06\u5206\u6790\u7ED3\u679C\u5199\u5165\u6307\u5B9A\u6587\u4EF6\uFF08JSON\uFF09`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).action(async (root, options) => {
1293
+ filterDuplicateOptions(options);
1294
+ const configFile = resolveConfigFile(options);
1295
+ const targets = resolveRuntimeTargets(options);
1296
+ logRuntimeTarget(targets);
1297
+ if (!targets.runMini) {
1298
+ logger_default.warn("\u5F53\u524D\u547D\u4EE4\u4EC5\u652F\u6301\u5C0F\u7A0B\u5E8F\u5E73\u53F0\uFF0C\u8BF7\u901A\u8FC7 --platform weapp \u6307\u5B9A\u76EE\u6807\u3002");
1299
+ return;
1300
+ }
1301
+ if (targets.runWeb) {
1302
+ logger_default.warn("\u5206\u6790\u547D\u4EE4\u6682\u4E0D\u652F\u6301 Web \u5E73\u53F0\uFF0C\u5C06\u5FFD\u7565\u76F8\u5173\u914D\u7F6E\u3002");
1303
+ }
1304
+ const inlineConfig = createInlineConfig(targets.mpPlatform);
1111
1305
  try {
1112
- await webService?.build();
1113
- logger_default.success(`Web \u6784\u5EFA\u5B8C\u6210\uFF0C\u8F93\u51FA\u76EE\u5F55\uFF1A${configService.relativeCwd(webConfig.outDir)}`);
1306
+ const ctx = await createCompilerContext({
1307
+ cwd: root,
1308
+ mode: options.mode ?? "production",
1309
+ configFile,
1310
+ inlineConfig
1311
+ });
1312
+ const result = await analyzeSubpackages(ctx);
1313
+ const outputJson = coerceBooleanOption(options.json);
1314
+ const outputOption = typeof options.output === "string" ? options.output.trim() : "";
1315
+ let writtenPath;
1316
+ if (outputOption) {
1317
+ const configService = ctx.configService;
1318
+ const baseDir = configService?.cwd ?? process3.cwd();
1319
+ const resolvedOutputPath = path2.isAbsolute(outputOption) ? outputOption : path2.resolve(baseDir, outputOption);
1320
+ await fs2.ensureDir(path2.dirname(resolvedOutputPath));
1321
+ await fs2.writeFile(resolvedOutputPath, `${JSON.stringify(result, null, 2)}
1322
+ `, "utf8");
1323
+ const relativeOutput = configService ? configService.relativeCwd(resolvedOutputPath) : resolvedOutputPath;
1324
+ logger_default.success(`\u5206\u6790\u7ED3\u679C\u5DF2\u5199\u5165 ${relativeOutput}`);
1325
+ writtenPath = resolvedOutputPath;
1326
+ }
1327
+ if (outputJson) {
1328
+ if (!writtenPath) {
1329
+ process3.stdout.write(`${JSON.stringify(result, null, 2)}
1330
+ `);
1331
+ }
1332
+ } else {
1333
+ printAnalysisSummary(result);
1334
+ await startAnalyzeDashboard(result);
1335
+ }
1114
1336
  } catch (error) {
1115
1337
  logger_default.error(error);
1116
- throw error;
1117
- }
1118
- }
1119
- if (targets.runMini) {
1120
- logBuildAppFinish(configService, void 0, { skipWeb: !targets.runWeb });
1121
- }
1122
- if (options.open && targets.runMini) {
1123
- await openIde();
1124
- }
1125
- });
1126
- cli.command("init").action(async () => {
1127
- try {
1128
- await initConfig({
1129
- command: "weapp-vite"
1130
- });
1131
- } catch (error) {
1132
- logger_default.error(error);
1133
- }
1134
- });
1135
- cli.command("open").action(async () => {
1136
- await openIde();
1137
- });
1138
- cli.command("npm").alias("build:npm").alias("build-npm").action(async () => {
1139
- try {
1140
- await parse(["build-npm", "-p"]);
1141
- } catch (error) {
1142
- logger_default.error(error);
1143
- }
1144
- });
1145
- cli.command("g [filepath]", "generate component").alias("generate").option("-a, --app", "type app").option("-p, --page", "type app").option("-n, --name <name>", "filename").action(async (filepath, options) => {
1146
- const config = await loadConfig(resolveConfigFile(options));
1147
- let type = "component";
1148
- let fileName = options.name;
1149
- if (options.app) {
1150
- type = "app";
1151
- if (filepath === void 0) {
1152
- filepath = "";
1338
+ process3.exitCode = 1;
1153
1339
  }
1154
- fileName = "app";
1155
- }
1156
- if (filepath === void 0) {
1157
- logger_default.error("weapp-vite generate <outDir> \u547D\u4EE4\u5FC5\u987B\u4F20\u5165\u8DEF\u5F84\u53C2\u6570 outDir");
1158
- return;
1159
- }
1160
- if (options.page) {
1161
- type = "page";
1162
- }
1163
- const generateOptions = config?.config.weapp?.generate;
1164
- fileName = generateOptions?.filenames?.[type] ?? fileName;
1165
- await generate({
1166
- outDir: path2.join(generateOptions?.dirs?.[type] ?? "", filepath),
1167
- type,
1168
- fileName,
1169
- extensions: generateOptions?.extensions,
1170
- templates: generateOptions?.templates
1171
1340
  });
1172
- });
1173
- cli.command("create [outDir]", "create project").option("-t, --template <type>", "template type").action(async (outDir, options) => {
1174
- await createProject(outDir, options.template);
1175
- });
1341
+ }
1342
+
1343
+ // src/cli/commands/build.ts
1344
+ init_esm_shims();
1345
+
1346
+ // src/cli/logBuildAppFinish.ts
1347
+ init_esm_shims();
1348
+
1349
+ // ../../node_modules/.pnpm/package-manager-detector@1.5.0/node_modules/package-manager-detector/dist/commands.mjs
1350
+ init_esm_shims();
1351
+ function dashDashArg(agent, agentCommand) {
1352
+ return (args) => {
1353
+ if (args.length > 1) {
1354
+ return [agent, agentCommand, args[0], "--", ...args.slice(1)];
1355
+ } else {
1356
+ return [agent, agentCommand, args[0]];
1357
+ }
1358
+ };
1359
+ }
1360
+ function denoExecute() {
1361
+ return (args) => {
1362
+ return ["deno", "run", `npm:${args[0]}`, ...args.slice(1)];
1363
+ };
1364
+ }
1365
+ var npm = {
1366
+ "agent": ["npm", 0],
1367
+ "run": dashDashArg("npm", "run"),
1368
+ "install": ["npm", "i", 0],
1369
+ "frozen": ["npm", "ci", 0],
1370
+ "global": ["npm", "i", "-g", 0],
1371
+ "add": ["npm", "i", 0],
1372
+ "upgrade": ["npm", "update", 0],
1373
+ "upgrade-interactive": null,
1374
+ "dedupe": ["npm", "dedupe", 0],
1375
+ "execute": ["npx", 0],
1376
+ "execute-local": ["npx", 0],
1377
+ "uninstall": ["npm", "uninstall", 0],
1378
+ "global_uninstall": ["npm", "uninstall", "-g", 0]
1379
+ };
1380
+ var yarn = {
1381
+ "agent": ["yarn", 0],
1382
+ "run": ["yarn", "run", 0],
1383
+ "install": ["yarn", "install", 0],
1384
+ "frozen": ["yarn", "install", "--frozen-lockfile", 0],
1385
+ "global": ["yarn", "global", "add", 0],
1386
+ "add": ["yarn", "add", 0],
1387
+ "upgrade": ["yarn", "upgrade", 0],
1388
+ "upgrade-interactive": ["yarn", "upgrade-interactive", 0],
1389
+ "dedupe": null,
1390
+ "execute": ["npx", 0],
1391
+ "execute-local": dashDashArg("yarn", "exec"),
1392
+ "uninstall": ["yarn", "remove", 0],
1393
+ "global_uninstall": ["yarn", "global", "remove", 0]
1394
+ };
1395
+ var yarnBerry = {
1396
+ ...yarn,
1397
+ "frozen": ["yarn", "install", "--immutable", 0],
1398
+ "upgrade": ["yarn", "up", 0],
1399
+ "upgrade-interactive": ["yarn", "up", "-i", 0],
1400
+ "dedupe": ["yarn", "dedupe", 0],
1401
+ "execute": ["yarn", "dlx", 0],
1402
+ "execute-local": ["yarn", "exec", 0],
1403
+ // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821
1404
+ "global": ["npm", "i", "-g", 0],
1405
+ "global_uninstall": ["npm", "uninstall", "-g", 0]
1406
+ };
1407
+ var pnpm = {
1408
+ "agent": ["pnpm", 0],
1409
+ "run": ["pnpm", "run", 0],
1410
+ "install": ["pnpm", "i", 0],
1411
+ "frozen": ["pnpm", "i", "--frozen-lockfile", 0],
1412
+ "global": ["pnpm", "add", "-g", 0],
1413
+ "add": ["pnpm", "add", 0],
1414
+ "upgrade": ["pnpm", "update", 0],
1415
+ "upgrade-interactive": ["pnpm", "update", "-i", 0],
1416
+ "dedupe": ["pnpm", "dedupe", 0],
1417
+ "execute": ["pnpm", "dlx", 0],
1418
+ "execute-local": ["pnpm", "exec", 0],
1419
+ "uninstall": ["pnpm", "remove", 0],
1420
+ "global_uninstall": ["pnpm", "remove", "--global", 0]
1421
+ };
1422
+ var bun = {
1423
+ "agent": ["bun", 0],
1424
+ "run": ["bun", "run", 0],
1425
+ "install": ["bun", "install", 0],
1426
+ "frozen": ["bun", "install", "--frozen-lockfile", 0],
1427
+ "global": ["bun", "add", "-g", 0],
1428
+ "add": ["bun", "add", 0],
1429
+ "upgrade": ["bun", "update", 0],
1430
+ "upgrade-interactive": ["bun", "update", "-i", 0],
1431
+ "dedupe": null,
1432
+ "execute": ["bun", "x", 0],
1433
+ "execute-local": ["bun", "x", 0],
1434
+ "uninstall": ["bun", "remove", 0],
1435
+ "global_uninstall": ["bun", "remove", "-g", 0]
1436
+ };
1437
+ var deno = {
1438
+ "agent": ["deno", 0],
1439
+ "run": ["deno", "task", 0],
1440
+ "install": ["deno", "install", 0],
1441
+ "frozen": ["deno", "install", "--frozen", 0],
1442
+ "global": ["deno", "install", "-g", 0],
1443
+ "add": ["deno", "add", 0],
1444
+ "upgrade": ["deno", "outdated", "--update", 0],
1445
+ "upgrade-interactive": ["deno", "outdated", "--update", 0],
1446
+ "dedupe": null,
1447
+ "execute": denoExecute(),
1448
+ "execute-local": ["deno", "task", "--eval", 0],
1449
+ "uninstall": ["deno", "remove", 0],
1450
+ "global_uninstall": ["deno", "uninstall", "-g", 0]
1451
+ };
1452
+ var COMMANDS = {
1453
+ "npm": npm,
1454
+ "yarn": yarn,
1455
+ "yarn@berry": yarnBerry,
1456
+ "pnpm": pnpm,
1457
+ // pnpm v6.x or below
1458
+ "pnpm@6": {
1459
+ ...pnpm,
1460
+ run: dashDashArg("pnpm", "run")
1461
+ },
1462
+ "bun": bun,
1463
+ "deno": deno
1464
+ };
1465
+ function resolveCommand(agent, command, args) {
1466
+ const value = COMMANDS[agent][command];
1467
+ return constructCommand(value, args);
1468
+ }
1469
+ function constructCommand(value, args) {
1470
+ if (value == null)
1471
+ return null;
1472
+ const list = typeof value === "function" ? value(args) : value.flatMap((v) => {
1473
+ if (typeof v === "number")
1474
+ return args;
1475
+ return [v];
1476
+ });
1477
+ return {
1478
+ command: list[0],
1479
+ args: list.slice(1)
1480
+ };
1481
+ }
1482
+
1483
+ // src/cli/logBuildAppFinish.ts
1484
+ var logBuildAppFinishOnlyShowOnce = false;
1485
+ function logBuildAppFinish(configService, webServer, options = {}) {
1486
+ if (logBuildAppFinishOnlyShowOnce) {
1487
+ return;
1488
+ }
1489
+ const { skipMini = false, skipWeb = false } = options;
1490
+ if (skipMini) {
1491
+ if (webServer) {
1492
+ const urls = webServer.resolvedUrls;
1493
+ const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
1494
+ if (candidates.length > 0) {
1495
+ logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A");
1496
+ for (const url of candidates) {
1497
+ logger_default.info(` \u279C ${url}`);
1498
+ }
1499
+ } else {
1500
+ logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1501
+ }
1502
+ } else {
1503
+ logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1504
+ }
1505
+ logBuildAppFinishOnlyShowOnce = true;
1506
+ return;
1507
+ }
1508
+ const { command, args } = resolveCommand(
1509
+ configService.packageManager.agent,
1510
+ "run",
1511
+ ["open"]
1512
+ ) ?? {
1513
+ command: "npm",
1514
+ args: ["run", "open"]
1515
+ };
1516
+ const devCommand = `${command} ${args.join(" ")}`;
1517
+ logger_default.success("\u5E94\u7528\u6784\u5EFA\u5B8C\u6210\uFF01\u9884\u89C8\u65B9\u5F0F ( `2` \u79CD\u9009\u5176\u4E00\u5373\u53EF)\uFF1A");
1518
+ logger_default.info(`\u6267\u884C \`${devCommand}\` \u53EF\u4EE5\u76F4\u63A5\u5728 \`\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\` \u91CC\u6253\u5F00\u5F53\u524D\u5E94\u7528`);
1519
+ logger_default.info("\u6216\u624B\u52A8\u6253\u5F00\u5FAE\u4FE1\u5F00\u53D1\u8005\u5DE5\u5177\uFF0C\u5BFC\u5165\u6839\u76EE\u5F55(`project.config.json` \u6587\u4EF6\u6240\u5728\u7684\u76EE\u5F55)\uFF0C\u5373\u53EF\u9884\u89C8\u6548\u679C");
1520
+ if (!skipWeb && webServer) {
1521
+ const urls = webServer.resolvedUrls;
1522
+ const candidates = urls ? [...urls.local ?? [], ...urls.network ?? []] : [];
1523
+ if (candidates.length > 0) {
1524
+ logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8\uFF0C\u6D4F\u89C8\u5668\u8BBF\u95EE\uFF1A");
1525
+ for (const url of candidates) {
1526
+ logger_default.info(` \u279C ${url}`);
1527
+ }
1528
+ } else {
1529
+ logger_default.success("Web \u8FD0\u884C\u65F6\u5DF2\u542F\u52A8");
1530
+ }
1531
+ }
1532
+ logBuildAppFinishOnlyShowOnce = true;
1533
+ }
1534
+
1535
+ // src/cli/openIde.ts
1536
+ init_esm_shims();
1537
+ import { parse } from "weapp-ide-cli";
1538
+ async function openIde() {
1539
+ try {
1540
+ await parse(["open", "-p"]);
1541
+ } catch (error) {
1542
+ logger_default.error(error);
1543
+ }
1544
+ }
1545
+
1546
+ // src/cli/commands/build.ts
1547
+ function registerBuildCommand(cli2) {
1548
+ cli2.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option(
1549
+ "--sourcemap [output]",
1550
+ `[boolean | "inline" | "hidden"] output source maps for build (default: false)`
1551
+ ).option(
1552
+ "--minify [minifier]",
1553
+ `[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)`
1554
+ ).option(
1555
+ "--emptyOutDir",
1556
+ `[boolean] force empty outDir when it's outside of root`
1557
+ ).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("--analyze", `[boolean] \u8F93\u51FA\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8`, { default: false }).action(async (root, options) => {
1558
+ filterDuplicateOptions(options);
1559
+ const configFile = resolveConfigFile(options);
1560
+ const targets = resolveRuntimeTargets(options);
1561
+ logRuntimeTarget(targets);
1562
+ const inlineConfig = createInlineConfig(targets.mpPlatform);
1563
+ const ctx = await createCompilerContext({
1564
+ cwd: root,
1565
+ mode: options.mode ?? "production",
1566
+ configFile,
1567
+ inlineConfig
1568
+ });
1569
+ const { buildService, configService, webService } = ctx;
1570
+ const enableAnalyze = Boolean(options.analyze && targets.runMini);
1571
+ let analyzeHandle;
1572
+ if (targets.runMini) {
1573
+ await buildService.build(options);
1574
+ if (enableAnalyze) {
1575
+ const analyzeResult = await analyzeSubpackages(ctx);
1576
+ analyzeHandle = await startAnalyzeDashboard(analyzeResult, { watch: true }) ?? void 0;
1577
+ }
1578
+ }
1579
+ const webConfig = configService.weappWebConfig;
1580
+ if (targets.runWeb && webConfig?.enabled) {
1581
+ try {
1582
+ await webService?.build();
1583
+ logger_default.success(`Web \u6784\u5EFA\u5B8C\u6210\uFF0C\u8F93\u51FA\u76EE\u5F55\uFF1A${configService.relativeCwd(webConfig.outDir)}`);
1584
+ } catch (error) {
1585
+ logger_default.error(error);
1586
+ throw error;
1587
+ }
1588
+ }
1589
+ if (targets.runMini) {
1590
+ logBuildAppFinish(configService, void 0, { skipWeb: !targets.runWeb });
1591
+ }
1592
+ if (options.open && targets.runMini) {
1593
+ await openIde();
1594
+ }
1595
+ if (analyzeHandle) {
1596
+ await analyzeHandle.waitForExit();
1597
+ }
1598
+ });
1599
+ }
1600
+
1601
+ // src/cli/commands/create.ts
1602
+ init_esm_shims();
1603
+ import { createProject } from "@weapp-core/init";
1604
+ function registerCreateCommand(cli2) {
1605
+ cli2.command("create [outDir]", "create project").option("-t, --template <type>", "template type").action(async (outDir, options) => {
1606
+ await createProject(outDir, options.template);
1607
+ });
1608
+ }
1609
+
1610
+ // src/cli/commands/generate.ts
1611
+ init_esm_shims();
1612
+ import path5 from "pathe";
1613
+
1614
+ // src/schematics.ts
1615
+ init_esm_shims();
1616
+ import process4 from "process";
1617
+ import { generateJs, generateJson, generateWxml, generateWxss } from "@weapp-core/schematics";
1618
+ import { defu } from "@weapp-core/shared";
1619
+ import fs3 from "fs-extra";
1620
+ import path3 from "pathe";
1621
+ function composePath(outDir, filename) {
1622
+ return `${outDir}${outDir ? "/" : ""}${filename}`;
1623
+ }
1624
+ var defaultExtensions = {
1625
+ js: "js",
1626
+ json: "json",
1627
+ wxml: "wxml",
1628
+ wxss: "wxss"
1629
+ };
1630
+ function resolveExtension(extension) {
1631
+ return extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
1632
+ }
1633
+ async function readTemplateFile(templatePath, context) {
1634
+ const absolutePath = path3.isAbsolute(templatePath) ? templatePath : path3.resolve(context.cwd, templatePath);
1635
+ return fs3.readFile(absolutePath, "utf8");
1636
+ }
1637
+ async function loadTemplate(template, context) {
1638
+ if (template === void 0) {
1639
+ return void 0;
1640
+ }
1641
+ if (typeof template === "function") {
1642
+ const result = await template(context);
1643
+ return result == null ? void 0 : String(result);
1644
+ }
1645
+ if (typeof template === "string") {
1646
+ return readTemplateFile(template, context);
1647
+ }
1648
+ if ("content" in template && typeof template.content === "string") {
1649
+ return template.content;
1650
+ }
1651
+ if ("path" in template && typeof template.path === "string") {
1652
+ return readTemplateFile(template.path, context);
1653
+ }
1654
+ return void 0;
1655
+ }
1656
+ function resolveTemplate(templates, type, fileType) {
1657
+ const scoped = templates?.[type]?.[fileType];
1658
+ if (scoped !== void 0) {
1659
+ return scoped;
1660
+ }
1661
+ return templates?.shared?.[fileType];
1662
+ }
1663
+ async function generate(options) {
1664
+ let { fileName, outDir, extensions, type, cwd, templates } = defu(options, {
1665
+ type: "component",
1666
+ extensions: {
1667
+ ...defaultExtensions
1668
+ },
1669
+ cwd: process4.cwd(),
1670
+ templates: void 0
1671
+ });
1672
+ if (fileName === void 0) {
1673
+ fileName = path3.basename(outDir);
1674
+ }
1675
+ const basepath = path3.resolve(cwd, outDir);
1676
+ const targetFileTypes = type === "app" ? ["js", "wxss", "json"] : ["js", "wxss", "json", "wxml"];
1677
+ const files = [];
1678
+ for (const fileType of targetFileTypes) {
1679
+ const configuredExt = extensions[fileType] ?? defaultExtensions[fileType];
1680
+ let resolvedExt = configuredExt;
1681
+ let defaultCode;
1682
+ if (fileType === "js") {
1683
+ defaultCode = generateJs(type);
1684
+ } else if (fileType === "wxss") {
1685
+ defaultCode = generateWxss();
1686
+ } else if (fileType === "wxml") {
1687
+ defaultCode = generateWxml(path3.join(outDir, fileName));
1688
+ } else if (fileType === "json") {
1689
+ defaultCode = generateJson(type, configuredExt);
1690
+ if (configuredExt === "js" || configuredExt === "ts") {
1691
+ resolvedExt = `json.${configuredExt}`;
1692
+ }
1693
+ }
1694
+ const context = {
1695
+ type,
1696
+ fileType,
1697
+ fileName,
1698
+ outDir,
1699
+ extension: resolvedExt,
1700
+ cwd,
1701
+ defaultCode
1702
+ };
1703
+ const template = resolveTemplate(templates, type, fileType);
1704
+ const customCode = await loadTemplate(template, context);
1705
+ const finalCode = customCode ?? defaultCode;
1706
+ if (finalCode !== void 0) {
1707
+ files.push({
1708
+ fileName: `${fileName}${resolveExtension(resolvedExt)}`,
1709
+ code: finalCode
1710
+ });
1711
+ }
1712
+ }
1713
+ for (const { code, fileName: fileName2 } of files) {
1714
+ if (code !== void 0) {
1715
+ await fs3.outputFile(path3.resolve(basepath, fileName2), code, "utf8");
1716
+ logger_default.success(`${composePath(outDir, fileName2)} \u521B\u5EFA\u6210\u529F\uFF01`);
1717
+ }
1718
+ }
1719
+ }
1720
+
1721
+ // src/cli/loadConfig.ts
1722
+ init_esm_shims();
1723
+ import process5 from "process";
1724
+ import { defu as defu2 } from "@weapp-core/shared";
1725
+ import path4 from "pathe";
1726
+ import { loadConfigFromFile } from "vite";
1727
+ async function loadConfig(configFile) {
1728
+ const cwd = process5.cwd();
1729
+ let resolvedConfigFile = configFile;
1730
+ if (resolvedConfigFile && !path4.isAbsolute(resolvedConfigFile)) {
1731
+ resolvedConfigFile = path4.resolve(cwd, resolvedConfigFile);
1732
+ }
1733
+ const configEnv = {
1734
+ command: "serve",
1735
+ mode: "development"
1736
+ };
1737
+ const loaded = await loadConfigFromFile(configEnv, resolvedConfigFile, cwd);
1738
+ const weappConfigFilePath = await resolveWeappConfigFile({
1739
+ root: cwd,
1740
+ specified: resolvedConfigFile
1741
+ });
1742
+ let weappLoaded;
1743
+ if (weappConfigFilePath) {
1744
+ const normalizedWeappPath = path4.resolve(weappConfigFilePath);
1745
+ const normalizedLoadedPath = loaded?.path ? path4.resolve(loaded.path) : void 0;
1746
+ if (normalizedLoadedPath && normalizedLoadedPath === normalizedWeappPath) {
1747
+ weappLoaded = loaded;
1748
+ } else {
1749
+ weappLoaded = await loadConfigFromFile(configEnv, weappConfigFilePath, cwd);
1750
+ }
1751
+ }
1752
+ if (!loaded && !weappLoaded) {
1753
+ return void 0;
1754
+ }
1755
+ const config = loaded?.config ?? (weappLoaded?.config ?? {});
1756
+ if (weappLoaded?.config?.weapp) {
1757
+ config.weapp = defu2(
1758
+ weappLoaded.config.weapp,
1759
+ config.weapp ?? {}
1760
+ );
1761
+ }
1762
+ const dependencySet = /* @__PURE__ */ new Set();
1763
+ for (const dependency of loaded?.dependencies ?? []) {
1764
+ dependencySet.add(dependency);
1765
+ }
1766
+ for (const dependency of weappLoaded?.dependencies ?? []) {
1767
+ dependencySet.add(dependency);
1768
+ }
1769
+ return {
1770
+ config,
1771
+ path: weappLoaded?.path ?? loaded?.path ?? resolvedConfigFile,
1772
+ dependencies: Array.from(dependencySet)
1773
+ };
1774
+ }
1775
+
1776
+ // src/cli/commands/generate.ts
1777
+ function registerGenerateCommand(cli2) {
1778
+ cli2.command("g [filepath]", "generate component").alias("generate").option("-a, --app", "type app").option("-p, --page", "type app").option("-n, --name <name>", "filename").action(async (filepath, options) => {
1779
+ filterDuplicateOptions(options);
1780
+ const config = await loadConfig(resolveConfigFile(options));
1781
+ let type = "component";
1782
+ let fileName = options.name;
1783
+ if (options.app) {
1784
+ type = "app";
1785
+ if (filepath === void 0) {
1786
+ filepath = "";
1787
+ }
1788
+ fileName = "app";
1789
+ }
1790
+ if (filepath === void 0) {
1791
+ logger_default.error("weapp-vite generate <outDir> \u547D\u4EE4\u5FC5\u987B\u4F20\u5165\u8DEF\u5F84\u53C2\u6570 outDir");
1792
+ return;
1793
+ }
1794
+ if (options.page) {
1795
+ type = "page";
1796
+ }
1797
+ const generateOptions = config?.config.weapp?.generate;
1798
+ fileName = generateOptions?.filenames?.[type] ?? fileName;
1799
+ await generate({
1800
+ outDir: path5.join(generateOptions?.dirs?.[type] ?? "", filepath),
1801
+ type,
1802
+ fileName,
1803
+ extensions: generateOptions?.extensions,
1804
+ templates: generateOptions?.templates
1805
+ });
1806
+ });
1807
+ }
1808
+
1809
+ // src/cli/commands/init.ts
1810
+ init_esm_shims();
1811
+ import { initConfig } from "@weapp-core/init";
1812
+ function registerInitCommand(cli2) {
1813
+ cli2.command("init").action(async () => {
1814
+ try {
1815
+ await initConfig({
1816
+ command: "weapp-vite"
1817
+ });
1818
+ } catch (error) {
1819
+ logger_default.error(error);
1820
+ }
1821
+ });
1822
+ }
1823
+
1824
+ // src/cli/commands/npm.ts
1825
+ init_esm_shims();
1826
+ import { parse as parse2 } from "weapp-ide-cli";
1827
+ function registerNpmCommand(cli2) {
1828
+ cli2.command("npm").alias("build:npm").alias("build-npm").action(async () => {
1829
+ try {
1830
+ await parse2(["build-npm", "-p"]);
1831
+ } catch (error) {
1832
+ logger_default.error(error);
1833
+ }
1834
+ });
1835
+ }
1836
+
1837
+ // src/cli/commands/open.ts
1838
+ init_esm_shims();
1839
+ function registerOpenCommand(cli2) {
1840
+ cli2.command("open").action(async () => {
1841
+ await openIde();
1842
+ });
1843
+ }
1844
+
1845
+ // src/cli/commands/serve.ts
1846
+ init_esm_shims();
1847
+ function registerServeCommand(cli2) {
1848
+ cli2.command("[root]", "start dev server").alias("serve").alias("dev").option("--skipNpm", `[boolean] if skip npm build`).option("-o, --open", `[boolean] open ide`).option("-p, --platform <platform>", `[string] target platform (weapp | h5)`).option("--analyze", `[boolean] \u542F\u52A8\u5206\u5305\u5206\u6790\u4EEA\u8868\u76D8 (\u5B9E\u9A8C\u7279\u6027)`, { default: false }).action(async (root, options) => {
1849
+ filterDuplicateOptions(options);
1850
+ const configFile = resolveConfigFile(options);
1851
+ const targets = resolveRuntimeTargets(options);
1852
+ logRuntimeTarget(targets);
1853
+ const inlineConfig = createInlineConfig(targets.mpPlatform);
1854
+ const ctx = await createCompilerContext({
1855
+ cwd: root,
1856
+ mode: options.mode ?? "development",
1857
+ isDev: true,
1858
+ configFile,
1859
+ inlineConfig
1860
+ });
1861
+ const { buildService, configService, webService } = ctx;
1862
+ const enableAnalyze = Boolean(options.analyze && targets.runMini);
1863
+ let analyzeHandle;
1864
+ const triggerAnalyzeUpdate = async () => {
1865
+ if (!analyzeHandle) {
1866
+ return;
1867
+ }
1868
+ const next = await analyzeSubpackages(ctx);
1869
+ await analyzeHandle.update(next);
1870
+ };
1871
+ if (targets.runMini) {
1872
+ const buildResult = await buildService.build(options);
1873
+ if (enableAnalyze) {
1874
+ const initialResult = await analyzeSubpackages(ctx);
1875
+ analyzeHandle = await startAnalyzeDashboard(initialResult, { watch: true }) ?? void 0;
1876
+ if (analyzeHandle && buildResult && typeof buildResult.on === "function") {
1877
+ const watcher = buildResult;
1878
+ let updating = false;
1879
+ watcher.on("event", (event) => {
1880
+ if (event.code !== "END" || updating) {
1881
+ return;
1882
+ }
1883
+ updating = true;
1884
+ triggerAnalyzeUpdate().finally(() => {
1885
+ updating = false;
1886
+ });
1887
+ });
1888
+ } else if (analyzeHandle) {
1889
+ await triggerAnalyzeUpdate();
1890
+ }
1891
+ }
1892
+ }
1893
+ let webServer;
1894
+ if (targets.runWeb) {
1895
+ try {
1896
+ webServer = await webService?.startDevServer();
1897
+ } catch (error) {
1898
+ logger_default.error(error);
1899
+ throw error;
1900
+ }
1901
+ }
1902
+ if (targets.runMini) {
1903
+ logBuildAppFinish(configService, webServer, { skipWeb: !targets.runWeb });
1904
+ } else if (targets.runWeb) {
1905
+ logBuildAppFinish(configService, webServer, { skipMini: true });
1906
+ }
1907
+ if (options.open && targets.runMini) {
1908
+ await openIde();
1909
+ }
1910
+ if (analyzeHandle) {
1911
+ await analyzeHandle.waitForExit();
1912
+ }
1913
+ });
1914
+ }
1915
+
1916
+ // src/cli.ts
1917
+ var cli = cac("weapp-vite");
1918
+ try {
1919
+ checkRuntime({
1920
+ bun: "0.0.0",
1921
+ deno: "0.0.0",
1922
+ node: "20.19.0"
1923
+ });
1924
+ } catch {
1925
+ }
1926
+ cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, {
1927
+ type: [convertBase]
1928
+ }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option("-d, --debug [feat]", `[string | boolean] show debug logs`).option("-f, --filter <filter>", `[string] filter debug logs`).option("-m, --mode <mode>", `[string] set env mode`);
1929
+ registerServeCommand(cli);
1930
+ registerBuildCommand(cli);
1931
+ registerAnalyzeCommand(cli);
1932
+ registerInitCommand(cli);
1933
+ registerOpenCommand(cli);
1934
+ registerNpmCommand(cli);
1935
+ registerGenerateCommand(cli);
1936
+ registerCreateCommand(cli);
1176
1937
  cli.help();
1177
1938
  cli.version(VERSION);
1178
1939
  cli.parse();