@vulform/core
Version:
Core utilities and types for VulForm packages
318 lines (234 loc) • 7.85 kB
Markdown
# @vulform/core
> 🚀 **Built with Bun for maximum performance!**
Core utilities, types, and shared functionality for VulForm packages. This package provides the foundation for all VulForm SDK components.
## Features
- ✅ **TypeScript First** - Full type safety with comprehensive interfaces
- ✅ **Zero Dependencies** - Lightweight core with no external deps
- ✅ **Tree Shakeable** - Import only what you need
- ✅ **Universal** - Works in Node.js, browsers, and edge runtimes
- ✅ **Validation** - Built-in form field validation utilities
- ✅ **API Client** - HTTP client with retry logic and error handling
## Installation
```bash
# Install with Bun (recommended)
bun add @vulform/core
# Or with other package managers
npm install @vulform/core
pnpm add @vulform/core
yarn add @vulform/core
```
> **Note:** This package is automatically installed when you install any VulForm SDK package (`@vulform/js`, `@vulform/react`, `@vulform/vue`).
## URL Configuration
VulForm Core provides a flexible URL configuration system that supports multiple deployment scenarios:
### Configuration Strategies
#### 1. **SaaS (Default)**
Uses VulForm's hosted service:
```typescript
import { createSaaSConfig } from '@vulform/core';
const config = createSaaSConfig();
// baseUrl: 'https://api.vulform.dev'
```
#### 2. **Self-Hosted**
Uses relative URLs for same-domain deployment:
```typescript
import { createSelfHostedConfig } from '@vulform/core';
const config = createSelfHostedConfig();
// baseUrl: '/api/v1'
```
#### 3. **Custom URL**
Uses your specific endpoint:
```typescript
import { createCustomConfig } from '@vulform/core';
const config = createCustomConfig('https://forms.mycompany.com/api');
// baseUrl: 'https://forms.mycompany.com/api'
```
#### 4. **Auto-Detection (Recommended)**
Automatically detects the best configuration:
```typescript
import { getDefaultConfig, resolveApiUrl } from '@vulform/core';
// Auto-detect based on environment
const config = getDefaultConfig();
// Or resolve a specific URL
const apiUrl = resolveApiUrl(); // Auto-detects
const customUrl = resolveApiUrl('https://my-api.com');
```
### Environment Variables
VulForm supports multiple environment variable formats:
```bash
# Next.js
NEXT_PUBLIC_VULFORM_BASE_URL=https://api.mycompany.com
NEXT_PUBLIC_VULFORM_API_KEY=vf_your_key_here
# Create React App
REACT_APP_VULFORM_BASE_URL=https://api.mycompany.com
REACT_APP_VULFORM_API_KEY=vf_your_key_here
# Vite (Vue, Vanilla)
VITE_VULFORM_BASE_URL=https://api.mycompany.com
VITE_VULFORM_API_KEY=vf_your_key_here
# Universal (works in all environments)
VULFORM_BASE_URL=https://api.mycompany.com
VULFORM_API_KEY=vf_your_key_here
```
### URL Resolution Hierarchy
VulForm resolves URLs in the following order:
1. **Explicitly provided URL** (component prop or function parameter)
2. **Environment variables** (framework-specific, then universal)
3. **Auto-detection based on environment:**
- **Development**: `http://localhost:3000/api/v1`
- **Self-hosted detection**: `/api/v1` (relative URL)
- **Default fallback**: `https://api.vulform.dev` (SaaS)
## Usage
### Types
```typescript
import type {
FormTemplate,
FormField,
FormSettings,
FormTheme,
SubmissionResponse,
FormError,
ValidationRule,
ApiResponse,
} from '@vulform/core';
// Use in your application
const template: FormTemplate = {
id: 'contact-form',
name: 'Contact Form',
fields: [
{
id: 'email',
name: 'email',
type: 'email',
label: 'Email Address',
validation: {
required: true,
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
},
},
],
};
```
### Validation Utilities
```typescript
import { validateField, validateEmail, validateRequired } from '@vulform/core';
// Validate individual fields
const emailError = validateField('invalid-email', {
type: 'email',
validation: { required: true },
});
// Built-in validators
const isValidEmail = validateEmail('user@example.com'); // true
const hasValue = validateRequired('some value'); // true
```
### API Client
```typescript
import { VulFormApiClient } from '@vulform/core';
// Auto-configured client
const client = new VulFormApiClient({
apiKey: 'vf_your_api_key_here',
// baseUrl is auto-detected
});
// Custom URL client
const customClient = new VulFormApiClient({
apiKey: 'vf_your_api_key_here',
baseUrl: 'https://forms.mycompany.com/api',
});
```
### Configuration
```typescript
import { createConfig, validateConfig } from '@vulform/core';
const config = createConfig({
apiKey: process.env.VULFORM_API_KEY,
debug: process.env.NODE_ENV === 'development',
timeout: 15000,
});
// Validate configuration
const isValid = validateConfig(config);
```
## Type Definitions
### Core Types
- **`FormTemplate`** - Complete form definition with fields and settings
- **`FormField`** - Individual field configuration and validation
- **`FormSettings`** - Form-level configuration and behavior
- **`FormTheme`** - Styling and appearance customization
- **`SubmissionResponse`** - Server response after form submission
- **`FormError`** - Standardized error handling
### Field Types
Supports all HTML input types plus custom field types:
- `text`, `email`, `tel`, `url`, `password`
- `number`, `range`, `date`, `time`, `datetime-local`
- `textarea`, `select`, `checkbox`, `radio`
- `file` (coming soon)
### Validation Rules
- **`required`** - Field must have a value
- **`minLength`/`maxLength`** - String length validation
- **`min`/`max`** - Numeric range validation
- **`pattern`** - RegExp pattern matching
- **`custom`** - Custom validation functions
## API Reference
### Validation Functions
```typescript
// Field validation
validateField(value: any, field: FormField): string | null
// Built-in validators
validateRequired(value: any): boolean
validateEmail(value: string): boolean
validateMinLength(value: string, min: number): boolean
validateMaxLength(value: string, max: number): boolean
validatePattern(value: string, pattern: RegExp): boolean
```
### Configuration
```typescript
// Create and validate configuration
createConfig(options: Partial<VulFormConfig>): VulFormConfig
validateConfig(config: VulFormConfig): boolean
```
### API Client
```typescript
interface ApiClientConfig {
apiKey: string; // Required: Your VulForm API key
baseUrl?: string; // Optional: API base URL (auto-detected if not provided)
timeout?: number; // Optional: Request timeout in ms (default: 10000)
retries?: number; // Optional: Number of retries (default: 3)
debug?: boolean; // Optional: Enable debug logging (default: false)
}
```
## Error Handling
```typescript
import { FormError, isFormError } from '@vulform/core';
try {
await client.post('/submit', formData);
} catch (error) {
if (isFormError(error)) {
switch (error.code) {
case 'MISSING_API_KEY':
console.error('API key not configured');
break;
case 'VALIDATION_ERROR':
console.error('Form validation failed:', error.details);
break;
case 'RATE_LIMIT_EXCEEDED':
console.error('Too many requests');
break;
}
}
}
```
## Environment Support
Works across all JavaScript environments:
- **Node.js** 18+ (ESM and CommonJS)
- **Browsers** (ES2020+)
- **Edge Runtimes** (Vercel, Cloudflare Workers, etc.)
- **Bun** runtime (native support)
## Bundle Size
- **ESM**: ~9KB minified
- **CJS**: ~9KB minified
- **Types**: ~3KB
- **Gzipped**: ~3KB
## 🔗 Related Packages
- **[@vulform/js](../@vulform/js)** - Vanilla JavaScript SDK
- **[@vulform/react](../@vulform/react)** - React components and hooks
- **[@vulform/vue](../@vulform/vue)** - Vue.js components and composables
## 📄 License
MIT License - see [LICENSE](../../LICENSE) for details.
---
**Built with ❤️ and Bun by Dogu Yilmaz**