UNPKG

@rilaykit/workflow

Version:

Commercial workflow and multi-step form utilities for RilayKit - License required for all use

1,149 lines (1,123 loc) 40.8 kB
import { ril, FormConfiguration, CustomStepRenderer, StepConditionalBehavior, StepDataHelper, WorkflowContext, WorkflowAnalytics, WorkflowPlugin, StepConfig, WorkflowConfig, ConditionalBehavior, ComponentRendererBaseProps, WorkflowNextButtonRendererProps, WorkflowPreviousButtonRendererProps, WorkflowSkipButtonRendererProps, WorkflowStepperRendererProps } from '@rilaykit/core'; export * from '@rilaykit/core'; import { form } from '@rilaykit/forms'; export { form } from '@rilaykit/forms'; import * as react_jsx_runtime from 'react/jsx-runtime'; import React$1 from 'react'; /** * Enhanced step configuration interface for better type safety and simplicity * * This interface defines the structure for creating workflow steps with all * necessary configuration options. It provides a clean API for step definition * while maintaining flexibility for complex workflows. * * @interface StepDefinition */ interface StepDefinition { /** * Unique identifier for the step * If not provided, will be auto-generated using the internal ID generator */ id?: string; /** * Display title for the step * This will be shown to users in the workflow interface */ title: string; /** * Optional description providing additional context about the step * Useful for complex workflows where steps need explanation */ description?: string; /** * Form configuration for the step * Can be either a built FormConfiguration or a form builder instance */ formConfig: FormConfiguration | form; /** * Whether users can skip this step * @default false */ allowSkip?: boolean; /** * Whether this step is required to complete the workflow * @default true */ requiredToComplete?: boolean; /** * Custom renderer for the step * Allows complete customization of step presentation */ renderer?: CustomStepRenderer; /** * Conditional behavior configuration for this step * Controls visibility and skippable state */ conditions?: StepConditionalBehavior; /** * Callback function that executes after successful validation and before moving to next step * Provides clean helper methods for modifying workflow data and pre-filling subsequent steps * * @param stepData - The validated data from the current step * @param helper - Helper object with methods to modify workflow data cleanly * @param context - Full workflow context for reference * * @example * ```typescript * onAfterValidation: async (stepData, helper, context) => { * // API call based on current step data * const companyInfo = await fetchCompanyBySiren(stepData.siren); * * // Pre-fill next step with clean helper methods * helper.setNextStepFields({ * companyName: companyInfo.name, * address: companyInfo.address, * industry: companyInfo.sector * }); * * // Or set data for a specific step * helper.setStepFields('company-details', { * legalForm: companyInfo.legalForm, * foundedYear: companyInfo.creation_date * }); * } * ``` */ onAfterValidation?: (stepData: Record<string, any>, helper: StepDataHelper, context: WorkflowContext) => void | Promise<void>; } /** * Configuration options for workflow behavior and features * * This interface consolidates all workflow-level configuration options * into a single, easy-to-use structure for the configure() method. * * @interface WorkflowOptions */ interface WorkflowOptions { /** Analytics and tracking configuration */ analytics?: WorkflowAnalytics; } /** * Workflow builder class for creating complex multi-step workflows * * The flow class provides a comprehensive API for building multi-step workflows * with form-based steps. It follows the builder pattern with method chaining * and includes advanced features like dynamic steps, plugins, and analytics. * * Key Features: * - Polymorphic step addition (single or multiple steps) * - Plugin system for extensibility * - Built-in validation and error handling * - Clone and export/import functionality * - Comprehensive statistics and analytics * - Type-safe configuration management * * @example * ```typescript * const workflow = flow.create(rilConfig, 'user-onboarding', 'User Onboarding') * .addStep({ * title: 'Personal Information', * formConfig: personalInfoForm * }) * .addStep({ * title: 'Account Setup', * formConfig: accountForm, * allowSkip: true * }) * .configure({ * navigation: { allowBackNavigation: true }, * persistence: { saveOnStepComplete: true } * }) * .build(); * ``` * * @class flow */ declare class flow { private config; private workflowId; private workflowName; private workflowDescription?; private steps; private analytics?; private plugins; private idGenerator; /** * Creates a new workflow builder instance * * @param config - The ril configuration instance * @param workflowId - Unique identifier for the workflow * @param workflowName - Display name for the workflow * @param description - Optional description of the workflow purpose */ constructor(config: ril, workflowId: string, workflowName: string, description?: string); /** * Static factory method to create a new workflow builder * * This is the preferred way to create workflow builders as it provides * better type inference and follows the factory pattern. * * @param config - The ril configuration instance * @param workflowId - Unique identifier for the workflow * @param workflowName - Display name for the workflow * @param description - Optional description of the workflow purpose * @returns A new flow builder instance * * @example * ```typescript * const workflow = flow.create(rilConfig, 'checkout', 'Checkout Process'); * ``` */ static create(config: ril, workflowId: string, workflowName: string, description?: string): flow; /** * Helper method to create a step configuration from StepDefinition * * This internal method handles the conversion from the user-friendly * StepDefinition interface to the internal StepConfig structure, * including ID generation, form configuration processing, and validation setup. * * @private * @param stepDef - The step definition to convert * @returns A complete StepConfig object */ private createStepFromDefinition; /** * Universal add method - handles single steps or multiple steps * * This polymorphic method provides a clean API for adding steps to the workflow. * It can handle both single step definitions and arrays of step definitions, * making it easy to build workflows programmatically. * * @param stepDefinition - Single step definition * @returns The flow instance for method chaining * * @example * ```typescript * // Add a single step * workflow.addStep({ * title: 'User Details', * formConfig: userForm * }); * ``` */ addStep(stepDefinition: StepDefinition): this; /** * Universal add method - handles single steps or multiple steps * * @param stepDefinitions - Array of step definitions * @returns The flow instance for method chaining * * @example * ```typescript * // Add multiple steps at once * workflow.addStep([ * { title: 'Step 1', formConfig: form1 }, * { title: 'Step 2', formConfig: form2 } * ]); * ``` */ addStep(stepDefinitions: StepDefinition[]): this; /** * Universal configuration method for all workflow options * * This method replaces individual setter methods with a single consolidated API * for configuring all aspects of workflow behavior. It uses deep merging to * preserve existing configurations while applying new settings. * * @param options - Configuration options to apply * @returns The flow instance for method chaining * * @example * ```typescript * workflow.configure({ * navigation: { * allowBackNavigation: true, * showProgressBar: true * }, * persistence: { * saveOnStepComplete: true, * storageKey: 'my-workflow' * }, * analytics: { * trackStepCompletion: true, * trackFieldInteractions: false * } * }); * ``` */ configure(options: WorkflowOptions): this; /** * Plugin management with enhanced validation * * Installs a plugin into the workflow with dependency validation. * Plugins can extend workflow functionality, add custom renderers, * or integrate with external services. * * @param plugin - The plugin to install * @returns The flow instance for method chaining * @throws Error if plugin installation fails or dependencies are missing * * @example * ```typescript * workflow.use(customPlugin) * .use(anotherPlugin); * ``` */ use(plugin: WorkflowPlugin): this; /** * Validates plugin dependencies before installation * * @private * @param plugin - The plugin to validate * @throws Error if required dependencies are missing */ private validatePluginDependencies; /** * Remove a plugin from the workflow * * @param pluginName - Name of the plugin to remove * @returns The flow instance for method chaining * * @example * ```typescript * workflow.removePlugin('analytics-plugin'); * ``` */ removePlugin(pluginName: string): this; /** * Update an existing step configuration * * Allows modification of step properties after the step has been added. * Useful for dynamic workflows or configuration updates based on user input. * * @param stepId - ID of the step to update * @param updates - Partial step configuration updates * @returns The flow instance for method chaining * @throws Error if step with given ID is not found * * @example * ```typescript * workflow.updateStep('step-1', { * title: 'Updated Title', * allowSkip: true * }); * ``` */ updateStep(stepId: string, updates: Partial<Omit<StepConfig, 'id'>>): this; /** * Adds conditions to a specific step by ID * * This method allows adding conditional behavior to a step after it has been created, * useful for dynamic conditional requirements. * * @param stepId - The ID of the step to add conditions to * @param conditions - Conditional behavior configuration * @returns The flow instance for method chaining * @throws Error if the step with the specified ID is not found * * @example * ```typescript * workflow.addStepConditions('payment-step', { * visible: when('hasPayment').equals(true).build(), * skippable: when('balance').equals(0).build() * }); * ``` */ addStepConditions(stepId: string, conditions: StepConditionalBehavior): this; /** * Remove a step from the workflow * * @param stepId - ID of the step to remove * @returns The flow instance for method chaining * * @example * ```typescript * workflow.removeStep('optional-step'); * ``` */ removeStep(stepId: string): this; /** * Get a specific step by ID * * @param stepId - ID of the step to retrieve * @returns The step configuration or undefined if not found * * @example * ```typescript * const step = workflow.getStep('user-details'); * if (step) { * console.log(step.title); * } * ``` */ getStep(stepId: string): StepConfig | undefined; /** * Get all steps in the workflow * * Returns a copy of the steps array to prevent external modification. * * @returns Array of all step configurations * * @example * ```typescript * const allSteps = workflow.getSteps(); * console.log(`Workflow has ${allSteps.length} steps`); * ``` */ getSteps(): StepConfig[]; /** * Clear all steps from the workflow * * Removes all steps and resets the ID generator. Useful for rebuilding * workflows or creating templates. * * @returns The flow instance for method chaining * * @example * ```typescript * workflow.clearSteps() * .addStep(newStep1) * .addStep(newStep2); * ``` */ clearSteps(): this; /** * Clone the workflow builder * * Creates a deep copy of the workflow builder with optional new ID and name. * All configuration, steps, and plugins are copied to the new instance. * * @param newWorkflowId - Optional new workflow ID * @param newWorkflowName - Optional new workflow name * @returns A new flow instance with copied configuration * * @example * ```typescript * const template = workflow.clone('new-workflow', 'New Workflow'); * template.addStep(additionalStep); * ``` */ clone(newWorkflowId?: string, newWorkflowName?: string): flow; /** * Enhanced validation using shared utilities * * Performs comprehensive validation of the workflow configuration, * checking for common issues like missing steps, duplicate IDs, * and plugin dependency problems. * * @returns Array of validation error messages (empty if valid) * * @example * ```typescript * const errors = workflow.validate(); * if (errors.length > 0) { * console.error('Validation errors:', errors); * } * ``` */ validate(): string[]; /** * Get comprehensive workflow statistics * * Provides detailed analytics about the workflow structure and configuration. * Useful for monitoring, optimization, and reporting purposes. * * @returns Object containing various workflow statistics * * @example * ```typescript * const stats = workflow.getStats(); * console.log(`Workflow has ${stats.totalSteps} steps`); * console.log(`Estimated ${stats.estimatedFields} total fields`); * ``` */ getStats(): { totalSteps: number; totalFields: number; averageFieldsPerStep: number; maxFieldsInStep: number; minFieldsInStep: number; hasAnalytics: boolean; }; /** * Build the final workflow configuration * * Validates the workflow and creates the final configuration object * that can be used by the workflow runtime. This method should be * called after all configuration is complete. * * @returns Complete workflow configuration * @throws Error if validation fails * * @example * ```typescript * try { * const workflowConfig = workflow.build(); * // Use workflowConfig with workflow runtime * } catch (error) { * console.error('Workflow build failed:', error.message); * } * ``` */ build(): WorkflowConfig; /** * Export workflow configuration to JSON * * Serializes the workflow configuration to a JSON-compatible object. * Useful for saving workflows, creating templates, or transferring * configurations between systems. * * @returns JSON-serializable workflow configuration * * @example * ```typescript * const json = workflow.toJSON(); * localStorage.setItem('workflow-template', JSON.stringify(json)); * ``` */ toJSON(): any; /** * Import workflow configuration from JSON * * Loads workflow configuration from a JSON object. This method * performs partial updates, only modifying properties that are * present in the JSON object. * * @param json - JSON object containing workflow configuration * @returns The flow instance for method chaining * * @example * ```typescript * const json = JSON.parse(localStorage.getItem('workflow-template')); * workflow.fromJSON(json); * ``` */ fromJSON(json: any): this; } /** * Factory function to create a workflow builder directly * * This is a convenience function that provides an alternative to using * the class constructor or static create method. It's particularly useful * for functional programming styles or when you prefer function calls * over class instantiation. * * @param config - The ril configuration instance * @param workflowId - Unique identifier for the workflow * @param workflowName - Display name for the workflow * @param description - Optional description of the workflow purpose * @returns A new flow builder instance * * @example * ```typescript * const workflow = createFlow(rilConfig, 'onboarding', 'User Onboarding'); * ``` */ declare function createFlow(config: ril, workflowId: string, workflowName: string, description?: string): flow; /** * Module augmentation to add createFlow method to ril instances * * This declaration extends the ril interface to include the createFlow * method, allowing for a more integrated API experience where workflows * can be created directly from ril configuration instances. */ declare module '@rilaykit/core' { interface ril { /** * Creates a new workflow builder using this ril configuration * * @param workflowId - Unique identifier for the workflow * @param workflowName - Display name for the workflow * @param description - Optional description of the workflow purpose * @returns A new flow builder instance * * @example * ```typescript * const workflow = rilConfig.createFlow('checkout', 'Checkout Process'); * ``` */ flow(workflowId: string, workflowName: string, description?: string): flow; } } interface ConditionEvaluationResult { visible: boolean; disabled: boolean; required: boolean; readonly: boolean; } /** * Hook to evaluate conditional behaviors based on workflow data * * @param conditions - The conditional behavior configuration * @param workflowData - Current workflow data to evaluate against * @param defaultState - Default state when no conditions are provided * @returns Evaluated condition results */ declare function useConditionEvaluation(conditions?: ConditionalBehavior, workflowData?: Record<string, any>, defaultState?: Partial<ConditionEvaluationResult>): ConditionEvaluationResult; /** * Hook to evaluate multiple field conditions at once * * @param fieldsWithConditions - Map of field IDs to their conditional behaviors * @param workflowData - Current workflow data to evaluate against * @returns Map of field IDs to their evaluated conditions */ declare function useMultipleConditionEvaluation(fieldsWithConditions: Record<string, ConditionalBehavior | undefined>, workflowData?: Record<string, any>): Record<string, ConditionEvaluationResult>; /** * Hook to evaluate multiple step conditions at once using numeric indices * * @param stepsWithConditions - Map of step indices to their conditional behaviors * @param workflowData - Current workflow data to evaluate against * @returns Map of step indices to their evaluated conditions */ declare function useMultipleStepConditionEvaluation(stepsWithConditions: Record<number, ConditionalBehavior | undefined>, workflowData?: Record<string, any>): Record<number, ConditionEvaluationResult>; /** * @fileoverview Persistence system types for Rilay workflows * * This module defines the core interfaces and types for the workflow persistence system. * It provides a flexible adapter pattern allowing different persistence strategies: * - localStorage persistence * - API-based persistence * - Custom persistence implementations * * The system is designed to be type-safe and extensible while maintaining * a simple API for common use cases. */ /** * Persistent workflow data that gets saved/loaded */ interface PersistedWorkflowData { /** Unique identifier for the workflow */ workflowId: string; /** Current step index in the workflow */ currentStepIndex: number; /** All collected data across steps */ allData: Record<string, any>; /** Currently active step data */ stepData: Record<string, any>; /** Set of visited step IDs */ visitedSteps: string[]; /** When this data was last saved */ lastSaved: number; /** Optional metadata for custom persistence needs */ metadata?: Record<string, any>; } /** * Options for persistence operations */ interface PersistenceOptions { /** Whether to automatically persist on state changes */ autoPersist?: boolean; /** Debounce delay in ms for auto-persistence (default: 500ms) */ debounceMs?: number; /** Custom key for storage (overrides default) */ storageKey?: string; /** Additional metadata to include in persisted data */ metadata?: Record<string, any>; } /** * Core persistence adapter interface * * All persistence implementations must implement this interface. * It provides a consistent API regardless of the underlying storage mechanism. */ interface WorkflowPersistenceAdapter { /** * Save workflow data * @param key - Unique identifier for the stored data * @param data - Workflow data to persist * @returns Promise that resolves when save is complete */ save(key: string, data: PersistedWorkflowData): Promise<void>; /** * Load workflow data * @param key - Unique identifier for the stored data * @returns Promise that resolves to persisted data or null if not found */ load(key: string): Promise<PersistedWorkflowData | null>; /** * Remove persisted workflow data * @param key - Unique identifier for the stored data * @returns Promise that resolves when deletion is complete */ remove(key: string): Promise<void>; /** * Check if data exists for the given key * @param key - Unique identifier to check * @returns Promise that resolves to true if data exists */ exists(key: string): Promise<boolean>; /** * List all available keys (optional, for debugging/admin) * @returns Promise that resolves to array of available keys */ listKeys?(): Promise<string[]>; /** * Clear all persisted data (optional, for cleanup) * @returns Promise that resolves when all data is cleared */ clear?(): Promise<void>; } /** * Configuration for localStorage persistence adapter */ interface LocalStorageAdapterConfig { /** Prefix for localStorage keys (default: 'rilay_workflow_') */ keyPrefix?: string; /** Whether to compress data before storage */ compress?: boolean; /** Maximum age in ms before data expires (optional) */ maxAge?: number; } /** * Error types for persistence operations */ declare class WorkflowPersistenceError extends Error { readonly code: string; readonly cause?: Error | undefined; constructor(message: string, code: string, cause?: Error | undefined); } /** * Persistence hook return type */ interface UsePersistenceReturn { /** Whether persistence is currently saving */ isPersisting: boolean; /** Last persistence error (if any) */ persistenceError: WorkflowPersistenceError | null; /** Manually trigger a save operation */ persistNow: () => Promise<void>; /** Load data from persistence */ loadPersistedData: () => Promise<PersistedWorkflowData | null>; /** Clear persisted data */ clearPersistedData: () => Promise<void>; /** Whether persisted data exists */ hasPersistedData: () => Promise<boolean>; } interface WorkflowState { currentStepIndex: number; allData: Record<string, any>; stepData: Record<string, any>; visitedSteps: Set<string>; isSubmitting: boolean; isTransitioning: boolean; } type WorkflowAction = { type: 'SET_CURRENT_STEP'; stepIndex: number; } | { type: 'SET_STEP_DATA'; data: Record<string, any>; stepId: string; } | { type: 'SET_ALL_DATA'; data: Record<string, any>; } | { type: 'SET_FIELD_VALUE'; fieldId: string; value: any; stepId: string; } | { type: 'SET_SUBMITTING'; isSubmitting: boolean; } | { type: 'SET_TRANSITIONING'; isTransitioning: boolean; } | { type: 'MARK_STEP_VISITED'; stepIndex: number; stepId: string; } | { type: 'RESET_WORKFLOW'; } | { type: 'LOAD_PERSISTED_STATE'; state: Partial<WorkflowState>; }; interface UseWorkflowStateProps { defaultValues?: Record<string, any>; persistence?: { workflowId: string; adapter?: WorkflowPersistenceAdapter; options?: PersistenceOptions; userId?: string; autoLoad?: boolean; }; } declare function useWorkflowState({ defaultValues, persistence }: UseWorkflowStateProps): { workflowState: WorkflowState; setCurrentStep: (stepIndex: number) => void; setStepData: (data: Record<string, any>, stepId: string) => void; setFieldValue: (fieldId: string, value: any, stepId: string) => void; setSubmitting: (isSubmitting: boolean) => void; setTransitioning: (isTransitioning: boolean) => void; markStepVisited: (stepIndex: number, stepId: string) => void; resetWorkflow: () => void; loadPersistedState: () => Promise<boolean>; persistence: { isPersisting: boolean; persistenceError: WorkflowPersistenceError | null; persistNow: () => Promise<void>; clearPersistedData: () => Promise<void>; hasPersistedData: () => Promise<boolean>; } | null; }; interface UseWorkflowAnalyticsProps { workflowConfig: WorkflowConfig; workflowState: WorkflowState; workflowContext: WorkflowContext; } interface UseWorkflowAnalyticsReturn { analyticsStartTime: React.MutableRefObject<number>; trackStepSkip: (stepId: string, reason: string) => void; trackError: (error: Error) => void; } declare function useWorkflowAnalytics({ workflowConfig, workflowState, workflowContext, }: UseWorkflowAnalyticsProps): UseWorkflowAnalyticsReturn; interface UseWorkflowConditionsProps { workflowConfig: WorkflowConfig; workflowState: WorkflowState; currentStep: StepConfig; } /** * Result of step condition evaluation - only relevant properties for workflow steps */ interface StepConditionResult { visible: boolean; skippable: boolean; } interface UseWorkflowConditionsReturn { stepConditions: StepConditionResult; fieldConditions: Record<string, ConditionEvaluationResult>; allStepConditions: Record<number, StepConditionResult>; isStepVisible: (stepIndex: number) => boolean; isStepSkippable: (stepIndex: number) => boolean; isFieldVisible: (fieldId: string) => boolean; isFieldDisabled: (fieldId: string) => boolean; isFieldRequired: (fieldId: string) => boolean; isFieldReadonly: (fieldId: string) => boolean; } /** * Hook to manage conditional behaviors for workflow steps and fields * * This hook evaluates conditions for steps and form fields within a workflow, * providing convenient methods to check step and field states based on conditions. * * Steps have different condition types than fields: * - Steps: visible, skippable * - Fields: visible, disabled, required, readonly */ declare function useWorkflowConditions({ workflowConfig, workflowState, currentStep, }: UseWorkflowConditionsProps): UseWorkflowConditionsReturn; interface UseWorkflowNavigationProps { workflowConfig: WorkflowConfig; workflowState: WorkflowState; workflowContext: WorkflowContext; conditionsHelpers: UseWorkflowConditionsReturn; setCurrentStep: (stepIndex: number) => void; setTransitioning: (isTransitioning: boolean) => void; markStepVisited: (stepIndex: number, stepId: string) => void; setStepData: (data: Record<string, any>, stepId: string) => void; onStepChange?: (fromStep: number, toStep: number, context: WorkflowContext) => void; } interface UseWorkflowNavigationReturn { goToStep: (stepIndex: number) => Promise<boolean>; goNext: () => Promise<boolean>; goPrevious: () => Promise<boolean>; skipStep: () => Promise<boolean>; canGoToStep: (stepIndex: number) => boolean; canGoNext: () => boolean; canGoPrevious: () => boolean; canSkipCurrentStep: () => boolean; } declare function useWorkflowNavigation({ workflowConfig, workflowState, workflowContext, conditionsHelpers, setCurrentStep, setTransitioning, markStepVisited, setStepData, onStepChange, }: UseWorkflowNavigationProps): UseWorkflowNavigationReturn; interface UseWorkflowSubmissionProps { workflowConfig: WorkflowConfig; workflowState: WorkflowState; workflowContext: WorkflowContext; setSubmitting: (isSubmitting: boolean) => void; onWorkflowComplete?: (data: Record<string, any>) => void | Promise<void>; analyticsStartTime: React.MutableRefObject<number>; } interface UseWorkflowSubmissionReturn { submitWorkflow: () => Promise<void>; isSubmitting: boolean; canSubmit: boolean; } declare function useWorkflowSubmission({ workflowConfig, workflowState, workflowContext, setSubmitting, onWorkflowComplete, analyticsStartTime, }: UseWorkflowSubmissionProps): UseWorkflowSubmissionReturn; interface WorkflowContextValue { workflowState: ReturnType<typeof useWorkflowState>['workflowState']; workflowConfig: WorkflowConfig; currentStep: StepConfig; context: WorkflowContext; formConfig?: FormConfiguration; conditionsHelpers: UseWorkflowConditionsReturn; goToStep: (stepIndex: number) => Promise<boolean>; goNext: () => Promise<boolean>; goPrevious: () => Promise<boolean>; skipStep: () => Promise<boolean>; canGoToStep: (stepIndex: number) => boolean; canGoNext: () => boolean; canGoPrevious: () => boolean; canSkipCurrentStep: () => boolean; setValue: (fieldId: string, value: any) => void; setStepData: (data: Record<string, any>) => void; resetWorkflow: () => void; submitWorkflow: () => Promise<void>; isSubmitting: boolean; canSubmit: boolean; } interface WorkflowProviderProps { children: React$1.ReactNode; workflowConfig: WorkflowConfig; defaultValues?: Record<string, any>; onStepChange?: (fromStep: number, toStep: number, context: WorkflowContext) => void; onWorkflowComplete?: (data: Record<string, any>) => void | Promise<void>; className?: string; } declare function WorkflowProvider({ children, workflowConfig, defaultValues, onStepChange, onWorkflowComplete, className, }: WorkflowProviderProps): react_jsx_runtime.JSX.Element; declare function useWorkflowContext(): WorkflowContextValue; type WorkflowProps = Omit<WorkflowProviderProps, 'children' | 'workflowConfig'> & { children: React$1.ReactNode; workflowConfig: WorkflowConfig | flow; }; /** * A wrapper component for the Rilay workflow system. * It simplifies the API by wrapping the WorkflowProvider and providing a clean, * component-based interface for building workflows. * Accepts both WorkflowConfig and flow builder instances. */ declare function Workflow({ children, workflowConfig, ...props }: WorkflowProps): react_jsx_runtime.JSX.Element; /** * Renders the main content of the current workflow step. * Simple component that renders either the children or FormBody by default. */ declare function WorkflowBody(): react_jsx_runtime.JSX.Element | null; declare function WorkflowNextButton({ className, ...props }: ComponentRendererBaseProps<WorkflowNextButtonRendererProps>): react_jsx_runtime.JSX.Element; declare function WorkflowPreviousButton({ className, ...props }: ComponentRendererBaseProps<WorkflowPreviousButtonRendererProps>): react_jsx_runtime.JSX.Element; declare function WorkflowSkipButton({ className, ...props }: ComponentRendererBaseProps<WorkflowSkipButtonRendererProps>): react_jsx_runtime.JSX.Element; interface WorkflowStepperProps extends ComponentRendererBaseProps<WorkflowStepperRendererProps> { onStepClick?: (stepIndex: number) => void; } declare function WorkflowStepper({ onStepClick, className, ...props }: WorkflowStepperProps): react_jsx_runtime.JSX.Element; /** * @fileoverview LocalStorage persistence adapter for Rilay workflows * * This adapter provides browser localStorage-based persistence for workflow data. * It includes features like data compression, expiration handling, and error recovery. * * Key features: * - Automatic data expiration based on maxAge * - Optional data compression for large workflows * - Graceful handling of localStorage quota exceeded * - Type-safe serialization/deserialization */ /** * LocalStorage-based persistence adapter * * Provides a robust localStorage implementation with features like: * - Automatic cleanup of expired data * - Configurable key prefixes for namespace isolation * - Error handling for quota exceeded scenarios * - Optional data compression * * @example * ```typescript * const adapter = new LocalStorageAdapter({ * keyPrefix: 'myapp_workflow_', * maxAge: 24 * 60 * 60 * 1000, // 24 hours * compress: true * }); * ``` */ declare class LocalStorageAdapter implements WorkflowPersistenceAdapter { private readonly keyPrefix; private readonly compress; private readonly maxAge?; private readonly version; private readonly _isAvailable; constructor(config?: LocalStorageAdapterConfig); /** * Save workflow data to localStorage */ save(key: string, data: PersistedWorkflowData): Promise<void>; /** * Load workflow data from localStorage */ load(key: string): Promise<PersistedWorkflowData | null>; /** * Remove workflow data from localStorage */ remove(key: string): Promise<void>; /** * Check if data exists for the given key */ exists(key: string): Promise<boolean>; /** * List all available keys */ listKeys(): Promise<string[]>; /** * Clear all workflow data */ clear(): Promise<void>; /** * Get the full storage key with prefix */ private getStorageKey; /** * Check if localStorage is available */ private isLocalStorageAvailable; /** * Simple data compression using basic string compression * Note: In production, you might want to use a proper compression library */ private compressData; /** * Decompress data */ private decompressData; /** * Clear expired data entries */ private clearExpiredData; } /** * @fileoverview Persistence utilities for Rilay workflows * * This module provides utility functions for working with workflow persistence, * including data transformation, validation, and helper functions for * converting between different data formats. */ /** * Convert WorkflowState to PersistedWorkflowData format */ declare function workflowStateToPersisted(workflowId: string, state: WorkflowState, metadata?: Record<string, any>): PersistedWorkflowData; /** * Convert PersistedWorkflowData to WorkflowState format */ declare function persistedToWorkflowState(data: PersistedWorkflowData): Partial<WorkflowState>; /** * Validate persisted workflow data structure */ declare function validatePersistedData(data: any): data is PersistedWorkflowData; /** * Generate a storage key for a workflow */ declare function generateStorageKey(workflowId: string, userId?: string): string; /** * Debounce function for auto-persistence */ declare function debounce<T extends (...args: any[]) => any>(func: T, wait: number): (...args: Parameters<T>) => void; /** * Merge persisted data with current state, handling conflicts */ declare function mergePersistedState(currentState: WorkflowState, persistedData: PersistedWorkflowData, strategy?: 'persist' | 'current' | 'merge'): Partial<WorkflowState>; /** * @fileoverview Persistence hook for Rilay workflows * * This hook provides workflow persistence functionality with automatic * debounced saving, error handling, and flexible adapter support. * It integrates seamlessly with the existing workflow state management. */ interface UsePersistenceProps { /** Unique workflow identifier */ workflowId: string; /** Current workflow state */ workflowState: WorkflowState; /** Persistence adapter to use */ adapter: WorkflowPersistenceAdapter; /** Persistence options */ options?: PersistenceOptions; /** Optional user ID for multi-user scenarios */ userId?: string; } /** * Hook for managing workflow persistence * * Provides automatic persistence with debouncing, manual save/load operations, * and comprehensive error handling. Integrates with any persistence adapter * that implements the WorkflowPersistenceAdapter interface. * * @example * ```typescript * const persistence = usePersistence({ * workflowId: 'user-onboarding', * workflowState, * adapter: new LocalStorageAdapter(), * options: { * autoPersist: true, * debounceMs: 1000 * } * }); * * if (persistence.persistenceError) { * console.error('Persistence error:', persistence.persistenceError); * } * ``` */ declare function usePersistence({ workflowId, workflowState, adapter, options, userId, }: UsePersistenceProps): UsePersistenceReturn; interface LicensePayload { plan: 'ARCHITECT' | 'FOUNDRY'; company: string; customerId: string; expiry: number; iat: number; } interface LicenseResult { valid: boolean; data?: LicensePayload; error?: 'EXPIRED' | 'INVALID' | 'MISSING' | 'FORMAT_INVALID' | 'SIGNATURE_INVALID'; } type LicensePlan = 'ARCHITECT' | 'FOUNDRY'; /** * Enhanced Rilay License Manager with Ed25519 cryptographic validation * Uses @noble/ed25519 for secure and fast signature verification */ declare class RilayLicenseManager { private static licenseKey; private static licenseResult; private static isInitialized; /** * Initialize with a license key and Ed25519 public key */ static setLicenseKey(licenseKey?: string): Promise<void>; /** * Validate license using Ed25519 signature verification */ private static validateLicense; /** * Convert compressed payload to full payload */ private static decompressPayload; /** * Convert hex string to Uint8Array */ private static hexToBytes; /** * Convert base64 string to text (browser-compatible) */ private static base64ToString; /** * Get license validation result */ static getLicenseResult(): LicenseResult; /** * Check if watermark should be displayed */ static shouldDisplayWatermark(): boolean; /** * Get watermark message */ static getWatermarkMessage(): string; /** * Display license status in console */ static logLicenseStatus(): void; /** * Get license info */ static getLicenseInfo(): Promise<{ plan?: string; company?: string; expiryDate?: string; }>; } export { type ConditionEvaluationResult, type LicensePayload, type LicensePlan, type LicenseResult, LocalStorageAdapter, type LocalStorageAdapterConfig, type PersistedWorkflowData, type PersistenceOptions, RilayLicenseManager, type StepConditionResult, type StepDefinition, type UsePersistenceProps, type UsePersistenceReturn, type UseWorkflowAnalyticsProps, type UseWorkflowAnalyticsReturn, type UseWorkflowConditionsProps, type UseWorkflowConditionsReturn, type UseWorkflowNavigationProps, type UseWorkflowNavigationReturn, type UseWorkflowStateProps, type UseWorkflowSubmissionProps, type UseWorkflowSubmissionReturn, Workflow, type WorkflowAction, WorkflowBody, type WorkflowContextValue, WorkflowNextButton, type WorkflowPersistenceAdapter, WorkflowPersistenceError, WorkflowPreviousButton, WorkflowProvider, WorkflowSkipButton, type WorkflowState, WorkflowStepper, createFlow, debounce, flow, generateStorageKey, mergePersistedState, persistedToWorkflowState, useConditionEvaluation, useMultipleConditionEvaluation, useMultipleStepConditionEvaluation, usePersistence, useWorkflowAnalytics, useWorkflowConditions, useWorkflowContext, useWorkflowNavigation, useWorkflowState, useWorkflowSubmission, validatePersistedData, workflowStateToPersisted };