NodeSecure 隐藏功能:mama

发布: (2026年1月10日 GMT+8 15:12)
3 min read
原文: Dev.to

Source: Dev.to

Hello 👋

我将开启一个 短篇 系列文章,重点介绍 NodeSecure 项目中不太为人所知的部分。目标是帮助新贡献者更清晰地了解驱动该项目的后端构建块。

Chapter 1: mama

Mama 代表 ManifestManager。该包旨在管理并加载 npm 清单(这里指 package.json 文件,为简化起见)。

在内部它使用 @nodesecure/npm-types 来提供精确、最新的类型(包括运行时相关字段)。我们将在另一篇文章中深入探讨该包。

import { ManifestManager } from "@nodesecure/mama";

// asynchronous version
const mama = await ManifestManager.fromPackageJSON(process.cwd());
console.log(mama.document);

此包提供了许多在 Scanner monorepo 中后端组件间共享的实用工具。

Integrity

你可以通过 只读 getter integrity 轻松提取哈希值。

console.log(mama.integrity);

Scanner 使用它来断言 tar 包中的 package.json 与上传到注册表的文件相匹配(即所谓的 manifest confusion)。

被哈希的属性包括:

{
  "name",
  "version",
  "dependencies",
  "license": "license ?? \"NONE\"",
  "scripts"
}

当检测到不匹配时,工具会将其报告为全局警告,如 CLI 界面所示:

NodeSecure global warnings

Module type

受 Antfu 最近推出的 node-modules-inspector 工具启发,我们重新实现了相同的模块类型检测:

// "dts" | "faux" | "dual" | "esm" | "cjs"
console.log(mama.moduleType);

Entry files

mama 可以递归提取入口文件,使用 Node.js 的 exports 字段(或像 main 这样的旧字段)。该 API 为惰性加载,返回一个 IterableIterator

console.log([...mama.getEntryFiles()]);

此 API 在 tarball 包中与 JS‑X‑Ray 的 EntryFilesAnalyser 结合使用。

async scanFiles(): Promise {
  const location = this.manifest.location;
  const [composition, spdx] = await Promise.all([
    getTarballComposition(location),
    conformance.extractLicenses(location)
  ]);

  const code = await new SourceCodeScanner(this.manifest).iterate({
    manifest: [...this.manifest.getEntryFiles()]
      .flatMap(filterJavaScriptFiles()),
    javascript: composition.files
      .flatMap(filterJavaScriptFiles())
  });

  return {
    conformance: spdx,
    composition,
    code
  };
}

Author

解析 NPM author 字段(如果存在),并返回一个 Contact 接口:

interface Contact {
  email?: string;
  url?: string;
  name: string;
}

例如,John Doe 会产生:

{
  "name": "John Doe",
  "email": "john.doe@gmail.com"
}

Others

该模块还提供了其他与读取和管理清单相关的实用工具,例如:

  • 解析包规格(包括作用域/组织、包名以及 semver 版本范围)
  • 检测本地 lockfile

The end

完整的模块文档可在 这里 查看。

感谢阅读。

Back to Blog

相关文章

阅读更多 »