vite-bridge
v1.1.5
Published
A Vite plugin that bridges React applications with Kulp.AI, providing error reporting, route tracking, component tagging, and more
Maintainers
Readme
vite-bridge
A comprehensive Vite plugin that bridges React applications with Kulp.AI, providing seamless communication between your React app and the Kulp.AI development environment.
Features
- 🔍 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
Installation
npm install vite-bridge
# or
yarn add vite-bridge
# or
pnpm add vite-bridgeRequired Dependencies for Full Functionality
For the component tagger (enabled by default), install these additional dependencies:
npm install @babel/parser magic-string estree-walker
# or
yarn add @babel/parser magic-string estree-walker
# or
pnpm add @babel/parser magic-string estree-walkerFor Tailwind CSS configuration generation (optional):
npm install esbuild tailwindcss
# or
yarn add esbuild tailwindcss
# or
pnpm add esbuild tailwindcssNote: If you don't install the component tagger dependencies, the plugin will gracefully disable that feature and show helpful error messages.
Quick Start
Add the plugin to your vite.config.ts:
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
],
})Configuration
Customize which bridges to enable:
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)
}),
],
})Bridges
1. Error Reporter Bridge
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
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
{
type: 'console',
method: 'error',
args: [BuildError],
timestamp: string // ISO timestamp
}2. Route Tracker Bridge
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
// 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:
// 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);
}
});3. Component Tagger Bridge
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:
<!-- Example of a tagged component -->
<div
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
</div>Component Content
The data-component-content attribute contains URL-encoded JSON with:
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:
FragmentandReact.Fragmentcomponents
Usage Example
// 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:
- Development Environment: Kulp.AI displays your React app in an iframe
- Error Monitoring: All errors are automatically reported to Kulp.AI
- Route Tracking: Navigation changes are sent to Kulp.AI for better debugging
- Seamless Integration: No additional configuration needed
Parent Window Integration
To receive messages in your parent application:
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
Programmatic Access
You can also use bridge functions programmatically:
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();Type Definitions
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.
Requirements
- Vite: 2.x, 3.x, 4.x, or 5.x
- React: Any version (for route tracking)
- TypeScript: Optional but recommended
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License - see the LICENSE file for details.
