@chromatic-com/vitest 0.1.6 → 0.1.7

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
@@ -236,7 +236,7 @@ var require_srcset = __commonJS({
236
236
 
237
237
  // src/node/plugin.ts
238
238
  import { rmSync } from "node:fs";
239
- import { resolve as resolve3 } from "node:path";
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,204 @@ 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, 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 outputFile2 = resolve2(
1133
+ ctx.config.root,
1134
+ pluginOptions.outputDirectory,
1135
+ "preview-stats.json"
1136
+ );
1137
+ ctx.config.reporters.push(new _WebpackStatsReporter(ctx, { outputFile: outputFile2 }));
1138
+ }
1139
+ }
1140
+ /**
1141
+ * Custom reporter life-cycle called when `*.stories.json` is written to file system.
1142
+ */
1143
+ static onStoryFileWrite(ctx, testCase, storyFilePath) {
1144
+ const reporter = ctx.config.reporters.find(isWebpackStatsReporter);
1145
+ reporter?._onStoryFileWrite(testCase, storyFilePath);
1146
+ }
1147
+ /**
1148
+ * Collect Story files written per each test module during test run
1149
+ */
1150
+ _onStoryFileWrite(testCase, storyFilePath) {
1151
+ const moduleId = testCase.module.moduleId;
1152
+ let entry = this.moduleIdsToStoryFiles.get(moduleId);
1153
+ if (!entry) {
1154
+ entry = /* @__PURE__ */ new Set();
1155
+ this.moduleIdsToStoryFiles.set(moduleId, entry);
1156
+ }
1157
+ entry.add(storyFilePath);
1158
+ }
1159
+ async onTestRunStart() {
1160
+ await rm(this.options.outputFile, { force: true });
1161
+ this.moduleIdsToStoryFiles.clear();
1162
+ }
1163
+ /**
1164
+ * Generate `preview-stats.json` from collected Story files and their dependent test modules
1165
+ */
1166
+ async onTestRunEnd(testModules) {
1167
+ const statsMap = /* @__PURE__ */ new Map();
1168
+ for (const testModule of testModules) {
1169
+ const storyFiles = this.moduleIdsToStoryFiles.get(testModule.moduleId);
1170
+ if (!storyFiles || storyFiles.size === 0) {
1171
+ continue;
1172
+ }
1173
+ const vite = testModule.project.browser?.vite;
1174
+ if (!vite) {
1175
+ continue;
1176
+ }
1177
+ const id = this.normalize(testModule.moduleId);
1178
+ statsMap.set(id, this.createStatsMapModule(id, [...storyFiles]));
1179
+ if (testModule.project.config.config) {
1180
+ const configId = this.normalize(testModule.project.config.config);
1181
+ const configEntry = statsMap.get(configId) || this.createStatsMapModule(configId, []);
1182
+ configEntry.reasons.push({ moduleName: id });
1183
+ statsMap.set(configId, configEntry);
1184
+ }
1185
+ this.addModule(testModule.moduleId, statsMap, vite.moduleGraph, vite.config.cacheDir);
1186
+ }
1187
+ if (!existsSync3(dirname(this.options.outputFile))) {
1188
+ await mkdir(dirname(this.options.outputFile), { recursive: true });
1189
+ }
1190
+ await writeFile2(
1191
+ this.options.outputFile,
1192
+ JSON.stringify({ modules: Array.from(statsMap.values()) }, null, 2),
1193
+ "utf-8"
1194
+ );
1195
+ }
1196
+ addModule(id, statsMap, moduleGraph, cacheDir, visited = /* @__PURE__ */ new Set()) {
1197
+ if (visited.has(id)) {
1198
+ return;
1199
+ }
1200
+ visited.add(id);
1201
+ const mod = moduleGraph.getModuleById(id);
1202
+ if (!mod) {
1203
+ return this.ctx.logger.error(
1204
+ `[chromatic] Could not find module for id ${id}. Excluding from TurboSnap.`
1205
+ );
1206
+ }
1207
+ const importedModules = [];
1208
+ for (const imported of mod.importedModules) {
1209
+ if (imported.id == null) {
1210
+ if (imported.file) {
1211
+ importedModules.push({ id: imported.file, isInModuleGraph: false });
1212
+ }
1213
+ continue;
1214
+ }
1215
+ const isOptimizedDependency = imported.id.startsWith(cacheDir);
1216
+ if (!isOptimizedDependency) {
1217
+ importedModules.push({ id: imported.id, isInModuleGraph: true });
1218
+ continue;
1219
+ }
1220
+ importedModules.push(...resolveOptimizedDependencySources(imported, cacheDir, visited));
1221
+ }
1222
+ for (const imported of importedModules) {
1223
+ if (imported.id.startsWith(VIRTUAL_MODULE_PREFIX)) {
1224
+ continue;
1225
+ }
1226
+ if (imported.isInModuleGraph) {
1227
+ this.addModule(imported.id, statsMap, moduleGraph, cacheDir, visited);
1228
+ }
1229
+ const depId = this.normalize(imported.id);
1230
+ const entry = statsMap.get(depId);
1231
+ if (!entry) {
1232
+ statsMap.set(depId, this.createStatsMapModule(depId, [mod.id]));
1233
+ continue;
1234
+ }
1235
+ const moduleName = this.normalize(mod.id);
1236
+ if (!entry.reasons.find((reason) => reason.moduleName === moduleName)) {
1237
+ entry.reasons.push({ moduleName });
1238
+ }
1239
+ }
1240
+ }
1241
+ createStatsMapModule(filename, importers) {
1242
+ return {
1243
+ id: filename,
1244
+ name: filename,
1245
+ reasons: importers.map((importer) => ({ moduleName: this.normalize(importer) }))
1246
+ };
1247
+ }
1248
+ normalize(filePath) {
1249
+ return relative2(this.ctx.config.root, filePath).replaceAll(sep, "/").split("?")[0];
1250
+ }
1251
+ };
1252
+ function isWebpackStatsReporter(reporter) {
1253
+ return "name" in reporter && reporter.name === REPORTER_NAME2;
1254
+ }
1255
+ function resolveOptimizedDependencySources(mod, cacheDir, visited) {
1256
+ if (visited.has(mod.id)) {
1257
+ return [];
1258
+ }
1259
+ visited.add(mod.id);
1260
+ const sources = getChunkSources(mod, cacheDir).map((id) => ({
1261
+ id,
1262
+ // These entries are not in module graph as they were bundled
1263
+ isInModuleGraph: false
1264
+ }));
1265
+ for (const imported of mod.importedModules) {
1266
+ if (imported.id == null) {
1267
+ if (imported.file) {
1268
+ sources.push({ id: imported.file, isInModuleGraph: false });
1269
+ }
1270
+ continue;
1271
+ }
1272
+ if (imported.id.startsWith(VIRTUAL_MODULE_PREFIX)) {
1273
+ continue;
1274
+ }
1275
+ if (imported.id.startsWith(cacheDir)) {
1276
+ sources.push(...resolveOptimizedDependencySources(imported, cacheDir, visited));
1277
+ } else {
1278
+ sources.push({ id: imported.id, isInModuleGraph: true });
1279
+ }
1280
+ }
1281
+ return sources;
1282
+ }
1283
+ function getChunkSources(mod, cacheDir) {
1284
+ const sources = resolveMapSources(mod, mod.transformResult?.map, cacheDir);
1285
+ if (sources.length) {
1286
+ return sources;
1287
+ }
1288
+ try {
1289
+ const diskMap = JSON.parse(readFileSync(`${mod.id.split("?")[0]}.map`, "utf-8"));
1290
+ return resolveMapSources(mod, diskMap, cacheDir);
1291
+ } catch {
1292
+ return [];
1293
+ }
1294
+ }
1295
+ function resolveMapSources(mod, map, cacheDir) {
1296
+ if (!map || typeof map !== "object" || !("sources" in map) || !Array.isArray(map.sources)) {
1297
+ return [];
1298
+ }
1299
+ return map.sources.flatMap((source) => {
1300
+ if (typeof source !== "string" || source.startsWith(VIRTUAL_MODULE_PREFIX)) {
1301
+ return [];
1302
+ }
1303
+ const resolved = resolve2(dirname(mod.id), source).replaceAll(sep, "/");
1304
+ if (resolved.startsWith(cacheDir)) {
1305
+ return [];
1306
+ }
1307
+ return [resolved];
1308
+ });
1309
+ }
1310
+
1108
1311
  // src/node/commands.ts
1109
1312
  function createCommands(options) {
1110
1313
  const resourceArchivers = /* @__PURE__ */ new Map();
@@ -1217,9 +1420,9 @@ function createCommands(options) {
1217
1420
  }
1218
1421
  };
1219
1422
  }
1220
- await writeTestResult(
1423
+ const { storiesFile } = await writeTestResult(
1221
1424
  {
1222
- outputDir: resolve2(context.project.vitest.config.root, options.outputDirectory),
1425
+ outputDir: resolve3(context.project.vitest.config.root, options.outputDirectory),
1223
1426
  pageUrl: context.page.url(),
1224
1427
  titlePath
1225
1428
  },
@@ -1237,6 +1440,9 @@ function createCommands(options) {
1237
1440
  },
1238
1441
  "vitest"
1239
1442
  );
1443
+ if (options.turboSnap) {
1444
+ WebpackStatsReporter.onStoryFileWrite(context.project.vitest, entity, storiesFile);
1445
+ }
1240
1446
  },
1241
1447
  /**
1242
1448
  * Clear test state without writing test results.
@@ -1341,11 +1547,12 @@ function chromaticPlugin(userOptions = {}) {
1341
1547
  outputDirectory: DEFAULT_OUTPUT_DIR,
1342
1548
  resourceArchiveTimeout: DEFAULT_GLOBAL_RESOURCE_ARCHIVE_TIMEOUT_MS,
1343
1549
  idleNetworkInterval: 100,
1550
+ turboSnap: false,
1344
1551
  ...userOptions,
1345
1552
  reporter: resolveReporterOptions(userOptions.reporter)
1346
1553
  };
1347
1554
  const isDist = import.meta.url.includes("dist/plugin.js");
1348
- const setupFile = resolve3(
1555
+ const setupFile = resolve4(
1349
1556
  import.meta.dirname,
1350
1557
  isDist ? "./setupFile.js" : "../browser/setupFile.ts"
1351
1558
  );
@@ -1373,6 +1580,9 @@ function chromaticPlugin(userOptions = {}) {
1373
1580
  if (options.reporter.enabled) {
1374
1581
  ChromaticReporter.apply(context.vitest, options);
1375
1582
  }
1583
+ if (options.turboSnap) {
1584
+ WebpackStatsReporter.apply(context.vitest, options);
1585
+ }
1376
1586
  if (sequence.hooks === "stack") {
1377
1587
  project.config.setupFiles.push(setupFile);
1378
1588
  } else if (sequence.hooks === "list") {
@@ -1411,10 +1621,10 @@ function chromaticPlugin(userOptions = {}) {
1411
1621
  await project.browser?.triggerCommand("__chromatic_reset", {});
1412
1622
  });
1413
1623
  function clean() {
1414
- rmSync(resolve3(project.vitest.config.root, options.outputDirectory, "chromatic-archives"), {
1415
- recursive: true,
1416
- force: true
1417
- });
1624
+ const outputDirectory = resolve4(project.vitest.config.root, options.outputDirectory);
1625
+ for (const output of ["chromatic-archives", "preview-stats.json"]) {
1626
+ rmSync(resolve4(outputDirectory, output), { recursive: true, force: true });
1627
+ }
1418
1628
  }
1419
1629
  }
1420
1630
  };
@@ -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.7",
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",