mp-lens
Version:
微信小程序分析工具 (Unused Code, Dependencies, Visualization)
169 lines • 6.72 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.analyzeWxmlTags = analyzeWxmlTags;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Could not find a declaration file for module '@wxml/parser'
const parser_1 = require("@wxml/parser");
const fs = __importStar(require("fs"));
const debug_logger_1 = require("../../utils/debug-logger");
const wxml_path_1 = require("../../utils/wxml-path");
/**
* Analyzes a WXML file and all its imported/included templates recursively
* to extract a map of tag name -> set of WXML files where it is used.
*
* @param wxmlFilePath Path to the WXML file to analyze
* @param pathResolver Instance of PathResolver to resolve import/include paths
* @param visited Set of already visited files (to prevent infinite loops)
* @returns Map<tag, Set<wxmlFile>>
*/
async function analyzeWxmlTags(wxmlFilePath, pathResolver, visited = new Set()) {
// Check for circular imports
if (visited.has(wxmlFilePath)) {
return new Map();
}
visited.add(wxmlFilePath);
const tagToFiles = new Map();
try {
// Read WXML file content
const content = fs.readFileSync(wxmlFilePath, 'utf-8');
// Parse WXML content to AST
const ast = (0, parser_1.parse)(content);
// Collect tags in this file
collectTagsWithSource(ast, wxmlFilePath, tagToFiles);
// Process imports and includes
const importPaths = extractImportPaths(ast);
for (const importPath of importPaths) {
try {
const resolvedPath = pathResolver.resolveAnyPath(importPath, wxmlFilePath, ['.wxml']);
if (resolvedPath) {
const importedTagToFiles = await analyzeWxmlTags(resolvedPath, pathResolver, visited);
// Merge importedTagToFiles into tagToFiles
for (const [tag, files] of importedTagToFiles.entries()) {
if (!tagToFiles.has(tag))
tagToFiles.set(tag, new Set());
for (const f of files)
tagToFiles.get(tag).add(f);
}
}
}
catch (err) {
debug_logger_1.logger.warn(`Error processing import ${importPath} in ${wxmlFilePath}: ${err}`);
}
}
return tagToFiles;
}
catch (err) {
debug_logger_1.logger.error(`Error analyzing WXML file ${wxmlFilePath}: ${err}`);
return tagToFiles;
}
}
/**
* Collects all tag names in the AST, mapping each tag to the WXML file where it is found.
*/
function collectTagsWithSource(ast, wxmlFilePath, tagToFiles) {
var _a;
if (ast.type === 'WXElement') {
if (!tagToFiles.has(ast.name))
tagToFiles.set(ast.name, new Set());
tagToFiles.get(ast.name).add(wxmlFilePath);
// Process attributes for generic components
const attrs = (_a = ast.startTag) === null || _a === void 0 ? void 0 : _a.attributes;
if (attrs && Array.isArray(attrs)) {
for (const attr of attrs) {
if (attr.key && attr.key.startsWith('generic:') && attr.value) {
if (!tagToFiles.has(attr.value))
tagToFiles.set(attr.value, new Set());
tagToFiles.get(attr.value).add(wxmlFilePath);
}
}
}
}
// Recursively process children
if (ast.type === 'WXElement' && Array.isArray(ast.children)) {
for (const child of ast.children) {
collectTagsWithSource(child, wxmlFilePath, tagToFiles);
}
}
// Handle Program/body
if (ast.type === 'Program' && Array.isArray(ast.body)) {
for (const node of ast.body) {
collectTagsWithSource(node, wxmlFilePath, tagToFiles);
}
}
}
/**
* Extracts import and include paths from the AST
*
* @param ast WXML AST node or Program
* @returns Array of import/include paths
*/
function extractImportPaths(ast) {
const importPaths = [];
findImportTags(ast, importPaths);
return importPaths;
}
/**
* Recursively finds import and include tags in the AST
*
* @param ast WXML AST node or Program
* @param importPaths Array to store found paths
*/
function findImportTags(ast, importPaths) {
var _a;
if (ast.type === 'WXElement' && (ast.name === 'import' || ast.name === 'include')) {
// Find src attribute from startTag.attributes per wxml-parser AST docs
const attrs = (_a = ast.startTag) === null || _a === void 0 ? void 0 : _a.attributes;
if (attrs && Array.isArray(attrs)) {
const srcAttr = attrs.find((attr) => attr.key === 'src');
if (srcAttr && srcAttr.value) {
importPaths.push((0, wxml_path_1.normalizeWxmlImportPath)(srcAttr.value));
}
}
}
// Recursively process children
if (ast.type === 'WXElement' && Array.isArray(ast.children)) {
for (const child of ast.children) {
findImportTags(child, importPaths);
}
}
// Handle Program/body
if (ast.type === 'Program' && Array.isArray(ast.body)) {
for (const node of ast.body) {
findImportTags(node, importPaths);
}
}
}
//# sourceMappingURL=analyzeWxmlTags.js.map