@chromatic-com/vitest 1.0.1 → 1.0.3
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/archive-storybook-Bqn7D3Ez.mjs +55 -0
- package/dist/bin/archive-storybook.mjs +47 -0
- package/dist/bin/build-archive-storybook.mjs +65 -0
- package/dist/constants-Dos4OOMt.mjs +68 -0
- package/dist/{index.d.ts → index.d.mts} +48 -42
- package/dist/index.mjs +44 -0
- package/dist/plugin.d.mts +102 -0
- package/dist/plugin.mjs +2632 -0
- package/dist/setupFile.mjs +66 -0
- package/dist/storybook-config/main.mjs +63 -0
- package/dist/storybook-config/manager.mjs +12 -0
- package/dist/storybook-config/preview.mjs +113 -0
- package/dist/telemetry-Db1MVI-S.mjs +320 -0
- package/dist/telemetry-sender.mjs +14 -0
- package/dist/waitForIdleNetwork-CEON19Zg.mjs +193 -0
- package/package.json +28 -23
- package/dist/bin/archive-storybook.d.ts +0 -1
- package/dist/bin/archive-storybook.js +0 -368
- package/dist/bin/build-archive-storybook.d.ts +0 -1
- package/dist/bin/build-archive-storybook.js +0 -383
- package/dist/index.js +0 -250
- package/dist/plugin.d.ts +0 -99
- package/dist/plugin.js +0 -2148
- package/dist/setupFile.d.ts +0 -2
- package/dist/setupFile.js +0 -287
- package/dist/storybook-config/main.d.ts +0 -5
- package/dist/storybook-config/main.js +0 -88
- package/dist/storybook-config/manager.d.ts +0 -2
- package/dist/storybook-config/manager.js +0 -14
- package/dist/storybook-config/preview.d.ts +0 -17
- package/dist/storybook-config/preview.js +0 -138
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { n as takeSnapshot, r as trackEvent, t as waitForIdleNetwork } from "./waitForIdleNetwork-CEON19Zg.mjs";
|
|
2
|
+
import { afterEach, beforeEach, inject } from "vitest";
|
|
3
|
+
import { commands } from "vitest/browser";
|
|
4
|
+
|
|
5
|
+
//#region src/browser/setupFile.ts
|
|
6
|
+
beforeEach(async ({ task }) => {
|
|
7
|
+
const options = inject("__chromatic_options");
|
|
8
|
+
if (options.tags) {
|
|
9
|
+
if (!task.tags?.some((tag) => options.tags?.includes(tag))) {
|
|
10
|
+
task.meta.__chromatic_isRegistered = false;
|
|
11
|
+
return cleanup;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
task.meta.__chromatic_isRegistered = true;
|
|
15
|
+
task.meta.__chromatic_isTakeSnapshotCalled = false;
|
|
16
|
+
task.meta.__chromatic_options ||= {};
|
|
17
|
+
task.meta.__chromatic_options.disableAutoSnapshot ??= options.disableAutoSnapshot;
|
|
18
|
+
task.meta.__chromatic_options.resourceArchiveTimeout ??= options.resourceArchiveTimeout;
|
|
19
|
+
await commands.__chromatic_interceptFetch();
|
|
20
|
+
return async function beforeEachCleanup() {
|
|
21
|
+
const { __chromatic_isTakeSnapshotCalled: isTakeSnapshotCalled, __chromatic_pendingTakeSnapshots: pendingTakeSnapshots, __chromatic_isRegistered: isRegistered } = task.meta;
|
|
22
|
+
if (!isRegistered) return cleanup();
|
|
23
|
+
if (pendingTakeSnapshots?.length) throw new PendingSnapshotsError(pendingTakeSnapshots);
|
|
24
|
+
if (!isTakeSnapshotCalled) {
|
|
25
|
+
await commands.__chromatic_stopWithoutSnapshots(task.id);
|
|
26
|
+
return cleanup();
|
|
27
|
+
}
|
|
28
|
+
await commands.__chromatic_writeTestResult(task.id, task.meta.__chromatic_options);
|
|
29
|
+
return cleanup();
|
|
30
|
+
};
|
|
31
|
+
function cleanup() {
|
|
32
|
+
task.meta.__chromatic_options = void 0;
|
|
33
|
+
task.meta.__chromatic_isTakeSnapshotCalled = void 0;
|
|
34
|
+
task.meta.__chromatic_isRegistered = void 0;
|
|
35
|
+
task.meta.__chromatic_pendingTakeSnapshots = void 0;
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
afterEach(async ({ task }) => {
|
|
39
|
+
const { __chromatic_options: options, __chromatic_pendingTakeSnapshots: pendingTakeSnapshots, __chromatic_isRegistered: isRegistered, __chromatic_options: testOptions } = task.meta;
|
|
40
|
+
if (!isRegistered) return;
|
|
41
|
+
if (pendingTakeSnapshots?.length) throw new PendingSnapshotsError(pendingTakeSnapshots);
|
|
42
|
+
if (testOptions.resourceArchiveTimeout !== 0) {
|
|
43
|
+
await document.fonts.ready;
|
|
44
|
+
await waitForIdleNetwork(testOptions.resourceArchiveTimeout, { _internal: true });
|
|
45
|
+
}
|
|
46
|
+
if (!options.disableAutoSnapshot) await takeSnapshot(void 0, { isAutomaticSnapshot: true });
|
|
47
|
+
});
|
|
48
|
+
var PendingSnapshotsError = class extends AggregateError {
|
|
49
|
+
pendingCalls;
|
|
50
|
+
constructor(pendingCalls) {
|
|
51
|
+
super(pendingCalls.map((call) => call.error), `${pendingCalls.length} unawaited takeSnapshot() call(s)`);
|
|
52
|
+
this.pendingCalls = pendingCalls;
|
|
53
|
+
this.name = "PendingSnapshotsError";
|
|
54
|
+
trackEvent({
|
|
55
|
+
eventType: "take_snapshot_invalid_call",
|
|
56
|
+
level: "error",
|
|
57
|
+
payload: {
|
|
58
|
+
isAwaited: false,
|
|
59
|
+
isInsideTest: true,
|
|
60
|
+
isRegisteredTest: true
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
//#endregion
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { n as archivesDir, t as DEFAULT_OUTPUT_DIR } from "../constants-Dos4OOMt.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
|
|
7
|
+
//#region ../shared/src/utils/storybookPaths.ts
|
|
8
|
+
function storybookParentNodeModulesDir(importMetaUrl) {
|
|
9
|
+
const require = createRequire(importMetaUrl);
|
|
10
|
+
const dir = path.dirname(path.dirname(require.resolve("storybook/package.json")));
|
|
11
|
+
return path.basename(dir) === "node_modules" ? dir : null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/storybook-config/main.ts
|
|
16
|
+
const packageRoot = path.resolve(import.meta.dirname, "..", "..");
|
|
17
|
+
const embeddedDir = path.join(packageRoot, "embedded", "node_modules");
|
|
18
|
+
var main_default = {
|
|
19
|
+
stories: [path.resolve(archivesDir(DEFAULT_OUTPUT_DIR), "*.stories.json")],
|
|
20
|
+
managerEntries: [path.resolve(import.meta.dirname, "manager.mjs")],
|
|
21
|
+
previewAnnotations: [path.resolve(import.meta.dirname, "preview.mjs")],
|
|
22
|
+
framework: {
|
|
23
|
+
name: path.join(embeddedDir, "@storybook", "server-webpack5"),
|
|
24
|
+
options: {}
|
|
25
|
+
},
|
|
26
|
+
core: {
|
|
27
|
+
builder: pathToFileURL(path.join(embeddedDir, "@storybook", "builder-webpack5", "dist", "index.js")).href,
|
|
28
|
+
renderer: pathToFileURL(path.join(embeddedDir, "@storybook", "server", "preset.js")).href
|
|
29
|
+
},
|
|
30
|
+
staticDirs: [path.resolve(archivesDir(DEFAULT_OUTPUT_DIR), "archive")],
|
|
31
|
+
features: { sidebarOnboardingChecklist: false },
|
|
32
|
+
webpackFinal: async (config) => {
|
|
33
|
+
config.target = ["web"];
|
|
34
|
+
config.plugins.push(new VitestStatsPlugin());
|
|
35
|
+
const storybookNodeModules = storybookParentNodeModulesDir(import.meta.url);
|
|
36
|
+
if (storybookNodeModules) {
|
|
37
|
+
config.resolve ??= {};
|
|
38
|
+
config.resolve.modules = [...config.resolve.modules ?? ["node_modules"], storybookNodeModules];
|
|
39
|
+
}
|
|
40
|
+
return config;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
var VitestStatsPlugin = class {
|
|
44
|
+
apply(compiler) {
|
|
45
|
+
const chromaticResults = path.dirname(archivesDir(DEFAULT_OUTPUT_DIR));
|
|
46
|
+
const previewStats = path.resolve(chromaticResults, "preview-stats.json");
|
|
47
|
+
if (existsSync(previewStats)) compiler.hooks.done.tap("Vitest Stats Plugin", (stats) => {
|
|
48
|
+
const { modules } = JSON.parse(readFileSync(previewStats, "utf-8"));
|
|
49
|
+
const toJson = stats.toJson.bind(stats);
|
|
50
|
+
const testModules = modules.filter((mod) => !mod.name.endsWith(".stories.json") && mod.name !== "/virtual:/@storybook/builder-vite/storybook-stories.js");
|
|
51
|
+
stats.toJson = (...args) => {
|
|
52
|
+
const json = toJson(...args);
|
|
53
|
+
return {
|
|
54
|
+
...json,
|
|
55
|
+
modules: [...json.modules || [], ...testModules]
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
//#endregion
|
|
63
|
+
export { main_default as default };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { addons } from "storybook/manager-api";
|
|
2
|
+
|
|
3
|
+
//#region ../shared/storybook-config/manager.ts
|
|
4
|
+
addons.setConfig({
|
|
5
|
+
sidebar: { showRoots: false },
|
|
6
|
+
layoutCustomisations: {
|
|
7
|
+
showToolbar: () => false,
|
|
8
|
+
showPanel: () => false
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
//#endregion
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createCache, createMirror, rebuild } from "@chromaui/rrweb-snapshot";
|
|
2
|
+
|
|
3
|
+
//#region ../../node_modules/.pnpm/@rrweb+types@2.1.0/node_modules/@rrweb/types/dist/types.js
|
|
4
|
+
var NodeType = /* @__PURE__ */ ((NodeType2) => {
|
|
5
|
+
NodeType2[NodeType2["Document"] = 0] = "Document";
|
|
6
|
+
NodeType2[NodeType2["DocumentType"] = 1] = "DocumentType";
|
|
7
|
+
NodeType2[NodeType2["Element"] = 2] = "Element";
|
|
8
|
+
NodeType2[NodeType2["Text"] = 3] = "Text";
|
|
9
|
+
NodeType2[NodeType2["CDATA"] = 4] = "CDATA";
|
|
10
|
+
NodeType2[NodeType2["Comment"] = 5] = "Comment";
|
|
11
|
+
return NodeType2;
|
|
12
|
+
})(NodeType || {});
|
|
13
|
+
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region ../shared/src/utils/nodes.ts
|
|
16
|
+
function isIframeSerializedNode(node) {
|
|
17
|
+
return node.type === NodeType.Element && node.tagName === "iframe" && "contentDocument" in node && !!node.contentDocument;
|
|
18
|
+
}
|
|
19
|
+
function isElement(node) {
|
|
20
|
+
return node?.nodeType === Node.ELEMENT_NODE;
|
|
21
|
+
}
|
|
22
|
+
function isIframeElement(node) {
|
|
23
|
+
return isElement(node) && node.tagName.toLowerCase() === "iframe";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region ../shared/storybook-config/preview.ts
|
|
28
|
+
const pageUrl = new URL(window.location.href);
|
|
29
|
+
pageUrl.pathname = "";
|
|
30
|
+
pageUrl.search = "";
|
|
31
|
+
const strippedUrl = pageUrl.toString().replace(/\/$/, "");
|
|
32
|
+
const findHtmlNode = (node) => {
|
|
33
|
+
if (node.type === NodeType.Element && node.tagName === "html") return node;
|
|
34
|
+
if ("childNodes" in node) return node.childNodes.find((childNode) => {
|
|
35
|
+
return findHtmlNode(childNode);
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
const findNodeById = (node, id) => {
|
|
39
|
+
if (node.id === id) return node;
|
|
40
|
+
if ("childNodes" in node) for (const childNode of node.childNodes) {
|
|
41
|
+
const match = findNodeById(childNode, id);
|
|
42
|
+
if (match) return match;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
function snapshotFileName(snapshotId, viewport) {
|
|
46
|
+
return [
|
|
47
|
+
snapshotId,
|
|
48
|
+
viewport,
|
|
49
|
+
"snapshot.json"
|
|
50
|
+
].join(".");
|
|
51
|
+
}
|
|
52
|
+
async function fetchSnapshot(context) {
|
|
53
|
+
const { url, id } = context.storyContext.parameters.server;
|
|
54
|
+
const { viewport } = context.storyContext.globals;
|
|
55
|
+
let viewportName;
|
|
56
|
+
if (typeof viewport === "string") viewportName = viewport;
|
|
57
|
+
else viewportName = `w${viewport.width}h${viewport.height}`;
|
|
58
|
+
let response = await fetch(`${url}/${snapshotFileName(id, viewportName)}`);
|
|
59
|
+
if (!response.ok) {
|
|
60
|
+
const { defaultViewport } = context.storyContext.parameters.viewport;
|
|
61
|
+
response = await fetch(`${url}/${snapshotFileName(id, defaultViewport)}`);
|
|
62
|
+
}
|
|
63
|
+
return response.json();
|
|
64
|
+
}
|
|
65
|
+
const renderToCanvas = async (context) => {
|
|
66
|
+
const { snapshot, pseudoClassIds } = await fetchSnapshot(context);
|
|
67
|
+
const htmlNode = findHtmlNode(snapshot);
|
|
68
|
+
const mirror = createMirror();
|
|
69
|
+
const html = rebuild(htmlNode, {
|
|
70
|
+
doc: document,
|
|
71
|
+
mirror,
|
|
72
|
+
cache: createCache(),
|
|
73
|
+
afterAppend: afterAppendIframes(snapshot)
|
|
74
|
+
});
|
|
75
|
+
for (const [className, ids] of Object.entries(pseudoClassIds)) for (const id of ids) {
|
|
76
|
+
const el = mirror.getNode(id);
|
|
77
|
+
if (isElement(el)) el.classList.add(className);
|
|
78
|
+
}
|
|
79
|
+
document.replaceChild(html, document.children[0]);
|
|
80
|
+
document.head.innerHTML += "<script id=\"storybook-root\"><\/script><script id=\"storybook-docs\"><\/script>";
|
|
81
|
+
context.showMain();
|
|
82
|
+
return () => {};
|
|
83
|
+
};
|
|
84
|
+
function afterAppendIframes(snapshot) {
|
|
85
|
+
return function afterAppend(node, id) {
|
|
86
|
+
if (!isIframeElement(node)) return;
|
|
87
|
+
const serializedNode = findNodeById(snapshot, id);
|
|
88
|
+
if (!isIframeSerializedNode(serializedNode)) return;
|
|
89
|
+
node.onload = () => {
|
|
90
|
+
const mirror = createMirror();
|
|
91
|
+
rebuild(serializedNode.contentDocument, {
|
|
92
|
+
doc: node.contentDocument,
|
|
93
|
+
mirror,
|
|
94
|
+
cache: createCache(),
|
|
95
|
+
afterAppend: afterAppendIframes(serializedNode.contentDocument)
|
|
96
|
+
});
|
|
97
|
+
for (const [className, ids] of Object.entries(serializedNode.pseudoClassIds)) for (const id of ids) {
|
|
98
|
+
const el = mirror.getNode(id);
|
|
99
|
+
if (isElement(el)) el.classList.add(className);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
var preview_default = {
|
|
105
|
+
renderToCanvas,
|
|
106
|
+
parameters: {
|
|
107
|
+
server: { url: strippedUrl },
|
|
108
|
+
layout: "fullscreen"
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
//#endregion
|
|
113
|
+
export { preview_default as default };
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { existsSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { join, resolve, sep } from "node:path";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
import util from "node:util";
|
|
7
|
+
import { env, isCI, nodeVersion } from "std-env";
|
|
8
|
+
import { x } from "tinyexec";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
//#region src/node/telemetry/constants.ts
|
|
14
|
+
const EVENT_TYPE_PREFIX = "vitest_";
|
|
15
|
+
const TELEMETRY_FETCH_TIMEOUT_MS = 5e3;
|
|
16
|
+
const TELEMETRY_URL = "https://analytics.chromatic.com";
|
|
17
|
+
const TELEMETRY_LOG_FILE = "telemetry.jsonl";
|
|
18
|
+
const TELEMETRY_METADATA_FILE = "telemetry-metadata.json";
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/node/telemetry/env.ts
|
|
22
|
+
let dotEnv = void 0;
|
|
23
|
+
function getEnv(name) {
|
|
24
|
+
if (dotEnv === void 0) {
|
|
25
|
+
if (typeof util.parseEnv !== "function") dotEnv = {};
|
|
26
|
+
else try {
|
|
27
|
+
dotEnv = util.parseEnv(readFileSync(resolve(process.cwd(), ".env"), "utf8"));
|
|
28
|
+
} catch {
|
|
29
|
+
dotEnv = {};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return env[name] ?? dotEnv[name];
|
|
33
|
+
}
|
|
34
|
+
function resolveTelemetryOptions() {
|
|
35
|
+
return {
|
|
36
|
+
enabled: isTruthyEnv(getEnv("CHROMATIC_DISABLE_TELEMETRY")) === false && isTruthyEnv(getEnv("DO_NOT_TRACK")) === false,
|
|
37
|
+
logToFile: isTruthyEnv(getEnv("CHROMATIC_TELEMETRY_LOG_TO_FILE"))
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function isTruthyEnv(value) {
|
|
41
|
+
return value !== void 0 && value !== "" && value !== "0" && value !== "false";
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
//#endregion
|
|
45
|
+
//#region package.json
|
|
46
|
+
var version = "1.0.3";
|
|
47
|
+
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region src/node/telemetry/metadata.ts
|
|
50
|
+
const userAgentMatch = env.npm_config_user_agent?.match(/^([^/\s]+)\/(\S+)/);
|
|
51
|
+
const packageManager = {
|
|
52
|
+
name: userAgentMatch?.[1] || "unknown",
|
|
53
|
+
version: userAgentMatch?.[2] || "unknown"
|
|
54
|
+
};
|
|
55
|
+
async function createProjectId(root) {
|
|
56
|
+
let remote = void 0;
|
|
57
|
+
try {
|
|
58
|
+
const result = await x("git", [
|
|
59
|
+
"remote",
|
|
60
|
+
"get-url",
|
|
61
|
+
"origin"
|
|
62
|
+
], { nodeOptions: { cwd: root } });
|
|
63
|
+
remote = result.exitCode === 0 ? result.stdout.trim().toLowerCase() : void 0;
|
|
64
|
+
} catch {}
|
|
65
|
+
if (!remote) return hash(root);
|
|
66
|
+
const hasProtocol = remote.includes("://");
|
|
67
|
+
remote = remote.replace(/^[a-z+]+:\/\//, "").replace(/^[^@/]+@/, "");
|
|
68
|
+
if (!hasProtocol) remote = remote.replace(":", "/");
|
|
69
|
+
remote = remote.replace(/\.git$/, "").replace(/\/+$/, "");
|
|
70
|
+
return hash(remote);
|
|
71
|
+
}
|
|
72
|
+
function hash(value) {
|
|
73
|
+
return createHash("sha256").update(`chromatic-vitest-telemetry-v1:${value}`).digest("hex");
|
|
74
|
+
}
|
|
75
|
+
function getChromaticVersion(root) {
|
|
76
|
+
try {
|
|
77
|
+
return createRequire(join(root, "package.json"))("chromatic/package.json").version || "unknown";
|
|
78
|
+
} catch {
|
|
79
|
+
return "unknown";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function writeTelemetryMetadata(outputDirectory, data) {
|
|
83
|
+
await writeFile(resolve(outputDirectory, TELEMETRY_METADATA_FILE), JSON.stringify(data, null, 2), "utf8");
|
|
84
|
+
}
|
|
85
|
+
async function readTelemetryMetadata(outputDirectory) {
|
|
86
|
+
const defaults = {
|
|
87
|
+
sessionId: "unknown",
|
|
88
|
+
projectId: "unknown",
|
|
89
|
+
chromaticVersion: "unknown",
|
|
90
|
+
vitestVersion: "unknown",
|
|
91
|
+
isVitestProjects: false
|
|
92
|
+
};
|
|
93
|
+
try {
|
|
94
|
+
const filename = resolve(outputDirectory, TELEMETRY_METADATA_FILE);
|
|
95
|
+
if (!existsSync(filename)) return defaults;
|
|
96
|
+
const content = await readFile(filename, "utf8");
|
|
97
|
+
const json = JSON.parse(content);
|
|
98
|
+
return {
|
|
99
|
+
...defaults,
|
|
100
|
+
...json
|
|
101
|
+
};
|
|
102
|
+
} catch {
|
|
103
|
+
return defaults;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/node/telemetry/sanitize.ts
|
|
109
|
+
function sanitizeError(error) {
|
|
110
|
+
if (error instanceof Error && error.stack) return sanitizeString(error.stack.includes(error.message) ? error.stack : `${error.message}\nStack: ${error.stack}`).slice(0, 2e3);
|
|
111
|
+
return sanitizeString(error instanceof Error ? error.message : String(error)).slice(0, 1e3);
|
|
112
|
+
}
|
|
113
|
+
function sanitizeString(value) {
|
|
114
|
+
return value.replaceAll(sep, "/").replace(toPathRegExp(process.cwd()), "<process-cwd>").replace(toPathRegExp(homedir()), "<homedir>");
|
|
115
|
+
}
|
|
116
|
+
function toPathRegExp(path) {
|
|
117
|
+
const escaped = path.replaceAll(sep, "/").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
118
|
+
return new RegExp(escaped, "gi");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region src/node/telemetry/session.ts
|
|
123
|
+
const session = {
|
|
124
|
+
id: randomUUID(),
|
|
125
|
+
projectId: void 0,
|
|
126
|
+
chromaticVersion: void 0,
|
|
127
|
+
cleanedLogFileDirectories: /* @__PURE__ */ new Set(),
|
|
128
|
+
cleanups: /* @__PURE__ */ new Set(),
|
|
129
|
+
transport: void 0,
|
|
130
|
+
cleanupRegistered: false,
|
|
131
|
+
isMetadataWritten: false,
|
|
132
|
+
telemetryMetadata: void 0
|
|
133
|
+
};
|
|
134
|
+
function cleanTelemetryLogFiles(outputDirectory) {
|
|
135
|
+
if (session.cleanedLogFileDirectories.has(outputDirectory)) return;
|
|
136
|
+
session.cleanedLogFileDirectories.add(outputDirectory);
|
|
137
|
+
rmSync(resolve(outputDirectory, TELEMETRY_LOG_FILE), { force: true });
|
|
138
|
+
rmSync(resolve(outputDirectory, TELEMETRY_METADATA_FILE), { force: true });
|
|
139
|
+
}
|
|
140
|
+
async function flushTelemetry() {
|
|
141
|
+
await Promise.all(Array.from(session.cleanups.values()));
|
|
142
|
+
session.cleanups.clear();
|
|
143
|
+
await session.transport?.close();
|
|
144
|
+
session.transport = void 0;
|
|
145
|
+
}
|
|
146
|
+
function setupTelemetryCleanup(vitest) {
|
|
147
|
+
if (session.cleanupRegistered) return;
|
|
148
|
+
session.cleanupRegistered = true;
|
|
149
|
+
vitest.onClose(async () => {
|
|
150
|
+
await flushTelemetry();
|
|
151
|
+
session.isMetadataWritten = false;
|
|
152
|
+
session.cleanedLogFileDirectories.clear();
|
|
153
|
+
session.cleanupRegistered = false;
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/node/telemetry/transport.ts
|
|
159
|
+
const SENDER_PATH = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./sender.ts" : "./telemetry-sender.mjs", import.meta.url));
|
|
160
|
+
function createTelemetryTransport() {
|
|
161
|
+
const child = spawn(process.execPath, [SENDER_PATH, String(TELEMETRY_FETCH_TIMEOUT_MS)], {
|
|
162
|
+
detached: true,
|
|
163
|
+
stdio: [
|
|
164
|
+
"ignore",
|
|
165
|
+
"ignore",
|
|
166
|
+
"ignore",
|
|
167
|
+
"ipc"
|
|
168
|
+
],
|
|
169
|
+
windowsHide: true
|
|
170
|
+
});
|
|
171
|
+
child.on("error", () => {});
|
|
172
|
+
child.unref();
|
|
173
|
+
child.channel?.unref();
|
|
174
|
+
const pending = /* @__PURE__ */ new Set();
|
|
175
|
+
return {
|
|
176
|
+
send(message) {
|
|
177
|
+
if (!child.connected) return;
|
|
178
|
+
const promise = new Promise((resolve) => {
|
|
179
|
+
try {
|
|
180
|
+
child.send(message, () => resolve());
|
|
181
|
+
} catch {
|
|
182
|
+
resolve();
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
pending.add(promise);
|
|
186
|
+
promise.finally(() => pending.delete(promise));
|
|
187
|
+
},
|
|
188
|
+
async close() {
|
|
189
|
+
await Promise.all(pending);
|
|
190
|
+
if (child.connected) child.disconnect();
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
//#endregion
|
|
196
|
+
//#region src/node/telemetry/track.ts
|
|
197
|
+
function trackEvent(event, vitest, options) {
|
|
198
|
+
if (!options.telemetry.enabled) return;
|
|
199
|
+
const promise = _trackEvent(event, vitest, options).catch(() => {}).finally(() => session.cleanups.delete(promise));
|
|
200
|
+
session.cleanups.add(promise);
|
|
201
|
+
}
|
|
202
|
+
async function trackCliEvent(event, options) {
|
|
203
|
+
const telemetry = resolveTelemetryOptions();
|
|
204
|
+
if (!telemetry.enabled) return;
|
|
205
|
+
let telemetryMetadata = session.telemetryMetadata;
|
|
206
|
+
if (session.telemetryMetadata === void 0) {
|
|
207
|
+
telemetryMetadata = await readTelemetryMetadata(options.outputDirectory);
|
|
208
|
+
session.telemetryMetadata = telemetryMetadata;
|
|
209
|
+
if (!("disabled" in telemetryMetadata)) {
|
|
210
|
+
session.id = telemetryMetadata.sessionId;
|
|
211
|
+
session.projectId = telemetryMetadata.projectId;
|
|
212
|
+
session.chromaticVersion = telemetryMetadata.chromaticVersion;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
await _trackEvent(event, {
|
|
216
|
+
version: telemetryMetadata.vitestVersion,
|
|
217
|
+
config: { root: options.outputDirectory },
|
|
218
|
+
projects: telemetryMetadata.isVitestProjects ? [1, 2] : []
|
|
219
|
+
}, {
|
|
220
|
+
outputDirectory: options.outputDirectory,
|
|
221
|
+
telemetry
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
async function _trackEvent(event, vitest, options) {
|
|
225
|
+
const url = getEnv("CHROMATIC_TELEMETRY_URL") || "https://analytics.chromatic.com";
|
|
226
|
+
const root = vitest.config.root;
|
|
227
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
228
|
+
const outputDirectory = resolve(root, options.outputDirectory);
|
|
229
|
+
session.projectId ||= await createProjectId(root);
|
|
230
|
+
session.chromaticVersion ||= getChromaticVersion(root);
|
|
231
|
+
const wireEvent = {
|
|
232
|
+
id: randomUUID(),
|
|
233
|
+
sessionId: session.id,
|
|
234
|
+
projectId: session.projectId,
|
|
235
|
+
timestamp,
|
|
236
|
+
eventType: `${EVENT_TYPE_PREFIX}${event.eventType}`,
|
|
237
|
+
level: event.level,
|
|
238
|
+
payload: event.payload,
|
|
239
|
+
metadata: {
|
|
240
|
+
isCI,
|
|
241
|
+
pluginVersion: version,
|
|
242
|
+
nodeVersion: nodeVersion || "unknown",
|
|
243
|
+
vitestVersion: vitest.version,
|
|
244
|
+
isVitestProjects: vitest.projects.length > 1,
|
|
245
|
+
packageManager: packageManager.name,
|
|
246
|
+
packageManagerVersion: packageManager.version,
|
|
247
|
+
chromaticVersion: session.chromaticVersion
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
if (wireEvent.level === "error" && "error" in wireEvent.payload) wireEvent.payload.error = sanitizeError(wireEvent.payload.error);
|
|
251
|
+
session.transport ||= createTelemetryTransport();
|
|
252
|
+
session.transport.send({
|
|
253
|
+
endpoint: `${url}/telemetry/v1/vitest/events`,
|
|
254
|
+
event: wireEvent
|
|
255
|
+
});
|
|
256
|
+
if (options.telemetry.logToFile) {
|
|
257
|
+
const logFile = resolve(outputDirectory, TELEMETRY_LOG_FILE);
|
|
258
|
+
await mkdir(outputDirectory, { recursive: true });
|
|
259
|
+
await appendFile(logFile, `${JSON.stringify(wireEvent)}\n`, "utf8");
|
|
260
|
+
}
|
|
261
|
+
if (!session.isMetadataWritten) {
|
|
262
|
+
session.isMetadataWritten = true;
|
|
263
|
+
await writeTelemetryMetadata(outputDirectory, {
|
|
264
|
+
...wireEvent.metadata,
|
|
265
|
+
sessionId: wireEvent.sessionId,
|
|
266
|
+
projectId: wireEvent.projectId
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
//#endregion
|
|
272
|
+
//#region src/node/telemetry/reporter.ts
|
|
273
|
+
const REPORTER_NAME = "chromatic-telemetry-reporter";
|
|
274
|
+
var TelemetryReporter = class TelemetryReporter {
|
|
275
|
+
ctx;
|
|
276
|
+
options;
|
|
277
|
+
name = REPORTER_NAME;
|
|
278
|
+
snapshotCount = 0;
|
|
279
|
+
constructor(ctx, options) {
|
|
280
|
+
this.ctx = ctx;
|
|
281
|
+
this.options = options;
|
|
282
|
+
}
|
|
283
|
+
static apply(ctx, options) {
|
|
284
|
+
if (!options.telemetry.enabled) return;
|
|
285
|
+
for (const reporter of ctx.config.reporters) if (isTelemetryReporter(reporter)) return;
|
|
286
|
+
ctx.config.reporters.push(new TelemetryReporter(ctx, options));
|
|
287
|
+
}
|
|
288
|
+
static onSnapshot(ctx, payload) {
|
|
289
|
+
ctx.config.reporters.find(isTelemetryReporter)?._onSnapshot(payload);
|
|
290
|
+
}
|
|
291
|
+
_onSnapshot(payload) {
|
|
292
|
+
this.snapshotCount++;
|
|
293
|
+
trackEvent({
|
|
294
|
+
eventType: "snapshot_captured",
|
|
295
|
+
level: "info",
|
|
296
|
+
payload
|
|
297
|
+
}, this.ctx, this.options);
|
|
298
|
+
}
|
|
299
|
+
onTestRunStart() {
|
|
300
|
+
this.snapshotCount = 0;
|
|
301
|
+
trackEvent({
|
|
302
|
+
eventType: "run_started",
|
|
303
|
+
level: "info",
|
|
304
|
+
payload: {}
|
|
305
|
+
}, this.ctx, this.options);
|
|
306
|
+
}
|
|
307
|
+
onTestRunEnd() {
|
|
308
|
+
trackEvent({
|
|
309
|
+
eventType: "run_ended",
|
|
310
|
+
level: "info",
|
|
311
|
+
payload: { snapshotCount: this.snapshotCount }
|
|
312
|
+
}, this.ctx, this.options);
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
function isTelemetryReporter(reporter) {
|
|
316
|
+
return "name" in reporter && reporter.name === REPORTER_NAME;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
//#endregion
|
|
320
|
+
export { flushTelemetry as a, TELEMETRY_LOG_FILE as c, cleanTelemetryLogFiles as i, trackCliEvent as n, setupTelemetryCleanup as o, trackEvent as r, resolveTelemetryOptions as s, TelemetryReporter as t };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/node/telemetry/sender.ts
|
|
2
|
+
const timeout = Number(process.argv[2]);
|
|
3
|
+
process.on("message", (message) => {
|
|
4
|
+
const { endpoint, event } = message;
|
|
5
|
+
fetch(endpoint, {
|
|
6
|
+
method: "POST",
|
|
7
|
+
headers: { "Content-Type": "application/json" },
|
|
8
|
+
body: JSON.stringify(event),
|
|
9
|
+
signal: AbortSignal.timeout(timeout)
|
|
10
|
+
}).catch(() => {});
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
//#endregion
|
|
14
|
+
export { };
|