@kya-os/agentshield-beacon
v0.2.3
Published
Lightweight JavaScript beacon for AI agent detection and analytics
Readme
@kya-os/agentshield-beacon
Lightweight JavaScript beacon for AI agent detection and analytics. Track and analyze AI agent interactions with your web applications in real-time.
Features
- 🚀 Lightweight - Minimal impact on page performance
- 🔄 Web Worker Support - Offload processing to background threads
- 📊 Real-time Analytics - Track AI agent behavior as it happens
- 🔌 Framework Agnostic - Works with React, Vue, Angular, or vanilla JS
- 📦 Automatic Batching - Efficient network usage with smart batching
- 🔒 Privacy-First - No PII collection, GDPR compliant
- 💾 Offline Support - Queue events when offline, sync when back online
- 🎯 TypeScript Support - Full type definitions included
Installation
# npm
npm install @kya-os/agentshield-beacon
# pnpm
pnpm add @kya-os/agentshield-beacon
# yarn
yarn add @kya-os/agentshield-beaconQuick Start
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';
// Initialize the beacon (same projectId as pixel!)
const beacon = new AgentShieldBeacon({
projectId: 'proj_abc123' // Same as data-project-id in pixel
});
// Start collecting page views
beacon.collect('pageview');
// Track custom events
beacon.trackEvent('button_click', {
buttonId: 'signup-cta',
page: '/home',
});
// Clean up when done
beacon.destroy();CDN Usage
<script src="https://cdn.jsdelivr.net/npm/@kya-os/agentshield-beacon/dist/beacon.min.js"></script>
<script>
const beacon = new AgentShieldBeacon({
projectId: 'proj_abc123' // Same as pixel
});
beacon.collect('pageview');
</script>Configuration
const beacon = new AgentShieldBeacon({
// Required
projectId: 'proj_abc123', // Same as pixel's data-project-id
// Optional
environment: 'production', // Tag your environment
tags: { // Custom segmentation
version: '2.0.0',
region: 'us-east'
},
batchSize: 10, // Events per batch
flushInterval: 5000, // Ms between flushes
enableWebWorker: true, // Use web worker for processing
enableCompression: true, // Compress event payloads
enableOfflineQueue: true, // Queue events when offline
maxQueueSize: 100, // Max events to queue
sessionTimeout: 30 * 60000, // Session timeout in ms
debug: false, // Enable debug logging
});Framework Integration
React
import { useEffect } from 'react';
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';
const beacon = new AgentShieldBeacon({
projectId: process.env.REACT_APP_AGENTSHIELD_PROJECT_ID,
environment: process.env.NODE_ENV
});
function App() {
useEffect(() => {
beacon.collect('pageview');
return () => beacon.destroy();
}, []);
return <div>Your App</div>;
}Vue
<script setup>
import { onMounted, onUnmounted } from 'vue';
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';
const beacon = new AgentShieldBeacon({
projectId: import.meta.env.VITE_AGENTSHIELD_PROJECT_ID,
environment: import.meta.env.MODE
});
onMounted(() => {
beacon.collect('pageview');
});
onUnmounted(() => {
beacon.destroy();
});
</script>Next.js
App Router (Recommended)
// app/providers/beacon-provider.tsx
'use client';
import { useEffect } from 'react';
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';
let beacon: AgentShieldBeacon | null = null;
export default function BeaconProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
if (!beacon) {
beacon = new AgentShieldBeacon({
projectId: process.env.NEXT_PUBLIC_AGENTSHIELD_PROJECT_ID!,
// Workers are automatically disabled in development
// Set explicitly if needed:
// useWorker: false
});
}
beacon.collect('pageview');
return () => {
if (beacon) {
beacon.flush();
}
};
}, []);
return <>{children}</>;
}
// app/layout.tsx
import BeaconProvider from './providers/beacon-provider';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<BeaconProvider>
{children}
</BeaconProvider>
</body>
</html>
);
}Pages Router
// pages/_app.js
import { useEffect } from 'react';
import { AgentShieldBeacon } from '@kya-os/agentshield-beacon';
let beacon;
export default function App({ Component, pageProps }) {
useEffect(() => {
if (!beacon) {
beacon = new AgentShieldBeacon({
projectId: process.env.NEXT_PUBLIC_AGENTSHIELD_PROJECT_ID,
// Workers are automatically disabled in development
});
}
beacon.collect('pageview');
return () => {
if (beacon) {
beacon.flush();
}
};
}, []);
return <Component {...pageProps} />;
}Note: Web Workers are automatically disabled in Next.js development mode as webpack doesn't serve the worker files. The beacon works perfectly without workers for typical analytics use cases. In production, workers will be enabled automatically if supported.
API Reference
Core Methods
new AgentShieldBeacon(config)
Creates a new beacon instance.
beacon.collect(eventType, data?)
Collect an event with optional data.
beacon.trackEvent(name, properties?)
Track a custom event with properties.
beacon.identify(userId, traits?)
Identify a user with optional traits.
beacon.flush()
Manually flush the event queue.
beacon.destroy()
Clean up and destroy the beacon instance.
Event Types
pageview- Page view eventclick- Click interactionscroll- Scroll interactionform_submit- Form submissionerror- Error eventcustom- Custom event
Browser Support
- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
For older browsers, use the legacy build:
<script src="https://cdn.jsdelivr.net/npm/@kya-os/agentshield-beacon/dist/beacon.legacy.js"></script>Bundle Sizes
- Modern Build: ~18KB gzipped
- Legacy Build: ~23KB gzipped
- Worker Script: ~5KB gzipped
Troubleshooting
Next.js/Webpack Issues
If you see worker-related errors in development:
// Explicitly disable workers in development
const beacon = new AgentShieldBeacon({
projectId: 'your-project-id',
useWorker: false // Disable workers
});The beacon automatically disables workers in localhost/development environments.
Module Resolution Issues
If you get "Module not found" errors:
- Ensure you have the shared dependency:
npm install @kya-os/agentshield-shared- Clear your module cache:
rm -rf node_modules/.cache
npm installTypeScript Issues
If TypeScript can't find types:
// tsconfig.json
{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}Documentation
For detailed documentation, visit our docs site.
Contributing
Contributions are welcome! Please read our Contributing Guide for details.
License
This project is licensed under the MIT OR Apache-2.0 license - see the LICENSE file for details.
