@chromatic-com/vitest 1.0.1 → 1.0.2

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.
@@ -0,0 +1,55 @@
1
+ import { r as checkArchivesDirExists } from "./constants-Dos4OOMt.mjs";
2
+ import { createRequire } from "node:module";
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname, resolve } from "node:path";
5
+ import { spawn } from "node:child_process";
6
+
7
+ //#region ../shared/src/archive-storybook/index.ts
8
+ const req = createRequire(import.meta.url);
9
+ async function archiveStorybook(processArgs, configDir, defaultOutputDir, callbacks) {
10
+ assertOutputDirectory(defaultOutputDir, callbacks);
11
+ await runBin([
12
+ binPath(),
13
+ "dev",
14
+ ...processArgs,
15
+ "-c",
16
+ configDir
17
+ ]);
18
+ }
19
+ async function buildArchiveStorybook(processArgs, configDir, defaultOutputDir, callbacks) {
20
+ assertOutputDirectory(defaultOutputDir, callbacks);
21
+ await runBin([
22
+ binPath(),
23
+ "build",
24
+ ...processArgs,
25
+ "-c",
26
+ configDir
27
+ ]);
28
+ }
29
+ function assertOutputDirectory(outputDirectory, callbacks) {
30
+ try {
31
+ checkArchivesDirExists(outputDirectory);
32
+ } catch (error) {
33
+ callbacks?.onArchivesCheck(error);
34
+ throw error;
35
+ }
36
+ callbacks?.onArchivesCheck();
37
+ }
38
+ function runBin(args) {
39
+ return new Promise((resolvePromise, reject) => {
40
+ const child = spawn("node", args, { stdio: "inherit" });
41
+ child.on("error", reject);
42
+ child.on("close", (code, signal) => {
43
+ if (code === 0 || signal === "SIGINT" || signal === "SIGTERM") resolvePromise();
44
+ else reject(Object.assign(/* @__PURE__ */ new Error(`Storybook exited with ${signal ?? `code ${code}`}`), { status: code }));
45
+ });
46
+ });
47
+ }
48
+ function binPath() {
49
+ const filename = req.resolve("storybook/package.json");
50
+ const packageJson = JSON.parse(readFileSync(filename, "utf8"));
51
+ return resolve(dirname(filename), packageJson.bin);
52
+ }
53
+
54
+ //#endregion
55
+ export { buildArchiveStorybook as n, archiveStorybook as t };
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ import { n as archivesDir, t as DEFAULT_OUTPUT_DIR } from "../constants-Dos4OOMt.mjs";
3
+ import { a as flushTelemetry, n as trackCliEvent } from "../telemetry-DOABfuU5.mjs";
4
+ import { t as archiveStorybook } from "../archive-storybook-Bqn7D3Ez.mjs";
5
+ import path from "node:path";
6
+
7
+ //#region src/bin/archive-storybook.ts
8
+ const args = process.argv.slice(2);
9
+ const configDir = path.resolve(import.meta.dirname, "../storybook-config");
10
+ let queue = Promise.resolve();
11
+ try {
12
+ trackEvent({
13
+ eventType: "storybook_dev_started",
14
+ level: "info",
15
+ payload: {}
16
+ });
17
+ await archiveStorybook(args, configDir, DEFAULT_OUTPUT_DIR, { onArchivesCheck });
18
+ } catch (err) {
19
+ trackEvent({
20
+ eventType: "storybook_dev_failed",
21
+ level: "error",
22
+ payload: { error: err }
23
+ });
24
+ console.error(err.message);
25
+ process.exitCode = 1;
26
+ }
27
+ await queue;
28
+ await flushTelemetry().catch(() => {});
29
+ function trackEvent(event) {
30
+ queue = queue.then(() => trackCliEvent(event, { outputDirectory: path.dirname(archivesDir(DEFAULT_OUTPUT_DIR)) }).catch(() => {}));
31
+ }
32
+ function onArchivesCheck(error) {
33
+ trackEvent({
34
+ eventType: "archives_resolved",
35
+ level: error ? "error" : "info",
36
+ payload: {
37
+ success: error == void 0,
38
+ error,
39
+ isCustomLocation: process.env.CHROMATIC_ARCHIVE_LOCATION != void 0,
40
+ command: "archiveStorybook",
41
+ chromaticProjectId: void 0
42
+ }
43
+ });
44
+ }
45
+
46
+ //#endregion
47
+ export { };
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ import { n as archivesDir, t as DEFAULT_OUTPUT_DIR } from "../constants-Dos4OOMt.mjs";
3
+ import { a as flushTelemetry, n as trackCliEvent } from "../telemetry-DOABfuU5.mjs";
4
+ import { n as buildArchiveStorybook } from "../archive-storybook-Bqn7D3Ez.mjs";
5
+ import path from "node:path";
6
+
7
+ //#region src/bin/build-archive-storybook.ts
8
+ const args = process.argv.slice(2);
9
+ const configDir = path.resolve(import.meta.dirname, "../storybook-config");
10
+ const isCalledFromCLI = process.env.STORYBOOK_INVOKED_BY === "chromatic";
11
+ const chromaticProjectId = process.env.CHROMATIC_PROJECT_ID || "unknown";
12
+ let queue = Promise.resolve();
13
+ try {
14
+ trackEvent({
15
+ eventType: "storybook_build_started",
16
+ level: "info",
17
+ payload: {
18
+ isCalledFromCLI,
19
+ chromaticProjectId
20
+ }
21
+ });
22
+ await buildArchiveStorybook(args, configDir, DEFAULT_OUTPUT_DIR, { onArchivesCheck });
23
+ trackEvent({
24
+ eventType: "storybook_build_completed",
25
+ level: "info",
26
+ payload: {
27
+ success: true,
28
+ error: void 0,
29
+ chromaticProjectId
30
+ }
31
+ });
32
+ } catch (err) {
33
+ trackEvent({
34
+ eventType: "storybook_build_completed",
35
+ level: "error",
36
+ payload: {
37
+ success: false,
38
+ error: err,
39
+ chromaticProjectId
40
+ }
41
+ });
42
+ console.error(err.message);
43
+ process.exitCode = 1;
44
+ }
45
+ await queue;
46
+ await flushTelemetry().catch(() => {});
47
+ function trackEvent(event) {
48
+ queue = queue.then(() => trackCliEvent(event, { outputDirectory: path.dirname(archivesDir(DEFAULT_OUTPUT_DIR)) }).catch(() => {}));
49
+ }
50
+ function onArchivesCheck(error) {
51
+ trackEvent({
52
+ eventType: "archives_resolved",
53
+ level: error ? "error" : "info",
54
+ payload: {
55
+ success: error == void 0,
56
+ error,
57
+ isCustomLocation: process.env.CHROMATIC_ARCHIVE_LOCATION != void 0,
58
+ command: "buildArchiveStorybook",
59
+ chromaticProjectId
60
+ }
61
+ });
62
+ }
63
+
64
+ //#endregion
65
+ export { };
@@ -0,0 +1,68 @@
1
+ import { existsSync, mkdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { writeFile } from "node:fs/promises";
5
+
6
+ //#region ../shared/src/utils/filePaths.ts
7
+ function rootDir() {
8
+ return process.cwd();
9
+ }
10
+ function outputDirOverride() {
11
+ const { CHROMATIC_ARCHIVE_LOCATION } = process.env;
12
+ return CHROMATIC_ARCHIVE_LOCATION;
13
+ }
14
+ function archivesDir(defaultOutputDir) {
15
+ const outputDir = outputDirOverride() || defaultOutputDir;
16
+ return path.resolve(rootDir(), outputDir, "chromatic-archives");
17
+ }
18
+ function checkArchivesDirExists(defaultOutputDir) {
19
+ const dir = archivesDir(defaultOutputDir);
20
+ if (!existsSync(dir)) throw new Error(`Chromatic archives directory cannot be found: ${dir}\n\nPlease make sure that you have run your E2E tests, or have set the CHROMATIC_ARCHIVE_LOCATION env var if the output directory for the tests is not in the standard location.`);
21
+ }
22
+ function ensureDir(directory) {
23
+ if (!existsSync(directory)) mkdirSync(directory, { recursive: true });
24
+ }
25
+ async function outputFile(filePath, data) {
26
+ ensureDir(path.dirname(filePath));
27
+ return writeFile(filePath, data, { mode: 511 });
28
+ }
29
+ async function outputJSONFile(filePath, data) {
30
+ return outputFile(filePath, JSON.stringify(data));
31
+ }
32
+ function hash(data) {
33
+ return createHash("shake256", { outputLength: 2 }).update(data).digest("hex");
34
+ }
35
+ const MAX_FILE_NAME_BYTE_LENGTH = 255;
36
+ function truncateFileName(filePath, maxByteLength = 255) {
37
+ const encoder = new TextEncoder();
38
+ const decoder = new TextDecoder();
39
+ const filePathParts = filePath.split("/");
40
+ const fileName = filePathParts.pop();
41
+ if (encoder.encode(fileName).byteLength <= maxByteLength) return filePath;
42
+ const hashedFileName = hash(fileName);
43
+ const [baseName, ...extensions] = fileName.split(".");
44
+ const baseNameByteArray = encoder.encode(baseName);
45
+ const ext = extensions.join(".");
46
+ const extLength = ext.length === 0 ? 0 : encoder.encode(ext).byteLength + 1;
47
+ const lengthHashAndExt = encoder.encode(hashedFileName).byteLength + extLength;
48
+ const truncatedBaseNameByteArray = baseNameByteArray.slice(0, maxByteLength - lengthHashAndExt);
49
+ const truncatedFileName = [`${decoder.decode(truncatedBaseNameByteArray)}${hashedFileName}`, ext].filter(Boolean).join(".");
50
+ return [...filePathParts, truncatedFileName].join("/");
51
+ }
52
+ const removeLocalhostFromBaseUrl = (href) => {
53
+ let baseUrl;
54
+ try {
55
+ baseUrl = new URL(href);
56
+ if (baseUrl.hostname === "localhost") return baseUrl.pathname + baseUrl.search + baseUrl.hash;
57
+ return href;
58
+ } catch {
59
+ return href;
60
+ }
61
+ };
62
+
63
+ //#endregion
64
+ //#region src/constants.ts
65
+ const DEFAULT_OUTPUT_DIR = ".vitest/chromatic";
66
+
67
+ //#endregion
68
+ export { outputFile as a, truncateFileName as c, ensureDir as i, archivesDir as n, outputJSONFile as o, checkArchivesDirExists as r, removeLocalhostFromBaseUrl as s, DEFAULT_OUTPUT_DIR as t };
@@ -1,55 +1,60 @@
1
+ //#region src/browser/public/takeSnapshot.d.ts
1
2
  /**
2
3
  * Take visual regression snapshot of the current state of the DOM.
3
4
  */
4
5
  declare function takeSnapshot(name?: string): Promise<void>;
5
-
6
+ //#endregion
7
+ //#region ../../node_modules/.pnpm/@rrweb+types@2.1.0/node_modules/@rrweb/types/dist/index.d.ts
6
8
  declare global {
7
- interface Window {
8
- FontFace: typeof FontFace;
9
- }
9
+ interface Window {
10
+ FontFace: typeof FontFace;
11
+ }
10
12
  }
11
-
13
+ //#endregion
14
+ //#region ../shared/src/types.d.ts
12
15
  interface ChromaticConfig {
13
- /** https://www.chromatic.com/docs/delay/ */
14
- delay?: number;
15
- /** https://www.chromatic.com/docs/threshold/#anti-aliasing */
16
- diffIncludeAntiAliasing?: boolean;
17
- /** https://www.chromatic.com/docs/threshold/#setting-the-threshold */
18
- diffThreshold?: number;
19
- /** Disable the capture that happens automatically at the end of a test when using the Chromatic test fixture */
20
- disableAutoSnapshot?: boolean;
21
- /** https://www.chromatic.com/docs/media-features/#test-high-contrast-color-schemes */
22
- forcedColors?: string;
23
- /** https://www.chromatic.com/docs/animations/#css-animations */
24
- pauseAnimationAtEnd?: boolean;
25
- /** https://www.chromatic.com/docs/media-features/#verify-reduced-motion-animations */
26
- prefersReducedMotion?: string;
27
- /**
28
- * Specify a network timeout, in milliseconds. This is the maximum amount of time that
29
- * each test will wait for the network to be idle while archiving resources.
30
- */
31
- resourceArchiveTimeout?: number;
32
- /**
33
- * Domains (besides where the test is being run from) that assets should be archived from
34
- * (needed when, for example, CI environment can't access the archives later on)
35
- * ex: www.some-domain.com
36
- */
37
- assetDomains?: string[];
38
- /** Crop snapshots to the viewport size. */
39
- cropToViewport?: boolean;
40
- /** CSS selectors of elements to ignore when comparing snapshots. */
41
- ignoreSelectors?: string[];
16
+ /** https://www.chromatic.com/docs/delay/ */
17
+ delay?: number;
18
+ /** https://www.chromatic.com/docs/threshold/#anti-aliasing */
19
+ diffIncludeAntiAliasing?: boolean;
20
+ /** https://www.chromatic.com/docs/threshold/#setting-the-threshold */
21
+ diffThreshold?: number;
22
+ /** Disable the capture that happens automatically at the end of a test when using the Chromatic test fixture */
23
+ disableAutoSnapshot?: boolean;
24
+ /** https://www.chromatic.com/docs/media-features/#test-high-contrast-color-schemes */
25
+ forcedColors?: string;
26
+ /** https://www.chromatic.com/docs/animations/#css-animations */
27
+ pauseAnimationAtEnd?: boolean;
28
+ /** https://www.chromatic.com/docs/media-features/#verify-reduced-motion-animations */
29
+ prefersReducedMotion?: string;
30
+ /**
31
+ * Specify a network timeout, in milliseconds. This is the maximum amount of time that
32
+ * each test will wait for the network to be idle while archiving resources.
33
+ */
34
+ resourceArchiveTimeout?: number;
35
+ /**
36
+ * Domains (besides where the test is being run from) that assets should be archived from
37
+ * (needed when, for example, CI environment can't access the archives later on)
38
+ * ex: www.some-domain.com
39
+ */
40
+ assetDomains?: string[];
41
+ /** Crop snapshots to the viewport size. */
42
+ cropToViewport?: boolean;
43
+ /** CSS selectors of elements to ignore when comparing snapshots. */
44
+ ignoreSelectors?: string[];
42
45
  }
43
-
46
+ //#endregion
47
+ //#region src/types.d.ts
44
48
  /**
45
49
  * Options that can be set per test, suite or module via `configure()`
46
50
  * - `assetDomains` is excluded as it can only be configured globally on the plugin
47
51
  */
48
52
  type ConfigureOptions = {
49
- /** Custom title to be shown in Chromatic. Default is derived from test file name. */
50
- title?: string;
51
- } & Omit<ChromaticConfig, 'assetDomains'>;
52
-
53
+ /** Custom title to be shown in Chromatic. Default is derived from test file name. */
54
+ title?: string;
55
+ } & Omit<ChromaticConfig, "assetDomains">;
56
+ //#endregion
57
+ //#region src/browser/public/configure.d.ts
53
58
  /**
54
59
  * Configure options for the current scope.
55
60
  *
@@ -110,7 +115,8 @@ type ConfigureOptions = {
110
115
  * ```
111
116
  */
112
117
  declare function configure(options: ConfigureOptions): void;
113
-
118
+ //#endregion
119
+ //#region src/browser/public/waitForIdleNetwork.d.ts
114
120
  /**
115
121
  * Wait for network to be idle, meaning no new network requests for at least `idleNetworkInterval` ms.
116
122
  *
@@ -125,5 +131,5 @@ declare function configure(options: ConfigureOptions): void;
125
131
  * Use `timeout` argument to reject if network doesn't become idle within given time.
126
132
  */
127
133
  declare function waitForIdleNetwork(timeout: number): Promise<void>;
128
-
129
- export { configure, takeSnapshot, waitForIdleNetwork };
134
+ //#endregion
135
+ export { configure, takeSnapshot, waitForIdleNetwork };
package/dist/index.mjs ADDED
@@ -0,0 +1,44 @@
1
+ import { a as getCurrentSuite, i as isChromium, n as takeSnapshot, o as getCurrentTest, r as trackEvent, t as waitForIdleNetwork } from "./waitForIdleNetwork-CEON19Zg.mjs";
2
+ import { beforeAll } from "vitest";
3
+
4
+ //#region src/browser/public/configure.ts
5
+ function configure(options) {
6
+ if (!isChromium()) return;
7
+ const test = getCurrentTest();
8
+ if (test) {
9
+ test.meta.__chromatic_options = {
10
+ ...test.meta.__chromatic_options,
11
+ ...options
12
+ };
13
+ return trackConfigure("test");
14
+ }
15
+ const scope = getCurrentSuite()?.suite ? "suite" : "file";
16
+ beforeAll(({}, suite) => {
17
+ trackConfigure(scope);
18
+ traverseTests(suite);
19
+ function traverseTests(task) {
20
+ if (task.type === "test") {
21
+ const test = task;
22
+ test.meta.__chromatic_options = {
23
+ ...test.meta.__chromatic_options,
24
+ ...options
25
+ };
26
+ return;
27
+ }
28
+ task.tasks.forEach(traverseTests);
29
+ }
30
+ });
31
+ function trackConfigure(scope) {
32
+ trackEvent({
33
+ eventType: "configure_called",
34
+ level: "info",
35
+ payload: {
36
+ options: Object.keys(options),
37
+ scope
38
+ }
39
+ });
40
+ }
41
+ }
42
+
43
+ //#endregion
44
+ export { configure, takeSnapshot, waitForIdleNetwork };
@@ -0,0 +1,102 @@
1
+ import { Vite } from "vitest/node";
2
+ //#region ../../node_modules/.pnpm/@rrweb+types@2.1.0/node_modules/@rrweb/types/dist/index.d.ts
3
+ declare global {
4
+ interface Window {
5
+ FontFace: typeof FontFace;
6
+ }
7
+ }
8
+ //#endregion
9
+ //#region ../shared/src/types.d.ts
10
+ interface ChromaticConfig {
11
+ /** https://www.chromatic.com/docs/delay/ */
12
+ delay?: number;
13
+ /** https://www.chromatic.com/docs/threshold/#anti-aliasing */
14
+ diffIncludeAntiAliasing?: boolean;
15
+ /** https://www.chromatic.com/docs/threshold/#setting-the-threshold */
16
+ diffThreshold?: number;
17
+ /** Disable the capture that happens automatically at the end of a test when using the Chromatic test fixture */
18
+ disableAutoSnapshot?: boolean;
19
+ /** https://www.chromatic.com/docs/media-features/#test-high-contrast-color-schemes */
20
+ forcedColors?: string;
21
+ /** https://www.chromatic.com/docs/animations/#css-animations */
22
+ pauseAnimationAtEnd?: boolean;
23
+ /** https://www.chromatic.com/docs/media-features/#verify-reduced-motion-animations */
24
+ prefersReducedMotion?: string;
25
+ /**
26
+ * Specify a network timeout, in milliseconds. This is the maximum amount of time that
27
+ * each test will wait for the network to be idle while archiving resources.
28
+ */
29
+ resourceArchiveTimeout?: number;
30
+ /**
31
+ * Domains (besides where the test is being run from) that assets should be archived from
32
+ * (needed when, for example, CI environment can't access the archives later on)
33
+ * ex: www.some-domain.com
34
+ */
35
+ assetDomains?: string[];
36
+ /** Crop snapshots to the viewport size. */
37
+ cropToViewport?: boolean;
38
+ /** CSS selectors of elements to ignore when comparing snapshots. */
39
+ ignoreSelectors?: string[];
40
+ }
41
+ //#endregion
42
+ //#region src/types.d.ts
43
+ /**
44
+ * Options for the Chromatic Vitest plugin
45
+ */
46
+ interface Options extends ChromaticConfig {
47
+ /**
48
+ * Tags used to register tests for visual regression tracking.
49
+ * If specified, only tests with at least one matching tag will be registered for visual regression tracking.
50
+ * Tests without any of the specified tags will be ignored and won't have snapshots taken, even if `disableAutoSnapshot` is false.
51
+ *
52
+ * @default none (all tests are registered)
53
+ */
54
+ tags?: string[];
55
+ /**
56
+ * Directory where temporary archives and snapshots will be stored.
57
+ * Relative to the project [the project `root`](https://vitest.dev/config/root.html#root).
58
+ *
59
+ * Defaults to `.vitest/chromatic`.
60
+ */
61
+ outputDirectory?: string;
62
+ /**
63
+ * Time in milliseconds to determine whether network is idle.
64
+ * The network is considered idle if there are no new network requests for at least this duration.
65
+ *
66
+ * @default 100
67
+ */
68
+ idleNetworkInterval?: number;
69
+ /**
70
+ * Logger used to report status of captured archives.
71
+ *
72
+ * @default true
73
+ */
74
+ reporter?: boolean | {
75
+ /**
76
+ * Whether the reporter is enabled.
77
+ *
78
+ * @default true
79
+ */
80
+ enabled?: boolean;
81
+ /**
82
+ * Log information about captured archives during test run.
83
+ *
84
+ * @default true
85
+ */
86
+ verbose?: boolean;
87
+ };
88
+ /**
89
+ * Enables [TurboSnap](https://www.chromatic.com/docs/turbosnap/).
90
+ *
91
+ * @default false
92
+ */
93
+ turboSnap?: boolean;
94
+ }
95
+ //#endregion
96
+ //#region src/node/plugin.d.ts
97
+ /**
98
+ * Vitest plugin for integrating with Chromatic's visual regression testing.
99
+ */
100
+ declare function chromaticPlugin(userOptions?: Options): Vite.Plugin;
101
+ //#endregion
102
+ export { chromaticPlugin };