AgentShield
JavaScript Beacon

Beacon API Reference

Complete API documentation for the AgentShield JavaScript Beacon

AgentShieldBeacon Class

The main class for initializing and managing the beacon.

Constructor

new AgentShieldBeacon(config: BeaconConfig)

Creates a new beacon instance with the specified configuration.

Parameters

ParameterTypeRequiredDescription
configBeaconConfigYesConfiguration object for the beacon

Configuration Options

interface BeaconConfig {
  // Required
  apiKey: string; // Your AgentShield API key

  // Endpoint Configuration
  endpoint?: string; // API endpoint (default: 'https://kya.vouched.id/v1/beacon')

  // Batching Configuration
  batchSize?: number; // Events per batch (1-100, default: 10)
  flushInterval?: number; // Auto-flush interval in ms (default: 5000)

  // Worker Configuration
  useWorker?: boolean; // Enable WebWorker (default: true)
  workerUrl?: string; // Custom worker script URL
  workerConfig?: {
    // Advanced worker settings
    heartbeatInterval?: number; // Health check interval (default: 5000ms)
    enableCompression?: boolean; // Enable message compression (default: true)
    maxRetries?: number; // Max restart attempts (default: 3)
  };

  // Privacy Configuration
  respectDoNotTrack?: boolean; // Honor DNT header (default: true)
  anonymizeIp?: boolean; // Anonymize IP addresses (default: false)

  // Session Configuration
  sessionTimeout?: number; // Session timeout in ms (default: 1800000)
  sessionCookieName?: string; // Session cookie name (default: '_as_beacon_session')

  // Debug Configuration
  debug?: boolean; // Enable debug mode (default: false)
  logLevel?: 'error' | 'warn' | 'info' | 'debug'; // Log level (default: 'error')

  // Performance Configuration
  maxQueueSize?: number; // Max queued events (10-1000, default: 100)
  retryAttempts?: number; // Retry attempts (0-10, default: 3)
  retryDelay?: number; // Base retry delay in ms (default: 2000)
}

Example

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  batchSize: 20,
  debug: true,
  useWorker: true,
});

Methods

collect()

Manually collect and send detection data.

collect(eventType?: BeaconEventType): Promise<void>

Parameters

ParameterTypeRequiredDescription
eventTypeBeaconEventTypeNoType of event to collect

Event Types

  • 'pageview' - Page view event
  • 'pageunload' - Page unload event
  • 'error' - Error event
  • 'custom' - Custom event
  • 'heartbeat' - Heartbeat event

Example

// Collect pageview
await beacon.collect('pageview');

// Collect with automatic type detection
await beacon.collect();

trackEvent()

Track a custom event with metadata.

trackEvent(eventName: string, metadata?: Record<string, unknown>): Promise<void>

Parameters

ParameterTypeRequiredDescription
eventNamestringYesName of the custom event
metadataobjectNoAdditional event metadata

Example

await beacon.trackEvent('button_click', {
  buttonId: 'signup-cta',
  page: '/home',
  timestamp: Date.now(),
});

await beacon.trackEvent('form_submit', {
  formType: 'registration',
  fields: ['email', 'name'],
  validationPassed: true,
});

trackPageUnload()

Track page unload event using the SendBeacon API for reliability.

trackPageUnload(): void

This method uses the browser's SendBeacon API to ensure the event is sent even when the page is closing.

Example

window.addEventListener('beforeunload', () => {
  beacon.trackPageUnload();
});

updateConfig()

Update beacon configuration at runtime.

updateConfig(updates: Partial<BeaconConfig>): void

Parameters

ParameterTypeRequiredDescription
updatesPartial<BeaconConfig>YesConfiguration updates to apply

Example

// Enable debug mode
beacon.updateConfig({
  debug: true,
  logLevel: 'debug',
});

// Change batch settings
beacon.updateConfig({
  batchSize: 50,
  flushInterval: 10000,
});

destroy()

Destroy the beacon instance and clean up all resources.

destroy(): void

Always call destroy() when the beacon is no longer needed to prevent memory leaks and ensure all pending events are sent.

Example

// Clean up on page unload
window.addEventListener('beforeunload', () => {
  beacon.destroy();
});

// Clean up in React component
useEffect(() => {
  const beacon = new AgentShieldBeacon(config);
  return () => beacon.destroy();
}, []);

Event Object Structure

Events sent by the beacon follow this structure:

interface BeaconEvent {
  type: BeaconEventType; // Event type
  data: {
    // Collected data
    userAgent: string; // User agent string
    url: string; // Current URL
    timestamp: number; // Event timestamp
    sessionId: string; // Session identifier
    screenResolution?: string; // Screen resolution
    viewport?: string; // Viewport size
    timezone?: string; // User timezone
    platform?: string; // Platform/OS
    // ... additional fields
  };
  metadata?: Record<string, any>; // Custom metadata
}

Error Handling

All async methods return promises that may reject with structured errors:

interface BeaconError {
  code: string; // Error code
  message: string; // Human-readable message
  recoverable: boolean; // Whether the error is recoverable
  retryAfter?: number; // Suggested retry delay in ms
}

Error Codes

CodeDescriptionRecoverable
INVALID_CONFIGInvalid configurationNo
NETWORK_ERRORNetwork request failedYes
QUOTA_EXCEEDEDStorage quota exceededNo
WORKER_ERRORWebWorker errorYes
RATE_LIMITEDAPI rate limit exceededYes

Example Error Handling

try {
  await beacon.trackEvent('important_action', { value: 100 });
} catch (error) {
  if (error.recoverable) {
    // Retry after suggested delay
    setTimeout(() => {
      beacon.trackEvent('important_action', { value: 100 });
    }, error.retryAfter || 5000);
  } else {
    // Log permanent error
    console.error('Unrecoverable error:', error.message);
  }
}

TypeScript Support

The beacon includes full TypeScript definitions. Import types as needed:

import {
  AgentShieldBeacon,
  BeaconConfig,
  BeaconEvent,
  BeaconEventType,
  BeaconError,
} from '@kya-os/agentshield-beacon';

const config: BeaconConfig = {
  apiKey: 'your-api-key',
  debug: true,
};

const beacon = new AgentShieldBeacon(config);

Best Practices

1. Initialize Early

Initialize the beacon as early as possible in your application lifecycle:

// Good: Initialize immediately
const beacon = new AgentShieldBeacon(config);

// Bad: Delayed initialization
setTimeout(() => {
  const beacon = new AgentShieldBeacon(config);
}, 5000);

2. Use Environment Variables

Store sensitive configuration in environment variables:

const beacon = new AgentShieldBeacon({
  apiKey: process.env.AGENTSHIELD_API_KEY,
  endpoint: process.env.AGENTSHIELD_ENDPOINT || 'https://kya.vouched.id/v1/beacon',
});

3. Handle Errors Gracefully

Always handle potential errors in production:

const safeTrackEvent = async (name, metadata) => {
  try {
    await beacon.trackEvent(name, metadata);
  } catch (error) {
    // Log to your error tracking service
    console.error('Beacon error:', error);
    // Don't let tracking errors break your app
  }
};

4. Clean Up Resources

Always destroy the beacon when it's no longer needed:

// SPA route change
router.beforeEach((to, from, next) => {
  beacon.destroy();
  next();
});

// Component unmount
onUnmounted(() => {
  beacon.destroy();
});

5. Optimize Batch Settings

Adjust batching based on your traffic patterns:

// High-traffic site: larger batches, longer intervals
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  batchSize: 50,
  flushInterval: 10000,
});

// Low-traffic site: smaller batches, shorter intervals
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  batchSize: 5,
  flushInterval: 3000,
});

Next Steps

Command Palette

Search for a command to run...