# @bugmail-js/sdk — Browser JavaScript SDK

The BugMail browser SDK captures unhandled errors, unhandled promise rejections, and user breadcrumbs and sends them to your BugMail backend. Optional plugins add more features (e.g., performance metrics, network breadcrumbs).

This README provides a fast, friendly guide so users can get started quickly via npm or CDN and understand common integration points.

Installation

```bash
# Using npm
npm install @bugmail-js/sdk

# Using pnpm
pnpm add @bugmail-js/sdk
```

CDN

```html
<!-- jsDelivr (recommended) -->
<script src="https://cdn.jsdelivr.net/npm/@bugmail-js/sdk@0.1.10/dist/bugmail.umd.js"></script>
<!-- or unpkg -->
<script src="https://unpkg.com/@bugmail-js/sdk@0.1.10/dist/bugmail.umd.js"></script>
```

Quick start (browser)

```javascript
// Option 1: Default import (recommended for compatibility with examples)
import BugMail from '@bugmail-js/sdk';
const bugmail = new BugMail({ 
  apiKey: 'YOUR_PROJECT_API_KEY',
  endpoint: '<your-bugmail-endpoint>'
});

// Option 2: Named import
import { BugMailClient } from '@bugmail-js/sdk';
const bugmail2 = new BugMailClient({ 
  apiKey: 'YOUR_PROJECT_API_KEY',
  endpoint: '<your-bugmail-endpoint>'
});

// Note on casing: the exported class is `BugMailClient` (camel-case). Import names are case-sensitive.

// API key is required. If not provided, the SDK will warn and will not auto-initialize.

// Optional: set user context
bugmail.setUser({ id: '123', email: 'user@example.com' });

// Manual capture
try {
  throw new Error('Manual test');
} catch (err) {
  bugmail.captureError(err, { component: 'Checkout' });
}
```

Key API

- `new BugMail(config)` - initialize the SDK
  - `apiKey` (required) — project API key (sent as `x-bugmail-api-key` header)
  - `endpoint` — BugMail backend URL (e.g., `<your-bugmail-endpoint>`)
  - `environment`, `release`, `sampleRate`, `maxBreadcrumbs`

- `captureError(error, context)` — send an error manually

- `setUser(user)` — attach user metadata: { id, email, name }

- `setContext(context)` — attach custom context data

- `addBreadcrumb(breadcrumb)` — programmatically add breadcrumb

Framework integrations (quick)

Note: The React/Vue packages are experimental and may not yet be published to npm. The snippets below show intended usage once available. Until then, you can integrate the browser SDK directly in those frameworks.

React

```jsx
import { BugMailProvider, ErrorBoundary } from '@bugmail-js/react';

function App() {
  return (
    <BugMailProvider apiKey="YOUR_API_KEY">
      <ErrorBoundary fallback={<div>Something broke</div>}>
        <YourApp />
      </ErrorBoundary>
    </BugMailProvider>
  );
}
```

Vue

```javascript
import { createApp } from 'vue';
import { bugmailPlugin } from '@bugmail-js/vue';
import App from './App.vue';

const app = createApp(App);
app.use(bugmailPlugin, { apiKey: 'YOUR_API_KEY' });
app.mount('#app');
```

Examples

- See `bugmail-sdk/examples/browser-demo` for a runnable demo.
- Server-side ingestion examples use the Node SDK (`@bugmail-js/node`) in `examples/express-server`.

Troubleshooting

- If you see no reports: check `apiKey`, `endpoint`, and browser console for network errors.
- CSP: ensure your CSP allows requests to your BugMail API endpoint.

Contributing and tests

- This package builds from `src/` and outputs `dist/` via Rollup. Tests use Jest.

License

MIT
# BugMail SDK

JavaScript error tracking SDK for the BugMail platform.

## Features

- Automatic error capturing for unhandled exceptions
- Promise rejection tracking
- Detailed environment information collection
- User context support
- Offline support with automatic retry
- Framework-specific integrations
- Breadcrumb tracking for debugging

## Installation

### NPM/Yarn

```bash
# Using npm
npm install @bugmail-js/sdk

# Using yarn
yarn add @bugmail-js/sdk
```

### CDN

```html
<!-- Option A: jsDelivr -->
<script src="https://cdn.jsdelivr.net/npm/@bugmail-js/sdk@0.1.10/dist/bugmail.umd.js"></script>

<!-- Option B: unpkg -->
<script src="https://unpkg.com/@bugmail-js/sdk@0.1.10/dist/bugmail.umd.js"></script>
```

## Quick Start

### Basic Usage

```javascript
// Import the SDK
import BugMail from '@bugmail-js/sdk';

// Initialize with your API key
const bugmail = new BugMail({
  apiKey: 'YOUR_PROJECT_API_KEY',
  endpoint: '<your-bugmail-endpoint>',
  environment: 'production' // or 'development', 'staging' for your app environment
});

// Errors will now be automatically captured
```

### CDN Usage

```html
<!-- Define config BEFORE including the SDK to enable auto-initialize -->
<script>
  window.BUGMAIL_CONFIG = {
    apiKey: 'YOUR_PROJECT_API_KEY',
    endpoint: '<your-bugmail-endpoint>',
    environment: 'production',
    enableAIAnalysis: true
  };
  // The SDK auto-initializes only if BUGMAIL_CONFIG exists before the script loads
</script>
<script src="https://cdn.jsdelivr.net/npm/@bugmail-js/sdk@0.1.10/dist/bugmail.umd.js"></script>

<!-- Alternatively, initialize manually AFTER the script: -->
<script>
  window.bugmail = new BugMail.BugMailClient({
    apiKey: 'YOUR_PROJECT_API_KEY',
    endpoint: '<your-bugmail-endpoint>',
    environment: 'production'
  });
</script>
```

## Manual Error Capturing

```javascript
try {
  // Your code that might throw an error
  doSomethingRisky();
} catch (error) {
  // Manually capture the error
  bugmail.captureError(error, {
    // Additional context
    component: 'PaymentForm',
    action: 'processPayment'
  });
}
```

## Setting User Context

```javascript
// Set user information for better error context
bugmail.setUser({
  id: '123',
  email: 'user@example.com',
  name: 'John Doe',
  role: 'admin'
});
```

## Adding Custom Context

```javascript
// Add any custom data that might help with debugging
bugmail.setContext({
  theme: 'dark',
  plan: 'premium',
  featureFlags: {
    newDashboard: true,
    betaFeatures: false
  }
});
```

## Breadcrumbs

Breadcrumbs help trace user actions leading up to an error:

```javascript
// Add breadcrumb when user performs important action
bugmail.addBreadcrumb({
  type: 'user',
  message: 'User clicked checkout button',
  level: 'info',
  data: { cartTotal: '$45.67', itemCount: 3 }
});
```

## Framework Integrations

### React

```jsx
import { BugMailProvider, useBugMail, ErrorBoundary } from '@bugmail-js/react';

function App() {
  return (
    <BugMailProvider apiKey="YOUR_API_KEY">
      <ErrorBoundary fallback={<ErrorPage />}>
        <YourApp />
      </ErrorBoundary>
    </BugMailProvider>
  );
}

// In a component
function Component() {
  const bugmail = useBugMail();
  
  const handleClick = () => {
    bugmail.addBreadcrumb({
      type: 'user',
      message: 'Button clicked'
    });
  };
  
  return <button onClick={handleClick}>Click me</button>;
}
```

### Vue.js

```javascript
import { createApp } from 'vue';
import { bugmailPlugin } from '@bugmail-js/vue';
import App from './App.vue';

const app = createApp(App);
app.use(bugmailPlugin, {
  apiKey: 'YOUR_API_KEY'
});
app.mount('#app');
```

## Configuration Options

```javascript
const bugmail = new BugMail({
  // Required
  apiKey: 'YOUR_PROJECT_API_KEY',
  endpoint: '<your-bugmail-endpoint>',
  
  // Optional
  environment: 'production', // 'development', 'staging', 'production'
  release: '1.2.3', // Application version
  captureUnhandledErrors: true, // Capture window.onerror
  captureUnhandledRejections: true, // Capture unhandled promises
  captureConsoleErrors: true, // Capture console.error calls
  maxBreadcrumbs: 100, // Maximum breadcrumbs to store
  sampleRate: 1.0, // 1.0 = 100% of errors, 0.5 = 50% of errors
  enableAIAnalysis: true // Enable AI-powered error analysis
});
```

## Backend setup & Auth

The Browser SDK sends error reports to the BugMail backend using your API key for authentication.

**Authentication:**
- Auth header: `x-bugmail-api-key: <YOUR_PROJECT_API_KEY>`

**Server-side behavior:**
- Validates API key and maps it to your project
- Groups errors and stores breadcrumbs
- Enforces plan limits and rate limits (100/minute)
- Optionally runs AI analysis for error groups
- Returns `201` with `{ status: "success", error_id: "..." }` on success

**Common responses:**
- `400` missing API key or malformed payload
- `401/403` invalid or inactive API key
- `402/403` plan not active or trial expired
- `429` quota exceeded
- `500` internal error

## Error Filtering

The BugMail SDK automatically filters out its own internal errors to prevent infinite loops and reduce noise in your error dashboard. This means:

- SDK network errors are logged but not reported
- API validation failures (invalid API key, etc.) don't create loops
- Console messages from the SDK are not captured

### What Gets Filtered?

The SDK filters errors that:
- Originate from SDK code (stack trace contains `@bugmail-js`, `bugmail-sdk`, etc.)
- Are SDK console messages (start with `[BugMail`, `BugMail Network`, etc.)
- Occur during SDK internal operations

### Debug Mode

Enable debug mode to see what errors are being filtered and why:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  debug: true  // See filtering decisions in console
});
```

With debug mode enabled, you'll see messages like:
```
[BugMail Filter] Filtered: SDK pattern in message
[BugMail Filter] Filtered: SDK pattern in stack trace
```

### Common Scenarios

**Invalid API Key:**
```
[BugMail Network] Failed to send error: { status: 401, body: { detail: "Invalid API key" } }
```
This error is logged once and NOT captured (prevents infinite loop).

**Network Error:**
```
[BugMail Network] Failed to send error: { status: 'network_error', message: 'Failed to fetch' }
```
This error is logged and NOT captured (temporary network issues shouldn't flood your dashboard).

**Your Application Error:**
```
TypeError: Cannot read property 'foo' of undefined
    at MyComponent.render (app.js:123)
```
This error IS captured and sent to your dashboard (it's from your code, not the SDK).

For detailed information about error filtering, see [Error Filtering Documentation](./docs/ERROR_FILTERING.md).

## Troubleshooting

### SDK not capturing errors

- Ensure your API key is correct
- Check that your application has connectivity to the BugMail API
- Verify that you're not using a Content Security Policy that blocks the API
- Enable debug mode to see detailed logging

### SDK errors not appearing in dashboard

This is expected! The SDK filters out its own internal errors to prevent infinite loops. If you see errors in the console with `[BugMail]` or `[BugMail Network]` prefixes, these are SDK errors that are intentionally not sent to your dashboard.

To debug SDK issues:
1. Enable debug mode: `debug: true` in config
2. Check browser console for `[BugMail]` prefixed messages
3. Check Network tab for failed requests
4. Verify your API key is correct and active

### Too many errors reported

- Adjust the `sampleRate` setting to capture fewer errors
- Add custom logic to filter out repetitive errors using the `beforeSend` hook

## Browser Support

The BugMail SDK supports all modern browsers:

- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 16+

For IE11 support, you'll need to include appropriate polyfills.

## Documentation

### Guides

- [Error Filtering Guide](./docs/ERROR_FILTERING.md) - Detailed explanation of how the SDK filters its own errors
- [Error Filtering Quick Reference](./docs/ERROR_FILTERING_QUICK_REFERENCE.md) - Quick reference for error filtering
- [FAQ](./docs/FAQ.md) - Frequently asked questions

### Examples

- See `bugmail-sdk/examples/browser-demo` for a runnable demo
- See `bugmail-sdk/examples/express-server` for server-side integration

## License

MIT
