get-packed.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. const fs = require("fs-extra");
  3. const path = require("path");
  4. const ssri = require("ssri");
  5. const tar = require("tar");
  6. module.exports.getPacked = getPacked;
  7. function getPacked(pkg, tarFilePath) {
  8. const bundledWanted = new Set(pkg.bundleDependencies || pkg.bundledDependencies || []);
  9. const bundled = new Set();
  10. const files = [];
  11. let totalEntries = 0;
  12. let totalEntrySize = 0;
  13. return tar
  14. .list({
  15. file: tarFilePath,
  16. onentry(entry) {
  17. totalEntries += 1;
  18. totalEntrySize += entry.size;
  19. const p = entry.path;
  20. /* istanbul ignore if */
  21. if (p.startsWith("package/node_modules/")) {
  22. const name = p.match(/^package\/node_modules\/((?:@[^/]+\/)?[^/]+)/)[1];
  23. if (bundledWanted.has(name)) {
  24. bundled.add(name);
  25. }
  26. } else {
  27. files.push({
  28. path: entry.path.replace(/^package\//, ""),
  29. size: entry.size,
  30. mode: entry.mode,
  31. });
  32. }
  33. },
  34. strip: 1,
  35. })
  36. .then(() =>
  37. Promise.all([
  38. fs.stat(tarFilePath),
  39. ssri.fromStream(fs.createReadStream(tarFilePath), {
  40. algorithms: ["sha1", "sha512"],
  41. }),
  42. ])
  43. )
  44. .then(([{ size }, { sha1, sha512 }]) => {
  45. const shasum = sha1[0].hexDigest();
  46. return {
  47. id: `${pkg.name}@${pkg.version}`,
  48. name: pkg.name,
  49. version: pkg.version,
  50. size,
  51. unpackedSize: totalEntrySize,
  52. shasum,
  53. integrity: ssri.parse(sha512[0]),
  54. filename: path.basename(tarFilePath),
  55. files,
  56. entryCount: totalEntries,
  57. bundled: Array.from(bundled),
  58. tarFilePath,
  59. };
  60. });
  61. }