@kaizenreport/kensho-vitest 0.1.0

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -0
  3. package/index.js +173 -0
  4. package/package.json +38 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brandon Ordoñez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @kaizenreport/kensho-vitest
2
+
3
+ A Vitest custom reporter that emits the canonical [Kensho v1](../schema) JSON format.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add -D @kaizenreport/kensho-vitest
9
+ # or
10
+ npm i -D @kaizenreport/kensho-vitest
11
+ ```
12
+
13
+ ## Configure
14
+
15
+ ```ts
16
+ // vitest.config.ts
17
+ import { defineConfig } from 'vitest/config';
18
+ import KenshoReporter from '@kaizenreport/kensho-vitest';
19
+
20
+ export default defineConfig({
21
+ test: {
22
+ reporters: [
23
+ 'default',
24
+ new KenshoReporter({
25
+ output: 'kensho-results',
26
+ project: { name: 'Acme API', slug: 'acme-api' },
27
+ severityFromTag: true,
28
+ }),
29
+ ],
30
+ },
31
+ });
32
+ ```
33
+
34
+ ## Run
35
+
36
+ ```bash
37
+ npx vitest run
38
+ # => kensho-results/ populated
39
+
40
+ npx kensho generate # → kensho-report/
41
+ npx kensho open
42
+ ```
43
+
44
+ ## What it produces
45
+
46
+ - `kensho-results/run.json` — manifest (project, env, totals, timing)
47
+ - `kensho-results/cases/<stableId>.json` — one per test
48
+ - `kensho-results/attachments/` — empty by default (Vitest tests rarely produce
49
+ artifacts; you can add them post-hoc if your setup captures any)
50
+
51
+ Stable ids are hashed from fullName + file path so tests correlate across runs.
52
+ Nested `test.each` / custom tasks become Kensho **steps** inside the parent.
53
+
54
+ ## Environment auto-detected
55
+
56
+ GitHub Actions, CircleCI, GitLab CI, Jenkins, Buildkite — CI provider, branch,
57
+ commit, run URL, OS, architecture, Node version.
package/index.js ADDED
@@ -0,0 +1,173 @@
1
+ // @kaizenreport/kensho-vitest — Vitest custom reporter. Walks the Vitest task
2
+ // tree on onFinished() and writes kensho-results/run.json + cases/<id>.json.
3
+
4
+ import { mkdirSync, writeFileSync } from 'node:fs';
5
+ import { resolve, relative } from 'node:path';
6
+ import { emptyRun, computeTotals, stableCaseId, validateRun, envInfo } from '@kaizenreport/kensho-schema';
7
+
8
+ // envInfo() is imported from @kaizenreport/kensho-schema below.
9
+
10
+ function mapStatus(task) {
11
+ // Vitest task.result.state: 'pass' | 'fail' | 'skip' | 'todo' | 'only' | 'run'
12
+ const state = task?.result?.state;
13
+ const mode = task?.mode;
14
+ if (mode === 'skip' || mode === 'todo' || state === 'skip' || state === 'todo') return 'skip';
15
+ if (state === 'pass') return 'pass';
16
+ if (state === 'fail') return 'fail';
17
+ return 'broken';
18
+ }
19
+
20
+ function extractInlineTags(title) {
21
+ const tags = [];
22
+ const re = /@([\w-]+)/g;
23
+ let m;
24
+ while ((m = re.exec(title || ''))) tags.push(m[1]);
25
+ return tags;
26
+ }
27
+
28
+ function severityFromTags(tags) {
29
+ for (const t of tags || []) {
30
+ const m = /^@?(blocker|critical|normal|minor|trivial)$/i.exec(t);
31
+ if (m) return m[1].toLowerCase();
32
+ }
33
+ return undefined;
34
+ }
35
+
36
+ function walkTests(task, suiteChain, out) {
37
+ // Vitest task types: 'suite' | 'test' | 'custom'
38
+ if (task.type === 'suite') {
39
+ const nextChain = task.name ? suiteChain.concat(task.name) : suiteChain;
40
+ for (const child of task.tasks || []) walkTests(child, nextChain, out);
41
+ } else if (task.type === 'test' || task.type === 'custom') {
42
+ out.push({ task, suiteChain });
43
+ }
44
+ }
45
+
46
+ export default class KenshoVitestReporter {
47
+ constructor(opts = {}) {
48
+ this.outputDir = resolve(process.cwd(), opts.output || 'kensho-results');
49
+ this.casesDir = resolve(this.outputDir, 'cases');
50
+ this.attachmentsDir = resolve(this.outputDir, 'attachments');
51
+ this.project = opts.project || {};
52
+ this.severityFromTag = opts.severityFromTag !== false;
53
+ this.runId = opts.runId || ('run_' + new Date().toISOString().replace(/[^0-9]/g, '').slice(0, 14));
54
+ this.startedAt = new Date().toISOString();
55
+ this.casesById = new Map();
56
+ }
57
+
58
+ onInit(/* ctx */) {
59
+ mkdirSync(this.outputDir, { recursive: true });
60
+ mkdirSync(this.casesDir, { recursive: true });
61
+ mkdirSync(this.attachmentsDir, { recursive: true });
62
+ this.startedAt = new Date().toISOString();
63
+ }
64
+
65
+ onFinished(files = [] /* , errors = [] */) {
66
+ try {
67
+ const collected = [];
68
+ for (const f of files || []) {
69
+ // File-level task: its own name is the file path; its tasks are describe/suite blocks.
70
+ walkTests(f, [], collected);
71
+ this._filePath = f.filepath || f.name;
72
+ }
73
+ for (const { task, suiteChain } of collected) {
74
+ const caseObj = this._toKenshoCase(task, suiteChain);
75
+ writeFileSync(
76
+ resolve(this.casesDir, caseObj.id + '.json'),
77
+ JSON.stringify(caseObj, null, 2),
78
+ );
79
+ this.casesById.set(caseObj.id, caseObj);
80
+ }
81
+ this._writeManifest();
82
+ } catch (e) {
83
+ console.error('[kensho] vitest reporter failed:', e && e.message);
84
+ }
85
+ }
86
+
87
+ _toKenshoCase(task, suiteChain) {
88
+ const name = task.name || 'unnamed';
89
+ const filePath = (task.file?.filepath || task.file?.name)
90
+ ? relative(process.cwd(), task.file.filepath || task.file.name)
91
+ : undefined;
92
+ const fullName = suiteChain.concat(name).join(' › ');
93
+ let id = stableCaseId(fullName, filePath);
94
+ if (this.casesById.has(id)) {
95
+ let i = 2;
96
+ while (this.casesById.has(id + '_' + i)) i++;
97
+ id = id + '_' + i;
98
+ }
99
+ const tags = extractInlineTags(name);
100
+ const duration = Math.max(0, Math.round(task.result?.duration || 0));
101
+ const startMs = task.result?.startTime || Date.now();
102
+ const startedAt = new Date(startMs).toISOString();
103
+
104
+ const errors = (task.result?.errors || []).map(e => ({
105
+ message: String(e.message || e),
106
+ stack: e.stack,
107
+ type: e.name,
108
+ }));
109
+
110
+ // Nested tasks (e.g. test.each or custom child tasks) → Kensho steps.
111
+ const steps = [];
112
+ if (Array.isArray(task.tasks) && task.tasks.length) {
113
+ task.tasks.forEach((child, i) => {
114
+ const childStatus = mapStatus(child);
115
+ steps.push({
116
+ id: 'step_' + i + '_' + Math.random().toString(36).slice(2, 6),
117
+ title: child.name || `Step ${i + 1}`,
118
+ status: childStatus === 'fail' ? 'fail' : childStatus === 'skip' ? 'skip' : 'pass',
119
+ startedAt: new Date(child.result?.startTime || startMs).toISOString(),
120
+ duration: Math.max(0, Math.round(child.result?.duration || 0)),
121
+ });
122
+ });
123
+ }
124
+
125
+ return {
126
+ id,
127
+ name,
128
+ fullName,
129
+ filePath,
130
+ suite: suiteChain,
131
+ tags,
132
+ severity: this.severityFromTag ? severityFromTags(tags) : undefined,
133
+ status: mapStatus(task),
134
+ startedAt,
135
+ finishedAt: new Date(startMs + duration).toISOString(),
136
+ duration,
137
+ retries: task.result?.retryCount || 0,
138
+ platform: process.platform,
139
+ steps,
140
+ errors: errors.length ? errors : undefined,
141
+ attachments: [],
142
+ logs: [],
143
+ };
144
+ }
145
+
146
+ _writeManifest() {
147
+ const cases = [...this.casesById.values()];
148
+ const finishedAt = new Date().toISOString();
149
+ const run = emptyRun({
150
+ id: this.runId,
151
+ project: {
152
+ name: this.project.name || 'Unknown project',
153
+ slug: this.project.slug || 'unknown',
154
+ url: this.project.url,
155
+ },
156
+ framework: { name: 'vitest', version: process.env.VITEST_VERSION || 'unknown' },
157
+ env: envInfo(),
158
+ startedAt: this.startedAt,
159
+ });
160
+ run.finishedAt = finishedAt;
161
+ run.durationMs = Math.max(0, Date.parse(finishedAt) - Date.parse(this.startedAt));
162
+ run.testCases = cases;
163
+ run.totals = computeTotals(cases);
164
+
165
+ writeFileSync(resolve(this.outputDir, 'run.json'), JSON.stringify(run, null, 2));
166
+ const { ok, errors } = validateRun(run);
167
+ if (!ok) {
168
+ console.warn('[kensho] run.json failed validation:');
169
+ for (const e of errors.slice(0, 8)) console.warn(' -', e);
170
+ }
171
+ console.log(`[kensho] wrote ${cases.length} cases + run.json to ${this.outputDir}`);
172
+ }
173
+ }
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@kaizenreport/kensho-vitest",
3
+ "version": "0.1.0",
4
+ "description": "Kensho reporter for Vitest — writes kensho-results/ so the Kensho CLI can generate a rich HTML report.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "files": [
8
+ "index.js",
9
+ "README.md"
10
+ ],
11
+ "peerDependencies": {
12
+ "vitest": ">=1.0.0"
13
+ },
14
+ "peerDependenciesMeta": {
15
+ "vitest": {
16
+ "optional": true
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@kaizenreport/kensho-schema": "0.1.0"
21
+ },
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "license": "Apache-2.0",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/brandon1794/kensho.git",
32
+ "directory": "packages/vitest"
33
+ },
34
+ "homepage": "https://github.com/brandon1794/kensho/tree/main/packages/vitest#readme",
35
+ "bugs": {
36
+ "url": "https://github.com/brandon1794/kensho/issues"
37
+ }
38
+ }