### Initialize Hawk Catcher in JavaScript Source: https://context7.com/context7/hawk_so/llms.txt This snippet shows how to install and initialize the Hawk Catcher library in a JavaScript application. It covers setting up the catcher with an integration token, configuring optional data filtering with `beforeSend`, and providing global context and user information. The example also demonstrates automatic error catching and manual error reporting with custom context, as well as sending custom messages. ```javascript // Install via npm // npm install @hawk.so/javascript import HawkCatcher from '@hawk.so/javascript'; // Initialize with configuration const hawk = new HawkCatcher({ token: 'eyJpbnRlZ3JhdGlvbklkIjoiMDQ0NmVlZDctYmYyNC00YmE3LTlmZDktYjIyMTJkM2NmYzg5Iiwic2VjcmV0IjoiYjAxMDlkYjktODgzNi00ZDMzLWJjNjktY2JmYzY1MWMzZWMzIn0=', // Optional: Filter sensitive data before sending beforeSend(event) { if (event.user) { delete event.user.email; delete event.user.password; } if (event.context?.creditCard) { delete event.context.creditCard; } return event; }, // Global context sent with every event context: { environment: process.env.NODE_ENV, appVersion: '1.2.3', serverRegion: 'us-east-1' }, // User information for tracking affected users user: { id: 'user-12345', name: 'Jane Smith', url: 'https://example.com/users/12345' } }); // Automatic error catching (no code needed - happens automatically) // Manual error reporting try { riskyOperation(); } catch (error) { hawk.send(error, { context: { operation: 'riskyOperation', params: { id: 123 } } }); } // Send custom message hawk.send('Payment processing timeout', { level: 'warning', user: { id: 'user-999' } }); ``` -------------------------------- ### Hawk Catcher JavaScript Initialization Source: https://context7.com/context7/hawk_so/llms.txt Instructions on how to install and initialize the Hawk Catcher library in a JavaScript application to automatically capture and report errors. ```APIDOC ## Hawk Catcher JavaScript ### Description Install and configure the Hawk Catcher library to automatically capture unhandled errors with custom context. The library also allows for manual error reporting. ### Installation ```bash npm install @hawk.so/javascript ``` ### Initialization ```javascript import HawkCatcher from '@hawk.so/javascript'; const hawk = new HawkCatcher({ token: 'YOUR_INTEGRATION_TOKEN', // Optional: Filter sensitive data before sending beforeSend(event) { // Example: Remove sensitive user data if (event.user) { delete event.user.email; delete event.user.password; } // Example: Remove sensitive context data if (event.context?.creditCard) { delete event.context.creditCard; } return event; }, // Global context sent with every event context: { environment: process.env.NODE_ENV, appVersion: '1.2.3', serverRegion: 'us-east-1' }, // User information for tracking affected users user: { id: 'user-12345', name: 'Jane Smith', url: 'https://example.com/users/12345' } }); // Automatic error catching (no code needed - happens automatically) // Manual error reporting try { riskyOperation(); } catch (error) { hawk.send(error, { context: { operation: 'riskyOperation', params: { id: 123 } } }); } // Send custom message hawk.send('Payment processing timeout', { level: 'warning', user: { id: 'user-999' } }); ``` ### Configuration Options - **token** (string) - Required - Your Hawk.so integration token. - **beforeSend** (function) - Optional - A function that takes the event object and returns it (or a modified version) before sending. Useful for filtering sensitive data. - **context** (object) - Optional - Global context information to be sent with every captured event. - **user** (object) - Optional - Information about the current user for tracking purposes. ``` -------------------------------- ### Configure Hawk Notification Rule for Slack Source: https://context7.com/context7/hawk_so/llms.txt Sets up a notification rule to send error alerts to a Slack channel via an incoming webhook. Requires a Slack webhook URL and specifies the notification strategy and filters for events. The example also shows how to trigger a test notification. ```javascript // Step 1: Set up Slack Webhook in Slack workspace // 1. Go to https://api.slack.com/apps // 2. Create new app -> From scratch // 3. Enable Incoming Webhooks // 4. Add New Webhook to Workspace -> Select channel // 5. Copy webhook URL: https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX // Step 2: Configure in Hawk UI (Project Settings -> Notifications -> Add Rule) // Or via API: const notificationRule = { channel: 'slack', endpoint: 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXX', // Notification strategy strategy: 'only_new_events', // or 'all_events' // Filter events by keywords filters: { include: ['payment', 'authentication', 'database'], exclude: ['test', 'staging'] }, enabled: true }; // Step 3: Test notification by triggering an error hawk.send('Payment gateway connection failed', { context: { gateway: 'stripe', amount: 99.99 } }); // Telegram setup: // 1. Add @hawkso_bot to your chat // 2. Send /notify command // 3. Copy endpoint URL and use in notification rule // Email setup: const emailRule = { channel: 'email', endpoint: 'team@example.com', strategy: 'only_new_events', filters: { include: ['critical', 'fatal'] } }; ``` -------------------------------- ### Send Commits to Hawk via Shell Script Source: https://docs.hawk.so/releases This example demonstrates how to send Git commit information associated with a specific release to Hawk using a shell script. The script requires the release name and the integration token. This is useful for associating commits with releases for error tracking. ```bash $ ./commits.sh --release="Version 2.0.1" --token=eyJ...integrationToken... ``` -------------------------------- ### Hawk Catcher Message Format Example (JSON) Source: https://docs.hawk.so/event-format This JSON object represents the structure of a message that the Hawk catcher expects to receive. It includes fields for authentication (token), event categorization (catcherType), detailed event information within the payload (title, type, description, level, backtrace), and optional user and release identifiers. ```json { "token": "AAAABB...wER232r2wer", "catcherType": "error/php", "payload": { "title": "Field `blocks` is missing", "type": "ParseError", "description": "evaluating 't.children.length'", "level": 16, "backtrace": [ { "file": "/var/www/codex/vendor/codex-team/editor.js/EditorJS/EditorJS.php", "line": 77, "column": 12, "function": null, "arguments": null, "sourceCode": [ { "line": 76, "content": " if (!isset($data['blocks'])) {" }, { "line": 77, "content": " throw new EditorJSException('Field `blocks` is missing');" }, { "line": 78, "content": " }" } ] }, { "file": "/var/www/codex/application/classes/Controller/Articles/Index.php", "calledLine": "191", "sourceCode": [ { "line": "190", "content": " {" }, { "line": "191", "content": " $editor = new EditorJS($content, Model_Article::getEditorConfig());" }, { "line": "192", "content": " $blocks = $editor->getBlocks();" } ] } ], "addons": {}, "release": "", "user": { "id": "1233", "name": "Vitaly Guryn", "url": "https://codex.so/user/123", "photo": "https://leonardo.osnova.io/66b0786b-c5f7-ecde-6fa1-60c8462fab42/-/scale_crop/60x60/center/" }, "context": {} } } ``` -------------------------------- ### Send Error Event to Hawk Collector using cURL Source: https://context7.com/context7/hawk_so/llms.txt This snippet demonstrates how to send error events to the Hawk Collector API using cURL. It includes decoding an integration token and constructing a POST request with a detailed event payload. The payload contains information about the error, release, user, and context. It also shows an example of establishing a WebSocket connection for real-time event streaming. ```bash # Decode your integration token to get the integrationId cat integration_token.txt | base64 -d # Send POST request to collector endpoint curl -X POST https://0446eed7-bf24-4ba7-9fd9-b2212d3cfc89.k1.hawk.so:433 \ -H "Content-Type: application/json" \ -d '{ \ "token": "AAAABB...wER232r2wer", \ "catcherType": "error/javascript", \ "payload": { \ "title": "TypeError: Cannot read property length", \ "type": "TypeError", \ "description": "evaluating t.children.length", \ "level": 16, \ "backtrace": [ \ { \ "file": "/src/components/Editor.js", \ "line": 145, \ "column": 12, \ "function": "renderBlocks", \ "sourceCode": [ \ {"line": 144, "content": "function renderBlocks(data) {"}, \ {"line": 145, "content": " return data.children.length > 0;"}, \ {"line": 146, "content": "}"} \ ] \ } \ ], \ "release": "1.2.3", \ "user": { \ "id": "user-8821", \ "name": "John Doe", \ "email": "john@example.com" \ }, \ "context": { \ "userId": "8821", \ "sessionId": "abc-123", \ "environment": "production" \ }, \ "addons": { \ "browser": "Chrome 96.0", \ "os": "macOS 12.1" \ } \ } \ }' # WebSocket connection for real-time event streaming wscat -c wss://0446eed7-bf24-4ba7-9fd9-b2212d3cfc89.k1.hawk.so:433/ws ``` -------------------------------- ### Filter Sensitive Data with beforeSend Hook (JavaScript) Source: https://docs.hawk.so/sensitive-data-filtering This JavaScript code snippet demonstrates how to use the `beforeSend` hook in the HawkCatcher configuration to filter sensitive data from events. The hook receives the event object and allows modification before it's sent. It shows an example of removing the user's email address if it exists. This method is effective for client-side filtering. ```javascript const hawk = new HawkCatcher({ token: 'INTEGRATION_TOKEN', beforeSend(event) { // Modify the event here if (event.user) { // Don't send user's email address delete event.user.email; } return event; }, }); ``` -------------------------------- ### Create Workspace and Project in Hawk.so (JavaScript) Source: https://context7.com/context7/hawk_so/llms.txt This snippet demonstrates how to define the structure for creating a workspace and a project within Hawk.so using JavaScript. It includes sample data structures for workspace and project configurations and shows how to initialize the HawkCatcher with an integration token and send test events. ```javascript const workspace = { name: 'Acme Corporation', description: 'Production applications', billing: { plan: 'team', members: ['user1@acme.com', 'user2@acme.com'] } }; const project = { name: 'E-commerce Platform', workspace: 'acme-corporation', logo: 'https://example.com/logo.png', settings: { retention: 30, // days integrations: [] } }; const integrationToken = 'eyJpbnRlZ3JhdGlvbklkIjoiMDQ0NmVlZDctYmYyNC00YmE3LTlmZDktYjIyMTJkM2NmYzg5Iiwic2VjcmV0IjoiYjAxMDlkYjktODgzNi00ZDMzLWJjNjktY2JmYzY1MWMzZWMzIn0='; const decoded = { integrationId: '0446eed7-bf24-4ba7-9fd9-b2212d3cfc89', secret: 'b0109db9-8836-4d33-bc69-cbfc651c3ec3' }; // npm install @hawk.so/javascript import HawkCatcher from '@hawk.so/javascript'; const hawk = new HawkCatcher({ token: integrationToken }); // Test integration hawk.send('Test event from E-commerce Platform'); ``` -------------------------------- ### Python: Initialize HawkCatcher and Catch Errors Source: https://context7.com/context7/hawk_so/llms.txt Demonstrates how to initialize the HawkCatcher client in Python, set context, and automatically catch errors from function calls. It also shows how to manually send exceptions with additional context. ```python from hawk_catcher import HawkCatcher hawk = HawkCatcher( token='eyJpbnRlZ3JhdGlvbklkIjoiMDQ0NmVlZDctYmYyNC00YmE3LTlmZDktYjIyMTJkM2NmYzg5Iiwic2VjcmV0IjoiYjAxMDlkYjktODgzNi00ZDMzLWJjNjktY2JmYzY1MWMzZWMzIn0=', context={'app': 'data-processor', 'env': 'production'} ) def process_data(data): result = data['items'][0] # May raise KeyError return result process_data({}) def risky_operation(): pass try: risky_operation() except ValueError as e: hawk.send(e, context={'operation': 'data_validation'}, user={'id': 'user-456', 'name': 'Bob'}) ``` -------------------------------- ### JavaScript: Migrate from Sentry to Hawk SDK Source: https://context7.com/context7/hawk_so/llms.txt Provides guidance on migrating from the Sentry SDK to the HawkCatcher JavaScript SDK. It shows how to update the DSN to the Hawk integration token and adapt error capturing, manual messages, and user context settings. ```javascript // Before (Sentry): import * as Sentry from '@sentry/browser'; Sentry.init({ dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0', environment: 'production', release: '1.0.0', beforeSend(event, hint) { if (event.user) { delete event.user.email; } return event; } }); // After (Hawk) - Option 1: Minimal change import * as Sentry from '@sentry/browser'; Sentry.init({ // Replace Sentry DSN with Hawk's Integration Token dsn: 'https://0446eed7-bf24-4ba7-9fd9-b2212d3cfc89.k1.hawk.so:433', environment: 'production', release: '1.0.0', beforeSend(event, hint) { if (event.user) { delete event.user.email; } return event; } }); // After (Hawk) - Option 2: Full migration to native Hawk SDK import HawkCatcher from '@hawk.so/javascript'; const hawk = new HawkCatcher({ token: 'eyJpbnRlZ3JhdGlvbklkIjoiMDQ0NmVlZDctYmYyNC00YmE3LTlmZDktYjIyMTJkM2NmYzg5Iiwic2VjcmV0IjoiYjAxMDlkYjktODgzNi00ZDMzLWJjNjktY2JmYzY1MWMzZWMzIn0=', release: '1.0.0', context: { environment: 'production' }, beforeSend(event) { if (event.user) { delete event.user.email; } return event; } }); // Error capturing works the same way try { problematicCode(); } catch (error) { // Sentry: Sentry.captureException(error); // Hawk: hawk.send(error); } // Manual messages // Sentry: Sentry.captureMessage('Something went wrong'); // Hawk: hawk.send('Something went wrong'); // Set user context // Sentry: Sentry.setUser({ id: '123', username: 'john' }); // Hawk: (set during initialization or with each event) hawk.send(error, { user: { id: '123', name: 'john' } }); ``` -------------------------------- ### Configure Hawk Webpack Plugin for Source Maps Source: https://docs.hawk.so/releases This configuration sets up the Hawk Webpack plugin to automatically send JavaScript source maps and recent Git commits to Hawk. Ensure you replace the placeholder with your project's Integration Token. This helps in associating errors with specific code versions. ```javascript const HawkWebpackPlugin = require('@hawk.so/webpack-plugin'); module.exports = { // ... other webpack options plugins: [ new HawkWebpackPlugin({ integrationToken: '' // Your project's Integration Token }) ], devtool: 'hidden-source-map', } ``` -------------------------------- ### Send Release Commits using Shell Script Source: https://context7.com/context7/hawk_so/llms.txt Uploads git commit history for a specific release to enable suspected commit identification in error reports. This script requires `curl` and `chmod` to download and execute. It takes a release tag and an integration token as arguments. ```bash # Download and run the commits script curl https://raw.githubusercontent.com/codex-team/hawk.releases/main/scripts/commits.sh -O chmod +x ./commits.sh # Send commits for a specific release ./commits.sh --release="v2.1.0" --token="eyJpbnRlZ3JhdGlvbklkIjoiMDQ0NmVlZDctYmYyNC00YmE3LTlmZDktYjIyMTJkM2NmYzg5Iiwic2VjcmV0IjoiYjAxMDlkYjktODgzNi00ZDMzLWJjNjktY2JmYzY1MWMzZWMzIn0=" # Expected output: # Collecting commits for release v2.1.0... # Found 12 commits since last release # ✓ Commits uploaded successfully # GitHub Actions workflow integration cat > .github/workflows/release.yml << 'EOF' name: Deploy and Send Commits on: push: tags: - 'v*' jobs: release: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 with: fetch-depth: 0 - name: Get package version id: package uses: codex-team/action-nodejs-package-info@v1 - name: Send commits to Hawk run: | curl https://raw.githubusercontent.com/codex-team/hawk.releases/main/scripts/commits.sh -O chmod +x ./commits.sh ./commits.sh -r=${{ steps.package.outputs.name }}-${{ steps.package.outputs.version }} -t=${{ secrets.HAWK_TOKEN }} rm ./commits.sh EOF ``` -------------------------------- ### Configure Hawk Webpack Plugin for Source Maps Source: https://context7.com/context7/hawk_so/llms.txt Automatically uploads source maps and git commits to Hawk for enhanced debugging. Requires the @hawk.so/webpack-plugin. The plugin takes an integration token, release version, and can optionally send commit information. It generates hidden source maps for security. ```javascript // Install webpack plugin // npm install @hawk.so/webpack-plugin --save-dev const HawkWebpackPlugin = require('@hawk.so/webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: __dirname + '/dist' }, plugins: [ new HawkWebpackPlugin({ integrationToken: 'eyJpbnRlZ3JhdGlvbklkIjoiMDQ0NmVlZDctYmYyNC00YmE3LTlmZDktYjIyMTJkM2NmYzg5Iiwic2VjcmV0IjoiYjAxMDlkYjktODgzNi00ZDMzLWJjNjktY2JmYzY1MWMzZWMzIn0=', // Release name must match what your catcher sends release: process.env.npm_package_version || '1.0.0', // Automatically send last commits for suspected commit detection commits: true }) ], // Generate hidden source maps (not exposed to users) devtool: 'hidden-source-map' }; // Expected output after build: // ✓ Source maps uploaded to Hawk // ✓ 5 commits sent for release 1.0.0 // ✓ Suspected commits will appear in event overview ``` -------------------------------- ### Hawk Collector Endpoint (WebSocket) Source: https://docs.hawk.so/endpoint-and-credentials For real-time data streaming, WebSocket connections can be established to the collector endpoint. The URL includes the integration ID and collector address, appended with '/ws'. ```websocket wss://0446eed7-bf24-4ba7-9fd9-b2212d3cfc89.k1.hawk.so:433/ws ``` -------------------------------- ### Hawk Collector Endpoint (POST) Source: https://docs.hawk.so/endpoint-and-credentials The collector endpoint is constructed using the integration ID and the Hawk collector URL. POST requests are sent to this endpoint to transmit data. The URL structure supports load balancing. ```http https://0446eed7-bf24-4ba7-9fd9-b2212d3cfc89.k1.hawk.so:433 ``` -------------------------------- ### Manual Event Sending with Hawk Catcher Source: https://docs.hawk.so/integrations Demonstrates how to manually send an error object or a simple message to Hawk using a Catcher. This method allows for direct event reporting when automatic capture is not sufficient. No external dependencies are explicitly mentioned beyond the Catcher itself. ```javascript hawk.send(new Error()); // or hawk.send('Your message'); ``` -------------------------------- ### Automate Hawk Commit Sending in GitHub Actions Source: https://docs.hawk.so/releases This GitHub Actions workflow snippet shows how to automatically send commits to Hawk. It first retrieves the package name and version using the 'codex-team/action-nodejs-package-info' action, then downloads and executes the Hawk commits script with the release name and token from environment variables. ```yaml jobs: build: runs-on: ubuntu-20.04 steps: # Get package new version name - name: Get package info id: packageInfo uses: codex-team/action-nodejs-package-info@v1 - name: Send commits to Hawk run: | curl https://raw.githubusercontent.com/codex-team/hawk.releases/main/scripts/commits.sh -O chmod +x ./commits.sh ./commits.sh -r=${{ steps.package.outputs.name }}-${{ steps.package.outputs.version }} -t=${{ env.HAWK_TOKEN }} rm ./commits.sh ``` -------------------------------- ### Collector Endpoint Interaction Source: https://docs.hawk.so/endpoint-and-credentials The collector endpoint allows you to send data to your Hawk project. It requires an integration token and supports both HTTP POST and WebSocket connections. The endpoint URL is dynamically generated based on your integration ID. ```APIDOC ## POST /..hawk.so ### Description Sends data to the Hawk collector endpoint using an HTTP POST request. The endpoint URL includes your integration ID and the region. ### Method POST ### Endpoint `https://..hawk.so:` ### Parameters #### Path Parameters - **integrationId** (string) - Required - Your unique integration identifier. - **region** (string) - Required - The region identifier for the collector. #### Query Parameters None #### Request Body - **message** (object) - Required - The data payload to be sent to the collector. The exact format depends on the 'Catcher Message format' documentation (not provided here). ### Request Example ```json { "message": { "key": "value" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the request (e.g., "accepted"). - **messageId** (string) - A unique identifier for the received message. #### Response Example ```json { "status": "accepted", "messageId": "some-unique-message-id" } ``` --- ## WebSocket Connection to Collector Endpoint ### Description Establishes a WebSocket connection to the Hawk collector endpoint for real-time data streaming. ### Method WebSocket Upgrade ### Endpoint `wss://..hawk.so:/ws` ### Parameters #### Path Parameters - **integrationId** (string) - Required - Your unique integration identifier. - **region** (string) - Required - The region identifier for the collector. #### Query Parameters None #### Request Body (Not applicable for WebSocket connection establishment, data is sent via messages over the established connection) ### Request Example (Connection establishment is typically handled by WebSocket client libraries) ### Response #### Success Response (101 Switching Protocols) - The connection is upgraded from HTTP to WebSocket. #### Response Example (No explicit JSON response for connection upgrade; the client and server will then exchange messages) --- ## Token Information ### Description Integration tokens are encoded in Base64. Decoding the token provides the `integrationId` and `secret` required for authentication and endpoint construction. ### Method N/A (Information only) ### Endpoint N/A ### Parameters N/A ### Request Example (This is not an API request, but an example of a decoded token) ```json { "integrationId": "0446eed7-bf24-4ba7-9fd9-b2212d3cfc89", "secret": "b0109db9-8836-4d33-bc69-cbfc651c3ec3" } ``` ### Response N/A ``` -------------------------------- ### Implement Custom Python Catcher for Hawk.so Source: https://context7.com/context7/hawk_so/llms.txt This Python code provides a custom HawkCatcher class to send events to Hawk.so. It handles uncaught exceptions by default and allows sending custom errors with detailed backtraces, source code snippets, and context. The catcher decodes the integration token and sends data to the specified Hawk endpoint. ```python import json import base64 import requests import traceback import sys from typing import Dict, Any, Optional, List class HawkCatcher: def __init__(self, token: str, context: Optional[Dict] = None): """Initialize Hawk Catcher with integration token.""" # Decode token to get integrationId and secret decoded = json.loads(base64.b64decode(token)) self.integration_id = decoded['integrationId'] self.secret = decoded['secret'] self.endpoint = f"https://{self.integration_id}.k1.hawk.so:433" self.token = token self.global_context = context or {} # Bind to global exception handler sys.excepthook = self._exception_handler def _exception_handler(self, exc_type, exc_value, exc_traceback): """Global exception handler for uncaught errors.""" self.send(exc_value, exc_traceback) # Call default handler sys.__excepthook__(exc_type, exc_value, exc_traceback) def _extract_backtrace(self, tb) -> List[Dict]: """Extract backtrace with source code snippets.""" backtrace = [] for frame in traceback.extract_tb(tb): source_lines = [] try: with open(frame.filename, 'r') as f: all_lines = f.readlines() start = max(0, frame.lineno - 3) end = min(len(all_lines), frame.lineno + 2) for i in range(start, end): source_lines.append({ 'line': i + 1, 'content': all_lines[i].rstrip() }) except: pass backtrace.append({ 'file': frame.filename, 'line': frame.lineno, 'function': frame.name, 'sourceCode': source_lines }) return backtrace def send(self, error: Exception, tb=None, context: Optional[Dict] = None, user: Optional[Dict] = None): """Send error event to Hawk.""" if tb is None: tb = error.__traceback__ # Merge contexts merged_context = {**self.global_context, **(context or {})} payload = { 'token': self.token, 'catcherType': 'error/python', 'payload': { 'title': str(error), 'type': type(error).__name__, 'description': str(error), 'backtrace': self._extract_backtrace(tb) if tb else [], 'context': merged_context, 'user': user or {'id': 'anonymous'}, 'addons': { 'python_version': sys.version, 'platform': sys.platform } } } try: response = requests.post(self.endpoint, json=payload, timeout=5) return response.status_code == 200 except Exception as e: print(f'Hawk error: {e}') return False ``` -------------------------------- ### JavaScript: Filter Sensitive Data with beforeSend Hook Source: https://context7.com/context7/hawk_so/llms.txt Illustrates how to use the `beforeSend` hook in the HawkCatcher JavaScript SDK to filter sensitive information from events before they are sent to Hawk. This includes removing emails, passwords, credit card numbers, and API keys. ```javascript import HawkCatcher from '@hawk.so/javascript'; const hawk = new HawkCatcher({ token: 'YOUR_INTEGRATION_TOKEN', beforeSend(event) { // Remove user email addresses if (event.user?.email) { delete event.user.email; } // Filter password fields from context if (event.context) { Object.keys(event.context).forEach(key => { if (key.toLowerCase().includes('password') || key.toLowerCase().includes('secret') || key.toLowerCase().includes('token')) { delete event.context[key]; } }); } // Filter credit card numbers from all string values const creditCardRegex = /\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}/g; const filterValue = (obj) => { for (let key in obj) { if (typeof obj[key] === 'string') { obj[key] = obj[key].replace(creditCardRegex, '[FILTERED]'); } else if (typeof obj[key] === 'object' && obj[key] !== null) { filterValue(obj[key]); } } }; filterValue(event); // Remove specific addons if (event.addons?.localStorage) { delete event.addons.localStorage; } // Filter backtrace source code containing sensitive patterns if (event.backtrace) { event.backtrace.forEach(frame => { if (frame.sourceCode) { frame.sourceCode.forEach(line => { line.content = line.content.replace(/api_key=\w+/g, 'api_key=[FILTERED]'); }); } }); } // Return modified event (or null to prevent sending) return event; } }); // Test filtered data hawk.send('Payment failed', { context: { cardNumber: '4532-1234-5678-9010', // Will be filtered apiKey: 'sk_live_abc123', // Will be filtered amount: 99.99 // Will be sent }, user: { id: 'user-789', email: 'user@example.com' // Filtered by beforeSend } }); ``` -------------------------------- ### Decode Integration Token (JSON) Source: https://docs.hawk.so/endpoint-and-credentials An integration token is base64 encoded and decodes into a JSON object containing integrationId and secret. This format is used for authentication with Hawk services. ```json { "integrationId":"0446eed7-bf24-4ba7-9fd9-b2212d3cfc89", "secret":"b0109db9-8836-4d33-bc69-cbfc651c3ec3" } ``` -------------------------------- ### Send Error Event to Hawk Collector API Source: https://context7.com/context7/hawk_so/llms.txt This endpoint allows you to send error events to the Hawk Collector API. It requires your integration token and a detailed event payload. ```APIDOC ## POST /collector ### Description Send error events to Hawk using the Collector API endpoint with your integration token and event payload. ### Method POST ### Endpoint `https://[integrationId].k1.hawk.so:433` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **token** (string) - Required - The integration token. - **catcherType** (string) - Required - The type of catcher, e.g., `error/javascript`. - **payload** (object) - Required - The detailed error event payload. - **title** (string) - Required - The title of the error. - **type** (string) - Required - The type of the error. - **description** (string) - Optional - A detailed description of the error. - **level** (number) - Optional - The severity level of the error. - **backtrace** (array) - Optional - An array of stack trace frames. - **file** (string) - Required - The file path. - **line** (number) - Required - The line number. - **column** (number) - Optional - The column number. - **function** (string) - Optional - The function name. - **sourceCode** (array) - Optional - An array of source code lines. - **line** (number) - Required - The line number. - **content** (string) - Required - The content of the line. - **release** (string) - Optional - The release version of the application. - **user** (object) - Optional - Information about the affected user. - **id** (string) - Required - The user ID. - **name** (string) - Optional - The user name. - **email** (string) - Optional - The user email. - **context** (object) - Optional - Additional context about the error. - **userId** (string) - Required - The user ID in context. - **sessionId** (string) - Required - The session ID. - **environment** (string) - Required - The environment where the error occurred. - **addons** (object) - Optional - Add-on information. - **browser** (string) - Optional - Browser details. - **os** (string) - Optional - Operating system details. ### Request Example ```json { "token": "AAAABB...wER232r2wer", "catcherType": "error/javascript", "payload": { "title": "TypeError: Cannot read property length", "type": "TypeError", "description": "evaluating t.children.length", "level": 16, "backtrace": [ { "file": "/src/components/Editor.js", "line": 145, "column": 12, "function": "renderBlocks", "sourceCode": [ {"line": 144, "content": "function renderBlocks(data) {"}, {"line": 145, "content": " return data.children.length > 0;"}, {"line": 146, "content": "}"} ] } ], "release": "1.2.3", "user": { "id": "user-8821", "name": "John Doe", "email": "john@example.com" }, "context": { "userId": "8821", "sessionId": "abc-123", "environment": "production" }, "addons": { "browser": "Chrome 96.0", "os": "macOS 12.1" } } } ``` ### Response #### Success Response (200) Hawk.so typically responds with a 200 OK status upon successful receipt of the event. The response body may contain an acknowledgement or an event ID. #### Response Example ```json { "message": "Event received successfully.", "eventId": "some-event-id" } ``` ### WebSocket #### Description Establish a WebSocket connection for real-time event streaming. #### Endpoint `wss://[integrationId].k1.hawk.so:433/ws` #### Example Usage ```bash wscat -c wss://0446eed7-bf24-4ba7-9fd9-b2212d3cfc89.k1.hawk.so:433/ws ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.