AgentShield
JavaScript Beacon

Installation

How to install and set up the AgentShield JavaScript Beacon

Installation Methods

Choose the installation method that best fits your project:

Package Manager Installation

Install the beacon using your preferred package manager:

# npm
npm install @kya-os/agentshield-beacon

# yarn
yarn add @kya-os/agentshield-beacon

# pnpm
pnpm add @kya-os/agentshield-beacon

Import and Initialize

import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  // Optional configuration
  batchSize: 20,
  flushInterval: 5000,
  useWorker: true
});

// Start tracking
beacon.collect('pageview');

TypeScript Support

TypeScript definitions are included. No additional @types package needed.

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

const config: BeaconConfig = {
  apiKey: process.env.AGENTSHIELD_API_KEY!,
  debug: process.env.NODE_ENV === 'development'
};

const beacon = new AgentShieldBeacon(config);

CDN Installation

Add the beacon directly to your HTML:

<!-- Minified version (recommended for production) -->
<script src="https://cdn.jsdelivr.net/npm/@kya-os/agentshield-beacon@latest/dist/beacon.min.js"></script>

<!-- Specific version (recommended for stability) -->
<script src="https://cdn.jsdelivr.net/npm/@kya-os/agentshield-beacon@1.0.0/dist/beacon.min.js"></script>

Alternative CDNs

<!-- unpkg -->
<script src="https://unpkg.com/@kya-os/agentshield-beacon@latest/dist/beacon.min.js"></script>

<!-- cdnjs (when available) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/agentshield-beacon/1.0.0/beacon.min.js"></script>

Initialize

<script>
  // The beacon is available globally as AgentShieldBeacon
  const beacon = new AgentShieldBeacon({
    apiKey: 'your-api-key',
    debug: false
  });

  // Start tracking
  beacon.collect('pageview');
</script>

Async Loading

Load the script asynchronously to prevent blocking:

<script async>
  (function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/@kya-os/agentshield-beacon@latest/dist/beacon.min.js';
    script.onload = function() {
      window.beacon = new AgentShieldBeacon({
        apiKey: 'your-api-key'
      });
      window.beacon.collect('pageview');
    };
    document.head.appendChild(script);
  })();
</script>

ES Module Installation

For modern browsers with ES module support:

<script type="module">
  import { AgentShieldBeacon } from 'https://cdn.skypack.dev/@kya-os/agentshield-beacon';

  const beacon = new AgentShieldBeacon({
    apiKey: 'your-api-key'
  });

  beacon.collect('pageview');
</script>

With Import Maps

<script type="importmap">
{
  "imports": {
    "@kya-os/agentshield-beacon": "https://cdn.skypack.dev/@kya-os/agentshield-beacon"
  }
}
</script>

<script type="module">
  import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';

  const beacon = new AgentShieldBeacon({
    apiKey: 'your-api-key'
  });
</script>

Dynamic Import

async function initializeBeacon() {
  const { AgentShieldBeacon } = await import(
    'https://cdn.skypack.dev/@kya-os/agentshield-beacon'
  );

  return new AgentShieldBeacon({
    apiKey: 'your-api-key'
  });
}

// Use the beacon
initializeBeacon().then(beacon => {
  beacon.collect('pageview');
});

Framework Integration

React

import { useEffect, useRef } from 'react';
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';

function useAgentShield(config) {
  const beaconRef = useRef(null);

  useEffect(() => {
    beaconRef.current = new AgentShieldBeacon(config);
    beaconRef.current.collect('pageview');

    return () => {
      beaconRef.current?.destroy();
    };
  }, []);

  return beaconRef.current;
}

// Usage
function App() {
  const beacon = useAgentShield({
    apiKey: process.env.REACT_APP_AGENTSHIELD_KEY
  });

  return <div>Your app content</div>;
}

Vue 3

// plugins/agentshield.js
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';

export default {
  install(app, options) {
    const beacon = new AgentShieldBeacon(options);
    
    app.config.globalProperties.$beacon = beacon;
    app.provide('beacon', beacon);
    
    // Auto-track route changes
    app.config.globalProperties.$router?.afterEach(() => {
      beacon.collect('pageview');
    });
  }
};

// main.js
import { createApp } from 'vue';
import AgentShield from './plugins/agentshield';

const app = createApp(App);

app.use(AgentShield, {
  apiKey: import.meta.env.VITE_AGENTSHIELD_KEY
});

Angular

// agentshield.service.ts
import { Injectable, OnDestroy } from '@angular/core';
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';

@Injectable({
  providedIn: 'root'
})
export class AgentShieldService implements OnDestroy {
  private beacon: AgentShieldBeacon;

  constructor() {
    this.beacon = new AgentShieldBeacon({
      apiKey: environment.agentShieldKey
    });
    this.beacon.collect('pageview');
  }

  trackEvent(name: string, data?: any) {
    return this.beacon.trackEvent(name, data);
  }

  ngOnDestroy() {
    this.beacon.destroy();
  }
}

Bundle Size Optimization

The beacon is already optimized at 41KB gzipped. For further optimization, consider these strategies:

Tree Shaking

Import only what you need:

// Instead of
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';

// Use specific imports if available
import AgentShieldBeacon from '@kya-os/agentshield-beacon/beacon';

Lazy Loading

Load the beacon only when needed:

// Lazy load on user interaction
button.addEventListener('click', async () => {
  const { AgentShieldBeacon } = await import('@kya-os/agentshield-beacon');
  const beacon = new AgentShieldBeacon({ apiKey: 'key' });
  beacon.trackEvent('button_click');
});

// Lazy load after page load
if ('requestIdleCallback' in window) {
  requestIdleCallback(async () => {
    const { AgentShieldBeacon } = await import('@kya-os/agentshield-beacon');
    window.beacon = new AgentShieldBeacon({ apiKey: 'key' });
  });
}

WebWorker Bundle

For optimal performance, use the separate worker bundle:

const beacon = new AgentShieldBeacon({
  apiKey: 'your-key',
  useWorker: true,
  workerUrl: '/beacon-worker.min.js' // Serve separately
});

Content Security Policy

If you're using CSP, add these directives:

Content-Security-Policy: 
  script-src 'self' https://cdn.jsdelivr.net https://kya.vouched.id;
  connect-src 'self' https://kya.vouched.id;
  worker-src 'self' blob:;

For inline scripts, you'll need to add a nonce or use 'unsafe-inline':

<script nonce="random-nonce">
  const beacon = new AgentShieldBeacon({ apiKey: 'key' });
</script>

Verification

After installation, verify the beacon is working:

Check Network Requests

  1. Open Developer Tools → Network tab
  2. Filter by "agentshield"
  3. You should see requests to kya.vouched.id

Enable Debug Mode

const beacon = new AgentShieldBeacon({
  apiKey: 'your-key',
  debug: true,
  logLevel: 'debug'
});

Check the console for:

  • Initialization messages
  • Event tracking logs
  • API responses
  • Any errors or warnings

Test Event Tracking

// Test basic tracking
beacon.collect('pageview').then(() => {
  console.log('Pageview tracked successfully');
}).catch(error => {
  console.error('Tracking failed:', error);
});

// Test custom events
beacon.trackEvent('test_event', {
  timestamp: Date.now()
}).then(() => {
  console.log('Test event sent');
});

Troubleshooting

Beacon not initializing

  • Check API key is valid
  • Verify network connectivity
  • Check browser console for errors
  • Ensure JavaScript is enabled

Events not being sent

  • Check if Do Not Track is enabled
  • Verify API endpoint is accessible
  • Check for Content Security Policy blocks
  • Review browser console for network errors

WebWorker not working

  • Ensure browser supports WebWorkers
  • Check worker script URL is correct
  • Verify CSP allows worker-src
  • Falls back to main thread automatically

Next Steps

Command Palette

Search for a command to run...