diff --git a/.claude/agents/test-writer.md b/.claude/agents/test-writer.md new file mode 100644 index 00000000..905dc813 --- /dev/null +++ b/.claude/agents/test-writer.md @@ -0,0 +1,14 @@ +--- +name: test-writer +description: Writes failing tests from a requirement before the implementation exists. Use at the start of new behaviour or a bug fix. +tools: Read, Grep, Glob, Edit, Write, Bash +--- + +You turn a requirement into tests. You do not write implementation code. The one exception: a new module may start as a file with its exported signatures throwing `not implemented`, so that the tests can import it. + +- Read the requirement, `.claude/rules/testing.md` and `.claude/rules/host-page.md`. Work from what the code must do on a customer's page, not from how it does it today. +- Write at least one test per requirement, next to the code it will test, at the level the rules name: `src/.test.js` with Vitest (a `@vitest-environment jsdom` docblock when it needs a DOM), or `smoke/*.spec.mjs` when only the built bundle in a real browser can show it. Name each test after the behaviour: `it('ignores a message from another frame')`. +- Import `describe`, `it`, `expect` and `vi` from `vitest`. Assert behaviour, not that code ran. Fake the network, time and the Messenger frame; do not mock the module under test or its helpers. +- Cover what the host page sees: no new global, no error thrown into the page, nothing sent to a frame without its target origin, masking left on. +- Run the tests with `npx vitest run ` (smoke: `npm run build`, then `npx playwright test `) and confirm they fail for the expected reason, not because of a typo or a wrong import. +- Report which test covers which requirement, and the failing output. diff --git a/.claude/commands/review.md b/.claude/commands/review.md new file mode 100644 index 00000000..15046ce5 --- /dev/null +++ b/.claude/commands/review.md @@ -0,0 +1,113 @@ +You are a strict code reviewer for the Gleap JavaScript SDK (the `gleap` package customers embed in their pages: plain JavaScript, webpack, Vitest, Playwright smoke tests). Review all changes on the current branch compared to `origin/master`. + +## Steps + +1. Run `git diff $(git merge-base HEAD origin/master)..HEAD -- src index.d.ts smoke package.json webpack.config.js babel.config.js README.md CHANGELOG.md` to get the full diff. +2. If it is empty, run the same with `git diff --cached`, then `git diff`. +3. If all diffs are empty, output "No reviewable code changes found." and stop. +4. Read `AGENTS.md` and `.claude/rules/*.md`, then check every changed file against the rules below. +5. Run `node tools/quality/check.mjs --base origin/master` and include what it reports. +6. For SSOT checks, search the codebase (Grep, Glob) for duplicate helpers, constants and message names, the Server (`../Server`, from a worktree `../../Server`) for values it stores, and the Messenger (`../Messenger-App`) for message names it sends or reads. +7. For every non-formatting change, read the surrounding code, not only the diff, and judge whether existing behaviour could break on a customer's page. + +## Review output format + +Structure the review exactly like this. If everything passes, one line per topic with a checkmark; details only where something is wrong. + +``` +### Overview +_1-2 sentences on what the changes do._ + +### Checklist + +✅ SSOT +✅ Code conventions +✅ Public API and compatibility +✅ Host page: globals, teardown, errors +✅ CSP and Trusted Types +✅ Frames and messages +✅ Privacy +✅ Load time, size and browsers +✅ Tests +✅ Over-engineering +✅ Dead code +✅ Impact & Risk +``` + +- One line per topic. ✅ = clean, ❌ = issue found, with a reason of at most ~10 words. +- Below the checklist, output only the sections that have findings: + +``` +### Critical Issues (must fix before merge) + +> **[Rule]** [GleapThing.js:42](src/GleapThing.js#L42) +> What is wrong and why it matters. +> **Fix:** Concrete suggestion. + +### Warnings + +> **[Rule]** [GleapThing.js:10](src/GleapThing.js#L10) +> Short explanation. + +### Impact & Risk Analysis + +> **Risk:** `sendMessage()` is called from 9 places. The new early return drops queued messages when the frame reloads. + +--- + +### Confidence: X/5 +``` + +If the score is below 5, say why. 5: every rule verified with searches, all usages traced. 4: minor gaps in tracing. 3: some checks limited. 2: files skimmed. 1: superficial. + +Do not output suggestions for nice-to-haves, praise, or formatting-only changes. + +## Rules to check + +### 1. SSOT (critical) + +For every new helper, constant or message name: search for an existing one. Flag a duplicate of an existing helper (the table in `.claude/rules/code-conventions.md`), a value the Server stores spelled differently from the Server, and a message name that differs from what the Messenger sends or reads. + +### 2. Code conventions + +Everything in `.claude/rules/code-conventions.md`, including the one-job-one-system table. Critical: a new runtime package (in `dependencies` or imported), new logic added to a file already over its limit instead of its own module. + +### 3. Public API and compatibility (critical) + +Flag a removed or renamed `Gleap.*` method, parameter, option, default, callback, event, custom element, cookie or storage key; a changed meaning without a major version; an API change without `index.d.ts`, `CHANGELOG.md` and, for a new call, `README.md`; new behaviour that existing projects get without opting in; a third positional parameter on a public method. + +### 4. Host page: globals, teardown, errors (critical) + +Flag a new `window.*` property, a change to a built-in prototype, a polyfill; a listener, observer, timer or frame without a teardown; a non-passive scroll, touch or wheel listener; a wrapper of `fetch`, XHR or `console` that drops `this` or arguments, can throw, or restores unconditionally; a public method or customer callback that can throw into the page. + +### 5. CSP and Trusted Types (critical) + +Flag `eval`, `new Function` or string timers; a ` +${scriptTag}`, +}); + +// The host page and the bundle are served here; everything else (the Gleap API, the messenger) is aborted. +const servePage = async (page, { csp, scriptTag = `` } = {}) => { + const problems = []; + page.on('pageerror', (error) => problems.push(`pageerror: ${error.message}`)); + page.on('console', (message) => { + if (message.type() === 'error' && !message.text().startsWith('Failed to load resource')) problems.push(`console.error: ${message.text()}`); + }); + await page.route('**/*', (route) => { + const url = new URL(route.request().url()); + if (url.origin !== HOST) return route.abort(); + if (url.pathname === '/sdk.js') return route.fulfill({ path: BROWSER_BUNDLE, contentType: 'text/javascript' }); + if (url.pathname === '/sdk.mjs') return route.fulfill({ path: ESM_BUNDLE, contentType: 'text/javascript' }); + return route.fulfill(hostPage({ csp, scriptTag })); + }); + await page.goto(`${HOST}/`); + return problems; +}; + +test('the CDN bundle defines window.Gleap and nothing else, without an error', async ({ page }) => { + const problems = await servePage(page); + + const added = await page.evaluate(() => Object.keys(window).filter((key) => !window.__keysBefore.includes(key))); + expect(added).toEqual(['Gleap']); + expect(problems).toEqual([]); +}); + +test('every function index.d.ts declares exists on window.Gleap', async ({ page }) => { + await servePage(page); + + const missing = await page.evaluate((names) => names.filter((name) => typeof window.Gleap[name] !== 'function'), declaredFunctions()); + expect(missing).toEqual(DECLARED_BUT_MISSING); +}); + +test('initialize under a strict nonce CSP that allows the Gleap hosts, with them unreachable: no violation, no page error', async ({ page }) => { + const gleap = 'https://*.gleap.io wss://*.gleap.io'; + const csp = `default-src 'none'; script-src 'nonce-${NONCE}' 'strict-dynamic'; style-src 'nonce-${NONCE}'; img-src 'self' data: ${gleap}; connect-src 'self' ${gleap}; frame-src 'self' ${gleap}`; + const problems = await servePage(page, { csp }); + + const sessionFailed = page.waitForEvent('requestfailed', (request) => request.url().startsWith('https://api.gleap.io/')); + await page.evaluate(() => window.Gleap.initialize('smoke-test-project')); + await sessionFailed; + // One frame later the SDK has handled the failure. + await page.evaluate(() => new Promise((resolve) => requestAnimationFrame(resolve))); + + expect(await page.evaluate(() => window.__violations)).toEqual([]); + expect(problems.filter((problem) => problem.startsWith('pageerror'))).toEqual([]); +}); + +test('the ESM bundle exports the same Gleap as the CDN bundle', async ({ page }) => { + await servePage(page, { + scriptTag: ` +`, + }); + + await page.waitForFunction(() => window.__esm); + const [esm, cdn] = await page.evaluate(() => [window.__esm, Object.getOwnPropertyNames(window.Gleap).sort()]); + expect(esm).toEqual(cdn); +}); + +test('the npm entry points load in Node without a DOM, as in server-side rendering', async () => { + const require = createRequire(import.meta.url); + const commonJs = require(`${ROOT}build/cjs/index.js`); + const { default: esm } = await import(ESM_BUNDLE); + + expect(typeof commonJs.initialize).toBe('function'); + expect(typeof esm.initialize).toBe('function'); +}); diff --git a/src/GleapAdminOrigins.test.js b/src/GleapAdminOrigins.test.js index 323710db..f3149901 100644 --- a/src/GleapAdminOrigins.test.js +++ b/src/GleapAdminOrigins.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapAdminManager from './GleapAdminManager'; import { GLEAP_ADMIN_ORIGINS, @@ -39,7 +40,8 @@ describe('admin origin allowlist', () => { expect(isGleapAdminOrigin('https://app.gleap.io')).toBe(true); }); - it.each(LOOKALIKES)('rejects %p', (origin) => { + // As objects: a title takes an array row apart into its items, so the array origin would read like a real one. + it.each(LOOKALIKES.map((origin) => ({ origin })))('rejects $origin', ({ origin }) => { expect(isGleapAdminOrigin(origin)).toBe(false); expect(resolveGleapAdminOrigin(origin)).toBe(GLEAP_DEFAULT_ADMIN_ORIGIN); }); @@ -64,11 +66,11 @@ describe('GleapAdminManager message origin', () => { GleapAdminManager.instance = undefined; manager = GleapAdminManager.getInstance(); // Keep the admin UI side effects out of the origin check. - manager.initAdminHelper = jest.fn(() => manager.injectFrame()); - manager.startPageListener = jest.fn(); + manager.initAdminHelper = vi.fn(() => manager.injectFrame()); + manager.startPageListener = vi.fn(); listeners = []; const add = window.addEventListener.bind(window); - jest.spyOn(window, 'addEventListener').mockImplementation((type, fn, opts) => { + vi.spyOn(window, 'addEventListener').mockImplementation((type, fn, opts) => { if (type === 'message') listeners.push(fn); return add(type, fn, opts); }); @@ -77,7 +79,7 @@ describe('GleapAdminManager message origin', () => { afterEach(() => { listeners.forEach((fn) => window.removeEventListener('message', fn)); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); it.each(['https://app.gleap.ai.evil.com', 'https://evilgleap.ai', 'https://example.com'])( diff --git a/src/GleapAiChatbarManager.test.js b/src/GleapAiChatbarManager.test.js index 1e82fa1a..c07b1d7f 100644 --- a/src/GleapAiChatbarManager.test.js +++ b/src/GleapAiChatbarManager.test.js @@ -1,26 +1,27 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { GleapFrameManager, GleapSession, GleapTabCommunication } from './Gleap'; import GleapAiChatbarManager from './GleapAiChatbarManager'; // Keep the barrel + helper imports light (no DOM bootstrap, no SDK_VERSION global). // The manager only reaches for GleapSession/GleapTabCommunication on the paths under // test here; the other managers just need to exist so the module resolves. -jest.mock('./Gleap', () => ({ - GleapFrameManager: { getInstance: jest.fn(() => ({})) }, - GleapConfigManager: { getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })) }, - GleapSession: { getInstance: jest.fn() }, - GleapEventManager: { notifyEvent: jest.fn() }, - GleapTranslationManager: { getInstance: jest.fn(() => ({ getOverrideLanguage: () => null })) }, - GleapTabCommunication: { getInstance: jest.fn() }, +vi.mock('./Gleap', () => ({ + GleapFrameManager: { getInstance: vi.fn(() => ({})) }, + GleapConfigManager: { getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })) }, + GleapSession: { getInstance: vi.fn() }, + GleapEventManager: { notifyEvent: vi.fn() }, + GleapTranslationManager: { getInstance: vi.fn(() => ({ getOverrideLanguage: () => null })) }, + GleapTabCommunication: { getInstance: vi.fn() }, })); -jest.mock('./GleapAgentToolManager', () => ({ +vi.mock('./GleapAgentToolManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ getAgentTools: () => [] })) }, + default: { getInstance: vi.fn(() => ({ getAgentTools: () => [] })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), - runFunctionWhenDomIsReady: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), + runFunctionWhenDomIsReady: vi.fn(), })); let sendMessageMock; @@ -28,7 +29,7 @@ let messageHandler; // the window 'message' listener registered by _listenForMes // A fake chatbar iframe whose contentWindow captures every posted message. const attachReadyFrame = (manager) => { - const contentWindow = { postMessage: jest.fn() }; + const contentWindow = { postMessage: vi.fn() }; manager.chatbarFrame = { contentWindow }; manager.comReady = true; return contentWindow; @@ -46,13 +47,13 @@ beforeEach(() => { // constructor's _listenForMessages / _listenForOutsideClicks, capturing the // 'message' handler so we can simulate inbound frame messages. global.window = { - addEventListener: jest.fn((type, handler) => { + addEventListener: vi.fn((type, handler) => { if (type === 'message') messageHandler = handler; }), }; - global.document = { addEventListener: jest.fn() }; + global.document = { addEventListener: vi.fn() }; - sendMessageMock = jest.fn(); + sendMessageMock = vi.fn(); GleapTabCommunication.getInstance.mockReturnValue({ sendMessage: sendMessageMock }); GleapSession.getInstance.mockReturnValue({ session: { gleapId: 'user-1' } }); @@ -164,7 +165,7 @@ describe('inbound chatbar-notification-read (from the frame)', () => { attachReadyFrame(manager); messageHandler({ - source: { postMessage: jest.fn() }, // some other window + source: { postMessage: vi.fn() }, // some other window data: JSON.stringify({ name: 'chatbar-notification-read' }), }); diff --git a/src/GleapBannerManager.test.js b/src/GleapBannerManager.test.js index 3c2f7320..99b20fe0 100644 --- a/src/GleapBannerManager.test.js +++ b/src/GleapBannerManager.test.js @@ -1,22 +1,23 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapBannerManager, { bodyClipsInlineBanner, closedBannerEventName } from './GleapBannerManager'; -const mockUrlHandler = jest.fn(); -const mockLogEvent = jest.fn(); -const mockStreamEvents = jest.fn(); +const mockUrlHandler = vi.fn(); +const mockLogEvent = vi.fn(); +const mockStreamEvents = vi.fn(); const mockSession = { session: { gleapId: 'gleap-1' } }; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, - GleapFrameManager: { getInstance: jest.fn(() => ({ urlHandler: mockUrlHandler })) }, - GleapSession: { getInstance: jest.fn(() => mockSession) }, - GleapStreamedEvent: { getInstance: jest.fn(() => ({ logEvent: mockLogEvent, streamEvents: mockStreamEvents })) }, + GleapFrameManager: { getInstance: vi.fn(() => ({ urlHandler: mockUrlHandler })) }, + GleapSession: { getInstance: vi.fn(() => mockSession) }, + GleapStreamedEvent: { getInstance: vi.fn(() => ({ logEvent: mockLogEvent, streamEvents: mockStreamEvents })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), })); const style = (overflowX, overflowY = overflowX) => ({ overflowX, overflowY }); diff --git a/src/GleapCSPNonce.test.js b/src/GleapCSPNonce.test.js index d3cb899f..2ac4c083 100644 --- a/src/GleapCSPNonce.test.js +++ b/src/GleapCSPNonce.test.js @@ -1,16 +1,14 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, afterEach } from 'vitest'; // The nonce is auto-detected at module-evaluation time (document.currentScript is only // readable then), so every detection test has to require the module with the DOM already // in the state under test — hence the isolated re-require instead of a top-level import. -const loadHelper = () => { - let helper; - jest.isolateModules(() => { - helper = require('./GleapHelper'); - }); - return helper; +const loadHelper = async () => { + vi.resetModules(); + return import('./GleapHelper'); }; const addSdkScript = (nonce, { hideAttribute = false } = {}) => { @@ -35,12 +33,12 @@ const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); // bootstrapGleapFrame writes into iframe.contentDocument. Replacing it with a spy is what // lets us assert on the exact markup — the whole point of the fix is what lands in there. const bootstrapAndCaptureMarkup = async (helper, html, url = 'https://messenger-app.gleap.io/') => { - const writtenDoc = { open: jest.fn(), write: jest.fn(), close: jest.fn() }; + const writtenDoc = { open: vi.fn(), write: vi.fn(), close: vi.fn() }; const iframe = document.createElement('iframe'); document.body.appendChild(iframe); Object.defineProperty(iframe, 'contentDocument', { value: writtenDoc, configurable: true }); - global.fetch = jest.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); + global.fetch = vi.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); helper.bootstrapGleapFrame(iframe, url); await flush(); @@ -52,49 +50,49 @@ afterEach(() => { document.head.innerHTML = ''; document.body.innerHTML = ''; delete global.fetch; - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); describe('CSP nonce detection from the SDK script tag', () => { - test('picks up the nonce so a correctly-nonced loader needs no configuration', () => { + test('picks up the nonce so a correctly-nonced loader needs no configuration', async () => { addSdkScript('r4nd0m123'); - expect(loadHelper().getGleapCSPNonce()).toBe('r4nd0m123'); + expect((await loadHelper()).getGleapCSPNonce()).toBe('r4nd0m123'); }); // Regression: reading getAttribute('nonce') first returns "" on exactly the strict-CSP // pages this feature exists for, because browsers hide the content attribute. - test('still detects the nonce when the content attribute is hidden', () => { + test('still detects the nonce when the content attribute is hidden', async () => { addSdkScript('hidden-nonce-value', { hideAttribute: true }); - expect(loadHelper().getGleapCSPNonce()).toBe('hidden-nonce-value'); + expect((await loadHelper()).getGleapCSPNonce()).toBe('hidden-nonce-value'); }); - test('is null when the SDK tag carries no nonce', () => { + test('is null when the SDK tag carries no nonce', async () => { addSdkScript(undefined); - expect(loadHelper().getGleapCSPNonce()).toBeNull(); + expect((await loadHelper()).getGleapCSPNonce()).toBeNull(); }); - test('is null when there is no SDK tag at all', () => { - expect(loadHelper().getGleapCSPNonce()).toBeNull(); + test('is null when there is no SDK tag at all', async () => { + expect((await loadHelper()).getGleapCSPNonce()).toBeNull(); }); }); describe('setGleapCSPNonce', () => { - test('overrides the auto-detected nonce', () => { + test('overrides the auto-detected nonce', async () => { addSdkScript('detected'); - const helper = loadHelper(); + const helper = await loadHelper(); helper.setGleapCSPNonce('configured'); expect(helper.getGleapCSPNonce()).toBe('configured'); }); - test('falls back to the detected nonce when passed a rejected value', () => { + test('falls back to the detected nonce when passed a rejected value', async () => { addSdkScript('detected'); - const helper = loadHelper(); + const helper = await loadHelper(); helper.setGleapCSPNonce(null); expect(helper.getGleapCSPNonce()).toBe('detected'); }); - test('trims surrounding whitespace', () => { - const helper = loadHelper(); + test('trims surrounding whitespace', async () => { + const helper = await loadHelper(); helper.setGleapCSPNonce(' spaced-nonce '); expect(helper.getGleapCSPNonce()).toBe('spaced-nonce'); }); @@ -105,17 +103,17 @@ describe('setGleapCSPNonce', () => { ['a space-separated injection', 'abc onload=alert(1)'], ['a non-string', { nonce: 'abc' }], ['an empty string', ''], - ])('rejects %s', (_label, value) => { - const helper = loadHelper(); + ])('rejects %s', async (_label, value) => { + const helper = await loadHelper(); helper.setGleapCSPNonce(value); expect(helper.getGleapCSPNonce()).toBeNull(); }); }); describe('applyGleapCSPNonce', () => { - test('sets both the attribute and the IDL property on a created '); }); @@ -179,7 +177,7 @@ describe('bootstrapGleapFrame — nonce stamping on the written document', () => test('still sets the SPA route before the app bundle runs', async () => { addSdkScript('order-nonce'); const { markup } = await bootstrapAndCaptureMarkup( - loadHelper(), + await loadHelper(), APP_HTML, 'https://messenger-app.gleap.io/conversation' ); @@ -191,7 +189,7 @@ describe('bootstrapGleapFrame — nonce stamping on the written document', () => test('does not double-stamp a tag that already carries a nonce', async () => { addSdkScript('dedupe-nonce'); const { markup } = await bootstrapAndCaptureMarkup( - loadHelper(), + await loadHelper(), '' ); @@ -201,14 +199,14 @@ describe('bootstrapGleapFrame — nonce stamping on the written document', () => // Non-CSP pages are the overwhelming majority — they must keep byte-identical markup. test('writes unchanged markup when there is no nonce', async () => { - const { markup } = await bootstrapAndCaptureMarkup(loadHelper(), APP_HTML); + const { markup } = await bootstrapAndCaptureMarkup(await loadHelper(), APP_HTML); expect(markup).not.toContain('nonce'); expect(markup).toContain(''; - global.fetch = jest.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); + global.fetch = vi.fn(() => Promise.resolve({ ok: true, text: () => Promise.resolve(html) })); helper.bootstrapGleapFrame(iframe, 'https://messenger-app.gleap.io/'); await flush(); return { writtenDoc, violationListener: listeners['securitypolicyviolation'] }; }; test('a CSP violation inside the bootstrapped frame is surfaced with URI and directive', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); - const helper = loadHelper(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const helper = await loadHelper(); const { writtenDoc, violationListener } = await bootstrapAndCaptureViolationListener(helper); @@ -323,8 +321,8 @@ describe('bootstrapGleapFrame — CSP/network failure diagnostics', () => { }); test('duplicate violations warn once; Report-Only violations stay silent', async () => { - const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); - const helper = loadHelper(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const helper = await loadHelper(); const { violationListener } = await bootstrapAndCaptureViolationListener(helper); diff --git a/src/GleapCaptureLogs.test.js b/src/GleapCaptureLogs.test.js index edde2049..606d26dd 100644 --- a/src/GleapCaptureLogs.test.js +++ b/src/GleapCaptureLogs.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach } from 'vitest'; // Background log collection sends only what a bug report carries, only what the request asks for, // and nothing when the app switched it off (Gleap.setRemoteLogCollectionEnabled(false)). @@ -9,9 +10,9 @@ const mockFlowConfig = { enableWebReplays: true, capture: {} }; const mockReplay = { startDate: 1, events: [{ type: 4, data: { href: 'https://app.test' } }], packed: false, type: 'rrweb' }; const iso = (ms) => new Date(ms).toISOString(); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { openConversation: jest.fn(), open: jest.fn() }, + default: { openConversation: vi.fn(), open: vi.fn() }, GleapConfigManager: { getInstance: () => ({ getFlowConfig: () => mockFlowConfig, onConfigLoaded: (callback) => callback() }), }, @@ -39,7 +40,7 @@ jest.mock('./Gleap', () => ({ getInstance: () => ({ session: { gleapId: 'g1' }, sdkKey: 'key', apiUrl: 'https://api.test', injectSession: () => {} }), }, GleapFrameManager: { - getInstance: () => ({ sendMessage: jest.fn(), setCaptureHidden: jest.fn(), setCaptureEditorOpen: jest.fn() }), + getInstance: () => ({ sendMessage: vi.fn(), setCaptureHidden: vi.fn(), setCaptureEditorOpen: vi.fn() }), }, GleapTranslationManager: { getInstance: () => ({ isRTLLayout: false }) }, })); @@ -135,21 +136,21 @@ describe('log requests from the websocket', () => { const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); - beforeEach(() => { - jest.resetModules(); - jest.doMock('./GleapCaptureApi', () => { - const actual = jest.requireActual('./GleapCaptureApi'); + beforeEach(async () => { + vi.resetModules(); + vi.doMock('./GleapCaptureApi', async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, - claimCaptureRequest: jest.fn(() => Promise.resolve({ status: 200, data: { claimedElsewhere: false } })), - postCaptureLogs: jest.fn(() => Promise.resolve({ status: 200, data: {} })), - reportCaptureEvent: jest.fn(() => Promise.resolve({ status: 200, data: {} })), + claimCaptureRequest: vi.fn(() => Promise.resolve({ status: 200, data: { claimedElsewhere: false } })), + postCaptureLogs: vi.fn(() => Promise.resolve({ status: 200, data: {} })), + reportCaptureEvent: vi.fn(() => Promise.resolve({ status: 200, data: {} })), }; }); - api = require('./GleapCaptureApi'); - const settings = require('./GleapCaptureSettings'); + api = await import('./GleapCaptureApi'); + const settings = await import('./GleapCaptureSettings'); settings.setRemoteLogCollectionEnabled(true); - manager = new (require('./GleapCaptureManager').default)(); + manager = new (await import('./GleapCaptureManager')).default(); mockFlowConfig.capture = {}; }); @@ -170,7 +171,7 @@ describe('log requests from the websocket', () => { }); test('switched off by the app: answered "unsupported", nothing collected', async () => { - require('./GleapCaptureSettings').setRemoteLogCollectionEnabled(false); + (await import('./GleapCaptureSettings')).setRemoteLogCollectionEnabled(false); manager.handleServerRequest(request('cr-2')); await flush(); @@ -197,7 +198,7 @@ describe('log requests from the websocket', () => { }); test('logs along with a screenshot or recording: none when the app switched log collection off', async () => { - const settings = require('./GleapCaptureSettings'); + const settings = await import('./GleapCaptureSettings'); const session = { options: { attachLogs: true } }; settings.setRemoteLogCollectionEnabled(false); diff --git a/src/GleapCaptureMasking.test.js b/src/GleapCaptureMasking.test.js index ecde78eb..8d1e70df 100644 --- a/src/GleapCaptureMasking.test.js +++ b/src/GleapCaptureMasking.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeAll, afterAll } from 'vitest'; // What capture requests must keep private: the black boxes painted over screenshots, and the page // recording (rrweb) used where there is no screen capture. Both follow the rules bug reports use @@ -8,11 +9,11 @@ const mockReplayRecorder = { customOptions: {}, - pauseForCapture: jest.fn(() => false), - resumeAfterCapture: jest.fn(), + pauseForCapture: vi.fn(() => false), + resumeAfterCapture: vi.fn(), }; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapNetworkIntercepter: { getInstance: () => ({ getRequests: () => [], stopped: false, setStopped: () => {} }) }, diff --git a/src/GleapClickListener.test.js b/src/GleapClickListener.test.js index 4d9b9767..d264c7df 100644 --- a/src/GleapClickListener.test.js +++ b/src/GleapClickListener.test.js @@ -1,31 +1,30 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; // GleapClickListener pulls the frame/console managers in from the main Gleap module, // which drags in the whole SDK — mock it so the listener can be tested on its own. -const mockHandleGleapLink = jest.fn(); -const mockAddLog = jest.fn(); -const mockIsOpened = jest.fn(() => true); +const mockHandleGleapLink = vi.fn(); +const mockAddLog = vi.fn(); +const mockIsOpened = vi.fn(() => true); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ handleGleapLink: (...args) => mockHandleGleapLink(...args), GleapConsoleLogManager: { getInstance: () => ({ addLog: mockAddLog }) }, GleapFrameManager: { getInstance: () => ({ isOpened: mockIsOpened }) }, })); -jest.mock('./GleapHelper', () => ({ +vi.mock('./GleapHelper', () => ({ getDOMElementDescription: () => 'element', })); const CHECKLIST_LINK = 'gleap://checklist/6739f47e013864770e120adf'; -const startListener = () => { - let GleapClickListener; - jest.isolateModules(() => { - GleapClickListener = require('./GleapClickListener').default; - }); - // The singleton is per-module-registry, so isolateModules gives a fresh one each time. +const startListener = async () => { + vi.resetModules(); + const { default: GleapClickListener } = await import('./GleapClickListener'); + // The singleton is per-module-registry, so a fresh registry gives a fresh one each time. GleapClickListener.getInstance().start(); }; @@ -42,9 +41,9 @@ describe('GleapClickListener gleap:// links', () => { mockAddLog.mockClear(); }); - it('handles a click directly on the anchor', () => { + it('handles a click directly on the anchor', async () => { document.body.innerHTML = `Start checklist`; - startListener(); + await startListener(); const event = clickAndCapture(document.getElementById('link')); @@ -52,11 +51,11 @@ describe('GleapClickListener gleap:// links', () => { expect(event.defaultPrevented).toBe(true); }); - it('handles a click on a formatted child inside the anchor', () => { + it('handles a click on a formatted child inside the anchor', async () => { // Rich-text editors wrap link text in /, so the click target is // the child, not the anchor itself. document.body.innerHTML = `Start checklist`; - startListener(); + await startListener(); const event = clickAndCapture(document.getElementById('child')); @@ -64,18 +63,18 @@ describe('GleapClickListener gleap:// links', () => { expect(event.defaultPrevented).toBe(true); }); - it('handles a click on a deeply nested icon inside the anchor', () => { + it('handles a click on a deeply nested icon inside the anchor', async () => { document.body.innerHTML = `go`; - startListener(); + await startListener(); clickAndCapture(document.getElementById('icon')); expect(mockHandleGleapLink).toHaveBeenCalledWith(CHECKLIST_LINK); }); - it('ignores anchors that are not gleap:// links', () => { + it('ignores anchors that are not gleap:// links', async () => { document.body.innerHTML = `Normal link`; - startListener(); + await startListener(); const event = clickAndCapture(document.getElementById('link')); @@ -83,9 +82,9 @@ describe('GleapClickListener gleap:// links', () => { expect(event.defaultPrevented).toBe(false); }); - it('ignores clicks outside of any anchor', () => { + it('ignores clicks outside of any anchor', async () => { document.body.innerHTML = `
Just text
`; - startListener(); + await startListener(); clickAndCapture(document.getElementById('plain')); diff --git a/src/GleapCopilotTours.test.js b/src/GleapCopilotTours.test.js index 2a1d75aa..c2cc635b 100644 --- a/src/GleapCopilotTours.test.js +++ b/src/GleapCopilotTours.test.js @@ -1,23 +1,24 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; import GleapCopilotTours, { getJoinedIndicatorPositionClass } from './GleapCopilotTours'; // Stub the barrel so the real GleapCopilotTours loads without the rest of the SDK. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapConfigManager: { - getInstance: jest.fn(() => ({ flowConfig: { color: '#485BFF' } })), + getInstance: vi.fn(() => ({ flowConfig: { color: '#485BFF' } })), }, - GleapTranslationManager: { translateText: jest.fn((key) => key) }, + GleapTranslationManager: { translateText: vi.fn((key) => key) }, })); -jest.mock('./GleapHelper', () => ({ applyGleapCSPNonce: jest.fn() })); -jest.mock('./GleapInputFiller', () => ({ typeIntoElement: jest.fn() })); -jest.mock('./UI', () => ({ - calculateContrast: jest.fn(() => '#ffffff'), - loadIcon: jest.fn(() => ''), +vi.mock('./GleapHelper', () => ({ applyGleapCSPNonce: vi.fn() })); +vi.mock('./GleapInputFiller', () => ({ typeIntoElement: vi.fn() })); +vi.mock('./UI', () => ({ + calculateContrast: vi.fn(() => '#ffffff'), + loadIcon: vi.fn(() => ''), })); const localStorageKey = 'gleap-tour-data'; @@ -43,12 +44,12 @@ const installAudioDouble = () => { createdAudioSources = []; playBehaviour = 'resolve'; - window.Audio = jest.fn(function (src) { + window.Audio = vi.fn(function (src) { createdAudioSources.push(src); this.muted = false; - this.pause = jest.fn(); - this.addEventListener = jest.fn(); - this.play = jest.fn(() => { + this.pause = vi.fn(); + this.addEventListener = vi.fn(); + this.play = vi.fn(() => { if (playBehaviour === 'reject') return Promise.reject(new DOMException('blocked', 'NotAllowedError')); if (playBehaviour === 'never') return new Promise(() => {}); return Promise.resolve(); @@ -67,7 +68,7 @@ const newTour = (config = buildConfig(), tourId = 'tour-1') => { // start() awaits the autoplay probe (a real promise) before touching the DOM, so let the // microtask queue drain between advancing the fake timers. const flush = async (ms = 0) => { - if (ms > 0) jest.advanceTimersByTime(ms); + if (ms > 0) vi.advanceTimersByTime(ms); await Promise.resolve(); await Promise.resolve(); }; @@ -78,8 +79,8 @@ beforeEach(() => { document.head.innerHTML = ''; installAudioDouble(); // jsdom implements neither, and the pointer positioning calls both. - window.scrollTo = jest.fn(); - Element.prototype.scrollIntoView = jest.fn(); + window.scrollTo = vi.fn(); + Element.prototype.scrollIntoView = vi.fn(); }); describe('audio state across page changes', () => { @@ -108,7 +109,7 @@ describe('audio state across page changes', () => { }); it('stays muted after a page change instead of asking the browser again', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); localStorage.setItem(localStorageKey, JSON.stringify({ tourId: 'tour-1', audioMuted: true })); const tours = newTour(); @@ -118,11 +119,11 @@ describe('audio state across page changes', () => { expect(tours.audioMuted).toBe(true); // The autoplay probe would have unmuted the tour - it must not run on a resume. expect(window.Audio).not.toHaveBeenCalled(); - jest.useRealTimers(); + vi.useRealTimers(); }); it('does not re-prompt with the unmute modal after a page change', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); localStorage.setItem(localStorageKey, JSON.stringify({ tourId: 'tour-1', audioMuted: true })); const tours = newTour(buildConfig({ showUnmuteModal: true })); @@ -130,11 +131,11 @@ describe('audio state across page changes', () => { await flush(); expect(document.querySelector('.gleap-audio-unmute-modal')).toBeNull(); - jest.useRealTimers(); + vi.useRealTimers(); }); it('falls back to the autoplay probe on a fresh start', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); playBehaviour = 'reject'; const tours = newTour(); @@ -142,13 +143,13 @@ describe('audio state across page changes', () => { await flush(); expect(tours.audioMuted).toBe(true); - jest.useRealTimers(); + vi.useRealTimers(); }); }); describe('autoplay probe', () => { it('starts the tour even when play() never settles', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); playBehaviour = 'never'; const tours = newTour(); @@ -157,13 +158,13 @@ describe('autoplay probe', () => { expect(tours.audioMuted).toBe(false); expect(document.getElementById('copilot-joined-container')).not.toBeNull(); - jest.useRealTimers(); + vi.useRealTimers(); }); }); describe('read text aloud', () => { it('skips the stored voice clip when the setting is off', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(buildConfig({ playVoice: false })); tours.audioMuted = false; tours.setupCopilotTour(); @@ -172,11 +173,11 @@ describe('read text aloud', () => { await flush(100); expect(createdAudioSources).not.toContain('https://example.com/1.mp3'); - jest.useRealTimers(); + vi.useRealTimers(); }); it('plays the stored voice clip when the setting is on', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(); tours.audioMuted = false; tours.setupCopilotTour(); @@ -185,13 +186,13 @@ describe('read text aloud', () => { await flush(100); expect(createdAudioSources).toContain('https://example.com/1.mp3'); - jest.useRealTimers(); + vi.useRealTimers(); }); }); describe('step message flattening', () => { const bubbleText = async (message) => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(buildConfig({ steps: [{ selector: '', message, type: 'post', mode: 'BUTTON' }] })); tours.setupCopilotTour(); @@ -199,7 +200,7 @@ describe('step message flattening', () => { await flush(100); const text = document.getElementById('copilot-info-bubble-content').textContent; - jest.useRealTimers(); + vi.useRealTimers(); return text; }; @@ -269,7 +270,7 @@ describe('joined indicator position', () => { }); it('pins the indicator top-right when the tour config has no position', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(); tours.start(); @@ -277,11 +278,11 @@ describe('joined indicator position', () => { const indicator = document.getElementById('copilot-joined-container'); expect(positionClasses(indicator)).toEqual(['copilot-joined-container--top-right']); - jest.useRealTimers(); + vi.useRealTimers(); }); it('pins the indicator to the configured corner', async () => { - jest.useFakeTimers(); + vi.useFakeTimers(); const tours = newTour(buildConfig({ joinedIndicatorPosition: 'BOTTOM_LEFT' })); tours.start(); @@ -292,6 +293,6 @@ describe('joined indicator position', () => { expect(document.getElementById('copilot-tour-styles').textContent).toContain( '.copilot-joined-container--bottom-left {', ); - jest.useRealTimers(); + vi.useRealTimers(); }); }); diff --git a/src/GleapFeedback.test.js b/src/GleapFeedback.test.js index 01dfb330..7072784a 100644 --- a/src/GleapFeedback.test.js +++ b/src/GleapFeedback.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect, vi, beforeEach } from 'vitest'; import GleapFeedback from './GleapFeedback'; import { startScreenCapture } from './ScreenCapture'; import { GleapScreenRecorder } from './GleapScreenRecorder'; @@ -10,12 +11,12 @@ const REPLAY_OPTIONS = { maskAllInputs: true }; // The SDK's global data; tests add to it (reset in beforeEach). const mockGlobalData = {}; -jest.mock('./Gleap', () => { - const manager = (methods) => ({ getInstance: jest.fn(() => methods) }); +vi.mock('./Gleap', () => { + const manager = (methods) => ({ getInstance: vi.fn(() => methods) }); return { __esModule: true, default: { - getInstance: jest.fn(() => ({ + getInstance: vi.fn(() => ({ getGlobalDataItem: (key) => mockGlobalData[key] ?? null, setGlobalDataItem: (key, value) => { mockGlobalData[key] = value; @@ -25,7 +26,7 @@ jest.mock('./Gleap', () => { }, GleapConsoleLogManager: manager({ getLogs: () => [{ log: 'hello' }] }), GleapStreamedEvent: manager({ getEventArray: () => [] }), - GleapSession: manager({ apiUrl: 'https://api.gleap.io', injectSession: jest.fn() }), + GleapSession: manager({ apiUrl: 'https://api.gleap.io', injectSession: vi.fn() }), GleapCustomDataManager: manager({ getCustomData: () => ({}), getTicketAttributes: () => ({}) }), GleapMetaDataManager: manager({ getMetaData: () => ({}) }), GleapNetworkIntercepter: manager({ getRequests: () => [{ url: 'https://app.example.com/api' }] }), @@ -34,11 +35,11 @@ jest.mock('./Gleap', () => { }; }); -jest.mock('./ScreenCapture', () => ({ - startScreenCapture: jest.fn(() => Promise.resolve({ html: '' })), +vi.mock('./ScreenCapture', () => ({ + startScreenCapture: vi.fn(() => Promise.resolve({ html: '' })), })); -jest.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: { uploadFile: jest.fn() } })); +vi.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: { uploadFile: vi.fn() } })); // Minimal XHR double: tests drive responses explicitly via respond(). class MockXhr { @@ -80,7 +81,7 @@ const send = async ({ isSilent = false, excludeData = {} } = {}) => { undefined, undefined ).sendFeedback(); - const settled = jest.fn(); + const settled = vi.fn(); result.then( (value) => settled('resolved', value), () => settled('rejected') diff --git a/src/GleapFrameManager.test.js b/src/GleapFrameManager.test.js index 3f907bb7..0a006b41 100644 --- a/src/GleapFrameManager.test.js +++ b/src/GleapFrameManager.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { loadFromGleapCache, saveToGleapCache } from './GleapHelper'; import GleapFrameManager, { FRAME_LOAD_TIMEOUT_MS } from './GleapFrameManager'; @@ -8,42 +9,45 @@ import GleapFrameManager, { FRAME_LOAD_TIMEOUT_MS } from './GleapFrameManager'; // Webpack global. flowConfig is a mutable object so tests can flip // hideExpandButton the way a config reload would. const mockFlowConfig = {}; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ setGlobalDataItem: jest.fn() })) }, - GleapConfigManager: { getInstance: jest.fn(() => ({ getFlowConfig: () => mockFlowConfig })) }, + default: { getInstance: vi.fn(() => ({ setGlobalDataItem: vi.fn() })) }, + GleapConfigManager: { getInstance: vi.fn(() => ({ getFlowConfig: () => mockFlowConfig })) }, GleapFeedbackButtonManager: { - getInstance: jest.fn(() => ({ + getInstance: vi.fn(() => ({ buttonHidden: null, - updateNotificationBadge: jest.fn(), - updateFeedbackButtonState: jest.fn(), + updateNotificationBadge: vi.fn(), + updateFeedbackButtonState: vi.fn(), })), }, GleapTranslationManager: { - getInstance: jest.fn(() => ({ isRTLLayout: false, getOverrideLanguage: () => '' })), + getInstance: vi.fn(() => ({ isRTLLayout: false, getOverrideLanguage: () => '' })), }, GleapNotificationManager: { - getInstance: jest.fn(() => ({ clearAllNotifications: jest.fn(), reloadNotificationsFromCache: jest.fn() })), + getInstance: vi.fn(() => ({ clearAllNotifications: vi.fn(), reloadNotificationsFromCache: vi.fn() })), }, - GleapEventManager: { notifyEvent: jest.fn() }, - GleapBannerManager: { getInstance: jest.fn(() => ({})) }, - GleapSession: { getInstance: jest.fn(() => ({ getSession: () => ({}) })) }, + GleapEventManager: { notifyEvent: vi.fn() }, + GleapBannerManager: { getInstance: vi.fn(() => ({})) }, + GleapSession: { getInstance: vi.fn(() => ({ getSession: () => ({}) })) }, + // Not part of these tests: the frame manager skips capture messages without it. Vitest throws on an export a + // mock leaves out, so it is listed as absent. + GleapCaptureManager: undefined, })); -jest.mock('./GleapAgentToolManager', () => ({ +vi.mock('./GleapAgentToolManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ getAgentTools: () => [] })) }, + default: { getInstance: vi.fn(() => ({ getAgentTools: () => [] })) }, })); -jest.mock('./GleapHelper', () => ({ - loadFromGleapCache: jest.fn(() => null), - saveToGleapCache: jest.fn(), - bootstrapGleapFrame: jest.fn(), - runFunctionWhenDomIsReady: jest.fn(), +vi.mock('./GleapHelper', () => ({ + loadFromGleapCache: vi.fn(() => null), + saveToGleapCache: vi.fn(), + bootstrapGleapFrame: vi.fn(), + runFunctionWhenDomIsReady: vi.fn(), })); -jest.mock('./UI', () => ({ - widgetLoaderMarkup: jest.fn(() => ''), +vi.mock('./UI', () => ({ + widgetLoaderMarkup: vi.fn(() => ''), widgetMaxHeight: 700, widgetExpandMinWidth: 768, })); @@ -66,7 +70,7 @@ const setup = () => { previous = fm; fm.gleapFrameContainer = document.querySelector('.gleap-frame-container'); fm.comReady = true; - postMessage = jest.spyOn(document.querySelector('.gleap-frame').contentWindow, 'postMessage').mockImplementation(() => {}); + postMessage = vi.spyOn(document.querySelector('.gleap-frame').contentWindow, 'postMessage').mockImplementation(() => {}); return fm; }; @@ -88,7 +92,7 @@ const matchWidthQuery = (query) => { beforeEach(() => { isMobile = false; viewportWidth = 1440; - window.matchMedia = jest.fn(matchWidthQuery); + window.matchMedia = vi.fn(matchWidthQuery); Object.keys(mockFlowConfig).forEach((k) => delete mockFlowConfig[k]); loadFromGleapCache.mockReset().mockReturnValue(null); saveToGleapCache.mockReset(); @@ -276,7 +280,7 @@ describe('GleapFrameManager expand/collapse window', () => { describe('GleapFrameManager url handler', () => { let open; beforeEach(() => { - open = jest.spyOn(window, 'open').mockImplementation(() => null); + open = vi.spyOn(window, 'open').mockImplementation(() => null); }); afterEach(() => open.mockRestore()); @@ -299,7 +303,7 @@ describe('GleapFrameManager url handler', () => { it('runs a custom handler for deep links but never for script URLs', () => { const fm = setup(); - const custom = jest.fn(); + const custom = vi.fn(); fm.setUrlHandler(custom); fm.urlHandler('myapp://settings', false); fm.urlHandler('javascript:alert(1)', false); @@ -335,25 +339,25 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( }; beforeEach(() => { - jest.useFakeTimers(); - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + vi.useFakeTimers(); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); warn.mockRestore(); }); it('keeps the loader up when opened again before the messenger pinged, and opens on the ping', () => { const fm = setupLoading(); fm.showWidget(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); const container = fm.gleapFrameContainer; expect(container.classList.contains(HIDDEN)).toBe(false); expect(container.classList.contains(LOADING)).toBe(true); expect(fm.widgetOpened).toBe(true); dispatch(fm, { name: 'ping' }); - jest.advanceTimersByTime(300); + vi.advanceTimersByTime(300); expect(container.classList.contains(LOADING)).toBe(false); }); @@ -363,11 +367,11 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( fm.showFrameContainer(true); fm.armFrameLoadWatchdog(frame); - jest.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); expect(frame.getAttribute('src')).toBe(fm.frameUrl); expect(fm.gleapFrameContainer).not.toBeNull(); - jest.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS); expect(fm.gleapFrameContainer).toBeNull(); expect(fm.injectedFrame).toBe(false); expect(fm.widgetOpened).toBe(false); @@ -379,7 +383,7 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( const fm = setupLoading(); fm.armFrameLoadWatchdog(fm.gleapFrame); dispatch(fm, { name: 'ping' }); - jest.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS * 2); + vi.advanceTimersByTime(FRAME_LOAD_TIMEOUT_MS * 2); expect(fm.gleapFrame.getAttribute('src')).toBeNull(); expect(fm.gleapFrameContainer).not.toBeNull(); }); @@ -397,14 +401,14 @@ describe('GleapFrameManager opens reliably (iOS: never stuck until a reload)', ( it('restarts a frame that was still loading when the page went into the back/forward cache', () => { const fm = setupLoading(); fm.showFrameContainer(true); - const inject = jest.spyOn(fm, 'injectFrame').mockImplementation(() => {}); - const instance = jest.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(fm); + const inject = vi.spyOn(fm, 'injectFrame').mockImplementation(() => {}); + const instance = vi.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(fm); fm.handlePageShow({ persisted: true }); expect(document.querySelector('.gleap-frame-container')).toBeNull(); expect(fm.injectedFrame).toBe(false); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(inject).toHaveBeenCalledTimes(1); instance.mockRestore(); }); diff --git a/src/GleapHelper.bootstrap.file.test.js b/src/GleapHelper.bootstrap.file.test.js index f4026a00..472f9462 100644 --- a/src/GleapHelper.bootstrap.file.test.js +++ b/src/GleapHelper.bootstrap.file.test.js @@ -1,7 +1,8 @@ /** - * @jest-environment jsdom - * @jest-environment-options {"url": "file:///C:/Users/me/AppData/Local/Programs/twinmind/resources/app.asar/dist/renderer/index.html"} + * @vitest-environment jsdom + * @vitest-environment-options {"url": "file:///C:/Users/me/AppData/Local/Programs/twinmind/resources/app.asar/dist/renderer/index.html"} */ +import { describe, it, expect, vi, afterEach } from 'vitest'; import { bootstrapGleapFrame, isHttpDocument } from './GleapHelper'; const MODAL_URL = 'https://outboundmedia.gleap.io/modal'; @@ -19,7 +20,7 @@ describe('bootstrapGleapFrame inside a file:// host document', () => { }); it('skips the about:blank bootstrap and loads the frame directly', async () => { - global.fetch = jest.fn(); + global.fetch = vi.fn(); const iframe = document.createElement('iframe'); document.body.appendChild(iframe); diff --git a/src/GleapHelper.bootstrap.test.js b/src/GleapHelper.bootstrap.test.js index f2760522..3aceac85 100644 --- a/src/GleapHelper.bootstrap.test.js +++ b/src/GleapHelper.bootstrap.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { bootstrapGleapFrame, warnOnCSPViolation, isHttpDocument, ROUTE_FAILED_EVENT } from './GleapHelper'; const MODAL_URL = 'https://outboundmedia.gleap.io/modal'; @@ -20,18 +21,18 @@ let warn; beforeEach(() => { document.body.innerHTML = ''; - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); delete global.fetch; }); describe('bootstrapGleapFrame on a regular http(s) page', () => { it('fetches the app document from the Gleap origin', async () => { expect(isHttpDocument()).toBe(true); - global.fetch = jest.fn(() => okResponse('')); + global.fetch = vi.fn(() => okResponse('')); const iframe = appendFrame(); bootstrapGleapFrame(iframe, MODAL_URL); @@ -41,7 +42,7 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { }); it('keeps the bootstrapped document when the app route was applied', async () => { - global.fetch = jest.fn(() => okResponse('')); + global.fetch = vi.fn(() => okResponse('')); const iframe = appendFrame(); // Give the frame a same-origin http document URL, as browsers do after doc.open() (jsdom // keeps about:blank, against which no path can be set — see the next test). @@ -59,9 +60,9 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { // replaceState is refused on some origins (sandboxed, file://, exotic schemes — and jsdom's // about:blank). The route script swallows that, and the app router would then match // nothing: a blank frame. - global.fetch = jest.fn(() => okResponse('')); + global.fetch = vi.fn(() => okResponse('')); const iframe = appendFrame(); - const listener = jest.fn(); + const listener = vi.fn(); iframe.addEventListener(ROUTE_FAILED_EVENT, listener); bootstrapGleapFrame(iframe, MODAL_URL); @@ -72,7 +73,7 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { }); it('loads the frame directly when the fetch fails', async () => { - global.fetch = jest.fn(() => Promise.reject(new TypeError('Failed to fetch'))); + global.fetch = vi.fn(() => Promise.reject(new TypeError('Failed to fetch'))); const iframe = appendFrame(); bootstrapGleapFrame(iframe, MODAL_URL); @@ -83,8 +84,8 @@ describe('bootstrapGleapFrame on a regular http(s) page', () => { }); it('never assigns src twice, however many checks conclude the same thing', async () => { - global.fetch = jest.fn(() => okResponse('')); - const setSrc = jest.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); + global.fetch = vi.fn(() => okResponse('')); + const setSrc = vi.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); const iframe = appendFrame(); // Route failure (about:blank, see above) and a CSP block on the bundle, back to back. bootstrapGleapFrame(iframe, MODAL_URL); @@ -109,7 +110,7 @@ describe('warnOnCSPViolation fallback hook', () => { beforeEach(() => { doc = document.implementation.createHTMLDocument('frame'); - onBlocked = jest.fn(); + onBlocked = vi.fn(); warnOnCSPViolation(doc, { baseHref: BASE_HREF, onBlocked }); }); diff --git a/src/GleapHelper.test.js b/src/GleapHelper.test.js index e7d78c4c..4d0c82ad 100644 --- a/src/GleapHelper.test.js +++ b/src/GleapHelper.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect } from 'vitest'; import { cookieDomainFor, eraseGleapCookie, flattenCompany, formatRelativeTime, setGleapCookie } from './GleapHelper'; describe('formatRelativeTime — the notification meta line', () => { @@ -339,7 +340,7 @@ describe('cookie domain', () => { ['[2001:db8::7]:443', null], ['::1', null], ['', null], - ])('cookieDomainFor(%p) is %p', (host, domain) => { + ])('cookieDomainFor(%j) is %j', (host, domain) => { expect(cookieDomainFor(host)).toBe(domain); }); diff --git a/src/GleapHighlight.test.js b/src/GleapHighlight.test.js index bc47550d..7d08b44a 100644 --- a/src/GleapHighlight.test.js +++ b/src/GleapHighlight.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach, beforeAll } from 'vitest'; import { checkForHighlightParam, clearHighlight, @@ -35,7 +36,7 @@ describe('GleapHighlight', () => { afterEach(() => { clearHighlight(); - jest.useRealTimers(); + vi.useRealTimers(); }); describe('scoreLabel', () => { @@ -95,7 +96,7 @@ describe('GleapHighlight', () => { describe('showHighlight', () => { beforeAll(() => { - Element.prototype.scrollIntoView = jest.fn(); + Element.prototype.scrollIntoView = vi.fn(); }); it('outlines the element and removes the outline on the next click', () => { @@ -110,16 +111,16 @@ describe('GleapHighlight', () => { }); it('fades out on its own', () => { - jest.useFakeTimers(); + vi.useFakeTimers(); showHighlight(document.getElementById('save')); - jest.advanceTimersByTime(7000); + vi.advanceTimersByTime(7000); expect(document.getElementById('gleap-highlight-overlay')).toBeNull(); }); }); describe('checkForHighlightParam', () => { it('strips the parameter, keeps the rest of the URL and the router state, and waits for the element', () => { - jest.useFakeTimers(); + vi.useFakeTimers(); document.body.innerHTML = '
'; window.history.replaceState({ route: 'settings' }, '', '/account/settings/publishing?tab=1&gleap_highlight=Post+as+draft#top'); @@ -135,7 +136,7 @@ describe('GleapHighlight', () => { const original = Element.prototype.getClientRects; Element.prototype.getClientRects = () => [{}]; try { - jest.advanceTimersByTime(400); + vi.advanceTimersByTime(400); expect(document.getElementById('gleap-highlight-overlay')).not.toBeNull(); } finally { Element.prototype.getClientRects = original; diff --git a/src/GleapInitialize.test.js b/src/GleapInitialize.test.js index 92c5b85c..b77c0dfa 100644 --- a/src/GleapInitialize.test.js +++ b/src/GleapInitialize.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapSession } from './Gleap'; // initialize() names the key "Project ID"; the positional form keeps working. @@ -12,8 +13,8 @@ describe('Gleap.initialize(projectId)', () => { Gleap.getInstance().initialized = false; GleapSession.instance = undefined; // startSession is an instance arrow property: stub it on the fresh singleton. - startSpy = jest.spyOn(GleapSession.getInstance(), 'startSession').mockImplementation(() => {}); - warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + startSpy = vi.spyOn(GleapSession.getInstance(), 'startSession').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { diff --git a/src/GleapInputFiller.test.js b/src/GleapInputFiller.test.js index defb493c..74f9437e 100644 --- a/src/GleapInputFiller.test.js +++ b/src/GleapInputFiller.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { resolveInputTarget, setInputValue, typeIntoElement } from './GleapInputFiller'; const realInputValue = (element) => @@ -111,11 +112,11 @@ describe('setInputValue', () => { describe('typeIntoElement', () => { beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); document.body.innerHTML = ''; }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); it('types the exact value and fires one input event per character plus a final change', () => { @@ -125,10 +126,10 @@ describe('typeIntoElement', () => { const changeEvents = []; input.addEventListener('input', (e) => inputEvents.push(e.target.value)); input.addEventListener('change', (e) => changeEvents.push(e.target.value)); - const onDone = jest.fn(); + const onDone = vi.fn(); typeIntoElement(input, 'Oslo', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(input.value).toBe('Oslo'); expect(inputEvents).toEqual(['O', 'Os', 'Osl', 'Oslo']); @@ -142,7 +143,7 @@ describe('typeIntoElement', () => { document.body.appendChild(input); typeIntoElement(input, 'new', { charDelay: 100 }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(input.value).toBe('new'); }); @@ -154,7 +155,7 @@ describe('typeIntoElement', () => { document.body.appendChild(field); typeIntoElement(field, 'Oslo', { charDelay: 100 }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(field.querySelector('input').value).toBe('Oslo'); }); @@ -162,10 +163,10 @@ describe('typeIntoElement', () => { it('still calls onDone when there is nothing to type into, so the tour never stalls', () => { const div = document.createElement('div'); document.body.appendChild(div); - const onDone = jest.fn(); + const onDone = vi.fn(); typeIntoElement(div, 'Oslo', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(onDone).toHaveBeenCalledTimes(1); }); @@ -181,11 +182,11 @@ describe('typeIntoElement', () => { get: () => '', configurable: true, }); - const onDone = jest.fn(); + const onDone = vi.fn(); expect(() => { typeIntoElement(editable, 'Oslo', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); }).not.toThrow(); expect(onDone).toHaveBeenCalledTimes(1); }); @@ -193,10 +194,10 @@ describe('typeIntoElement', () => { it('handles an empty value without hanging', () => { const input = document.createElement('input'); document.body.appendChild(input); - const onDone = jest.fn(); + const onDone = vi.fn(); typeIntoElement(input, '', { charDelay: 100, onDone }); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(input.value).toBe(''); expect(onDone).toHaveBeenCalledTimes(1); diff --git a/src/GleapInputMasking.test.js b/src/GleapInputMasking.test.js index 1159c8b2..be90b39c 100644 --- a/src/GleapInputMasking.test.js +++ b/src/GleapInputMasking.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect } from 'vitest'; import GleapReplayRecorder from './GleapReplayRecorder'; import { startScreenCapture } from './ScreenCapture'; diff --git a/src/GleapMarkerManager.test.js b/src/GleapMarkerManager.test.js index 0db57d50..9dc2485b 100644 --- a/src/GleapMarkerManager.test.js +++ b/src/GleapMarkerManager.test.js @@ -1,15 +1,16 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { test, expect, vi, beforeEach } from 'vitest'; import GleapMarkerManager from './GleapMarkerManager'; import { captureTabScreenshot, requestTabStream } from './GleapCaptureScreenshot'; import { canCaptureTab } from './GleapCaptureSettings'; // The feedback form's "Mark the bug" step takes its screenshot from the tab on Next (#228450). const mockGlobalData = {}; -const mockSendMessage = jest.fn(); +const mockSendMessage = vi.fn(); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: { getInstance: () => ({ @@ -25,12 +26,12 @@ jest.mock('./Gleap', () => ({ getInstance: () => ({ privacyOptions: () => ({ maskAllInputs: true }), maskSelectors: () => ['.secret'] }), }, })); -jest.mock('./ScreenDrawer', () => ({ ScreenDrawer: jest.fn() })); -jest.mock('./GleapScrollStopper', () => ({ GleapScrollStopper: { enableScroll: jest.fn(), disableScroll: jest.fn() } })); -jest.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: jest.fn() })); -jest.mock('./UI', () => ({ loadIcon: () => '' })); -jest.mock('./GleapCaptureSettings', () => ({ canCaptureTab: jest.fn() })); -jest.mock('./GleapCaptureScreenshot', () => ({ captureTabScreenshot: jest.fn(), requestTabStream: jest.fn() })); +vi.mock('./ScreenDrawer', () => ({ ScreenDrawer: vi.fn() })); +vi.mock('./GleapScrollStopper', () => ({ GleapScrollStopper: { enableScroll: vi.fn(), disableScroll: vi.fn() } })); +vi.mock('./GleapScreenRecorder', () => ({ GleapScreenRecorder: vi.fn() })); +vi.mock('./UI', () => ({ loadIcon: () => '' })); +vi.mock('./GleapCaptureSettings', () => ({ canCaptureTab: vi.fn() })); +vi.mock('./GleapCaptureScreenshot', () => ({ captureTabScreenshot: vi.fn(), requestTabStream: vi.fn() })); const IMAGE = { dataUrl: 'data:image/jpeg;base64,/9j/4AAQ', width: 1280, height: 720, method: 'tab' }; const STREAM_PROMISE = Promise.resolve({ id: 'tab-stream' }); @@ -55,7 +56,7 @@ beforeEach(() => { document.body.innerHTML = ''; manager = new GleapMarkerManager('screenshot'); manager.createEditorUI(); - callback = jest.fn(); + callback = vi.fn(); manager.callback = callback; }); diff --git a/src/GleapMessageSecurity.test.js b/src/GleapMessageSecurity.test.js index 04d90e05..aff98d63 100644 --- a/src/GleapMessageSecurity.test.js +++ b/src/GleapMessageSecurity.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect } from 'vitest'; import { frameTargetOrigin, isSafeNavigationUrl, isScriptUrl, originMatchesUrl } from './GleapMessageSecurity'; describe('isSafeNavigationUrl (default url handler)', () => { @@ -25,7 +26,7 @@ describe('isSafeNavigationUrl (default url handler)', () => { undefined, null, {}, - ])('rejects %p', (url) => { + ])('rejects %j', (url) => { expect(isSafeNavigationUrl(url)).toBe(false); }); }); diff --git a/src/GleapMetaDataManager.test.js b/src/GleapMetaDataManager.test.js index c83eb107..e0fc4afa 100644 --- a/src/GleapMetaDataManager.test.js +++ b/src/GleapMetaDataManager.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach } from 'vitest'; import GleapMetaDataManager from './GleapMetaDataManager'; // Normally injected by Webpack's DefinePlugin. @@ -49,7 +50,7 @@ describe('GleapMetaDataManager env data controls', () => { test('disabled env data is not gathered at all', () => { const instance = GleapMetaDataManager.getInstance(); - const collect = jest.spyOn(instance, 'collectMetaData'); + const collect = vi.spyOn(instance, 'collectMetaData'); GleapMetaDataManager.setDisableEnvData(true); diff --git a/src/GleapModalManager.test.js b/src/GleapModalManager.test.js index 0f386b2e..e353837d 100644 --- a/src/GleapModalManager.test.js +++ b/src/GleapModalManager.test.js @@ -1,21 +1,22 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapModalManager from './GleapModalManager'; // Stub the barrel so the real GleapModalManager loads without the rest of the SDK. // We only drive the modal-height contract, which reaches GleapConfigManager. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapConfigManager: { - getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })), + getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })), }, - GleapFrameManager: { getInstance: jest.fn(() => ({ urlHandler: jest.fn() })) }, + GleapFrameManager: { getInstance: vi.fn(() => ({ urlHandler: vi.fn() })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), })); const MODAL_ORIGIN = 'https://outboundmedia.gleap.io'; @@ -43,13 +44,13 @@ beforeEach(() => { document.body.className = ''; setViewportHeight(800); manager = new GleapModalManager(); - jest.spyOn(manager, '_postMessage').mockImplementation(() => {}); + vi.spyOn(manager, '_postMessage').mockImplementation(() => {}); manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); }); afterEach(() => { manager.hideModal(); - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); const postedMessages = (name) => manager._postMessage.mock.calls.map((c) => c[0]).filter((m) => m.name === name); diff --git a/src/GleapModalManager.watchdog.test.js b/src/GleapModalManager.watchdog.test.js index e4b50eca..df16105a 100644 --- a/src/GleapModalManager.watchdog.test.js +++ b/src/GleapModalManager.watchdog.test.js @@ -1,20 +1,21 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapModalManager, { MODAL_LOAD_TIMEOUT_MS } from './GleapModalManager'; import { bootstrapGleapFrame } from './GleapHelper'; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, GleapConfigManager: { - getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })), + getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })), }, - GleapFrameManager: { getInstance: jest.fn(() => ({ urlHandler: jest.fn() })) }, + GleapFrameManager: { getInstance: vi.fn(() => ({ urlHandler: vi.fn() })) }, })); -jest.mock('./GleapHelper', () => ({ - bootstrapGleapFrame: jest.fn(), +vi.mock('./GleapHelper', () => ({ + bootstrapGleapFrame: vi.fn(), })); const MODAL_URL = 'https://outboundmedia.gleap.io/modal'; @@ -36,19 +37,19 @@ let manager; let warn; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); document.body.innerHTML = ''; document.body.className = ''; bootstrapGleapFrame.mockReset(); - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); manager = new GleapModalManager(); - jest.spyOn(manager, '_postMessage').mockImplementation(() => {}); + vi.spyOn(manager, '_postMessage').mockImplementation(() => {}); }); afterEach(() => { manager.hideModal(); - jest.restoreAllMocks(); - jest.useRealTimers(); + vi.restoreAllMocks(); + vi.useRealTimers(); }); describe('the card stays invisible until it has content', () => { @@ -73,10 +74,10 @@ describe('load watchdog', () => { expect(bootstrapGleapFrame).toHaveBeenCalledWith(frame(), MODAL_URL); expect(frame().getAttribute('src')).toBeNull(); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 1); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 1); expect(frame().getAttribute('src')).toBeNull(); - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); expect(frame().getAttribute('src')).toBe(MODAL_URL); // Still showing — the direct load gets its own chance. expect(wrapper()).not.toBeNull(); @@ -86,7 +87,7 @@ describe('load watchdog', () => { it('takes the blank card down when the direct load does not report in either', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); expect(wrapper()).toBeNull(); expect(document.body.classList.contains('gleap-modal-open')).toBe(false); @@ -98,7 +99,7 @@ describe('load watchdog', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); emitFromModal('modal-loaded'); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); expect(frame().getAttribute('src')).toBeNull(); expect(wrapper()).not.toBeNull(); @@ -108,12 +109,12 @@ describe('load watchdog', () => { it('accepts a late modal-loaded from the direct load and keeps the card', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); expect(frame().getAttribute('src')).toBe(MODAL_URL); emitFromModal('modal-loaded'); emitFromModal('modal-height', { height: 200 }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 2); expect(wrapper()).not.toBeNull(); expect(wrapper().classList.contains('gleap-modal-wrapper--loading')).toBe(false); @@ -124,15 +125,15 @@ describe('load watchdog', () => { bootstrapGleapFrame.mockImplementation((iframe, url) => { iframe.src = url; }); - const setSrc = jest.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); + const setSrc = vi.spyOn(HTMLIFrameElement.prototype, 'src', 'set'); manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); expect(setSrc).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); expect(setSrc).toHaveBeenCalledTimes(1); // ...but it still gives up on it eventually. - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS); expect(wrapper()).toBeNull(); }); @@ -140,21 +141,21 @@ describe('load watchdog', () => { manager.showModal({ config: { steps: [{ title: 'Hi' }] } }); manager.hideModal(); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS * 3); expect(warn).not.toHaveBeenCalled(); expect(manager.modalLoadTimeout).toBeNull(); }); it('re-arms for every show, even while a previous card is still pending', () => { manager.showModal({ config: { steps: [{ title: 'first' }] } }); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 100); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 100); manager.showModal({ config: { steps: [{ title: 'second' }] } }); - jest.advanceTimersByTime(200); + vi.advanceTimersByTime(200); // The first card's timer must not have fired against the second card. expect(frame().getAttribute('src')).toBeNull(); - jest.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 200); + vi.advanceTimersByTime(MODAL_LOAD_TIMEOUT_MS - 200); expect(frame().getAttribute('src')).toBe(MODAL_URL); }); }); diff --git a/src/GleapNetworkLogSanitizer.test.js b/src/GleapNetworkLogSanitizer.test.js index 83bae5a1..0252ee0a 100644 --- a/src/GleapNetworkLogSanitizer.test.js +++ b/src/GleapNetworkLogSanitizer.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect } from 'vitest'; import { REDACTED_VALUE, sanitizeNetworkLogs } from './GleapNetworkLogSanitizer'; import GleapNetworkIntercepter from './GleapNetworkIntercepter'; diff --git a/src/GleapNotificationManager.test.js b/src/GleapNotificationManager.test.js index d55aca13..38ef1898 100644 --- a/src/GleapNotificationManager.test.js +++ b/src/GleapNotificationManager.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapTabCommunication, GleapSession, GleapAudioManager } from './Gleap'; import { loadFromGleapCache, saveToGleapCache } from './GleapHelper'; import GleapNotificationManager from './GleapNotificationManager'; @@ -5,30 +6,30 @@ import GleapNotificationManager from './GleapNotificationManager'; // Stub the barrel so the real GleapNotificationManager loads without a DOM or the // SDK_VERSION Webpack global. We only drive clearAllNotifications, which reaches // GleapTabCommunication, GleapSession and saveToGleapCache. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn() }, - GleapFeedbackButtonManager: { getInstance: jest.fn(() => ({ updateNotificationBadge: jest.fn() })) }, - GleapConfigManager: { getInstance: jest.fn(() => ({ getFlowConfig: () => ({}) })) }, - GleapSession: { getInstance: jest.fn() }, - GleapAudioManager: { ping: jest.fn() }, + default: { getInstance: vi.fn() }, + GleapFeedbackButtonManager: { getInstance: vi.fn(() => ({ updateNotificationBadge: vi.fn() })) }, + GleapConfigManager: { getInstance: vi.fn(() => ({ getFlowConfig: () => ({}) })) }, + GleapSession: { getInstance: vi.fn() }, + GleapAudioManager: { ping: vi.fn() }, GleapTranslationManager: { - getInstance: jest.fn(() => ({ isRTLLayout: false, getActiveLanguage: () => 'en' })), + getInstance: vi.fn(() => ({ isRTLLayout: false, getActiveLanguage: () => 'en' })), translateText: (s) => s, }, - GleapEventManager: { notifyEvent: jest.fn() }, - GleapAiChatbarManager: { getInstance: jest.fn(() => ({})) }, - GleapTabCommunication: { getInstance: jest.fn() }, + GleapEventManager: { notifyEvent: vi.fn() }, + GleapAiChatbarManager: { getInstance: vi.fn(() => ({})) }, + GleapTabCommunication: { getInstance: vi.fn() }, })); -jest.mock('./GleapHelper', () => ({ - loadFromGleapCache: jest.fn(), - saveToGleapCache: jest.fn(), - formatRelativeTime: jest.fn(() => 'now'), +vi.mock('./GleapHelper', () => ({ + loadFromGleapCache: vi.fn(), + saveToGleapCache: vi.fn(), + formatRelativeTime: vi.fn(() => 'now'), })); -jest.mock('./UI', () => ({ - loadIcon: jest.fn(() => ''), +vi.mock('./UI', () => ({ + loadIcon: vi.fn(() => ''), })); let sendMessageMock; @@ -36,16 +37,16 @@ let sendMessageMock; const withContainer = (nm) => { nm.notificationContainer = { firstChild: null, - appendChild: jest.fn(), - removeChild: jest.fn(), - classList: { add: jest.fn(), remove: jest.fn(), toggle: jest.fn(), contains: jest.fn(() => false) }, + appendChild: vi.fn(), + removeChild: vi.fn(), + classList: { add: vi.fn(), remove: vi.fn(), toggle: vi.fn(), contains: vi.fn(() => false) }, }; return nm; }; beforeEach(() => { Gleap.getInstance.mockReturnValue({ disableInAppNotifications: false }); - sendMessageMock = jest.fn(); + sendMessageMock = vi.fn(); GleapTabCommunication.getInstance.mockReturnValue({ sendMessage: sendMessageMock }); GleapSession.getInstance.mockReturnValue({ session: { gleapId: 'user-1' } }); @@ -78,7 +79,7 @@ describe('clearNotificationsForConversation', () => { test('filters in-memory notifications and re-renders when something was removed', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); const keep = convNotification('token-other'); nm.notifications = [convNotification('token-read'), keep]; loadFromGleapCache.mockReturnValue(null); @@ -91,7 +92,7 @@ describe('clearNotificationsForConversation', () => { test('does not re-render when nothing matched', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [convNotification('token-other')]; loadFromGleapCache.mockReturnValue(null); @@ -170,7 +171,7 @@ describe('page rules — render-time evaluation (#141052)', () => { saveToGleapCache.mockReset(); // The suite runs in the node environment; renderNotifications only needs // createElement + property assignments, so a minimal stub is enough. - global.document = { createElement: jest.fn(() => ({})) }; + global.document = { createElement: vi.fn(() => ({})) }; setUrl(ALLOWED_URL); }); @@ -221,7 +222,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('checkPageRulesForUrl re-renders only once per URL', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [pageRuledNotification()]; nm.checkPageRulesForUrl(ALLOWED_URL); @@ -232,7 +233,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('checkPageRulesForUrl skips re-rendering when nothing is page-ruled', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [plainNotification()]; nm.checkPageRulesForUrl('https://a.example.com/1'); @@ -243,7 +244,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('legacy single pageFilter notifications also trigger re-evaluation', () => { const nm = GleapNotificationManager.getInstance(); - const renderSpy = jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + const renderSpy = vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.notifications = [{ outbound: 'o1', data: { text: 'x' }, pageFilter: '/x', pageFilterType: 'notcontains' }]; nm.checkPageRulesForUrl('https://a.example.com/1'); @@ -266,7 +267,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('a notification arriving on an excluded page is stored + persisted (not consumed), without a ping', () => { setUrl(EXCLUDED_URL); const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); const notification = { ...pageRuledNotification(), sound: true }; nm.showNotification(notification); @@ -278,7 +279,7 @@ describe('page rules — render-time evaluation (#141052)', () => { test('a notification arriving on an allowed page still pings', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.showNotification({ ...pageRuledNotification(), sound: true }); @@ -298,7 +299,7 @@ describe('notification stack', () => { loadFromGleapCache.mockReset(); saveToGleapCache.mockReset(); global.window = { location: { href: 'https://a.example.com/' } }; - global.document = { createElement: jest.fn(() => ({})) }; + global.document = { createElement: vi.fn(() => ({})) }; }); afterEach(() => { @@ -308,7 +309,7 @@ describe('notification stack', () => { test('showNotification keeps the newest 4, dropping the oldest beyond that', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); for (let i = 1; i <= 6; i++) { nm.showNotification(plainNotification(`n${i}`)); @@ -319,7 +320,7 @@ describe('notification stack', () => { test('reloadNotificationsFromCache keeps the NEWEST 4 (the same end shift() trims from)', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); loadFromGleapCache.mockReturnValue( [1, 2, 3, 4, 5, 6].map((i) => ({ ...plainNotification(`n${i}`), cachedForGleapId: 'user-1' })) ); @@ -412,7 +413,7 @@ describe('notification cache vs identity (#225880)', () => { test('showNotification stamps the receiving gleapId on the cached notification', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); nm.showNotification(plainNotification('hello')); @@ -423,7 +424,7 @@ describe('notification cache vs identity (#225880)', () => { test('reloadNotificationsFromCache drops notifications cached for another (or no) gleapId', () => { const nm = withContainer(GleapNotificationManager.getInstance()); - jest.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); + vi.spyOn(nm, 'renderNotifications').mockImplementation(() => {}); const own = plainNotification('own', 'user-1'); loadFromGleapCache.mockReturnValue([ plainNotification('previous user', 'user-0'), diff --git a/src/GleapNotifications.disabled.test.js b/src/GleapNotifications.disabled.test.js index 26e21f1b..c56fa5e2 100644 --- a/src/GleapNotifications.disabled.test.js +++ b/src/GleapNotifications.disabled.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapAudioManager, GleapConfigManager, @@ -30,20 +31,20 @@ const visibleCards = (manager) => manager.notificationContainer.querySelectorAll beforeEach(() => { // Exercise the real public setter and notification renderer, without SDK startup. - jest.spyOn(Gleap, 'getInstance').mockReturnValue({ disableInAppNotifications: false }); - jest.spyOn(GleapSession, 'getInstance').mockReturnValue({ + vi.spyOn(Gleap, 'getInstance').mockReturnValue({ disableInAppNotifications: false }); + vi.spyOn(GleapSession, 'getInstance').mockReturnValue({ session: { gleapId: 'signup-visitor' }, getName: () => 'Visitor', }); - jest.spyOn(GleapConfigManager, 'getInstance').mockReturnValue({ getFlowConfig: () => ({}) }); - jest.spyOn(GleapAudioManager, 'ping').mockImplementation(() => {}); - jest.spyOn(cache, 'loadFromGleapCache').mockReturnValue(null); - jest.spyOn(cache, 'saveToGleapCache').mockImplementation(() => {}); + vi.spyOn(GleapConfigManager, 'getInstance').mockReturnValue({ getFlowConfig: () => ({}) }); + vi.spyOn(GleapAudioManager, 'ping').mockImplementation(() => {}); + vi.spyOn(cache, 'loadFromGleapCache').mockReturnValue(null); + vi.spyOn(cache, 'saveToGleapCache').mockImplementation(() => {}); GleapNotificationManager.instance = undefined; }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); GleapNotificationManager.instance = undefined; document.body.innerHTML = ''; }); @@ -111,9 +112,9 @@ test('reenabling notifications still respects their page exclusions', () => { }); test('support chat can still open while notification cards are disabled', () => { - const frame = { setAppMode: jest.fn(), showWidget: jest.fn(), hideWidget: jest.fn() }; - jest.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(frame); - const buttonManager = jest.spyOn(GleapFeedbackButtonManager, 'getInstance'); + const frame = { setAppMode: vi.fn(), showWidget: vi.fn(), hideWidget: vi.fn() }; + vi.spyOn(GleapFrameManager, 'getInstance').mockReturnValue(frame); + const buttonManager = vi.spyOn(GleapFeedbackButtonManager, 'getInstance'); Gleap.setDisableInAppNotifications(true); Gleap.open(); diff --git a/src/GleapPageFilter.test.js b/src/GleapPageFilter.test.js index 342abeee..81ee7515 100644 --- a/src/GleapPageFilter.test.js +++ b/src/GleapPageFilter.test.js @@ -1,3 +1,4 @@ +import { describe, it, test, expect } from 'vitest'; import { checkPageRules, checkPageFilter } from './GleapPageFilter'; const url = (path) => `https://app.example.com${path}`; diff --git a/src/GleapProductTourStart.test.js b/src/GleapProductTourStart.test.js index a2825ba2..715c1412 100644 --- a/src/GleapProductTourStart.test.js +++ b/src/GleapProductTourStart.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, afterEach } from 'vitest'; import Gleap, { GleapSession } from './Gleap'; const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); @@ -14,7 +15,7 @@ describe('Gleap.startProductTour redirect to the start URL', () => { const startFrom = async (currentUrl, config) => { delete window.location; window.location = { href: currentUrl }; - configSpy = jest.spyOn(GleapSession.getInstance(), 'startProductTourConfig').mockResolvedValue(config); + configSpy = vi.spyOn(GleapSession.getInstance(), 'startProductTourConfig').mockResolvedValue(config); Gleap.startProductTour('tour-1', true); await flush(); return new URL(window.location.href); diff --git a/src/GleapRegions.test.js b/src/GleapRegions.test.js index 9c2b2450..7499e702 100644 --- a/src/GleapRegions.test.js +++ b/src/GleapRegions.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapBannerManager, GleapFrameManager, GleapModalManager, GleapSession } from './Gleap'; import GleapNetworkIntercepter from './GleapNetworkIntercepter'; import { GLEAP_DEFAULT_REGION, GLEAP_REGIONS, resolveGleapRegion } from './GleapRegions'; @@ -37,7 +38,7 @@ let warnSpy; beforeEach(() => { // Fresh session singleton per test so the defaults are observable. GleapSession.instance = undefined; - warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { @@ -181,7 +182,7 @@ describe('region side effects', () => { test('setAgentConversationUrl applies to newly attached agent conversations', () => { // The iframe bootstrap fetches the frame document; keep it pending. - global.fetch = jest.fn(() => new Promise(() => {})); + global.fetch = vi.fn(() => new Promise(() => {})); const create = () => { const element = document.createElement('gleap-agent-conversation'); diff --git a/src/GleapReplayRecorder.test.js b/src/GleapReplayRecorder.test.js index 9db7543b..bb1be80b 100644 --- a/src/GleapReplayRecorder.test.js +++ b/src/GleapReplayRecorder.test.js @@ -1,10 +1,11 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { record } from '@rrweb/record'; import GleapReplayRecorder, { approximateSize } from './GleapReplayRecorder'; // The recorder only needs rrweb's emit callback; tests drive it directly. -jest.mock('@rrweb/record', () => ({ record: jest.fn() })); -jest.mock('@rrweb/packer', () => ({ pack: (event) => event })); -jest.mock('./GleapHelper', () => ({ isMobile: () => false })); +vi.mock('@rrweb/record', () => ({ record: vi.fn() })); +vi.mock('@rrweb/packer', () => ({ pack: (event) => event })); +vi.mock('./GleapHelper', () => ({ isMobile: () => false })); const MB = 1024 * 1024; const META = 4; @@ -42,17 +43,17 @@ const bufferedHrefs = (recorder) => .map((event) => event.data.href); beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); record.mockReset().mockImplementation((options) => { emit = options.emit; - return jest.fn(); + return vi.fn(); }); - record.takeFullSnapshot = jest.fn((isCheckout) => checkpoint('forced', MB, isCheckout)); + record.takeFullSnapshot = vi.fn((isCheckout) => checkpoint('forced', MB, isCheckout)); global.window = { location: { origin: 'https://app.example.com' }, innerWidth: 1920, innerHeight: 1080 }; }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); delete global.window; }); @@ -91,7 +92,7 @@ describe('replay buffer byte budget (#147738)', () => { for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); expect(record.takeFullSnapshot).not.toHaveBeenCalled(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(record.takeFullSnapshot).toHaveBeenCalledTimes(1); expect(record.takeFullSnapshot).toHaveBeenCalledWith(true); @@ -103,13 +104,13 @@ describe('replay buffer byte budget (#147738)', () => { startRecorder(); checkpoint('first', MB, false); for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); - jest.advanceTimersByTime(29 * 1000); + vi.advanceTimersByTime(29 * 1000); expect(record.takeFullSnapshot).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(record.takeFullSnapshot).toHaveBeenCalledTimes(2); }); @@ -118,7 +119,7 @@ describe('replay buffer byte budget (#147738)', () => { checkpoint('first', 12 * MB, false); emit(mutation(MB)); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); expect(record.takeFullSnapshot).not.toHaveBeenCalled(); expect(bufferedHrefs(recorder)).toEqual(['first']); @@ -130,7 +131,7 @@ describe('replay buffer byte budget (#147738)', () => { for (let i = 0; i < 4; i++) emit(mutation(3 * MB)); recorder.stop(); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); expect(record.takeFullSnapshot).not.toHaveBeenCalled(); }); @@ -154,7 +155,7 @@ describe('input masking options passed to rrweb', () => { }); test("a site's maskInputOptions keep their kinds; its maskInputFn is wrapped, not replaced", () => { - const siteMaskInputFn = jest.fn(() => 'masked by site'); + const siteMaskInputFn = vi.fn(() => 'masked by site'); const options = recordOptions({ maskInputOptions: { select: true }, maskInputFn: siteMaskInputFn }); expect(options.maskInputOptions.select).toBe(true); @@ -213,7 +214,7 @@ describe('approximateSize', () => { timestamp: 1790000000000, }, ], - ])('%s -> within 25%% of its serialized size', (_label, event) => { + ])('%s -> within 25% of its serialized size', (_label, event) => { const ratio = approximateSize(event) / JSON.stringify(event).length; expect(ratio).toBeGreaterThan(0.75); expect(ratio).toBeLessThan(1.25); @@ -227,11 +228,11 @@ describe('startIfNotRunning waits for an idle moment', () => { beforeEach(() => { idleCallbacks = []; - global.window.requestIdleCallback = jest.fn((callback, options) => { + global.window.requestIdleCallback = vi.fn((callback, options) => { idleCallbacks.push({ callback, options }); return idleCallbacks.length; }); - global.window.cancelIdleCallback = jest.fn((handle) => { + global.window.cancelIdleCallback = vi.fn((handle) => { idleCallbacks[handle - 1].cancelled = true; }); }); @@ -297,7 +298,7 @@ describe('startIfNotRunning waits for an idle moment', () => { recorder.startIfNotRunning(); expect(record).not.toHaveBeenCalled(); - jest.advanceTimersByTime(2000); + vi.advanceTimersByTime(2000); expect(record).toHaveBeenCalledTimes(1); }); }); diff --git a/src/GleapScreenRecorder.test.js b/src/GleapScreenRecorder.test.js index 4b4b6b7e..1dece9ac 100644 --- a/src/GleapScreenRecorder.test.js +++ b/src/GleapScreenRecorder.test.js @@ -1,34 +1,35 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { test, expect, vi, beforeEach } from 'vitest'; import { GleapScreenRecorder } from './GleapScreenRecorder'; import { requestDisplayStream } from './GleapCaptureRecorder'; import { hasDisplayMedia, isDesktopChromium } from './GleapCaptureSettings'; +import { stopStream } from './GleapCaptureScreenshot'; // The feedback form's recorder runs on the capture requests' recording engine (#228450). const mockRecordings = []; -jest.mock('./GleapSession', () => ({ __esModule: true, default: { getInstance: () => ({}) } })); -jest.mock('./GleapCaptureScreenshot', () => ({ stopStream: jest.fn() })); -jest.mock('./GleapCaptureSettings', () => ({ - hasDisplayMedia: jest.fn(() => true), - isDesktopChromium: jest.fn(() => true), +vi.mock('./GleapSession', () => ({ __esModule: true, default: { getInstance: () => ({}) } })); +vi.mock('./GleapCaptureScreenshot', () => ({ stopStream: vi.fn() })); +vi.mock('./GleapCaptureSettings', () => ({ + hasDisplayMedia: vi.fn(() => true), + isDesktopChromium: vi.fn(() => true), })); -jest.mock('./GleapCaptureRecorder', () => ({ - requestDisplayStream: jest.fn(), +vi.mock('./GleapCaptureRecorder', () => ({ + requestDisplayStream: vi.fn(), DisplayRecording: class { constructor(options) { this.options = options; - this.start = jest.fn(() => Promise.resolve({ hasMicrophone: true })); - this.stop = jest.fn(); - this.cancel = jest.fn(); - this.setMicrophoneEnabled = jest.fn(); + this.start = vi.fn(() => Promise.resolve({ hasMicrophone: true })); + this.stop = vi.fn(); + this.cancel = vi.fn(); + this.setMicrophoneEnabled = vi.fn(); mockRecordings.push(this); } }, })); -const { stopStream } = jest.requireMock('./GleapCaptureScreenshot'); const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); const STREAM = { id: 'tab-stream' }; @@ -37,13 +38,13 @@ const createRecorder = () => new GleapScreenRecorder(rerender, 'No access to the beforeEach(() => { mockRecordings.length = 0; - rerender = jest.fn(); + rerender = vi.fn(); hasDisplayMedia.mockReturnValue(true); isDesktopChromium.mockReturnValue(true); requestDisplayStream.mockReset().mockReturnValue(Promise.resolve(STREAM)); stopStream.mockClear(); - window.alert = jest.fn(); - URL.createObjectURL = jest.fn(() => 'blob:preview'); + window.alert = vi.fn(); + URL.createObjectURL = vi.fn(() => 'blob:preview'); document.body.innerHTML = '
' + '
'; diff --git a/src/GleapSession.test.js b/src/GleapSession.test.js index 6bc03067..6da5ae9c 100644 --- a/src/GleapSession.test.js +++ b/src/GleapSession.test.js @@ -1,49 +1,51 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapSession from './GleapSession'; import { saveToGleapCache, loadFromGleapCache, setGleapCookie, eraseGleapCookie, getGleapCookie } from './GleapHelper'; +import { GleapFrameManager } from './Gleap'; // The session manager only needs the sibling managers to exist; none of the // paths under test depend on their behavior beyond being callable. -jest.mock('./Gleap', () => ({ - GleapBannerManager: { getInstance: jest.fn(() => ({ removeBannerUI: jest.fn() })) }, - GleapEventManager: { notifyEvent: jest.fn() }, +vi.mock('./Gleap', () => ({ + GleapBannerManager: { getInstance: vi.fn(() => ({ removeBannerUI: vi.fn() })) }, + GleapEventManager: { notifyEvent: vi.fn() }, GleapFrameManager: { - getInstance: jest.fn(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn() })), + getInstance: vi.fn(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn() })), }, - GleapModalManager: { getInstance: jest.fn(() => ({ hideModal: jest.fn() })) }, + GleapModalManager: { getInstance: vi.fn(() => ({ hideModal: vi.fn() })) }, GleapNotificationManager: { - getInstance: jest.fn(() => ({ clearAllNotifications: jest.fn(), setNotificationCount: jest.fn() })), + getInstance: vi.fn(() => ({ clearAllNotifications: vi.fn(), setNotificationCount: vi.fn() })), }, - GleapStreamedEvent: { getInstance: jest.fn(() => ({ restart: jest.fn(), stop: jest.fn() })) }, - GleapTranslationManager: { getInstance: jest.fn(() => ({ getActiveLanguage: () => 'en' })) }, + GleapStreamedEvent: { getInstance: vi.fn(() => ({ restart: vi.fn(), stop: vi.fn() })) }, + GleapTranslationManager: { getInstance: vi.fn(() => ({ getActiveLanguage: () => 'en' })) }, })); -jest.mock('./ChecklistNetworkManager', () => ({ +vi.mock('./ChecklistNetworkManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ clearCache: jest.fn() })) }, + default: { getInstance: vi.fn(() => ({ clearCache: vi.fn() })) }, })); -jest.mock('./AgentNetworkManager', () => ({ +vi.mock('./AgentNetworkManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ clearCache: jest.fn() })) }, + default: { getInstance: vi.fn(() => ({ clearCache: vi.fn() })) }, })); -jest.mock('./GleapTooltipManager', () => ({ +vi.mock('./GleapTooltipManager', () => ({ __esModule: true, - default: { getInstance: jest.fn(() => ({ destroy: jest.fn(), load: jest.fn() })) }, + default: { getInstance: vi.fn(() => ({ destroy: vi.fn(), load: vi.fn() })) }, })); -jest.mock('./GleapAiChatbarManager', () => ({ +vi.mock('./GleapAiChatbarManager', () => ({ __esModule: true, default: { instance: null }, })); -jest.mock('./GleapHelper', () => ({ - eraseGleapCookie: jest.fn(), - getDeviceType: jest.fn(() => 'desktop'), - getGleapCookie: jest.fn(() => null), - loadFromGleapCache: jest.fn(() => null), - saveToGleapCache: jest.fn(), - setGleapCookie: jest.fn(), +vi.mock('./GleapHelper', () => ({ + eraseGleapCookie: vi.fn(), + getDeviceType: vi.fn(() => 'desktop'), + getGleapCookie: vi.fn(() => null), + loadFromGleapCache: vi.fn(() => null), + saveToGleapCache: vi.fn(), + setGleapCookie: vi.fn(), })); // Minimal XHR double: tests drive responses explicitly via respond()/error(). @@ -109,12 +111,12 @@ const buildSession = () => { }; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); MockXhr.instances = []; global.XMLHttpRequest = MockXhr; // No dispatchEvent on purpose: validateSession guards on its existence, and // node has no CustomEvent to construct. - global.window = { addEventListener: jest.fn() }; + global.window = { addEventListener: vi.fn() }; cacheStore = {}; loadFromGleapCache.mockReset().mockImplementation((key) => (key in cacheStore ? cacheStore[key] : null)); saveToGleapCache.mockReset().mockImplementation((key, value) => { @@ -123,7 +125,7 @@ beforeEach(() => { }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); describe('startSession failure handling', () => { @@ -143,7 +145,7 @@ describe('startSession failure handling', () => { expect(saveToGleapCache).not.toHaveBeenCalledWith(expect.anything(), null); // The retry re-sends the same session credentials. - jest.advanceTimersByTime(10 * 1000); + vi.advanceTimersByTime(10 * 1000); const retry = MockXhr.instances[1]; expect(retry).toBeDefined(); expect(retry.headers['Gleap-Id']).toBe('gleap-id-1'); @@ -162,7 +164,7 @@ describe('startSession failure handling', () => { expect(saveToGleapCache).toHaveBeenCalledWith(expect.anything(), null); // Retry happens without stale credentials. - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); const retry = MockXhr.instances[1]; expect(retry).toBeDefined(); expect(retry.headers['Gleap-Id']).toBeUndefined(); @@ -175,7 +177,7 @@ describe('startSession failure handling', () => { MockXhr.instances[0].respond(503); expect(session.session.gleapId).toBe(null); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(MockXhr.instances.length).toBe(2); }); @@ -187,7 +189,7 @@ describe('startSession failure handling', () => { MockXhr.instances[0].respond(429); expect(session.session.gleapId).toBe('gleap-id-1'); - jest.advanceTimersByTime(60 * 60 * 1000); + vi.advanceTimersByTime(60 * 60 * 1000); expect(MockXhr.instances.length).toBe(1); }); }); @@ -351,7 +353,7 @@ describe('user switch in the same browser', () => { session.startSession(); session.identifySession('user-2', { email: 'other@example.com' }); - const started = jest.fn(() => session.session.userId); + const started = vi.fn(() => session.session.userId); session.onContactSettled(started); expect(started).not.toHaveBeenCalled(); @@ -373,9 +375,9 @@ describe('authenticated file sessions', () => { const session = buildSession(); session.lastIdentify = { userId: 'user-1', userData: {}, userHash: 'verified-hmac' }; session.validateSession({ ...CACHED_IDENTIFIED_SESSION, fileAccessToken: 'file-session', fileAccessExpiresAt: new Date(Date.now() + 900000).toISOString() }); - jest.advanceTimersByTime(300000); + vi.advanceTimersByTime(300000); session.validateSession({ ...CACHED_IDENTIFIED_SESSION }); - jest.advanceTimersByTime(300000); + vi.advanceTimersByTime(300000); expect(identifyRequests()).toHaveLength(1); }); it('re-verifies an unchanged cached identity when the project now requires authenticated files', () => { @@ -397,7 +399,7 @@ describe('authenticated file sessions', () => { const session = buildSession(); session.lastIdentify = { userId: 'user-1', userData: { email: 'bec@example.com' }, userHash: 'verified-hmac' }; session.validateSession({ ...CACHED_IDENTIFIED_SESSION, fileAccessToken: 'file-session', fileAccessExpiresAt: new Date(Date.now() + 900000).toISOString() }); - jest.advanceTimersByTime(600000); + vi.advanceTimersByTime(600000); expect(identifyRequests()).toHaveLength(1); expect(JSON.parse(identifyRequests()[0].body).userHash).toBe('verified-hmac'); }); @@ -426,7 +428,7 @@ describe('identity tokens (setUserJwt)', () => { let warn; beforeEach(() => { - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { warn.mockRestore(); @@ -516,7 +518,7 @@ describe('identity tokens (setUserJwt)', () => { it('on token_expired asks the provider once and retries with the new token', async () => { const session = readySession(); const fresh = jwtOf({ userId: 'user-1', exp: inSeconds(3600) }); - const provider = jest.fn(() => Promise.resolve(fresh)); + const provider = vi.fn(() => Promise.resolve(fresh)); session.setUserJwtProvider(provider); const done = session.setUserJwt(jwtOf({ userId: 'user-1', exp: inSeconds(-10) })); @@ -533,7 +535,7 @@ describe('identity tokens (setUserJwt)', () => { it('retries only once and shares one provider call', async () => { const session = readySession(); - const provider = jest.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); + const provider = vi.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); session.setUserJwtProvider(provider); const done = session.setUserJwt(jwtOf({ userId: 'user-1', exp: inSeconds(-10) })); @@ -550,13 +552,13 @@ describe('identity tokens (setUserJwt)', () => { it('pauses 30 s after a provider failure', async () => { const session = buildSession(); - const provider = jest.fn(() => Promise.reject(new Error('offline'))); + const provider = vi.fn(() => Promise.reject(new Error('offline'))); session.setUserJwtProvider(provider); expect(await session.requestUserJwt()).toBeNull(); expect(await session.requestUserJwt()).toBeNull(); expect(provider).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await session.requestUserJwt(); expect(provider).toHaveBeenCalledTimes(2); }); @@ -565,7 +567,7 @@ describe('identity tokens (setUserJwt)', () => { const session = buildSession(); session.setUserJwtProvider(() => new Promise(() => {})); const pending = session.requestUserJwt(); - jest.advanceTimersByTime(10 * 1000); + vi.advanceTimersByTime(10 * 1000); expect(await pending).toBeNull(); }); @@ -584,12 +586,12 @@ describe('identity tokens (setUserJwt)', () => { it('asks the provider before a file-access renewal when the token expires within 5 minutes', async () => { const session = buildSession(); const fresh = jwtOf({ userId: 'user-1', exp: inSeconds(3600) }); - const provider = jest.fn(() => fresh); + const provider = vi.fn(() => fresh); session.setUserJwtProvider(provider); session.lastIdentify = { userId: 'user-1', userData: {}, userHash: jwtOf({ userId: 'user-1', exp: inSeconds(60) }) }; session.validateSession({ ...CACHED_IDENTIFIED_SESSION, fileAccessToken: 'file-session', fileAccessExpiresAt: new Date(Date.now() + 900000).toISOString() }); - jest.advanceTimersByTime(600000); + vi.advanceTimersByTime(600000); await flush(); expect(provider).toHaveBeenCalledTimes(1); expect(identifyRequests()).toHaveLength(1); @@ -598,7 +600,7 @@ describe('identity tokens (setUserJwt)', () => { it('clearIdentity drops the token and auth tokens but keeps the provider', () => { const session = readySession(); - const provider = jest.fn(); + const provider = vi.fn(); session.setUserJwtProvider(provider); session.setUserJwt(jwtOf({ userId: 'user-1' })); session.authTokens = { backend: 'secret' }; @@ -613,7 +615,7 @@ describe('auth tokens (setAuthTokens)', () => { const authTokenRequests = () => MockXhr.instances.filter((xhr) => xhr.url && xhr.url.endsWith('/sessions/auth-tokens')); let warn; beforeEach(() => { - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); afterEach(() => { warn.mockRestore(); @@ -694,7 +696,7 @@ describe('grant (signed session credential)', () => { let warn; beforeEach(() => { - warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); setGleapCookie.mockClear(); eraseGleapCookie.mockClear(); getGleapCookie.mockReset().mockImplementation(() => null); @@ -754,7 +756,7 @@ describe('grant (signed session credential)', () => { const session = readySession(); session.setUserJwt(jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); respondWithGrant(identifyRequests()[0], grantFor('gleap-id-1')); - const provider = jest.fn(); + const provider = vi.fn(); session.setUserJwtProvider(provider); session.clearSession(0, false); expect(session.grant).toBe(null); @@ -811,9 +813,9 @@ describe('grant (signed session credential)', () => { it('renews a minute before the grant lifetime ends, counted from receipt', async () => { const session = readySession(); signIn(session, shortGrant(3600)); - jest.advanceTimersByTime(3540 * 1000 - 1); + vi.advanceTimersByTime(3540 * 1000 - 1); expect(identifyRequests()).toHaveLength(1); - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); await flush(); expect(identifyRequests()).toHaveLength(2); }); @@ -821,20 +823,20 @@ describe('grant (signed session credential)', () => { it('a 60-70 s grant waits 30 s and renews at most once a minute (no loop)', async () => { const session = readySession(); signIn(session, shortGrant(65)); - jest.advanceTimersByTime(29 * 1000); + vi.advanceTimersByTime(29 * 1000); expect(identifyRequests()).toHaveLength(1); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); await flush(); expect(identifyRequests()).toHaveLength(2); // The refresh answers with another short grant: the next refresh waits for the minute. - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); respondWithGrant(identifyRequests()[1], shortGrant(65, 1)); await flush(); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); - jest.advanceTimersByTime(29 * 1000); + vi.advanceTimersByTime(29 * 1000); await flush(); expect(identifyRequests()).toHaveLength(3); }); @@ -843,10 +845,10 @@ describe('grant (signed session credential)', () => { const session = readySession(); // Issued by a server whose clock is two hours behind the device: exp already lies in the device's past. signIn(session, shortGrant(3600, -7200)); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(identifyRequests()).toHaveLength(1); - jest.advanceTimersByTime(3480 * 1000); + vi.advanceTimersByTime(3480 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); }); @@ -854,13 +856,13 @@ describe('grant (signed session credential)', () => { it('skips while a refresh is in flight', async () => { const session = readySession(); signIn(session, shortGrant(65)); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); expect(session.grantRefreshInFlight).toBe(true); // Re-arming for the same grant while the refresh runs sends nothing more. session.armGrantRefresh(session.grant, Date.now()); - jest.advanceTimersByTime(120 * 1000); + vi.advanceTimersByTime(120 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); identifyRequests()[1].error(); @@ -871,15 +873,15 @@ describe('grant (signed session credential)', () => { it('a failed refresh is tried again a minute later', async () => { const session = readySession(); signIn(session, shortGrant(65)); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); identifyRequests()[1].error(); await flush(); - jest.advanceTimersByTime(59 * 1000); + vi.advanceTimersByTime(59 * 1000); await flush(); expect(identifyRequests()).toHaveLength(2); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); await flush(); expect(identifyRequests()).toHaveLength(3); }); @@ -916,7 +918,7 @@ describe('grant (signed session credential)', () => { session.setUserJwt(token()); session.startSession(); sessionsRequests()[1].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, ...SIGNED_MODE })); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); expect(identifyRequests()).toHaveLength(1); }); @@ -938,7 +940,7 @@ describe('grant (signed session credential)', () => { expect(session.hasLiveGrant()).toBe(true); eraseGleapCookie.mockClear(); MockXhr.instances = []; - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); // The grant still looks live locally, but the server no longer accepts it. session.startSession(); @@ -955,7 +957,7 @@ describe('grant (signed session credential)', () => { identifyRequests()[0].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, identity: { signed: false, mode: 'signed' } })); session.startSession(); sessionsRequests()[1].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, identity: { signed: false, mode: 'signed' } })); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); expect(identifyRequests()).toHaveLength(1); }); @@ -991,7 +993,7 @@ describe('grant (signed session credential)', () => { it('asks the provider once and identifies with its token, which brings the grant back', async () => { const token = jwtOf({ userId: 'user-1', exp: inSeconds(3600) }); - const provider = jest.fn(() => Promise.resolve(token)); + const provider = vi.fn(() => Promise.resolve(token)); const session = reloadWithProvider(provider); expect(provider).not.toHaveBeenCalled(); @@ -1011,7 +1013,7 @@ describe('grant (signed session credential)', () => { }); it('no loop: at most one provider call and one identify per session load', async () => { - const provider = jest.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); + const provider = vi.fn(() => Promise.resolve(jwtOf({ userId: 'user-1', exp: inSeconds(3600) }))); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1023,7 +1025,7 @@ describe('grant (signed session credential)', () => { session.startSession(); answerSignedMode(sessionsRequests()[1]); await flush(); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); session.startSession(); answerSignedMode(sessionsRequests()[2]); await flush(); @@ -1033,7 +1035,7 @@ describe('grant (signed session credential)', () => { it('one call at a time: a second signed-mode answer while the provider runs asks nothing more', async () => { let resolveToken; - const provider = jest.fn(() => new Promise((resolve) => (resolveToken = resolve))); + const provider = vi.fn(() => new Promise((resolve) => (resolveToken = resolve))); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); session.startSession(); @@ -1054,7 +1056,7 @@ describe('grant (signed session credential)', () => { }); it('the provider returns null: nothing is sent, nothing logged, and it is not asked again this load', async () => { - const provider = jest.fn(() => null); + const provider = vi.fn(() => null); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1062,7 +1064,7 @@ describe('grant (signed session credential)', () => { expect(identifyRequests()).toHaveLength(0); expect(warn).not.toHaveBeenCalled(); - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); session.startSession(); answerSignedMode(sessionsRequests()[1]); await flush(); @@ -1072,7 +1074,7 @@ describe('grant (signed session credential)', () => { it('a token for another user goes through identity_mismatch (fresh visitor, identify once more)', async () => { const token = jwtOf({ userId: 'user-2', exp: inSeconds(3600) }); - const provider = jest.fn(() => token); + const provider = vi.fn(() => token); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1094,7 +1096,7 @@ describe('grant (signed session credential)', () => { }); it('a provider set after the /sessions answer is still asked once', async () => { - const provider = jest.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); + const provider = vi.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); const session = reloadWithProvider(null); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1108,7 +1110,7 @@ describe('grant (signed session credential)', () => { }); it('does not ask for a Classic answer, an anonymous session, a live grant or a held token', async () => { - const provider = jest.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); + const provider = vi.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(3600) })); reloadWithProvider(provider); sessionsRequests()[0].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION })); @@ -1138,7 +1140,7 @@ describe('grant (signed session credential)', () => { it('a logout while the provider runs drops its token', async () => { let resolveToken; - const provider = jest.fn(() => new Promise((resolve) => (resolveToken = resolve))); + const provider = vi.fn(() => new Promise((resolve) => (resolveToken = resolve))); const session = reloadWithProvider(provider); answerSignedMode(sessionsRequests()[0]); await flush(); @@ -1151,7 +1153,6 @@ describe('grant (signed session credential)', () => { }); describe('signed session expiry (a visitor afterwards, like Intercom on the web)', () => { - const { GleapFrameManager } = require('./Gleap'); const UNSIGNED_SIGNED_MODE = { identity: { signed: false, grant: null, mode: 'signed' } }; const sessionsRequests = () => MockXhr.instances.filter((xhr) => xhr.url.endsWith('/sessions')); const answerUnsigned = (xhr) => xhr.respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION, ...UNSIGNED_SIGNED_MODE })); @@ -1159,11 +1160,11 @@ describe('grant (signed session credential)', () => { let info; beforeEach(() => { - info = jest.spyOn(console, 'info').mockImplementation(() => {}); + info = vi.spyOn(console, 'info').mockImplementation(() => {}); }); afterEach(() => { info.mockRestore(); - GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn() })); + GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn() })); }); // Signs user-1 in on gleap-id-1 with a grant that runs out in `grantSeconds`. @@ -1176,8 +1177,8 @@ describe('grant (signed session credential)', () => { // The page is closed, then reopened `laterSeconds` on; the grant cookie expired with the grant. const reloadLater = (laterSeconds, setup = () => {}) => { - jest.clearAllTimers(); - jest.setSystemTime(Date.now() + laterSeconds * 1000); + vi.clearAllTimers(); + vi.setSystemTime(Date.now() + laterSeconds * 1000); MockXhr.instances = []; const session = buildSession(); setup(session); @@ -1193,7 +1194,7 @@ describe('grant (signed session credential)', () => { expect(cacheStore['session-sdk-key']).toBe(null); expect(cacheStore['signed-session-sdk-key']).toBe(null); expect(session.lastIdentify).toBe(null); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); const fresh = sessionsRequests()[sessionsRequests().length - 1]; expect(fresh.headers['Gleap-Id']).toBeUndefined(); fresh.respond(200, JSON.stringify({ gleapId: 'gleap-id-guest', gleapHash: 'gleap-hash-guest' })); @@ -1219,7 +1220,7 @@ describe('grant (signed session credential)', () => { expect(identifyRequests()).toHaveLength(0); expect(info).toHaveBeenCalledWith(expect.stringContaining('continues as a visitor')); // The visitor session is final: nothing more is sent. - jest.advanceTimersByTime(10 * 60 * 1000); + vi.advanceTimersByTime(10 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(2); expect(identifyRequests()).toHaveLength(0); @@ -1245,7 +1246,7 @@ describe('grant (signed session credential)', () => { it('a JWT provider with a fresh token keeps the user signed (asked once)', async () => { signedIn(600); const fresh = token(); - const provider = jest.fn(() => Promise.resolve(fresh)); + const provider = vi.fn(() => Promise.resolve(fresh)); const session = reloadLater(11 * 60, (s) => s.setUserJwtProvider(provider)); answerUnsigned(sessionsRequests()[0]); await flush(); @@ -1262,7 +1263,7 @@ describe('grant (signed session credential)', () => { it('a JWT provider that returns null: the session ends (provider asked once, kept afterwards)', async () => { signedIn(600); - const provider = jest.fn(() => null); + const provider = vi.fn(() => null); const session = reloadLater(11 * 60, (s) => s.setUserJwtProvider(provider)); answerUnsigned(sessionsRequests()[0]); await expectVisitor(session); @@ -1278,7 +1279,7 @@ describe('grant (signed session credential)', () => { expect(identifyRequests()).toHaveLength(1); answerUnsigned(sessionsRequests()[0]); await flush(); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await flush(); expect(session.session.gleapId).toBe('gleap-id-1'); respondWithGrant(identifyRequests()[0], grantFor('gleap-id-1')); @@ -1312,7 +1313,7 @@ describe('grant (signed session credential)', () => { answerUnsigned(sessionsRequests()[0]); identifyRequests()[0].error(); await flush(); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(session.session.gleapId).toBe('gleap-id-1'); expect(session.session.userId).toBe('user-1'); @@ -1328,7 +1329,7 @@ describe('grant (signed session credential)', () => { const session = reloadLater(30 * 24 * 3600); answerUnsigned(sessionsRequests()[0]); await flush(); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); expect(session.session.gleapId).toBe('gleap-id-1'); expect(session.session.userId).toBe('user-1'); expect(info).not.toHaveBeenCalled(); @@ -1339,7 +1340,7 @@ describe('grant (signed session credential)', () => { const session = reloadLater(5 * 60); answerUnsigned(sessionsRequests()[0]); await flush(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(session.session.gleapId).toBe('gleap-id-1'); expect(session.session.userId).toBe('user-1'); expect(info).not.toHaveBeenCalled(); @@ -1350,7 +1351,7 @@ describe('grant (signed session credential)', () => { const session = reloadLater(11 * 60); sessionsRequests()[0].respond(200, JSON.stringify({ ...CACHED_IDENTIFIED_SESSION })); await flush(); - jest.advanceTimersByTime(0); + vi.advanceTimersByTime(0); expect(session.session.userId).toBe('user-1'); expect(info).not.toHaveBeenCalled(); }); @@ -1369,7 +1370,7 @@ describe('grant (signed session credential)', () => { expect(session.signedSessionExpiryTimeout).not.toBe(null); session.lastIdentify = null; MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000); + vi.advanceTimersByTime(600 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); }); @@ -1387,14 +1388,14 @@ describe('grant (signed session credential)', () => { // Token valid 5 min, grant 10 min, no provider: the refresh a minute before the end sends the expired token. const session = signedIn(600, 300); MockXhr.instances = []; - jest.advanceTimersByTime(540 * 1000); + vi.advanceTimersByTime(540 * 1000); await flush(); expect(identifyRequests()).toHaveLength(1); identifyRequests()[0].respond(401, JSON.stringify({ detail: { value: 'token_expired' } })); await flush(); expect(sessionsRequests()).toHaveLength(0); - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); expect(sessionsRequests()[0].headers['Gleap-Id']).toBe('gleap-id-1'); @@ -1407,10 +1408,10 @@ describe('grant (signed session credential)', () => { it('a renewed grant re-arms the check: nothing ends', async () => { const session = signedIn(600); MockXhr.instances = []; - jest.advanceTimersByTime(540 * 1000); + vi.advanceTimersByTime(540 * 1000); await flush(); respondWithGrant(identifyRequests()[0], grantFor('gleap-id-1', inSeconds(600))); - jest.advanceTimersByTime(120 * 1000); + vi.advanceTimersByTime(120 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(0); expect(session.hasLiveGrant()).toBe(true); @@ -1422,7 +1423,7 @@ describe('grant (signed session credential)', () => { const renewed = grantFor('gleap-id-1', inSeconds(1800)); getGleapCookie.mockImplementation((name) => (name === 'gleap-grant-sdk-key' ? encodeURIComponent(renewed) : null)); MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000); + vi.advanceTimersByTime(600 * 1000); await flush(); expect(session.grant).toBe(renewed); expect(sessionsRequests()).toHaveLength(0); @@ -1430,15 +1431,15 @@ describe('grant (signed session credential)', () => { it('waits while the messenger is open, then ends once it closes (at most an hour)', async () => { let open = true; - GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn(), isOpened: () => open })); + GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn(), isOpened: () => open })); const session = signedIn(600); session.lastIdentify = null; MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000 + 30 * 60 * 1000); + vi.advanceTimersByTime(600 * 1000 + 30 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(0); open = false; - jest.advanceTimersByTime(60 * 1000); + vi.advanceTimersByTime(60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); answerUnsigned(sessionsRequests()[0]); @@ -1446,14 +1447,14 @@ describe('grant (signed session credential)', () => { }); it('the messenger left open: the session still ends an hour after the expiry', async () => { - GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: jest.fn(), sendSessionUpdate: jest.fn(), isOpened: () => true })); + GleapFrameManager.getInstance.mockImplementation(() => ({ sendMessage: vi.fn(), sendSessionUpdate: vi.fn(), isOpened: () => true })); const session = signedIn(600); session.lastIdentify = null; MockXhr.instances = []; - jest.advanceTimersByTime(600 * 1000 + 59 * 60 * 1000); + vi.advanceTimersByTime(600 * 1000 + 59 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(0); - jest.advanceTimersByTime(2 * 60 * 1000); + vi.advanceTimersByTime(2 * 60 * 1000); await flush(); expect(sessionsRequests()).toHaveLength(1); }); @@ -1501,13 +1502,13 @@ describe('grant (signed session credential)', () => { it('a provider token that already expired counts as a failure (30 s pause)', async () => { const session = readySession(); - const provider = jest.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(0) })); + const provider = vi.fn(() => jwtOf({ userId: 'user-1', exp: inSeconds(0) })); session.setUserJwtProvider(provider); await expect(session.requestUserJwt()).resolves.toBe(null); expect(warn).toHaveBeenCalledWith(expect.stringContaining('expired token')); await expect(session.requestUserJwt()).resolves.toBe(null); expect(provider).toHaveBeenCalledTimes(1); - jest.advanceTimersByTime(30 * 1000); + vi.advanceTimersByTime(30 * 1000); await session.requestUserJwt(); expect(provider).toHaveBeenCalledTimes(2); }); diff --git a/src/GleapShadowSelector.test.js b/src/GleapShadowSelector.test.js index 7ee556e5..580fd039 100644 --- a/src/GleapShadowSelector.test.js +++ b/src/GleapShadowSelector.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect } from 'vitest'; import { querySelectorSafe, querySelectorAllSafe, matchesSelectorSafe } from './GleapSafeSelector'; import { buildStableSelector, withShadowHosts } from './GleapTourSelector'; diff --git a/src/GleapStreamedEvent.test.js b/src/GleapStreamedEvent.test.js index 24614de5..14cf9f0d 100644 --- a/src/GleapStreamedEvent.test.js +++ b/src/GleapStreamedEvent.test.js @@ -1,21 +1,22 @@ +import { describe, it, test, expect, vi, beforeEach, afterEach } from 'vitest'; import Gleap, { GleapMetaDataManager, GleapNotificationManager, GleapSession } from './Gleap'; import GleapStreamedEvent from './GleapStreamedEvent'; // Stub the barrel so the real GleapStreamedEvent loads without a DOM or the // SDK_VERSION Webpack global. -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn() }, - GleapFrameManager: { getInstance: jest.fn(() => ({ isOpened: () => false })) }, - GleapMetaDataManager: { getInstance: jest.fn(() => ({})) }, - GleapAiChatbarManager: { getInstance: jest.fn(() => ({})) }, - GleapNotificationManager: { getInstance: jest.fn() }, - GleapSession: { getInstance: jest.fn(() => ({})) }, - GleapAdminManager: { getInstance: jest.fn(() => ({})) }, - GleapEventManager: { notifyEvent: jest.fn() }, + default: { getInstance: vi.fn() }, + GleapFrameManager: { getInstance: vi.fn(() => ({ isOpened: () => false })) }, + GleapMetaDataManager: { getInstance: vi.fn(() => ({})) }, + GleapAiChatbarManager: { getInstance: vi.fn(() => ({})) }, + GleapNotificationManager: { getInstance: vi.fn() }, + GleapSession: { getInstance: vi.fn(() => ({})) }, + GleapAdminManager: { getInstance: vi.fn(() => ({})) }, + GleapEventManager: { notifyEvent: vi.fn() }, })); -jest.mock('./GleapHelper', () => ({ +vi.mock('./GleapHelper', () => ({ gleapDataParser: (data) => data, })); @@ -23,41 +24,41 @@ describe('startPageListener — notification page-rule re-evaluation (#141052)', let checkPageRulesForUrl; beforeEach(() => { - jest.useFakeTimers(); - checkPageRulesForUrl = jest.fn(); + vi.useFakeTimers(); + checkPageRulesForUrl = vi.fn(); GleapNotificationManager.getInstance.mockReturnValue({ checkPageRulesForUrl }); global.window = { location: { href: 'https://app.example.com/a' } }; }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); delete global.window; }); test('re-evaluates page rules every tick, even with page tracking disabled', () => { Gleap.getInstance.mockReturnValue({ disablePageTracking: true }); const streamer = new GleapStreamedEvent(); - const logEventSpy = jest.spyOn(streamer, 'logEvent'); + const logEventSpy = vi.spyOn(streamer, 'logEvent'); streamer.startPageListener(); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(checkPageRulesForUrl).toHaveBeenCalledWith('https://app.example.com/a'); // disablePageTracking must only suppress pageView streaming, not page rules. expect(logEventSpy).not.toHaveBeenCalled(); global.window.location.href = 'https://app.example.com/b'; - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(checkPageRulesForUrl).toHaveBeenLastCalledWith('https://app.example.com/b'); }); test('still streams pageView events when page tracking is enabled', () => { Gleap.getInstance.mockReturnValue({ disablePageTracking: false }); const streamer = new GleapStreamedEvent(); - const logEventSpy = jest.spyOn(streamer, 'logEvent'); + const logEventSpy = vi.spyOn(streamer, 'logEvent'); streamer.startPageListener(); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); expect(logEventSpy).toHaveBeenCalledWith('pageView', { page: 'https://app.example.com/a' }); expect(checkPageRulesForUrl).toHaveBeenCalledWith('https://app.example.com/a'); @@ -113,14 +114,14 @@ describe('event pings', () => { // Advances the clock and runs a loop tick; true when that tick sent a ping. const tickAfter = (streamer, ms) => { const count = requests.length; - jest.advanceTimersByTime(ms); + vi.advanceTimersByTime(ms); streamer.streamEvents(); return requests.length > count; }; beforeEach(() => { - jest.useFakeTimers(); - jest.setSystemTime(new Date('2026-01-01T00:00:00Z')); + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); requests = []; global.XMLHttpRequest = FakeXHR; global.SDK_VERSION = 'test'; @@ -128,17 +129,17 @@ describe('event pings', () => { ready: true, session: { gleapId: 'id', gleapHash: 'hash' }, apiUrl: 'https://api.test', - injectSession: jest.fn(), + injectSession: vi.fn(), }; GleapSession.getInstance.mockReturnValue(sessionInstance); GleapMetaDataManager.getInstance.mockReturnValue({ getSessionDuration: () => 1 }); // No jitter: every delay is exactly its base value. - jest.spyOn(Math, 'random').mockReturnValue(0.5); + vi.spyOn(Math, 'random').mockReturnValue(0.5); }); afterEach(() => { - jest.useRealTimers(); - jest.restoreAllMocks(); + vi.useRealTimers(); + vi.restoreAllMocks(); delete global.XMLHttpRequest; delete global.SDK_VERSION; }); @@ -169,7 +170,7 @@ describe('event pings', () => { expect(tickAfter(streamer, 29999)).toBe(false); // Timed out: aborted, counted as a failure, the events stay and go again after the backoff. - jest.advanceTimersByTime(1); + vi.advanceTimersByTime(1); expect(requests[0].aborted).toBe(true); expect(names(streamer.streamedEventArray)).toEqual(['a', 'b']); expect(tickAfter(streamer, 2999)).toBe(false); @@ -363,12 +364,12 @@ describe('WebSocket reconnects', () => { // Advances the clock; true when a new socket was opened in that time. const reconnectsAfter = (ms) => { const count = sockets.length; - jest.advanceTimersByTime(ms); + vi.advanceTimersByTime(ms); return sockets.length > count; }; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); sockets = []; online = true; global.WebSocket = FakeWebSocket; @@ -379,12 +380,12 @@ describe('WebSocket reconnects', () => { sessionInstance = { session: { gleapId: 'id', gleapHash: 'hash' }, sdkKey: 'key', wsApiUrl: 'wss://ws.test' }; GleapSession.getInstance.mockReturnValue(sessionInstance); // No jitter: every delay is exactly its base value. - jest.spyOn(Math, 'random').mockReturnValue(0.5); + vi.spyOn(Math, 'random').mockReturnValue(0.5); }); afterEach(() => { - jest.useRealTimers(); - jest.restoreAllMocks(); + vi.useRealTimers(); + vi.restoreAllMocks(); delete global.WebSocket; delete global.SDK_VERSION; delete global.window; @@ -418,14 +419,14 @@ describe('WebSocket reconnects', () => { // Accepted, then closed before 10 s: still backs off. latest().open(); - jest.advanceTimersByTime(9999); + vi.advanceTimersByTime(9999); latest().drop(); expect(reconnectsAfter(1999)).toBe(false); expect(reconnectsAfter(1)).toBe(true); // Open for 10 s: 1 s again. latest().open(); - jest.advanceTimersByTime(10000); + vi.advanceTimersByTime(10000); latest().drop(); expect(reconnectsAfter(999)).toBe(false); expect(reconnectsAfter(1)).toBe(true); @@ -446,10 +447,10 @@ describe('WebSocket reconnects', () => { latest().drop(); streamer.handleClose({}); // Just the reconnect: no second one and no ping interval of the dropped socket. - expect(jest.getTimerCount()).toBe(1); + expect(vi.getTimerCount()).toBe(1); - jest.spyOn(streamer, 'trackInitialEvents').mockImplementation(() => {}); - jest.spyOn(streamer, 'runEventStreamLoop').mockImplementation(() => {}); + vi.spyOn(streamer, 'trackInitialEvents').mockImplementation(() => {}); + vi.spyOn(streamer, 'runEventStreamLoop').mockImplementation(() => {}); sessionInstance.session = { gleapId: 'id2', gleapHash: 'hash2' }; streamer.restart(); expect(sockets).toHaveLength(2); @@ -482,7 +483,7 @@ describe('WebSocket reconnects', () => { // A drop while offline schedules nothing. online = false; latest().drop(); - expect(jest.getTimerCount()).toBe(0); + expect(vi.getTimerCount()).toBe(0); // Back online with an open socket: it is kept. online = true; diff --git a/src/GleapSurveyAnalyticsForwarder.test.js b/src/GleapSurveyAnalyticsForwarder.test.js index b426c386..9bd05b67 100644 --- a/src/GleapSurveyAnalyticsForwarder.test.js +++ b/src/GleapSurveyAnalyticsForwarder.test.js @@ -1,13 +1,14 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { GleapConfigManager } from './Gleap'; import { forwardSurveyAnalyticsEvent, surveyAnalyticsParams } from './GleapSurveyAnalyticsForwarder'; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, - default: { getInstance: jest.fn() }, - GleapConfigManager: { getInstance: jest.fn() }, + default: { getInstance: vi.fn() }, + GleapConfigManager: { getInstance: vi.fn() }, })); const setFlowConfig = (flowConfig) => { @@ -31,8 +32,8 @@ describe('GleapSurveyAnalyticsForwarder', () => { beforeEach(() => { setFlowConfig({}); window.dataLayer = []; - window.gtag = jest.fn(); - window.fbq = jest.fn(); + window.gtag = vi.fn(); + window.fbq = vi.fn(); }); afterEach(() => { @@ -96,19 +97,19 @@ describe('GleapSurveyAnalyticsForwarder', () => { test('each sink is optional', () => { delete window.gtag; delete window.fbq; - window.dataLayer = { push: jest.fn() }; // not an array: left alone + window.dataLayer = { push: vi.fn() }; // not an array: left alone expect(() => forwardSurveyAnalyticsEvent('survey-shown', message({ forward: true }))).not.toThrow(); expect(window.dataLayer.push).not.toHaveBeenCalled(); delete window.dataLayer; - window.fbq = jest.fn(); + window.fbq = vi.fn(); forwardSurveyAnalyticsEvent('survey-shown', message({ forward: true })); expect(window.fbq).toHaveBeenCalledTimes(1); expect(window.dataLayer).toBeUndefined(); }); test('a throwing sink does not stop the others', () => { - window.gtag = jest.fn(() => { + window.gtag = vi.fn(() => { throw new Error('gtag broken'); }); expect(forwardSurveyAnalyticsEvent('survey-shown', message({ forward: true }))).toBe(true); diff --git a/src/GleapTabCommunication.test.js b/src/GleapTabCommunication.test.js index 42b77401..6bdc5698 100644 --- a/src/GleapTabCommunication.test.js +++ b/src/GleapTabCommunication.test.js @@ -1,3 +1,4 @@ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { GleapNotificationManager, GleapSession, @@ -8,11 +9,11 @@ import GleapTabCommunication from './GleapTabCommunication'; // Keep the barrel import light (no DOM, no SDK_VERSION Webpack global): only the // managers GleapTabCommunication actually reaches for. -jest.mock('./Gleap', () => ({ - GleapNotificationManager: { getInstance: jest.fn() }, - GleapSession: { getInstance: jest.fn() }, - GleapFeedbackButtonManager: { getInstance: jest.fn() }, - GleapAiChatbarManager: { getInstance: jest.fn() }, +vi.mock('./Gleap', () => ({ + GleapNotificationManager: { getInstance: vi.fn() }, + GleapSession: { getInstance: vi.fn() }, + GleapFeedbackButtonManager: { getInstance: vi.fn() }, + GleapAiChatbarManager: { getInstance: vi.fn() }, })); // Minimal BroadcastChannel stand-in. Node's test env has no BroadcastChannel, so @@ -63,9 +64,9 @@ beforeEach(() => { MockBroadcastChannel.reset(); global.BroadcastChannel = MockBroadcastChannel; - notifStub = { clearAllNotifications: jest.fn(), clearNotificationsForConversation: jest.fn() }; - buttonStub = { updateNotificationBadge: jest.fn() }; - chatbarStub = { hideChatbarNotification: jest.fn() }; + notifStub = { clearAllNotifications: vi.fn(), clearNotificationsForConversation: vi.fn() }; + buttonStub = { updateNotificationBadge: vi.fn() }; + chatbarStub = { hideChatbarNotification: vi.fn() }; sessionStub = { sdkKey: SDK_KEY, session: { gleapId: 'user-1' } }; GleapNotificationManager.getInstance.mockReturnValue(notifStub); @@ -153,7 +154,7 @@ describe('inbound notifications-cleared', () => { test('applying the inbound clear does not post back on the channel (loop guard)', () => { const tc = GleapTabCommunication.getInstance(); tc.start(); - const postSpy = jest.spyOn(tc.channel, 'postMessage'); + const postSpy = vi.spyOn(tc.channel, 'postMessage'); openSiblingTab().postMessage({ type: 'notifications-cleared', gleapId: 'user-1' }); @@ -227,7 +228,7 @@ describe('inbound conversation-notifications-cleared', () => { test('applying the inbound clear does not post back on the channel (loop guard)', () => { const tc = GleapTabCommunication.getInstance(); tc.start(); - const postSpy = jest.spyOn(tc.channel, 'postMessage'); + const postSpy = vi.spyOn(tc.channel, 'postMessage'); openSiblingTab().postMessage({ type: 'conversation-notifications-cleared', @@ -274,7 +275,7 @@ describe('inbound chatbar-notification-cleared', () => { test('applying the inbound dismissal does not post back on the channel (loop guard)', () => { const tc = GleapTabCommunication.getInstance(); tc.start(); - const postSpy = jest.spyOn(tc.channel, 'postMessage'); + const postSpy = vi.spyOn(tc.channel, 'postMessage'); openSiblingTab().postMessage({ type: 'chatbar-notification-cleared', gleapId: 'user-1' }); diff --git a/src/GleapThemeManager.test.js b/src/GleapThemeManager.test.js index 572e380d..9a29224d 100644 --- a/src/GleapThemeManager.test.js +++ b/src/GleapThemeManager.test.js @@ -1,34 +1,35 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest'; -const mockRefreshColorScheme = jest.fn(); -const mockSetStyles = jest.fn(); -const mockSendConfigUpdate = jest.fn(); -const mockChatbarSendConfigUpdate = jest.fn(); +const mockRefreshColorScheme = vi.fn(); +const mockSetStyles = vi.fn(); +const mockSendConfigUpdate = vi.fn(); +const mockChatbarSendConfigUpdate = vi.fn(); const mockChatbar = { comReady: false, _sendConfigUpdate: mockChatbarSendConfigUpdate }; -const mockSendModalData = jest.fn(); +const mockSendModalData = vi.fn(); -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: { setStyles: (...args) => mockSetStyles(...args) }, GleapConfigManager: { getInstance: () => { - // The real config manager is used by the integration tests below. - const RealConfigManager = jest.requireActual('./GleapConfigManager').default; + // The real config manager (the module imported below, not this mock) is used by the integration tests below. + const RealConfigManager = GleapConfigManager; return mockUseRealConfigManager ? RealConfigManager.getInstance() : { refreshColorScheme: mockRefreshColorScheme, rawFlowConfig: mockDashboardConfig }; }, }, GleapFrameManager: { getInstance: () => ({ sendConfigUpdate: mockSendConfigUpdate }) }, - GleapFeedbackButtonManager: { getInstance: () => ({ updateFeedbackButtonState: jest.fn() }) }, - GleapNotificationManager: { getInstance: () => ({ updateContainerStyle: jest.fn() }) }, - GleapReplayRecorder: { getInstance: () => ({ startIfNotRunning: jest.fn(), stop: jest.fn() }) }, + GleapFeedbackButtonManager: { getInstance: () => ({ updateFeedbackButtonState: vi.fn() }) }, + GleapNotificationManager: { getInstance: () => ({ updateContainerStyle: vi.fn() }) }, + GleapReplayRecorder: { getInstance: () => ({ startIfNotRunning: vi.fn(), stop: vi.fn() }) }, GleapNetworkIntercepter: { - getInstance: () => ({ start: jest.fn(), setLoadAllResources: jest.fn(), setFilters: jest.fn(), setBlacklist: jest.fn() }), + getInstance: () => ({ start: vi.fn(), setLoadAllResources: vi.fn(), setFilters: vi.fn(), setBlacklist: vi.fn() }), }, - GleapTranslationManager: { getInstance: () => ({ updateRTLSupport: jest.fn(), getActiveLanguage: () => 'en' }) }, + GleapTranslationManager: { getInstance: () => ({ updateRTLSupport: vi.fn(), getActiveLanguage: () => 'en' }) }, GleapAiChatbarManager: { getInstance: () => mockChatbar }, GleapModalManager: { getInstance: () => ({ sendModalData: mockSendModalData }) }, GleapSession: { getInstance: () => ({}) }, @@ -57,10 +58,10 @@ const resetDocument = () => { }; beforeEach(() => { - jest.useFakeTimers(); + vi.useFakeTimers(); prefersDark = false; mediaListeners = []; - window.matchMedia = jest.fn(() => ({ + window.matchMedia = vi.fn(() => ({ get matches() { return prefersDark; }, @@ -78,11 +79,11 @@ beforeEach(() => { mockUseRealConfigManager = false; mockDashboardConfig = { colorScheme: 'light' }; mockChatbar.comReady = false; - jest.clearAllMocks(); + vi.clearAllMocks(); }); afterEach(() => { - jest.useRealTimers(); + vi.useRealTimers(); }); describe('parseColor', () => { @@ -484,7 +485,7 @@ describe('auto color scheme', () => { // Unrelated mutations don't trigger a refresh. document.body.style.overflow = 'hidden'; await Promise.resolve(); - jest.runAllTimers(); + vi.runAllTimers(); expect(mockRefreshColorScheme).toHaveBeenCalledTimes(2); document.documentElement.classList.remove('dark'); @@ -505,7 +506,7 @@ describe('auto color scheme', () => { mockRefreshColorScheme.mockClear(); document.documentElement.classList.add('dark'); await Promise.resolve(); - jest.runAllTimers(); + vi.runAllTimers(); expect(mockRefreshColorScheme).not.toHaveBeenCalled(); }); @@ -538,7 +539,7 @@ describe('GleapConfigManager integration', () => { const configManager = GleapConfigManager.getInstance(); configManager.applyConfig(serverConfig()); expect(configManager.getFlowConfig().backgroundColor).toBe('#FFFFFF'); - jest.clearAllMocks(); + vi.clearAllMocks(); // Still light (light host), so nothing is re-sent. GleapThemeManager.getInstance().setColorScheme('auto'); @@ -575,7 +576,7 @@ describe('GleapConfigManager integration', () => { const configManager = GleapConfigManager.getInstance(); configManager.applyConfig({ flowConfig: { ...serverConfig().flowConfig, colorScheme: 'auto', darkBackgroundColor: '#101828' } }); expect(configManager.getFlowConfig().backgroundColor).toBe('#FFFFFF'); - jest.clearAllMocks(); + vi.clearAllMocks(); document.documentElement.classList.add('dark'); await Promise.resolve(); @@ -599,7 +600,7 @@ describe('GleapConfigManager integration', () => { expect(configManager.getFlowConfig()).toBe(flowConfig); const checklist = document.createElement('gleap-checklist'); document.body.appendChild(checklist); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); expect(configManager.getFlowConfig()).toBe(flowConfig); @@ -618,7 +619,7 @@ describe('GleapConfigManager integration', () => { configManager.applyConfig({ flowConfig }); const checklist = document.createElement('gleap-checklist'); document.body.appendChild(checklist); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark', { darkBackgroundColor: '#000000' }); expect(configManager.getFlowConfig()).toBe(flowConfig); @@ -651,9 +652,9 @@ describe('GleapConfigManager integration', () => { const checklist = document.createElement('gleap-checklist'); checklist._hasLoaded = true; checklist.checklistData = { id: 'c1' }; - checklist.renderChecklist = jest.fn(); + checklist.renderChecklist = vi.fn(); document.body.appendChild(checklist); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); const flowConfig = configManager.getFlowConfig(); @@ -675,7 +676,7 @@ describe('GleapConfigManager integration', () => { configManager.applyConfig({ flowConfig: { colorScheme: 'light', backgroundColor: '#111111', color: '#485BFF', headerColor: '#485BFF', darkBackgroundColor: '#111111' }, }); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); expect(configManager.getFlowConfig().backgroundColor).toBe('#111111'); @@ -706,7 +707,7 @@ describe('GleapConfigManager integration', () => { darkAurora: { ...aurora, seed: 2 }, }, }); - jest.clearAllMocks(); + vi.clearAllMocks(); GleapThemeManager.getInstance().setColorScheme('dark'); const flowConfig = configManager.getFlowConfig(); diff --git a/src/GleapTooltipManager.test.js b/src/GleapTooltipManager.test.js index 9b6748d8..17ad2dfb 100644 --- a/src/GleapTooltipManager.test.js +++ b/src/GleapTooltipManager.test.js @@ -1,25 +1,26 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, test, expect, vi, beforeEach } from 'vitest'; import GleapTooltipManager from './GleapTooltipManager'; -jest.mock('./Gleap', () => ({ +vi.mock('./Gleap', () => ({ __esModule: true, default: {}, - GleapSession: { getInstance: jest.fn(() => ({})) }, + GleapSession: { getInstance: vi.fn(() => ({})) }, })); -jest.mock('./UI', () => ({ - loadIcon: jest.fn(() => ''), +vi.mock('./UI', () => ({ + loadIcon: vi.fn(() => ''), })); -jest.mock('@floating-ui/dom', () => ({ - autoUpdate: jest.fn(() => jest.fn()), - computePosition: jest.fn(() => Promise.resolve({ x: 0, y: 0, middlewareData: {}, placement: 'right' })), - arrow: jest.fn(), - flip: jest.fn(), - offset: jest.fn(), - shift: jest.fn(), +vi.mock('@floating-ui/dom', () => ({ + autoUpdate: vi.fn(() => vi.fn()), + computePosition: vi.fn(() => Promise.resolve({ x: 0, y: 0, middlewareData: {}, placement: 'right' })), + arrow: vi.fn(), + flip: vi.fn(), + offset: vi.fn(), + shift: vi.fn(), })); const hotspotTooltip = (overrides = {}) => ({ diff --git a/src/GleapTourSelector.test.js b/src/GleapTourSelector.test.js index 28f9a10a..16dfba6f 100644 --- a/src/GleapTourSelector.test.js +++ b/src/GleapTourSelector.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, beforeEach } from 'vitest'; import { UNSTABLE_SELECTOR_PATTERN, buildStableSelector } from './GleapTourSelector'; const resolvesToElement = (selector, element) => { diff --git a/src/GleapTours.test.js b/src/GleapTours.test.js index 81cb417d..c85151bb 100644 --- a/src/GleapTours.test.js +++ b/src/GleapTours.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import GleapTours from './GleapTours'; // jsdom has no layout, so every element reports no client rects. Treat an @@ -20,11 +21,11 @@ describe('GleapTours step target resolution', () => { let onElementNotFound; beforeEach(() => { - jest.useFakeTimers(); - jest.spyOn(Element.prototype, 'getClientRects').mockImplementation(function () { + vi.useFakeTimers(); + vi.spyOn(Element.prototype, 'getClientRects').mockImplementation(function () { return isHiddenInTest(this) ? [] : [{ top: 0, left: 0, width: 40, height: 20 }]; }); - onElementNotFound = jest.fn(() => tour.destroy()); + onElementNotFound = vi.fn(() => tour.destroy()); }); afterEach(() => { @@ -32,9 +33,9 @@ describe('GleapTours step target resolution', () => { tour.destroy(); } tour = null; - jest.runOnlyPendingTimers(); - jest.useRealTimers(); - jest.restoreAllMocks(); + vi.runOnlyPendingTimers(); + vi.useRealTimers(); + vi.restoreAllMocks(); document.body.innerHTML = ''; }); @@ -65,7 +66,7 @@ describe('GleapTours step target resolution', () => { expect(tour.getActiveElement()).toBeUndefined(); expect(document.querySelector('.label').classList.contains('gleap-tour-active-element')).toBe(false); - jest.advanceTimersByTime(5200); + vi.advanceTimersByTime(5200); expect(onElementNotFound).toHaveBeenCalledTimes(1); expect(onElementNotFound.mock.calls[0][0].element).toBe('.menu-item > .label'); @@ -86,12 +87,12 @@ describe('GleapTours step target resolution', () => { document.body.innerHTML = ''; startTour('.menu-item > .label'); - jest.advanceTimersByTime(1000); + vi.advanceTimersByTime(1000); document.querySelector('.label').style.display = ''; - jest.advanceTimersByTime(200); + vi.advanceTimersByTime(200); expect(tour.getActiveElement()).toBe(document.querySelector('.label')); - jest.advanceTimersByTime(5000); + vi.advanceTimersByTime(5000); expect(onElementNotFound).not.toHaveBeenCalled(); }); @@ -99,7 +100,7 @@ describe('GleapTours step target resolution', () => { document.body.innerHTML = ''; startTour('.menu-item > .label'); - jest.advanceTimersByTime(5200); + vi.advanceTimersByTime(5200); expect(onElementNotFound).toHaveBeenCalledTimes(1); }); diff --git a/src/GleapUserJwt.test.js b/src/GleapUserJwt.test.js index 21b01e47..ddb04eee 100644 --- a/src/GleapUserJwt.test.js +++ b/src/GleapUserJwt.test.js @@ -1,3 +1,4 @@ +import { describe, it, expect } from 'vitest'; import { decodeUserJwt, identifyRefusalOf } from './GleapUserJwt'; const b64url = (value) => Buffer.from(value).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); diff --git a/src/ScreenCapture.test.js b/src/ScreenCapture.test.js index c408f8b8..959171e1 100644 --- a/src/ScreenCapture.test.js +++ b/src/ScreenCapture.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, test, expect, vi, beforeEach, afterEach } from 'vitest'; import { startScreenCapture } from './ScreenCapture'; @@ -15,7 +16,7 @@ const fakeAnimation = (target, property = 'opacity') => ({ }); const installRootAnimations = (root, animations) => { - root.getAnimations = jest.fn(() => animations); + root.getAnimations = vi.fn(() => animations); return root.getAnimations; }; @@ -215,7 +216,7 @@ const fakeComputedStyle = (values) => { // A '::before' / '::after' entry in an element's values is the style of that pseudo-element. const stubComputedStyles = (stylesByElement) => { const getComputedStyle = window.getComputedStyle; - jest.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => { + vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudo) => { if (!stylesByElement.has(element)) { return getComputedStyle.call(window, element, pseudo); } @@ -255,7 +256,7 @@ describe('startScreenCapture — blocked elements', () => { }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); }); // Private: the text, the attributes (the id too), and a nested image, link and field. @@ -465,8 +466,8 @@ describe('startScreenCapture — blocked elements', () => { '
' + ''; const requested = []; - jest.spyOn(XMLHttpRequest.prototype, 'open').mockImplementation((method, url) => requested.push(url)); - jest.spyOn(XMLHttpRequest.prototype, 'send').mockImplementation(function () { + vi.spyOn(XMLHttpRequest.prototype, 'open').mockImplementation((method, url) => requested.push(url)); + vi.spyOn(XMLHttpRequest.prototype, 'send').mockImplementation(function () { this.onerror(); }); @@ -509,7 +510,7 @@ describe('startScreenCapture — blocked elements keep the layout around them', }); afterEach(() => { - jest.restoreAllMocks(); + vi.restoreAllMocks(); delete Range.prototype.getClientRects; }); @@ -724,7 +725,7 @@ describe('startScreenCapture — blocked elements keep the layout around them', describe('baselines', () => { beforeEach(() => { - jest.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ + vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ measureText: () => ({ fontBoundingBoxAscent: 14 }), }); }); @@ -844,7 +845,7 @@ describe('startScreenCapture — masked text', () => { }); test("the site's maskTextFn formats masked text, as in replays", async () => { - const maskTextFn = jest.fn((text) => `[${text.length}]`); + const maskTextFn = vi.fn((text) => `[${text.length}]`); document.body.innerHTML = '

Jane Doe

'; const doc = parse((await startScreenCapture(true, { maskTextFn })).html); @@ -952,7 +953,7 @@ describe('startScreenCapture — frames', () => { document.body.innerHTML = ''; document.getElementById('dialog').contentDocument.body.innerHTML = '

Fortschritt

'; const setAttribute = Element.prototype.setAttribute; - const spy = jest.spyOn(HTMLIFrameElement.prototype, 'setAttribute').mockImplementation(function (name, value) { + const spy = vi.spyOn(HTMLIFrameElement.prototype, 'setAttribute').mockImplementation(function (name, value) { if (name === 'srcdoc') { throw new TypeError("This document requires 'TrustedHTML' assignment."); } diff --git a/src/ScreenDrawer.test.js b/src/ScreenDrawer.test.js index 0fde6113..4a8bbdc3 100644 --- a/src/ScreenDrawer.test.js +++ b/src/ScreenDrawer.test.js @@ -1,6 +1,7 @@ /** - * @jest-environment jsdom + * @vitest-environment jsdom */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { ScreenDrawer } from './ScreenDrawer'; const setScroll = (x, y) => { diff --git a/tools/quality/analyze.mjs b/tools/quality/analyze.mjs new file mode 100644 index 00000000..73528fb1 --- /dev/null +++ b/tools/quality/analyze.mjs @@ -0,0 +1,618 @@ +// Parses one file and collects what the rules compare. Parsing only: no Program, no type information. +import { createHash } from 'node:crypto'; +import { posix } from 'node:path'; + +import ts from 'typescript'; + +import { measureLines } from './measure.mjs'; + +const WRAPPER_CALL = /^(observer|memo|forwardRef|inject|useCallback|useMemo|debounce|throttle|with[A-Z]\w*)$/; +const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/; +const ALLOW_COMMENT = /quality-allow[ \t]+([a-z-]+)[ \t]*:[ \t]*(\S.*?)[ \t]*(?:\*\/)?[ \t]*$/m; +// @ts-expect-error is fine with a reason on the same line. +const TS_SUPPRESSION = /@ts-(ignore|nocheck)\b|@ts-expect-error[:\s-]*(\*\/)?\s*$/m; +const BASE_COUNTERS = [ + 'any', + 'ts-ignore', + 'console-log', + 'string-compare', + 'default-export', + 'comment-reference', + 'comment-attribution', + 'comment-date', + 'type-assertion', + 'non-null-assertion', + 'const-enum', +]; +// `#` needs 4 digits, because #123 is a colour. A word needs the singular: "tickets 100 per page" is no reference. +const COMMENT_REFERENCE = /(? ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node); + +const MODULE_EXTENSION = /\.[cm]?[jt]sx?$/; + +// The module a relative path names, from the repo root: code that moves to another folder re-paths its require, yet +// still loads the same module, so the move pool must see the same item. +const moduleTargetOf = ({ path, specifier }) => + specifier.startsWith('.') ? posix.normalize(posix.join(posix.dirname(path), specifier)).replace(MODULE_EXTENSION, '') : specifier; + +const isFunctionWithBody = (node) => + Boolean(node.body) && + (ts.isFunctionDeclaration(node) || + ts.isFunctionExpression(node) || + ts.isArrowFunction(node) || + ts.isMethodDeclaration(node) || + ts.isConstructorDeclaration(node) || + ts.isGetAccessorDeclaration(node) || + ts.isSetAccessorDeclaration(node)); + +const isJsxNode = (node) => ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node); + +const isJsxResult = (expression) => { + if (!expression) return false; + const node = ts.skipOuterExpressions(expression); + if (isJsxNode(node)) return true; + if (ts.isConditionalExpression(node)) return isJsxResult(node.whenTrue) || isJsxResult(node.whenFalse); + if (ts.isBinaryExpression(node) && !EQUALITY_OPERATORS.has(node.operatorToken.kind)) { + return isJsxResult(node.left) || isJsxResult(node.right); + } + return false; +}; + +const calleeHead = (callee) => { + if (ts.isIdentifier(callee)) return callee.text; + if (ts.isPropertyAccessExpression(callee)) return callee.name.text; + if (ts.isCallExpression(callee)) return calleeHead(callee.expression); + return ''; +}; + +const isTransparent = (parent, child) => + ts.isParenthesizedExpression(parent) || + ts.isAsExpression(parent) || + ts.isSatisfiesExpression(parent) || + ts.isNonNullExpression(parent) || + ts.isTypeAssertionExpression(parent) || + (ts.isCallExpression(parent) && parent.arguments.includes(child) && WRAPPER_CALL.test(calleeHead(parent.expression))); + +const outermost = (node) => { + let current = node; + while (current.parent && isTransparent(current.parent, current)) current = current.parent; + return current; +}; + +const isCallArgumentOrJsx = (node) => { + let current = node; + while ( + current.parent && + (ts.isObjectLiteralExpression(current.parent) || + ts.isArrayLiteralExpression(current.parent) || + ts.isPropertyAssignment(current.parent) || + isTransparent(current.parent, current)) + ) { + current = current.parent; + } + const parent = current.parent; + return Boolean(parent) && (ts.isCallExpression(parent) || ts.isNewExpression(parent) || ts.isJsxExpression(parent)); +}; + +const propertyNameText = (name) => (ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : name.getText()); + +const describeExpressionFunction = (node) => { + const outer = outermost(node); + const parent = outer.parent; + if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) { + return { name: parent.name.text, isTyped: Boolean(parent.type) }; + } + if (ts.isPropertyAssignment(parent)) { + return { name: propertyNameText(parent.name), isCallback: isCallArgumentOrJsx(parent.parent) }; + } + if (ts.isPropertyDeclaration(parent)) return { name: propertyNameText(parent.name), isTyped: Boolean(parent.type) }; + if (ts.isBinaryExpression(parent) && parent.right === outer) return { name: parent.left.getText() }; + if (ts.isExportAssignment(parent)) return { name: 'default' }; + return { isCallback: ts.isCallExpression(parent) || ts.isNewExpression(parent) || ts.isJsxExpression(parent), outer }; +}; + +const describeFunction = (node) => { + if (ts.isFunctionDeclaration(node)) return { name: node.name?.text ?? 'default' }; + if (ts.isConstructorDeclaration(node)) return { name: 'constructor' }; + if (ts.isGetAccessorDeclaration(node)) return { name: `get ${propertyNameText(node.name)}` }; + if (ts.isSetAccessorDeclaration(node)) return { name: `set ${propertyNameText(node.name)}` }; + if (ts.isMethodDeclaration(node)) { + const isCallback = ts.isObjectLiteralExpression(node.parent) && isCallArgumentOrJsx(node.parent); + return { name: propertyNameText(node.name), isCallback }; + } + return describeExpressionFunction(node); +}; + +const moduleLevelCallbackName = (outer) => { + let current = outer.parent; + while (current && (ts.isCallExpression(current) || isTransparent(current.parent ?? current, current))) { + if (ts.isVariableDeclaration(current.parent) && ts.isIdentifier(current.parent.name)) return current.parent.name.text; + current = current.parent; + } + if (!outer.parent || !ts.isCallExpression(outer.parent)) return 'anonymous'; + const firstArgument = outer.parent.arguments[0]; + const callee = outer.parent.expression.getText().replace(/\s+/g, '').slice(0, 60); + return firstArgument && isStringLiteral(firstArgument) ? `${callee}('${firstArgument.text}')` : callee; +}; + +const bodyHashOf = (node) => { + const text = `${node.parameters.map((parameter) => parameter.getText()).join(',')}=>${node.body.getText()}`; + return createHash('sha1').update(text.replace(/\s+/g, '')).digest('hex'); +}; + +// `@Request() request: any` is the one exemption from counting `any`: there are 1372 of these and no usable type yet. +// A typed request belongs to the strict-types step. +const isDecoratedRequestAny = (node) => { + const parameter = node.parent; + if (!ts.isParameter(parameter) || parameter.type !== node) return false; + return (ts.getDecorators(parameter) ?? []).some((decorator) => calleeHead(decorator.expression) === 'Request'); +}; + +const isConsoleNoise = (node) => { + if (ts.isPropertyAccessExpression(node)) { + return CONSOLE_METHODS.has(node.name.text) && CONSOLE_OBJECT.test(node.expression.getText()); + } + if (ts.isElementAccessExpression(node) && isStringLiteral(node.argumentExpression)) { + return CONSOLE_METHODS.has(node.argumentExpression.text) && CONSOLE_OBJECT.test(node.expression.getText()); + } + if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer) { + if (!CONSOLE_OBJECT.test(node.initializer.getText())) return false; + return node.name.elements.some((element) => CONSOLE_METHODS.has((element.propertyName ?? element.name).getText())); + } + return false; +}; + +// `x as unknown as T` is `any` in disguise, and agents would move there if it counted as less. +const isDoubleAssertion = (node) => { + if (!ts.isAsExpression(node) || node.type.kind === ts.SyntaxKind.UnknownKeyword) return false; + const inner = ts.skipOuterExpressions(node.expression, ts.OuterExpressionKinds.Parentheses); + return ts.isAsExpression(inner) && inner.type.kind === ts.SyntaxKind.UnknownKeyword; +}; + +const isPartOfDoubleAssertion = (node) => { + const outer = ts.isParenthesizedExpression(node.parent) ? node.parent.parent : node.parent; + return node.type.kind === ts.SyntaxKind.UnknownKeyword && ts.isAsExpression(outer); +}; + +const isCountedAssertion = (node) => { + if (!ts.isAsExpression(node) && !ts.isTypeAssertionExpression(node)) return false; + if (ts.isConstTypeReference(node.type) || node.type.kind === ts.SyntaxKind.AnyKeyword) return false; + if (isDoubleAssertion(node) || isPartOfDoubleAssertion(node)) return false; + return !ts.isAsExpression(node.parent); +}; + +const isConstEnum = (node) => ts.isEnumDeclaration(node) && (node.modifiers ?? []).some(({ kind }) => kind === ts.SyntaxKind.ConstKeyword); + +const isRouteRegistration = (node) => { + if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) return false; + const { name, expression: receiver } = node.expression; + if (!HTTP_VERBS.has(name.text) || node.arguments.length < 2 || !ROUTE_RECEIVER.test(receiver.getText())) return false; + const [path] = node.arguments; + return isStringLiteral(path) || ts.isTemplateExpression(path) || ts.isRegularExpressionLiteral(path) || ts.isArrayLiteralExpression(path); +}; + +const isEmptyConflictError = (node) => { + if (!ts.isNewExpression(node) || node.expression.getText() !== 'ConflictError') return false; + const [first] = node.arguments ?? []; + return !first || (ts.isObjectLiteralExpression(first) && first.properties.length === 0); +}; + +const isLoadCall = (node) => + ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(node.expression) && node.expression.text === 'require')); + +const requireTargetOf = (node) => (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference) ? node.moduleReference.expression : null); + +// A require or import() inside a function hides an import cycle. Only heavy packages may load late. +const isLocalRequire = ({ node, owner, config }) => { + const importEqualsTarget = requireTargetOf(node); + if (importEqualsTarget) return isStringLiteral(importEqualsTarget) && importEqualsTarget.text.startsWith('.'); + if (!isLoadCall(node)) return false; + const [target] = node.arguments; + if (!target) return false; + if (!isStringLiteral(target)) return Boolean(owner); + if (target.text.startsWith('.')) return true; + return Boolean(owner) && !config.lazyRequireAllowed.test(target.text); +}; + +const isDefaultExport = (node) => { + if (ts.isExportAssignment(node)) return !node.isExportEquals; + if (ts.isExportSpecifier(node)) return node.name.text === 'default'; + if (!ts.isFunctionDeclaration(node) && !ts.isClassDeclaration(node)) return false; + return (node.modifiers ?? []).some(({ kind }) => kind === ts.SyntaxKind.DefaultKeyword); +}; + +// In a comment, #808080 and #00000080 are colours: a grey repeats one pair, and ticket numbers have 6 digits at most. +const looksLikeHexColor = (digits) => digits.length === 8 || /^(\d\d)\1\1$/.test(digits); + +const namesReference = (comment) => + [...comment.replace(NOT_A_REFERENCE, '').matchAll(COMMENT_REFERENCE)].some(([, hashDigits]) => !hashDigits || !looksLikeHexColor(hashDigits)); + +// First names of the git authors of both repos. Kai and Claude are products, not people. +const TEAM_NAME = /\b(?:Lukas|Tobias|Luca|Florian|Manuel|Hagop|Eleni|Simon|Niklas|Andrei|Ali)\b/g; +// A year before 2025 is an API version such as Twilio's 2010-04-01, never a stamp. A date after a quote is data. +const MONTH_DAY = /(? { + const groups = []; + let previous = null; + let allow = null; + for (const comment of comments) { + const isLineComment = comment.text.startsWith('//'); + if (isLineComment && ALLOW_COMMENT.test(comment.text)) { + previous = null; + allow = { rule: comment.text.match(ALLOW_COMMENT)[1], line: comment.line }; + continue; + } + const lines = comment.text + .split('\n') + .map((text, offset) => ({ text: ALLOW_LINE.test(text) ? '' : text, line: isLineComment ? comment.startLine + offset : comment.startLine })); + const continues = previous?.isLineComment && isLineComment && comment.startLine === previous.line + 1; + if (continues) groups.at(-1).lines.push(...lines); + else groups.push({ lines, allowedRule: allow?.line === comment.startLine - 1 ? allow.rule : null }); + previous = { isLineComment, line: comment.line }; + allow = null; + } + return groups; +}; + +const blank = (text) => text.replace(/[^\n]/g, ' '); + +// The group as one text with the comment markers and quotes blanked out, so every offset still points into its line. +const proseOf = (lines) => + lines + .map(({ text }) => text.replace(/^[ \t]*(?:\/\/+|\/\*+|\*+)/, blank).replace(/\*\/\s*$/, blank)) + .join('\n') + .replace(QUOTED_OR_LINK, blank); + +// A date in parentheses stamps when something happened nearly every time; elsewhere it is sometimes a reason. +const markDates = ({ prose, mark }) => { + let depth = 0; + let scanned = 0; + for (const match of prose.matchAll(MONTH_DAY)) { + for (; scanned < match.index; scanned += 1) { + if (prose[scanned] === '(') depth += 1; + if (prose[scanned] === ')') depth = Math.max(0, depth - 1); + } + const before = prose.slice(Math.max(0, match.index - LOOK_AROUND), match.index); + const end = match.index + match[0].length; + if (RANGE_OR_EXAMPLE_BEFORE.test(before) || RANGE_OR_UNIT_AFTER.test(prose.slice(end, end + LOOK_AROUND))) continue; + mark(match.index, depth > 0 && !CUTOFF_BEFORE.test(before) ? 'comment-attribution' : 'comment-date'); + } +}; + +const firstAbove = ({ sorted, value }) => { + let low = 0; + let high = sorted.length - 1; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (value < sorted[middle]) high = middle; + else low = middle + 1; + } + return low; +}; + +const readAttributions = ({ comments, counters }) => { + for (const { lines, allowedRule } of commentGroupsOf(comments)) { + const prose = proseOf(lines); + const lineEnds = []; + for (const { text } of lines) lineEnds.push((lineEnds.at(-1) ?? -1) + text.length + 1); + const rules = new Map(); + const mark = (offset, rule) => { + const index = firstAbove({ sorted: lineEnds, value: offset }); + if ((RULE_WEIGHT[rules.get(index)] ?? 0) < RULE_WEIGHT[rule]) rules.set(index, rule); + }; + for (const match of prose.matchAll(TEAM_NAME)) mark(match.index, 'comment-attribution'); + markDates({ prose, mark }); + for (const [index, rule] of rules) counters[rule].push({ line: rule === allowedRule ? lines[0].line : lines[index].line, text: lines[index].text.trim() }); + } +}; + +const hasOnlyTypes = (elements) => elements.length > 0 && elements.every((element) => element.isTypeOnly); + +const isTypeOnlyImport = ({ importClause }) => { + if (!importClause) return false; + if (importClause.isTypeOnly) return true; + const { name, namedBindings } = importClause; + return !name && Boolean(namedBindings) && ts.isNamedImports(namedBindings) && hasOnlyTypes(namedBindings.elements); +}; + +const isTypeOnlyReExport = ({ isTypeOnly, exportClause }) => isTypeOnly || (Boolean(exportClause) && ts.isNamedExports(exportClause) && hasOnlyTypes(exportClause.elements)); + +// The string that names the module an import, export, require or import() loads. +const moduleSpecifierNodeOf = (node) => { + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) return node.moduleSpecifier ?? null; + const target = requireTargetOf(node) ?? (isLoadCall(node) ? node.arguments[0] : null); + return target && isStringLiteral(target) ? target : null; +}; + +// Every way this file reaches another module, static or late. +const moduleUseOf = (node) => { + if (ts.isImportDeclaration(node)) return { specifier: node.moduleSpecifier.text, isTypeOnly: isTypeOnlyImport(node) }; + if (ts.isExportDeclaration(node) && node.moduleSpecifier) return { specifier: node.moduleSpecifier.text, isTypeOnly: isTypeOnlyReExport(node) }; + const target = moduleSpecifierNodeOf(node); + return target ? { specifier: target.text, isTypeOnly: false } : null; +}; + +const isStringComparisonToCount = ({ compared, literal, strings }) => { + const other = ts.skipOuterExpressions(compared); + if (literal.text === '' || ts.isTypeOfExpression(other)) return false; + const isProperty = ts.isPropertyAccessExpression(other); + const name = isProperty ? other.name.text : ts.isIdentifier(other) ? other.text : ''; + return !strings.isExempt({ name, receiver: isProperty ? other.expression.getText() : '', value: literal.text }); +}; + +const collectFacts = ({ path, sourceFile, measure, config }) => { + const { lineOf, codeLinesOf } = measure; + const lineTexts = sourceFile.text.split('\n'); + const functions = new Map(); + const regions = new Map(); + const counters = Object.fromEntries([...BASE_COUNTERS, ...config.extraCounters].map((rule) => [rule, []])); + const usedKeys = new Map(); + const imports = []; + + const lineNumberOf = (node) => lineOf(node.getStart(sourceFile)) + 1; + // An item is its line; a relative module path in it counts as the module it names (moduleTargetOf). + const count = (rule, line, specifierNode = null) => { + const text = lineTexts[line - 1].trim(); + const raw = specifierNode && isStringLiteral(specifierNode) && specifierNode.text.startsWith('.') ? specifierNode.getText(sourceFile) : null; + const item = raw && text.includes(raw) ? text.replace(raw, `<${moduleTargetOf({ path, specifier: specifierNode.text })}>`) : text; + counters[rule].push({ line, text: item }); + }; + const uniqueKey = (key) => { + const seen = (usedKeys.get(key) ?? 0) + 1; + usedKeys.set(key, seen); + return seen === 1 ? key : `${key}#${seen}`; + }; + const qualify = (scope, name) => (scope ? `${scope}.${name}` : name); + + const recordJsx = (owner, node) => { + if (!owner) return; + const lines = codeLinesOf(node); + if (lines > owner.jsxReturnLines) { + owner.jsxReturnLines = lines; + owner.jsxReturnLine = lineNumberOf(node); + } + }; + + const trackFunction = (node, { naming, context }) => { + const name = naming.name ?? moduleLevelCallbackName(naming.outer); + const params = node.parameters.filter((parameter) => parameter.name.getText() !== 'this'); + const fact = { + key: uniqueKey(qualify(context.scope, name)), + name, + bodyHash: bodyHashOf(node), + line: lineNumberOf(node), + lines: codeLinesOf(node), + params: params.length, + isParamsExempt: + Boolean(naming.isCallback || naming.isTyped) || params.some((parameter) => parameter.type?.getText() === 'NextFunction'), + isNested: Boolean(context.owner), + hasOwnJsx: false, + returnsJsx: false, + jsxReturnLines: 0, + jsxReturnLine: lineNumberOf(node), + }; + functions.set(fact.key, fact); + return fact; + }; + + const countComparison = (node) => { + const { stringExemptions: strings } = config; + if (ts.isBinaryExpression(node) && EQUALITY_OPERATORS.has(node.operatorToken.kind)) { + const right = ts.skipOuterExpressions(node.right); + const left = ts.skipOuterExpressions(node.left); + const [literal, compared] = isStringLiteral(right) ? [right, node.left] : [left, node.right]; + if (isStringLiteral(literal) && isStringComparisonToCount({ compared, literal, strings })) count('string-compare', lineNumberOf(node)); + } + if (ts.isCaseClause(node)) { + const literal = ts.skipOuterExpressions(node.expression); + const compared = node.parent.parent.expression; + if (isStringLiteral(literal) && isStringComparisonToCount({ compared, literal, strings })) count('string-compare', lineNumberOf(node)); + } + }; + + const countBannedImport = (node) => { + const moduleUse = moduleUseOf(node); + if (!moduleUse || moduleUse.isTypeOnly) return; + for (const { rule, module, isExemptFile } of config.bannedImports) { + if (module.test(moduleUse.specifier) && !isExemptFile?.(path)) count(rule, lineNumberOf(node), moduleSpecifierNodeOf(node)); + } + }; + + const countOptionalRules = (node, owner) => { + if (counters['local-require'] && isLocalRequire({ node, owner, config })) count('local-require', lineNumberOf(node), moduleSpecifierNodeOf(node)); + if (counters['server-logs'] && ts.isCallExpression(node) && node.expression.getText() === 'ServerLogs.send') count('server-logs', lineNumberOf(node)); + if (counters['empty-conflict-error'] && isEmptyConflictError(node)) count('empty-conflict-error', lineNumberOf(node)); + if (counters['route-outside-tsoa'] && isRouteRegistration(node)) count('route-outside-tsoa', lineNumberOf(node)); + }; + + const recordRegion = (node) => { + if (ts.isEnumDeclaration(node)) regions.set(`enum:${node.name.text}`, codeLinesOf(node)); + if (ts.isInterfaceDeclaration(node)) regions.set(`type:${node.name.text}`, codeLinesOf(node)); + if (ts.isTypeAliasDeclaration(node) && ts.isTypeLiteralNode(node.type)) regions.set(`type:${node.name.text}`, codeLinesOf(node)); + if (ts.isNewExpression(node) && calleeHead(node.expression) === 'Schema') { + const holder = ts.isVariableDeclaration(node.parent) ? node.parent.name.getText() : lineNumberOf(node); + regions.set(`schema:${holder}`, codeLinesOf(node)); + } + }; + + const isObjectValue = (value) => Boolean(value) && ts.isObjectLiteralExpression(ts.skipOuterExpressions(value)); + + const scopeFor = (node, scope) => { + if (ts.isClassLike(node)) return qualify(scope, node.name?.text ?? 'default'); + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && isObjectValue(node.initializer)) { + return qualify(scope, node.name.text); + } + if (ts.isPropertyAssignment(node) && isObjectValue(node.initializer)) return qualify(scope, propertyNameText(node.name)); + return scope; + }; + + const walk = (node, context) => { + if (isDefaultExport(node) && !config.defaultExports.isExemptFile(path)) count('default-export', lineNumberOf(node)); + const moduleUse = moduleUseOf(node); + if (moduleUse) imports.push({ ...moduleUse, line: lineNumberOf(node) }); + if (isFunctionWithBody(node)) return walkFunction(node, context); + if (node.kind === ts.SyntaxKind.AnyKeyword && !isDecoratedRequestAny(node)) count('any', lineNumberOf(node)); + if (isConsoleNoise(node)) count('console-log', lineNumberOf(node)); + if (isDoubleAssertion(node)) count('any', lineNumberOf(node)); + if (isCountedAssertion(node)) count('type-assertion', lineNumberOf(node)); + if (ts.isNonNullExpression(node)) count('non-null-assertion', lineNumberOf(node)); + if (isConstEnum(node)) count('const-enum', lineNumberOf(node)); + countComparison(node); + countBannedImport(node); + countOptionalRules(node, context.owner); + recordRegion(node); + let { isInsideJsx } = context; + if (isJsxNode(node)) { + if (context.owner) context.owner.hasOwnJsx = true; + if (!isInsideJsx) recordJsx(context.owner, node); + isInsideJsx = true; + } + if (ts.isReturnStatement(node) && isJsxResult(node.expression) && context.owner) { + recordJsx(context.owner, node); + if (context.isDirect) context.owner.returnsJsx = true; + } + const next = { ...context, isInsideJsx, scope: scopeFor(node, context.scope) }; + ts.forEachChild(node, (child) => walk(child, next)); + }; + + const walkFunction = (node, context) => { + const naming = describeFunction(node); + // An unnamed callback inside a named function belongs to that function. + const fact = naming.name || !context.owner ? trackFunction(node, { naming, context }) : null; + const inner = fact ? { scope: fact.key, owner: fact, isDirect: true, isInsideJsx: false } : { ...context, isDirect: false }; + if (ts.isArrowFunction(node) && isJsxResult(node.body) && inner.owner) { + if (!inner.isInsideJsx) recordJsx(inner.owner, node.body); + if (inner.isDirect) inner.owner.returnsJsx = true; + } + ts.forEachChild(node, (child) => walk(child, inner)); + }; + + ts.forEachChild(sourceFile, (child) => walk(child, { scope: '', owner: null, isDirect: false, isInsideJsx: false })); + + for (const fact of functions.values()) { + const baseName = fact.name.split('.').pop(); + const looksLikeComponent = PASCAL_CASE.test(baseName) || fact.name === 'default' || fact.name === 'render'; + fact.isComponent = fact.hasOwnJsx && looksLikeComponent; + fact.isPascalCase = PASCAL_CASE.test(baseName); + fact.baseName = baseName; + } + return { functions, regions, counters, imports }; +}; + +const readComments = ({ comments, counters }) => { + const allows = []; + for (const comment of comments) { + if (TS_SUPPRESSION.test(comment.text)) { + counters['ts-ignore'].push({ line: comment.line, text: comment.text.trim() }); + } + if (namesReference(comment.text)) counters['comment-reference'].push({ line: comment.startLine, text: comment.text.trim() }); + const match = comment.text.match(ALLOW_COMMENT); + if (match) allows.push({ rule: match[1], reason: match[2], line: comment.line }); + } + readAttributions({ comments, counters }); + return allows; +}; + +const isLiteralValue = (value) => { + if (!value) return false; + const node = ts.skipOuterExpressions(value); + return ( + ts.isObjectLiteralExpression(node) || + ts.isArrayLiteralExpression(node) || + ts.isStringLiteral(node) || + ts.isNoSubstitutionTemplateLiteral(node) || + ts.isTemplateExpression(node) + ); +}; + + +// A table has no logic to split, whatever its file is called: translations, templates, time zones. +const isDataFile = ({ sourceFile, measure, functions, limits }) => { + if (measure.codeLines < limits.dataMinLines) return false; + let dataLines = 0; + for (const statement of sourceFile.statements) { + const isLiteral = ts.isVariableStatement(statement) + ? statement.declarationList.declarations.every((declaration) => isLiteralValue(declaration.initializer)) + : ts.isExportAssignment(statement) && isLiteralValue(statement.expression); + if (isLiteral) dataLines += measure.codeLinesOf(statement); + } + for (const fact of functions.values()) if (!fact.isNested) dataLines -= fact.lines; + return dataLines / measure.codeLines >= limits.dataShare; +}; + +export const analyzeSource = ({ path, source, config }) => { + const sourceFile = ts.createSourceFile( + path, + source, + { languageVersion: ts.ScriptTarget.Latest, jsDocParsingMode: ts.JSDocParsingMode.ParseNone }, + true, + SCRIPT_KINDS.get(path.split('.').pop()) ?? ts.ScriptKind.TS + ); + const measure = measureLines({ sourceFile, lineChars: config.limits.lineChars }); + const { functions, regions, counters, imports } = collectFacts({ path, sourceFile, measure, config }); + const allows = readComments({ comments: measure.comments, counters }); + const [parseError] = sourceFile.parseDiagnostics; + const importLines = new Set(); + let importCodeLines = 0; + for (const statement of sourceFile.statements) { + if (!ts.isImportDeclaration(statement) && !(ts.isExportDeclaration(statement) && statement.moduleSpecifier)) continue; + importCodeLines += measure.codeLinesOf(statement); + const lastLine = measure.lineOf(statement.end); + for (let line = measure.lineOf(statement.getStart(sourceFile)); line <= lastLine; line += 1) importLines.add(line + 1); + } + return { + imports, + codeLines: measure.codeLines, + codeLineTexts: measure.codeLineTexts, + importCodeLines, + firstCodeLine: measure.firstCodeLine, + // A list of names is no squeezed code, and an import cannot be broken up by responsibility. + longLines: measure.longLines.filter(({ line }) => !importLines.has(line)), + functions, + regions, + counters, + allows, + isDataFile: isDataFile({ sourceFile, measure, functions, limits: config.limits }), + parseError: parseError + ? { line: measure.lineOf(parseError.start) + 1, message: ts.flattenDiagnosticMessageText(parseError.messageText, ' ') } + : null, + definesComponent: [...functions.values()].some((fact) => fact.isComponent && !fact.isNested), + }; +}; diff --git a/tools/quality/changes.mjs b/tools/quality/changes.mjs new file mode 100644 index 00000000..a68fccc8 --- /dev/null +++ b/tools/quality/changes.mjs @@ -0,0 +1,144 @@ +// What git knows about a change. One process per question, never one per file: a big PR stays fast. +import { execFileSync } from 'node:child_process'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; + +const git = ({ root, args, input, env }) => + execFileSync('git', args, { + cwd: root, + input, + env: env ? { ...process.env, ...env } : undefined, + maxBuffer: 2 ** 31 - 1, + stdio: ['pipe', 'pipe', 'pipe'], + }); +const gitText = (request) => git(request).toString('utf8').trim(); +const gitList = (request) => git(request).toString('utf8').split('\0').filter(Boolean); +const gitPath = ({ root, name }) => resolve(root, gitText({ root, args: ['rev-parse', '--git-path', name] })); + +export const repoRootOf = (directory) => { + try { + return gitText({ root: directory, args: ['rev-parse', '--show-toplevel'] }); + } catch { + return null; + } +}; + +export const isSameRepository = (a, b) => commonDirOf(a) === commonDirOf(b); + +export const commonDirOf = (root) => realpathSync(resolve(root, gitText({ root, args: ['rev-parse', '--git-common-dir'] }))); + +export const forkPointOf = ({ root, base, head }) => gitText({ root, args: ['merge-base', base, head ?? 'HEAD'] }); + +export const headOf = ({ root }) => gitText({ root, args: ['rev-parse', 'HEAD'] }); + +// origin/HEAD as the clone recorded it, else origin/main or origin/master, whichever exists. +const defaultBranchOf = ({ root, rows }) => { + try { + return gitText({ root, args: ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'] }); + } catch { + return ['origin/main', 'origin/master'].find((ref) => rows.some((row) => row.startsWith(`${ref} `))); + } +}; + +// The closest remote branch this one left. The default branch wins a tie, and a branch that holds this one plus more +// is its child, not its base. A ref at this very commit is this work pushed under another name, unless the commit is +// on the default branch anyway. Costs about 250 ms across 2000 refs, so the answer is kept per commit. +const findBase = ({ root, head }) => { + const branch = gitText({ root, args: ['branch', '--show-current'] }); + const skipped = new Set(['origin/HEAD', 'origin', `origin/${branch}`]); + const refs = gitText({ root, args: ['for-each-ref', '--format=%(refname:short) %(ahead-behind:HEAD)', 'refs/remotes/origin'] }); + const rows = refs.split('\n').filter(Boolean); + const defaultBase = defaultBranchOf({ root, rows }); + const defaultRow = rows.find((row) => row.startsWith(`${defaultBase} `)); + const isAheadOfDefault = !defaultRow || Number(defaultRow.split(' ')[2]) > 0; + let best = null; + for (const row of rows) { + const [ref, ahead, behind] = row.split(' '); + const isChild = Number(ahead) > 0 && Number(behind) === 0 && ref !== defaultBase; + const isThisCommit = Number(ahead) === 0 && Number(behind) === 0 && ref !== defaultBase; + if (skipped.has(ref) || isChild || (isThisCommit && isAheadOfDefault)) continue; + const isBetter = !best || Number(behind) < best.behind || (Number(behind) === best.behind && ref === defaultBase); + if (isBetter) best = { ref, behind: Number(behind) }; + } + if (!best) throw new Error(`no remote branch to compare ${head.slice(0, 10)} with`); + return best.ref; +}; + +export const resolveBase = ({ root }) => { + const head = headOf({ root }); + const cache = gitPath({ root, name: 'quality-base' }); + const [cachedHead, cachedBase] = existsSync(cache) ? readFileSync(cache, 'utf8').trim().split(' ') : []; + if (cachedHead === head && cachedBase) return cachedBase; + const base = findBase({ root, head }); + writeFileSync(cache, `${head} ${base}\n`); + return base; +}; + +const parseNameStatus = (tokens) => { + const changes = []; + for (let i = 0; i < tokens.length; i += 1) { + const status = tokens[i]; + const isTwoPaths = status.startsWith('R') || status.startsWith('C'); + const first = tokens[(i += 1)]; + const path = isTwoPaths ? tokens[(i += 1)] : first; + changes.push({ path, previousPath: status.startsWith('R') ? first : null, isDeleted: status === 'D' }); + } + return changes; +}; + +// The working tree as git would see it after `git add -A`, without touching the real index or object store. That +// makes a plain `mv` a rename and gives one hash for the whole tree. +export const workingTreeState = ({ root, fork }) => { + const scratch = mkdtempSync(join(tmpdir(), 'quality-tree-')); + try { + const index = gitPath({ root, name: 'index' }); + if (existsSync(index)) copyFileSync(index, join(scratch, 'index')); + mkdirSync(join(scratch, 'objects')); + const env = { + GIT_INDEX_FILE: join(scratch, 'index'), + GIT_OBJECT_DIRECTORY: join(scratch, 'objects'), + GIT_ALTERNATE_OBJECT_DIRECTORIES: gitPath({ root, name: 'objects' }), + }; + git({ root, args: ['add', '-A', '--', '.'], env }); + const tree = gitText({ root, args: ['write-tree'], env }); + const args = ['diff', '--cached', '--name-status', '-M', '--no-ext-diff', '-z', fork]; + return { tree, changes: parseNameStatus(gitList({ root, args, env })) }; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } +}; + +// Without a head this compares with the working tree, so it also sees what is not committed yet. +export const changedFiles = ({ root, fork, head }) => { + if (!head) return workingTreeState({ root, fork }).changes; + return parseNameStatus(gitList({ root, args: ['diff', '--name-status', '-M', '--no-ext-diff', '-z', fork, head] })); +}; + +export const readBlobs = ({ root, rev, paths }) => { + const blobs = new Map(); + if (!paths.length) return blobs; + const input = paths.map((path) => `${rev}:${path}\n`).join(''); + const output = git({ root, args: ['cat-file', '--batch'], input }); + let offset = 0; + for (const path of paths) { + const headerEnd = output.indexOf(10, offset); + const header = output.toString('utf8', offset, headerEnd); + offset = headerEnd + 1; + if (header.endsWith(' missing')) continue; + const size = Number(header.split(' ')[2]); + blobs.set(path, output.toString('utf8', offset, offset + size)); + offset += size + 1; + } + return blobs; +}; + +export const filesAt = ({ root, rev }) => new Set(gitList({ root, args: ['ls-tree', '-r', '--name-only', '-z', rev] })); + +export const foldersAt = ({ root, rev }) => new Set(gitList({ root, args: ['ls-tree', '-r', '-d', '--name-only', '-z', rev] })); + +export const newFoldersOf = ({ path, existing }) => { + const segments = path.split('/').slice(0, -1); + const folders = segments.map((_, index) => segments.slice(0, index + 1).join('/')); + return folders.filter((folder) => !existing.has(folder)); +}; diff --git a/tools/quality/check.mjs b/tools/quality/check.mjs new file mode 100644 index 00000000..26c14439 --- /dev/null +++ b/tools/quality/check.mjs @@ -0,0 +1,168 @@ +#!/usr/bin/env node +// Compares changed files with their state where the branch left its base. Old code may stay as it is, but must not +// get worse, and new code keeps the rules in .claude/rules/code-conventions.md. +// +// check.mjs --file one file, for the edit hook +// check.mjs [--base ] [--head ] every changed file, for CI and the stop hook. Without --base it finds +// the closest remote branch; without --head it reads the working tree +// +// Exit codes: 0 clean, 1 problems found, 3 the check itself could not run. +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseArgs } from 'node:util'; + +import { changedFiles, filesAt, foldersAt, forkPointOf, isSameRepository, newFoldersOf, readBlobs, repoRootOf, resolveBase } from './changes.mjs'; +import { config } from './config.mjs'; + +const TOOL_ROOT = repoRootOf(dirname(fileURLToPath(import.meta.url))); + +const ALLOW_HELP = 'Only if a split is really wrong here: `// quality-allow : ` on the line above. Reviewers see it.'; + +const escapeAnnotation = (text) => text.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A'); + +const WARNING_LABEL = 'Warning, not blocking:'; + +const annotate = ({ violations, notes, allows, formatViolation }) => { + if (!process.env.GITHUB_ACTIONS) return; + const annotation = ({ level, path, line, title, body }) => + console.log(`::${level} file=${path},line=${line},title=${title}::${escapeAnnotation(body)}`); + for (const item of violations) { + annotation({ level: 'error', path: item.path, line: item.line, title: `quality ${item.rule}`, body: formatViolation(item) }); + } + for (const item of notes) { + annotation({ level: 'warning', path: item.path, line: item.line, title: `quality ${item.rule}`, body: formatViolation(item) }); + } + for (const { path, line, rule, reason } of allows) { + annotation({ level: 'notice', path, line, title: `quality-allow ${rule}`, body: reason }); + } +}; + +const printReport = ({ violations, later = [], notes, allows, formatViolation }) => { + for (const violation of violations) console.log(`${formatViolation(violation)}\n`); + if (violations.length) console.log(`${ALLOW_HELP}\n`); + for (const item of later) console.log(`Not blocking yet, needed before you finish:\n${formatViolation(item)}\n`); + for (const note of notes) console.log(`${WARNING_LABEL}\n${formatViolation(note)}\n`); + for (const allow of allows) console.log(`quality-allow ${allow.rule}: ${allow.reason} (${allow.path}:${allow.line})`); + annotate({ violations, notes, allows, formatViolation }); +}; + +const changesAgainst = ({ root, fork, head }) => { + const inScope = changedFiles({ root, fork, head }).filter(({ path, previousPath }) => config.isInScope(path) || (previousPath && config.isInScope(previousPath))); + const beforeBlobs = readBlobs({ root, rev: fork, paths: inScope.map(({ path, previousPath }) => previousPath ?? path) }); + const present = inScope.filter(({ isDeleted }) => !isDeleted).map(({ path }) => path); + const afterBlobs = head ? readBlobs({ root, rev: head, paths: present }) : null; + const readAfter = (path) => (afterBlobs ? afterBlobs.get(path) : readFileSync(join(root, path), 'utf8')); + + let foldersAtFork; + const newFolders = (path) => { + foldersAtFork ??= foldersAt({ root, rev: fork }); + return newFoldersOf({ path, existing: foldersAtFork }); + }; + return inScope.map(({ path, previousPath, isDeleted }) => { + const isNewPath = !isDeleted && (previousPath !== null || !beforeBlobs.has(path)); + return { + path, + previousPath, + before: beforeBlobs.get(previousPath ?? path), + after: isDeleted ? null : readAfter(path), + isNewPath, + newFolders: isNewPath ? newFolders(path) : [], + }; + }); +}; + +const judgeInWholeChange = ({ change, root, fork, pathExists, rules }) => { + // This file goes first, so that what moved is credited to it and not to another file with the same line. + const others = changesAgainst({ root, fork }).filter(({ path }) => path !== change.path); + const { violations, notes, allows } = rules.checkChanges({ changes: [change, ...others], config, pathExists }); + const inThisFile = ({ path }) => path === change.path; + return { violations: violations.filter(inThisFile), notes: notes.filter(inThisFile), allows: allows.filter(inThisFile) }; +}; + +const runFile = async (file) => { + const absolute = resolve(file); + if (!existsSync(absolute)) return 0; + const realPath = realpathSync(absolute); + const root = repoRootOf(dirname(realPath)); + if (!root || !TOOL_ROOT || !isSameRepository(root, TOOL_ROOT)) return 0; + const path = relative(root, realPath); + if (!config.isInScope(path)) return 0; + + const rules = await import('./rules.mjs'); + const fork = forkPointOf({ root, base: resolveBase({ root }) }); + let before = readBlobs({ root, rev: fork, paths: [path] }).get(path); + const isNewPath = before === undefined; + let previousPath = null; + if (isNewPath) { + previousPath = changedFiles({ root, fork }).find((change) => change.path === path)?.previousPath ?? null; + if (previousPath) before = readBlobs({ root, rev: fork, paths: [previousPath] }).get(previousPath); + } + const change = { + path, + previousPath, + before, + after: readFileSync(realPath, 'utf8'), + isNewPath, + newFolders: isNewPath ? newFoldersOf({ path, existing: foldersAt({ root, rev: fork }) }) : [], + }; + const pathExists = (candidate) => existsSync(join(root, candidate)); + const firstLook = rules.checkChange({ change, config, pathExists }); + // Code may have moved in from another changed file. That takes every changed file, so only when there is something + // to report: most edits stay fast. + const { violations, notes, allows } = firstLook.violations.length ? judgeInWholeChange({ change, root, fork, pathExists, rules }) : firstLook; + // A new file may be the first half of a split whose source is not trimmed yet, so only the whole change can judge it. + const isNewFile = before === undefined; + printReport({ + violations: isNewFile ? [] : violations, + later: isNewFile ? violations : [], + notes, + allows, + formatViolation: rules.formatViolation, + }); + return !isNewFile && violations.length ? 1 : 0; +}; + +const runBase = async ({ base: givenBase, head }) => { + const root = repoRootOf(process.cwd()); + if (!root) throw new Error('not inside a git repository'); + const base = givenBase ?? resolveBase({ root }); + const fork = forkPointOf({ root, base, head }); + const changes = changesAgainst({ root, fork, head }); + const present = changes.filter(({ after }) => after != null); + let filesAtHead; + const pathExists = (candidate) => { + if (!head) return existsSync(join(root, candidate)); + filesAtHead ??= filesAt({ root, rev: head }); + return filesAtHead.has(candidate); + }; + + const rules = await import('./rules.mjs'); + const { violations, notes, allows } = rules.checkChanges({ changes, config, pathExists }); + printReport({ violations, notes, allows, formatViolation: rules.formatViolation }); + console.log( + `quality check: ${violations.length} problem(s), ${notes.length} warning(s) in ${present.length} changed source file(s), compared with ${fork.slice(0, 10)} (where this branch left ${base}).` + ); + return violations.length ? 1 : 0; +}; + +const main = async () => { + const { values } = parseArgs({ + options: { file: { type: 'string' }, base: { type: 'string' }, head: { type: 'string' } }, + }); + if (!values.file) return runBase({ base: values.base, head: values.head }); + try { + return await runFile(values.file); + } catch (error) { + // An edit hook must not stop a session over a missing default branch or typescript. CI still runs it. + console.error(`quality check skipped for ${values.file}: ${error.message}`); + return 0; + } +}; + +try { + process.exitCode = await main(); +} catch (error) { + console.error(`quality check could not run: ${error.message}`); + process.exitCode = 3; +} diff --git a/tools/quality/check.test.mjs b/tools/quality/check.test.mjs new file mode 100644 index 00000000..dc136aac --- /dev/null +++ b/tools/quality/check.test.mjs @@ -0,0 +1,104 @@ +// The shared core's cases, then what only this repo's config decides. Runs with the unit tests (npm test). +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { afterAll, describe, expect, it, vi } from 'vitest'; + +import { config, LIMITS } from './config.mjs'; +import { defineCoreCases } from './core.cases.mjs'; +import { checkChange, checkChanges } from './rules.mjs'; + +// Many cases start git, node and npm in a temp repo, which takes seconds on a busy machine. +vi.setConfig({ testTimeout: 60_000 }); + +const TOOL_DIR = dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = resolve(TOOL_DIR, '../..'); + +defineCoreCases({ + describe, + it, + afterAll, + config, + LIMITS, + checkChange, + checkChanges, + toolDir: TOOL_DIR, + repoRoot: REPO_ROOT, + toolRelative: 'tools/quality', + // Modules here are PascalCase, like src/GleapTourSelector.js. + pathFor: (name) => `src/${name.replace(/[^/]+$/, (file) => file[0].toUpperCase() + file.slice(1))}.ts`, +}); + +// Detection is tested with every rule at full strength. The core cases pin which rules only warn. +const strict = { ...config, warningRules: new Set(), legacySizeGrowthWarns: false }; +const report = (change, pathExists = () => true) => + checkChange({ change: { isNewPath: change.before == null, newFolders: [], ...change }, config: strict, pathExists }); +const rulesOf = (change, pathExists) => report(change, pathExists).violations.map(({ rule }) => rule); + +const logic = 'export const run = (value) => value + 1;'; + +describe('scope', () => { + for (const path of ['src/Gleap.js', 'src/GleapTourSelector.js', 'src/index.js', 'src/UI.js']) { + it(`checks ${path}`, () => expect(config.isInScope(path)).toBe(true)); + } + for (const path of [ + 'src/GleapTours.test.js', + 'src/unique-selector/src/getID.js', + 'smoke/sdkBundle.spec.mjs', + 'index.d.ts', + 'webpack.config.js', + 'build/browser/index.js', + 'published/latest/index.js', + 'demo/main.js', + 'tools/quality/rules.mjs', + ]) { + it(`leaves out ${path}`, () => expect(config.isInScope(path)).toBe(false)); + } +}); + +describe('file names', () => { + it('accepts a PascalCase module and the package entry', () => { + expect(rulesOf({ path: 'src/GleapTourSelector.js', after: logic })).toEqual([]); + const entry = "import Gleap from './Gleap';\nexport default Gleap;"; + expect(rulesOf({ path: 'src/index.js', before: entry, after: `${entry}\n` })).toEqual([]); + }); + for (const path of ['src/tourSelector.js', 'src/gleap-tour-selector.js', 'src/Gleap_Tours.js']) { + it(`wants ${path} in PascalCase`, () => expect(rulesOf({ path, after: logic })).toContain('file-name')); + } +}); + +describe('default exports', () => { + it('a new module takes named exports', () => { + expect(rulesOf({ path: 'src/GleapThing.js', after: 'const thing = 1;\nexport default thing;' })).toContain('default-export'); + }); + it('an existing default export stays', () => { + const before = 'class GleapThing {}\nexport default GleapThing;'; + expect(rulesOf({ path: 'src/GleapThing.js', before, after: `${before}\nexport const extra = 1;` })).toEqual([]); + }); +}); + +describe('plain JavaScript', () => { + const classWith = (body) => `export class GleapThing {\n${body}\n}`; + it('measures a static method of a class', () => { + const method = (lines) => ` static run() {\n${Array.from({ length: lines - 2 }, (_, i) => ` step${i}();`).join('\n')}\n }`; + expect(rulesOf({ path: 'src/GleapThing.js', before: classWith(method(90)), after: classWith(method(101)) })).toEqual(['function-lines']); + }); + it('wants an options object from the third parameter on', () => { + expect(rulesOf({ path: 'src/GleapThing.js', after: classWith(' static open(a, b, c) {}') })).toContain('params'); + }); + it('compares a message name with a constant', () => { + const after = "export const isOpen = (data) => data.name === 'open';"; + expect(rulesOf({ path: 'src/GleapThing.js', after })).toContain('string-compare'); + }); + it('leaves DOM values alone', () => { + const after = "export const isEnter = (event) => event.key === 'Enter' || event.target.tagName === 'INPUT';"; + expect(rulesOf({ path: 'src/GleapThing.js', after })).toEqual([]); + }); +}); + +describe('needs-test', () => { + it('wants .test.js next to new logic', () => { + expect(rulesOf({ path: 'src/GleapThing.js', after: logic }, () => false)).toEqual(['needs-test']); + expect(rulesOf({ path: 'src/GleapThing.js', after: logic }, (path) => path === 'src/GleapThing.test.js')).toEqual([]); + }); +}); diff --git a/tools/quality/config.mjs b/tools/quality/config.mjs new file mode 100644 index 00000000..9ede9340 --- /dev/null +++ b/tools/quality/config.mjs @@ -0,0 +1,106 @@ +// The JavaScript SDK half of the quality check: limits, scope and names from .claude/rules/code-conventions.md. +import { basename, dirname } from 'node:path'; + +export const LIMITS = { + // A new file over fileLines is a warning, over newFileLines an error. An existing file over fileLines may not grow. + fileLines: 400, + newFileLines: 700, + functionLines: 80, + componentLines: 150, + jsxReturnLines: 60, + positionalParams: 2, + // Growth up to this in a file or function already over its limit is a note, not a failure. + smallGrowthLines: 10, + lineChars: 160, + // This share of a new file found in what the change removed elsewhere makes it moved code. + movedShare: 0.9, + // This share of a file in literal tables makes it data, with no line limit. + dataShare: 0.9, + dataMinLines: 50, +}; + +const SOURCE_EXTENSION = /\.[cm]?[jt]sx?$/; +// src/unique-selector is a vendored copy of a library: it keeps upstream's shape. +const OUT_OF_SCOPE = [/\.(test|spec)\.[cm]?[jt]sx?$/, /\.d\.[cm]?ts$/, /\.generated\.[cm]?[jt]sx?$/, /^src\/unique-selector\//]; +const FIXTURE = [/(^|\/)(__fixtures__|fixtures)\//, /\.fixtures?\.[cm]?[jt]sx?$/]; + +const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/; +const CAMEL_CASE = /^[a-z][A-Za-z0-9]*$/; + +// Modules are PascalCase like the rest of src (GleapTourSelector.js). src/index.js is the package entry. +const fileNameProblem = ({ path }) => { + const name = basename(path).replace(SOURCE_EXTENSION, ''); + if (PASCAL_CASE.test(name) || path === 'src/index.js') return null; + return 'a module file is PascalCase and names what it holds, like GleapTourSelector.js'; +}; + +const folderNameProblem = (folder) => + CAMEL_CASE.test(basename(folder)) || PASCAL_CASE.test(basename(folder)) ? null : 'a new folder is camelCase or PascalCase'; + +const testCandidates = ({ path, facts }) => { + if (!facts.functions.size) return null; + return [`${path.replace(SOURCE_EXTENSION, '')}.test.js`]; +}; + +const EVENT = /(^|\.)(e|ev|evt|event|\w*Event)$/; +const URL_LIKE = /(^|\.)(location|url|uri|base|parsed|link|\w*(Url|URL|Uri|Location))$|^new URL\(/; +const ELEMENT = /(^|\.)(target|currentTarget|relatedTarget|activeElement|current|el|element|node|\w*(Element|Node|Target|Ref))$/; +const KEY_PROPERTIES = new Set(['key', 'code']); +const KEY_VALUES = new Set( + 'Enter Escape Esc Tab Space Backspace Delete ArrowUp ArrowDown ArrowLeft ArrowRight Home End PageUp PageDown Shift Control Alt Meta'.split(' ').concat(' ') +); +const DOM_PROPERTIES = new Map([ + ['key', EVENT], + ['code', EVENT], + ['inputType', EVENT], + ['pointerType', EVENT], + ['tagName', ELEMENT], + ['nodeName', ELEMENT], + ['localName', ELEMENT], + ['type', EVENT], + ['visibilityState', /(^|\.)document$/], + ['readyState', /(^|\.)(document|ws|socket|xhr|\w*(Socket|Source|Xhr|XHR|Request))$/], + ['origin', new RegExp(`${EVENT.source}|${URL_LIKE.source}`)], + ['protocol', URL_LIKE], + ['hostname', URL_LIKE], + ['host', URL_LIKE], + ['pathname', URL_LIKE], +]); + +export const config = { + limits: LIMITS, + isInScope: (path) => /^src\/.*\.[cm]?[jt]sx?$/.test(path) && !OUT_OF_SCOPE.some((pattern) => pattern.test(path)), + // Fixtures have no line limit and no name or test rule. Every other rule still applies to them. + isFixture: (path) => FIXTURE.some((pattern) => pattern.test(path)), + registryFiles: new Set(), + isModelFile: () => false, + isParamsExemptFile: () => false, + genericFileNames: new Set(['index', 'types', 'utils', 'helpers', 'controller', 'model']), + // No second system to ban yet. A new runtime package fails smoke/bundleCost.spec.mjs instead. + extraCounters: [], + bannedImports: [], + // Message names and server values are compared as strings all over the SDK: string-compare warns until that changes. + // long-line and needs-test warn only until the check is required. Comment stamps only warn while old comments still + // carry them for new ones to copy. + warningRules: new Set(['string-compare', 'type-assertion', 'long-line', 'needs-test', 'comment-attribution', 'comment-date']), + // Until the check is required, growth of old code warns too. A new file over newFileLines still fails. + legacySizeGrowthWarns: true, + stringExemptions: { + // `typeof` and the empty string are exempt in the core. Everything here needs a DOM or URL receiver. + isExempt: ({ name, receiver, value }) => (KEY_PROPERTIES.has(name) && KEY_VALUES.has(value)) || Boolean(receiver && DOM_PROPERTIES.get(name)?.test(receiver)), + }, + // The package entry exports Gleap as its default: `import Gleap from 'gleap'` and the CDN's window.Gleap need it. + // Existing default exports stay until their codemod, so only a rising count fails. + defaultExports: { isExemptFile: (path) => path === 'src/index.js' || /\.config\.[cm]?[jt]sx?$/.test(path) }, + fixes: { + 'default-export': 'Use a named export: a default export has no canonical name, so agents cannot find or rename it reliably.', + 'string-compare': + 'Compare with a named constant: one frozen object per set of values (Object.freeze({ OPEN: \'open\' })), next to the code that owns them. Search for an existing one first.', + }, + // No components and no domains: the SDK is one flat src/. + isNewComponentBlock: () => false, + isDomainImport: () => false, + fileNameProblem, + folderNameProblem, + testCandidates, +}; diff --git a/tools/quality/core.cases.mjs b/tools/quality/core.cases.mjs new file mode 100644 index 00000000..57cac109 --- /dev/null +++ b/tools/quality/core.cases.mjs @@ -0,0 +1,1161 @@ +// Test cases of the shared core, byte-identical in Frontend and Server. Each repo runs them through its own test +// runner and config: nothing here knows about Vitest or node:test. +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + renameSync, + rmSync, + symlinkSync, + unlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; + +const CORE_FILES = ['analyze.mjs', 'changes.mjs', 'check.mjs', 'core.cases.mjs', 'hooks.mjs', 'measure.mjs', 'moves.mjs', 'rules.mjs']; + +const statements = (count, name = 'step') => Array.from({ length: count }, (_, i) => ` ${name}${i}();`).join('\n'); +const moduleOf = (count) => Array.from({ length: count }, (_, i) => `export const v${i} = ${i};`).join('\n'); +const plainFunction = (name, lines, bodyName = name) => `export const ${name} = () => {\n${statements(lines - 2, bodyName)}\n};`; +const dataTable = (count) => + `export const table = {\n${Array.from({ length: count }, (_, i) => ` key${i}: 'value ${i}',`).join('\n')}\n};`; +// Still fails with the levels for the start: a size overrun only warns there. +const broken = (lines) => `${plainFunction('run', lines)}\nconsole.log('x');`; +const rulesIn = (items) => items.map((item) => item.rule).sort(); +const STUB = '#!/bin/sh\necho "$(basename "$0") $*" >> "$PWD/.stub-log"\n[ -f "$PWD/.stub-fail-$(basename "$0")" ] && { echo "$(basename "$0") is red"; exit 1; }\nexit 0\n'; +const RUNNER_STUB = + "const fs=require('node:fs');fs.appendFileSync('.stub-log','runner '+process.argv.slice(2).join(' ')+'\\n');process.exit(fs.existsSync('.stub-fail-runner')?1:0);\n"; + +export const defineCoreCases = ({ describe, it, afterAll, config, LIMITS, checkChange, checkChanges, toolDir, repoRoot, toolRelative, pathFor }) => { + const LOGIC = pathFor('thing'); + // Detection is tested with every rule at full strength. Which rules only warn is pinned once, below. + const strict = { ...config, warningRules: new Set(), legacySizeGrowthWarns: false }; + const report = (change, pathExists = () => true) => + checkChange({ change: { isNewPath: change.before == null, newFolders: [], ...change }, config: strict, pathExists }); + const rulesOf = (change, pathExists) => rulesIn(report(change, pathExists).violations); + const reportAll = (changes, pathExists = () => true) => + checkChanges({ + changes: changes.map((change) => ({ isNewPath: change.before == null, newFolders: [], ...change })), + config: strict, + pathExists, + }); + + describe('the shared core', () => { + it('is pinned, so the two copies cannot drift apart unnoticed', () => { + const hash = createHash('sha256'); + for (const file of CORE_FILES) hash.update(readFileSync(join(toolDir, file))); + const actual = hash.digest('hex'); + const pinned = readFileSync(join(toolDir, 'core.sha256'), 'utf8').trim(); + assert.equal(actual, pinned, `Core changed. Make the same change in the other repo, then put ${actual} in core.sha256 in both.`); + }); + }); + + describe('a ban that only the config knows', () => { + const banned = { + ...strict, + extraCounters: [...strict.extraCounters, 'test-import'], + bannedImports: [...strict.bannedImports, { rule: 'test-import', module: /^banned-package$/ }], + fixes: { ...strict.fixes, 'test-import': 'Use the other package.' }, + }; + const before = 'export const v = 1;'; + const line = "import thing from 'banned-package';"; + const check = (change) => checkChange({ change: { isNewPath: false, newFolders: [], ...change }, config: banned, pathExists: () => true }); + it('names the fix from the config and reads like the others', () => { + const [problem] = check({ path: LOGIC, before, after: `${line}\n${before}` }).violations; + assert.equal(problem.rule, 'test-import'); + assert.equal(problem.fix, 'Use the other package.'); + assert.match(problem.subject, /^banned imports in this file, new at line 1$/); + }); + it('leaves an import that was already there', () => { + const old = `${line}\n${before}`; + assert.deepEqual(check({ path: LOGIC, before: old, after: `${old}\nexport const w = 2;` }).violations, []); + }); + for (const other of [ + "export { thing } from 'banned-package';", + "export * from 'banned-package';", + "const thing = require('banned-package');", + "export const load = () => import('banned-package');", + ]) { + it(`counts ${other}`, () => { + assert.equal(rulesIn(check({ path: LOGIC, before, after: `${other}\n${before}` }).violations).includes('test-import'), true); + }); + } + for (const typeOnly of [ + "import type { Thing } from 'banned-package';", + "import { type Thing } from 'banned-package';", + "export type { Thing } from 'banned-package';", + ]) { + it(`leaves ${typeOnly}: a type brings no second system`, () => { + assert.deepEqual(check({ path: LOGIC, before, after: `${typeOnly}\n${before}` }).violations, []); + }); + } + }); + + describe('a moved lazy require', () => { + // Counted with the rule on, whether or not this repo's config counts lazy requires. + const lazy = { ...strict, extraCounters: [...new Set([...strict.extraCounters, 'local-require'])] }; + const reportMoves = (changes) => + checkChanges({ changes: changes.map((change) => ({ isNewPath: change.before == null, newFolders: [], ...change })), config: lazy, pathExists: () => true }); + // Only this rule: a repo may also ban the `../` paths these use (the Frontend does). + const lazyRules = (result) => rulesIn(result.violations).filter((rule) => rule === 'local-require'); + const lazyLoad = (specifier) => `export const moved = async () => {\n const { thing } = require('${specifier}');\n return thing();\n};`; + const source = pathFor('source'); + // One folder further down: the same module is one more `../` away. + const deeper = pathFor('deeper/target'); + + it('stays old when it moves with its code to another folder and still loads the same module', () => { + const result = reportMoves([ + { path: source, before: `${lazyLoad('./lib/thing')}\n${moduleOf(1)}`, after: moduleOf(1) }, + { path: deeper, after: lazyLoad('../lib/thing') }, + ]); + assert.deepEqual(lazyRules(result), []); + }); + it('is new when the moved code loads another module', () => { + const result = reportMoves([ + { path: source, before: `${lazyLoad('./lib/thing')}\n${moduleOf(1)}`, after: moduleOf(1) }, + { path: deeper, after: lazyLoad('../lib/other') }, + ]); + assert.deepEqual(lazyRules(result), ['local-require']); + }); + it('is new when nothing that loads it moved', () => { + const result = reportMoves([{ path: deeper, after: lazyLoad('../lib/thing') }]); + assert.deepEqual(lazyRules(result), ['local-require']); + }); + }); + + describe('moved code', () => { + const big = plainFunction('moved', 90); + const dirty = (extra = '') => + `export const moved = (a: any, b: string, c: string) => {\n console.log(a);\n if (b === 'OPEN') c.trim();\n${statements(90, 'moved')}\n${extra}};`; + + it('is old when a function moves to a new file', () => { + const result = reportAll([ + { path: pathFor('source'), before: `${dirty()}\n${moduleOf(3)}`, after: moduleOf(3) }, + { path: pathFor('target'), after: dirty() }, + ]); + assert.deepEqual(rulesIn(result.violations), []); + }); + it('is old when a deleted file moves into two new files', () => { + const one = plainFunction('one', 90); + const two = plainFunction('two', 90); + const result = reportAll([ + { path: pathFor('source'), before: `${one}\n${two}`, after: null }, + { path: pathFor('first'), after: one }, + { path: pathFor('second'), after: two }, + ]); + assert.deepEqual(rulesIn(result.violations), []); + }); + it('stays old when the move adds export', () => { + const line = 'const moved = (x: any) => x;'; + const result = reportAll([ + { path: pathFor('source'), before: `${line}\nexport const kept = moved;`, after: 'export const kept = 1;' }, + { path: pathFor('target'), after: `export ${line}` }, + ]); + assert.deepEqual(rulesIn(result.violations), []); + }); + it('is new again when the moved function grew', () => { + const result = reportAll([ + { path: pathFor('source'), before: big, after: moduleOf(1) }, + { path: pathFor('target'), after: plainFunction('moved', 120) }, + ]); + assert.deepEqual(rulesIn(result.violations), ['function-lines']); + assert.equal(result.violations[0].before, 90); + }); + it('does not hide new problems in the new file', () => { + const result = reportAll([ + { path: pathFor('source'), before: big, after: moduleOf(1) }, + { path: pathFor('target'), after: `${big}\nexport const fresh = (x: any, y: any, z: any) => [x, y, z];` }, + ]); + assert.deepEqual(rulesIn(result.violations), ['any', 'params']); + }); + it('renames in a file by the hash of the body', () => { + const before = 'export const oldName = (a, b, c) => a + b + c;'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: 'export const newName = (a, b, c) => a + b + c;' }), []); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: 'export const newName = (a, b, c) => a - b - c;' }), ['params']); + }); + it('does not count moved lines against a new file over the limit', () => { + const body = moduleOf(450); + assert.deepEqual( + rulesIn(reportAll([{ path: pathFor('source'), before: body, after: null }, { path: pathFor('target'), after: body }]).violations), + [] + ); + const fresh = (count) => Array.from({ length: count }, (_, i) => `export const fresh${i} = ${i};`).join('\n'); + const withFresh = (count) => + reportAll([{ path: pathFor('source'), before: body, after: null }, { path: pathFor('target'), after: `${body}\n${fresh(count)}` }]); + assert.deepEqual(rulesIn(withFresh(450).violations), []); + assert.deepEqual(rulesIn(withFresh(450).notes), ['file-lines']); + assert.deepEqual(rulesIn(withFresh(750).violations), ['file-lines']); + }); + it('still fails an existing file that takes in moved code over its limit', () => { + const moved = Array.from({ length: 30 }, (_, i) => `export const moved${i} = ${i};`).join('\n'); + const result = reportAll([ + { path: pathFor('source'), before: moved, after: moduleOf(1) }, + { path: pathFor('target'), before: moduleOf(500), after: `${moduleOf(500)}\n${moved}` }, + ]); + assert.deepEqual(rulesIn(result.violations), ['file-lines']); + }); + it('drops needs-test only when nearly all of a new file is moved code', () => { + const logic = 'logic'; + const stem = pathFor(logic); + const source = plainFunction('moved', 50); + const noTest = (candidate) => !candidate.startsWith(stem.replace(/\.tsx?$/, '')); + const movedOnly = reportAll( + [{ path: pathFor('source'), before: source, after: moduleOf(1) }, { path: stem, after: source }], + noTest + ); + assert.ok(!rulesIn(movedOnly.violations).includes('needs-test')); + if (!config.testCandidates({ path: stem, facts: { functions: new Map([['x', {}]]), definesComponent: false } })) return; + const mostlyNew = reportAll( + [{ path: pathFor('source'), before: source, after: moduleOf(1) }, { path: stem, after: `${source}\n${plainFunction('fresh', 30)}` }], + noTest + ); + assert.ok(rulesIn(mostlyNew.violations).includes('needs-test')); + }); + it('does not count the imports of a new file against the moved share', () => { + const stem = pathFor('logic'); + const source = plainFunction('moved', 20); + const imports = Array.from({ length: 5 }, (_, i) => `import { a${i} } from './a${i}';`).join('\n'); + const noTest = (candidate) => !candidate.startsWith(stem.replace(/\.tsx?$/, '')); + const result = reportAll( + [{ path: pathFor('source'), before: source, after: moduleOf(1) }, { path: stem, after: `${imports}\n${source}` }], + noTest + ); + assert.ok(!rulesIn(result.violations).includes('needs-test')); + }); + it('keeps honest name problems on moved code', () => { + const result = reportAll([ + { path: pathFor('source'), before: moduleOf(5), after: null }, + { path: 'src/helper/bad_name.ts', after: moduleOf(5) }, + ]); + assert.deepEqual(rulesIn(result.violations), ['file-name']); + }); + }); + + describe('small growth', () => { + it('has one number, in the config', () => assert.equal(LIMITS.smallGrowthLines, 10)); + it('of a file already over its limit is a note up to the number, then a failure', () => { + const at = (growth) => report({ path: LOGIC, before: moduleOf(410), after: moduleOf(410 + growth) }); + assert.deepEqual(rulesIn(at(10).violations), []); + assert.deepEqual(rulesIn(at(10).notes), ['file-lines']); + assert.deepEqual(rulesIn(at(11).violations), ['file-lines']); + assert.deepEqual(rulesIn(at(11).notes), []); + }); + it('of a function already over its limit is a note up to the number, then a failure', () => { + const at = (growth) => report({ path: LOGIC, before: plainFunction('run', 90), after: plainFunction('run', 90 + growth) }); + assert.deepEqual(rulesIn(at(10).violations), []); + assert.deepEqual(rulesIn(at(10).notes), ['function-lines']); + assert.deepEqual(rulesIn(at(11).violations), ['function-lines']); + }); + it('crossing a limit is a warning, because nothing was too big before', () => { + const file = report({ path: LOGIC, before: moduleOf(399), after: moduleOf(401) }); + assert.deepEqual(rulesIn(file.violations), []); + assert.deepEqual(rulesIn(file.notes), ['file-lines']); + const fn = report({ path: LOGIC, before: plainFunction('run', 79), after: plainFunction('run', 81) }); + assert.deepEqual(rulesIn(fn.violations), []); + assert.deepEqual(rulesIn(fn.notes), ['function-lines']); + }); + it('crossing the maximum for a new file is an error', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: moduleOf(399), after: moduleOf(701) }), ['file-lines']); + }); + }); + + describe('quality-allow over time', () => { + const fn = (lines, comment = '') => `${comment}${plainFunction('run', lines)}`; + const old = '// quality-allow function-lines: one state machine\n'; + it('an old size allow does not cover further growth', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: fn(90, old), after: fn(120, old) }), ['function-lines']); + }); + it('an old size allow still stands while nothing grows', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: fn(90, old), after: fn(90, old) }), []); + }); + it('a new reason covers the growth and is reported', () => { + const result = report({ path: LOGIC, before: fn(90, old), after: fn(120, '// quality-allow function-lines: a new reason\n') }); + assert.deepEqual(rulesIn(result.violations), []); + assert.deepEqual(result.allows.map((allow) => allow.reason), ['a new reason']); + }); + it('reports every new allow per line, also with a repeated reason', () => { + const allow = '// quality-allow any: untyped library\n'; + const line = (name) => `export const ${name} = (x) => x as any;\n`; + const before = `${allow}${line('a')}`; + const result = report({ path: LOGIC, before, after: `${before}${allow}${line('b')}${allow}${line('c')}` }); + assert.deepEqual(rulesIn(result.violations), []); + assert.deepEqual(result.allows.map((item) => item.line), [3, 5]); + }); + }); + + describe('parameter growth', () => { + it('fails when an existing function over the limit gains parameters', () => { + const result = report({ path: LOGIC, before: 'export const f = (a, b, c) => a;', after: 'export const f = (a, b, c, d) => a;' }); + assert.deepEqual(rulesIn(result.violations), ['params']); + assert.deepEqual([result.violations[0].before, result.violations[0].after], [3, 4]); + }); + it('fails when an existing function crosses the limit', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: 'export const f = (a, b) => a;', after: 'export const f = (a, b, c) => a;' }), ['params']); + }); + it('passes when the count stays or falls', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: 'export const f = (a, b, c, d) => a;', after: 'export const f = (a, b, c) => a;' }), []); + }); + }); + + describe('string comparisons that hide', () => { + const body = (line) => `export const run = (x) => {\n ${line}\n};`; + const before = body('x();'); + for (const line of [ + "if (x.status === ('OPEN')) x();", + "if (x.status === 'OPEN' as Status) x();", + "if (x.status === ('OPEN' satisfies Status)) x();", + "if ((x.status as string) === 'OPEN') x();", + "switch (x.status) {\n case ('OPEN'):\n x();\n }", + "if (task.origin === 'schedule') x();", + "if (task.host === 'kai') x();", + "if (x === 'Enter') x();", + ]) { + it(`red: ${line.split('\n')[0]}`, () => assert.ok(rulesOf({ path: LOGIC, before, after: body(line) }).includes('string-compare'))); + } + for (const line of ["if (url.origin === 'https://a.b') x();", "if (window.location.pathname === '/x') x();", "if (new URL(x).hostname === 'a.b') x();"]) { + it(`green: ${line}`, () => assert.deepEqual(rulesOf({ path: LOGIC, before, after: body(line) }), [])); + } + }); + + describe('scope', () => { + const bad = `// @ts-ignore\nexport const f = (a: any) => a;`; + it('takes in .mts, .cts, .js and .mjs under src', () => { + for (const extension of ['mts', 'cts', 'js', 'mjs', 'cjs', 'jsx']) { + const path = `src/helper/thing.${extension}`; + assert.ok(config.isInScope(path), path); + } + }); + it('takes in real code under a templates or test folder', () => { + assert.ok(rulesOf({ path: 'src/foo/templates/real.ts', after: bad }).includes('any')); + assert.ok(rulesOf({ path: 'src/foo/test/real.ts', after: bad }).includes('any')); + }); + it('a fixture name lifts the line limit, not the other rules', () => { + const big = `${moduleOf(500)}\n${plainFunction('factory', 120)}`; + assert.deepEqual(rulesOf({ path: 'src/foo/thing.fixtures.ts', after: big }), []); + assert.deepEqual(rulesOf({ path: 'src/foo/thing.fixtures.ts', after: bad }), ['any', 'ts-ignore']); + }); + it('leaves out generated files', () => assert.ok(!config.isInScope('src/services/gleapKnowledge/dashboardMap.generated.ts'))); + it('a file of plain data has no line limit, whatever its name', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: dataTable(500), after: dataTable(600) }), []); + assert.deepEqual(rulesOf({ path: pathFor('fresh'), after: dataTable(600) }), []); + }); + it('data does not hide logic', () => { + const withLogic = `${dataTable(300)}\n${Array.from({ length: 500 }, (_, i) => `export const f${i} = () => ${i};`).join('\n')}`; + assert.deepEqual(rulesOf({ path: pathFor('fresh'), after: withLogic }), ['file-lines']); + }); + }); + + describe('size levels', () => { + it('has the numbers in the config', () => { + assert.equal(LIMITS.fileLines, 400); + assert.equal(LIMITS.newFileLines, 700); + }); + it('a new file: warning over 400, error over 700', () => { + const at = (lines) => report({ path: LOGIC, after: moduleOf(lines) }); + assert.deepEqual([rulesIn(at(400).violations), rulesIn(at(400).notes)], [[], []]); + assert.deepEqual([rulesIn(at(401).violations), rulesIn(at(401).notes)], [[], ['file-lines']]); + assert.deepEqual([rulesIn(at(700).violations), rulesIn(at(700).notes)], [[], ['file-lines']]); + assert.deepEqual([rulesIn(at(701).violations), rulesIn(at(701).notes)], [['file-lines'], []]); + }); + it('a new function over its limit is a warning', () => { + const result = report({ path: LOGIC, after: plainFunction('fresh', 81) }); + assert.deepEqual([rulesIn(result.violations), rulesIn(result.notes)], [[], ['function-lines']]); + }); + it('the ratchet stays: an existing function or file over its limit may not grow', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: plainFunction('run', 90), after: plainFunction('run', 101) }), ['function-lines']); + assert.deepEqual(rulesOf({ path: LOGIC, before: moduleOf(450), after: moduleOf(461) }), ['file-lines']); + }); + }); + + describe('assertions', () => { + const before = 'export const v = 1;'; + const added = (line) => `${before}\n${line}`; + it('red: as', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('export const a = (x: unknown) => x as Thing;') }), ['type-assertion']); + }); + it('red: !', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('export const a = (x: Thing) => x.y!.z;') }), ['non-null-assertion']); + }); + it('green: as const, satisfies, renamed imports, !x and a declared field', () => { + for (const line of [ + "export const a = ['x'] as const;", + 'export const a = { x: 1 } satisfies Thing;', + "import { x as y } from './x';", + 'export const a = (x: boolean) => !x;', + 'export class A {\n x!: string;\n}', + ]) { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(line) }), [], line); + } + }); + it('as unknown as T counts as any, or agents move there', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('export const a = (x: Other) => x as unknown as Thing;') }), ['any']); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('export const a = (x: Other) => (x as unknown) as Thing;') }), ['any']); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('export const a = (x: Other) => x as unknown;') }), ['type-assertion']); + }); + it('as any counts once, as any', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('export const a = (x: unknown) => x as any;') }), ['any']); + }); + it('only on new lines: an old one stays', () => { + const old = added('export const a = (x: unknown) => x as Thing;'); + assert.deepEqual(rulesOf({ path: LOGIC, before: old, after: `${old}\nexport const z = 1;` }), []); + }); + it('red and green: const enum', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added("export const enum K {\n A = 'A',\n}") }), ['const-enum']); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added("export enum K {\n A = 'A',\n}") }), []); + }); + }); + + describe('ts-expect-error', () => { + const before = 'export const run = (x) => {\n x();\n};'; + const added = (comment) => `export const run = (x) => {\n ${comment}\n x();\n};`; + it('is fine with a reason', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('// @ts-expect-error the library has the wrong type') }), []); + }); + it('is not without one', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('// @ts-expect-error') }), ['ts-ignore']); + }); + it('@ts-ignore never is', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added('// @ts-ignore the library has the wrong type') }), ['ts-ignore']); + }); + }); + + describe('a rule that is too loud', () => { + it('as and string comparisons only warn: too many hits cannot be avoided', () => { + const before = 'export const v = 1;'; + const after = `${before}\nexport const a = (x: unknown) => x as Thing;\nexport const b = (x) => x === 'OPEN';`; + const change = { path: LOGIC, before, after, isNewPath: false, newFolders: [] }; + const result = checkChange({ change, config, pathExists: () => true }); + assert.deepEqual([rulesIn(result.violations), rulesIn(result.notes)], [[], ['string-compare', 'type-assertion']]); + }); + it('while the check is not required: long lines, missing tests and growth of old code only warn', () => { + const real = (change, pathExists = () => true) => + checkChange({ change: { isNewPath: change.before == null, newFolders: [], ...change }, config, pathExists }); + const width = `export const a${'b'.repeat(170)} = 1;`; + const levels = (result) => [rulesIn(result.violations), rulesIn(result.notes)]; + assert.deepEqual(levels(real({ path: LOGIC, before: moduleOf(1), after: `${moduleOf(1)}\n${width}` })), [[], ['long-line']]); + assert.deepEqual(levels(real({ path: LOGIC, before: moduleOf(500), after: moduleOf(600) })), [[], ['file-lines']]); + assert.deepEqual(levels(real({ path: LOGIC, before: moduleOf(399), after: moduleOf(800) })), [[], ['file-lines']]); + assert.deepEqual(levels(real({ path: LOGIC, before: plainFunction('run', 90), after: plainFunction('run', 150) })), [[], ['function-lines']]); + assert.equal(config.warningRules.has('needs-test'), true); + }); + it('a new file over the maximum still fails', () => { + const change = { path: LOGIC, after: moduleOf(701), isNewPath: true, newFolders: [] }; + assert.deepEqual(rulesIn(checkChange({ change, config, pathExists: () => true }).violations), ['file-lines']); + }); + it('can be a warning through the config, without touching the core', () => { + const before = 'export const v = 1;'; + const after = `${before}\nexport const a = (x: any) => x;`; + const quiet = { ...config, warningRules: new Set(['any']) }; + const change = { path: LOGIC, before, after, isNewPath: false, newFolders: [] }; + const result = checkChange({ change, config: quiet, pathExists: () => true }); + assert.deepEqual([rulesIn(result.violations), rulesIn(result.notes)], [[], ['any']]); + }); + }); + + describe('comment-reference', () => { + const before = 'export const v = 1;'; + const added = (comment) => `${before}\n${comment}\nexport const w = 2;`; + for (const comment of [ + '// see #12345', + '// fixed in PR 123', + '// PR #2752 moved this', + '// ticket 12345', + '// Ticket #148144 asked for this', + '// the view (Server#2271) needs it', + '// a customer hit this (Gleap #227529)', + '// the "Pass to Flow" step was skipped (#227518)', + '// tickets #129850 and #129851', + '/* comes from #2752 */', + '/**\n * A block comment.\n * It names #148144 on a later line.\n */', + ]) { + it(`red: ${comment.split('\n')[0]}`, () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), ['comment-reference']); + }); + } + for (const comment of [ + '// step #1 of the list', + '// #12 is not a ticket yet', + '// PR 12', + '// the #fff background', + '// #0000ff on white', + '// `#333` on white, and #000 for text', + '// #000000 is black', + '// color: #00000080 beats the utility', + '// https://github.com/acme/lib/issues/12345 explains the workaround', + '// see https://example.com/page#12345', + '// the number 12345 is the limit', + '// #121212 is the dark background', + '// #808080 grey', + '// #123 is short for a colour', + '// the entity é in a name', + '// tickets 100 per page', + '// a page holds 100 tickets 250 at most', + '// the footer reads "Server #2641 · started by Kai"', + '// the title says `Review PR #2387`', + ]) { + it(`green: ${comment}`, () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), []); + }); + } + it('green: a number in a string is no comment', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `${before}\nexport const s = 'see #12345';` }), []); + }); + it('green: an old comment stays while the file changes', () => { + const old = added('// see #12345'); + assert.deepEqual(rulesOf({ path: LOGIC, before: old, after: `${old}\nexport const z = 1;` }), []); + }); + it('green: a comment that only moved', () => { + const comment = '// see #12345'; + const result = reportAll([ + { path: pathFor('source'), before: added(comment), after: before }, + { path: pathFor('target'), after: `${comment}\nexport const w = 2;` }, + ]); + assert.ok(!rulesIn(result.violations).includes('comment-reference')); + }); + it('red: a new number is not paid for by removing an old one', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: added('// see #12345'), after: added('// see #54321') }), ['comment-reference']); + }); + it('a block comment is reported where it starts, and can be allowed above that', () => { + const block = '/**\n * A block comment.\n * It names #148144 on a later line.\n */'; + const [violation] = report({ path: LOGIC, before, after: added(block) }).violations; + assert.equal(violation.line, 2); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(`// quality-allow comment-reference: the name of a customer's incident\n${block}`) }), []); + }); + it('says where the number belongs', () => { + const [violation] = report({ path: LOGIC, before, after: added('// see #12345') }).violations; + assert.equal(violation.line, 2); + assert.match(violation.fix, /belongs in the PR/); + }); + }); + + describe('comment-attribution and comment-date', () => { + const before = 'export const v = 1;'; + const added = (comment) => `${before}\n${comment}\nexport const w = 2;`; + const levels = (result) => [rulesIn(result.violations), rulesIn(result.notes)]; + for (const comment of [ + '// 24px under the header (Lukas)', + '// the list fades out (Lukas 10-27)', + '// one row per agent (Luca, 2026-10-07)', + "// the rail's icons, picked by Florian", + '// per Tobias: no email for this', + '// Florian wanted the old order', + '// Lukas said the badge reads as noise', + '// Lukas: no Free plan without a card', + "// Lukas' restructure keeps the tabs", + '// Push and in-app only (10-27)', + '// the dialog frame (2026-10-21): an 18px title', + '// one card (review 10-31): no gap between them', + '// the setup card (Kai PM folded in, 10-27)', + '/**\n * One card for both.\n * (Lukas 10-25)\n */', + '/**\n * The order stays (decided in the\n * review 10-31) for every board.\n */', + '// The order stays (decided in the\n// review 10-31) for every board.', + '// one card (the list (left) and the pane, 10-31)', + ]) { + it(`red: ${comment.split('\n').join(' ')}`, () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), ['comment-attribution']); + }); + } + for (const comment of [ + '// Kai answers first, Kai Support drafts', + '// the thread in Claude Code style', + '// Simonyi notation for the handles', + '// Alias of the old name', + '// the line reads "Florian drives · Kai Support"', + '/**\n * The pane folds it: "Not sent: the reply to Sam, Florian\n * answered first".\n */', + '// a scrape takes 10-20 s', + '// waits (10-15 s) for the scrape', + '// keeps 2026-01-01 → 2026-12-31 as the year', + '// semver 1.10-12 is no date', + '// the key is report-2026-10-21-eu', + '// the fixture holds `2026-10-21`', + '// a share of (10-20%) of the rows', + '// (10-20 %) of the rows', + '// 10-12× faster than before', + '// a summary (10-12 words) per ticket', + '// a budget (10-30 tokens) per step', + '// the poll waits (10-15 sec)', + '// the label size (12-14 pt)', + '// the retention offer ends (2026-12-03 + 2 months)', + '// the window (2026-10-01..2026-10-31)', + '// the batch covers 2026-07-15…08-14', + '// the Twilio API (the 2010-04-01 paths)', + '// the header anthropic-version (2023-06-01)', + '// the expiry (an ISO date, e.g. 2026-10-27 at noon)', + "// @example formatDate('2026-10-21')", + '// the label reads “Florian drives”', + '// see https://example.com/2026-10-21/notes', + '// the job runs (10-20 seconds)', + '// a pause (10-15 minutes) between runs', + '// a drop (10-20 percent) in replies', + '// a page (10-12 rows) at a time', + '// a burst (10-12 requests) per user', + '// the budget (10-12 calls) per run', + '// gives up (01-05 retries) later', + '// the window (10-01 - 10-31) of the report', + ]) { + it(`green: ${comment.split('\n').join(' ')}`, () => { + assert.deepEqual(levels(report({ path: LOGIC, before, after: added(comment) })), [[], []]); + }); + } + for (const comment of [ + '// Removed with the 07-29 rebuild and restored 08-07', + '// the stall on 09-28 went unnoticed', + '// agents created before 2026-10-21 have no avatar', + '// a fallback (agents created before 2026-10-21 have no avatar)', + ]) { + it(`date only: ${comment}`, () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), ['comment-date']); + }); + } + it('green: a name in a string is no comment', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `${before}\nexport const s = '(Lukas 10-27)';` }), []); + }); + it('green: an old stamp stays while the file changes', () => { + const old = added('// the list fades out (Lukas 10-27)'); + assert.deepEqual(rulesOf({ path: LOGIC, before: old, after: `${old}\nexport const z = 1;` }), []); + }); + it('green: a stamped comment that only moved', () => { + const comment = '// the list fades out (Lukas 10-27)'; + const result = reportAll([ + { path: pathFor('source'), before: added(comment), after: before }, + { path: pathFor('target'), after: `${comment}\nexport const w = 2;` }, + ]); + assert.ok(!rulesIn(result.violations).includes('comment-attribution')); + }); + it('red: an edited comment that keeps its stamp', () => { + const after = added('// the whole list fades out (Lukas 10-27)'); + assert.deepEqual(rulesOf({ path: LOGIC, before: added('// the list fades out (Lukas 10-27)'), after }), ['comment-attribution']); + }); + it('a stamp can be allowed on the line above', () => { + const comment = '// quality-allow comment-attribution: names the customer the format comes from\n// the format of Florian Ltd (Florian)'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), []); + }); + it('a stamp inside a run of line comments is allowed on the line right above it', () => { + const comment = '// the format of\n// quality-allow comment-attribution: names the customer the format comes from\n// Florian Ltd (Florian)'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), []); + }); + it('an allow above a run of line comments covers the whole run', () => { + const comment = '// quality-allow comment-attribution: names the customer the format comes from\n// the format of\n// Florian Ltd (Florian)'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), []); + }); + it('an allow above a run covers only its own rule', () => { + const comment = '// quality-allow comment-date: the cutoff the import depends on\n// the format of\n// Florian Ltd (Florian)'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), ['comment-attribution']); + }); + it('red: an allow for another rule inside a block comment does not hide its stamp', () => { + const comment = '/**\n * quality-allow function-lines: one table of all the plans\n * fades out (Lukas 10-27)\n */'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(comment) }), ['comment-attribution']); + }); + it('an allow comment that names a teammate or a date is not a stamp itself', () => { + const name = "// quality-allow comment-attribution: Florian Ltd's export format\n// the format of Florian Ltd (Florian)"; + const date = '// quality-allow comment-date: the cutoff 2026-10-21 is when the field arrived\n// agents created before 2026-10-21 have no avatar'; + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(name) }), []); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: added(date) }), []); + }); + it('green: an old stamp stays old when the lines around it change', () => { + const run = (rest) => added(`// The list fades out (Lukas 10-27)\n${rest}`); + const block = (rest) => added(`/**\n * The list fades out.\n * (Lukas 10-25)\n * ${rest}\n */`); + const levelsOf = (beforeText, afterText) => levels(report({ path: LOGIC, before: beforeText, after: afterText })); + assert.deepEqual(levelsOf(run('// over 200 ms.'), run('// over 300 ms.')), [[], []]); + assert.deepEqual(levelsOf(run('// over 200 ms.'), run('// over 200 ms.\n// and then stops.')), [[], []]); + assert.deepEqual(levelsOf(block('Over 200 ms.'), block('Over 300 ms.')), [[], []]); + }); + it('green: an old stamp in a trailing comment stays old when the next line changes', () => { + const code = (gap) => `export const a = 1; // fades (Lukas 10-27)\nexport const c = 2; // ${gap}`; + assert.deepEqual(rulesOf({ path: LOGIC, before: code('the gap'), after: code('the wider gap') }), []); + }); + it('green: a stamped comment that moved under another comment', () => { + const comment = '// the list fades out (Lukas 10-27)'; + const result = reportAll([ + { path: pathFor('source'), before: added(comment), after: before }, + { path: pathFor('target'), after: `// ---- helpers\n${comment}\nexport const w = 2;` }, + ]); + assert.ok(!rulesIn([...result.violations, ...result.notes]).includes('comment-attribution')); + }); + it('reports the line of a stamp that wraps over line comments', () => { + const comment = '// The order stays (decided in the\n// review 10-31) for every board.'; + const [violation] = report({ path: LOGIC, before, after: added(comment) }).violations; + assert.equal(violation.line, 3); + }); + it('reads a comment full of dates in linear time', () => { + const dates = Array.from({ length: 20000 }, () => '10-27').join(' and '); + const started = performance.now(); + report({ path: LOGIC, before, after: added(`/* ${dates} */`) }); + assert.ok(performance.now() - started < 2000); + }); + it('says to keep the reason and move the rest to the PR', () => { + const [violation] = report({ path: LOGIC, before, after: added('// fades out (Lukas 10-27)') }).violations; + assert.equal(violation.line, 2); + assert.match(violation.fix, /Remove the name or date and keep the reason/); + assert.match(violation.fix, /PR/); + const [note] = report({ path: LOGIC, before, after: added('// the stall on 09-28 went unnoticed') }).violations; + assert.match(note.fix, /PR/); + }); + it('only warn, a name and a date in parentheses too', () => { + const real = (comment) => checkChange({ change: { path: LOGIC, before, after: added(comment), isNewPath: false, newFolders: [] }, config, pathExists: () => true }); + assert.deepEqual(levels(real('// fades out (Lukas 10-27)')), [[], ['comment-attribution']]); + assert.deepEqual(levels(real('// the stall on 09-28 went unnoticed')), [[], ['comment-date']]); + }); + }); + + describe('@Request() request: any', () => { + const method = (signature) => `export class ThingController {\n public run(${signature}) {\n return 1;\n }\n}`; + const before = 'export class ThingController {}'; + it('is exempt, exactly this decorated parameter', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: method('@Request() request: any') }), []); + }); + it('does not cover another parameter or decorator', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: method('@Body() body: any') }), ['any']); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: method('@Request() request: any, other: any') }), ['any']); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: method('request: any') }), ['any']); + }); + }); + + describe('long lines', () => { + const before = 'export const v = 1;'; + const code = (width) => `export const a${'b'.repeat(width - 'export const a = 1;'.length)} = 1;`; + it('has its limit in the config', () => assert.equal(LIMITS.lineChars, 160)); + it('red and green at the limit', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `${before}\n${code(161)}` }), ['long-line']); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `${before}\n${code(160)}` }), []); + }); + it('red: many statements squeezed onto one line', () => { + const squeezed = Array.from({ length: 200 }, (_, i) => `step${i}();`).join(' '); + assert.deepEqual(rulesOf({ path: LOGIC, before: 'export const v = () => {};', after: `export const v = () => { ${squeezed} };` }), ['long-line']); + }); + it('strings, templates and comments do not count', () => { + const text = 'x'.repeat(300); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `export const s = '${text}';` }), []); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `export const s = \`${text}\`;` }), []); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `export const s = 1; // ${text}` }), []); + }); + it('a regular expression cannot be broken up', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `export const r = /${'a|'.repeat(150)}b/;` }), []); + }); + it('import and re-export lists are no squeezed code', () => { + const names = Array.from({ length: 40 }, (_, i) => `name${i}`).join(', '); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `import { ${names} } from './other';\n${before}` }), []); + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `export { ${names} } from './other';\n${before}` }), []); + }); + it('green: a long line that got shorter, red: one that grew', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: code(216), after: code(201) }), []); + assert.deepEqual(rulesOf({ path: LOGIC, before: code(216), after: code(230) }), ['long-line']); + }); + it('red: a shortened line does not pay for a second new one', () => { + const other = code(180).replace('export const a', 'export const c'); + assert.deepEqual(rulesOf({ path: LOGIC, before: code(216), after: `${code(201)}\n${other}` }), ['long-line']); + }); + it('an old long line that did not change passes', () => { + const old = code(200); + assert.deepEqual(rulesOf({ path: LOGIC, before: old, after: `${old}\nexport const z = 1;` }), []); + }); + it('a moved long line is old', () => { + const old = code(200); + const result = reportAll([ + { path: pathFor('source'), before: old, after: moduleOf(1) }, + { path: pathFor('target'), after: old }, + ]); + assert.deepEqual(rulesIn(result.violations), []); + }); + }); + + describe('syntax errors', () => { + it('fail, because nothing else can be measured on them', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: moduleOf(1), after: 'export const x = (;' }), ['parse-error']); + }); + it('in the old version do not count', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before: 'export const x = (;', after: moduleOf(1) }), []); + }); + }); + + describe('console', () => { + const before = 'export const run = (x) => x;'; + for (const line of [ + 'console.info(1);', + 'console.debug(1);', + 'console.table(1);', + 'window.console.log(1);', + 'globalThis.console.log(1);', + "console['log'](1);", + 'const { log } = console;', + ]) { + it(`red: ${line}`, () => assert.deepEqual(rulesOf({ path: LOGIC, before, after: `${before}\n${line}` }), ['console-log'])); + } + it('green: error and warn', () => { + assert.deepEqual(rulesOf({ path: LOGIC, before, after: `${before}\nconsole.error(1);\nconsole.warn(1);` }), []); + }); + }); + + describe('generic-file-name', () => { + for (const name of ['index.ts', 'index.tsx', 'types.ts', 'utils.ts', 'helpers.ts', 'controller.ts', 'model.ts']) { + it(`red: a new ${name}`, () => { + assert.deepEqual(rulesOf({ path: `src/helper/${name}`, after: moduleOf(1) }), ['generic-file-name']); + }); + } + it('green: an existing one, also moved with its folder', () => { + assert.deepEqual(rulesOf({ path: 'src/helper/index.ts', before: moduleOf(1), after: moduleOf(2) }), []); + assert.deepEqual( + rulesOf({ path: 'src/other/index.ts', previousPath: 'src/helper/index.ts', before: moduleOf(1), after: moduleOf(1), isNewPath: true }), + [] + ); + }); + it('red: a rename into one', () => { + assert.deepEqual( + rulesOf({ path: 'src/helper/index.ts', previousPath: pathFor('thing'), before: moduleOf(1), after: moduleOf(1), isNewPath: true }), + ['generic-file-name'] + ); + }); + }); + + const repos = []; + afterAll(() => { + for (const repo of repos) rmSync(repo, { recursive: true, force: true }); + }); + const git = (repo, ...args) => + execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.com', '-c', 'commit.gpgsign=false', ...args], { + cwd: repo, + encoding: 'utf8', + stdio: 'pipe', + }).trim(); + const put = (repo, path, content) => { + mkdirSync(dirname(join(repo, path)), { recursive: true }); + writeFileSync(join(repo, path), content); + }; + const makeRepo = (files = {}) => { + const repo = realpathSync(mkdtempSync(join(tmpdir(), 'quality-core-'))); + repos.push(repo); + cpSync(toolDir, join(repo, toolRelative), { recursive: true }); + cpSync(join(repoRoot, '.claude/hooks'), join(repo, '.claude/hooks'), { recursive: true }); + writeFileSync(join(repo, '.gitignore'), 'node_modules\n.stub-*\n'); + mkdirSync(join(repo, 'node_modules/.bin'), { recursive: true }); + symlinkSync(join(repoRoot, 'node_modules/typescript'), join(repo, 'node_modules/typescript')); + for (const name of ['tsc', 'vitest', 'eslint']) { + writeFileSync(join(repo, 'node_modules/.bin', name), STUB); + chmodSync(join(repo, 'node_modules/.bin', name), 0o755); + } + put(repo, 'package.json', JSON.stringify({ name: 'fixture', scripts: { typecheck: 'tsc' } })); + put(repo, 'scripts/test/run.cjs', RUNNER_STUB); + git(repo, 'init', '-q', '-b', 'master'); + for (const [path, content] of Object.entries(files)) put(repo, path, content); + git(repo, 'add', '.'); + git(repo, 'commit', '-qm', 'base'); + git(repo, 'update-ref', 'refs/remotes/origin/master', 'HEAD'); + git(repo, 'switch', '-qc', 'feature'); + return repo; + }; + const run = (repo, ...args) => { + const result = spawnSync(process.execPath, [join(repo, toolRelative, 'check.mjs'), ...args], { cwd: repo, encoding: 'utf8' }); + return { code: result.status, out: `${result.stdout}${result.stderr}` }; + }; + const hook = (repo, name, input, cwd = repo) => { + const result = spawnSync(process.execPath, [join(repo, '.claude/hooks', name)], { + cwd, + input: JSON.stringify(input), + encoding: 'utf8', + env: { ...process.env, CLAUDE_PROJECT_DIR: repo }, + }); + return { code: result.status, out: result.stdout, err: result.stderr }; + }; + const stubLog = (repo) => (existsSync(join(repo, '.stub-log')) ? readFileSync(join(repo, '.stub-log'), 'utf8') : ''); + const clearLog = (repo) => rmSync(join(repo, '.stub-log'), { force: true }); + const stop = (repo, extra = {}) => hook(repo, 'check-before-stop.mjs', { stop_hook_active: false, cwd: repo, ...extra }); + const EXISTING = { [LOGIC]: plainFunction('run', 90) }; + + describe('command line: base and working tree', () => { + it('--file: problems in a new file are notes, because the source may not be trimmed yet', () => { + const repo = makeRepo(EXISTING); + put(repo, pathFor('fresh'), 'export const fresh = (x: any, y: any, z: any) => [x, y, z];'); + const { code, out } = run(repo, '--file', pathFor('fresh')); + assert.equal(code, 0); + assert.ok(out.includes('[any]'), out); + assert.ok(out.includes('[params]'), out); + }); + it('--file: problems in an existing file block', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + assert.equal(run(repo, '--file', LOGIC).code, 1); + }); + it('--file: small growth is a note with the number', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 93)); + const { code, out } = run(repo, '--file', LOGIC); + assert.equal(code, 0); + assert.ok(out.includes('90 -> 93'), out); + }); + it('--base: moved code across a deleted file passes', () => { + const repo = makeRepo({ [pathFor('source')]: `${plainFunction('one', 90)}\n${plainFunction('two', 90)}` }); + unlinkSync(join(repo, pathFor('source'))); + put(repo, pathFor('first'), plainFunction('one', 90)); + put(repo, pathFor('second'), plainFunction('two', 90)); + assert.equal(run(repo, '--base', 'origin/master').code, 0); + }); + it('--base: a plain mv without git add stays a rename', () => { + const repo = makeRepo(EXISTING); + renameSync(join(repo, LOGIC), join(repo, pathFor('moved'))); + assert.equal(run(repo, '--base', 'origin/master').code, 0); + assert.equal(run(repo, '--file', pathFor('moved')).code, 0); + }); + it('finds the base the branch really left, not only origin/master', () => { + const repo = makeRepo(EXISTING); + git(repo, 'switch', '-qc', 'release', 'master'); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'release has its own problem'); + git(repo, 'update-ref', 'refs/remotes/origin/release', 'HEAD'); + git(repo, 'switch', '-qc', 'on-release'); + put(repo, pathFor('other'), moduleOf(1)); + git(repo, 'add', '.'); + git(repo, 'commit', '-qm', 'own work'); + const { code, out } = run(repo); + assert.equal(code, 0, out); + assert.ok(out.includes('origin/release'), out); + put(repo, LOGIC, `${broken(90)}\nconsole.log('y');`); + assert.equal(run(repo, '--file', LOGIC).code, 1); + }); + it('a commit pushed under another name is still checked against master', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'a problem'); + git(repo, 'update-ref', 'refs/remotes/origin/another-name', 'HEAD'); + const { code, out } = run(repo); + assert.equal(code, 1, out); + assert.ok(out.includes('origin/master'), out); + }); + it('a detached HEAD on a pushed commit is still checked against master', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'a problem'); + git(repo, 'update-ref', 'refs/remotes/origin/feature', 'HEAD'); + git(repo, 'switch', '-q', '--detach'); + assert.equal(run(repo).code, 1); + }); + it('prefers origin/master when another branch is just as close', () => { + const repo = makeRepo(EXISTING); + git(repo, 'update-ref', 'refs/remotes/origin/sibling', 'HEAD'); + assert.ok(run(repo).out.includes('origin/master')); + }); + // The hooks pass no --base. A branch without commits of its own sits on the default branch, which wins. + it('takes the default branch from origin/HEAD', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'develop moved on'); + git(repo, 'update-ref', 'refs/remotes/origin/develop', 'HEAD'); + git(repo, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/develop'); + const { code, out } = run(repo); + assert.equal(code, 0, out); + assert.ok(out.includes('origin/develop'), out); + }); + it('without origin/HEAD, takes origin/main over an old merged branch', () => { + const repo = makeRepo(EXISTING); + git(repo, 'update-ref', 'refs/remotes/origin/old-fix', 'HEAD'); + git(repo, 'update-ref', '-d', 'refs/remotes/origin/master'); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'main moved on'); + git(repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD'); + const { code, out } = run(repo); + assert.equal(code, 0, out); + assert.ok(out.includes('origin/main'), out); + }); + it('does not write to the index or the object store of the checkout', () => { + const repo = makeRepo(EXISTING); + put(repo, pathFor('fresh'), moduleOf(1)); + const objects = () => git(repo, 'count-objects'); + const before = [git(repo, 'status', '--porcelain'), objects()]; + run(repo, '--base', 'origin/master'); + assert.deepEqual([git(repo, 'status', '--porcelain'), objects()], before); + }); + }); + + describe('edit hook', () => { + const edit = (repo, path) => hook(repo, 'check-edited-file.mjs', { tool_name: 'Write', tool_input: { file_path: join(repo, path) }, cwd: repo }); + it('blocks with exit 2 and the rule on stderr', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + const { code, err } = edit(repo, LOGIC); + assert.equal(code, 2); + assert.ok(err.includes('console-log'), err); + }); + it('does not block code that moved in from another changed file', () => { + const line = 'export const moved = (x) => { console.log(x); };'; + const [source, target] = [pathFor('a'), pathFor('c')]; + const repo = makeRepo({ [source]: `${line}\nexport const k = 1;`, [target]: 'export const j = 1;' }); + put(repo, source, 'export const k = 1;'); + put(repo, target, `export const j = 1;\n${line}`); + assert.equal(run(repo).code, 0); + assert.equal(edit(repo, target).code, 0); + }); + it('still blocks a new problem next to moved code', () => { + const line = 'export const moved = (x) => { console.log(x); };'; + const [source, target] = [pathFor('a'), pathFor('c')]; + const repo = makeRepo({ [source]: `${line}\nexport const k = 1;`, [target]: 'export const j = 1;' }); + put(repo, source, 'export const k = 1;'); + put(repo, target, `export const j = 1;\n${line}\nconsole.log('new');`); + assert.equal(edit(repo, target).code, 2); + }); + it('hands a note to the agent as JSON, with exit 0', () => { + const repo = makeRepo(EXISTING); + put(repo, pathFor('fresh'), 'export const fresh = (x: any) => x;'); + const { code, out } = edit(repo, pathFor('fresh')); + assert.equal(code, 0); + const parsed = JSON.parse(out); + assert.equal(parsed.hookSpecificOutput.hookEventName, 'PostToolUse'); + assert.ok(parsed.hookSpecificOutput.additionalContext.includes('[any]')); + }); + it('stays silent on a clean edit', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 90).replace('run0', 'runA')); + assert.deepEqual(edit(repo, LOGIC), { code: 0, out: '', err: '' }); + }); + it('stays out of the way when the file belongs to another repo', () => { + const repo = makeRepo(EXISTING); + const other = realpathSync(mkdtempSync(join(tmpdir(), 'quality-other-'))); + repos.push(other); + git(other, 'init', '-q', '-b', 'master'); + put(other, LOGIC, plainFunction('run', 300)); + assert.deepEqual(hook(repo, 'check-edited-file.mjs', { tool_input: { file_path: join(other, LOGIC) } }), { code: 0, out: '', err: '' }); + }); + }); + + describe('stop hook', () => { + const fail = (repo, step) => writeFileSync(join(repo, `.stub-fail-${step}`), ''); + const pass = (repo, step) => rmSync(join(repo, `.stub-fail-${step}`), { force: true }); + + it('costs nothing on a branch without changes', () => { + const repo = makeRepo(EXISTING); + assert.deepEqual(stop(repo), { code: 0, out: '', err: '' }); + assert.equal(stubLog(repo), ''); + }); + it('catches a committed violation with a clean tree', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + git(repo, 'commit', '-qam', 'a problem'); + const { code, err } = stop(repo); + assert.equal(code, 2); + assert.ok(err.includes('console-log'), err); + }); + it('runs the typecheck when a change only deletes files', () => { + const repo = makeRepo(EXISTING); + unlinkSync(join(repo, LOGIC)); + fail(repo, 'tsc'); + const { code, err } = stop(repo); + assert.equal(code, 2); + assert.ok(err.includes('tsc is red'), err); + }); + it('runs nothing when no code changed', () => { + const repo = makeRepo(EXISTING); + put(repo, 'README.md', '# hi'); + assert.equal(stop(repo).code, 0); + assert.equal(stubLog(repo), ''); + }); + it('checks the worktree the session is in, not only the project', () => { + const repo = makeRepo(EXISTING); + const linked = join(realpathSync(mkdtempSync(join(tmpdir(), 'quality-linked-'))), 'wt'); + repos.push(dirname(linked)); + git(repo, 'worktree', 'add', '-q', '-b', 'linked', linked, 'master'); + symlinkSync(join(repo, 'node_modules'), join(linked, 'node_modules')); + put(linked, LOGIC, broken(90)); + const { code, err } = stop(repo, { cwd: linked }); + assert.equal(code, 2); + assert.ok(err.includes('console-log'), err); + }); + it('checks a worktree edited through an absolute path, with the cwd in the main checkout', () => { + const repo = makeRepo(EXISTING); + const linked = join(realpathSync(mkdtempSync(join(tmpdir(), 'quality-linked-'))), 'wt'); + repos.push(dirname(linked)); + git(repo, 'worktree', 'add', '-q', '-b', 'linked', linked, 'master'); + symlinkSync(join(repo, 'node_modules'), join(linked, 'node_modules')); + put(linked, LOGIC, broken(90)); + const editInput = { session_id: 'one', tool_input: { file_path: join(linked, LOGIC) }, cwd: repo }; + assert.equal(hook(repo, 'check-edited-file.mjs', editInput).code, 2); + assert.equal(stop(repo, { session_id: 'two', cwd: repo }).code, 0); + const { code, err } = stop(repo, { session_id: 'one', cwd: repo }); + assert.equal(code, 2); + assert.ok(err.includes('console-log'), err); + put(linked, LOGIC, plainFunction('run', 91)); + assert.equal(stop(repo, { session_id: 'one', cwd: repo, stop_hook_active: true }).code, 0); + clearLog(linked); + assert.equal(stop(repo, { session_id: 'one', cwd: repo }).code, 0); + assert.equal(stubLog(linked), ''); + }); + it('checks again after a block when the tree changed', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 91)); + fail(repo, 'tsc'); + assert.equal(stop(repo).code, 2); + put(repo, LOGIC, plainFunction('run', 92)); + assert.equal(stop(repo, { stop_hook_active: true }).code, 2); + pass(repo, 'tsc'); + put(repo, LOGIC, plainFunction('run', 93)); + assert.equal(stop(repo, { stop_hook_active: true }).code, 0); + }); + it('lets go when a block changed nothing, and tells the user', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 91)); + fail(repo, 'tsc'); + assert.equal(stop(repo).code, 2); + clearLog(repo); + const second = stop(repo, { stop_hook_active: true }); + assert.equal(second.code, 0); + assert.equal(stubLog(repo), ''); + assert.ok(JSON.parse(second.out).systemMessage.length > 0); + }); + it('does not loop forever', () => { + const repo = makeRepo(EXISTING); + fail(repo, 'tsc'); + const codes = []; + for (let lines = 91; lines < 96; lines += 1) { + put(repo, LOGIC, plainFunction('run', lines)); + codes.push(stop(repo, { stop_hook_active: lines > 91 }).code); + } + assert.deepEqual(codes, [2, 2, 2, 0, 0]); + }); + it('caches a green tree: an unchanged or question-only turn runs nothing', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 91)); + assert.equal(stop(repo).code, 0); + assert.notEqual(stubLog(repo), ''); + clearLog(repo); + assert.deepEqual(stop(repo), { code: 0, out: '', err: '' }); + assert.equal(stubLog(repo), ''); + put(repo, LOGIC, plainFunction('run', 92)); + assert.equal(stop(repo).code, 0); + assert.notEqual(stubLog(repo), ''); + }); + it('a check that could not run is a note, not a block', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 91)); + git(repo, 'update-ref', '-d', 'refs/remotes/origin/master'); + const { code, out } = stop(repo); + assert.equal(code, 0); + assert.ok(JSON.parse(out).hookSpecificOutput.additionalContext.includes('quality check'), out); + }); + it('a missing tool is a note, not a block', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, plainFunction('run', 91)); + rmSync(join(repo, 'node_modules/.bin/tsc')); + const { code, out } = stop(repo); + assert.equal(code, 0); + assert.ok(JSON.parse(out).hookSpecificOutput.additionalContext.includes('typecheck'), out); + }); + it('a plain mv does not turn moved code into new code', () => { + const repo = makeRepo(EXISTING); + renameSync(join(repo, LOGIC), join(repo, pathFor('moved'))); + assert.equal(stop(repo).code, 0); + }); + it('reports every red step at once', () => { + const repo = makeRepo(EXISTING); + put(repo, LOGIC, broken(90)); + fail(repo, 'tsc'); + const { code, err } = stop(repo); + assert.equal(code, 2); + assert.ok(err.includes('console-log') && err.includes('tsc is red'), err); + }); + }); +}; diff --git a/tools/quality/core.sha256 b/tools/quality/core.sha256 new file mode 100644 index 00000000..69958074 --- /dev/null +++ b/tools/quality/core.sha256 @@ -0,0 +1 @@ +08c8424e02fba5e2718a721ad3f00c0374650ec713b995c724ac0e686bd63029 diff --git a/tools/quality/hooks.mjs b/tools/quality/hooks.mjs new file mode 100644 index 00000000..f95c258d --- /dev/null +++ b/tools/quality/hooks.mjs @@ -0,0 +1,193 @@ +// What the Claude Code and Codex hooks of this repo do. The files in .claude/hooks only name the steps. +// Exit 2 with stderr blocks in both. Plain stdout on exit 0 reaches neither model, so notes go out as JSON. +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { commonDirOf, forkPointOf, headOf, isSameRepository, repoRootOf, resolveBase, workingTreeState } from './changes.mjs'; + +const OUTPUT_LINES = 60; +const MAX_BLOCKS_IN_A_ROW = 3; + +export const projectDirOf = (hookUrl) => resolve(dirname(fileURLToPath(hookUrl)), '../..'); + +export const readHookInput = async () => { + let raw = ''; + for await (const chunk of process.stdin) raw += chunk; + return raw ? JSON.parse(raw) : {}; +}; + +// Claude Code names one file_path. Codex edits through apply_patch and only has the patch in tool_input.command. +export const editedFiles = (input) => { + const toolInput = input.tool_input ?? {}; + if (toolInput.file_path) return [toolInput.file_path]; + const files = []; + for (const line of String(toolInput.command ?? '').split('\n')) { + const edited = line.match(/^\*\*\* (?:Update|Add) File: (.+)$/); + if (edited) files.push(edited[1].trim()); + const moved = line.match(/^\*\*\* Move to: (.+)$/); + if (moved) files[files.length - 1] = moved[1].trim(); + } + return files; +}; + +const block = (reason) => { + process.stderr.write(`${reason}\n`); + process.exit(2); +}; + +const emit = (output) => process.stdout.write(`${JSON.stringify(output)}\n`); + +const rootFor = ({ input, projectDir }) => { + const root = input.cwd ? repoRootOf(input.cwd) : null; + return root && isSameRepository(root, projectDir) ? root : projectDir; +}; + +// A session can edit a linked worktree through an absolute path while its cwd stays elsewhere. The stop hook only knows +// the cwd, so the edit hook leaves the other root here. +const sessionRootsFile = ({ input, projectDir }) => { + const session = String(input.session_id ?? 'unknown').replace(/[^\w.-]/g, '_'); + return join(commonDirOf(projectDir), 'quality-session-roots', `${session}.json`); +}; + +const readSessionRoots = (file) => { + try { + return JSON.parse(readFileSync(file, 'utf8')); + } catch { + return []; + } +}; + +const rememberRoot = ({ input, projectDir, absolute }) => { + if (!existsSync(dirname(absolute))) return; + const root = repoRootOf(dirname(absolute)); + if (!root || root === projectDir || root === rootFor({ input, projectDir }) || !isSameRepository(root, projectDir)) return; + const file = sessionRootsFile({ input, projectDir }); + const roots = readSessionRoots(file); + if (roots.includes(root)) return; + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify([...roots, root])); +}; + +export const runEditHook = async ({ toolPath, projectDir, extraCheck }) => { + const input = await readHookInput(); + const blocking = []; + const notes = []; + for (const file of editedFiles(input)) { + const absolute = resolve(input.cwd ?? projectDir, file); + rememberRoot({ input, projectDir, absolute }); + const result = spawnSync(process.execPath, [toolPath, '--file', absolute], { cwd: projectDir, encoding: 'utf8' }); + if (result.stderr) process.stderr.write(result.stderr); + if (result.status === 1) blocking.push(result.stdout); + else if (result.stdout) notes.push(result.stdout); + const extra = extraCheck?.(absolute); + if (extra) blocking.push(extra); + } + if (blocking.length) block(`The edit is on disk, but it breaks the rules below. Fix it before you continue:\n\n${blocking.join('\n')}`); + if (notes.length) emit({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: `Quality check:\n\n${notes.join('\n')}` } }); +}; + +const tail = (result) => `${result.stdout ?? ''}${result.stderr ?? ''}`.split('\n').slice(-OUTPUT_LINES).join('\n'); + +const runStep = ({ step, root }) => { + if (step.requires && !existsSync(join(root, step.requires))) return { note: `${step.name} could not run: ${step.requires} is missing.` }; + const result = spawnSync(step.command, step.args, { + cwd: root, + encoding: 'utf8', + timeout: step.timeout, + env: { ...process.env, ...step.env }, + maxBuffer: 2 ** 28, + }); + if (result.error?.code === 'ETIMEDOUT') return { note: `${step.name} did not finish in ${step.timeout / 1000} s; CI runs it.` }; + if (result.error) return { note: `${step.name} could not run: ${result.error.message}` }; + if (result.status === step.couldNotRunStatus) return { note: `${step.name} could not run: ${tail(result).trim()}` }; + return result.status === 0 ? {} : { failure: `${step.name} is red:\n${tail(result)}` }; +}; + +const readState = (file) => { + try { + return JSON.parse(readFileSync(file, 'utf8')); + } catch { + return {}; + } +}; + +const forkOrHead = ({ root }) => { + try { + return forkPointOf({ root, base: resolveBase({ root }) }); + } catch { + return headOf({ root }); + } +}; + +// Only Claude Code takes extra context on Stop; it continues the turn once so the agent can say what was not checked. +const emitStopNotes = (notes) => { + const text = `Before you finish, say what was not checked:\n${notes.join('\n')}`; + if (process.env.CLAUDE_PROJECT_DIR) emit({ hookSpecificOutput: { hookEventName: 'Stop', additionalContext: text } }); + else emit({ systemMessage: text }); +}; + +// One checkout: what is left to tell. `isSettled` means nothing more can come of this root in this session. +const gateRoot = ({ root, input, toolPath, isCode, stepsFor }) => { + const fork = forkOrHead({ root }); + const { tree, changes } = workingTreeState({ root, fork }); + const key = `${tree}:${fork}`; + const stateFile = resolve(root, spawnSync('git', ['rev-parse', '--git-path', 'quality-stop-state.json'], { cwd: root, encoding: 'utf8' }).stdout.trim()); + const state = readState(stateFile); + const save = (next) => writeFileSync(stateFile, JSON.stringify(next)); + + const code = changes.filter(({ path }) => isCode(path)); + if (!code.length || state.greenKey === key) return { isSettled: true }; + if (state.reportedKey === key) { + // The agent was told and changed nothing: another block would only burn a turn. + const message = input.stop_hook_active && state.isRed ? 'The quality gate is still red; the agent stopped without changing anything.' : null; + return { message }; + } + const blocks = input.stop_hook_active ? (state.blocks ?? 0) : 0; + if (blocks >= MAX_BLOCKS_IN_A_ROW) return { message: `The quality gate blocked ${blocks} times in a row and was not run again.` }; + + const qualityStep = { name: 'The quality check', command: process.execPath, args: [toolPath], couldNotRunStatus: 3 }; + const existing = changes.filter(({ path, isDeleted }) => !isDeleted && isCode(path)).map(({ path }) => path); + const planned = [qualityStep, ...stepsFor({ root, changed: code.map(({ path }) => path), existing })]; + const failures = []; + const notes = []; + for (const step of planned) { + const { failure, note } = step.note ? { note: step.note } : runStep({ step, root }); + if (failure) failures.push(failure); + if (note) notes.push(note); + } + if (failures.length) { + save({ reportedKey: key, isRed: true, blocks: blocks + 1 }); + return { failures }; + } + if (notes.length) { + save({ reportedKey: key, isRed: false }); + return { notes }; + } + save({ greenKey: key }); + return { isSettled: true }; +}; + +export const runStopGate = async ({ toolPath, projectDir, isCode, stepsFor }) => { + const input = await readHookInput(); + const primary = rootFor({ input, projectDir }); + const rootsFile = sessionRootsFile({ input, projectDir }); + const remembered = readSessionRoots(rootsFile).filter((root) => root !== primary && existsSync(root)); + const outcomes = [primary, ...remembered].map((root) => ({ root, ...gateRoot({ root, input, toolPath, isCode, stepsFor }) })); + + const open = remembered.filter((root) => !outcomes.find((outcome) => outcome.root === root).isSettled); + if (open.length) writeFileSync(rootsFile, JSON.stringify(open)); + else rmSync(rootsFile, { force: true }); + + const inRoot = ({ root }, text) => (root === primary ? text : `In ${root}:\n${text}`); + const failures = outcomes.flatMap((outcome) => (outcome.failures ?? []).map((failure) => inRoot(outcome, failure))); + if (failures.length) block(`Fix this before you finish, or report BLOCKED with the reason:\n\n${failures.join('\n\n')}`); + const notes = outcomes.flatMap((outcome) => (outcome.notes ?? []).map((note) => inRoot(outcome, note))); + if (notes.length) { + emitStopNotes(notes); + return; + } + const messages = outcomes.map(({ message }) => message).filter(Boolean); + if (messages.length) emit({ systemMessage: messages.join('\n') }); +}; diff --git a/tools/quality/measure.mjs b/tools/quality/measure.mjs new file mode 100644 index 00000000..6fdd852e --- /dev/null +++ b/tools/quality/measure.mjs @@ -0,0 +1,78 @@ +// Counts what is on each line of a parsed file: code lines, comments and how wide the code really is. +import ts from 'typescript'; + +const COMMENT = /\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g; +// Text an author cannot break up without changing it: it does not count towards a line's width. +const TEXT_TOKENS = new Set([ + ts.SyntaxKind.StringLiteral, + ts.SyntaxKind.NoSubstitutionTemplateLiteral, + ts.SyntaxKind.TemplateHead, + ts.SyntaxKind.TemplateMiddle, + ts.SyntaxKind.TemplateTail, + ts.SyntaxKind.JsxText, + ts.SyntaxKind.RegularExpressionLiteral, +]); + +export const measureLines = ({ sourceFile, lineChars }) => { + const { text } = sourceFile; + const lineOf = (position) => sourceFile.getLineAndCharacterOfPosition(position).line; + const lineStarts = sourceFile.getLineStarts(); + const marked = new Uint8Array(lineStarts.length); + const spans = new Map(); + const comments = []; + let previousEnd = 0; + + const recordSpan = ({ token, start, line }) => { + const span = spans.get(line) ?? { first: start, last: token.end, textChars: 0 }; + span.first = Math.min(span.first, start); + span.last = Math.max(span.last, token.end); + if (TEXT_TOKENS.has(token.kind)) span.textChars += token.end - start; + spans.set(line, span); + }; + + const visitToken = (token, shouldMark) => { + const start = token.getStart(sourceFile); + const gap = text.slice(previousEnd, start); + // Between two tokens there is only whitespace and comments, so a regex is safe here and only here. + for (const match of gap.matchAll(COMMENT)) { + const commentStart = previousEnd + match.index; + comments.push({ text: match[0], startLine: lineOf(commentStart) + 1, line: lineOf(commentStart + match[0].length) + 1 }); + } + previousEnd = Math.max(previousEnd, token.end); + const isBlankJsxText = token.kind === ts.SyntaxKind.JsxText && token.containsOnlyTriviaWhiteSpaces; + if (!shouldMark || isBlankJsxText || token.end <= start) return; + const firstLine = lineOf(start); + const lastLine = lineOf(token.end - 1); + for (let line = firstLine; line <= lastLine; line += 1) marked[line] = 1; + if (firstLine === lastLine) recordSpan({ token, start, line: firstLine }); + }; + const visit = (node, shouldMark) => { + const children = node.getChildren(sourceFile); + if (!children.length) { + if (node.kind !== ts.SyntaxKind.SyntaxList) visitToken(node, shouldMark); + return; + } + const childMark = shouldMark && !(ts.isJsxExpression(node) && !node.expression); + for (const child of children) visit(child, childMark); + }; + visit(sourceFile, true); + + const lineTextOf = (line) => text.slice(lineStarts[line], line + 1 < lineStarts.length ? lineStarts[line + 1] : text.length).trim(); + const codeUpTo = new Uint32Array(lineStarts.length + 1); + const codeLineTexts = []; + let firstCodeLine = lineStarts.length + 1; + for (let line = 0; line < lineStarts.length; line += 1) { + const lineText = marked[line] === 1 ? lineTextOf(line) : ''; + codeUpTo[line + 1] = codeUpTo[line] + (lineText ? 1 : 0); + if (!lineText) continue; + codeLineTexts.push(lineText); + if (line + 1 < firstCodeLine) firstCodeLine = line + 1; + } + const longLines = []; + for (const [line, span] of spans) { + const width = span.last - span.first - span.textChars; + if (width > lineChars) longLines.push({ line: line + 1, text: lineTextOf(line), width }); + } + const codeLinesOf = (node) => codeUpTo[lineOf(node.end) + 1] - codeUpTo[lineOf(node.getStart(sourceFile))]; + return { comments, codeLines: codeUpTo[lineStarts.length], codeLineTexts, firstCodeLine, longLines, lineOf, codeLinesOf }; +}; diff --git a/tools/quality/moves.mjs b/tools/quality/moves.mjs new file mode 100644 index 00000000..56bb6e95 --- /dev/null +++ b/tools/quality/moves.mjs @@ -0,0 +1,64 @@ +// What a change took out of its files. Code found here again is moved, not new: a split without behaviour change +// must not be punished for code that only changed its address. +export const normalizeItem = (text) => + text + .replace(/^export\s+(default\s+)?/, '') + .replace(/^(public|private|protected)\s+/, '') + .replace(/^(static\s+)?(async\s+)?/, '') + .replace(/\s+/g, ' ') + .trim(); + +const add = (counts, key) => counts.set(key, (counts.get(key) ?? 0) + 1); + +const take = (counts, key) => { + const left = counts.get(key) ?? 0; + if (left <= 0) return false; + counts.set(key, left - 1); + return true; +}; + +const countsWithout = ({ items, removed }) => { + const kept = new Map(); + for (const item of removed) add(kept, normalizeItem(item)); + const gone = new Map(); + for (const item of items) if (!take(kept, normalizeItem(item))) add(gone, normalizeItem(item)); + return gone; +}; + +const mergeInto = (target, counts) => { + for (const [key, count] of counts) target.set(key, (target.get(key) ?? 0) + count); +}; + +const keepLarger = (map, { key, fact }) => { + const current = map.get(key); + if (!current || current.lines < fact.lines) map.set(key, fact); +}; + +export const buildMovePool = (analyzed) => { + const counters = new Map(); + const lines = new Map(); + const byName = new Map(); + const byHash = new Map(); + for (const { beforeFacts, afterFacts } of analyzed) { + if (!beforeFacts) continue; + for (const [rule, items] of Object.entries(beforeFacts.counters)) { + const texts = items.map(({ text }) => text); + const stays = (afterFacts?.counters[rule] ?? []).map(({ text }) => text); + if (!counters.has(rule)) counters.set(rule, new Map()); + mergeInto(counters.get(rule), countsWithout({ items: texts, removed: stays })); + } + mergeInto(lines, countsWithout({ items: beforeFacts.codeLineTexts, removed: afterFacts?.codeLineTexts ?? [] })); + for (const fact of beforeFacts.functions.values()) { + if (afterFacts?.functions.has(fact.key)) continue; + keepLarger(byName, { key: fact.baseName, fact }); + keepLarger(byHash, { key: fact.bodyHash, fact }); + } + } + const removedLines = new Set(lines.keys()); + return { + takeCounter: ({ rule, text }) => take(counters.get(rule) ?? new Map(), normalizeItem(text)), + hasLine: (text) => removedLines.has(normalizeItem(text)), + takeLines: (texts) => texts.filter((text) => take(lines, normalizeItem(text))).length, + findFunction: (fact) => byHash.get(fact.bodyHash) ?? byName.get(fact.baseName) ?? null, + }; +}; diff --git a/tools/quality/rules.mjs b/tools/quality/rules.mjs new file mode 100644 index 00000000..a2703b0b --- /dev/null +++ b/tools/quality/rules.mjs @@ -0,0 +1,345 @@ +// Compares each changed file with its state at the fork point. A rule breaks only if the change made things worse; +// old code that already breaks a rule stays allowed, and code that only moved stays old. +import { basename, dirname } from 'node:path'; + +import { analyzeSource } from './analyze.mjs'; +import { buildMovePool, normalizeItem } from './moves.mjs'; + +const NO_SQUEEZE = 'Never squeeze code onto fewer lines.'; +const FIXES = { + 'file-lines': `Move one responsibility into its own file next to this one. ${NO_SQUEEZE}`, + 'function-lines': `Split by responsibility: extract a part into its own function or sub-component at module level. ${NO_SQUEEZE}`, + 'jsx-return-lines': `Move a part of this JSX into a private sub-component at module level in this file. ${NO_SQUEEZE}`, + 'long-line': `Break it up by responsibility: one statement per line, with named steps. ${NO_SQUEEZE}`, + any: 'Use the real type, or unknown with a type guard. `as unknown as T` is `any` in disguise.', + 'ts-ignore': 'Fix the type error instead of suppressing it.', + 'console-log': 'Remove it. console.error and console.warn are for real failures.', + 'string-compare': 'Compare with a member of the enum for this set of values; search for an existing enum before adding one.', + params: 'Take one object with named fields: fn({ a, b, c }).', + 'file-name': 'Rename the file.', + 'generic-file-name': 'Name the file after what it holds, so the name is unique in the repo and an agent can find it.', + 'folder-name': 'Rename the folder.', + 'component-domain-import': 'src/components holds blocks without a domain. Put this in src/features///, or pass the data in as props.', + 'type-assertion': 'Narrow with a type guard, or fix the type where it comes from. `as const` is fine.', + 'non-null-assertion': 'Handle the missing case, or narrow first.', + 'const-enum': 'Use a plain enum.', + 'local-require': 'Import it at the top of the file. If that makes a cycle, move the shared part into its own module. Only heavy packages load late.', + 'server-logs': 'Log with console.error.', + 'class-validator': 'TSOA validates from the DTO types: leave out the class-validator decorators.', + 'empty-conflict-error': 'Say what went wrong: new ConflictError({ message: ... }).', + 'route-outside-tsoa': 'Add it to a TSOA controller. Only a latency reason justifies a router route: `// quality-allow route-outside-tsoa: ` on the line above.', + 'classnames-import': 'Use cn from @/lib/utils.', + 'default-export': 'Use a named export, so agents can find and rename it.', + 'comment-reference': 'A comment explains why the code is this way; the number belongs in the PR.', + 'comment-attribution': + "Remove the name or date and keep the reason: who decided what, and when, belongs in the PR. An example takes a name that is no teammate's; a date that is data goes in backticks.", + 'comment-date': 'If the date only says when something happened, remove it and keep the reason: that history belongs in the PR. A date the code depends on, such as a cutoff for old data, can stay.', + 'nested-component': 'Move it to module level and pass what it needs as props: a component defined inside another remounts on every render and loses its state.', + 'build-function': 'Write a sub-component at module level instead.', + 'needs-test': 'Add the test or story next to the file.', + 'parse-error': 'Fix the syntax error; nothing else can be measured until then.', +}; +// These have no single line: their quality-allow comment goes anywhere above the first code line. +const FILE_RULES = new Set(['file-lines', 'file-name', 'generic-file-name', 'folder-name', 'needs-test']); +// An allow for these covers the size it was written for. Growing past it needs a new reason, which reviewers then see. +const GROWTH_RULES = new Set(['file-lines', 'function-lines', 'jsx-return-lines', 'params']); +const FOLDER_RULES = new Set(['folder-name']); +// These fail on every new one: a comment that loses its number or stamp does not pay for one that gains it. +const EVERY_NEW_ONE_RULES = new Set(['comment-reference', 'comment-attribution', 'comment-date']); + +const countBy = (items, keyOf) => { + const counts = new Map(); + for (const item of items) counts.set(keyOf(item), (counts.get(keyOf(item)) ?? 0) + 1); + return counts; +}; + +const allowKey = (allow) => `${allow.rule}:${allow.reason}`; + +const newAllowsOf = ({ beforeFacts, afterFacts }) => { + const remaining = countBy(beforeFacts?.allows ?? [], allowKey); + return afterFacts.allows.filter((allow) => { + const left = remaining.get(allowKey(allow)) ?? 0; + remaining.set(allowKey(allow), left - 1); + return left <= 0; + }); +}; + +const isAllowedAt = ({ allows, facts, rule, line }) => + allows.some((allow) => allow.rule === rule && (FILE_RULES.has(rule) ? allow.line < facts.firstCodeLine : allow.line === line - 1)); + +// The sizes are working values, so going over one is a warning. What fails is the ratchet: growing further, by more +// than a small bug fix, what is already too big. +const sizeProblem = ({ config, before, after, growth = after - (before ?? 0), limit, isGuideOnly = false, ...problem }) => { + if (after <= limit || (before != null && growth <= 0)) return null; + const isRatchet = before != null && before > limit && growth > config.limits.smallGrowthLines && !config.legacySizeGrowthWarns; + return { ...problem, before, after, limit, unit: 'code lines', isNote: isGuideOnly || !isRatchet }; +}; + +const growthAllowance = ({ path, beforeFacts, afterFacts, config }) => { + let allowance = 0; + for (const [key, lines] of afterFacts.regions) { + const isCounted = key.startsWith('enum:') || config.isModelFile(path); + if (isCounted && beforeFacts.regions.has(key)) allowance += Math.max(0, lines - beforeFacts.regions.get(key)); + } + return allowance; +}; + +const fileLineProblems = ({ path, beforeFacts, afterFacts, config, movedLines }) => { + const { limits } = config; + if (config.registryFiles.has(path) || config.isFixture(path) || afterFacts.isDataFile) return []; + const after = afterFacts.codeLines; + if (!beforeFacts && after - movedLines <= limits.fileLines) return []; + const before = beforeFacts?.codeLines ?? null; + const growth = beforeFacts ? after - growthAllowance({ path, beforeFacts, afterFacts, config }) - before : after; + const line = afterFacts.firstCodeLine; + const problem = sizeProblem({ config, before, after, growth, limit: limits.fileLines, rule: 'file-lines', line, subject: 'file' }); + if (!problem) return []; + const isExistingUnderLimit = Boolean(beforeFacts) && before <= limits.fileLines && !config.legacySizeGrowthWarns; + const isOverMaximum = (!beforeFacts || isExistingUnderLimit) && after - movedLines > limits.newFileLines; + return [{ ...problem, isNote: problem.isNote && !isOverMaximum }]; +}; + +const newFunctionProblems = ({ fact }) => { + const problems = []; + const { line, name } = fact; + if (fact.isNested && fact.isPascalCase && fact.hasOwnJsx) { + problems.push({ rule: 'nested-component', line, before: null, after: name, subject: 'component inside a function' }); + } + if (/^_?build[A-Z]/.test(fact.baseName) && fact.returnsJsx) { + problems.push({ rule: 'build-function', line, before: null, after: name, subject: 'buildX() returning JSX' }); + } + return problems; +}; + +const paramsProblem = ({ fact, old, path, config }) => { + const limit = config.limits.positionalParams; + if (fact.params <= limit || fact.isParamsExempt || config.isParamsExemptFile(path)) return null; + if (old && fact.params <= old.params) return null; + const subject = `${old ? '' : 'new '}function "${fact.name}"`; + return { rule: 'params', line: fact.line, before: old?.params ?? null, after: fact.params, limit, subject, unit: 'positional parameters' }; +}; + +const functionProblems = ({ path, beforeFacts, afterFacts, config, pool }) => { + const { limits } = config; + const hasNoLineLimit = config.isFixture(path); + const problems = []; + for (const fact of afterFacts.functions.values()) { + const old = beforeFacts?.functions.get(fact.key) ?? pool.findFunction(fact); + const label = `${old ? '' : 'new '}${fact.isComponent ? 'component' : 'function'} "${fact.key}"`; + const limit = fact.isComponent ? (limits.componentLines ?? limits.functionLines) : limits.functionLines; + if (!hasNoLineLimit) { + problems.push( + sizeProblem({ config, before: old?.lines ?? null, after: fact.lines, limit, rule: 'function-lines', line: fact.line, subject: label }) + ); + problems.push( + limits.jsxReturnLines && + sizeProblem({ + config, + before: old?.jsxReturnLines ?? null, + after: fact.jsxReturnLines, + limit: limits.jsxReturnLines, + isGuideOnly: true, + rule: 'jsx-return-lines', + line: fact.jsxReturnLine, + subject: `JSX of ${label}`, + }) + ); + } + problems.push(paramsProblem({ fact, old, path, config })); + if (!old) problems.push(...newFunctionProblems({ fact })); + } + return problems.filter(Boolean); +}; + +const itemsNotInBefore = ({ beforeItems, afterItems }) => { + const remaining = countBy(beforeItems, ({ text }) => normalizeItem(text)); + return afterItems.filter(({ text }) => { + const key = normalizeItem(text); + const left = remaining.get(key) ?? 0; + remaining.set(key, left - 1); + return left <= 0; + }); +}; + +const COUNTER_LABELS = { + any: '`any`', + 'ts-ignore': '@ts-ignore or @ts-expect-error', + 'console-log': 'console.log, info, debug or table', + 'string-compare': 'comparisons or case with a string literal', + 'default-export': 'default exports', + 'comment-reference': 'comments with a ticket or PR number', + 'comment-attribution': "comments with a teammate's name or a date stamp", + 'comment-date': 'comments with a date', + 'type-assertion': '`as` assertions', + 'non-null-assertion': '`!` assertions', + 'const-enum': '`const enum` declarations', + 'local-require': 'local require() calls', + 'server-logs': 'ServerLogs.send calls', + 'class-validator': 'class-validator imports', + 'empty-conflict-error': 'new ConflictError without a message', + 'route-outside-tsoa': 'routes outside TSOA', + 'classnames-import': 'classnames or clsx imports', +}; + +const isMostlyMoved = ({ afterFacts, movedLines, config }) => + movedLines / Math.max(1, afterFacts.codeLines - afterFacts.importCodeLines) >= config.limits.movedShare; + +const counterProblems = ({ beforeFacts, afterFacts, beforeAllows, afterAllows, pool, config, movedLines }) => + Object.keys(afterFacts.counters).flatMap((rule) => { + // An import follows its moved code while the source keeps its own, so it never shows up as removed. + const isImportRule = config.bannedImports.some((banned) => banned.rule === rule); + if (isImportRule && !beforeFacts && isMostlyMoved({ afterFacts, movedLines, config })) return []; + const notAllowed = ({ items, facts, allows }) => items.filter(({ line }) => !isAllowedAt({ allows, facts, rule, line })); + const beforeItems = beforeFacts ? notAllowed({ items: beforeFacts.counters[rule] ?? [], facts: beforeFacts, allows: beforeAllows }) : []; + const afterItems = notAllowed({ items: afterFacts.counters[rule], facts: afterFacts, allows: afterAllows }); + const fresh = itemsNotInBefore({ beforeItems, afterItems }); + const brandNew = fresh.filter(({ text }) => !pool.takeCounter({ rule, text })); + const isWithinCount = afterItems.length - (fresh.length - brandNew.length) <= beforeItems.length; + if (EVERY_NEW_ONE_RULES.has(rule) ? !brandNew.length : isWithinCount) return []; + const lines = [...new Set(brandNew.map(({ line }) => line))].sort((a, b) => a - b).slice(0, 8); + const subject = `${COUNTER_LABELS[rule] ?? 'banned imports'} in this file, new at line ${lines.join(', ')}`; + return [{ rule, line: lines[0], before: beforeItems.length, after: afterItems.length, subject, unit: 'found' }]; + }); + +// An edit that leaves a long line shorter is an improvement, so each new line may take the place of one at least as wide. +const notReplacingAWiderLine = ({ fresh, removed }) => { + const widest = (a, b) => b.width - a.width; + const candidates = [...removed].sort(widest); + return [...fresh].sort(widest).filter(({ width }) => { + if (!candidates.length || candidates[0].width < width) return true; + candidates.shift(); + return false; + }); +}; + +const longLineProblems = ({ beforeFacts, afterFacts, config, pool }) => { + const beforeItems = beforeFacts?.longLines ?? []; + const fresh = itemsNotInBefore({ beforeItems, afterItems: afterFacts.longLines }); + const removed = itemsNotInBefore({ beforeItems: afterFacts.longLines, afterItems: beforeItems }); + const limit = config.limits.lineChars; + return notReplacingAWiderLine({ fresh, removed }) + .filter(({ text }) => !pool.hasLine(text)) + .map(({ line }) => ({ rule: 'long-line', line, before: null, after: 'too wide', limit, subject: `code over ${limit} characters, without strings` })); +}; + +const nameProblems = ({ path, afterFacts, change, config }) => { + const problems = []; + const line = afterFacts.firstCodeLine; + const keptItsName = change.previousPath && basename(change.previousPath) === basename(path); + if (!keptItsName) { + if (config.genericFileNames.has(basename(path).replace(/\.[^.]+$/, ''))) { + problems.push({ rule: 'generic-file-name', line, before: null, after: basename(path), subject: 'a name that many files could have' }); + } else if (!config.isFixture(path) && !afterFacts.isDataFile) { + const subject = config.fileNameProblem({ path, facts: afterFacts }); + if (subject) problems.push({ rule: 'file-name', line, before: null, after: path, subject }); + } + } + for (const folder of change.newFolders ?? []) { + const subject = config.folderNameProblem(folder); + if (subject) problems.push({ rule: 'folder-name', line, before: null, after: folder, subject, folder }); + } + return problems; +}; + +const componentImportProblems = ({ path, beforeFacts, afterFacts, change, config }) => { + if (beforeFacts || !config.isNewComponentBlock?.({ path, newFolders: change.newFolders ?? [] })) return []; + return afterFacts.imports + .filter(({ isTypeOnly, specifier }) => !isTypeOnly && config.isDomainImport({ path, specifier })) + .map(({ line, specifier }) => ({ rule: 'component-domain-import', line, before: null, after: specifier, subject: 'a new block in src/components imports domain code' })); +}; + +const testProblems = ({ path, afterFacts, pathExists, config, movedLines }) => { + if (config.isFixture(path) || afterFacts.isDataFile) return []; + if (isMostlyMoved({ afterFacts, movedLines, config })) return []; + const candidates = config.testCandidates({ path, facts: afterFacts }); + if (!candidates || candidates.some(pathExists)) return []; + const wanted = candidates.map((candidate) => candidate.slice(dirname(path).length + 1)).join(' or '); + return [{ rule: 'needs-test', line: afterFacts.firstCodeLine, before: null, after: `no ${wanted} next to it`, subject: 'new file' }]; +}; + +const checkAnalyzed = ({ entry, config, pathExists, pool }) => { + const { change, beforeFacts, afterFacts } = entry; + const { path } = change; + if (afterFacts.parseError) { + const { line, message } = afterFacts.parseError; + const problem = { rule: 'parse-error', line, before: null, after: message, subject: 'syntax error', path, fix: FIXES['parse-error'] }; + return { problems: [problem], allows: [] }; + } + const newAllows = newAllowsOf({ beforeFacts, afterFacts }); + const movedLines = beforeFacts ? 0 : pool.takeLines(afterFacts.codeLineTexts); + const context = { + path, + beforeFacts, + afterFacts, + beforeAllows: beforeFacts?.allows ?? [], + afterAllows: afterFacts.allows, + config, + change, + pathExists, + pool, + movedLines, + }; + const found = [ + ...fileLineProblems(context), + ...functionProblems(context), + ...counterProblems(context), + ...longLineProblems(context), + ...(change.isNewPath ? nameProblems(context) : []), + ...componentImportProblems(context), + ...(beforeFacts ? [] : testProblems(context)), + ]; + const problems = found.map((problem) => { + const allows = GROWTH_RULES.has(problem.rule) ? newAllows : afterFacts.allows; + const isAllowed = isAllowedAt({ allows, facts: afterFacts, rule: problem.rule, line: problem.line }); + const isNote = problem.isNote || Boolean(config.warningRules?.has(problem.rule)); + return { ...problem, isNote, path, fix: config.fixes?.[problem.rule] ?? FIXES[problem.rule], isAllowed }; + }); + return { problems: problems.filter(({ isAllowed, rule }) => !isAllowed || FOLDER_RULES.has(rule)), allows: newAllows.map((allow) => ({ ...allow, path })) }; +}; + +// One report per new folder, and one allow in any of its files covers the folder. +const mergeFolderProblems = (problems) => { + const groups = new Map(); + const others = []; + for (const problem of problems) { + if (!FOLDER_RULES.has(problem.rule)) { + others.push(problem); + continue; + } + const key = `${problem.rule}:${problem.folder}`; + groups.set(key, [...(groups.get(key) ?? []), problem]); + } + const merged = [...groups.values()].filter((group) => !group.some(({ isAllowed }) => isAllowed)).map(([first]) => first); + return [...others, ...merged]; +}; + +export const checkChanges = ({ changes, config, pathExists }) => { + const analyzeIn = ({ path, source }) => (source == null || !config.isInScope(path) ? null : analyzeSource({ path, source, config })); + const analyzed = changes.map((change) => ({ + change, + beforeFacts: analyzeIn({ path: change.previousPath ?? change.path, source: change.before }), + afterFacts: analyzeIn({ path: change.path, source: change.after }), + })); + const pool = buildMovePool(analyzed); + const results = analyzed.filter(({ afterFacts }) => afterFacts).map((entry) => checkAnalyzed({ entry, config, pathExists, pool })); + const problems = mergeFolderProblems(results.flatMap((result) => result.problems)); + return { + violations: problems.filter(({ isNote }) => !isNote), + notes: problems.filter(({ isNote }) => isNote), + allows: results.flatMap((result) => result.allows), + }; +}; + +export const checkChange = ({ change, config, pathExists }) => checkChanges({ changes: [change], config, pathExists }); + +const describeNumbers = ({ before, after, limit, unit }) => { + const from = before ?? 'new'; + return `${from} -> ${after}${unit ? ` ${unit}` : ''}${limit ? ` (limit ${limit})` : ''}`; +}; + +export const formatViolation = (violation) => + [ + `[${violation.rule}] ${violation.path}:${violation.line}`, + ` ${violation.subject}: ${describeNumbers(violation)}`, + ` Fix: ${violation.fix}`, + ].join('\n'); diff --git a/vitest.config.mjs b/vitest.config.mjs new file mode 100644 index 00000000..c292a070 --- /dev/null +++ b/vitest.config.mjs @@ -0,0 +1,13 @@ +import { defineConfig } from 'vitest/config'; + +// Unit tests run in node; a test file that needs a DOM says so in its docblock (`@vitest-environment jsdom`). +// The built bundle is tested in a real browser by Playwright (playwright.config.mjs), not here. +export default defineConfig({ + test: { + include: ['src/**/*.test.js', 'tools/**/*.test.mjs'], + // The page URL the tests were written against (Jest's default). Vitest's own default adds port 3000. + environmentOptions: { jsdom: { url: 'http://localhost/' } }, + // Node's own Web Storage (on by default from Node 25) shadows jsdom's localStorage. Workers always run without it. + execArgv: ['--no-experimental-webstorage'], + }, +});