A Vite plugin that bridges React applications with Kulp.AI, providing error reporting, route tracking, component tagging, and more
npm install vite-bridgeA comprehensive Vite plugin that bridges React applications with Kulp.AI, providing seamless communication between your React app and the Kulp.AI development environment.
- 🔍 Error Reporting: Captures and reports build and runtime errors to Kulp.AI
- 🧭 Route Tracking: Monitors React Router navigation and sends route changes to parent
- 🏷️ Component Tagger: Automatically tags JSX elements with unique identifiers for debugging
- 📡 PostMessage Bridge: Seamless communication via iframe postMessage
- 🎯 Development Only: Only active in development environment
- 🔧 Configurable: Enable/disable specific bridges as needed
- 📝 TypeScript Support: Full TypeScript definitions included
``bash`
npm install vite-bridgeor
yarn add vite-bridgeor
pnpm add vite-bridge
For the component tagger (enabled by default), install these additional dependencies:
`bash`
npm install @babel/parser magic-string estree-walkeror
yarn add @babel/parser magic-string estree-walkeror
pnpm add @babel/parser magic-string estree-walker
For Tailwind CSS configuration generation (optional):
`bash`
npm install esbuild tailwindcssor
yarn add esbuild tailwindcssor
pnpm add esbuild tailwindcss
Note: If you don't install the component tagger dependencies, the plugin will gracefully disable that feature and show helpful error messages.
Add the plugin to your vite.config.ts:
`typescript
import { defineConfig } from 'vite'
import { viteBridge } from 'vite-bridge'
export default defineConfig({
plugins: [
...viteBridge(), // All bridges enabled by default (error reporter, route tracker, component tagger)
// ... other plugins
],
})
`
Customize which bridges to enable:
`typescript
import { defineConfig } from 'vite'
import { viteBridge } from 'vite-bridge'
export default defineConfig({
plugins: [
...viteBridge({
enableErrorReporter: true, // Default: true
enableRouteTracker: true, // Default: true
enableComponentTagger: true, // Default: true
componentTaggerConfig: {
enableTailwindGeneration: false, // Default: false
tailwindConfigPath: './tailwind.config.ts', // Default: './tailwind.config.ts'
tailwindOutputPath: './src/tailwind.config.kulp.json', // Default: './src/tailwind.config.kulp.json'
},
enableConsoleLogger: false, // Default: false (future)
enablePerformanceTracker: false, // Default: false (future)
}),
],
})
`
Captures and reports various types of errors:
- Build Errors: Vite compilation errors
- Runtime Errors: JavaScript runtime exceptions
- Promise Rejections: Unhandled promise rejections
- HMR Errors: Hot Module Replacement errors
#### Error Object Structure
`typescript`
interface BuildError {
id: string; // Unique identifier
message: string; // Error message
count: number; // Occurrence count
file?: string; // Source file
line?: number; // Line number
column?: number; // Column number
stack?: string; // Stack trace
timestamp: number; // Unix timestamp
solved: boolean; // Resolution status
severity: 'error' | 'warning'; // Severity level
isSolving: boolean; // Processing status
}
#### Message Format
`typescript`
{
type: 'console',
method: 'error',
args: [BuildError],
timestamp: string // ISO timestamp
}
Monitors React Router navigation and communicates route changes:
- Automatic Detection: Works with React Router out of the box
- Multiple Tracking Methods: URL polling, popstate events, history API hooks
- Debounced Updates: Prevents duplicate route notifications
- Bidirectional Communication: Responds to route requests from parent
#### Route Messages
`typescript
// Route change notification
{
type: 'ROUTE_CHANGED',
path: string,
search: string,
hash: string,
fullUrl: string,
timestamp: number
}
// Current route response
{
type: 'CURRENT_ROUTE',
path: string,
search: string,
hash: string,
fullUrl: string,
timestamp: number
}
`
#### Requesting Current Route
From parent window:
`javascript
// Request current route
iframe.contentWindow.postMessage({
type: 'REQUEST_CURRENT_ROUTE'
}, '*');
// Listen for response
window.addEventListener('message', (event) => {
if (event.data.type === 'CURRENT_ROUTE') {
console.log('Current route:', event.data.path);
}
});
`
Automatically tags JSX elements with unique identifiers for debugging and development:
- Smart Tagging: Only tags custom components and HTML elements, skips Three.js Fiber and Drei components
- Unique Identifiers: Generates unique data attributes based on file path, line, and column
- Component Metadata: Captures component name, location, and content for debugging
- Development Only: Only active in development environment
#### Tag Structure
Each tagged element receives multiple data attributes:
`html
data-kulp-id="src/components/Button.tsx:15:8"
data-kulp-name="div"
data-component-path="src/components/Button.tsx"
data-component-line="15"
data-component-file="Button.tsx"
data-component-name="div"
data-component-content="%7B%22text%22%3A%22Click%20me%22%2C%22className%22%3A%22btn%20btn-primary%22%7D"
>
Click me
#### Component Content
The
data-component-content attribute contains URL-encoded JSON with:`typescript
interface ComponentContent {
text?: string; // Text content of the element
placeholder?: string; // Placeholder attribute value
className?: string; // CSS class names
}
`#### Excluded Elements
The following elements are automatically excluded from tagging:
- Three.js Fiber Elements: All Three.js mesh, geometry, material, and helper components
- Drei Components: All @react-three/drei components
- React Fragments:
Fragment and React.Fragment components#### Usage Example
`typescript
// Enable component tagger
export default defineConfig({
plugins: [
...viteBridge({
enableComponentTagger: true,
componentTaggerConfig: {
enableTailwindGeneration: false, // Optional: generate Tailwind config
},
}),
],
});
`Usage with Kulp.AI
This plugin is specifically designed for React applications running within Kulp.AI:
1. Development Environment: Kulp.AI displays your React app in an iframe
2. Error Monitoring: All errors are automatically reported to Kulp.AI
3. Route Tracking: Navigation changes are sent to Kulp.AI for better debugging
4. Seamless Integration: No additional configuration needed
Parent Window Integration
To receive messages in your parent application:
`javascript
window.addEventListener('message', (event) => {
switch (event.data.type) {
case 'console':
if (event.data.method === 'error') {
const error = event.data.args[0];
console.log('Received error:', error);
// Handle error as needed
}
break;
case 'ROUTE_CHANGED':
console.log('Route changed:', event.data.path);
// Update parent UI based on route
break;
case 'CURRENT_ROUTE':
console.log('Current route:', event.data.path);
// Handle current route response
break;
}
});
`Advanced Usage
$3
You can also use bridge functions programmatically:
`typescript
import {
sendErrorToParent,
getErrorReporterScript,
getRouteTrackerScript,
createComponentTagger,
shouldTagElement,
findProjectRoot
} from 'vite-bridge';// Send custom error
sendErrorToParent({
message: 'Custom error',
stack: new Error().stack
});
// Get bridge scripts (for custom injection)
const errorScript = getErrorReporterScript();
const routeScript = getRouteTrackerScript();
// Create component tagger instance
const tagger = createComponentTagger({
enableTailwindGeneration: false
});
// Check if element should be tagged
const shouldTag = shouldTagElement('CustomComponent'); // true
const shouldTagThree = shouldTagElement('mesh'); // false (Three.js component)
// Find project root
const projectRoot = findProjectRoot();
`$3
`typescript
import type {
BuildError,
KulpBridgeConfig,
ComponentTaggerConfig,
KulpMessage,
RouteChangeMessage,
CurrentRouteMessage,
RequestRouteMessage,
ErrorMessage
} from 'vite-bridge';
`Future Bridges
Coming soon:
- Console Logger: Capture and forward console logs
- Performance Tracker: Monitor performance metrics
- State Manager: Sync application state with parent
Development Only
The plugin only operates in development mode (
NODE_ENV === 'development'`). In production builds, no bridge code is injected.- Vite: 2.x, 3.x, 4.x, or 5.x
- React: Any version (for route tracking)
- TypeScript: Optional but recommended
Contributions are welcome! Please feel free to submit a Pull Request.
MIT License - see the LICENSE file for details.