check-main-package-js-usage.mjs 8.8 KB
/**
 * @file 检查分包是否把仅供分包使用的 JavaScript 依赖留在主包根目录。
 * 只分析静态 import/export-from/require;微信运行时动态路径不属于本门禁范围。
 */

import {
  existsSync,
  readFileSync,
  readdirSync,
  statSync
} from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { parse } from '@babel/parser'

const defaultProjectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const ALWAYS_IGNORED_DIRECTORIES = new Set(['.git', 'miniprogram_npm', 'node_modules'])

/**
 * 把路径统一为仓库相对 POSIX 格式,便于跨平台比较。
 * @param {string} projectRoot 项目绝对路径。
 * @param {string} absolutePath 文件绝对路径。
 * @returns {string} 仓库相对路径。
 */
function toProjectRelative(projectRoot, absolutePath) {
  return path.relative(projectRoot, absolutePath).replaceAll('\\', '/')
}

/**
 * 读取微信上传忽略配置,避免把测试、脚本和权威生成源当作运行时代码。
 * @param {string} projectRoot 项目绝对路径。
 * @returns {Array<{value: string, type: 'file'|'folder'}>} 规范化忽略项。
 */
function readUploadIgnores(projectRoot) {
  const configPath = path.join(projectRoot, 'project.config.json')
  if (!existsSync(configPath)) return []
  const config = JSON.parse(readFileSync(configPath, 'utf8'))
  return (config.packOptions?.ignore || [])
    .filter(item => item && typeof item.value === 'string')
    .map(item => ({
      value: item.value.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, ''),
      type: item.type === 'file' ? 'file' : 'folder'
    }))
}

/**
 * 判断文件是否被上传配置排除。
 * @param {string} relativePath 仓库相对路径。
 * @param {Array<{value: string, type: 'file'|'folder'}>} ignores 忽略项。
 * @returns {boolean} 是否忽略。
 */
function isUploadIgnored(relativePath, ignores) {
  const pathSegments = relativePath.split('/')
  if (pathSegments.some(segment => ALWAYS_IGNORED_DIRECTORIES.has(segment))) return true
  return ignores.some(item =>
    item.type === 'file'
      ? relativePath === item.value
      : relativePath === item.value || relativePath.startsWith(`${item.value}/`)
  )
}

/**
 * 收集参与上传的 JavaScript 文件。
 * @param {string} projectRoot 项目绝对路径。
 * @param {Array<{value: string, type: 'file'|'folder'}>} ignores 忽略项。
 * @param {string} [directory] 当前扫描目录。
 * @returns {string[]} JavaScript 文件绝对路径。
 */
function listRuntimeJavaScript(projectRoot, ignores, directory = projectRoot) {
  return readdirSync(directory, { withFileTypes: true })
    .sort((left, right) => left.name.localeCompare(right.name))
    .flatMap(entry => {
      const absolutePath = path.join(directory, entry.name)
      const relativePath = toProjectRelative(projectRoot, absolutePath)
      if (isUploadIgnored(relativePath, ignores)) return []
      if (entry.isDirectory()) return listRuntimeJavaScript(projectRoot, ignores, absolutePath)
      if (entry.isFile() && /\.(?:cjs|js|mjs)$/.test(entry.name)) return [absolutePath]
      return []
    })
}

/**
 * 递归提取 AST 中的静态模块路径。
 * @param {unknown} node Babel AST 节点。
 * @param {string[]} sources 收集结果。
 * @returns {void}
 */
function collectStaticModuleSources(node, sources) {
  if (!node || typeof node !== 'object') return
  if (
    (node.type === 'ImportDeclaration' ||
      node.type === 'ExportNamedDeclaration' ||
      node.type === 'ExportAllDeclaration') &&
    typeof node.source?.value === 'string'
  ) {
    sources.push(node.source.value)
  }
  if (
    node.type === 'CallExpression' &&
    (node.callee?.name === 'require' || node.callee?.type === 'Import') &&
    node.arguments?.[0]?.type === 'StringLiteral'
  ) {
    sources.push(node.arguments[0].value)
  }
  if (node.type === 'ImportExpression' && node.source?.type === 'StringLiteral') {
    sources.push(node.source.value)
  }

  for (const [key, value] of Object.entries(node)) {
    if (['comments', 'end', 'extra', 'loc', 'start'].includes(key)) continue
    if (Array.isArray(value)) {
      for (const child of value) collectStaticModuleSources(child, sources)
    } else {
      collectStaticModuleSources(value, sources)
    }
  }
}

/**
 * 解析本地模块路径;第三方包和无法静态解析的路径返回 null。
 * @param {string} projectRoot 项目绝对路径。
 * @param {string} importerPath 引用方绝对路径。
 * @param {string} source import/require 源字符串。
 * @returns {string|null} 已存在模块的绝对路径。
 */
function resolveLocalModule(projectRoot, importerPath, source) {
  let basePath
  if (source.startsWith('~/')) {
    basePath = path.resolve(projectRoot, source.slice(2))
  } else if (source.startsWith('/')) {
    basePath = path.resolve(projectRoot, source.slice(1))
  } else if (source.startsWith('.')) {
    basePath = path.resolve(path.dirname(importerPath), source)
  } else {
    return null
  }

  const relativeBase = path.relative(projectRoot, basePath)
  if (relativeBase === '..' || relativeBase.startsWith(`..${path.sep}`)) return null
  const candidates = [
    basePath,
    `${basePath}.js`,
    `${basePath}.mjs`,
    `${basePath}.cjs`,
    path.join(basePath, 'index.js'),
    path.join(basePath, 'index.mjs'),
    path.join(basePath, 'index.cjs')
  ]
  return candidates.find(candidate => existsSync(candidate) && statSync(candidate).isFile()) || null
}

/**
 * 找出“由分包直接引用、但没有任何主包运行时代码直接引用”的根目录 JS。
 * 这类文件会被跨包引用拉进主包,并触发微信开发者工具的主包未使用 JS 提示。
 *
 * @param {{projectRoot?: string}} [options] 检查选项。
 * @returns {Array<{target: string, importers: string[], packages: string[]}>} 违规列表。
 */
export function findSubpackageOnlyRootJavaScriptImports({
  projectRoot = defaultProjectRoot
} = {}) {
  const absoluteRoot = path.resolve(projectRoot)
  const appConfig = JSON.parse(readFileSync(path.join(absoluteRoot, 'app.json'), 'utf8'))
  const packageRoots = (appConfig.subPackages || appConfig.subpackages || [])
    .map(item => item.root?.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, ''))
    .filter(Boolean)
    .sort((left, right) => right.length - left.length)
  const ignores = readUploadIgnores(absoluteRoot)
  const inbound = new Map()

  /** @param {string} relativePath 仓库相对路径。 @returns {string|null} 所属分包根。 */
  const getPackageRoot = relativePath =>
    packageRoots.find(root => relativePath === root || relativePath.startsWith(`${root}/`)) || null

  for (const importerPath of listRuntimeJavaScript(absoluteRoot, ignores)) {
    const importer = toProjectRelative(absoluteRoot, importerPath)
    const ast = parse(readFileSync(importerPath, 'utf8'), {
      sourceType: 'unambiguous',
      plugins: [
        'classProperties',
        'dynamicImport',
        'nullishCoalescingOperator',
        'objectRestSpread',
        'optionalChaining'
      ]
    })
    const sources = []
    collectStaticModuleSources(ast, sources)
    for (const source of new Set(sources)) {
      const targetPath = resolveLocalModule(absoluteRoot, importerPath, source)
      if (!targetPath || !/\.(?:cjs|js|mjs)$/.test(targetPath)) continue
      const target = toProjectRelative(absoluteRoot, targetPath)
      if (!inbound.has(target)) inbound.set(target, [])
      inbound.get(target).push({ importer, packageRoot: getPackageRoot(importer) })
    }
  }

  return [...inbound.entries()]
    .filter(([target]) => !getPackageRoot(target))
    .map(([target, importRecords]) => {
      const subpackageImports = importRecords.filter(record => record.packageRoot)
      const mainImports = importRecords.filter(record => !record.packageRoot)
      return { target, subpackageImports, mainImports }
    })
    .filter(item => item.subpackageImports.length > 0 && item.mainImports.length === 0)
    .map(item => ({
      target: item.target,
      importers: [...new Set(item.subpackageImports.map(record => record.importer))].sort(),
      packages: [...new Set(item.subpackageImports.map(record => record.packageRoot))].sort()
    }))
    .sort((left, right) => left.target.localeCompare(right.target))
}

const isCommandLine =
  process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url

if (isCommandLine) {
  const violations = findSubpackageOnlyRootJavaScriptImports()
  if (violations.length === 0) {
    console.log('No subpackage-only JavaScript imports remain in the main package.')
  } else {
    console.error('Subpackage-only JavaScript imports found in the main package:')
    for (const violation of violations) {
      console.error(`- ${violation.target}`)
      for (const importer of violation.importers) console.error(`  <- ${importer}`)
    }
    process.exitCode = 1
  }
}