open-brainy/src/universal/uuid.ts
David Snelling 93804be354 feat: add universal adapters for browser compatibility
- Create universal adapters for cross-platform support (browser/Node/serverless)
- Replace Node.js-specific imports with universal implementations
- Add OPFS support for browser persistent storage
- Maintain same BrainyData interface across all environments
- Enable real Brainy usage in browser console UI
- Keep package size optimized (no bloat)

Universal adapters in /src/universal/:
- uuid.ts: Cross-platform UUID generation
- crypto.ts: Browser/Node crypto operations
- fs.ts: OPFS/FileSystem/Memory storage adapter
- path.ts: Universal path operations
- events.ts: EventEmitter compatibility layer

This enables 'write once, run anywhere' for Brainy while maintaining
the exact same API. No breaking changes to existing code.
2025-08-08 15:22:38 -07:00

26 lines
No EOL
725 B
TypeScript

/**
* Universal UUID implementation
* Works in all environments: Browser, Node.js, Serverless
*/
import { isBrowser, isNode } from '../utils/environment.js'
export function v4(): string {
// Use crypto.randomUUID if available (Node.js 19+, modern browsers)
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
return crypto.randomUUID()
}
// Fallback implementation for older environments
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = Math.random() * 16 | 0
const v = c === 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16)
})
}
// Named export to match uuid package API
export { v4 as uuidv4 }
// Default export for convenience
export default { v4 }