实现示例


type Pkg = { type?: 'module' | 'commonjs'; main?: string; module?: string; exports?: Record<string, any> }

function isJs(path?: string): boolean { return !!path && /\.js$/.test(path) }
function isCjs(path?: string): boolean { return !!path && /\.cjs$/.test(path) }
function isMjs(path?: string): boolean { return !!path && /\.mjs$/.test(path) }

function validExports(exp?: Record<string, any>, type?: 'module' | 'commonjs'): boolean {
  if (!exp) return true
  const keys = Object.keys(exp)
  for (const k of keys) {
    const v = exp[k]
    if (typeof v === 'string') {
      if (type === 'module' && !/\.m?js$/.test(v)) return false
      if (type === 'commonjs' && !/\.c?js$/.test(v)) return false
    }
    if (typeof v === 'object') {
      for (const c of Object.keys(v)) {
        const t = v[c]
        if (typeof t !== 'string') return false
        if (c === 'import' && !/\.m?js$/.test(t)) return false
        if (c === 'require' && !/\.c?js$/.test(t)) return false
      }
    }
  }
  return true
}

function evaluate(pkg: Pkg): { ok: boolean; errors: string[] } {
  const errors: string[] = []
  if (pkg.type === 'module') {
    if (pkg.main && !(isMjs(pkg.main) || isJs(pkg.main))) errors.push('type-module-main')
    if (pkg.module && !isJs(pkg.module)) errors.push('type-module-module')
  }
  if (pkg.type === 'commonjs') {
    if (pkg.main && !(isCjs(pkg.main) || isJs(pkg.main))) errors.push('type-cjs-main')
  }
  if (!validExports(pkg.exports, pkg.type)) errors.push('exports')
  return { ok: errors.length === 0, errors }
}

审计与发布治理

  • 审计入口字段与条件导出;不一致阻断并输出修复建议。
  • 变更需兼容性验证与审批,防止双包危害进入产线。


点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部