Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .claude/agents/test-writer.md
Original file line number Diff line number Diff line change
@@ -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/<Name>.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 <file>` (smoke: `npm run build`, then `npx playwright test <file>`) 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.
113 changes: 113 additions & 0 deletions .claude/commands/review.md
Original file line number Diff line number Diff line change
@@ -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 `<script>` or `<style>` without `applyGleapCSPNonce`; frame markup outside `bootstrapGleapFrame`; a `style` attribute, `setAttribute('style')` or `cssText`; new `innerHTML`, `insertAdjacentHTML`, `outerHTML` or `srcdoc` with text from the server, a message or the page.

### 6. Frames and messages (critical)

Flag `postMessage` with `'*'` for anything but public data; an inbound handler that acts before checking `event.source` or `originMatchesUrl`, or checks an origin with `includes`, `startsWith` or a regex; `JSON.parse` of message data outside `try`; an unknown message name treated as an error; a renamed or removed message name or field; a URL from a message opened without the url handler.

### 7. Privacy (critical)

Flag `localStorage` or `document.cookie` outside their helpers, a new key without the `gleap-` prefix, a renamed key; a capture path (screenshot, replay, network or console log) that skips the masking rules; an identity token, grant or auth token in storage, a log or a URL; data collected that no feature shows.

### 8. Load time, size and browsers

Flag a request, layout read or timer at module load; long synchronous work on the main thread; unbounded buffers; a raised size budget without a reason in the PR; a browser API newer than the ES2020 targets without feature detection; a changed browser target.

### 9. Tests

Flag new behaviour or a fix without a test, an existing test edited to make a change pass, `.skip`/`.only`, retries or sleeps, a mock of the module under test or its helpers, a public API change without `npm run test:smoke` having run.

### 10. Over-engineering

Flag abstractions for one use, helpers for a single call site, options for hypothetical future needs.

### 11. Dead code

Warning: unused imports, commented-out code, new `console.log`, stale TODOs. Critical: exported functions nothing imports (verify with Grep), a public method nothing calls is not dead code.

### 12. Impact and risk (critical)

Read the whole changed function, search all callers of a changed signature or return value, and check every branch of a changed condition. Flag a changed signature with callers not updated, a return that now differs, weakened error handling, a changed default, and anything that changes what an existing customer's page sees after the next merge to `master`.
38 changes: 38 additions & 0 deletions .claude/hooks/check-before-stop.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Before a turn ends: the quality check, the typings check and the tests the change reaches, once per tree. Red means
// the turn is not done. Never the full suite: several sessions share this machine and CI runs it anyway. The build and
// the smoke tests stay with CI and AGENTS.md: they need a build first.
import { join } from 'node:path';

import { projectDirOf, runStopGate } from '../../tools/quality/hooks.mjs';

const TEST_WORKERS = 4;
const TYPECHECK_TIMEOUT_MS = 60_000;
const TESTS_TIMEOUT_MS = 240_000;

const projectDir = projectDirOf(import.meta.url);

await runStopGate({
projectDir,
toolPath: join(projectDir, 'tools/quality/check.mjs'),
isCode: (file) => /^(src|tools|smoke)\/.*\.(js|mjs|cjs|ts)$/.test(file) || file === 'index.d.ts',
stepsFor: ({ existing }) => [
{
name: 'npm run typecheck',
command: 'npm',
args: ['run', '--silent', 'typecheck', '--', '--pretty', 'false'],
requires: 'node_modules/.bin/tsc',
timeout: TYPECHECK_TIMEOUT_MS,
},
...(existing.length
? [
{
name: 'vitest related',
command: 'npx',
args: ['--no-install', 'vitest', 'related', ...existing, '--run', '--passWithNoTests', `--maxWorkers=${TEST_WORKERS}`],
requires: 'node_modules/.bin/vitest',
timeout: TESTS_TIMEOUT_MS,
},
]
: []),
],
});
8 changes: 8 additions & 0 deletions .claude/hooks/check-edited-file.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// After every edit: the quality check on that one file, so the agent sees problems at once.
import { join } from 'node:path';

import { projectDirOf, runEditHook } from '../../tools/quality/hooks.mjs';

const projectDir = projectDirOf(import.meta.url);

await runEditHook({ projectDir, toolPath: join(projectDir, 'tools/quality/check.mjs') });
44 changes: 44 additions & 0 deletions .claude/rules/code-conventions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
paths:
- "src/**/*.js"
---

# Code conventions

For new files and the code you change; do not rewrite other code to match. The code around you is full of patterns new code must not copy, so copy the examples below, not your neighbours. `node tools/quality/check.mjs` checks the rules it can see; it judges only what your branch adds.

- **Size:** aim for files under 400 lines and never write a new one over 700. Functions 80 lines, counted without blanks and comments. These are working values, not proven limits. Tests and fixtures have none. A file or function already too big must not grow (`Gleap.js`, `GleapSession.js`, `UI.js`, `GleapFrameManager.js` and others are): put the new part in its own module and call it from there. Split by responsibility; never squeeze code onto fewer lines.
- **Parameters:** at most 2 positional, from 3 on one object with named fields. Callbacks a browser API or library calls are exempt. Existing public methods keep their signatures (`AGENTS.md` → Public API).
- **Modules:** one responsibility per file in `src/`, named after it in PascalCase (`GleapTourSelector.js`), unique in the repo: no new `index`, `utils` or `helpers`. Named exports only: a default export has no canonical name, so agents cannot find or rename it reliably. `src/index.js` keeps its default export, the package's entry. Existing default exports and `getInstance()` singletons stay; new logic is plain exported functions, with state in a class only when it has a lifecycle (start, stop).
- **Imports:** relative paths. A module that only needs one manager imports it from its own file, not from `./Gleap`: that file pulls in the whole SDK and makes cycles. No new runtime package: `smoke/bundleCost.spec.mjs` fails on an import package.json does not declare, and adding one is a Stop-and-ask (`AGENTS.md`).
- **Values:** a closed set of values is one frozen object of named constants (`Object.freeze({ OPEN: 'open' })`) next to the code that owns it, with no string literals in comparisons or `case`. The values are the stored or wire strings: add members, never rename a value, and handle a value the Server or the Messenger may add later. DOM values (`event.key === 'Enter'`, `typeof x === 'string'`) are fine.
- **One definition:** before adding a helper, constant or message name, search for an existing one and extend it if it covers most of the need. A value the Server stores keeps exactly the Server's strings (`../Server`, from a worktree `../../Server`); a message name the Messenger reads keeps the Messenger's (`../Messenger-App`).
- **Noise:** no `console.log`; `console.warn` and `console.error` only for what the customer's developer must act on, naming Gleap (`[Gleap] …`), at most once per cause. No commented-out code. A comment says why, in English, in one or two lines, and only where the code cannot. No ticket or PR numbers, people's names, dates or decision histories: those belong in the PR.
- **JSDoc** on every new exported function: what it does, `@param` and `@returns` with types. It is the only type information this code has.

## One job, one system

Where the code has a helper for a job, new code uses it. Each one carries a rule the direct call misses.

| Job | Use | Not in new code |
|---|---|---|
| Browser storage | `saveToGleapCache`, `loadFromGleapCache`, `clearGleapCache` (`src/GleapHelper.js`) | `localStorage` directly, a key without the `gleap-` prefix |
| Cookies | `setGleapCookie`, `getGleapCookie`, `eraseGleapCookie` (`src/GleapHelper.js`) | `document.cookie` directly |
| `<script>` and `<style>` the SDK creates | `applyGleapCSPNonce(element)` before it is added | an element without the page's nonce |
| A Gleap frame | `bootstrapGleapFrame` (`src/GleapHelper.js`): stamps the nonce, reports CSP blocks, falls back to `src` | `document.write` or `srcdoc` of your own |
| Sending to a frame | `postMessage(JSON.stringify(data), frameTargetOrigin(frame, url))` (`src/GleapMessageSecurity.js`) | `'*'` as the target origin |
| Receiving from a frame | `event.source === frame.contentWindow`, or `originMatchesUrl(event.origin, url)` | `includes`, `startsWith` or a regex on an origin |
| Opening a link | the frame manager's url handler, which checks `isSafeNavigationUrl` | `window.open` or `location.href` with a URL from a message or the server |
| Requests to the Gleap API | `XMLHttpRequest` to `GleapSession.getInstance().apiUrl` with `GleapSession.getInstance().injectSession(xhr)` | a literal API host, headers set by hand |
| Selectors from the dashboard | `querySelectorSafe`, `querySelectorAllSafe` (`src/GleapSafeSelector.js`) | `document.querySelector` with a server value |
| Work that can wait | `runWhenIdle` (`src/GleapIdle.js`) | `requestIdleCallback` directly |
| Masking in screenshots and replays | `src/GleapInputMasking.js` | a masking rule of your own |
| Network logs | `src/GleapNetworkLogSanitizer.js` (blacklist, redaction) | logging headers or bodies unredacted |

## Examples to copy

The closest we have today, so copy only what each line names, and not their default exports.

- Small module of exported functions with its test beside it: `src/GleapMessageSecurity.js`, `src/GleapMessageSecurity.test.js`.
- Logic with a DOM, tested in jsdom: `src/GleapSafeSelector.js`, `src/GleapShadowSelector.test.js`.
- A wrapper that restores only its own patch: `stop()` in `src/GleapConsoleLogManager.js`.
50 changes: 50 additions & 0 deletions .claude/rules/host-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
paths:
- "src/**/*.js"
---

# Code on the customer's page

This code runs inside websites we do not own, next to their frameworks, their monitoring tools and their Content Security Policy, in browsers we do not choose. For new code and the code you change; do not rewrite old code to match. Each rule names the helper that already does it right.

## Leave the page as it was

- **One global, `window.Gleap`.** No new `window.*` properties, no changes to built-in prototypes, no polyfills. The canvas patch at the top of `src/Gleap.js` is old and not a pattern. `npm run test:smoke` fails on a new global.
- **Custom elements** start with `gleap-` and are defined only if `customElements.get` finds none (`src/GleapChecklist.js`).
- **CSS** reaches only our own elements: selectors under a `gleap-` class or inside our shadow root, never bare element selectors, never `!important` on the page's elements.
- **Wrapping `fetch`, `XMLHttpRequest` or `console`:** only when the feature starts, once; call the original with the original `this` and arguments, never throw from the wrapper, and on stop restore only where our wrapper is still installed (`stop()` in `src/GleapConsoleLogManager.js`).
- **Everything you start, you stop:** each listener, observer, timer and frame has a teardown that `Gleap.destroy()` reaches. Scroll, touch and wheel listeners are `{ passive: true }`.
- **Never throw into the page.** A public method catches its own errors; a callback the customer passed us is called inside `try`. An unreachable Gleap API is normal: the page keeps working, at most one warning.

## Content Security Policy and Trusted Types

Many customers send a strict CSP, and the about:blank frames the SDK writes inherit it.

- No `eval`, `new Function`, or a string passed to `setTimeout` or `setInterval`.
- Every `<script>` and `<style>` the SDK creates goes through `applyGleapCSPNonce`; frame markup goes through `bootstrapGleapFrame`, which stamps the nonce.
- Set styles through `element.style.x` or `style.setProperty`: a `style` attribute in markup, `setAttribute('style')` and `cssText` are blocked under `style-src` without `'unsafe-inline'`.
- Build DOM with `createElement` and `textContent`. No new `innerHTML`, `insertAdjacentHTML`, `outerHTML` or `srcdoc` with text from the server, a message or the page: those are what Trusted Types forbids and where XSS starts. Static markup we wrote ourselves is the one exception.

## Frames and messages

- Send with `frameTargetOrigin(frame, url)`; `'*'` only for data any page may see, with a comment saying why.
- Act on a message only after `event.source === frame.contentWindow` or `originMatchesUrl(event.origin, url)` (`src/GleapMessageSecurity.js`). Parse it inside `try`, act only on names you know, and ignore the rest: an older or newer Messenger sends names this version does not know.
- A message name or field the Messenger sends or reads keeps working in both directions. Rename nothing; add a new name and keep handling the old one (`AGENTS.md` → Stop and ask).
- A URL from a message or the server opens only through the url handler (`isSafeNavigationUrl`), and never reaches an HTML sink.

## Privacy

- Cookies through `setGleapCookie` (credentials get `SameSite=Lax`, and `Secure` on https), storage through `saveToGleapCache`. New keys start with `gleap-`. Never rename an existing key: that signs users out. Respect `Gleap.setUseCookies(false)`.
- Screenshots, replays and logs mask with the shared rules (`src/GleapInputMasking.js`, `src/GleapNetworkLogSanitizer.js`) before anything leaves the browser. A new capture path reuses them; masking stays on by default.
- No fingerprinting: collect only what a feature shows to the support team, and nothing a page did not hand us.
- No identity token, grant or auth token in storage, a cookie we did not design for it, a log or a URL.

## Load time and size

- Loading the bundle only registers: no request, no layout read, no timer. Work starts in `Gleap.initialize` or later, and what can wait goes through `runWhenIdle`.
- Long work is split into tasks under 50 ms; buffers are capped; state per DOM node lives in a `WeakMap`.
- Every customer downloads the whole bundle on every page. A new dependency or a large feature says its size cost in the PR; `npm run test:smoke` enforces the budgets in `smoke/bundleCost.spec.mjs`, raised only with a reason.

## Browsers

Babel compiles our syntax; nothing adds missing APIs. The capture modules and our dependencies need ES2020 browsers (`babel.config.js`: Chrome and Edge 80, Firefox 74, Safari 13.1). An API newer than that is feature-detected with a fallback, like `runWhenIdle` for Safari's missing `requestIdleCallback`. Changing the browser targets is a build change: stop and ask.
Loading
Loading