# API Reference Complete reference for the TraceBug SDK programmatic API. ## Default Export ```typescript import TraceBug from "tracebug-sdk"; ``` `TraceBug` is a singleton instance of `TraceBugSDK`. All methods are called on this instance. --- ## Initialization ### `TraceBug.init(config)` Initialize TraceBug. Call once on app startup. ```typescript TraceBug.init({ projectId: "my-app", // Required maxEvents: 200, // Default: 200 maxSessions: 50, // Default: 50 enableDashboard: true, // Default: true enabled: "auto", // Default: "auto" theme: "light", // Default: "light" toolbarPosition: "right", // Default: "right" minimized: false, // Default: false captureConsole: "all", // Default: "all" shortcuts: { ... }, // Custom keyboard shortcuts }); ``` **Parameters:** | Option | Type | Default | Description | |--------|------|---------|-------------| | `projectId` | `string` | *required* | Identifies your app in stored data | | `maxEvents` | `number` | `200` | Max events stored per session | | `maxSessions` | `number` | `50` | Max sessions kept in localStorage | | `enableDashboard` | `boolean` | `true` | Show the compact toolbar on page | | `enabled` | `string \| string[]` | `"auto"` | Controls when SDK is active (see [Configuration](configuration.md)) | | `theme` | `"dark" \| "light" \| "auto"` | `"light"` | Color theme (`"auto"` follows system preference) | | `toolbarPosition` | `"right" \| "left" \| "bottom-right" \| "bottom-left"` | `"right"` | Toolbar position on screen | | `minimized` | `boolean` | `false` | Start in minimized FAB mode | | `captureConsole` | `"errors" \| "warnings" \| "all" \| "none"` | `"all"` | Console capture level (see [Configuration](configuration.md)) | | `redact` | `{ fields?: string[]; patterns?: (string \| RegExp)[] }` | — | App-specific redaction rules applied at capture (see [Configuration](configuration.md#redact)) | | `shortcuts` | `object` | `{}` | Custom keyboard shortcuts | ### `TraceBug.destroy()` Tear down the SDK completely. Removes all listeners, dashboard UI, and clears in-memory data. ```typescript TraceBug.destroy(); ``` --- ## Plan (Freemium) > All gates are currently dormant — everything is free. ### `TraceBug.getPlan(): "free" | "premium"` Returns the current plan. Hydrated from `chrome.storage.local` (extension) or `localStorage` (web SDK) at init. ### `TraceBug.isPremium(): boolean` Convenience for `getPlan() === "premium"`. ### `TraceBug.setPlan(plan): Promise` Persist the plan. Used by the in-modal dev toggle and (future) upgrade flow. ### `TraceBug.hydratePlan(): Promise` Read storage and cache. Called automatically at `init()`; rarely needed directly. ### `TraceBug.FREE_LIMITS` `{ screenshots: 2 }` — the free-tier caps. **Free vs premium gates summary** (all gates currently dormant — everything is free): > ⚠️ **Gates are currently OFF** — paid plans aren't live yet, so `PLANS_LIVE` is `false` and `isPremium()` returns `true` for everyone. Every method below behaves as the "premium" path today (unlimited screenshots, PDF/Jira generated, full report). The table describes behavior *when plans launch*. | Method | Free behavior (when plans are live) | |---|---| | `takeScreenshot()` / `takeRegionScreenshot()` | Returns `null` and shows upgrade modal at the 2-screenshot cap | | `downloadPdf()` | Shows upgrade modal; no PDF generated | | `getJiraTicket()` | Shows upgrade modal; returns `null` | | `generateReport()` | Returns the report with `consoleErrors: []` and `networkErrors: []` | | `companyName` config | Ignored (no branding line prepended) | --- ## Recording Control ### `TraceBug.pauseRecording()` Pause event capture. Events will not be recorded until resumed. ### `TraceBug.resumeRecording()` Resume recording after a pause. ### `TraceBug.startRecording()` Alias for `resumeRecording()`. Use `start` / `stop` when you want a clear "begin a bug ticket" semantic. ### `TraceBug.stopRecording()` Pauses recording **and** opens the ticket-review modal so the user can see every captured step + screenshot before exporting. Equivalent to `pauseRecording()` followed by `quickCapture()`. ```typescript TraceBug.startRecording(); // begin recording a ticket // ...user clicks around, takes screenshots via toolbar... TraceBug.stopRecording(); // pauses + opens the ticket-review modal ``` The modal uses any screenshots already stashed in the ticket; downloads happen only when the user clicks an export action. ### `TraceBug.isRecording(): boolean` Returns `true` if currently recording events. ### `TraceBug.getSessionId(): string | null` Returns the current session ID, or `null` if not initialized. --- ## Bug Ticket Flow > Full step-by-step flow with all options: see [docs/ticket-flow.md](ticket-flow.md). TraceBug treats a recording cycle as a **bug ticket**: 1. `startRecording()` (or just leave recording on by default) 2. User reproduces the bug. Toolbar buttons (camera / region) **add screenshots to the ticket** — no instant downloads. 3. `stopRecording()` (or click the recording toggle) → ticket-review modal opens automatically. 4. User reviews title + description + numbered screenshot gallery. 5. Click any export action — **all** screenshots in the ticket download alongside the markdown/clipboard payload. The ticket-review modal is the same modal opened by `quickCapture()` / `Ctrl+Shift+B`; calling either path is equivalent. ### `TraceBug.quickCapture(): Promise` Open the ticket-review modal. If the active ticket already has screenshots (added via the toolbar during recording), the modal renders all of them as a numbered gallery; otherwise it captures one fresh so the modal isn't empty. ```typescript await TraceBug.quickCapture(); ``` **Keyboard shortcut:** `Ctrl+Shift+B` (works anywhere on the page when the dashboard is mounted). **Toolbar button:** Click the ⚡ icon (first button after the recording dot). The modal: - Header: "Bug Ticket — Review & Export" with a count line ("3 screenshots attached · download/copy includes all screenshots") - Auto-fills title from session context (`generateBugTitle`) - Auto-fills description with steps + environment + error details - Renders the **primary preview** (first screenshot) and a **numbered thumbnail strip** for the rest; click a thumbnail to swap it into the primary preview - Auto-saves draft to `tracebug_last_bug_draft` (recovered if you accidentally close) - Closes on Escape, click-outside, or after a successful export **Export actions** (from the Quick Bug modal footer + **More ▾** menu): | Button | Action | |--------|--------| | **Export .html** | Self-contained interactive DOM replay (rrweb), with a live size estimate. Best for a developer or an MCP-connected agent. | | **Export HAR** | Network capture as a standard `.har` (DevTools / Charles / Postman). | | **Fix with AI** | Builds the structured AI prompt and opens Claude / ChatGPT (or runs BYO-key analysis in the AI tab). | | **Open in GitHub** | Prefilled GitHub issue (shown when `githubRepo` is set), or files a real issue if a token is configured. | | **Download .zip (attach to GitHub)** *(More)* | The replay `.html` wrapped in a `.zip` — GitHub issues accept `.zip` attachments but reject bare `.html`. | | **Download failing test (.spec.ts)** *(More)* | Runnable Playwright spec that replays the session and asserts the failure is gone — red until fixed. | | **Export for AI (.html)** *(More)* | Tiny (~5 KB) text-only HTML report — paste/upload into a chat, no MCP needed. | | **Download report (.md)** *(More)* | Compact markdown report. | | **Download screenshots** *(More)* | Raw PNG(s) to attach alongside the `.md`. | | **GitHub / Linear / Slack / Jira** *(More)* | File a real issue/message with a configured token ([integrations.md](integrations.md)). | > A cloud **Share link** button exists in the code but is gated off by default (`PHASE2-CLOUD`). ## Screenshots ### `TraceBug.takeScreenshot(): Promise` Capture a screenshot of the current page and add it to the active ticket. Returns the screenshot data (base64 data URL, filename, dimensions), or `null` if capture fails or the free screenshot cap is hit. Any visible annotation badges/outlines are included as rendered. ```typescript const screenshot = await TraceBug.takeScreenshot(); // Region screenshot (drag to select an area): const region = await TraceBug.takeRegionScreenshot(); ``` In the Chrome Extension, screenshots use `chrome.tabs.captureVisibleTab` instead of html2canvas for reliable cross-origin capture. ### `TraceBug.takeRegionScreenshot(): Promise` Snipping-tool style screenshot. Shows a fullscreen overlay; the user drags a rectangle; the cropped PNG is **added to the active ticket** (`getScreenshots()`). It is **not** auto-downloaded — downloads happen only when the user exports the ticket from the review modal. ```typescript const region = await TraceBug.takeRegionScreenshot(); if (region) { console.log("Added to ticket:", region.filename, region.width, region.height); } ``` **Behavior:** - Press `Esc` while the overlay is open to cancel — resolves to `null` - Drag smaller than 5×5 px — resolves to `null` - Cropping handles devicePixelRatio (scales source by `naturalWidth / window.innerWidth`) - Filename pattern: `XX_..._region.png` (the `_region` suffix differentiates from full-viewport captures) **Toolbar button:** corner-square icon next to the camera (tooltip: "Region Screenshot — drag to select, added to ticket"). ### `TraceBug.getScreenshots(): ScreenshotData[]` Get all screenshots captured in the current session. **ScreenshotData type:** ```typescript interface ScreenshotData { id: string; timestamp: number; dataUrl: string; // Base64 PNG filename: string; // e.g. "01_click_button.png" eventContext: string; // What triggered capture page: string; // URL pathname width: number; height: number; } ``` --- ## Tester Notes ### `TraceBug.addNote(options)` Add a tester annotation to the current session. ```typescript TraceBug.addNote({ text: "Button doesn't respond after first click", expected: "Button should submit the form", actual: "Nothing happens on click", severity: "critical", }); ``` **Options:** | Option | Type | Required | Description | |--------|------|----------|-------------| | `text` | `string` | Yes | The observation | | `expected` | `string` | No | Expected behavior | | `actual` | `string` | No | Actual behavior | | `severity` | `"critical" \| "major" \| "minor" \| "info"` | No | Default: `"info"` | | `screenshotId` | `string` | No | Link to a screenshot | --- ## Voice Recording Uses the Web Speech API (free, built into Chrome/Edge/Brave). No audio is stored — only text transcripts. ### `TraceBug.isVoiceSupported(): boolean` Check if the browser supports speech recognition. ### `TraceBug.startVoiceRecording(options?): boolean` Start speech-to-text recording. Returns `true` if started successfully. ```typescript TraceBug.startVoiceRecording({ onUpdate: (text, interim) => { console.log("Transcript:", text); console.log("Speaking:", interim); }, onStatus: (status, message) => { console.log(status); // "recording" | "stopped" | "error" }, }); ``` ### `TraceBug.stopVoiceRecording(): VoiceTranscript | null` Stop recording and return the transcript. ### `TraceBug.isVoiceRecording(): boolean` Check if voice is currently recording. ### `TraceBug.getVoiceTranscripts(): VoiceTranscript[]` Get all voice transcripts from the session. --- ## Element Annotate Mode Click any element on the page to select it and attach structured feedback (intent, severity, comment). Page scroll freezes during annotation. ### `TraceBug.activateAnnotateMode()` Enter annotate mode. A purple banner appears at the top of the page. ### `TraceBug.deactivateAnnotateMode()` Exit annotate mode. ### `TraceBug.isAnnotateModeActive(): boolean` Check if annotate mode is currently active. **In annotate mode:** - Hover over elements to see a purple highlight - Click an element to open the feedback form - Hold `Shift` and click to select multiple elements - Right-click to open feedback for multi-selected elements - Press `Esc` to exit --- ## Inspect Mode (Style Evidence) DevTools-style element inspection for design-QA bugs. Hover paints a box-model highlight (margin / padding / content tint) plus a computed-style tooltip; click attaches the element to the report as an `inspect` annotation with a curated ~20-property style snapshot (typography, colors as hex, box model, layout) and a WCAG contrast verdict. See [annotate-and-draw.md](annotate-and-draw.md). ### `TraceBug.activateInspectMode()` Enter inspect mode (also on the extension popup as **Inspect element**). Press `Esc` to exit. ### `TraceBug.deactivateInspectMode()` Exit inspect mode. ### `TraceBug.isInspectModeActive(): boolean` Check if inspect mode is currently active. ### Style-evidence helpers (named exports) ```typescript import { captureStyleEvidence, formatStyleSummary, contrastRatio, cssColorToHex } from "tracebug-sdk"; import type { StyleEvidence } from "tracebug-sdk"; ``` | Export | What it does | |---|---| | `captureStyleEvidence(el): StyleEvidence` | Snapshot the curated computed-style evidence for an element: `typography`, `colors`, `box`, `layout`, plus optional `contrast` (ratio + AA / AA-large pass, omitted when the element has no visible text). | | `formatStyleSummary(s): string` | One-line summary, e.g. `13.5px/20px 600 Inter · color #ffffff on #4f46e5 · 686px×38px · contrast 6.29:1` | | `contrastRatio(fg, bg): number \| null` | WCAG contrast ratio (1–21) between two computed CSS colors; `null` for unparseable input. | | `cssColorToHex(css): string` | Computed `rgb()/rgba()` → `#rrggbb` (alpha appended as ` / NN%` when < 1). | Annotate-mode annotations capture the same evidence automatically — it rides on `ElementAnnotation.styles`. --- ## Draw Mode Draw rectangles or ellipses directly on the live page to mark layout, spacing, or alignment regions. ### `TraceBug.activateDrawMode()` Enter draw mode. A toolbar appears at the top with shape and color options. ### `TraceBug.deactivateDrawMode()` Exit draw mode. ### `TraceBug.isDrawModeActive(): boolean` Check if draw mode is currently active. **In draw mode:** - Drag to draw shapes - Choose between Rectangle and Ellipse - Pick from 5 colors (Purple, Red, Yellow, Green, Blue) - Add a comment after each shape - Press `Esc` or click **Done** to exit --- ## UI Annotations (Export) ### `TraceBug.getAnnotationReport(): UIAnnotationReport` Get a complete report of all element annotations and draw regions. ```typescript const report = TraceBug.getAnnotationReport(); console.log(report.elementAnnotations); // ElementAnnotation[] console.log(report.drawRegions); // DrawRegion[] ``` ### `TraceBug.exportAnnotationsJSON(): string` Export all annotations as a formatted JSON string. ### `TraceBug.exportAnnotationsMarkdown(): string` Export all annotations as a Markdown document. ### `TraceBug.copyAnnotationsToClipboard(format): Promise` Copy annotations to clipboard. Returns `true` on success. ```typescript await TraceBug.copyAnnotationsToClipboard("markdown"); await TraceBug.copyAnnotationsToClipboard("json"); ``` ### `TraceBug.clearAnnotations()` Remove all element annotations and draw regions. --- ## Report Generation ### `TraceBug.generateReport(): BugReport | null` Generate a complete bug report for the current session including steps, errors, environment, screenshots, annotations, and timeline. ### `TraceBug.getGitHubIssue(): string | null` Generate a GitHub issue in Markdown format. Copies to clipboard via the dashboard. ### `TraceBug.getJiraTicket(): JiraTicket | null` Generate a Jira ticket payload with summary, description, priority, and labels. ### `TraceBug.downloadPdf()` Generate a print-optimized HTML report and open the browser print dialog. ### `TraceBug.getBugTitle(): string | null` Get an auto-generated bug title based on the session timeline (e.g., "Vendor Update Fails — TypeError"). ### `TraceBug.getEnvironment(): EnvironmentInfo` Get current environment info: browser, OS, viewport, device type, connection type. --- ## Debugging Assistant (v1.3+) Every report generated by TraceBug now includes four derived fields that turn "what happened" into "why it likely happened." You rarely need to call these directly — they are populated automatically when you call `TraceBug.generateReport()` — but they are exported for advanced use. ### `TraceBug.getNetworkFailures(): NetworkFailure[]` Returns the last 10 failed network requests captured in memory, newest last, with response body snippets. Cleared on `destroy()` and on "Clear All Data." ```typescript TraceBug.getNetworkFailures(); // [ // { url: "/api/orders", method: "POST", status: 500, // response: "{\"error\":\"database timeout\"}", timestamp: 1712992347123 }, // ... // ] ``` ### `generateRootCauseHint(report): RootCauseHint` Produces a confidence-tiered cause hint. Pure function, no async. Reads only `report.networkErrors[0]`, `report.consoleErrors[0]`, and `report.clickedElement`. ```typescript import { generateRootCauseHint } from "tracebug-sdk"; const report = TraceBug.generateReport()!; generateRootCauseHint(report); // { hint: "API POST /orders failed with 500 after clicking 'Place Order'", // confidence: "high" } ``` Confidence tiers: | Signal | Confidence | Example | |---|---|---| | Network failure present | `high` | `"API POST /orders failed with 500 after clicking 'Place Order'"` | | Runtime error, no network | `medium` | `"TypeError suggests undefined/null data — the response or upstream value was likely missing"` | | Click only / fallback | `low` | `"Click on 'Submit' did not trigger any observable effect"` | ### `formatRootCauseLine(rc): string` Renders a `RootCauseHint` as the shared one-liner used by all exporters: ``` 🔍 Possible Cause (high confidence): API POST /orders failed with 500 after clicking 'Place Order' ``` ### `generateSmartSummary(report): string` One-sentence TL;DR. Uses network + error + click + page signals in priority order. ```typescript import { generateSmartSummary } from "tracebug-sdk"; generateSmartSummary(TraceBug.generateReport()!); // "API POST /orders failed with 500 when clicking 'Place Order' button on /checkout" ``` ### `generateSessionSteps(events): string[]` Last ~10 user-facing actions as plain-English strings (FIFO). Input events are intentionally skipped to keep the list scannable. ```typescript import { generateSessionSteps, getAllSessions } from "tracebug-sdk"; const session = getAllSessions().at(-1)!; generateSessionSteps(session.events); // [ // "Clicked 'Cart' link", // "Navigated to /checkout", // "Selected 'Express shipping' in delivery", // "Clicked 'Place Order' button", // ] ``` ### `extractClickedElement(events): ClickedElementSummary | null` Structured snapshot of the last click before the bug. ```typescript import { extractClickedElement } from "tracebug-sdk"; extractClickedElement(session.events); // { // tag: "button", // text: "Place Order", // selector: "#checkout-form > button.primary", // id: "place-order", // ariaLabel: "Place your order", // testId: "checkout-submit", // page: "/checkout", // } ``` --- ## User Identification ### `TraceBug.setUser(user)` Identify the current user. The user is persisted in localStorage and attached to all sessions. ```typescript TraceBug.setUser({ id: "user_123", email: "dev@example.com", name: "Jane Doe", }); ``` **Fields:** | Field | Type | Required | Description | |-------|------|----------|-------------| | `id` | `string` | Yes | Unique user identifier | | `email` | `string` | No | User email | | `name` | `string` | No | Display name | Custom fields are also supported: `TraceBug.setUser({ id: "123", plan: "pro", role: "admin" })`. ### `TraceBug.getUser(): TraceBugUser | null` Get the identified user, or `null` if not set. ### `TraceBug.clearUser()` Clear the identified user from localStorage. --- ## Bug Flagging ### `TraceBug.markAsBug()` Flag the current session as a bug. Adds an `isBug: true` property to the session in localStorage. ```typescript TraceBug.markAsBug(); ``` ### `TraceBug.getCompactReport(): string | null` Get a 2-3 sentence Slack-friendly summary of the current session. ```typescript const summary = TraceBug.getCompactReport(); // "Bug on /vendor — TypeError: Cannot read 'status' after clicking Edit → selecting Inactive → clicking Update. POST /api/vendor/update returned 500. Chrome 121, Windows 11." ``` --- ## Plugin System Register plugins to filter, transform, or enrich events and reports. ### `TraceBug.use(plugin)` Register a plugin. ```typescript TraceBug.use({ name: "my-plugin", onEvent: (event) => { // Return event to keep, null to filter out if (event.type === "console_log") return null; return event; }, onReport: (report) => { // Enrich the report report.title = `[MyApp] ${report.title}`; return report; }, onExport: (format, data) => { // Transform export output return data; }, }); ``` **Plugin interface:** | Method | Type | Description | |--------|------|-------------| | `name` | `string` | Unique plugin name | | `onEvent` | `(event) => event \| null` | Filter/transform events before storage. Return `null` to drop. | | `onReport` | `(report) => report` | Enrich reports before export | | `onExport` | `(format, data) => data` | Transform export output | | `onInit` | `() => void` | Called when plugin is registered | | `onDestroy` | `() => void` | Called when plugin is removed | ### `TraceBug.removePlugin(name)` Unregister a plugin by name. ### `TraceBug.on(event, callback)` Subscribe to lifecycle hooks. Returns an unsubscribe function. ```typescript const unsub = TraceBug.on("error:captured", (error) => { console.log("Error caught:", error); }); // Later: unsub() to stop listening ``` **Available hooks:** | Hook | Payload | Description | |------|---------|-------------| | `session:start` | `sessionId` | New session started | | `error:captured` | `TraceBugEvent` | Runtime error or unhandled rejection captured | | `screenshot:taken` | `ScreenshotData` | Screenshot captured | | `report:generated` | `BugReport` | Report generated | | `recording:paused` | — | Recording paused | | `recording:resumed` | — | Recording resumed | | `annotate:saved` | `ElementAnnotation` | Element annotation saved | | `draw:saved` | `DrawRegion` | Draw region saved | --- ## CI/CD Helpers Methods for integrating TraceBug into automated test pipelines. ### `TraceBug.getErrorCount(): number` Get the number of errors in the current session. Useful for test assertions. ```typescript // In a Playwright/Cypress test expect(TraceBug.getErrorCount()).toBe(0); ``` ### `TraceBug.exportSessionJSON(): string | null` Export the current session as a formatted JSON string. Useful for CI artifact uploads. ```typescript const json = TraceBug.exportSessionJSON(); // Upload as test artifact on failure ``` --- ## Export & Redaction Helpers (v1.8+) Named exports — no TraceBug instance needed. ### `generatePlaywrightTest(report): string | null` Generate a runnable **failing Playwright spec** that replays the captured session (locator preference: `data-testid` → id → aria-label → role+name → captured CSS selector) and asserts the captured failure is gone — red while the bug exists, green after the fix. Returns `null` when the session has no replayable user actions. Redacted input values become `TODO` placeholders. ### `playwrightTestFilename(report): string` The suggested `.spec.ts` filename for the generated test. The spec is also embedded in the `.html` export and served by the MCP `get_playwright_test` tool. ### `exportSessionAsZip(session, report, options?)` / `buildZipBlob(entries): Promise` The self-contained replay `.html` wrapped in a `.zip` — GitHub issues accept `.zip` attachments by drag-and-drop but reject bare `.html`. Zero-dependency writer: `CompressionStream("deflate-raw")` when available, STORE fallback. ### `summarizeRedactions(report): RedactionSummary` Count the `[REDACTED]` markers in a built report by category — tokens, URL params, form fields, storage values. ### `formatRedactionSummary(summary): string | null` Render the summary line shown in the export modal and the exported Info tab — `"4 sensitive values auto-masked (2 tokens, 1 URL param, 1 form field)"`. Returns `null` when nothing was masked. ### `setRedactRules(rules: RedactRules)` Swap the app-specific redaction rules (`{ fields?, patterns? }`) at runtime — same shape as the `redact` init option ([configuration.md](configuration.md#redact)). ### `runRecordCountdown(seconds): Promise` Fullscreen 3-2-1 countdown overlay; resolves when it hits zero. Used by `prepareRecording({ delaySec })`. ### `startBlurThenRecord({ onStart, onCancel? })` Arm the element-level blur tool with the floating "● Start recording / Undo / Cancel" bar; `onStart` fires with the blurs still applied so the recording captures them from its first frame. Cancel unblurs everything. ### `isBlurModeActive(): boolean` / `removeAllBlurBoxes()` Whether the blur picker is currently active / unblur every element (placed blurs otherwise persist until the recording stops). --- ## Standalone Exports These functions can be imported directly without the TraceBug instance: ```typescript import { getAllSessions, clearAllSessions, deleteSession, generateReproSteps, captureEnvironment, buildReport, // Debugging Assistant (v1.3+) generateRootCauseHint, formatRootCauseLine, generateSmartSummary, generateSessionSteps, extractClickedElement, getNetworkFailures, // Report formatters generateGitHubIssue, generateJiraTicket, generatePdfReport, downloadPdfAsHtml, generateBugTitle, generateFlowSummary, buildTimeline, formatTimelineText, captureScreenshot, captureRegionScreenshot, getScreenshots, downloadAllScreenshots, startVoiceRecording, stopVoiceRecording, isVoiceSupported, isVoiceRecording, getVoiceTranscripts, clearVoiceTranscripts, // Failing-test generator (v1.8+) generatePlaywrightTest, playwrightTestFilename, // Zip export (v1.8+) exportSessionAsZip, buildZipBlob, // Redaction (v1.8+) summarizeRedactions, formatRedactionSummary, setRedactRules, // Style evidence (v1.8+) captureStyleEvidence, formatStyleSummary, contrastRatio, cssColorToHex, // Pre-recording + blur (v1.8+) runRecordCountdown, startBlurThenRecord, isBlurModeActive, removeAllBlurBoxes, } from "tracebug-sdk"; ``` --- ## Types All types are exported from the package: ```typescript import type { TraceBugConfig, TraceBugEvent, TraceBugUser, StoredSession, BugReport, Annotation, ScreenshotData, EnvironmentInfo, ElementAnnotation, DrawRegion, UIAnnotationReport, AnnotationIntent, VoiceTranscript, JiraTicket, TraceBugPlugin, // Debugging Assistant (v1.3+) RootCauseHint, ClickedElementSummary, NetworkErrorEntry, NetworkFailure, // v1.8+ StyleEvidence, RedactRules, RedactionSummary, } from "tracebug-sdk"; ``` ### `BugReport` (updated in v1.3) ```typescript interface BugReport { title: string; /** One-sentence TL;DR — generated via generateSmartSummary() */ summary: string; /** 🔍 Possible Cause hint — generated via generateRootCauseHint() */ rootCause: RootCauseHint; /** Last ~10 readable user actions, FIFO */ sessionSteps: string[]; /** Structured info about the last click before the bug */ clickedElement: ClickedElementSummary | null; steps: string; environment: EnvironmentInfo; consoleErrors: { message: string; stack?: string; timestamp: number }[]; /** networkErrors entries now include an optional response snippet */ networkErrors: NetworkErrorEntry[]; annotations: Annotation[]; screenshots: ScreenshotData[]; timeline: TimelineEntry[]; voiceTranscripts: VoiceTranscriptData[]; session: StoredSession; generatedAt: number; } ``` ### `RootCauseHint` ```typescript interface RootCauseHint { hint: string; confidence: "high" | "medium" | "low"; } ``` ### `NetworkErrorEntry` ```typescript interface NetworkErrorEntry { method: string; url: string; status: number; duration: number; timestamp: number; /** First 200 chars of the response body (failures only). May be omitted. */ response?: string; } ``` ### `NetworkFailure` In-memory ring-buffer entry returned by `getNetworkFailures()`. ```typescript interface NetworkFailure { url: string; method: string; status: number; response: string; timestamp: number; } ``` ### `ClickedElementSummary` ```typescript interface ClickedElementSummary { tag: string; text: string; selector?: string; id?: string; ariaLabel?: string; testId?: string; page: string; } ``` --- ## Sentry Mode (Rolling Video Buffer) Arm a screen-share once, file multiple bug tickets from the same recording. Inspired by NVIDIA Shadowplay / OBS replay buffer. ### `TraceBug.prepareRecording(options?)` Pre-roll flow for `startVideoRecording()`: optionally arm the element-level **blur tool** first (a floating "● Start recording / Undo / Cancel" bar — the blurs are captured from the very first frame), then an optional on-page 3-2-1 countdown, then record. This is what the extension popup's **⚙ Record options** panel calls. ```typescript TraceBug.prepareRecording({ blurFirst: true, // click elements to blur/unblur before capture starts delaySec: 3, // on-page countdown before recording rolls (0 = none) surfaceMode: "tab", // "tab" (current tab) | "desktop" (window/screen picker) withMicrophone: false, }); ``` ### `TraceBug.startVideoRecording(options?): Promise` Open the OS screen-picker and start recording. Resolves to `true` on success, `false` if the user cancelled or the browser refused. ```typescript const ok = await TraceBug.startVideoRecording({ mode: "rolling", // default; multiple captures per session withMicrophone: false, // mux mic audio for narration (asks for mic permission) onStatus: (status, msg) => console.log(status, msg), }); ``` **Options:** | Option | Type | Default | Description | |---|---|---|---| | `mode` | `"rolling" \| "standard"` | `"rolling"` | `rolling` = capture-and-keep-recording. `standard` = classic record-then-stop. | | `withMicrophone` | `boolean` | `false` | Mux microphone audio for narration. Requires user permission. | | `onStatus` | `(status, message?) => void` | — | Status callback. `status` is `"recording" \| "stopped" \| "error"`. | When recording starts, the floating HUD pill appears with a pulsing red dot, elapsed timer, capture counter, comment input, 📸 Capture button (rolling mode only), and ⏹ Stop. ### `TraceBug.captureRollingBuffer(): Promise` Snapshot the in-progress rolling recording into a finished `VideoRecording`. The screen-share keeps running so the same arm session can produce more tickets. Resolves to `null` if no rolling recording is active. The Quick Bug ticket modal opens automatically on success. The HUD flashes purple to confirm. Comments reset for the next bug — each ticket gets its own set of timestamped notes. ### `TraceBug.stopVideoRecording(): Promise` Stop the screen-share, hide the HUD. Smart behavior: - If captures were already taken this session, stops silently (those tickets are already filed). - If no captures were taken, opens the Quick Bug modal with the full recording — preserves the simple one-shot flow. ### `TraceBug.isVideoRecording(): boolean` True while a recording is in progress. ### `TraceBug.isRollingMode(): boolean` True while the active recording is in rolling/Sentry mode. ### `TraceBug.getCaptureCount(): number` Number of captures taken from the current rolling session. ### `TraceBug.getLastVideoRecording(): VideoRecording | null` Get the most recently captured recording. Lives in memory only — `null` after page reload. ### `VideoRecording` type ```typescript interface VideoRecording { url: string; // Blob URL (in-memory, valid until clearVideoRecording or reload) blob: Blob; // Underlying webm Blob durationMs: number; mimeType: string; // typically "video/webm;codecs=vp9,opus" sizeBytes: number; comments: VideoComment[]; startedAt: number; // ms timestamp when recording started } interface VideoComment { offsetMs: number; // ms since recording start text: string; } ``` ### Auto-capture on error When an unhandled error fires *and* a rolling session is armed, the existing error toast offers **"Capture with video"** instead of "Capture bug." One click captures the buffer and opens the ticket modal. No need to remember to record before the bug happens. --- ## Auto-Scanner Six in-browser detectors run in parallel; one failure doesn't block the others. ### `TraceBug.scanPage(): Promise` ```typescript interface ScanResult { issues: Issue[]; durationMs: number; scannedAt: number; } ``` Runs all detectors and returns the issues. Concurrent calls are coalesced — a second `scanPage()` while one is in-flight returns the same promise. ```typescript const { issues, durationMs } = await TraceBug.scanPage(); console.log(`${issues.length} issues found in ${durationMs}ms`); ``` ### `TraceBug.showIssuesPanel(options?): Promise` Opens the issues modal. Runs a fresh scan first by default; pass `{ rescan: false }` to use cached results. ### `TraceBug.getIssues(options?): Issue[]` Snapshot of current issues. Filters out dismissed by default; pass `{ includeDismissed: true }` to include all. ### `TraceBug.dismissIssue(id) / undismissIssue(id) / clearIssues()` Per-session dismissal. Returns `true` if the issue was found. `clearIssues()` wipes all results. ### `TraceBug.getIssue(id): Issue | null` Lookup helper. ### `TraceBug.getIssueCounts(): Record` Severity-bucketed counts of non-dismissed issues — useful for badges and CI thresholds. ### `Issue` type ```typescript type IssueDetector = | "axe-a11y" | "broken-image" | "mixed-content" | "console-error" | "slow-api" | "failed-request"; type IssueSeverity = "critical" | "serious" | "moderate" | "minor"; interface Issue { id: string; detector: IssueDetector; severity: IssueSeverity; title: string; // < 80 chars headline description: string; // longer plain-English explanation selector?: string; // CSS selector if anchored to DOM url?: string; // URL if anchored to a request/resource helpUrl?: string; // axe-core deque docs link, when applicable page: string; detectedAt: number; dismissed?: boolean; // session-only } ``` ### Detector summary | Detector | What it catches | Notes | |---|---|---| | **axe-a11y** | WCAG 2.0/2.1 A+AA violations | Lazy-loads axe-core (~1.4 MB) on first scan; multi-element violations roll up with `(+ N more)` suffix | | **broken-image** | `` where `naturalWidth === 0 && complete === true` | Skips still-loading images | | **mixed-content** | `http://` resources on HTTPS | Covers `img`, `script`, `iframe`, `link[rel=stylesheet|preload|prefetch|manifest|icon]`, `audio`, `video`, `source`, `embed`, `object` | | **console-error** | Errors / unhandled rejections in the session, deduped by message | Reads from existing event buffer — no new tracking | | **failed-request** | 4xx/5xx/network-error API calls | Pulls response body snippets from the network-failure ring buffer | | **slow-api** | Successful API calls over 2 s | Threshold hard-coded at 2000 ms; > 5000 ms bumped to "serious" | --- ## Cut from v1.0 default UI (still callable) These features were removed from the default toolbar in v1.0 to reduce noise. The source files still ship in the bundle and the public API methods are unchanged — power users can wire them into custom workflows. | Cut feature | API entry point | |---|---| | Element Annotate Mode | `TraceBug.activateAnnotateMode()`, `deactivateAnnotateMode()`, `isAnnotateModeActive()` | | Draw Mode | `TraceBug.activateDrawMode()`, `deactivateDrawMode()`, `isDrawModeActive()` | | Annotation list / export | `getAnnotationReport()`, `exportAnnotationsJSON()`, `exportAnnotationsMarkdown()`, `copyAnnotationsToClipboard("json"\|"markdown")`, `clearAnnotations()` | | PDF report | `TraceBug.downloadPdf()` (free shows upgrade modal) | | First-run attention cue | A one-time logo pulse on first mount (`src/onboarding.ts`); the original 4-step tooltip tour was removed in 1.7.0. Not a public export | | Plain text export | Build manually from `TraceBug.generateReport()` | The `shortcuts.annotate` and `shortcuts.draw` config keys are still typed in `TraceBugConfig` for backwards compatibility but are no-ops in v1.0.