marketing-source-map-evidence.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { readFile } from "node:fs/promises";
  2. import { createHash } from "node:crypto";
  3. import { resolve } from "node:path";
  4. import { fileURLToPath, pathToFileURL } from "node:url";
  5. import { TraceMap, eachMapping } from "@jridgewell/trace-mapping";
  6. /** 只接受与该次构建完全匹配的 map;不会把当前 out 当作历史产物。 */
  7. export async function loadGeneratedLineEvidence(outputRoot, domain, manifest) {
  8. if (
  9. manifest?.schemaVersion !== 1 ||
  10. manifest.status !== "fresh-stable" ||
  11. !Array.isArray(manifest.domains) ||
  12. !manifest.domains.includes(domain) ||
  13. !Array.isArray(manifest.changedFiles) ||
  14. manifest.changedFiles.length
  15. )
  16. return { status: "unverified" };
  17. const maps = Object.entries(manifest.outputs ?? {}).filter(
  18. ([key]) => key.startsWith(`${domain}/`) && key.endsWith(".map"),
  19. );
  20. if (!maps.length) return { status: "unverified" };
  21. const sources = new Map();
  22. for (const [key, hash] of maps) {
  23. if (key.split(/[\\/]/u).includes("..")) return { status: "unverified" };
  24. const path = resolve(outputRoot, key);
  25. let bytes;
  26. try {
  27. bytes = await readFile(path);
  28. } catch (error) {
  29. if (error.code === "ENOENT") return { status: "missing-map" };
  30. throw error;
  31. }
  32. if (createHash("sha256").update(bytes).digest("hex") !== hash) return { status: "mismatch" };
  33. const map = new TraceMap(JSON.parse(bytes.toString("utf8")), pathToFileURL(path).href);
  34. for (const source of map.resolvedSources) {
  35. if (source?.startsWith("file:")) {
  36. const file = fileURLToPath(source);
  37. if (!sources.has(file)) sources.set(file, new Set());
  38. }
  39. }
  40. eachMapping(map, (mapping) => {
  41. if (!mapping.source?.startsWith("file:") || mapping.originalLine === null) return;
  42. sources.get(fileURLToPath(mapping.source))?.add(mapping.originalLine);
  43. });
  44. }
  45. return {
  46. status: "matched",
  47. mapCount: maps.length,
  48. sources: Object.fromEntries(
  49. [...sources].map(([file, lines]) => [file, [...lines].sort((a, b) => a - b)]),
  50. ),
  51. };
  52. }