@rilaykit/core 0.1.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,636 @@
1
+ import React from 'react';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * Main configuration class for Rilay form components and workflows
6
+ * Manages component registration, retrieval, and configuration
7
+ */
8
+ declare class ril {
9
+ private components;
10
+ private formRenderConfig;
11
+ private workflowRenderConfig;
12
+ static create(): ril;
13
+ /**
14
+ * Add a component to the configuration
15
+ * @param subType - The component subtype (e.g., 'text', 'email', 'heading')
16
+ * @param config - Component configuration without id and subType
17
+ * @returns The ril instance for chaining
18
+ */
19
+ addComponent<TProps = any>(subType: InputType | LayoutType, config: Omit<ComponentConfig<TProps>, 'id' | 'subType'> & {
20
+ id?: string;
21
+ }): this;
22
+ /**
23
+ * Set custom row renderer
24
+ * @param renderer - Custom row renderer function
25
+ * @returns The ril instance for chaining
26
+ */
27
+ setRowRenderer(renderer: FormRowRenderer): this;
28
+ /**
29
+ * Set custom body renderer
30
+ * @param renderer - Custom body renderer function
31
+ * @returns The ril instance for chaining
32
+ */
33
+ setBodyRenderer(renderer: FormBodyRenderer): this;
34
+ /**
35
+ * Set custom submit button renderer
36
+ * @param renderer - Custom submit button renderer function
37
+ * @returns The ril instance for chaining
38
+ */
39
+ setSubmitButtonRenderer(renderer: FormSubmitButtonRenderer): this;
40
+ /**
41
+ * Set complete form render configuration
42
+ * @param config - Form render configuration
43
+ * @returns The ril instance for chaining
44
+ */
45
+ setFormRenderConfig(config: FormRenderConfig): this;
46
+ /**
47
+ * Get current form render configuration
48
+ * @returns Current form render configuration
49
+ */
50
+ getFormRenderConfig(): FormRenderConfig;
51
+ /**
52
+ * Set custom stepper renderer for workflows
53
+ * @param renderer - Custom stepper renderer function
54
+ * @returns The ril instance for chaining
55
+ */
56
+ setStepperRenderer(renderer: WorkflowStepperRenderer): this;
57
+ /**
58
+ * Set custom workflow navigation renderer
59
+ * @param renderer - Custom workflow navigation renderer function
60
+ * @returns The ril instance for chaining
61
+ */
62
+ setWorkflowNavigationRenderer(renderer: WorkflowNavigationRenderer): this;
63
+ /**
64
+ * Set complete workflow render configuration
65
+ * @param config - Workflow render configuration
66
+ * @returns The ril instance for chaining
67
+ */
68
+ setWorkflowRenderConfig(config: WorkflowRenderConfig): this;
69
+ /**
70
+ * Get current workflow render configuration
71
+ * @returns Current workflow render configuration
72
+ */
73
+ getWorkflowRenderConfig(): WorkflowRenderConfig;
74
+ /**
75
+ * @deprecated Use setFormRenderConfig() instead
76
+ */
77
+ setRenderConfig(config: FormRenderConfig): this;
78
+ /**
79
+ * Get a component by its ID
80
+ * @param id - Component ID
81
+ * @returns Component configuration or undefined
82
+ */
83
+ getComponent(id: string): ComponentConfig | undefined;
84
+ /**
85
+ * List components by type (input or layout)
86
+ * @param type - Component type
87
+ * @returns Array of matching components
88
+ */
89
+ getComponentsByType(type: ComponentType): ComponentConfig[];
90
+ /**
91
+ * List components by sub-type
92
+ * @param subType - Component sub-type
93
+ * @returns Array of matching components
94
+ */
95
+ getComponentsBySubType(subType: InputType | LayoutType): ComponentConfig[];
96
+ /**
97
+ * Get components by category
98
+ * @param category - Component category
99
+ * @returns Array of matching components
100
+ */
101
+ getComponentsByCategory(category: string): ComponentConfig[];
102
+ /**
103
+ * List all registered components
104
+ * @returns Array of all components
105
+ */
106
+ getAllComponents(): ComponentConfig[];
107
+ /**
108
+ * Check if a component exists
109
+ * @param id - Component ID
110
+ * @returns True if component exists
111
+ */
112
+ hasComponent(id: string): boolean;
113
+ /**
114
+ * Remove a component from the configuration
115
+ * @param id - Component ID
116
+ * @returns True if component was removed
117
+ */
118
+ removeComponent(id: string): boolean;
119
+ /**
120
+ * Clear all components
121
+ */
122
+ clear(): void;
123
+ /**
124
+ * Export configuration as a plain object
125
+ * @returns Object with component configurations
126
+ */
127
+ export(): Record<string, ComponentConfig>;
128
+ /**
129
+ * Import configuration from a plain object
130
+ * @param config - Object with component configurations
131
+ * @returns The ril instance for chaining
132
+ */
133
+ import(config: Record<string, ComponentConfig>): this;
134
+ /**
135
+ * Get statistics about registered components and renderers
136
+ * @returns Object with comprehensive statistics
137
+ */
138
+ getStats(): {
139
+ total: number;
140
+ byType: Record<ComponentType, number>;
141
+ bySubType: Record<string, number>;
142
+ byCategory: Record<string, number>;
143
+ hasCustomRenderers: {
144
+ row: boolean;
145
+ body: boolean;
146
+ submitButton: boolean;
147
+ stepper: boolean;
148
+ workflowNavigation: boolean;
149
+ };
150
+ };
151
+ /**
152
+ * Validate the configuration
153
+ * @returns Array of validation errors
154
+ */
155
+ validate(): string[];
156
+ }
157
+
158
+ interface RilayLicenseConfig {
159
+ readonly licenseKey?: string;
160
+ readonly environment?: 'development' | 'production';
161
+ readonly allowTrial?: boolean;
162
+ }
163
+ type ComponentType = 'input' | 'layout';
164
+ type InputType = 'text' | 'email' | 'password' | 'number' | 'select' | 'checkbox' | 'textarea' | 'file' | 'date';
165
+ type LayoutType = 'heading' | 'paragraph' | 'container' | 'divider' | 'spacer' | 'alert';
166
+ interface ValidationResult {
167
+ readonly isValid: boolean;
168
+ readonly errors: ValidationError[];
169
+ readonly warnings?: ValidationWarning[];
170
+ }
171
+ interface ValidationError {
172
+ readonly code: string;
173
+ readonly message: string;
174
+ readonly path?: string[];
175
+ }
176
+ interface ValidationWarning {
177
+ readonly code: string;
178
+ readonly message: string;
179
+ readonly path?: string[];
180
+ }
181
+ interface ValidationContext {
182
+ readonly fieldId: string;
183
+ readonly formData: Record<string, any>;
184
+ readonly fieldProps: Record<string, any>;
185
+ readonly touched: boolean;
186
+ readonly dirty: boolean;
187
+ }
188
+ type ValidatorFunction<TProps = any> = (value: any, context: ValidationContext, props: TProps) => ValidationResult | Promise<ValidationResult>;
189
+ interface ValidationConfig<TProps = any> {
190
+ readonly validator?: ValidatorFunction<TProps>;
191
+ readonly debounceMs?: number;
192
+ readonly validateOnChange?: boolean;
193
+ readonly validateOnBlur?: boolean;
194
+ readonly validateOnSubmit?: boolean;
195
+ readonly dependencies?: string[];
196
+ }
197
+ type ComponentRenderer<TProps = any> = (props: ComponentRenderProps<TProps>) => React.ReactElement;
198
+ interface ComponentRenderProps<TProps = any> {
199
+ id: string;
200
+ props: TProps;
201
+ value?: any;
202
+ onChange?: (value: any) => void;
203
+ onBlur?: () => void;
204
+ error?: ValidationError[];
205
+ warnings?: ValidationWarning[];
206
+ touched?: boolean;
207
+ disabled?: boolean;
208
+ isValidating?: boolean;
209
+ [key: string]: any;
210
+ }
211
+ interface ComponentOptions<TProps = any> {
212
+ readonly configurable?: Array<{
213
+ key: keyof TProps;
214
+ type: 'string' | 'number' | 'boolean' | 'select' | 'array';
215
+ label: string;
216
+ options?: any[];
217
+ default?: any;
218
+ }>;
219
+ readonly previewProps?: Partial<TProps>;
220
+ readonly icon?: string;
221
+ readonly tags?: string[];
222
+ }
223
+ interface ComponentConfig<TProps = any> {
224
+ readonly id: string;
225
+ readonly type: ComponentType;
226
+ readonly subType: InputType | LayoutType;
227
+ readonly name: string;
228
+ readonly description?: string;
229
+ readonly category?: string;
230
+ readonly renderer: ComponentRenderer<TProps>;
231
+ readonly options?: ComponentOptions<TProps>;
232
+ readonly validation?: ValidationConfig<TProps>;
233
+ readonly defaultProps?: Partial<TProps>;
234
+ }
235
+ interface FormFieldConfig {
236
+ readonly id: string;
237
+ readonly componentId: string;
238
+ readonly props: Record<string, any>;
239
+ readonly validation?: ValidationConfig;
240
+ readonly conditional?: ConditionalConfig;
241
+ }
242
+ interface FormFieldRow {
243
+ readonly id: string;
244
+ readonly fields: FormFieldConfig[];
245
+ readonly maxColumns?: number;
246
+ readonly spacing?: 'tight' | 'normal' | 'loose';
247
+ readonly alignment?: 'start' | 'center' | 'end' | 'stretch';
248
+ }
249
+ interface ConditionalConfig {
250
+ readonly condition: (formData: Record<string, any>) => boolean;
251
+ readonly action: 'show' | 'hide' | 'disable' | 'require';
252
+ }
253
+ interface StepLifecycleHooks {
254
+ readonly onBeforeEnter?: (stepData: any, allData: any, context: WorkflowContext) => Promise<void>;
255
+ readonly onAfterLeave?: (stepData: any, allData: any, context: WorkflowContext) => Promise<boolean>;
256
+ readonly onValidate?: (stepData: any, context: WorkflowContext) => Promise<ValidationResult>;
257
+ readonly onTransform?: (stepData: any, context: WorkflowContext) => Promise<any>;
258
+ readonly onError?: (error: Error, context: WorkflowContext) => Promise<void>;
259
+ }
260
+ interface WorkflowContext {
261
+ readonly workflowId: string;
262
+ readonly currentStepIndex: number;
263
+ readonly totalSteps: number;
264
+ readonly allData: Record<string, any>;
265
+ readonly stepData: Record<string, any>;
266
+ readonly isFirstStep: boolean;
267
+ readonly isLastStep: boolean;
268
+ readonly visitedSteps: Set<string>;
269
+ readonly user?: any;
270
+ }
271
+ interface StepPermissions {
272
+ readonly requiredRoles?: string[];
273
+ readonly requiredPermissions?: string[];
274
+ readonly customGuard?: (user: any, context: WorkflowContext) => boolean | Promise<boolean>;
275
+ }
276
+ interface DynamicStepConfig {
277
+ readonly resolver: (previousData: any, context: WorkflowContext) => Promise<StepConfig[]>;
278
+ readonly cacheKey?: string;
279
+ readonly retryPolicy?: RetryPolicy;
280
+ }
281
+ interface RetryPolicy {
282
+ readonly maxRetries: number;
283
+ readonly delayMs: number;
284
+ readonly backoffMultiplier?: number;
285
+ }
286
+ interface ConditionalBranch {
287
+ readonly condition: (data: any, context: WorkflowContext) => boolean | Promise<boolean>;
288
+ readonly steps: StepConfig[];
289
+ readonly fallback?: StepConfig[];
290
+ }
291
+ interface StepConfig {
292
+ readonly id: string;
293
+ readonly title: string;
294
+ readonly description?: string;
295
+ readonly formConfig: FormConfiguration;
296
+ readonly validation?: StepValidationConfig;
297
+ readonly conditional?: StepConditionalConfig;
298
+ readonly allowSkip?: boolean;
299
+ readonly requiredToComplete?: boolean;
300
+ readonly hooks?: StepLifecycleHooks;
301
+ readonly permissions?: StepPermissions;
302
+ readonly isDynamic?: boolean;
303
+ readonly dynamicConfig?: DynamicStepConfig;
304
+ readonly renderer?: CustomStepRenderer;
305
+ }
306
+ interface StepValidationConfig {
307
+ readonly validator?: (stepData: Record<string, any>, allFormData: Record<string, any>, context: WorkflowContext) => ValidationResult | Promise<ValidationResult>;
308
+ readonly validateOnStepChange?: boolean;
309
+ readonly blockNextIfInvalid?: boolean;
310
+ }
311
+ interface StepConditionalConfig {
312
+ readonly condition: (formData: Record<string, any>, context: WorkflowContext) => boolean;
313
+ readonly action: 'show' | 'hide' | 'skip';
314
+ }
315
+ type CustomStepRenderer = (props: StepConfig) => React.ReactElement;
316
+ interface WorkflowPersistenceData {
317
+ readonly workflowId: string;
318
+ readonly currentStepIndex: number;
319
+ readonly allData: Record<string, any>;
320
+ readonly metadata: {
321
+ readonly timestamp: number;
322
+ readonly version?: string;
323
+ readonly userId?: string;
324
+ readonly sessionId?: string;
325
+ };
326
+ }
327
+ interface PersistenceAdapter {
328
+ readonly name: string;
329
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
330
+ load(key: string): Promise<WorkflowPersistenceData | null>;
331
+ remove(key: string): Promise<void>;
332
+ exists(key: string): Promise<boolean>;
333
+ list?(pattern?: string): Promise<string[]>;
334
+ }
335
+ interface PersistenceConfig {
336
+ readonly adapter: PersistenceAdapter;
337
+ readonly key?: string;
338
+ readonly debounceMs?: number;
339
+ readonly autoSave?: boolean;
340
+ readonly saveOnStepChange?: boolean;
341
+ readonly encryptionKey?: string;
342
+ readonly maxRetries?: number;
343
+ readonly retryDelayMs?: number;
344
+ readonly onSave?: (data: WorkflowPersistenceData) => Promise<void> | void;
345
+ readonly onLoad?: (data: WorkflowPersistenceData) => Promise<void> | void;
346
+ readonly onError?: (error: Error, operation: 'save' | 'load' | 'remove') => Promise<void> | void;
347
+ readonly onRetry?: (attempt: number, maxRetries: number, error: Error) => Promise<void> | void;
348
+ }
349
+ interface WorkflowAnalytics {
350
+ readonly onWorkflowStart?: (workflowId: string, context: WorkflowContext) => void;
351
+ readonly onWorkflowComplete?: (workflowId: string, duration: number, data: any) => void;
352
+ readonly onWorkflowAbandon?: (workflowId: string, currentStep: string, data: any) => void;
353
+ readonly onStepStart?: (stepId: string, timestamp: number, context: WorkflowContext) => void;
354
+ readonly onStepComplete?: (stepId: string, duration: number, data: any, context: WorkflowContext) => void;
355
+ readonly onStepSkip?: (stepId: string, reason: string, context: WorkflowContext) => void;
356
+ readonly onValidationError?: (stepId: string, errors: ValidationError[], context: WorkflowContext) => void;
357
+ readonly onError?: (error: Error, context: WorkflowContext) => void;
358
+ }
359
+ interface WorkflowOptimizations {
360
+ readonly preloadNextStep?: boolean;
361
+ readonly cacheValidation?: boolean;
362
+ readonly virtualizeSteps?: boolean;
363
+ readonly lazyLoadComponents?: boolean;
364
+ readonly maxConcurrentRequests?: number;
365
+ }
366
+ interface WorkflowVersion {
367
+ readonly version: string;
368
+ readonly migrationStrategy?: (oldData: any, newConfig: any) => any;
369
+ readonly compatibilityMode?: boolean;
370
+ }
371
+ interface WorkflowHooks {
372
+ readonly onStepChange?: (from: string, to: string, context: WorkflowContext) => void;
373
+ readonly onDataChange?: (data: any, context: WorkflowContext) => void;
374
+ readonly onValidation?: (result: ValidationResult, context: WorkflowContext) => void;
375
+ }
376
+ interface WorkflowPlugin {
377
+ readonly name: string;
378
+ readonly version?: string;
379
+ readonly install: (workflow: any) => void;
380
+ readonly hooks?: WorkflowHooks;
381
+ readonly dependencies?: string[];
382
+ }
383
+ interface WorkflowConfig {
384
+ readonly id: string;
385
+ readonly name: string;
386
+ readonly description?: string;
387
+ readonly steps: StepConfig[];
388
+ readonly branches?: ConditionalBranch[];
389
+ readonly navigation?: NavigationConfig;
390
+ readonly persistence?: PersistenceConfig;
391
+ readonly completion?: CompletionConfig;
392
+ readonly analytics?: WorkflowAnalytics;
393
+ readonly optimizations?: WorkflowOptimizations;
394
+ readonly version?: WorkflowVersion;
395
+ readonly plugins?: WorkflowPlugin[];
396
+ readonly renderConfig?: WorkflowRenderConfig;
397
+ }
398
+ interface NavigationConfig {
399
+ readonly allowBackNavigation?: boolean;
400
+ readonly allowStepSkipping?: boolean;
401
+ readonly showProgress?: boolean;
402
+ readonly customNavigation?: boolean;
403
+ }
404
+ interface CompletionConfig {
405
+ readonly onComplete?: (formData: Record<string, any>) => void | Promise<void>;
406
+ readonly confirmBeforeSubmit?: boolean;
407
+ readonly customCompletionStep?: any;
408
+ }
409
+ interface WorkflowStepperRendererProps {
410
+ readonly steps: StepConfig[];
411
+ readonly currentStepIndex: number;
412
+ readonly visitedSteps: Set<string>;
413
+ readonly onStepClick?: (stepIndex: number) => void;
414
+ readonly className?: string;
415
+ }
416
+ interface WorkflowNavigationRendererProps {
417
+ readonly currentStep: StepConfig;
418
+ readonly context: WorkflowContext;
419
+ readonly canGoNext: boolean;
420
+ readonly canGoPrevious: boolean;
421
+ readonly canSkip: boolean;
422
+ readonly isSubmitting: boolean;
423
+ readonly onNext: (event?: React.FormEvent) => void;
424
+ readonly onPrevious: (event?: React.FormEvent) => void;
425
+ readonly onSkip: (event?: React.FormEvent) => void;
426
+ readonly onSubmit: (event?: React.FormEvent) => void;
427
+ readonly className?: string;
428
+ }
429
+ type WorkflowStepperRenderer = (props: WorkflowStepperRendererProps) => React.ReactElement;
430
+ type WorkflowNavigationRenderer = (props: WorkflowNavigationRendererProps) => React.ReactElement;
431
+ interface WorkflowRenderConfig {
432
+ readonly stepperRenderer?: WorkflowStepperRenderer;
433
+ readonly navigationRenderer?: WorkflowNavigationRenderer;
434
+ }
435
+ interface FormRowRendererProps {
436
+ row: FormFieldRow;
437
+ children: React.ReactNode;
438
+ className?: string;
439
+ spacing?: 'tight' | 'normal' | 'loose';
440
+ alignment?: 'start' | 'center' | 'end' | 'stretch';
441
+ }
442
+ interface FormBodyRendererProps {
443
+ formConfig: FormConfiguration;
444
+ children: React.ReactNode;
445
+ className?: string;
446
+ }
447
+ interface FormSubmitButtonRendererProps {
448
+ isSubmitting: boolean;
449
+ isValid: boolean;
450
+ isDirty: boolean;
451
+ onSubmit: () => void;
452
+ className?: string;
453
+ children?: React.ReactNode;
454
+ }
455
+ type FormRowRenderer = (props: FormRowRendererProps) => React.ReactElement;
456
+ type FormBodyRenderer = (props: FormBodyRendererProps) => React.ReactElement;
457
+ type FormSubmitButtonRenderer = (props: FormSubmitButtonRendererProps) => React.ReactElement;
458
+ interface FormRenderConfig {
459
+ readonly rowRenderer?: FormRowRenderer;
460
+ readonly bodyRenderer?: FormBodyRenderer;
461
+ readonly submitButtonRenderer?: FormSubmitButtonRenderer;
462
+ }
463
+ interface FormConfiguration {
464
+ readonly id: string;
465
+ readonly schema?: any;
466
+ readonly config: ril;
467
+ readonly rows: FormFieldRow[];
468
+ readonly allFields: FormFieldConfig[];
469
+ readonly renderConfig?: FormRenderConfig;
470
+ }
471
+
472
+ /**
473
+ * Create a Zod-based validator
474
+ * @param schema - Zod schema to validate against
475
+ * @returns Validator function
476
+ */
477
+ declare const createZodValidator: <T>(schema: z.ZodSchema<T>) => ValidatorFunction;
478
+ /**
479
+ * Create a custom validator from a validation function
480
+ * @param validationFn - Function that returns boolean, string, or Promise
481
+ * @returns Validator function
482
+ */
483
+ declare const createCustomValidator: (validationFn: (value: any, context: ValidationContext) => boolean | string | Promise<boolean | string>) => ValidatorFunction;
484
+ /**
485
+ * Combine multiple validators
486
+ * @param validators - Array of validators to combine
487
+ * @param mode - 'all' (all must pass) or 'any' (at least one must pass)
488
+ * @returns Combined validator function
489
+ */
490
+ declare const combineValidators: (validators: ValidatorFunction[], mode?: "all" | "any") => ValidatorFunction;
491
+ /**
492
+ * Create a conditional validator that only runs when condition is met
493
+ * @param condition - Function to determine if validation should run
494
+ * @param validator - Validator to run when condition is true
495
+ * @returns Conditional validator function
496
+ */
497
+ declare const createConditionalValidator: (condition: (value: any, context: ValidationContext) => boolean, validator: ValidatorFunction) => ValidatorFunction;
498
+ /**
499
+ * Common validation patterns
500
+ */
501
+ declare const commonValidators: {
502
+ /**
503
+ * Required field validator
504
+ */
505
+ required: (message?: string) => ValidatorFunction;
506
+ /**
507
+ * Email validation
508
+ */
509
+ email: (message?: string) => ValidatorFunction;
510
+ /**
511
+ * Minimum length validation
512
+ */
513
+ minLength: (min: number, message?: string) => ValidatorFunction;
514
+ /**
515
+ * Maximum length validation
516
+ */
517
+ maxLength: (max: number, message?: string) => ValidatorFunction;
518
+ /**
519
+ * Pattern/regex validation
520
+ */
521
+ pattern: (regex: RegExp, message?: string) => ValidatorFunction;
522
+ /**
523
+ * Number range validation
524
+ */
525
+ numberRange: (min?: number, max?: number, message?: string) => ValidatorFunction;
526
+ /**
527
+ * URL validation
528
+ */
529
+ url: (message?: string) => ValidatorFunction;
530
+ /**
531
+ * Phone number validation (basic)
532
+ */
533
+ phoneNumber: (message?: string) => ValidatorFunction;
534
+ /**
535
+ * Custom async validation with debouncing
536
+ */
537
+ asyncValidation: (asyncFn: (value: any, context: ValidationContext) => Promise<boolean | string>, debounceMs?: number) => ValidatorFunction;
538
+ };
539
+ /**
540
+ * Utility to create validation result
541
+ * @param isValid - Whether validation passed
542
+ * @param errors - Array of errors (optional)
543
+ * @param warnings - Array of warnings (optional)
544
+ * @returns ValidationResult object
545
+ */
546
+ declare const createValidationResult: (isValid: boolean, errors?: ValidationError[], warnings?: ValidationError[]) => ValidationResult;
547
+ /**
548
+ * Utility to create validation error
549
+ * @param code - Error code
550
+ * @param message - Error message
551
+ * @param path - Error path (optional)
552
+ * @returns ValidationError object
553
+ */
554
+ declare const createValidationError: (code: string, message: string, path?: string[]) => ValidationError;
555
+
556
+ /**
557
+ * LocalStorage persistence adapter
558
+ * Perfect for client-side persistence across browser sessions
559
+ */
560
+ declare class LocalStorageAdapter implements PersistenceAdapter {
561
+ readonly name = "localStorage";
562
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
563
+ load(key: string): Promise<WorkflowPersistenceData | null>;
564
+ remove(key: string): Promise<void>;
565
+ exists(key: string): Promise<boolean>;
566
+ list(pattern?: string): Promise<string[]>;
567
+ }
568
+ /**
569
+ * SessionStorage persistence adapter
570
+ * Perfect for temporary persistence within a single browser session
571
+ */
572
+ declare class SessionStorageAdapter implements PersistenceAdapter {
573
+ readonly name = "sessionStorage";
574
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
575
+ load(key: string): Promise<WorkflowPersistenceData | null>;
576
+ remove(key: string): Promise<void>;
577
+ exists(key: string): Promise<boolean>;
578
+ list(pattern?: string): Promise<string[]>;
579
+ }
580
+ /**
581
+ * In-Memory persistence adapter
582
+ * Perfect for testing or temporary workflows
583
+ */
584
+ declare class MemoryAdapter implements PersistenceAdapter {
585
+ readonly name = "memory";
586
+ private storage;
587
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
588
+ load(key: string): Promise<WorkflowPersistenceData | null>;
589
+ remove(key: string): Promise<void>;
590
+ exists(key: string): Promise<boolean>;
591
+ list(pattern?: string): Promise<string[]>;
592
+ clear(): void;
593
+ }
594
+ /**
595
+ * Composite adapter that can use multiple adapters with fallback
596
+ * Perfect for robust persistence with primary/backup strategies
597
+ */
598
+ declare class CompositeAdapter implements PersistenceAdapter {
599
+ private primary;
600
+ private fallbacks;
601
+ readonly name = "composite";
602
+ constructor(primary: PersistenceAdapter, fallbacks?: PersistenceAdapter[]);
603
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
604
+ load(key: string): Promise<WorkflowPersistenceData | null>;
605
+ remove(key: string): Promise<void>;
606
+ exists(key: string): Promise<boolean>;
607
+ list(pattern?: string): Promise<string[]>;
608
+ }
609
+
610
+ /**
611
+ * Utility functions to create persistence configurations easily
612
+ */
613
+ declare const persistence: {
614
+ /**
615
+ * Create a localStorage-based persistence configuration
616
+ */
617
+ localStorage(options?: Partial<PersistenceConfig>): PersistenceConfig;
618
+ /**
619
+ * Create a sessionStorage-based persistence configuration
620
+ */
621
+ sessionStorage(options?: Partial<PersistenceConfig>): PersistenceConfig;
622
+ /**
623
+ * Create an in-memory persistence configuration (for testing)
624
+ */
625
+ memory(options?: Partial<PersistenceConfig>): PersistenceConfig;
626
+ /**
627
+ * Create a custom persistence configuration
628
+ */
629
+ custom(adapter: PersistenceAdapter, options?: Partial<PersistenceConfig>): PersistenceConfig;
630
+ };
631
+ /**
632
+ * Utility to create persistence configurations with retry logic
633
+ */
634
+ declare function createResilientPersistence(primary: PersistenceAdapter, fallback?: PersistenceAdapter, options?: Partial<PersistenceConfig>): PersistenceConfig;
635
+
636
+ export { type CompletionConfig, type ComponentConfig, type ComponentOptions, type ComponentRenderProps, type ComponentRenderer, type ComponentType, CompositeAdapter, type ConditionalBranch, type ConditionalConfig, type CustomStepRenderer, type DynamicStepConfig, type FormBodyRenderer, type FormBodyRendererProps, type FormConfiguration, type FormFieldConfig, type FormFieldRow, type FormRenderConfig, type FormRowRenderer, type FormRowRendererProps, type FormSubmitButtonRenderer, type FormSubmitButtonRendererProps, type InputType, type LayoutType, LocalStorageAdapter, MemoryAdapter, type NavigationConfig, type PersistenceAdapter, type PersistenceConfig, type RetryPolicy, type RilayLicenseConfig, SessionStorageAdapter, type StepConditionalConfig, type StepConfig, type StepLifecycleHooks, type StepPermissions, type StepValidationConfig, type ValidationConfig, type ValidationContext, type ValidationError, type ValidationResult, type ValidationWarning, type ValidatorFunction, type WorkflowAnalytics, type WorkflowConfig, type WorkflowContext, type WorkflowHooks, type WorkflowNavigationRenderer, type WorkflowNavigationRendererProps, type WorkflowOptimizations, type WorkflowPersistenceData, type WorkflowPlugin, type WorkflowRenderConfig, type WorkflowStepperRenderer, type WorkflowStepperRendererProps, type WorkflowVersion, combineValidators, commonValidators, createConditionalValidator, createCustomValidator, createResilientPersistence, createValidationError, createValidationResult, createZodValidator, persistence, ril };
@@ -0,0 +1,636 @@
1
+ import React from 'react';
2
+ import { z } from 'zod';
3
+
4
+ /**
5
+ * Main configuration class for Rilay form components and workflows
6
+ * Manages component registration, retrieval, and configuration
7
+ */
8
+ declare class ril {
9
+ private components;
10
+ private formRenderConfig;
11
+ private workflowRenderConfig;
12
+ static create(): ril;
13
+ /**
14
+ * Add a component to the configuration
15
+ * @param subType - The component subtype (e.g., 'text', 'email', 'heading')
16
+ * @param config - Component configuration without id and subType
17
+ * @returns The ril instance for chaining
18
+ */
19
+ addComponent<TProps = any>(subType: InputType | LayoutType, config: Omit<ComponentConfig<TProps>, 'id' | 'subType'> & {
20
+ id?: string;
21
+ }): this;
22
+ /**
23
+ * Set custom row renderer
24
+ * @param renderer - Custom row renderer function
25
+ * @returns The ril instance for chaining
26
+ */
27
+ setRowRenderer(renderer: FormRowRenderer): this;
28
+ /**
29
+ * Set custom body renderer
30
+ * @param renderer - Custom body renderer function
31
+ * @returns The ril instance for chaining
32
+ */
33
+ setBodyRenderer(renderer: FormBodyRenderer): this;
34
+ /**
35
+ * Set custom submit button renderer
36
+ * @param renderer - Custom submit button renderer function
37
+ * @returns The ril instance for chaining
38
+ */
39
+ setSubmitButtonRenderer(renderer: FormSubmitButtonRenderer): this;
40
+ /**
41
+ * Set complete form render configuration
42
+ * @param config - Form render configuration
43
+ * @returns The ril instance for chaining
44
+ */
45
+ setFormRenderConfig(config: FormRenderConfig): this;
46
+ /**
47
+ * Get current form render configuration
48
+ * @returns Current form render configuration
49
+ */
50
+ getFormRenderConfig(): FormRenderConfig;
51
+ /**
52
+ * Set custom stepper renderer for workflows
53
+ * @param renderer - Custom stepper renderer function
54
+ * @returns The ril instance for chaining
55
+ */
56
+ setStepperRenderer(renderer: WorkflowStepperRenderer): this;
57
+ /**
58
+ * Set custom workflow navigation renderer
59
+ * @param renderer - Custom workflow navigation renderer function
60
+ * @returns The ril instance for chaining
61
+ */
62
+ setWorkflowNavigationRenderer(renderer: WorkflowNavigationRenderer): this;
63
+ /**
64
+ * Set complete workflow render configuration
65
+ * @param config - Workflow render configuration
66
+ * @returns The ril instance for chaining
67
+ */
68
+ setWorkflowRenderConfig(config: WorkflowRenderConfig): this;
69
+ /**
70
+ * Get current workflow render configuration
71
+ * @returns Current workflow render configuration
72
+ */
73
+ getWorkflowRenderConfig(): WorkflowRenderConfig;
74
+ /**
75
+ * @deprecated Use setFormRenderConfig() instead
76
+ */
77
+ setRenderConfig(config: FormRenderConfig): this;
78
+ /**
79
+ * Get a component by its ID
80
+ * @param id - Component ID
81
+ * @returns Component configuration or undefined
82
+ */
83
+ getComponent(id: string): ComponentConfig | undefined;
84
+ /**
85
+ * List components by type (input or layout)
86
+ * @param type - Component type
87
+ * @returns Array of matching components
88
+ */
89
+ getComponentsByType(type: ComponentType): ComponentConfig[];
90
+ /**
91
+ * List components by sub-type
92
+ * @param subType - Component sub-type
93
+ * @returns Array of matching components
94
+ */
95
+ getComponentsBySubType(subType: InputType | LayoutType): ComponentConfig[];
96
+ /**
97
+ * Get components by category
98
+ * @param category - Component category
99
+ * @returns Array of matching components
100
+ */
101
+ getComponentsByCategory(category: string): ComponentConfig[];
102
+ /**
103
+ * List all registered components
104
+ * @returns Array of all components
105
+ */
106
+ getAllComponents(): ComponentConfig[];
107
+ /**
108
+ * Check if a component exists
109
+ * @param id - Component ID
110
+ * @returns True if component exists
111
+ */
112
+ hasComponent(id: string): boolean;
113
+ /**
114
+ * Remove a component from the configuration
115
+ * @param id - Component ID
116
+ * @returns True if component was removed
117
+ */
118
+ removeComponent(id: string): boolean;
119
+ /**
120
+ * Clear all components
121
+ */
122
+ clear(): void;
123
+ /**
124
+ * Export configuration as a plain object
125
+ * @returns Object with component configurations
126
+ */
127
+ export(): Record<string, ComponentConfig>;
128
+ /**
129
+ * Import configuration from a plain object
130
+ * @param config - Object with component configurations
131
+ * @returns The ril instance for chaining
132
+ */
133
+ import(config: Record<string, ComponentConfig>): this;
134
+ /**
135
+ * Get statistics about registered components and renderers
136
+ * @returns Object with comprehensive statistics
137
+ */
138
+ getStats(): {
139
+ total: number;
140
+ byType: Record<ComponentType, number>;
141
+ bySubType: Record<string, number>;
142
+ byCategory: Record<string, number>;
143
+ hasCustomRenderers: {
144
+ row: boolean;
145
+ body: boolean;
146
+ submitButton: boolean;
147
+ stepper: boolean;
148
+ workflowNavigation: boolean;
149
+ };
150
+ };
151
+ /**
152
+ * Validate the configuration
153
+ * @returns Array of validation errors
154
+ */
155
+ validate(): string[];
156
+ }
157
+
158
+ interface RilayLicenseConfig {
159
+ readonly licenseKey?: string;
160
+ readonly environment?: 'development' | 'production';
161
+ readonly allowTrial?: boolean;
162
+ }
163
+ type ComponentType = 'input' | 'layout';
164
+ type InputType = 'text' | 'email' | 'password' | 'number' | 'select' | 'checkbox' | 'textarea' | 'file' | 'date';
165
+ type LayoutType = 'heading' | 'paragraph' | 'container' | 'divider' | 'spacer' | 'alert';
166
+ interface ValidationResult {
167
+ readonly isValid: boolean;
168
+ readonly errors: ValidationError[];
169
+ readonly warnings?: ValidationWarning[];
170
+ }
171
+ interface ValidationError {
172
+ readonly code: string;
173
+ readonly message: string;
174
+ readonly path?: string[];
175
+ }
176
+ interface ValidationWarning {
177
+ readonly code: string;
178
+ readonly message: string;
179
+ readonly path?: string[];
180
+ }
181
+ interface ValidationContext {
182
+ readonly fieldId: string;
183
+ readonly formData: Record<string, any>;
184
+ readonly fieldProps: Record<string, any>;
185
+ readonly touched: boolean;
186
+ readonly dirty: boolean;
187
+ }
188
+ type ValidatorFunction<TProps = any> = (value: any, context: ValidationContext, props: TProps) => ValidationResult | Promise<ValidationResult>;
189
+ interface ValidationConfig<TProps = any> {
190
+ readonly validator?: ValidatorFunction<TProps>;
191
+ readonly debounceMs?: number;
192
+ readonly validateOnChange?: boolean;
193
+ readonly validateOnBlur?: boolean;
194
+ readonly validateOnSubmit?: boolean;
195
+ readonly dependencies?: string[];
196
+ }
197
+ type ComponentRenderer<TProps = any> = (props: ComponentRenderProps<TProps>) => React.ReactElement;
198
+ interface ComponentRenderProps<TProps = any> {
199
+ id: string;
200
+ props: TProps;
201
+ value?: any;
202
+ onChange?: (value: any) => void;
203
+ onBlur?: () => void;
204
+ error?: ValidationError[];
205
+ warnings?: ValidationWarning[];
206
+ touched?: boolean;
207
+ disabled?: boolean;
208
+ isValidating?: boolean;
209
+ [key: string]: any;
210
+ }
211
+ interface ComponentOptions<TProps = any> {
212
+ readonly configurable?: Array<{
213
+ key: keyof TProps;
214
+ type: 'string' | 'number' | 'boolean' | 'select' | 'array';
215
+ label: string;
216
+ options?: any[];
217
+ default?: any;
218
+ }>;
219
+ readonly previewProps?: Partial<TProps>;
220
+ readonly icon?: string;
221
+ readonly tags?: string[];
222
+ }
223
+ interface ComponentConfig<TProps = any> {
224
+ readonly id: string;
225
+ readonly type: ComponentType;
226
+ readonly subType: InputType | LayoutType;
227
+ readonly name: string;
228
+ readonly description?: string;
229
+ readonly category?: string;
230
+ readonly renderer: ComponentRenderer<TProps>;
231
+ readonly options?: ComponentOptions<TProps>;
232
+ readonly validation?: ValidationConfig<TProps>;
233
+ readonly defaultProps?: Partial<TProps>;
234
+ }
235
+ interface FormFieldConfig {
236
+ readonly id: string;
237
+ readonly componentId: string;
238
+ readonly props: Record<string, any>;
239
+ readonly validation?: ValidationConfig;
240
+ readonly conditional?: ConditionalConfig;
241
+ }
242
+ interface FormFieldRow {
243
+ readonly id: string;
244
+ readonly fields: FormFieldConfig[];
245
+ readonly maxColumns?: number;
246
+ readonly spacing?: 'tight' | 'normal' | 'loose';
247
+ readonly alignment?: 'start' | 'center' | 'end' | 'stretch';
248
+ }
249
+ interface ConditionalConfig {
250
+ readonly condition: (formData: Record<string, any>) => boolean;
251
+ readonly action: 'show' | 'hide' | 'disable' | 'require';
252
+ }
253
+ interface StepLifecycleHooks {
254
+ readonly onBeforeEnter?: (stepData: any, allData: any, context: WorkflowContext) => Promise<void>;
255
+ readonly onAfterLeave?: (stepData: any, allData: any, context: WorkflowContext) => Promise<boolean>;
256
+ readonly onValidate?: (stepData: any, context: WorkflowContext) => Promise<ValidationResult>;
257
+ readonly onTransform?: (stepData: any, context: WorkflowContext) => Promise<any>;
258
+ readonly onError?: (error: Error, context: WorkflowContext) => Promise<void>;
259
+ }
260
+ interface WorkflowContext {
261
+ readonly workflowId: string;
262
+ readonly currentStepIndex: number;
263
+ readonly totalSteps: number;
264
+ readonly allData: Record<string, any>;
265
+ readonly stepData: Record<string, any>;
266
+ readonly isFirstStep: boolean;
267
+ readonly isLastStep: boolean;
268
+ readonly visitedSteps: Set<string>;
269
+ readonly user?: any;
270
+ }
271
+ interface StepPermissions {
272
+ readonly requiredRoles?: string[];
273
+ readonly requiredPermissions?: string[];
274
+ readonly customGuard?: (user: any, context: WorkflowContext) => boolean | Promise<boolean>;
275
+ }
276
+ interface DynamicStepConfig {
277
+ readonly resolver: (previousData: any, context: WorkflowContext) => Promise<StepConfig[]>;
278
+ readonly cacheKey?: string;
279
+ readonly retryPolicy?: RetryPolicy;
280
+ }
281
+ interface RetryPolicy {
282
+ readonly maxRetries: number;
283
+ readonly delayMs: number;
284
+ readonly backoffMultiplier?: number;
285
+ }
286
+ interface ConditionalBranch {
287
+ readonly condition: (data: any, context: WorkflowContext) => boolean | Promise<boolean>;
288
+ readonly steps: StepConfig[];
289
+ readonly fallback?: StepConfig[];
290
+ }
291
+ interface StepConfig {
292
+ readonly id: string;
293
+ readonly title: string;
294
+ readonly description?: string;
295
+ readonly formConfig: FormConfiguration;
296
+ readonly validation?: StepValidationConfig;
297
+ readonly conditional?: StepConditionalConfig;
298
+ readonly allowSkip?: boolean;
299
+ readonly requiredToComplete?: boolean;
300
+ readonly hooks?: StepLifecycleHooks;
301
+ readonly permissions?: StepPermissions;
302
+ readonly isDynamic?: boolean;
303
+ readonly dynamicConfig?: DynamicStepConfig;
304
+ readonly renderer?: CustomStepRenderer;
305
+ }
306
+ interface StepValidationConfig {
307
+ readonly validator?: (stepData: Record<string, any>, allFormData: Record<string, any>, context: WorkflowContext) => ValidationResult | Promise<ValidationResult>;
308
+ readonly validateOnStepChange?: boolean;
309
+ readonly blockNextIfInvalid?: boolean;
310
+ }
311
+ interface StepConditionalConfig {
312
+ readonly condition: (formData: Record<string, any>, context: WorkflowContext) => boolean;
313
+ readonly action: 'show' | 'hide' | 'skip';
314
+ }
315
+ type CustomStepRenderer = (props: StepConfig) => React.ReactElement;
316
+ interface WorkflowPersistenceData {
317
+ readonly workflowId: string;
318
+ readonly currentStepIndex: number;
319
+ readonly allData: Record<string, any>;
320
+ readonly metadata: {
321
+ readonly timestamp: number;
322
+ readonly version?: string;
323
+ readonly userId?: string;
324
+ readonly sessionId?: string;
325
+ };
326
+ }
327
+ interface PersistenceAdapter {
328
+ readonly name: string;
329
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
330
+ load(key: string): Promise<WorkflowPersistenceData | null>;
331
+ remove(key: string): Promise<void>;
332
+ exists(key: string): Promise<boolean>;
333
+ list?(pattern?: string): Promise<string[]>;
334
+ }
335
+ interface PersistenceConfig {
336
+ readonly adapter: PersistenceAdapter;
337
+ readonly key?: string;
338
+ readonly debounceMs?: number;
339
+ readonly autoSave?: boolean;
340
+ readonly saveOnStepChange?: boolean;
341
+ readonly encryptionKey?: string;
342
+ readonly maxRetries?: number;
343
+ readonly retryDelayMs?: number;
344
+ readonly onSave?: (data: WorkflowPersistenceData) => Promise<void> | void;
345
+ readonly onLoad?: (data: WorkflowPersistenceData) => Promise<void> | void;
346
+ readonly onError?: (error: Error, operation: 'save' | 'load' | 'remove') => Promise<void> | void;
347
+ readonly onRetry?: (attempt: number, maxRetries: number, error: Error) => Promise<void> | void;
348
+ }
349
+ interface WorkflowAnalytics {
350
+ readonly onWorkflowStart?: (workflowId: string, context: WorkflowContext) => void;
351
+ readonly onWorkflowComplete?: (workflowId: string, duration: number, data: any) => void;
352
+ readonly onWorkflowAbandon?: (workflowId: string, currentStep: string, data: any) => void;
353
+ readonly onStepStart?: (stepId: string, timestamp: number, context: WorkflowContext) => void;
354
+ readonly onStepComplete?: (stepId: string, duration: number, data: any, context: WorkflowContext) => void;
355
+ readonly onStepSkip?: (stepId: string, reason: string, context: WorkflowContext) => void;
356
+ readonly onValidationError?: (stepId: string, errors: ValidationError[], context: WorkflowContext) => void;
357
+ readonly onError?: (error: Error, context: WorkflowContext) => void;
358
+ }
359
+ interface WorkflowOptimizations {
360
+ readonly preloadNextStep?: boolean;
361
+ readonly cacheValidation?: boolean;
362
+ readonly virtualizeSteps?: boolean;
363
+ readonly lazyLoadComponents?: boolean;
364
+ readonly maxConcurrentRequests?: number;
365
+ }
366
+ interface WorkflowVersion {
367
+ readonly version: string;
368
+ readonly migrationStrategy?: (oldData: any, newConfig: any) => any;
369
+ readonly compatibilityMode?: boolean;
370
+ }
371
+ interface WorkflowHooks {
372
+ readonly onStepChange?: (from: string, to: string, context: WorkflowContext) => void;
373
+ readonly onDataChange?: (data: any, context: WorkflowContext) => void;
374
+ readonly onValidation?: (result: ValidationResult, context: WorkflowContext) => void;
375
+ }
376
+ interface WorkflowPlugin {
377
+ readonly name: string;
378
+ readonly version?: string;
379
+ readonly install: (workflow: any) => void;
380
+ readonly hooks?: WorkflowHooks;
381
+ readonly dependencies?: string[];
382
+ }
383
+ interface WorkflowConfig {
384
+ readonly id: string;
385
+ readonly name: string;
386
+ readonly description?: string;
387
+ readonly steps: StepConfig[];
388
+ readonly branches?: ConditionalBranch[];
389
+ readonly navigation?: NavigationConfig;
390
+ readonly persistence?: PersistenceConfig;
391
+ readonly completion?: CompletionConfig;
392
+ readonly analytics?: WorkflowAnalytics;
393
+ readonly optimizations?: WorkflowOptimizations;
394
+ readonly version?: WorkflowVersion;
395
+ readonly plugins?: WorkflowPlugin[];
396
+ readonly renderConfig?: WorkflowRenderConfig;
397
+ }
398
+ interface NavigationConfig {
399
+ readonly allowBackNavigation?: boolean;
400
+ readonly allowStepSkipping?: boolean;
401
+ readonly showProgress?: boolean;
402
+ readonly customNavigation?: boolean;
403
+ }
404
+ interface CompletionConfig {
405
+ readonly onComplete?: (formData: Record<string, any>) => void | Promise<void>;
406
+ readonly confirmBeforeSubmit?: boolean;
407
+ readonly customCompletionStep?: any;
408
+ }
409
+ interface WorkflowStepperRendererProps {
410
+ readonly steps: StepConfig[];
411
+ readonly currentStepIndex: number;
412
+ readonly visitedSteps: Set<string>;
413
+ readonly onStepClick?: (stepIndex: number) => void;
414
+ readonly className?: string;
415
+ }
416
+ interface WorkflowNavigationRendererProps {
417
+ readonly currentStep: StepConfig;
418
+ readonly context: WorkflowContext;
419
+ readonly canGoNext: boolean;
420
+ readonly canGoPrevious: boolean;
421
+ readonly canSkip: boolean;
422
+ readonly isSubmitting: boolean;
423
+ readonly onNext: (event?: React.FormEvent) => void;
424
+ readonly onPrevious: (event?: React.FormEvent) => void;
425
+ readonly onSkip: (event?: React.FormEvent) => void;
426
+ readonly onSubmit: (event?: React.FormEvent) => void;
427
+ readonly className?: string;
428
+ }
429
+ type WorkflowStepperRenderer = (props: WorkflowStepperRendererProps) => React.ReactElement;
430
+ type WorkflowNavigationRenderer = (props: WorkflowNavigationRendererProps) => React.ReactElement;
431
+ interface WorkflowRenderConfig {
432
+ readonly stepperRenderer?: WorkflowStepperRenderer;
433
+ readonly navigationRenderer?: WorkflowNavigationRenderer;
434
+ }
435
+ interface FormRowRendererProps {
436
+ row: FormFieldRow;
437
+ children: React.ReactNode;
438
+ className?: string;
439
+ spacing?: 'tight' | 'normal' | 'loose';
440
+ alignment?: 'start' | 'center' | 'end' | 'stretch';
441
+ }
442
+ interface FormBodyRendererProps {
443
+ formConfig: FormConfiguration;
444
+ children: React.ReactNode;
445
+ className?: string;
446
+ }
447
+ interface FormSubmitButtonRendererProps {
448
+ isSubmitting: boolean;
449
+ isValid: boolean;
450
+ isDirty: boolean;
451
+ onSubmit: () => void;
452
+ className?: string;
453
+ children?: React.ReactNode;
454
+ }
455
+ type FormRowRenderer = (props: FormRowRendererProps) => React.ReactElement;
456
+ type FormBodyRenderer = (props: FormBodyRendererProps) => React.ReactElement;
457
+ type FormSubmitButtonRenderer = (props: FormSubmitButtonRendererProps) => React.ReactElement;
458
+ interface FormRenderConfig {
459
+ readonly rowRenderer?: FormRowRenderer;
460
+ readonly bodyRenderer?: FormBodyRenderer;
461
+ readonly submitButtonRenderer?: FormSubmitButtonRenderer;
462
+ }
463
+ interface FormConfiguration {
464
+ readonly id: string;
465
+ readonly schema?: any;
466
+ readonly config: ril;
467
+ readonly rows: FormFieldRow[];
468
+ readonly allFields: FormFieldConfig[];
469
+ readonly renderConfig?: FormRenderConfig;
470
+ }
471
+
472
+ /**
473
+ * Create a Zod-based validator
474
+ * @param schema - Zod schema to validate against
475
+ * @returns Validator function
476
+ */
477
+ declare const createZodValidator: <T>(schema: z.ZodSchema<T>) => ValidatorFunction;
478
+ /**
479
+ * Create a custom validator from a validation function
480
+ * @param validationFn - Function that returns boolean, string, or Promise
481
+ * @returns Validator function
482
+ */
483
+ declare const createCustomValidator: (validationFn: (value: any, context: ValidationContext) => boolean | string | Promise<boolean | string>) => ValidatorFunction;
484
+ /**
485
+ * Combine multiple validators
486
+ * @param validators - Array of validators to combine
487
+ * @param mode - 'all' (all must pass) or 'any' (at least one must pass)
488
+ * @returns Combined validator function
489
+ */
490
+ declare const combineValidators: (validators: ValidatorFunction[], mode?: "all" | "any") => ValidatorFunction;
491
+ /**
492
+ * Create a conditional validator that only runs when condition is met
493
+ * @param condition - Function to determine if validation should run
494
+ * @param validator - Validator to run when condition is true
495
+ * @returns Conditional validator function
496
+ */
497
+ declare const createConditionalValidator: (condition: (value: any, context: ValidationContext) => boolean, validator: ValidatorFunction) => ValidatorFunction;
498
+ /**
499
+ * Common validation patterns
500
+ */
501
+ declare const commonValidators: {
502
+ /**
503
+ * Required field validator
504
+ */
505
+ required: (message?: string) => ValidatorFunction;
506
+ /**
507
+ * Email validation
508
+ */
509
+ email: (message?: string) => ValidatorFunction;
510
+ /**
511
+ * Minimum length validation
512
+ */
513
+ minLength: (min: number, message?: string) => ValidatorFunction;
514
+ /**
515
+ * Maximum length validation
516
+ */
517
+ maxLength: (max: number, message?: string) => ValidatorFunction;
518
+ /**
519
+ * Pattern/regex validation
520
+ */
521
+ pattern: (regex: RegExp, message?: string) => ValidatorFunction;
522
+ /**
523
+ * Number range validation
524
+ */
525
+ numberRange: (min?: number, max?: number, message?: string) => ValidatorFunction;
526
+ /**
527
+ * URL validation
528
+ */
529
+ url: (message?: string) => ValidatorFunction;
530
+ /**
531
+ * Phone number validation (basic)
532
+ */
533
+ phoneNumber: (message?: string) => ValidatorFunction;
534
+ /**
535
+ * Custom async validation with debouncing
536
+ */
537
+ asyncValidation: (asyncFn: (value: any, context: ValidationContext) => Promise<boolean | string>, debounceMs?: number) => ValidatorFunction;
538
+ };
539
+ /**
540
+ * Utility to create validation result
541
+ * @param isValid - Whether validation passed
542
+ * @param errors - Array of errors (optional)
543
+ * @param warnings - Array of warnings (optional)
544
+ * @returns ValidationResult object
545
+ */
546
+ declare const createValidationResult: (isValid: boolean, errors?: ValidationError[], warnings?: ValidationError[]) => ValidationResult;
547
+ /**
548
+ * Utility to create validation error
549
+ * @param code - Error code
550
+ * @param message - Error message
551
+ * @param path - Error path (optional)
552
+ * @returns ValidationError object
553
+ */
554
+ declare const createValidationError: (code: string, message: string, path?: string[]) => ValidationError;
555
+
556
+ /**
557
+ * LocalStorage persistence adapter
558
+ * Perfect for client-side persistence across browser sessions
559
+ */
560
+ declare class LocalStorageAdapter implements PersistenceAdapter {
561
+ readonly name = "localStorage";
562
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
563
+ load(key: string): Promise<WorkflowPersistenceData | null>;
564
+ remove(key: string): Promise<void>;
565
+ exists(key: string): Promise<boolean>;
566
+ list(pattern?: string): Promise<string[]>;
567
+ }
568
+ /**
569
+ * SessionStorage persistence adapter
570
+ * Perfect for temporary persistence within a single browser session
571
+ */
572
+ declare class SessionStorageAdapter implements PersistenceAdapter {
573
+ readonly name = "sessionStorage";
574
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
575
+ load(key: string): Promise<WorkflowPersistenceData | null>;
576
+ remove(key: string): Promise<void>;
577
+ exists(key: string): Promise<boolean>;
578
+ list(pattern?: string): Promise<string[]>;
579
+ }
580
+ /**
581
+ * In-Memory persistence adapter
582
+ * Perfect for testing or temporary workflows
583
+ */
584
+ declare class MemoryAdapter implements PersistenceAdapter {
585
+ readonly name = "memory";
586
+ private storage;
587
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
588
+ load(key: string): Promise<WorkflowPersistenceData | null>;
589
+ remove(key: string): Promise<void>;
590
+ exists(key: string): Promise<boolean>;
591
+ list(pattern?: string): Promise<string[]>;
592
+ clear(): void;
593
+ }
594
+ /**
595
+ * Composite adapter that can use multiple adapters with fallback
596
+ * Perfect for robust persistence with primary/backup strategies
597
+ */
598
+ declare class CompositeAdapter implements PersistenceAdapter {
599
+ private primary;
600
+ private fallbacks;
601
+ readonly name = "composite";
602
+ constructor(primary: PersistenceAdapter, fallbacks?: PersistenceAdapter[]);
603
+ save(key: string, data: WorkflowPersistenceData): Promise<void>;
604
+ load(key: string): Promise<WorkflowPersistenceData | null>;
605
+ remove(key: string): Promise<void>;
606
+ exists(key: string): Promise<boolean>;
607
+ list(pattern?: string): Promise<string[]>;
608
+ }
609
+
610
+ /**
611
+ * Utility functions to create persistence configurations easily
612
+ */
613
+ declare const persistence: {
614
+ /**
615
+ * Create a localStorage-based persistence configuration
616
+ */
617
+ localStorage(options?: Partial<PersistenceConfig>): PersistenceConfig;
618
+ /**
619
+ * Create a sessionStorage-based persistence configuration
620
+ */
621
+ sessionStorage(options?: Partial<PersistenceConfig>): PersistenceConfig;
622
+ /**
623
+ * Create an in-memory persistence configuration (for testing)
624
+ */
625
+ memory(options?: Partial<PersistenceConfig>): PersistenceConfig;
626
+ /**
627
+ * Create a custom persistence configuration
628
+ */
629
+ custom(adapter: PersistenceAdapter, options?: Partial<PersistenceConfig>): PersistenceConfig;
630
+ };
631
+ /**
632
+ * Utility to create persistence configurations with retry logic
633
+ */
634
+ declare function createResilientPersistence(primary: PersistenceAdapter, fallback?: PersistenceAdapter, options?: Partial<PersistenceConfig>): PersistenceConfig;
635
+
636
+ export { type CompletionConfig, type ComponentConfig, type ComponentOptions, type ComponentRenderProps, type ComponentRenderer, type ComponentType, CompositeAdapter, type ConditionalBranch, type ConditionalConfig, type CustomStepRenderer, type DynamicStepConfig, type FormBodyRenderer, type FormBodyRendererProps, type FormConfiguration, type FormFieldConfig, type FormFieldRow, type FormRenderConfig, type FormRowRenderer, type FormRowRendererProps, type FormSubmitButtonRenderer, type FormSubmitButtonRendererProps, type InputType, type LayoutType, LocalStorageAdapter, MemoryAdapter, type NavigationConfig, type PersistenceAdapter, type PersistenceConfig, type RetryPolicy, type RilayLicenseConfig, SessionStorageAdapter, type StepConditionalConfig, type StepConfig, type StepLifecycleHooks, type StepPermissions, type StepValidationConfig, type ValidationConfig, type ValidationContext, type ValidationError, type ValidationResult, type ValidationWarning, type ValidatorFunction, type WorkflowAnalytics, type WorkflowConfig, type WorkflowContext, type WorkflowHooks, type WorkflowNavigationRenderer, type WorkflowNavigationRendererProps, type WorkflowOptimizations, type WorkflowPersistenceData, type WorkflowPlugin, type WorkflowRenderConfig, type WorkflowStepperRenderer, type WorkflowStepperRendererProps, type WorkflowVersion, combineValidators, commonValidators, createConditionalValidator, createCustomValidator, createResilientPersistence, createValidationError, createValidationResult, createZodValidator, persistence, ril };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';var zod=require('zod');var y=class o{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new o}addComponent(e,r){let t=r.id||`${r.type}-${e}-${Date.now()}`,n={id:t,subType:e,...r};return this.components.set(t,n),this}setRowRenderer(e){return this.formRenderConfig={...this.formRenderConfig,rowRenderer:e},this}setBodyRenderer(e){return this.formRenderConfig={...this.formRenderConfig,bodyRenderer:e},this}setSubmitButtonRenderer(e){return this.formRenderConfig={...this.formRenderConfig,submitButtonRenderer:e},this}setFormRenderConfig(e){return this.formRenderConfig=e,this}getFormRenderConfig(){return {...this.formRenderConfig}}setStepperRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,stepperRenderer:e},this}setWorkflowNavigationRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,navigationRenderer:e},this}setWorkflowRenderConfig(e){return this.workflowRenderConfig=e,this}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}setRenderConfig(e){return this.setFormRenderConfig(e)}getComponent(e){return this.components.get(e)}getComponentsByType(e){return Array.from(this.components.values()).filter(r=>r.type===e)}getComponentsBySubType(e){return Array.from(this.components.values()).filter(r=>r.subType===e)}getComponentsByCategory(e){return Array.from(this.components.values()).filter(r=>r.category===e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){return this.components.delete(e)}clear(){this.components.clear();}export(){return Object.fromEntries(this.components)}import(e){for(let[r,t]of Object.entries(e))this.components.set(r,t);return this}getStats(){let e=Array.from(this.components.values());return {total:e.length,byType:e.reduce((r,t)=>(r[t.type]=(r[t.type]||0)+1,r),{}),bySubType:e.reduce((r,t)=>(r[t.subType]=(r[t.subType]||0)+1,r),{}),byCategory:e.reduce((r,t)=>{let n=t.category||"uncategorized";return r[n]=(r[n]||0)+1,r},{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNavigation:!!this.workflowRenderConfig.navigationRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(s=>s.id),n=t.filter((s,i)=>t.indexOf(s)!==i);n.length>0&&e.push(`Duplicate component IDs found: ${n.join(", ")}`);let a=r.filter(s=>!s.renderer);return a.length>0&&e.push(`Components without renderer: ${a.map(s=>s.id).join(", ")}`),e}};var m=o=>async e=>{try{return await o.parseAsync(e),{isValid:!0,errors:[]}}catch(r){return r&&typeof r=="object"&&"errors"in r&&Array.isArray(r.errors)?{isValid:false,errors:r.errors.map(t=>({code:t.code,message:t.message,path:t.path?t.path.map(String):[]}))}:{isValid:false,errors:[{code:"unknown",message:r instanceof Error?r.message:"Unknown validation error"}]}}},w=o=>async(e,r,t)=>{try{let n=await o(e,r);return n===!0?{isValid:!0,errors:[]}:n===!1?{isValid:!1,errors:[{code:"validation_failed",message:"Validation failed"}]}:{isValid:!1,errors:[{code:"validation_failed",message:String(n)}]}}catch(n){return {isValid:false,errors:[{code:"validation_error",message:n instanceof Error?n.message:"Validation error"}]}}},b=(o,e="all")=>async(r,t,n)=>{let a=await Promise.all(o.map(l=>l(r,t,n)));if(e==="all"){let l=a.flatMap(u=>u.errors),c=a.flatMap(u=>u.warnings||[]);return {isValid:a.every(u=>u.isValid),errors:l,warnings:c.length>0?c:void 0}}if(a.some(l=>l.isValid)){let l=a.flatMap(c=>c.warnings||[]);return {isValid:true,errors:[],warnings:l.length>0?l:void 0}}return {isValid:false,errors:a.flatMap(l=>l.errors)}},v=(o,e)=>async(r,t,n)=>o(r,t)?e(r,t,n):{isValid:true,errors:[]},P={required:(o="This field is required")=>w(e=>e==null||e===""?o:!0),email:(o="Invalid email format")=>m(zod.z.string().email(o)),minLength:(o,e)=>m(zod.z.string().min(o,e||`Minimum ${o} characters required`)),maxLength:(o,e)=>m(zod.z.string().max(o,e||`Maximum ${o} characters allowed`)),pattern:(o,e="Invalid format")=>m(zod.z.string().regex(o,e)),numberRange:(o,e,r)=>{let t=zod.z.number();return o!==void 0&&(t=t.min(o,r||`Value must be at least ${o}`)),e!==void 0&&(t=t.max(e,r||`Value must be at most ${e}`)),m(t)},url:(o="Invalid URL format")=>m(zod.z.string().url(o)),phoneNumber:(o="Invalid phone number format")=>m(zod.z.string().regex(/^\+?[\d\s\-\(\)]+$/,o)),asyncValidation:(o,e=300)=>{let r=new Map;return (t,n,a)=>new Promise(s=>{let i=`${n.fieldId}-${JSON.stringify(t)}`;r.has(i)&&clearTimeout(r.get(i));let l=setTimeout(async()=>{try{let c=await o(t,n);s(c===!0?{isValid:!0,errors:[]}:{isValid:!1,errors:[{code:"async_validation_failed",message:typeof c=="string"?c:"Async validation failed"}]});}catch(c){s({isValid:false,errors:[{code:"async_validation_error",message:c instanceof Error?c.message:"Async validation error"}]});}finally{r.delete(i);}},e);r.set(i,l);})}},k=(o,e=[],r)=>({isValid:o,errors:e,warnings:r}),V=(o,e,r)=>({code:o,message:e,path:r});var g=class{constructor(){this.name="localStorage";}async save(e,r){try{localStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to localStorage: ${t}`)}}async load(e){try{let r=localStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from localStorage: ${r}`)}}async remove(e){try{localStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from localStorage: ${r}`)}}async exists(e){return localStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},p=class{constructor(){this.name="sessionStorage";}async save(e,r){try{sessionStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to sessionStorage: ${t}`)}}async load(e){try{let r=sessionStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from sessionStorage: ${r}`)}}async remove(e){try{sessionStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from sessionStorage: ${r}`)}}async exists(e){return sessionStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},f=class{constructor(){this.name="memory";this.storage=new Map;}async save(e,r){this.storage.set(e,{...r});}async load(e){let r=this.storage.get(e);return r?{...r}:null}async remove(e){this.storage.delete(e);}async exists(e){return this.storage.has(e)}async list(e){let r=Array.from(this.storage.keys());return e?r.filter(t=>t.includes(e)):r}clear(){this.storage.clear();}},h=class{constructor(e,r=[]){this.primary=e;this.fallbacks=r;this.name="composite";}async save(e,r){let t=[this.primary,...this.fallbacks];for(let n of t)try{await n.save(e,r);return}catch(a){console.warn(`Failed to save with ${n.name}:`,a);}throw new Error("All persistence adapters failed to save")}async load(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{let n=await t.load(e);if(n)return n}catch(n){console.warn(`Failed to load with ${t.name}:`,n);}return null}async remove(e){let r=[this.primary,...this.fallbacks],t=[];for(let n of r)try{await n.remove(e);}catch(a){t.push(a);}if(t.length===r.length)throw new Error(`All adapters failed to remove: ${t.map(n=>n.message).join(", ")}`)}async exists(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{if(await t.exists(e))return !0}catch(n){console.warn(`Failed to check existence with ${t.name}:`,n);}return false}async list(e){try{return await this.primary.list?.(e)||[]}catch(r){console.warn("Failed to list with primary adapter:",r);for(let t of this.fallbacks)try{return await t.list?.(e)||[]}catch(n){console.warn(`Failed to list with fallback ${t.name}:`,n);}return []}}};var E={localStorage(o={}){return {adapter:new g,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},sessionStorage(o={}){return {adapter:new p,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},memory(o={}){return {adapter:new f,debounceMs:0,autoSave:true,saveOnStepChange:true,...o}},custom(o,e={}){return {adapter:o,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...e}}};function T(o,e,r={}){let t=e||new f;return {adapter:{name:`resilient-${o.name}`,async save(a,s){try{await o.save(a,s);}catch(i){console.warn("Primary persistence failed, using fallback:",i),await t.save(a,s);}},async load(a){try{let s=await o.load(a);if(s)return s}catch(s){console.warn("Primary persistence load failed, trying fallback:",s);}return await t.load(a)},async remove(a){let s=[];try{await o.remove(a);}catch(i){s.push(i);}try{await t.remove(a);}catch(i){s.push(i);}if(s.length===2)throw new Error(`Both adapters failed: ${s.map(i=>i.message).join(", ")}`)},async exists(a){try{if(await o.exists(a))return !0}catch(s){console.warn("Primary persistence exists check failed:",s);}try{return await t.exists(a)}catch(s){return console.warn("Fallback persistence exists check failed:",s),false}},async list(a){try{return await o.list?.(a)||[]}catch(s){console.warn("Primary persistence list failed:",s);try{return await t.list?.(a)||[]}catch(i){return console.warn("Fallback persistence list failed:",i),[]}}}},debounceMs:1e3,autoSave:true,saveOnStepChange:true,maxRetries:3,retryDelayMs:1e3,...r}}exports.CompositeAdapter=h;exports.LocalStorageAdapter=g;exports.MemoryAdapter=f;exports.SessionStorageAdapter=p;exports.combineValidators=b;exports.commonValidators=P;exports.createConditionalValidator=v;exports.createCustomValidator=w;exports.createResilientPersistence=T;exports.createValidationError=V;exports.createValidationResult=k;exports.createZodValidator=m;exports.persistence=E;exports.ril=y;
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import {z}from'zod';var y=class o{constructor(){this.components=new Map;this.formRenderConfig={};this.workflowRenderConfig={};}static create(){return new o}addComponent(e,r){let t=r.id||`${r.type}-${e}-${Date.now()}`,n={id:t,subType:e,...r};return this.components.set(t,n),this}setRowRenderer(e){return this.formRenderConfig={...this.formRenderConfig,rowRenderer:e},this}setBodyRenderer(e){return this.formRenderConfig={...this.formRenderConfig,bodyRenderer:e},this}setSubmitButtonRenderer(e){return this.formRenderConfig={...this.formRenderConfig,submitButtonRenderer:e},this}setFormRenderConfig(e){return this.formRenderConfig=e,this}getFormRenderConfig(){return {...this.formRenderConfig}}setStepperRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,stepperRenderer:e},this}setWorkflowNavigationRenderer(e){return this.workflowRenderConfig={...this.workflowRenderConfig,navigationRenderer:e},this}setWorkflowRenderConfig(e){return this.workflowRenderConfig=e,this}getWorkflowRenderConfig(){return {...this.workflowRenderConfig}}setRenderConfig(e){return this.setFormRenderConfig(e)}getComponent(e){return this.components.get(e)}getComponentsByType(e){return Array.from(this.components.values()).filter(r=>r.type===e)}getComponentsBySubType(e){return Array.from(this.components.values()).filter(r=>r.subType===e)}getComponentsByCategory(e){return Array.from(this.components.values()).filter(r=>r.category===e)}getAllComponents(){return Array.from(this.components.values())}hasComponent(e){return this.components.has(e)}removeComponent(e){return this.components.delete(e)}clear(){this.components.clear();}export(){return Object.fromEntries(this.components)}import(e){for(let[r,t]of Object.entries(e))this.components.set(r,t);return this}getStats(){let e=Array.from(this.components.values());return {total:e.length,byType:e.reduce((r,t)=>(r[t.type]=(r[t.type]||0)+1,r),{}),bySubType:e.reduce((r,t)=>(r[t.subType]=(r[t.subType]||0)+1,r),{}),byCategory:e.reduce((r,t)=>{let n=t.category||"uncategorized";return r[n]=(r[n]||0)+1,r},{}),hasCustomRenderers:{row:!!this.formRenderConfig.rowRenderer,body:!!this.formRenderConfig.bodyRenderer,submitButton:!!this.formRenderConfig.submitButtonRenderer,stepper:!!this.workflowRenderConfig.stepperRenderer,workflowNavigation:!!this.workflowRenderConfig.navigationRenderer}}}validate(){let e=[],r=Array.from(this.components.values()),t=r.map(s=>s.id),n=t.filter((s,i)=>t.indexOf(s)!==i);n.length>0&&e.push(`Duplicate component IDs found: ${n.join(", ")}`);let a=r.filter(s=>!s.renderer);return a.length>0&&e.push(`Components without renderer: ${a.map(s=>s.id).join(", ")}`),e}};var m=o=>async e=>{try{return await o.parseAsync(e),{isValid:!0,errors:[]}}catch(r){return r&&typeof r=="object"&&"errors"in r&&Array.isArray(r.errors)?{isValid:false,errors:r.errors.map(t=>({code:t.code,message:t.message,path:t.path?t.path.map(String):[]}))}:{isValid:false,errors:[{code:"unknown",message:r instanceof Error?r.message:"Unknown validation error"}]}}},w=o=>async(e,r,t)=>{try{let n=await o(e,r);return n===!0?{isValid:!0,errors:[]}:n===!1?{isValid:!1,errors:[{code:"validation_failed",message:"Validation failed"}]}:{isValid:!1,errors:[{code:"validation_failed",message:String(n)}]}}catch(n){return {isValid:false,errors:[{code:"validation_error",message:n instanceof Error?n.message:"Validation error"}]}}},b=(o,e="all")=>async(r,t,n)=>{let a=await Promise.all(o.map(l=>l(r,t,n)));if(e==="all"){let l=a.flatMap(u=>u.errors),c=a.flatMap(u=>u.warnings||[]);return {isValid:a.every(u=>u.isValid),errors:l,warnings:c.length>0?c:void 0}}if(a.some(l=>l.isValid)){let l=a.flatMap(c=>c.warnings||[]);return {isValid:true,errors:[],warnings:l.length>0?l:void 0}}return {isValid:false,errors:a.flatMap(l=>l.errors)}},v=(o,e)=>async(r,t,n)=>o(r,t)?e(r,t,n):{isValid:true,errors:[]},P={required:(o="This field is required")=>w(e=>e==null||e===""?o:!0),email:(o="Invalid email format")=>m(z.string().email(o)),minLength:(o,e)=>m(z.string().min(o,e||`Minimum ${o} characters required`)),maxLength:(o,e)=>m(z.string().max(o,e||`Maximum ${o} characters allowed`)),pattern:(o,e="Invalid format")=>m(z.string().regex(o,e)),numberRange:(o,e,r)=>{let t=z.number();return o!==void 0&&(t=t.min(o,r||`Value must be at least ${o}`)),e!==void 0&&(t=t.max(e,r||`Value must be at most ${e}`)),m(t)},url:(o="Invalid URL format")=>m(z.string().url(o)),phoneNumber:(o="Invalid phone number format")=>m(z.string().regex(/^\+?[\d\s\-\(\)]+$/,o)),asyncValidation:(o,e=300)=>{let r=new Map;return (t,n,a)=>new Promise(s=>{let i=`${n.fieldId}-${JSON.stringify(t)}`;r.has(i)&&clearTimeout(r.get(i));let l=setTimeout(async()=>{try{let c=await o(t,n);s(c===!0?{isValid:!0,errors:[]}:{isValid:!1,errors:[{code:"async_validation_failed",message:typeof c=="string"?c:"Async validation failed"}]});}catch(c){s({isValid:false,errors:[{code:"async_validation_error",message:c instanceof Error?c.message:"Async validation error"}]});}finally{r.delete(i);}},e);r.set(i,l);})}},k=(o,e=[],r)=>({isValid:o,errors:e,warnings:r}),V=(o,e,r)=>({code:o,message:e,path:r});var g=class{constructor(){this.name="localStorage";}async save(e,r){try{localStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to localStorage: ${t}`)}}async load(e){try{let r=localStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from localStorage: ${r}`)}}async remove(e){try{localStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from localStorage: ${r}`)}}async exists(e){return localStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},p=class{constructor(){this.name="sessionStorage";}async save(e,r){try{sessionStorage.setItem(e,JSON.stringify(r));}catch(t){throw new Error(`Failed to save to sessionStorage: ${t}`)}}async load(e){try{let r=sessionStorage.getItem(e);return r?JSON.parse(r):null}catch(r){throw new Error(`Failed to load from sessionStorage: ${r}`)}}async remove(e){try{sessionStorage.removeItem(e);}catch(r){throw new Error(`Failed to remove from sessionStorage: ${r}`)}}async exists(e){return sessionStorage.getItem(e)!==null}async list(e){let r=[];for(let t=0;t<sessionStorage.length;t++){let n=sessionStorage.key(t);n&&(!e||n.includes(e))&&r.push(n);}return r}},f=class{constructor(){this.name="memory";this.storage=new Map;}async save(e,r){this.storage.set(e,{...r});}async load(e){let r=this.storage.get(e);return r?{...r}:null}async remove(e){this.storage.delete(e);}async exists(e){return this.storage.has(e)}async list(e){let r=Array.from(this.storage.keys());return e?r.filter(t=>t.includes(e)):r}clear(){this.storage.clear();}},h=class{constructor(e,r=[]){this.primary=e;this.fallbacks=r;this.name="composite";}async save(e,r){let t=[this.primary,...this.fallbacks];for(let n of t)try{await n.save(e,r);return}catch(a){console.warn(`Failed to save with ${n.name}:`,a);}throw new Error("All persistence adapters failed to save")}async load(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{let n=await t.load(e);if(n)return n}catch(n){console.warn(`Failed to load with ${t.name}:`,n);}return null}async remove(e){let r=[this.primary,...this.fallbacks],t=[];for(let n of r)try{await n.remove(e);}catch(a){t.push(a);}if(t.length===r.length)throw new Error(`All adapters failed to remove: ${t.map(n=>n.message).join(", ")}`)}async exists(e){let r=[this.primary,...this.fallbacks];for(let t of r)try{if(await t.exists(e))return !0}catch(n){console.warn(`Failed to check existence with ${t.name}:`,n);}return false}async list(e){try{return await this.primary.list?.(e)||[]}catch(r){console.warn("Failed to list with primary adapter:",r);for(let t of this.fallbacks)try{return await t.list?.(e)||[]}catch(n){console.warn(`Failed to list with fallback ${t.name}:`,n);}return []}}};var E={localStorage(o={}){return {adapter:new g,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},sessionStorage(o={}){return {adapter:new p,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...o}},memory(o={}){return {adapter:new f,debounceMs:0,autoSave:true,saveOnStepChange:true,...o}},custom(o,e={}){return {adapter:o,debounceMs:1e3,autoSave:true,saveOnStepChange:true,...e}}};function T(o,e,r={}){let t=e||new f;return {adapter:{name:`resilient-${o.name}`,async save(a,s){try{await o.save(a,s);}catch(i){console.warn("Primary persistence failed, using fallback:",i),await t.save(a,s);}},async load(a){try{let s=await o.load(a);if(s)return s}catch(s){console.warn("Primary persistence load failed, trying fallback:",s);}return await t.load(a)},async remove(a){let s=[];try{await o.remove(a);}catch(i){s.push(i);}try{await t.remove(a);}catch(i){s.push(i);}if(s.length===2)throw new Error(`Both adapters failed: ${s.map(i=>i.message).join(", ")}`)},async exists(a){try{if(await o.exists(a))return !0}catch(s){console.warn("Primary persistence exists check failed:",s);}try{return await t.exists(a)}catch(s){return console.warn("Fallback persistence exists check failed:",s),false}},async list(a){try{return await o.list?.(a)||[]}catch(s){console.warn("Primary persistence list failed:",s);try{return await t.list?.(a)||[]}catch(i){return console.warn("Fallback persistence list failed:",i),[]}}}},debounceMs:1e3,autoSave:true,saveOnStepChange:true,maxRetries:3,retryDelayMs:1e3,...r}}export{h as CompositeAdapter,g as LocalStorageAdapter,f as MemoryAdapter,p as SessionStorageAdapter,b as combineValidators,P as commonValidators,v as createConditionalValidator,w as createCustomValidator,T as createResilientPersistence,V as createValidationError,k as createValidationResult,m as createZodValidator,E as persistence,y as ril};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@rilaykit/core",
3
+ "version": "0.1.1-alpha.1",
4
+ "description": "Core types, configurations, and utilities for the RilayKit form library",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "keywords": [
11
+ "react",
12
+ "forms",
13
+ "typescript",
14
+ "validation",
15
+ "builder-pattern"
16
+ ],
17
+ "author": "Rilay Team",
18
+ "license": "MIT",
19
+ "peerDependencies": {
20
+ "react": ">=18.0.0",
21
+ "typescript": ">=5.0.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/react": "^18.3.23",
25
+ "react": "^19.1.0",
26
+ "typescript": "^5.3.0"
27
+ },
28
+ "dependencies": {
29
+ "zod": "^3.22.4"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "scripts": {
35
+ "build": "tsup",
36
+ "dev": "tsup --watch",
37
+ "test": "vitest",
38
+ "test:run": "vitest run",
39
+ "test:ui": "vitest --ui",
40
+ "lint": "biome check .",
41
+ "lint:fix": "biome check --write .",
42
+ "type-check": "tsc --noEmit",
43
+ "clean": "rm -rf dist"
44
+ }
45
+ }