@chromatic-com/vitest 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/plugin.d.ts CHANGED
@@ -83,6 +83,12 @@ interface Options extends ChromaticConfig {
83
83
  */
84
84
  verbose?: boolean;
85
85
  };
86
+ /**
87
+ * Enables [TurboSnap](https://www.chromatic.com/docs/turbosnap/).
88
+ *
89
+ * @default false
90
+ */
91
+ turboSnap?: boolean;
86
92
  }
87
93
 
88
94
  /**
package/dist/plugin.js CHANGED
@@ -235,8 +235,8 @@ var require_srcset = __commonJS({
235
235
  });
236
236
 
237
237
  // src/node/plugin.ts
238
- import { rmSync } from "node:fs";
239
- import { resolve as resolve3 } from "node:path";
238
+ import { existsSync as existsSync4, readdirSync, rmSync } from "node:fs";
239
+ import { resolve as resolve4 } from "node:path";
240
240
  import colors2 from "tinyrainbow";
241
241
 
242
242
  // ../shared/src/utils/logger.ts
@@ -884,9 +884,9 @@ async function writeTestResult(e2eTestInfo, domSnapshots, archive, chromaticStor
884
884
  await outputFile(join(archiveDir, snapshotFile), mappedSnapshot);
885
885
  })
886
886
  );
887
- const storiesFile = storiesFileName(title, testRunner !== "vitest");
887
+ const storiesFile = join(finalOutputDir, storiesFileName(title, testRunner !== "vitest"));
888
888
  const storiesJson = createStories(title, domSnapshots, chromaticStorybookParams);
889
- await outputJSONFile(join(finalOutputDir, storiesFile), storiesJson);
889
+ await outputJSONFile(storiesFile, storiesJson);
890
890
  const errors = Object.entries(archive).filter(([, r]) => "error" in r);
891
891
  if (errors.length > 0) {
892
892
  logger.log(`Encountered ${errors.length} errors archiving resources, writing to 'errors.json'`);
@@ -894,6 +894,7 @@ async function writeTestResult(e2eTestInfo, domSnapshots, archive, chromaticStor
894
894
  errors: Object.fromEntries(errors)
895
895
  });
896
896
  }
897
+ return { storiesFile };
897
898
  }
898
899
 
899
900
  // ../shared/src/utils/analytics.ts
@@ -907,7 +908,7 @@ var DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS = 1e4;
907
908
 
908
909
  // src/node/commands.ts
909
910
  import assert from "node:assert";
910
- import { resolve as resolve2 } from "node:path";
911
+ import { resolve as resolve3 } from "node:path";
911
912
  import { storyNameFromExport as storyNameFromExport2, toId as toId2 } from "storybook/internal/csf";
912
913
 
913
914
  // src/node/NetworkIdleTracker.ts
@@ -945,12 +946,12 @@ var NetworkIdleTracker = class _NetworkIdleTracker {
945
946
  if (this.pending.size === 0 && this.idleTimer === null) {
946
947
  return Promise.resolve();
947
948
  }
948
- return new Promise((resolve4, reject) => {
949
+ return new Promise((resolve5, reject) => {
949
950
  const timeout = setTimeout(
950
951
  () => reject(new NetworkIdleTimeoutError("Timed out waiting for network to be idle")),
951
952
  rejectTimeout
952
953
  );
953
- this.idleResolvers.push(resolve4, () => clearTimeout(timeout));
954
+ this.idleResolvers.push(resolve5, () => clearTimeout(timeout));
954
955
  });
955
956
  }
956
957
  onComplete = (params) => {
@@ -1001,6 +1002,7 @@ var ChromaticReporter = class _ChromaticReporter {
1001
1002
  const options = {
1002
1003
  verbose: pluginOptions.reporter.verbose,
1003
1004
  outputDirectory: pluginOptions.outputDirectory,
1005
+ turboSnap: pluginOptions.turboSnap,
1004
1006
  builtInReporter: "default"
1005
1007
  };
1006
1008
  for (const reporter of ctx.config.reporters) {
@@ -1061,6 +1063,9 @@ var ChromaticReporter = class _ChromaticReporter {
1061
1063
  const output = resolve(this.ctx.config.root, this.options.outputDirectory);
1062
1064
  const separator = colors.dim("\u2500".repeat(this.ctx.logger.getColumns()));
1063
1065
  let uploadCommand = "chromatic --vitest --project-token=<TOKEN>";
1066
+ if (this.options.turboSnap) {
1067
+ uploadCommand += " --only-changed";
1068
+ }
1064
1069
  if (this.options.outputDirectory !== DEFAULT_OUTPUT_DIR || this.ctx.config.root !== process.cwd()) {
1065
1070
  uploadCommand = `CHROMATIC_ARCHIVE_LOCATION=${relative(process.cwd(), output)} ${uploadCommand}`;
1066
1071
  }
@@ -1105,6 +1110,233 @@ function pluralize(count, text) {
1105
1110
  return count === 1 ? text : `${text}s`;
1106
1111
  }
1107
1112
 
1113
+ // src/node/webpack-stats-reporter.ts
1114
+ import { existsSync as existsSync3, readFileSync } from "node:fs";
1115
+ import { mkdir, readdir, readFile, rm, writeFile as writeFile2 } from "node:fs/promises";
1116
+ import { dirname, relative as relative2, resolve as resolve2, sep } from "node:path";
1117
+ var REPORTER_NAME2 = "chromatic-webpack-stats-reporter";
1118
+ var VIRTUAL_MODULE_PREFIX = "\0";
1119
+ var WebpackStatsReporter = class _WebpackStatsReporter {
1120
+ constructor(ctx, options, moduleIdsToStoryFiles = /* @__PURE__ */ new Map()) {
1121
+ this.ctx = ctx;
1122
+ this.options = options;
1123
+ this.moduleIdsToStoryFiles = moduleIdsToStoryFiles;
1124
+ }
1125
+ name = REPORTER_NAME2;
1126
+ /**
1127
+ * Add `WebpackStatsReporter` to Vitest reporters unless it's already included.
1128
+ */
1129
+ static apply(ctx, pluginOptions) {
1130
+ const exists = ctx.config.reporters.some(isWebpackStatsReporter);
1131
+ if (!exists) {
1132
+ const filename = [
1133
+ "preview-stats",
1134
+ ctx.config.shard && `-${ctx.config.shard.index}-${ctx.config.shard.count}`,
1135
+ ".json"
1136
+ ].filter(Boolean).join("");
1137
+ const outputFile2 = resolve2(ctx.config.root, pluginOptions.outputDirectory, filename);
1138
+ ctx.config.reporters.push(new _WebpackStatsReporter(ctx, { outputFile: outputFile2 }));
1139
+ }
1140
+ }
1141
+ /**
1142
+ * Custom reporter life-cycle called when `*.stories.json` is written to file system.
1143
+ */
1144
+ static onStoryFileWrite(ctx, testCase, storyFilePath) {
1145
+ const reporter = ctx.config.reporters.find(isWebpackStatsReporter);
1146
+ reporter?._onStoryFileWrite(testCase, storyFilePath);
1147
+ }
1148
+ /**
1149
+ * Collect Story files written per each test module during test run
1150
+ */
1151
+ _onStoryFileWrite(testCase, storyFilePath) {
1152
+ const moduleId = testCase.module.moduleId;
1153
+ let entry = this.moduleIdsToStoryFiles.get(moduleId);
1154
+ if (!entry) {
1155
+ entry = /* @__PURE__ */ new Set();
1156
+ this.moduleIdsToStoryFiles.set(moduleId, entry);
1157
+ }
1158
+ entry.add(storyFilePath);
1159
+ }
1160
+ async onTestRunStart() {
1161
+ await rm(this.options.outputFile, { force: true });
1162
+ this.moduleIdsToStoryFiles.clear();
1163
+ }
1164
+ /**
1165
+ * Generate `preview-stats.json` from collected Story files and their dependent test modules
1166
+ */
1167
+ async onTestRunEnd(testModules) {
1168
+ const statsMap = /* @__PURE__ */ new Map();
1169
+ for (const testModule of testModules) {
1170
+ const storyFiles = this.moduleIdsToStoryFiles.get(testModule.moduleId);
1171
+ if (!storyFiles || storyFiles.size === 0) {
1172
+ continue;
1173
+ }
1174
+ const vite = testModule.project.browser?.vite;
1175
+ if (!vite) {
1176
+ continue;
1177
+ }
1178
+ const id = this.normalize(testModule.moduleId);
1179
+ statsMap.set(id, this.createStatsMapModule(id, [...storyFiles]));
1180
+ if (testModule.project.config.config) {
1181
+ const configId = this.normalize(testModule.project.config.config);
1182
+ const configEntry = statsMap.get(configId) || this.createStatsMapModule(configId, []);
1183
+ configEntry.reasons.push({ moduleName: id });
1184
+ statsMap.set(configId, configEntry);
1185
+ }
1186
+ this.addModule(testModule.moduleId, statsMap, vite.moduleGraph, vite.config.cacheDir);
1187
+ }
1188
+ if (!existsSync3(dirname(this.options.outputFile))) {
1189
+ await mkdir(dirname(this.options.outputFile), { recursive: true });
1190
+ }
1191
+ await writeFile2(
1192
+ this.options.outputFile,
1193
+ JSON.stringify({ modules: Array.from(statsMap.values()) }, null, 2),
1194
+ "utf-8"
1195
+ );
1196
+ }
1197
+ addModule(id, statsMap, moduleGraph, cacheDir, visited = /* @__PURE__ */ new Set()) {
1198
+ if (visited.has(id)) {
1199
+ return;
1200
+ }
1201
+ visited.add(id);
1202
+ const mod = moduleGraph.getModuleById(id);
1203
+ if (!mod) {
1204
+ return this.ctx.logger.error(
1205
+ `[chromatic] Could not find module for id ${id}. Excluding from TurboSnap.`
1206
+ );
1207
+ }
1208
+ const importedModules = [];
1209
+ for (const imported of mod.importedModules) {
1210
+ if (imported.id == null) {
1211
+ if (imported.file) {
1212
+ importedModules.push({ id: imported.file, isInModuleGraph: false });
1213
+ }
1214
+ continue;
1215
+ }
1216
+ const isOptimizedDependency = imported.id.startsWith(cacheDir);
1217
+ if (!isOptimizedDependency) {
1218
+ importedModules.push({ id: imported.id, isInModuleGraph: true });
1219
+ continue;
1220
+ }
1221
+ importedModules.push(...resolveOptimizedDependencySources(imported, cacheDir, visited));
1222
+ }
1223
+ for (const imported of importedModules) {
1224
+ if (imported.id.startsWith(VIRTUAL_MODULE_PREFIX)) {
1225
+ continue;
1226
+ }
1227
+ if (imported.isInModuleGraph) {
1228
+ this.addModule(imported.id, statsMap, moduleGraph, cacheDir, visited);
1229
+ }
1230
+ const depId = this.normalize(imported.id);
1231
+ const entry = statsMap.get(depId);
1232
+ if (!entry) {
1233
+ statsMap.set(depId, this.createStatsMapModule(depId, [mod.id]));
1234
+ continue;
1235
+ }
1236
+ const moduleName = this.normalize(mod.id);
1237
+ if (!entry.reasons.find((reason) => reason.moduleName === moduleName)) {
1238
+ entry.reasons.push({ moduleName });
1239
+ }
1240
+ }
1241
+ }
1242
+ createStatsMapModule(filename, importers) {
1243
+ return {
1244
+ id: filename,
1245
+ name: filename,
1246
+ reasons: importers.map((importer) => ({ moduleName: this.normalize(importer) }))
1247
+ };
1248
+ }
1249
+ normalize(filePath) {
1250
+ return relative2(this.ctx.config.root, filePath).replaceAll(sep, "/").split("?")[0];
1251
+ }
1252
+ };
1253
+ function isWebpackStatsReporter(reporter) {
1254
+ return "name" in reporter && reporter.name === REPORTER_NAME2;
1255
+ }
1256
+ function resolveOptimizedDependencySources(mod, cacheDir, visited) {
1257
+ if (visited.has(mod.id)) {
1258
+ return [];
1259
+ }
1260
+ visited.add(mod.id);
1261
+ const sources = getChunkSources(mod, cacheDir).map((id) => ({
1262
+ id,
1263
+ // These entries are not in module graph as they were bundled
1264
+ isInModuleGraph: false
1265
+ }));
1266
+ for (const imported of mod.importedModules) {
1267
+ if (imported.id == null) {
1268
+ if (imported.file) {
1269
+ sources.push({ id: imported.file, isInModuleGraph: false });
1270
+ }
1271
+ continue;
1272
+ }
1273
+ if (imported.id.startsWith(VIRTUAL_MODULE_PREFIX)) {
1274
+ continue;
1275
+ }
1276
+ if (imported.id.startsWith(cacheDir)) {
1277
+ sources.push(...resolveOptimizedDependencySources(imported, cacheDir, visited));
1278
+ } else {
1279
+ sources.push({ id: imported.id, isInModuleGraph: true });
1280
+ }
1281
+ }
1282
+ return sources;
1283
+ }
1284
+ function getChunkSources(mod, cacheDir) {
1285
+ const sources = resolveMapSources(mod, mod.transformResult?.map, cacheDir);
1286
+ if (sources.length) {
1287
+ return sources;
1288
+ }
1289
+ try {
1290
+ const diskMap = JSON.parse(readFileSync(`${mod.id.split("?")[0]}.map`, "utf-8"));
1291
+ return resolveMapSources(mod, diskMap, cacheDir);
1292
+ } catch {
1293
+ return [];
1294
+ }
1295
+ }
1296
+ function resolveMapSources(mod, map, cacheDir) {
1297
+ if (!map || typeof map !== "object" || !("sources" in map) || !Array.isArray(map.sources)) {
1298
+ return [];
1299
+ }
1300
+ return map.sources.flatMap((source) => {
1301
+ if (typeof source !== "string" || source.startsWith(VIRTUAL_MODULE_PREFIX)) {
1302
+ return [];
1303
+ }
1304
+ const resolved = resolve2(dirname(mod.id), source).replaceAll(sep, "/");
1305
+ if (resolved.startsWith(cacheDir)) {
1306
+ return [];
1307
+ }
1308
+ return [resolved];
1309
+ });
1310
+ }
1311
+ async function mergePreviewStats(options) {
1312
+ const outputDirectory = resolve2(options.root, options.outputDirectory);
1313
+ const merged = /* @__PURE__ */ new Map();
1314
+ for (const filename of await readdir(outputDirectory)) {
1315
+ if (filename.startsWith("preview-stats") && filename.endsWith(".json")) {
1316
+ const fullFilename = resolve2(outputDirectory, filename);
1317
+ const stats = JSON.parse(await readFile(fullFilename, "utf-8"));
1318
+ for (const mod of stats.modules) {
1319
+ const previous = merged.get(mod.id);
1320
+ if (previous) {
1321
+ for (const reason of mod.reasons) {
1322
+ if (!previous.reasons.some((r) => r.moduleName === reason.moduleName)) {
1323
+ previous.reasons.push(reason);
1324
+ }
1325
+ }
1326
+ } else {
1327
+ merged.set(mod.id, mod);
1328
+ }
1329
+ }
1330
+ await rm(fullFilename);
1331
+ }
1332
+ }
1333
+ await writeFile2(
1334
+ resolve2(outputDirectory, "preview-stats.json"),
1335
+ JSON.stringify({ modules: Array.from(merged.values()) }, null, 2),
1336
+ "utf-8"
1337
+ );
1338
+ }
1339
+
1108
1340
  // src/node/commands.ts
1109
1341
  function createCommands(options) {
1110
1342
  const resourceArchivers = /* @__PURE__ */ new Map();
@@ -1217,9 +1449,9 @@ function createCommands(options) {
1217
1449
  }
1218
1450
  };
1219
1451
  }
1220
- await writeTestResult(
1452
+ const { storiesFile } = await writeTestResult(
1221
1453
  {
1222
- outputDir: resolve2(context.project.vitest.config.root, options.outputDirectory),
1454
+ outputDir: resolve3(context.project.vitest.config.root, options.outputDirectory),
1223
1455
  pageUrl: context.page.url(),
1224
1456
  titlePath
1225
1457
  },
@@ -1237,6 +1469,9 @@ function createCommands(options) {
1237
1469
  },
1238
1470
  "vitest"
1239
1471
  );
1472
+ if (options.turboSnap) {
1473
+ WebpackStatsReporter.onStoryFileWrite(context.project.vitest, entity, storiesFile);
1474
+ }
1240
1475
  },
1241
1476
  /**
1242
1477
  * Clear test state without writing test results.
@@ -1341,11 +1576,12 @@ function chromaticPlugin(userOptions = {}) {
1341
1576
  outputDirectory: DEFAULT_OUTPUT_DIR,
1342
1577
  resourceArchiveTimeout: DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS,
1343
1578
  idleNetworkInterval: 100,
1579
+ turboSnap: false,
1344
1580
  ...userOptions,
1345
1581
  reporter: resolveReporterOptions(userOptions.reporter)
1346
1582
  };
1347
1583
  const isDist = import.meta.url.includes("dist/plugin.js");
1348
- const setupFile = resolve3(
1584
+ const setupFile = resolve4(
1349
1585
  import.meta.dirname,
1350
1586
  isDist ? "./setupFile.js" : "../browser/setupFile.ts"
1351
1587
  );
@@ -1363,16 +1599,20 @@ function chromaticPlugin(userOptions = {}) {
1363
1599
  }
1364
1600
  };
1365
1601
  },
1366
- configureVitest(context) {
1602
+ async configureVitest(context) {
1367
1603
  const project = context.project;
1368
1604
  const browser = project.config.browser;
1369
1605
  const sequence = context.vitest.config.sequence;
1606
+ const isMergeReports = project.globalConfig.mergeReports;
1370
1607
  if (!browser.enabled || browser.name !== "chromium") {
1371
1608
  return clean();
1372
1609
  }
1373
1610
  if (options.reporter.enabled) {
1374
1611
  ChromaticReporter.apply(context.vitest, options);
1375
1612
  }
1613
+ if (options.turboSnap && !isMergeReports) {
1614
+ WebpackStatsReporter.apply(context.vitest, options);
1615
+ }
1376
1616
  if (sequence.hooks === "stack") {
1377
1617
  project.config.setupFiles.push(setupFile);
1378
1618
  } else if (sequence.hooks === "list") {
@@ -1403,7 +1643,14 @@ function chromaticPlugin(userOptions = {}) {
1403
1643
  }
1404
1644
  }
1405
1645
  }
1406
- if (!project.globalConfig.mergeReports) {
1646
+ if (isMergeReports) {
1647
+ if (options.turboSnap) {
1648
+ await mergePreviewStats({
1649
+ root: project.vitest.config.root,
1650
+ outputDirectory: options.outputDirectory
1651
+ });
1652
+ }
1653
+ } else {
1407
1654
  clean();
1408
1655
  }
1409
1656
  project.onTestsRerun(async () => {
@@ -1411,10 +1658,15 @@ function chromaticPlugin(userOptions = {}) {
1411
1658
  await project.browser?.triggerCommand("__chromatic_reset", {});
1412
1659
  });
1413
1660
  function clean() {
1414
- rmSync(resolve3(project.vitest.config.root, options.outputDirectory, "chromatic-archives"), {
1415
- recursive: true,
1416
- force: true
1417
- });
1661
+ const outputDirectory = resolve4(project.vitest.config.root, options.outputDirectory);
1662
+ rmSync(resolve4(outputDirectory, "chromatic-archives"), { recursive: true, force: true });
1663
+ if (existsSync4(outputDirectory)) {
1664
+ for (const file of readdirSync(outputDirectory)) {
1665
+ if (file.startsWith("preview-stats") && file.endsWith(".json")) {
1666
+ rmSync(resolve4(outputDirectory, file), { force: true });
1667
+ }
1668
+ }
1669
+ }
1418
1670
  }
1419
1671
  }
1420
1672
  };
@@ -1,6 +1,7 @@
1
1
  // src/storybook-config/main.ts
2
2
  import path3 from "node:path";
3
3
  import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { existsSync, readFileSync } from "node:fs";
4
5
 
5
6
  // ../shared/src/utils/filePaths.ts
6
7
  import path from "path";
@@ -54,6 +55,7 @@ var main_default = {
54
55
  },
55
56
  webpackFinal: async (config) => {
56
57
  config.target = ["web"];
58
+ config.plugins.push(new VitestStatsPlugin());
57
59
  const storybookNodeModules = storybookParentNodeModulesDir(import.meta.url);
58
60
  if (storybookNodeModules) {
59
61
  config.resolve ??= {};
@@ -65,6 +67,22 @@ var main_default = {
65
67
  return config;
66
68
  }
67
69
  };
70
+ var VitestStatsPlugin = class {
71
+ apply(compiler) {
72
+ const chromaticResults = path3.dirname(archivesDir(DEFAULT_OUTPUT_DIR));
73
+ const previewStats = path3.resolve(chromaticResults, "preview-stats.json");
74
+ if (existsSync(previewStats)) {
75
+ compiler.hooks.done.tap("Vitest Stats Plugin", (stats) => {
76
+ const { modules } = JSON.parse(readFileSync(previewStats, "utf-8"));
77
+ const toJson = stats.toJson.bind(stats);
78
+ stats.toJson = (...args) => {
79
+ const json = toJson(...args);
80
+ return { ...json, modules: [...json.modules || [], ...modules] };
81
+ };
82
+ });
83
+ }
84
+ }
85
+ };
68
86
  export {
69
87
  main_default as default
70
88
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chromatic-com/vitest",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Chromatic Visual Regression Testing for Vitest",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,6 +42,7 @@
42
42
  "@storybook/server": "10.2.13",
43
43
  "@storybook/server-webpack5": "10.2.13",
44
44
  "@vitest/browser-playwright": "^4.1.0",
45
+ "extend-to-be-announced": "2.0.0",
45
46
  "msw": "^2.12.10",
46
47
  "rimraf": "^3.0.2",
47
48
  "tsup": "^7.3.0",