js-code-detector 0.0.50 → 0.0.51

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.
@@ -28,6 +28,7 @@ export declare function gitDiffDetect(): Promise<{
28
28
  } | undefined>;
29
29
  export { isRepoTypeSupported } from "./util/shared/getRepoSupportFlag";
30
30
  export declare function runDiffDetect(compareUrl?: string, token?: string): Promise<{
31
+ error: Error | null;
31
32
  repoType: string;
32
33
  effectedImportUsage: [string, string][];
33
34
  }>;
@@ -27,8 +27,10 @@ export declare class DetectService {
27
27
  clean(): Promise<void>;
28
28
  mkdir(): Promise<void>;
29
29
  clone(): Promise<void>;
30
+ move(): Promise<void>;
30
31
  projectHandle(): Promise<void>;
31
32
  formatResult(): {
33
+ error: Error | null;
32
34
  repoType: string;
33
35
  effectedImportUsage: [string, string][];
34
36
  };
@@ -43,6 +43,7 @@ var import_getRepoSupportFlag = require("../util/shared/getRepoSupportFlag");
43
43
  var import_UmiProjectService = __toESM(require("./projectServiceClass/UmiProjectService"));
44
44
  var import_perf_hooks = require("perf_hooks");
45
45
  var import_cloneRepoWithBranchAndDefault = __toESM(require("../util/git_util/cloneRepoWithBranchAndDefault"));
46
+ var import_VueProjectService = __toESM(require("./projectServiceClass/VueProjectService"));
46
47
  var DetectService = class {
47
48
  constructor(option) {
48
49
  this.directoryInfo = {
@@ -99,6 +100,10 @@ var DetectService = class {
99
100
  import_utils.logger.info(`mkdir 耗时: ${duration}ms`);
100
101
  }
101
102
  await this.clone();
103
+ const token = this.gitInfo.token;
104
+ if (token) {
105
+ await this.move();
106
+ }
102
107
  import_perf_hooks.performance.mark("projectHandle");
103
108
  {
104
109
  const duration = import_perf_hooks.performance.measure("clone", "clone", "projectHandle").duration;
@@ -155,6 +160,15 @@ var DetectService = class {
155
160
  this.gitInfo.repoType = repoType;
156
161
  import_utils.logger.info("克隆仓库成功");
157
162
  }
163
+ async move() {
164
+ const repoType = this.gitInfo.repoType;
165
+ const tmpWorkDir = this.directoryInfo.tmpWorkDir;
166
+ const newTmpWorkDir = (0, import_path.join)(repoType, tmpWorkDir);
167
+ this.directoryInfo.tmpWorkDir = newTmpWorkDir;
168
+ this.directoryInfo.sourceBranchDir = (0, import_path.join)(newTmpWorkDir, import_constants.SOURCE);
169
+ this.directoryInfo.targetBranchDir = (0, import_path.join)(newTmpWorkDir, import_constants.TARGET);
170
+ await import_utils.execa.execa(`mv ${tmpWorkDir} ${newTmpWorkDir}`, { shell: true });
171
+ }
158
172
  async projectHandle() {
159
173
  var _a;
160
174
  const { repoType } = this.gitInfo;
@@ -164,13 +178,17 @@ var DetectService = class {
164
178
  if (repoType === "umi") {
165
179
  this.projectService = new import_UmiProjectService.default(this);
166
180
  }
181
+ if (repoType === "vue2") {
182
+ this.projectService = new import_VueProjectService.default(this);
183
+ }
167
184
  await ((_a = this.projectService) == null ? void 0 : _a.run());
168
185
  }
169
186
  formatResult() {
170
187
  var _a;
171
188
  const repoType = this.gitInfo.repoType;
172
- const { effectedImportUsage } = ((_a = this.projectService) == null ? void 0 : _a.outputResult) || { effectedImportUsage: [] };
189
+ const { effectedImportUsage, error } = ((_a = this.projectService) == null ? void 0 : _a.outputResult) || { effectedImportUsage: [], error: null };
173
190
  return {
191
+ error,
174
192
  repoType,
175
193
  effectedImportUsage
176
194
  };
@@ -1,16 +1,15 @@
1
1
  import { DetectService } from "./DetectService";
2
2
  import { formatGitDiffContent } from "../util/format_git_diff_content";
3
- import { IMadgeInstance } from "../util/report_util/getMadgeInstance";
4
3
  export interface ProjectService {
5
4
  detectService: DetectService;
6
5
  gitDiffDetail: ReturnType<typeof formatGitDiffContent>;
7
6
  helpInfo: {
8
7
  projectFileList: string[];
9
- madgeResult: IMadgeInstance | null;
10
8
  parsedAlias: Record<string, any>;
11
9
  };
12
10
  outputResult: {
13
11
  effectedImportUsage: [string, string][];
12
+ error: Error | null;
14
13
  };
15
14
  run(): void;
16
15
  }
@@ -1,11 +1,15 @@
1
1
  import { GitDiffDetail } from "../../util/format_git_diff_content";
2
2
  import { DetectService } from "../DetectService";
3
3
  import { ProjectService } from "../ProjectService";
4
+ import { IMadgeInstance } from "../../util/report_util/getMadgeInstance";
4
5
  export default class UmiProjectService implements ProjectService {
5
6
  detectService: DetectService;
6
7
  gitDiffDetail: GitDiffDetail[];
7
8
  helpInfo: ProjectService['helpInfo'];
8
9
  outputResult: ProjectService['outputResult'];
10
+ umiHelpInfo: {
11
+ madgeResult: IMadgeInstance | null;
12
+ };
9
13
  constructor(detectService: DetectService);
10
14
  run(): Promise<void>;
11
15
  parseGitDiffContent(): Promise<void>;
@@ -46,11 +46,14 @@ var UmiProjectService = class {
46
46
  this.gitDiffDetail = [];
47
47
  this.helpInfo = {
48
48
  projectFileList: [],
49
- madgeResult: null,
50
49
  parsedAlias: {}
51
50
  };
52
51
  this.outputResult = {
53
- effectedImportUsage: []
52
+ effectedImportUsage: [],
53
+ error: null
54
+ };
55
+ this.umiHelpInfo = {
56
+ madgeResult: null
54
57
  };
55
58
  this.detectService = detectService;
56
59
  }
@@ -58,7 +61,7 @@ var UmiProjectService = class {
58
61
  const targetDirPath = this.detectService.directoryInfo.targetBranchDir;
59
62
  const { madgeResult, parsedAlias } = await (0, import_umi4ProjectUtil.umi4SetUp)({ targetDirPath, invokeType: "remote" });
60
63
  this.helpInfo.projectFileList = Object.keys(madgeResult.tree);
61
- this.helpInfo.madgeResult = madgeResult;
64
+ this.umiHelpInfo.madgeResult = madgeResult;
62
65
  this.helpInfo.parsedAlias = parsedAlias;
63
66
  await this.parseGitDiffContent();
64
67
  await this.collectEffectedFiles();
@@ -69,7 +72,8 @@ var UmiProjectService = class {
69
72
  this.gitDiffDetail = (0, import_format_git_diff_content.formatGitDiffContent)(diff_txt);
70
73
  }
71
74
  async collectEffectedFiles() {
72
- const { madgeResult, parsedAlias } = this.helpInfo;
75
+ const { parsedAlias } = this.helpInfo;
76
+ const { madgeResult } = this.umiHelpInfo;
73
77
  const projectFileList = this.helpInfo.projectFileList;
74
78
  const targetBranchDir = this.detectService.directoryInfo.targetBranchDir;
75
79
  const absPathPrefix = (0, import_path.join)(targetBranchDir, "/");
@@ -0,0 +1,31 @@
1
+ import { GitDiffDetail } from "../../util/format_git_diff_content";
2
+ import { ProjectService } from "../ProjectService";
3
+ import { DetectService } from "../DetectService";
4
+ import { IMadgeInstance } from "../../util/report_util/getMadgeInstance";
5
+ export default class VueProjectService implements ProjectService {
6
+ detectService: DetectService;
7
+ gitDiffDetail: GitDiffDetail[];
8
+ helpInfo: ProjectService['helpInfo'];
9
+ outputResult: ProjectService['outputResult'];
10
+ vueHelpInfo: {
11
+ madgeResult: IMadgeInstance | null;
12
+ webpackConfigPath: string;
13
+ webpackConfigTextLines: string[];
14
+ entryFiles: string[];
15
+ };
16
+ constructor(detectService: DetectService);
17
+ run(): Promise<void>;
18
+ readSrcDirFiles(): Promise<void>;
19
+ parseGitDiffContent(): Promise<void>;
20
+ handleWebpackConfigText(webpackConfigText: string): Promise<void>;
21
+ getWebpackConfigText(): Promise<void>;
22
+ createSimpleWebpackConfig(): {
23
+ resolve: {
24
+ alias: Record<string, any>;
25
+ };
26
+ };
27
+ getEntryFiles(): void;
28
+ getWebpackAlias(): void;
29
+ getMadgeResult(): Promise<void>;
30
+ collectEffectedFiles(): Promise<void>;
31
+ }
@@ -0,0 +1,191 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to2, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to2, key) && key !== except)
15
+ __defProp(to2, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to2;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/services/projectServiceClass/VueProjectService.ts
30
+ var VueProjectService_exports = {};
31
+ __export(VueProjectService_exports, {
32
+ default: () => VueProjectService
33
+ });
34
+ module.exports = __toCommonJS(VueProjectService_exports);
35
+ var import_format_git_diff_content = require("../../util/format_git_diff_content");
36
+ var import_fs = require("fs");
37
+ var import_path = require("path");
38
+ var import_constants = require("../../util/constants");
39
+ var import_utils = require("@umijs/utils");
40
+ var import_madge = __toESM(require("madge"));
41
+ var import_collectUpstreamFiles = __toESM(require("../../util/shared/collectUpstreamFiles"));
42
+ var import_createDependenceMap = require("../../util/report_util/createDependenceMap");
43
+ var import_filterEffectedExportMember = __toESM(require("../../util/report_util/filterEffectedExportMember"));
44
+ var import_await_to_js = __toESM(require("await-to-js"));
45
+ var VueProjectService = class {
46
+ constructor(detectService) {
47
+ this.detectService = detectService;
48
+ this.gitDiffDetail = [];
49
+ this.helpInfo = {
50
+ projectFileList: [],
51
+ parsedAlias: {}
52
+ };
53
+ this.outputResult = {
54
+ effectedImportUsage: [],
55
+ error: null
56
+ };
57
+ this.vueHelpInfo = {
58
+ madgeResult: null,
59
+ webpackConfigPath: "",
60
+ webpackConfigTextLines: [],
61
+ entryFiles: []
62
+ };
63
+ this.detectService = detectService;
64
+ }
65
+ async run() {
66
+ import_utils.logger.info("格式化 git diff 内容...");
67
+ await this.parseGitDiffContent();
68
+ import_utils.logger.info("获取 webpack 配置...");
69
+ await this.getWebpackConfigText();
70
+ await this.collectEffectedFiles();
71
+ }
72
+ async readSrcDirFiles() {
73
+ const targetDirPath = this.detectService.directoryInfo.targetBranchDir;
74
+ const projectFileList = (0, import_utils.readDirFiles)({ dir: (0, import_path.join)(targetDirPath, "src") });
75
+ }
76
+ async parseGitDiffContent() {
77
+ const targetDirPath = this.detectService.directoryInfo.targetBranchDir;
78
+ const diff_txt = (0, import_fs.readFileSync)((0, import_path.join)(targetDirPath, import_constants.gitDiffFileName), "utf-8");
79
+ this.gitDiffDetail = (0, import_format_git_diff_content.formatGitDiffContent)(diff_txt);
80
+ }
81
+ async handleWebpackConfigText(webpackConfigText) {
82
+ const targetDirPath = this.detectService.directoryInfo.targetBranchDir;
83
+ this.vueHelpInfo.webpackConfigTextLines = webpackConfigText.split("\n");
84
+ this.getWebpackAlias();
85
+ this.getEntryFiles();
86
+ const wb = this.createSimpleWebpackConfig();
87
+ (0, import_fs.writeFileSync)(this.vueHelpInfo.webpackConfigPath = (0, import_path.join)(targetDirPath, "webpack.config.js"), `module.exports = ${JSON.stringify(wb, null, 2)}`, "utf-8");
88
+ await this.getMadgeResult();
89
+ }
90
+ async getWebpackConfigText() {
91
+ const targetDirPath = this.detectService.directoryInfo.targetBranchDir;
92
+ let [err, data] = await (0, import_await_to_js.default)(import_utils.execa.execa(`cd ${targetDirPath} && npx vue-cli-service inspect`, { shell: true }));
93
+ if (err) {
94
+ await import_utils.execa.execa(`cd ${targetDirPath} && yarn`, { shell: true });
95
+ [err, data] = await (0, import_await_to_js.default)(import_utils.execa.execa(`cd ${targetDirPath} && npx vue-cli-service inspect`, { shell: true }));
96
+ }
97
+ this.outputResult.error = err;
98
+ const webpackConfigText = data == null ? void 0 : data.stdout;
99
+ if (webpackConfigText) {
100
+ await this.handleWebpackConfigText(webpackConfigText);
101
+ }
102
+ }
103
+ createSimpleWebpackConfig() {
104
+ return {
105
+ resolve: {
106
+ alias: this.helpInfo.parsedAlias
107
+ }
108
+ };
109
+ }
110
+ getEntryFiles() {
111
+ const lines = this.vueHelpInfo.webpackConfigTextLines;
112
+ let entryObject = {};
113
+ const entryLines = [];
114
+ let entryFind = false;
115
+ for (const line of lines) {
116
+ if (!entryFind && line.trim().startsWith("entry:")) {
117
+ entryLines.push(line.replace("entry:", ""));
118
+ entryFind = true;
119
+ } else if (entryFind && line.trim().startsWith("}")) {
120
+ entryLines.push(line.replace(/,/g, ""));
121
+ break;
122
+ } else if (entryFind) {
123
+ entryLines.push(line);
124
+ }
125
+ }
126
+ const entryLinesJoin = entryLines.join("\n");
127
+ entryObject = eval(`(${entryLinesJoin})`);
128
+ this.vueHelpInfo.entryFiles = Object.values({ ...entryObject }).flat();
129
+ }
130
+ getWebpackAlias() {
131
+ const lines = this.vueHelpInfo.webpackConfigTextLines;
132
+ const aliasLines = [];
133
+ let aliasFind = false;
134
+ for (const line of lines) {
135
+ if (!aliasFind && line.trim().startsWith("alias:")) {
136
+ aliasLines.push(line.replace("alias:", ""));
137
+ aliasFind = true;
138
+ } else if (aliasFind && line.trim().startsWith("}")) {
139
+ aliasLines.push(line.replace(/,/g, ""));
140
+ break;
141
+ } else if (aliasFind) {
142
+ aliasLines.push(line);
143
+ }
144
+ }
145
+ const userAlias = eval(`(${aliasLines.join("\n")})`);
146
+ this.helpInfo.parsedAlias = userAlias;
147
+ }
148
+ async getMadgeResult() {
149
+ const targetBranchDir = this.detectService.directoryInfo.targetBranchDir;
150
+ const entryFilePath = this.vueHelpInfo.entryFiles.map((file) => (0, import_path.join)(targetBranchDir, file));
151
+ const madgeConfig = {
152
+ baseDir: this.detectService.directoryInfo.targetBranchDir,
153
+ fileExtensions: ["js", "ts", "jsx", "tsx", "vue"],
154
+ webpackConfig: this.vueHelpInfo.webpackConfigPath
155
+ };
156
+ const res = await (0, import_madge.default)(entryFilePath, madgeConfig);
157
+ this.vueHelpInfo.madgeResult = res;
158
+ this.helpInfo.projectFileList = Object.keys(res.tree);
159
+ }
160
+ async collectEffectedFiles() {
161
+ const { parsedAlias } = this.helpInfo;
162
+ const { madgeResult } = this.vueHelpInfo;
163
+ const projectFileList = this.helpInfo.projectFileList;
164
+ const targetBranchDir = this.detectService.directoryInfo.targetBranchDir;
165
+ const absPathPrefix = (0, import_path.join)(targetBranchDir, "/");
166
+ const validModifiedFiles = this.gitDiffDetail.reduce((acc, item) => {
167
+ const { filePath } = item;
168
+ this.helpInfo.projectFileList.includes(filePath) && acc.push(filePath);
169
+ return acc;
170
+ }, []);
171
+ const possibleEffectedFiles = (0, import_collectUpstreamFiles.default)(madgeResult, validModifiedFiles);
172
+ const possibleEffectedFilesFullPath = possibleEffectedFiles.map((file) => (0, import_path.join)(absPathPrefix, file));
173
+ const { import2export, indirectExportMembers } = (0, import_createDependenceMap.createExportedNameToReferenceLocalSet)(possibleEffectedFilesFullPath, parsedAlias, absPathPrefix, projectFileList);
174
+ const gitDiffDetail = this.gitDiffDetail;
175
+ const validGitDiffDetail = gitDiffDetail.filter((item) => possibleEffectedFiles.includes(item.filePath));
176
+ const effectedExportNames = validGitDiffDetail.map((item) => {
177
+ const { filePath, newBranchLineScope, startLineOfNew } = item;
178
+ const exportedNames = (0, import_filterEffectedExportMember.default)((0, import_path.join)(absPathPrefix, filePath), absPathPrefix, Number(startLineOfNew), Number(startLineOfNew) + Number(newBranchLineScope));
179
+ return exportedNames.map((name) => [filePath, name].join("#"));
180
+ }).flat();
181
+ const effectedImportUsage = [...Object.entries(import2export), ...Object.entries(indirectExportMembers)].filter(([_, value]) => {
182
+ return effectedExportNames.includes(value);
183
+ });
184
+ this.outputResult.effectedImportUsage = effectedImportUsage;
185
+ const token = this.detectService.gitInfo.token;
186
+ if (!token) {
187
+ const pwd = (0, import_path.join)(this.detectService.directoryInfo.tmpWorkDir, "..");
188
+ (0, import_fs.writeFileSync)((0, import_path.join)(pwd, "effectedImportUsage.json"), JSON.stringify(effectedImportUsage, null, 2));
189
+ }
190
+ }
191
+ };
@@ -8,11 +8,17 @@ export declare class AstUtil {
8
8
  static FUNCTION_TYPES: string[];
9
9
  static getNodePath(node: AstNode): string;
10
10
  static getShortNodeMsg(node: AstNode, hideParentProperty?: boolean): string;
11
+ static getTopScopeNodesByLineNumberRange(mapFileLineToNodeSet: Map<number, Set<AstNode>>, lineNumberStart: number, lineNumberEnd: number, loose?: boolean): AstNode[];
11
12
  private static isValidNodeCollect;
12
13
  private static isValidArrayNodeCollect;
13
14
  private static collectEffectId;
15
+ private static findOrCreateImportedMember;
16
+ private static findOrCreateExportedMember;
14
17
  private static updateImportedAndExportedMember;
15
18
  private static deepSearchParamsIdentifier;
19
+ private static collectDependenceIdsOfExportMembers;
20
+ private static collectExpressionIdentifiersShallow;
21
+ private static _collectExpressionIdentifiersShallow;
16
22
  private static collectDependenceIds;
17
23
  private static updateLoc;
18
24
  private static collectVariableDeclarationIdentifiers;
@@ -43,6 +43,33 @@ var _AstUtil = class {
43
43
  ].map((e) => e.filter(Boolean).join(":")).filter(Boolean).join(" ");
44
44
  return `${msg}「${startLine}:${startColumn}, ${endLine}:${endColumn}」`;
45
45
  }
46
+ static getTopScopeNodesByLineNumberRange(mapFileLineToNodeSet, lineNumberStart, lineNumberEnd, loose = false) {
47
+ const nodeSet = /* @__PURE__ */ new Set();
48
+ for (let i = lineNumberStart; i <= lineNumberEnd; i++) {
49
+ const astNode = mapFileLineToNodeSet.get(i);
50
+ if (!astNode) {
51
+ continue;
52
+ }
53
+ let added = false;
54
+ for (const nodeItem of astNode) {
55
+ const { startLine, endLine } = nodeItem._util;
56
+ if (startLine >= lineNumberStart && endLine <= lineNumberEnd) {
57
+ if (!["File", "Program"].includes(nodeItem.type)) {
58
+ nodeSet.add(nodeItem);
59
+ }
60
+ added = true;
61
+ }
62
+ }
63
+ if (!added && loose) {
64
+ const firstNode = [...astNode][0];
65
+ if (!["File", "Program"].includes(firstNode.type)) {
66
+ nodeSet.add(firstNode);
67
+ }
68
+ }
69
+ }
70
+ const collections = [...nodeSet].map((e) => e._util.nodeCollection).flat();
71
+ return [...nodeSet].filter((e) => !collections.includes(e));
72
+ }
46
73
  static isValidNodeCollect(astNode) {
47
74
  return typeof (astNode == null ? void 0 : astNode.type) === "string";
48
75
  }
@@ -51,9 +78,118 @@ var _AstUtil = class {
51
78
  }
52
79
  static collectEffectId(id) {
53
80
  }
54
- static updateImportedAndExportedMember(programBodyChild, programNode) {
55
- if (programNode.type !== "Program")
56
- return;
81
+ static findOrCreateImportedMember(importedMember, sourceValue) {
82
+ let target = importedMember.find((v) => v.sourcePath === sourceValue);
83
+ if (!target) {
84
+ target = { sourcePath: sourceValue, members: [] };
85
+ importedMember.push(target);
86
+ }
87
+ return target;
88
+ }
89
+ static findOrCreateExportedMember(exportedMember, sourceValue) {
90
+ let target = exportedMember.find((v) => v.sourcePath === sourceValue);
91
+ if (!target) {
92
+ target = { sourcePath: sourceValue, members: [], ExportAllDeclaration: false };
93
+ exportedMember.push(target);
94
+ }
95
+ return target;
96
+ }
97
+ static updateImportedAndExportedMember(node, programNode) {
98
+ var _a;
99
+ const { type, source, declaration, specifiers, _util } = node;
100
+ const { filePath } = _util;
101
+ const sourceValue = (source == null ? void 0 : source.value) || filePath;
102
+ const { importedMember, exportedMember } = programNode._util;
103
+ if (type === "ImportDeclaration") {
104
+ specifiers.forEach((specifier) => {
105
+ const { local, imported } = specifier;
106
+ const target = this.findOrCreateImportedMember(importedMember, sourceValue);
107
+ if (specifier.type === "ImportNamespaceSpecifier") {
108
+ target.members.push({
109
+ localName: local.name,
110
+ importedName: "*"
111
+ });
112
+ return;
113
+ }
114
+ if (specifier.type === "ImportDefaultSpecifier") {
115
+ target.members.push({
116
+ localName: local.name,
117
+ importedName: "default"
118
+ });
119
+ return;
120
+ }
121
+ if (specifier.type === "ImportSpecifier") {
122
+ target.members.push({
123
+ localName: local.name,
124
+ importedName: imported.name
125
+ });
126
+ }
127
+ });
128
+ }
129
+ if (type === "ExportAllDeclaration") {
130
+ const target = exportedMember.find((v) => v.sourcePath === sourceValue);
131
+ if (!target) {
132
+ exportedMember.push({ sourcePath: sourceValue, members: [], ExportAllDeclaration: true });
133
+ }
134
+ }
135
+ if (type === "ExportNamedDeclaration") {
136
+ Array.isArray(specifiers) && specifiers.forEach((specifier) => {
137
+ const { local, exported } = specifier;
138
+ const target = this.findOrCreateExportedMember(exportedMember, sourceValue);
139
+ if (specifier.type === "ExportNamespaceSpecifier") {
140
+ target.members.push({
141
+ localName: "*",
142
+ exportedName: exported.name
143
+ });
144
+ return;
145
+ }
146
+ if (specifier.type === "ExportSpecifier") {
147
+ target.members.push({
148
+ localName: local.name,
149
+ exportedName: exported.name
150
+ });
151
+ return;
152
+ }
153
+ });
154
+ if (Array.isArray(declaration == null ? void 0 : declaration.declarations)) {
155
+ declaration == null ? void 0 : declaration.declarations.forEach((dec) => {
156
+ const target = this.findOrCreateExportedMember(exportedMember, sourceValue);
157
+ this.collectVariableDeclarationIdentifiers(dec, (identifier) => {
158
+ try {
159
+ const idName = identifier.name;
160
+ target.members.push({
161
+ localName: idName,
162
+ exportedName: idName
163
+ });
164
+ } catch (e) {
165
+ console.log("declaration?.declarations.forEach", e.message);
166
+ }
167
+ });
168
+ });
169
+ } else if (this.EXPORT_DECLARATION_TYPES.includes(declaration == null ? void 0 : declaration.type)) {
170
+ const target = this.findOrCreateExportedMember(exportedMember, sourceValue);
171
+ try {
172
+ const idName = (_a = declaration.id) == null ? void 0 : _a.name;
173
+ target.members.push({
174
+ localName: idName,
175
+ exportedName: idName
176
+ });
177
+ } catch (e) {
178
+ console.log("declaration " + e.message);
179
+ }
180
+ }
181
+ }
182
+ if (type === "ExportDefaultDeclaration") {
183
+ let target = exportedMember.find((v) => v.sourcePath === filePath);
184
+ if (!target) {
185
+ target = { sourcePath: filePath, members: [], ExportAllDeclaration: false };
186
+ exportedMember.push(target);
187
+ }
188
+ target.members.push({
189
+ localName: "default",
190
+ exportedName: "default"
191
+ });
192
+ }
57
193
  }
58
194
  static deepSearchParamsIdentifier(id, callback) {
59
195
  if (!id) {
@@ -86,7 +222,98 @@ var _AstUtil = class {
86
222
  }
87
223
  }
88
224
  }
225
+ static collectDependenceIdsOfExportMembers(node, callback) {
226
+ if (node.type === "ExportNamedDeclaration") {
227
+ const { declaration, specifiers } = node;
228
+ if ((declaration == null ? void 0 : declaration.type) === "Identifier") {
229
+ callback(declaration);
230
+ }
231
+ for (const specifier of specifiers) {
232
+ const { local } = specifier;
233
+ if ((local == null ? void 0 : local.type) === "Identifier") {
234
+ callback(local);
235
+ }
236
+ }
237
+ }
238
+ if (node.type === "ExportDefaultDeclaration") {
239
+ const declaration = node.declaration;
240
+ if ((declaration == null ? void 0 : declaration.type) === "Identifier") {
241
+ callback(declaration);
242
+ }
243
+ }
244
+ }
245
+ static collectExpressionIdentifiersShallow(exp, callback) {
246
+ if (!exp || exp.type === "ThisExpression") {
247
+ return;
248
+ }
249
+ this._collectExpressionIdentifiersShallow(exp, callback);
250
+ }
251
+ static _collectExpressionIdentifiersShallow(exp, callback) {
252
+ var _a, _b;
253
+ if (!exp || exp.type === "ThisExpression" || exp._util.holdingIdType)
254
+ return;
255
+ if (exp.type === "Identifier") {
256
+ if ((exp._util.parentProperty === "property" || exp._util.parentProperty === "key") && !((_a = exp._util.parent) == null ? void 0 : _a.computed))
257
+ return;
258
+ callback(exp);
259
+ return;
260
+ }
261
+ if (exp.type === "JSXIdentifier" && ((_b = exp._util.parent) == null ? void 0 : _b.type) !== "JSXAttribute") {
262
+ callback(exp);
263
+ return;
264
+ }
265
+ }
89
266
  static collectDependenceIds(node) {
267
+ const { _util } = node;
268
+ const { dependenceIds, holdingIdNameMap, children, dependenceIdsNoScope, holdingIds } = _util;
269
+ children.forEach((child) => {
270
+ if (child._util.dependenceIdsNoScope.size > 0) {
271
+ child._util.dependenceIdsNoScope.forEach((id) => dependenceIds.add(id));
272
+ }
273
+ this.collectDependenceIdsOfExportMembers(child, (id) => dependenceIds.add(id));
274
+ this.collectExpressionIdentifiersShallow(child, (exp) => {
275
+ var _a, _b;
276
+ if (exp.type === "ThisExpression" || exp._util.holdingIdType || ["imported", "exported"].includes(exp._util.parentProperty))
277
+ return;
278
+ if (exp.type === "Identifier") {
279
+ if ((exp._util.parentProperty === "property" || exp._util.parentProperty === "key") && !((_a = exp._util.parent) == null ? void 0 : _a.computed))
280
+ return;
281
+ }
282
+ if (exp.type === "JSXIdentifier" && ((_b = exp._util.parent) == null ? void 0 : _b.type) === "JSXAttribute")
283
+ return;
284
+ dependenceIds.add(exp);
285
+ });
286
+ });
287
+ for (const dependenceId of [...dependenceIds]) {
288
+ if (!dependenceId._util) {
289
+ continue;
290
+ }
291
+ if (holdingIds.has(dependenceId)) {
292
+ dependenceIds.delete(dependenceId);
293
+ continue;
294
+ }
295
+ if (dependenceId._util.variableScope.length === 0 && typeof dependenceId.name === "string" && holdingIdNameMap.has(dependenceId.name)) {
296
+ dependenceId._util.variableScope.push(...holdingIdNameMap.get(dependenceId.name));
297
+ const firstPick = dependenceId._util.variableScope[0];
298
+ if (firstPick && firstPick._util.uuid !== dependenceId._util.uuid) {
299
+ firstPick._util.occupation.add(dependenceId);
300
+ }
301
+ }
302
+ if (dependenceId._util.variableScope.length === 0) {
303
+ dependenceIdsNoScope.add(dependenceId);
304
+ }
305
+ }
306
+ if (node.type === "Program") {
307
+ for (const dependenceId of [...dependenceIdsNoScope]) {
308
+ if (dependenceId.type === "JSXIdentifier" && this.intrinsicElements.includes(dependenceId.name)) {
309
+ dependenceIdsNoScope.delete(dependenceId);
310
+ dependenceIds.delete(dependenceId);
311
+ } else if (dependenceId.type === "Identifier" && this.windowProperties.includes(dependenceId.name)) {
312
+ dependenceIdsNoScope.delete(dependenceId);
313
+ dependenceIds.delete(dependenceId);
314
+ }
315
+ }
316
+ }
90
317
  }
91
318
  static updateLoc(astNode, extra) {
92
319
  var _a, _b, _c, _d, _e, _f, _g;
@@ -109,7 +336,7 @@ var _AstUtil = class {
109
336
  var _a2, _b2;
110
337
  return (_b2 = (_a2 = n.loc) == null ? void 0 : _a2.end) == null ? void 0 : _b2.column;
111
338
  }), (_f = astNode.loc) == null ? void 0 : _f.end.column);
112
- _util.uuid = `${filePath}:${type}:${name}「${_util.startLine}:${_util.startColumn},${_util.endLine}:${_util.endColumn}」`;
339
+ _util.uuid = `${filePath}@${type}:${name}「${_util.startLine}:${_util.startColumn},${_util.endLine}:${_util.endColumn}」`;
113
340
  mapUuidToNode.set(_util.uuid, astNode);
114
341
  for (let i = _util.startLine; i <= _util.endLine; i++) {
115
342
  mapFileLineToNodeSet.set(i, mapFileLineToNodeSet.get(i) || /* @__PURE__ */ new Set());
@@ -295,7 +522,9 @@ var _AstUtil = class {
295
522
  });
296
523
  try {
297
524
  children.forEach((child) => child._util.parent = node);
298
- nodeCollection.forEach((nodeItem) => nodeItem._util.ancestors.unshift(node));
525
+ nodeCollection.forEach((nodeItem) => {
526
+ !nodeItem._util.ancestors.includes(node) && nodeItem._util.ancestors.unshift(node);
527
+ });
299
528
  } catch (e) {
300
529
  console.error("parent ancestors update", e.message);
301
530
  }
@@ -156,7 +156,9 @@ var _AstUtil = class {
156
156
  });
157
157
  try {
158
158
  children.forEach((child) => child._util.parent = node);
159
- nodeCollection.forEach((nodeItem) => nodeItem._util.ancestors.unshift(node));
159
+ nodeCollection.forEach((nodeItem) => {
160
+ !nodeItem._util.ancestors.includes(node) && nodeItem._util.ancestors.unshift(node);
161
+ });
160
162
  } catch (e) {
161
163
  console.error("parent ancestors update", e.message);
162
164
  }
@@ -187,7 +189,7 @@ var _AstUtil = class {
187
189
  try {
188
190
  node.body.forEach((child) => this.updateImportedAndExportedMember(child, node));
189
191
  } catch (e) {
190
- console.error("updateImportedAndExportedMember", e.message);
192
+ console.error("收集导入、导出成员 报错", e.message);
191
193
  }
192
194
  }
193
195
  try {
@@ -224,6 +226,10 @@ var _AstUtil = class {
224
226
  const nameList = /* @__PURE__ */ new Set();
225
227
  outer:
226
228
  for (const ancestor of nodeArray) {
229
+ if (ancestor.type === "VElement") {
230
+ nameList.add("default");
231
+ break outer;
232
+ }
227
233
  if (ancestor.type === "ExportDefaultDeclaration") {
228
234
  const { declaration } = ancestor;
229
235
  if (declaration) {
@@ -884,7 +890,7 @@ var _AstUtil = class {
884
890
  var _a2, _b2;
885
891
  return (_b2 = (_a2 = n.loc) == null ? void 0 : _a2.end) == null ? void 0 : _b2.column;
886
892
  }), (_f = astNode.loc) == null ? void 0 : _f.end.column);
887
- _util.uuid = `${filePath}:${type}:${name}「${_util.startLine}:${_util.startColumn},${_util.endLine}:${_util.endColumn}」`;
893
+ _util.uuid = `${filePath}@${type}:${name}「${_util.startLine}:${_util.startColumn},${_util.endLine}:${_util.endColumn}」`;
888
894
  mapUuidToNode.set(_util.uuid, astNode);
889
895
  for (let i = _util.startLine; i <= _util.endLine; i++) {
890
896
  mapFileLineToNodeSet.set(i, mapFileLineToNodeSet.get(i) || /* @__PURE__ */ new Set());
@@ -39,5 +39,9 @@ function filterEffectedExportMember(filePath, absPathPrefix, startLine, endLine)
39
39
  const { mapFileLineToNodeSet } = astKit;
40
40
  const topScopeNodes = import_AstUtil.default.getTopScopeNodesByLineNumberRange(mapFileLineToNodeSet, startLine, endLine);
41
41
  const exportMembers = topScopeNodes.map((node) => import_AstUtil.default.findExportedMembersNameFromAncestors(node)).flat();
42
- return [...new Set(exportMembers)];
42
+ const res = [...new Set(exportMembers)];
43
+ if (res.length === 0 && filePath.endsWith(".vue")) {
44
+ res.push("default");
45
+ }
46
+ return res;
43
47
  }
@@ -1,2 +1,2 @@
1
1
  export declare function isRepoTypeSupported(repoType: string): boolean;
2
- export declare function getRepoType(jsonPath: string): "unknown" | "umi" | "vue2";
2
+ export declare function getRepoType(jsonPath: string): "umi" | "vue2" | "unknown";
@@ -26,7 +26,7 @@ module.exports = __toCommonJS(getRepoSupportFlag_exports);
26
26
  var import_fs = require("fs");
27
27
  var import_utils = require("@umijs/utils");
28
28
  function isRepoTypeSupported(repoType) {
29
- return ["umi"].includes(repoType);
29
+ return ["umi", "vue2"].includes(repoType);
30
30
  }
31
31
  function getRepoType(jsonPath) {
32
32
  var _a, _b, _c;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "js-code-detector",
3
- "version": "0.0.50",
3
+ "version": "0.0.51",
4
4
  "description": "",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/cjs/index.d.ts",