@rilaykit/workflow 11.0.0 → 12.1.0

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.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),ht=require('react'),Ce=require('@noble/ed25519'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ht__default=/*#__PURE__*/_interopDefault(ht);var Ce__namespace=/*#__PURE__*/_interopNamespace(Ce);var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new core.IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof forms.form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=core.normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=core.deepClone(this.steps),n.analytics=this.analytics?core.deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?core.deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{core.ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(l=>l.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var et=1751361139160,tt="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,l]=n,a=`${i}.${s}`,g=new TextEncoder().encode(a),c=l.match(/.{2}/g);if(!c)return {valid:!1,error:"INVALID"};let o=new Uint8Array(c.map(E=>Number.parseInt(E,16))),f=k.hexToBytes(tt);if(!await Ce__namespace.verify(o,g,f))return {valid:!1,error:"SIGNATURE_INVALID"};let y=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(y),h=Math.floor(Date.now()/1e3);return d.e<h?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:et>d.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let l=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),g=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),o=l<<18|a<<12|g<<6|c;n+=String.fromCharCode(o>>16&255),g!==64&&(n+=String.fromCharCode(o>>8&255)),c!==64&&(n+=String.fromCharCode(o&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var B=k;function te(t,e={},r={}){return ht.useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,core.evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function Ae(t,e={}){return ht.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=l=>{try{return l&&typeof l=="object"&&"build"in l?core.evaluateCondition(l.build(),e):core.evaluateCondition(l,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function Ne(t,e={}){return ht.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let l=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(g){return console.warn(`Error evaluating condition for step ${s}:`,g),false}};r[s]={visible:i.visible?l(i.visible):true,disabled:i.disabled?l(i.disabled):false,required:i.required?l(i.required):false,readonly:i.readonly?l(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function re(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Le(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function rt(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function ne(t,e){return e?`${e}:${t}`:t}function ie(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function nt(t,e,r="persist"){let n=Le(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,l]=ht.useState(false),[a,g]=ht.useState(null),[c,o]=ht.useState(false),f=ht.useRef(r),m=ht.useRef(n),y=ht.useRef({hasPendingChanges:false});ht.useEffect(()=>{f.current=r,m.current=n;},[r,n]);let d=ne(m.current.storageKey||t,i),h=ht.useCallback(()=>{g(null);},[]),x=ht.useCallback((S,I)=>{let L=S instanceof D?S:new D(`${I} failed: ${S.message}`,"OPERATION_FAILED",S);g(L),console.error("[WorkflowPersistence]",L);},[]),E=ht.useCallback(async S=>{h(),l(true);try{let I=re(t,S,m.current.metadata);await f.current.save(d,I),y.current.lastSavedState={...S},y.current.hasPendingChanges=!1;}catch(I){throw x(I,"Save"),I}finally{l(false);}},[t,d,h,x]),p=ht.useRef(ie(async S=>{try{await E(S);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),b=ht.useCallback((S,I)=>I?S.currentStepIndex!==I.currentStepIndex||JSON.stringify(S.allData)!==JSON.stringify(I.allData)||JSON.stringify(S.stepData)!==JSON.stringify(I.stepData)||S.visitedSteps.size!==I.visitedSteps.size||!Array.from(S.visitedSteps).every(L=>I.visitedSteps.has(L)):true,[]),w=ht.useCallback(async()=>{h(),o(true);try{let S=await f.current.load(d);return S&&(y.current.lastSavedState={currentStepIndex:S.currentStepIndex,allData:S.allData,stepData:S.stepData,visitedSteps:new Set(S.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},y.current.hasPendingChanges=!1),S}catch(S){return x(S,"Load"),null}finally{setTimeout(()=>o(false),100);}},[d,h,x]),N=ht.useCallback(async()=>{h();try{await f.current.remove(d),y.current.lastSavedState=void 0,y.current.hasPendingChanges=!1;}catch(S){throw x(S,"Clear"),S}},[d,h,x]),u=ht.useCallback(async()=>{try{return await f.current.exists(d)}catch(S){return x(S,"Exists check"),false}},[d,x]);ht.useEffect(()=>{m.current.autoPersist&&(s||c||e.isInitializing||e.isSubmitting||e.isTransitioning||b(e,y.current.lastSavedState)&&(y.current.hasPendingChanges=true,p.current(e)));},[e,s,c,b]);let v=ht.useCallback(async()=>{await E(e);},[E,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:w,clearPersistedData:N,hasPersistedData:u}}function it(){let{workflowConfig:t,currentStep:e}=T(),r=ht.useMemo(()=>e?.metadata,[e?.metadata]),n=ht.useMemo(()=>c=>t.steps.find(f=>f.id===c)?.metadata,[t.steps]),i=ht.useMemo(()=>c=>t.steps[c]?.metadata,[t.steps]),s=ht.useMemo(()=>c=>r?c in r:false,[r]),l=ht.useMemo(()=>(c,o)=>r&&c in r?r[c]:o,[r]),a=ht.useMemo(()=>()=>t.steps.map((c,o)=>({id:c.id,title:c.title,index:o,metadata:c.metadata})),[t.steps]),g=ht.useMemo(()=>c=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>c(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:l,getAllStepsMetadata:a,findStepsByMetadata:g}}function oe({workflowConfig:t,workflowState:e,workflowContext:r}){let n=ht.useRef(Date.now()),i=ht.useRef(new Map),s=ht.useRef(false),l=ht.useRef(null),a=core.getGlobalMonitor();ht.useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),ht.useEffect(()=>{let m=t.steps[e.currentStepIndex];if(m&&l.current!==m.id){if(l.current&&t.analytics?.onStepComplete){let y=i.current.get(l.current);if(y){let d=Date.now()-y;t.analytics.onStepComplete(l.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:l.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}l.current=m.id,i.current.set(m.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(m.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:m.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let g=ht.useCallback((m,y)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(m,y,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:m,reason:y},void 0,"medium");},[t.analytics,r,a,t.id]),c=ht.useCallback(m=>{t.analytics?.onError&&t.analytics.onError(m,r),a&&a.trackError(m,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),o=ht.useCallback((m,y,d)=>{if(!a)return;let h={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:y,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:m,toStep:y,direction:y>m?"forward":"backward"},h,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=ht.useCallback((m,y)=>{if(!a)return;let d={timestamp:Date.now(),duration:m,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:m};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:y,currentStepIndex:e.currentStepIndex},d,m>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:g,trackError:c,trackNavigation:o,trackConditionEvaluation:f}}function ae(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,ae(i,s)):r[s]=i;}return r}function le(t,e){let r={...t,...e},n=ae(r);return {...r,...n}}function Ve(t,e){return {visible:t.visible,skippable:e===true||t.required}}function pe({workflowConfig:t,workflowState:e,currentStep:r}){let n=ht.useMemo(()=>le(e.allData,e.stepData),[e.allData,e.stepData]),i=ht.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=te(i,n,{visible:true,disabled:false,required:false,readonly:false}),l=ht.useMemo(()=>Ve(s,r?.allowSkip),[s,r?.allowSkip]),a=ht.useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{b.conditions&&(p[w]={visible:b.conditions.visible,required:b.conditions.skippable});}),p},[t.steps]),g=Ne(a,n),c=ht.useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{let N=g[w];N?p[w]=Ve(N,b.allowSkip):p[w]={visible:true,skippable:b.allowSkip===true};}),p},[t.steps,g]),o=ht.useMemo(()=>{if(!r?.formConfig?.allFields)return {};let p={};for(let b of r.formConfig.allFields)b.conditions&&(p[b.id]=b.conditions);return p},[r?.formConfig?.allFields]),f=Ae(o,n),m=ht.useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.visible??true,[c,t.steps.length]),y=ht.useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.skippable??false,[c,t.steps.length]),d=ht.useCallback(p=>f[p]?.visible??true,[f]),h=ht.useCallback(p=>f[p]?.disabled??false,[f]),x=ht.useCallback(p=>f[p]?.required??false,[f]),E=ht.useCallback(p=>f[p]?.readonly??false,[f]);return {stepConditions:l,fieldConditions:f,allStepConditions:c,isStepVisible:m,isStepSkippable:y,isFieldVisible:d,isFieldDisabled:h,isFieldRequired:x,isFieldReadonly:E}}function ce({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:l,setStepData:a,onStepChange:g}){let c=ht.useRef(g);c.current=g;let o=t.steps[e.currentStepIndex],f=ht.useCallback(()=>({setStepData:(u,v)=>{a(v,u);},setStepFields:(u,v)=>{let I={...e.allData[u]||{},...v};a(I,u);},getStepData:u=>e.allData[u]||{},setNextStepField:(u,v)=>{let S=e.currentStepIndex+1;if(S<t.steps.length){let I=t.steps[S].id,K={...e.allData[I]||{},[u]:v};a(K,I);}},setNextStepFields:u=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let S=t.steps[v].id,L={...e.allData[S]||{},...u};a(L,S);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),m=ht.useCallback(async u=>{if(u<0||u>=t.steps.length||!n.isStepVisible(u))return false;s(true);try{return c.current&&c.current(e.currentStepIndex,u,r),i(u),l(u,t.steps[u].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,l]),y=ht.useCallback(u=>{for(let v=u+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=ht.useCallback(u=>{for(let v=u-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),h=ht.useCallback(async()=>{if(o?.onAfterValidation)try{let v=f();await o.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let u=y(e.currentStepIndex);return u===null?false:m(u)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,y,m]),x=ht.useCallback(async()=>{let u=d(e.currentStepIndex);return u===null?false:m(u)},[e.currentStepIndex,d,m]),E=ht.useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),p=ht.useCallback(u=>u<0||u>=t.steps.length?false:n.isStepVisible(u),[t.steps.length,n]),b=ht.useCallback(()=>{let u=y(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,y,p]),w=ht.useCallback(()=>{let u=d(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,d,p]),N=ht.useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:m,goNext:h,goPrevious:x,skipStep:E,canGoToStep:p,canGoNext:b,canGoPrevious:w,canSkipCurrentStep:N}}function pt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function de({defaultValues:t={},defaultStepIndex:e,workflowSteps:r,persistence:n}){let i=ht.useMemo(()=>{let p=new Set;if(e&&e>0&&r)for(let b=0;b<e;b++)r[b]&&p.add(r[b].id);return p},[e,r]),s={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:i,isSubmitting:false,isTransitioning:false,isInitializing:true},[l,a]=ht.useReducer(pt,s),g=n?.adapter?X({workflowId:n.workflowId,workflowState:l,adapter:n.adapter,options:n.options,userId:n.userId}):null,c=ht.useCallback(p=>{a({type:"SET_CURRENT_STEP",stepIndex:p});},[]),o=ht.useCallback((p,b)=>{a({type:"SET_STEP_DATA",data:p,stepId:b});},[]),f=ht.useCallback((p,b,w)=>{a({type:"SET_FIELD_VALUE",fieldId:p,value:b,stepId:w});},[]),m=ht.useCallback(p=>{a({type:"SET_SUBMITTING",isSubmitting:p});},[]),y=ht.useCallback(p=>{a({type:"SET_TRANSITIONING",isTransitioning:p});},[]),d=ht.useCallback((p,b)=>{a({type:"MARK_STEP_VISITED",stepIndex:p,stepId:b});},[]),h=ht.useCallback(()=>{a({type:"RESET_WORKFLOW"});},[]),x=ht.useCallback(()=>{a({type:"SET_INITIALIZATION_COMPLETE"});},[]),E=ht.useCallback(async()=>{if(!g)return x(),false;try{let p=await g.loadPersistedData();if(p){let b={currentStepIndex:p.currentStepIndex,allData:p.allData,stepData:p.stepData,visitedSteps:new Set(p.visitedSteps)};return a({type:"LOAD_PERSISTED_STATE",state:b}),x(),!0}}catch(p){console.error("Failed to load persisted state:",p);}return x(),false},[g,x]);return {workflowState:l,setCurrentStep:c,setStepData:o,setFieldValue:f,setSubmitting:m,setTransitioning:y,markStepVisited:d,resetWorkflow:h,loadPersistedState:E,persistence:g?{isPersisting:g.isPersisting,persistenceError:g.persistenceError,persistNow:g.persistNow,clearPersistedData:g.clearPersistedData,hasPersistedData:g.hasPersistedData}:null}}function ue({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let l=ht.useRef(i);l.current=i;let a=ht.useCallback(async()=>{n(true);try{if(l.current&&await l.current(e.allData),t.analytics?.onWorkflowComplete){let c=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,c,e.allData);}}catch(c){throw console.error("Workflow submission failed:",c),t.analytics?.onError&&t.analytics.onError(c,r),c}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),g=ht.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:g()}}var Oe=ht.createContext(null);function ge({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:l}){let a=ht.useRef(i),g=ht.useRef(s);a.current=i,g.current=s;let c=ht.useMemo(()=>{if(!n)return 0;let R=e.steps.findIndex(P=>P.id===n);return R===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):R},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:m,setFieldValue:y,setSubmitting:d,setTransitioning:h,markStepVisited:x,resetWorkflow:E,loadPersistedState:p,persistence:b}=de({defaultValues:r,defaultStepIndex:c,workflowSteps:e.steps,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});ht.useEffect(()=>{e.persistence&&p&&p();},[]);let w=ht.useMemo(()=>({isPersisting:b?.isPersisting??false,persistenceError:b?.persistenceError??null,persistNow:b?.persistNow}),[b?.isPersisting,b?.persistenceError,b?.persistNow]),N=ht.useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),u=ht.useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),v=ht.useMemo(()=>u?.formConfig,[u?.formConfig]),S=pe({workflowConfig:e,workflowState:o,currentStep:u}),I=ht.useMemo(()=>{let R=-1;for(let W=0;W<e.steps.length;W++)if(S.isStepVisible(W)){R=W;break}let P=-1;for(let W=e.steps.length-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}return {...N,isFirstStep:o.currentStepIndex===R,isLastStep:o.currentStepIndex===P}},[N,o.currentStepIndex,S,e.steps.length]),{analyticsStartTime:L}=oe({workflowConfig:e,workflowState:o,workflowContext:I}),{goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}=ce({workflowConfig:e,workflowState:o,workflowContext:I,conditionsHelpers:S,setCurrentStep:f,setTransitioning:h,markStepVisited:x,setStepData:m,onStepChange:a.current}),j=ht.useRef(false);ht.useEffect(()=>{if(j.current)return;if(!S.isStepVisible(o.currentStepIndex)){for(let P=0;P<e.steps.length;P++)if(S.isStepVisible(P)){f(P),x(P,e.steps[P].id);break}}j.current=true;},[o.currentStepIndex,e.steps,f,x]),ht.useEffect(()=>{if(!j.current)return;if(!S.isStepVisible(o.currentStepIndex)){let P=null;for(let W=o.currentStepIndex+1;W<e.steps.length;W++)if(S.isStepVisible(W)){P=W;break}if(P===null){for(let W=o.currentStepIndex-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}}P!==null&&(f(P),x(P,e.steps[P].id));}},[S,o.currentStepIndex,e.steps,f,x]);let{submitWorkflow:q,isSubmitting:We,canSubmit:De}=ue({workflowConfig:e,workflowState:o,workflowContext:I,setSubmitting:d,onWorkflowComplete:g.current,analyticsStartTime:L}),Y=ht.useCallback((R,P)=>{y(R,P,u?.id||"");},[y,u?.id]),Re=ht.useCallback(R=>{m(R,u?.id||"");},[m,u?.id]),qe=ht.useCallback(async R=>{u?.id&&R&&m(R,u.id),I.isLastStep?await q():await $();},[I.isLastStep,q,$,u?.id,m]),Ee=ht.useMemo(()=>({goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}),[K,$,ve,he,xe,Ie,ke,Pe]),we=ht.useMemo(()=>({setValue:Y,setStepData:Re,resetWorkflow:E}),[Y,Re,E]),Te=ht.useMemo(()=>({submitWorkflow:q,isSubmitting:We,canSubmit:De}),[q,We,De]),ze=ht.useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:u,context:I,formConfig:v,conditionsHelpers:S,currentStepMetadata:u?.metadata,...Ee,...we,...Te,persistNow:w.persistNow,isPersisting:w.isPersisting,persistenceError:w.persistenceError}),[o,e,u,I,v,S,Ee,we,Te,w]),Je=ht.useMemo(()=>{if(!u?.id)return {};let R=o?.allData[u.id]||{};if(!v?.allFields)return R;let P=new Set(v.allFields.map(z=>z.id)),W={};for(let[z,He]of Object.entries(R))P.has(z)&&(W[z]=He);return W},[o?.allData,u?.id,v?.allFields]),Xe=ht.useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsxRuntime.jsx(Oe.Provider,{value:ze,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:v,defaultValues:Je,onFieldChange:Y,"data-workflow-id":e.id,className:l,onSubmit:qe,children:t},Xe)})}function T(){let t=ht.useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function yt({children:t,workflowConfig:e,...r}){let[n,i]=ht.useState(),s=ht.useMemo(()=>e instanceof U?e.build():e,[e]);return ht.useEffect(()=>{if(typeof window<"u"&&B.shouldDisplayWatermark()){let a=B.getWatermarkMessage();i(a);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(ge,{...r,workflowConfig:s,children:t}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var xt=ht__default.default.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsxRuntime.jsx(forms.FormBody,{}):null});var Rt=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:l,currentStep:a}=T(),{submit:g,formState:c}=forms.useFormContext(),o=ht.useMemo(()=>{let y=c.isSubmitting||s.isSubmitting,d=r??y,h=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:h}},[c.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=ht.useCallback(async y=>{y?.preventDefault(),o.canGoNext&&await g(y);},[o.canGoNext,g]),m=ht.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:c.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,a,c.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:l.renderConfig?.nextButtonRenderer,props:m,...n})});var Nt=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:l,workflowConfig:a,currentStep:g}=T(),{formState:c}=forms.useFormContext(),o=ht.useMemo(()=>{let y=c.isSubmitting||l.isSubmitting,d=r??y,h=i.currentStepIndex>0&&!l.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:h}},[c.isSubmitting,l.isSubmitting,l.isTransitioning,i.currentStepIndex,r]),f=ht.useCallback(async y=>{y?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),m=ht.useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:g,stepData:c.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,g,c.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:m,...n})});var _t=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:l,workflowConfig:a,context:g,conditionsHelpers:c}=T(),{formState:o}=forms.useFormContext(),f=ht.useMemo(()=>{let d=o.isSubmitting||l.isSubmitting,h=r??d,x=(!!i?.allowSkip||c.isStepSkippable(l.currentStepIndex))&&!l.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:x}},[o.isSubmitting,l.isSubmitting,l.isTransitioning,l.currentStepIndex,i?.allowSkip,c.isStepSkippable,r]),m=ht.useCallback(async d=>{d?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),y=ht.useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:m,className:e,currentStep:i,stepData:o.values||{},allData:g.allData,context:g}),[f.canSkip,f.finalIsSubmitting,m,e,i,o.values,g.allData,g]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:y,...n})});var $t=ht__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:l,conditionsHelpers:a}=T(),{visibleSteps:g,visibleToOriginalIndexMap:c,originalToVisibleIndexMap:o}=ht.useMemo(()=>{let d=[],h=new Map,x=new Map;return i.steps.forEach((E,p)=>{if(a.isStepVisible(p)){let b=d.length;d.push(E),h.set(b,p),x.set(p,b);}}),{visibleSteps:d,visibleToOriginalIndexMap:h,originalToVisibleIndexMap:x}},[i.steps,a]),f=ht.useCallback(d=>{let h=c.get(d);h!==void 0&&(e?e(h):l(h));},[c,e,l]),m=ht.useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),y=ht.useMemo(()=>({steps:g,currentStepIndex:m,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[g,m,s.visitedSteps,f,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:y,...n})});var be=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),l=this.compress?this.compressData(s):s;localStorage.setItem(n,l);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},l=JSON.stringify(s),a=this.compress?this.compressData(l):l;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,l=JSON.parse(s);l.expiresAt&&Date.now()>l.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
2
- exports.LocalStorageAdapter=be;exports.RilayLicenseManager=B;exports.Workflow=yt;exports.WorkflowBody=xt;exports.WorkflowNextButton=Rt;exports.WorkflowPersistenceError=D;exports.WorkflowPreviousButton=Nt;exports.WorkflowProvider=ge;exports.WorkflowSkipButton=_t;exports.WorkflowStepper=$t;exports.combineWorkflowDataForConditions=le;exports.debounce=ie;exports.flattenObject=ae;exports.flow=U;exports.generateStorageKey=ne;exports.mergePersistedState=nt;exports.persistedToWorkflowState=Le;exports.useConditionEvaluation=te;exports.usePersistence=X;exports.useStepMetadata=it;exports.useWorkflowAnalytics=oe;exports.useWorkflowConditions=pe;exports.useWorkflowContext=T;exports.useWorkflowNavigation=ce;exports.useWorkflowState=de;exports.useWorkflowSubmission=ue;exports.validatePersistedData=rt;exports.workflowStateToPersisted=re;
1
+ 'use strict';var core=require('@rilaykit/core'),forms=require('@rilaykit/forms'),ht=require('react'),Ce=require('@noble/ed25519'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ht__default=/*#__PURE__*/_interopDefault(ht);var Ce__namespace=/*#__PURE__*/_interopNamespace(Ce);var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new core.IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof forms.form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=core.normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=core.deepClone(this.steps),n.analytics=this.analytics?core.deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?core.deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{core.ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(l=>l.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var et=1751361139160,tt="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,l]=n,a=`${i}.${s}`,S=new TextEncoder().encode(a),p=l.match(/.{2}/g);if(!p)return {valid:!1,error:"INVALID"};let o=new Uint8Array(p.map(W=>Number.parseInt(W,16))),f=k.hexToBytes(tt);if(!await Ce__namespace.verify(o,S,f))return {valid:!1,error:"SIGNATURE_INVALID"};let y=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),u=JSON.parse(y),h=Math.floor(Date.now()/1e3);return u.e<h?{valid:!1,error:"EXPIRED",data:k.decompressPayload(u)}:et>u.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(u)}:u.p===void 0||!u.c||!u.i||!u.e||!u.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(u)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let l=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),S=r.indexOf(s.charAt(i++)),p=r.indexOf(s.charAt(i++)),o=l<<18|a<<12|S<<6|p;n+=String.fromCharCode(o>>16&255),S!==64&&(n+=String.fromCharCode(o>>8&255)),p!==64&&(n+=String.fromCharCode(o&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var B=k;function re(t,e={},r={}){return ht.useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,core.evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function Ae(t,e={}){return ht.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=l=>{try{return l&&typeof l=="object"&&"build"in l?core.evaluateCondition(l.build(),e):core.evaluateCondition(l,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function Ne(t,e={}){return ht.useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let l=a=>{try{return a&&typeof a=="object"&&"build"in a?core.evaluateCondition(a.build(),e):core.evaluateCondition(a,e)}catch(S){return console.warn(`Error evaluating condition for step ${s}:`,S),false}};r[s]={visible:i.visible?l(i.visible):true,disabled:i.disabled?l(i.disabled):false,required:i.required?l(i.required):false,readonly:i.readonly?l(i.readonly):false};}}return r},[t,e])}var E=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function ne(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Le(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function rt(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function ie(t,e){return e?`${e}:${t}`:t}function se(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function nt(t,e,r="persist"){let n=Le(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,l]=ht.useState(false),[a,S]=ht.useState(null),[p,o]=ht.useState(false),f=ht.useRef(r),m=ht.useRef(n),y=ht.useRef({hasPendingChanges:false});ht.useEffect(()=>{f.current=r,m.current=n;},[r,n]);let u=ie(m.current.storageKey||t,i),h=ht.useCallback(()=>{S(null);},[]),v=ht.useCallback((g,I)=>{let L=g instanceof E?g:new E(`${I} failed: ${g.message}`,"OPERATION_FAILED",g);S(L),console.error("[WorkflowPersistence]",L);},[]),W=ht.useCallback(async g=>{h(),l(true);try{let I=ne(t,g,m.current.metadata);await f.current.save(u,I),y.current.lastSavedState={...g},y.current.hasPendingChanges=!1;}catch(I){throw v(I,"Save"),I}finally{l(false);}},[t,u,h,v]),c=ht.useRef(se(async g=>{try{await W(g);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),b=ht.useCallback((g,I)=>I?g.currentStepIndex!==I.currentStepIndex||JSON.stringify(g.allData)!==JSON.stringify(I.allData)||JSON.stringify(g.stepData)!==JSON.stringify(I.stepData)||g.visitedSteps.size!==I.visitedSteps.size||!Array.from(g.visitedSteps).every(L=>I.visitedSteps.has(L)):true,[]),R=ht.useCallback(async()=>{h(),o(true);try{let g=await f.current.load(u);return g&&(y.current.lastSavedState={currentStepIndex:g.currentStepIndex,allData:g.allData,stepData:g.stepData,visitedSteps:new Set(g.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},y.current.hasPendingChanges=!1),g}catch(g){return v(g,"Load"),null}finally{setTimeout(()=>o(false),100);}},[u,h,v]),N=ht.useCallback(async()=>{h();try{await f.current.remove(u),y.current.lastSavedState=void 0,y.current.hasPendingChanges=!1;}catch(g){throw v(g,"Clear"),g}},[u,h,v]),d=ht.useCallback(async()=>{try{return await f.current.exists(u)}catch(g){return v(g,"Exists check"),false}},[u,v]);ht.useEffect(()=>{m.current.autoPersist&&(s||p||e.isInitializing||e.isSubmitting||e.isTransitioning||b(e,y.current.lastSavedState)&&(y.current.hasPendingChanges=true,c.current(e)));},[e,s,p,b]);let x=ht.useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:x,loadPersistedData:R,clearPersistedData:N,hasPersistedData:d}}function it(){let{workflowConfig:t,currentStep:e}=T(),r=ht.useMemo(()=>e?.metadata,[e?.metadata]),n=ht.useMemo(()=>p=>t.steps.find(f=>f.id===p)?.metadata,[t.steps]),i=ht.useMemo(()=>p=>t.steps[p]?.metadata,[t.steps]),s=ht.useMemo(()=>p=>r?p in r:false,[r]),l=ht.useMemo(()=>(p,o)=>r&&p in r?r[p]:o,[r]),a=ht.useMemo(()=>()=>t.steps.map((p,o)=>({id:p.id,title:p.title,index:o,metadata:p.metadata})),[t.steps]),S=ht.useMemo(()=>p=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>p(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:l,getAllStepsMetadata:a,findStepsByMetadata:S}}function ae({workflowConfig:t,workflowState:e,workflowContext:r}){let n=ht.useRef(Date.now()),i=ht.useRef(new Map),s=ht.useRef(false),l=ht.useRef(null),a=core.getGlobalMonitor();ht.useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),ht.useEffect(()=>{let m=t.steps[e.currentStepIndex];if(m&&l.current!==m.id){if(l.current&&t.analytics?.onStepComplete){let y=i.current.get(l.current);if(y){let u=Date.now()-y;t.analytics.onStepComplete(l.current,u,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:l.current,duration:u},{timestamp:Date.now(),duration:u,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:u,conditionEvaluationDuration:0},"low");}}l.current=m.id,i.current.set(m.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(m.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:m.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let S=ht.useCallback((m,y)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(m,y,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:m,reason:y},void 0,"medium");},[t.analytics,r,a,t.id]),p=ht.useCallback(m=>{t.analytics?.onError&&t.analytics.onError(m,r),a&&a.trackError(m,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),o=ht.useCallback((m,y,u)=>{if(!a)return;let h={timestamp:Date.now(),duration:u,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:y,navigationDuration:u,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:m,toStep:y,direction:y>m?"forward":"backward"},h,u>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=ht.useCallback((m,y)=>{if(!a)return;let u={timestamp:Date.now(),duration:m,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:m};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:y,currentStepIndex:e.currentStepIndex},u,m>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:S,trackError:p,trackNavigation:o,trackConditionEvaluation:f}}function le(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,le(i,s)):r[s]=i;}return r}function pe(t,e){let r={...t,...e},n=le(r);return {...r,...n}}function Ve(t,e){return {visible:t.visible,skippable:e===true||t.required}}function ce({workflowConfig:t,workflowState:e,currentStep:r}){let n=ht.useMemo(()=>pe(e.allData,e.stepData),[e.allData,e.stepData]),i=ht.useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=re(i,n,{visible:true,disabled:false,required:false,readonly:false}),l=ht.useMemo(()=>Ve(s,r?.allowSkip),[s,r?.allowSkip]),a=ht.useMemo(()=>{let c={};return t.steps.forEach((b,R)=>{b.conditions&&(c[R]={visible:b.conditions.visible,required:b.conditions.skippable});}),c},[t.steps]),S=Ne(a,n),p=ht.useMemo(()=>{let c={};return t.steps.forEach((b,R)=>{let N=S[R];N?c[R]=Ve(N,b.allowSkip):c[R]={visible:true,skippable:b.allowSkip===true};}),c},[t.steps,S]),o=ht.useMemo(()=>{if(!r?.formConfig?.allFields)return {};let c={};for(let b of r.formConfig.allFields)b.conditions&&(c[b.id]=b.conditions);return c},[r?.formConfig?.allFields]),f=Ae(o,n),m=ht.useCallback(c=>c<0||c>=t.steps.length?false:p[c]?.visible??true,[p,t.steps.length]),y=ht.useCallback(c=>c<0||c>=t.steps.length?false:p[c]?.skippable??false,[p,t.steps.length]),u=ht.useCallback(c=>f[c]?.visible??true,[f]),h=ht.useCallback(c=>f[c]?.disabled??false,[f]),v=ht.useCallback(c=>f[c]?.required??false,[f]),W=ht.useCallback(c=>f[c]?.readonly??false,[f]);return {stepConditions:l,fieldConditions:f,allStepConditions:p,isStepVisible:m,isStepSkippable:y,isFieldVisible:u,isFieldDisabled:h,isFieldRequired:v,isFieldReadonly:W}}function de({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:l,setStepData:a,onStepChange:S}){let p=ht.useRef(S);p.current=S;let o=t.steps[e.currentStepIndex],f=ht.useCallback(()=>({setStepData:(d,x)=>{a(x,d);},setStepFields:(d,x)=>{let I={...e.allData[d]||{},...x};a(I,d);},getStepData:d=>e.allData[d]||{},setNextStepField:(d,x)=>{let g=e.currentStepIndex+1;if(g<t.steps.length){let I=t.steps[g].id,K={...e.allData[I]||{},[d]:x};a(K,I);}},setNextStepFields:d=>{let x=e.currentStepIndex+1;if(x<t.steps.length){let g=t.steps[x].id,L={...e.allData[g]||{},...d};a(L,g);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),m=ht.useCallback(async d=>{if(d<0||d>=t.steps.length||!n.isStepVisible(d))return false;s(true);try{return p.current&&p.current(e.currentStepIndex,d,r),i(d),l(d,t.steps[d].id),!0}catch(x){return console.error("Step transition failed:",x),t.analytics?.onError&&t.analytics.onError(x,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,l]),y=ht.useCallback(d=>{for(let x=d+1;x<t.steps.length;x++)if(n.isStepVisible(x))return x;return null},[t.steps.length,n]),u=ht.useCallback(d=>{for(let x=d-1;x>=0;x--)if(n.isStepVisible(x))return x;return null},[n]),h=ht.useCallback(async()=>{if(o?.onAfterValidation)try{let x=f();await o.onAfterValidation(e.stepData,x,r);}catch(x){return console.error("onAfterValidation failed:",x),t.analytics?.onError&&t.analytics.onError(x,r),false}let d=y(e.currentStepIndex);return d===null?false:m(d)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,y,m]),v=ht.useCallback(async()=>{let d=u(e.currentStepIndex);return d===null?false:m(d)},[e.currentStepIndex,u,m]),W=ht.useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),c=ht.useCallback(d=>d<0||d>=t.steps.length?false:n.isStepVisible(d),[t.steps.length,n]),b=ht.useCallback(()=>{let d=y(e.currentStepIndex);return d!==null&&c(d)},[e.currentStepIndex,y,c]),R=ht.useCallback(()=>{let d=u(e.currentStepIndex);return d!==null&&c(d)},[e.currentStepIndex,u,c]),N=ht.useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:m,goNext:h,goPrevious:v,skipStep:W,canGoToStep:c,canGoNext:b,canGoPrevious:R,canSkipCurrentStep:N}}function pt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function ue({defaultValues:t={},defaultStepIndex:e,workflowSteps:r,persistence:n}){let i=ht.useMemo(()=>{let c=new Set;if(e&&e>0&&r)for(let b=0;b<e;b++)r[b]&&c.add(r[b].id);return c},[e,r]),s={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:i,isSubmitting:false,isTransitioning:false,isInitializing:true},[l,a]=ht.useReducer(pt,s),S=n?.adapter?X({workflowId:n.workflowId,workflowState:l,adapter:n.adapter,options:n.options,userId:n.userId}):null,p=ht.useCallback(c=>{a({type:"SET_CURRENT_STEP",stepIndex:c});},[]),o=ht.useCallback((c,b)=>{a({type:"SET_STEP_DATA",data:c,stepId:b});},[]),f=ht.useCallback((c,b,R)=>{a({type:"SET_FIELD_VALUE",fieldId:c,value:b,stepId:R});},[]),m=ht.useCallback(c=>{a({type:"SET_SUBMITTING",isSubmitting:c});},[]),y=ht.useCallback(c=>{a({type:"SET_TRANSITIONING",isTransitioning:c});},[]),u=ht.useCallback((c,b)=>{a({type:"MARK_STEP_VISITED",stepIndex:c,stepId:b});},[]),h=ht.useCallback(()=>{a({type:"RESET_WORKFLOW"});},[]),v=ht.useCallback(()=>{a({type:"SET_INITIALIZATION_COMPLETE"});},[]),W=ht.useCallback(async()=>{if(!S)return v(),false;try{let c=await S.loadPersistedData();if(c){let b={currentStepIndex:c.currentStepIndex,allData:c.allData,stepData:c.stepData,visitedSteps:new Set(c.visitedSteps)};return a({type:"LOAD_PERSISTED_STATE",state:b}),v(),!0}}catch(c){console.error("Failed to load persisted state:",c);}return v(),false},[S,v]);return {workflowState:l,setCurrentStep:p,setStepData:o,setFieldValue:f,setSubmitting:m,setTransitioning:y,markStepVisited:u,resetWorkflow:h,loadPersistedState:W,persistence:S?{isPersisting:S.isPersisting,persistenceError:S.persistenceError,persistNow:S.persistNow,clearPersistedData:S.clearPersistedData,hasPersistedData:S.hasPersistedData}:null}}function fe({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let l=ht.useRef(i);l.current=i;let a=ht.useCallback(async()=>{n(true);try{if(l.current&&await l.current(e.allData),t.analytics?.onWorkflowComplete){let p=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,p,e.allData);}}catch(p){throw console.error("Workflow submission failed:",p),t.analytics?.onError&&t.analytics.onError(p,r),p}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),S=ht.useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:S()}}var Oe=ht.createContext(null);function ye({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:l}){let a=ht.useRef(i),S=ht.useRef(s);a.current=i,S.current=s;let p=ht.useMemo(()=>{if(!n)return 0;let w=e.steps.findIndex(P=>P.id===n);return w===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):w},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:m,setFieldValue:y,setSubmitting:u,setTransitioning:h,markStepVisited:v,resetWorkflow:W,loadPersistedState:c,persistence:b}=ue({defaultValues:r,defaultStepIndex:p,workflowSteps:e.steps,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});ht.useEffect(()=>{e.persistence&&c&&c();},[]);let R=ht.useMemo(()=>({isPersisting:b?.isPersisting??false,persistenceError:b?.persistenceError??null,persistNow:b?.persistNow}),[b?.isPersisting,b?.persistenceError,b?.persistNow]),N=ht.useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),d=ht.useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),x=ht.useMemo(()=>d?.formConfig,[d?.formConfig]),g=ce({workflowConfig:e,workflowState:o,currentStep:d}),I=ht.useMemo(()=>{let w=-1;for(let D=0;D<e.steps.length;D++)if(g.isStepVisible(D)){w=D;break}let P=-1;for(let D=e.steps.length-1;D>=0;D--)if(g.isStepVisible(D)){P=D;break}return {...N,isFirstStep:o.currentStepIndex===w,isLastStep:o.currentStepIndex===P}},[N,o.currentStepIndex,g,e.steps.length]),{analyticsStartTime:L}=ae({workflowConfig:e,workflowState:o,workflowContext:I}),{goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}=de({workflowConfig:e,workflowState:o,workflowContext:I,conditionsHelpers:g,setCurrentStep:f,setTransitioning:h,markStepVisited:v,setStepData:m,onStepChange:a.current}),Y=ht.useRef(false);ht.useEffect(()=>{if(Y.current)return;if(!g.isStepVisible(o.currentStepIndex)){for(let P=0;P<e.steps.length;P++)if(g.isStepVisible(P)){f(P),v(P,e.steps[P].id);break}}Y.current=true;},[o.currentStepIndex,e.steps,f,v]),ht.useEffect(()=>{if(!Y.current)return;if(!g.isStepVisible(o.currentStepIndex)){let P=null;for(let D=o.currentStepIndex+1;D<e.steps.length;D++)if(g.isStepVisible(D)){P=D;break}if(P===null){for(let D=o.currentStepIndex-1;D>=0;D--)if(g.isStepVisible(D)){P=D;break}}P!==null&&(f(P),v(P,e.steps[P].id));}},[g,o.currentStepIndex,e.steps,f,v]);let{submitWorkflow:q,isSubmitting:We,canSubmit:De}=fe({workflowConfig:e,workflowState:o,workflowContext:I,setSubmitting:u,onWorkflowComplete:S.current,analyticsStartTime:L}),Q=ht.useCallback((w,P)=>{y(w,P,d?.id||"");},[y,d?.id]),Re=ht.useCallback(w=>{m(w,d?.id||"");},[m,d?.id]),qe=ht.useCallback(async w=>{d?.id&&w&&m(w,d.id),I.isLastStep?await q():await $();},[I.isLastStep,q,$,d?.id,m]),Ee=ht.useMemo(()=>({goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}),[K,$,ve,he,xe,Ie,ke,Pe]),we=ht.useMemo(()=>({setValue:Q,setStepData:Re,resetWorkflow:W}),[Q,Re,W]),Te=ht.useMemo(()=>({submitWorkflow:q,isSubmitting:We,canSubmit:De}),[q,We,De]),ze=ht.useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:d,context:I,formConfig:x,conditionsHelpers:g,currentStepMetadata:d?.metadata,...Ee,...we,...Te,persistNow:R.persistNow,isPersisting:R.isPersisting,persistenceError:R.persistenceError}),[o,e,d,I,x,g,Ee,we,Te,R]),Je=ht.useMemo(()=>{if(!d?.id)return {};let w=o?.allData[d.id]||{};if(!x?.allFields)return w;let P=new Set(x.allFields.map(z=>z.id)),D={};for(let[z,He]of Object.entries(w))P.has(z)&&(D[z]=He);return D},[o?.allData,d?.id,x?.allFields]),Xe=ht.useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsxRuntime.jsx(Oe.Provider,{value:ze,children:jsxRuntime.jsx(forms.FormProvider,{formConfig:x,defaultValues:Je,onFieldChange:Q,"data-workflow-id":e.id,className:l,onSubmit:qe,children:t},Xe)})}function T(){let t=ht.useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function yt({children:t,workflowConfig:e,...r}){let[n,i]=ht.useState(),s=ht.useMemo(()=>e instanceof U?e.build():e,[e]);return ht.useEffect(()=>{if(typeof window<"u"&&B.shouldDisplayWatermark()){let a=B.getWatermarkMessage();i(a);}},[]),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx(ye,{...r,workflowConfig:s,children:t}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var xt=ht__default.default.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsxRuntime.jsx(forms.FormBody,{}):null});var Rt=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:l,currentStep:a}=T(),{submit:S,formState:p}=forms.useFormContext(),o=ht.useMemo(()=>{let y=p.isSubmitting||s.isSubmitting,u=r??y,h=!s.isTransitioning&&!u;return {finalIsSubmitting:u,canGoNext:h}},[p.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=ht.useCallback(async y=>{y?.preventDefault(),o.canGoNext&&await S(y);},[o.canGoNext,S]),m=ht.useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:p.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,a,p.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:l.renderConfig?.nextButtonRenderer,props:m,...n})});var Nt=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:l,workflowConfig:a,currentStep:S}=T(),{formState:p}=forms.useFormContext(),o=ht.useMemo(()=>{let y=p.isSubmitting||l.isSubmitting,u=r??y,h=i.currentStepIndex>0&&!l.isTransitioning&&!u;return {finalIsSubmitting:u,canGoPrevious:h}},[p.isSubmitting,l.isSubmitting,l.isTransitioning,i.currentStepIndex,r]),f=ht.useCallback(async y=>{y?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),m=ht.useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:S,stepData:p.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,S,p.values,i.allData,i]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:m,...n})});var _t=ht__default.default.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:l,workflowConfig:a,context:S,conditionsHelpers:p}=T(),{formState:o}=forms.useFormContext(),f=ht.useMemo(()=>{let u=o.isSubmitting||l.isSubmitting,h=r??u,v=(!!i?.allowSkip||p.isStepSkippable(l.currentStepIndex))&&!l.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:v}},[o.isSubmitting,l.isSubmitting,l.isTransitioning,l.currentStepIndex,i?.allowSkip,p.isStepSkippable,r]),m=ht.useCallback(async u=>{u?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),y=ht.useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:m,className:e,currentStep:i,stepData:o.values||{},allData:S.allData,context:S}),[f.canSkip,f.finalIsSubmitting,m,e,i,o.values,S.allData,S]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:y,...n})});var $t=ht__default.default.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:l,conditionsHelpers:a}=T(),{visibleSteps:S,visibleToOriginalIndexMap:p,originalToVisibleIndexMap:o}=ht.useMemo(()=>{let h=[],v=new Map,W=new Map;return i.steps.forEach((c,b)=>{if(a.isStepVisible(b)){let R=h.length;h.push(c),v.set(R,b),W.set(b,R);}}),{visibleSteps:h,visibleToOriginalIndexMap:v,originalToVisibleIndexMap:W}},[i.steps,a]),f=ht.useCallback(h=>{let v=p.get(h);v!==void 0&&(e?e(v):l(v));},[p,e,l]),m=ht.useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),y=ht.useMemo(()=>{let h=new Set(S.map(W=>W.id)),v=new Set;for(let W of s.visitedSteps)h.has(W)&&v.add(W);return v},[S,s.visitedSteps]),u=ht.useMemo(()=>({steps:S,currentStepIndex:m,visitedSteps:y,onStepClick:f,className:r}),[S,m,y,f,r]);return jsxRuntime.jsx(core.ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:u,...n})});var be=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),l=this.compress?this.compressData(s):s;localStorage.setItem(n,l);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},l=JSON.stringify(s),a=this.compress?this.compressData(l):l;localStorage.setItem(i,a);}catch(i){throw new E("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new E(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new E("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new E(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new E("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new E(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new E("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new E(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new E("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new E(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new E("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,l=JSON.parse(s);l.expiresAt&&Date.now()>l.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
2
+ exports.LocalStorageAdapter=be;exports.RilayLicenseManager=B;exports.Workflow=yt;exports.WorkflowBody=xt;exports.WorkflowNextButton=Rt;exports.WorkflowPersistenceError=E;exports.WorkflowPreviousButton=Nt;exports.WorkflowProvider=ye;exports.WorkflowSkipButton=_t;exports.WorkflowStepper=$t;exports.combineWorkflowDataForConditions=pe;exports.debounce=se;exports.flattenObject=le;exports.flow=U;exports.generateStorageKey=ie;exports.mergePersistedState=nt;exports.persistedToWorkflowState=Le;exports.useConditionEvaluation=re;exports.usePersistence=X;exports.useStepMetadata=it;exports.useWorkflowAnalytics=ae;exports.useWorkflowConditions=ce;exports.useWorkflowContext=T;exports.useWorkflowNavigation=de;exports.useWorkflowState=ue;exports.useWorkflowSubmission=fe;exports.validatePersistedData=rt;exports.workflowStateToPersisted=ne;
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import {ComponentRendererWrapper,IdGenerator,normalizeToArray,deepClone,ensureUnique,getGlobalMonitor,evaluateCondition}from'@rilaykit/core';import {FormBody,useFormContext,form,FormProvider}from'@rilaykit/forms';import ht,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Ce from'@noble/ed25519';import {jsx,jsxs}from'react/jsx-runtime';var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=deepClone(this.steps),n.analytics=this.analytics?deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(l=>l.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var et=1751361139160,tt="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,l]=n,a=`${i}.${s}`,g=new TextEncoder().encode(a),c=l.match(/.{2}/g);if(!c)return {valid:!1,error:"INVALID"};let o=new Uint8Array(c.map(E=>Number.parseInt(E,16))),f=k.hexToBytes(tt);if(!await Ce.verify(o,g,f))return {valid:!1,error:"SIGNATURE_INVALID"};let y=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),d=JSON.parse(y),h=Math.floor(Date.now()/1e3);return d.e<h?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:et>d.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(d)}:d.p===void 0||!d.c||!d.i||!d.e||!d.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(d)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let l=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),g=r.indexOf(s.charAt(i++)),c=r.indexOf(s.charAt(i++)),o=l<<18|a<<12|g<<6|c;n+=String.fromCharCode(o>>16&255),g!==64&&(n+=String.fromCharCode(o>>8&255)),c!==64&&(n+=String.fromCharCode(o&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var B=k;function te(t,e={},r={}){return useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function Ae(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=l=>{try{return l&&typeof l=="object"&&"build"in l?evaluateCondition(l.build(),e):evaluateCondition(l,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function Ne(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let l=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(g){return console.warn(`Error evaluating condition for step ${s}:`,g),false}};r[s]={visible:i.visible?l(i.visible):true,disabled:i.disabled?l(i.disabled):false,required:i.required?l(i.required):false,readonly:i.readonly?l(i.readonly):false};}}return r},[t,e])}var D=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function re(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Le(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function rt(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function ne(t,e){return e?`${e}:${t}`:t}function ie(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function nt(t,e,r="persist"){let n=Le(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,l]=useState(false),[a,g]=useState(null),[c,o]=useState(false),f=useRef(r),m=useRef(n),y=useRef({hasPendingChanges:false});useEffect(()=>{f.current=r,m.current=n;},[r,n]);let d=ne(m.current.storageKey||t,i),h=useCallback(()=>{g(null);},[]),x=useCallback((S,I)=>{let L=S instanceof D?S:new D(`${I} failed: ${S.message}`,"OPERATION_FAILED",S);g(L),console.error("[WorkflowPersistence]",L);},[]),E=useCallback(async S=>{h(),l(true);try{let I=re(t,S,m.current.metadata);await f.current.save(d,I),y.current.lastSavedState={...S},y.current.hasPendingChanges=!1;}catch(I){throw x(I,"Save"),I}finally{l(false);}},[t,d,h,x]),p=useRef(ie(async S=>{try{await E(S);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),b=useCallback((S,I)=>I?S.currentStepIndex!==I.currentStepIndex||JSON.stringify(S.allData)!==JSON.stringify(I.allData)||JSON.stringify(S.stepData)!==JSON.stringify(I.stepData)||S.visitedSteps.size!==I.visitedSteps.size||!Array.from(S.visitedSteps).every(L=>I.visitedSteps.has(L)):true,[]),w=useCallback(async()=>{h(),o(true);try{let S=await f.current.load(d);return S&&(y.current.lastSavedState={currentStepIndex:S.currentStepIndex,allData:S.allData,stepData:S.stepData,visitedSteps:new Set(S.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},y.current.hasPendingChanges=!1),S}catch(S){return x(S,"Load"),null}finally{setTimeout(()=>o(false),100);}},[d,h,x]),N=useCallback(async()=>{h();try{await f.current.remove(d),y.current.lastSavedState=void 0,y.current.hasPendingChanges=!1;}catch(S){throw x(S,"Clear"),S}},[d,h,x]),u=useCallback(async()=>{try{return await f.current.exists(d)}catch(S){return x(S,"Exists check"),false}},[d,x]);useEffect(()=>{m.current.autoPersist&&(s||c||e.isInitializing||e.isSubmitting||e.isTransitioning||b(e,y.current.lastSavedState)&&(y.current.hasPendingChanges=true,p.current(e)));},[e,s,c,b]);let v=useCallback(async()=>{await E(e);},[E,e]);return {isPersisting:s,persistenceError:a,persistNow:v,loadPersistedData:w,clearPersistedData:N,hasPersistedData:u}}function it(){let{workflowConfig:t,currentStep:e}=T(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>c=>t.steps.find(f=>f.id===c)?.metadata,[t.steps]),i=useMemo(()=>c=>t.steps[c]?.metadata,[t.steps]),s=useMemo(()=>c=>r?c in r:false,[r]),l=useMemo(()=>(c,o)=>r&&c in r?r[c]:o,[r]),a=useMemo(()=>()=>t.steps.map((c,o)=>({id:c.id,title:c.title,index:o,metadata:c.metadata})),[t.steps]),g=useMemo(()=>c=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>c(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:l,getAllStepsMetadata:a,findStepsByMetadata:g}}function oe({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),l=useRef(null),a=getGlobalMonitor();useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),useEffect(()=>{let m=t.steps[e.currentStepIndex];if(m&&l.current!==m.id){if(l.current&&t.analytics?.onStepComplete){let y=i.current.get(l.current);if(y){let d=Date.now()-y;t.analytics.onStepComplete(l.current,d,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:l.current,duration:d},{timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:d,conditionEvaluationDuration:0},"low");}}l.current=m.id,i.current.set(m.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(m.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:m.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let g=useCallback((m,y)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(m,y,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:m,reason:y},void 0,"medium");},[t.analytics,r,a,t.id]),c=useCallback(m=>{t.analytics?.onError&&t.analytics.onError(m,r),a&&a.trackError(m,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),o=useCallback((m,y,d)=>{if(!a)return;let h={timestamp:Date.now(),duration:d,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:y,navigationDuration:d,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:m,toStep:y,direction:y>m?"forward":"backward"},h,d>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=useCallback((m,y)=>{if(!a)return;let d={timestamp:Date.now(),duration:m,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:m};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:y,currentStepIndex:e.currentStepIndex},d,m>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:g,trackError:c,trackNavigation:o,trackConditionEvaluation:f}}function ae(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,ae(i,s)):r[s]=i;}return r}function le(t,e){let r={...t,...e},n=ae(r);return {...r,...n}}function Ve(t,e){return {visible:t.visible,skippable:e===true||t.required}}function pe({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>le(e.allData,e.stepData),[e.allData,e.stepData]),i=useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=te(i,n,{visible:true,disabled:false,required:false,readonly:false}),l=useMemo(()=>Ve(s,r?.allowSkip),[s,r?.allowSkip]),a=useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{b.conditions&&(p[w]={visible:b.conditions.visible,required:b.conditions.skippable});}),p},[t.steps]),g=Ne(a,n),c=useMemo(()=>{let p={};return t.steps.forEach((b,w)=>{let N=g[w];N?p[w]=Ve(N,b.allowSkip):p[w]={visible:true,skippable:b.allowSkip===true};}),p},[t.steps,g]),o=useMemo(()=>{if(!r?.formConfig?.allFields)return {};let p={};for(let b of r.formConfig.allFields)b.conditions&&(p[b.id]=b.conditions);return p},[r?.formConfig?.allFields]),f=Ae(o,n),m=useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.visible??true,[c,t.steps.length]),y=useCallback(p=>p<0||p>=t.steps.length?false:c[p]?.skippable??false,[c,t.steps.length]),d=useCallback(p=>f[p]?.visible??true,[f]),h=useCallback(p=>f[p]?.disabled??false,[f]),x=useCallback(p=>f[p]?.required??false,[f]),E=useCallback(p=>f[p]?.readonly??false,[f]);return {stepConditions:l,fieldConditions:f,allStepConditions:c,isStepVisible:m,isStepSkippable:y,isFieldVisible:d,isFieldDisabled:h,isFieldRequired:x,isFieldReadonly:E}}function ce({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:l,setStepData:a,onStepChange:g}){let c=useRef(g);c.current=g;let o=t.steps[e.currentStepIndex],f=useCallback(()=>({setStepData:(u,v)=>{a(v,u);},setStepFields:(u,v)=>{let I={...e.allData[u]||{},...v};a(I,u);},getStepData:u=>e.allData[u]||{},setNextStepField:(u,v)=>{let S=e.currentStepIndex+1;if(S<t.steps.length){let I=t.steps[S].id,K={...e.allData[I]||{},[u]:v};a(K,I);}},setNextStepFields:u=>{let v=e.currentStepIndex+1;if(v<t.steps.length){let S=t.steps[v].id,L={...e.allData[S]||{},...u};a(L,S);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),m=useCallback(async u=>{if(u<0||u>=t.steps.length||!n.isStepVisible(u))return false;s(true);try{return c.current&&c.current(e.currentStepIndex,u,r),i(u),l(u,t.steps[u].id),!0}catch(v){return console.error("Step transition failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,l]),y=useCallback(u=>{for(let v=u+1;v<t.steps.length;v++)if(n.isStepVisible(v))return v;return null},[t.steps.length,n]),d=useCallback(u=>{for(let v=u-1;v>=0;v--)if(n.isStepVisible(v))return v;return null},[n]),h=useCallback(async()=>{if(o?.onAfterValidation)try{let v=f();await o.onAfterValidation(e.stepData,v,r);}catch(v){return console.error("onAfterValidation failed:",v),t.analytics?.onError&&t.analytics.onError(v,r),false}let u=y(e.currentStepIndex);return u===null?false:m(u)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,y,m]),x=useCallback(async()=>{let u=d(e.currentStepIndex);return u===null?false:m(u)},[e.currentStepIndex,d,m]),E=useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),p=useCallback(u=>u<0||u>=t.steps.length?false:n.isStepVisible(u),[t.steps.length,n]),b=useCallback(()=>{let u=y(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,y,p]),w=useCallback(()=>{let u=d(e.currentStepIndex);return u!==null&&p(u)},[e.currentStepIndex,d,p]),N=useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:m,goNext:h,goPrevious:x,skipStep:E,canGoToStep:p,canGoNext:b,canGoPrevious:w,canSkipCurrentStep:N}}function pt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function de({defaultValues:t={},defaultStepIndex:e,workflowSteps:r,persistence:n}){let i=useMemo(()=>{let p=new Set;if(e&&e>0&&r)for(let b=0;b<e;b++)r[b]&&p.add(r[b].id);return p},[e,r]),s={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:i,isSubmitting:false,isTransitioning:false,isInitializing:true},[l,a]=useReducer(pt,s),g=n?.adapter?X({workflowId:n.workflowId,workflowState:l,adapter:n.adapter,options:n.options,userId:n.userId}):null,c=useCallback(p=>{a({type:"SET_CURRENT_STEP",stepIndex:p});},[]),o=useCallback((p,b)=>{a({type:"SET_STEP_DATA",data:p,stepId:b});},[]),f=useCallback((p,b,w)=>{a({type:"SET_FIELD_VALUE",fieldId:p,value:b,stepId:w});},[]),m=useCallback(p=>{a({type:"SET_SUBMITTING",isSubmitting:p});},[]),y=useCallback(p=>{a({type:"SET_TRANSITIONING",isTransitioning:p});},[]),d=useCallback((p,b)=>{a({type:"MARK_STEP_VISITED",stepIndex:p,stepId:b});},[]),h=useCallback(()=>{a({type:"RESET_WORKFLOW"});},[]),x=useCallback(()=>{a({type:"SET_INITIALIZATION_COMPLETE"});},[]),E=useCallback(async()=>{if(!g)return x(),false;try{let p=await g.loadPersistedData();if(p){let b={currentStepIndex:p.currentStepIndex,allData:p.allData,stepData:p.stepData,visitedSteps:new Set(p.visitedSteps)};return a({type:"LOAD_PERSISTED_STATE",state:b}),x(),!0}}catch(p){console.error("Failed to load persisted state:",p);}return x(),false},[g,x]);return {workflowState:l,setCurrentStep:c,setStepData:o,setFieldValue:f,setSubmitting:m,setTransitioning:y,markStepVisited:d,resetWorkflow:h,loadPersistedState:E,persistence:g?{isPersisting:g.isPersisting,persistenceError:g.persistenceError,persistNow:g.persistNow,clearPersistedData:g.clearPersistedData,hasPersistedData:g.hasPersistedData}:null}}function ue({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let l=useRef(i);l.current=i;let a=useCallback(async()=>{n(true);try{if(l.current&&await l.current(e.allData),t.analytics?.onWorkflowComplete){let c=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,c,e.allData);}}catch(c){throw console.error("Workflow submission failed:",c),t.analytics?.onError&&t.analytics.onError(c,r),c}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),g=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:g()}}var Oe=createContext(null);function ge({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:l}){let a=useRef(i),g=useRef(s);a.current=i,g.current=s;let c=useMemo(()=>{if(!n)return 0;let R=e.steps.findIndex(P=>P.id===n);return R===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):R},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:m,setFieldValue:y,setSubmitting:d,setTransitioning:h,markStepVisited:x,resetWorkflow:E,loadPersistedState:p,persistence:b}=de({defaultValues:r,defaultStepIndex:c,workflowSteps:e.steps,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&p&&p();},[]);let w=useMemo(()=>({isPersisting:b?.isPersisting??false,persistenceError:b?.persistenceError??null,persistNow:b?.persistNow}),[b?.isPersisting,b?.persistenceError,b?.persistNow]),N=useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),u=useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),v=useMemo(()=>u?.formConfig,[u?.formConfig]),S=pe({workflowConfig:e,workflowState:o,currentStep:u}),I=useMemo(()=>{let R=-1;for(let W=0;W<e.steps.length;W++)if(S.isStepVisible(W)){R=W;break}let P=-1;for(let W=e.steps.length-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}return {...N,isFirstStep:o.currentStepIndex===R,isLastStep:o.currentStepIndex===P}},[N,o.currentStepIndex,S,e.steps.length]),{analyticsStartTime:L}=oe({workflowConfig:e,workflowState:o,workflowContext:I}),{goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}=ce({workflowConfig:e,workflowState:o,workflowContext:I,conditionsHelpers:S,setCurrentStep:f,setTransitioning:h,markStepVisited:x,setStepData:m,onStepChange:a.current}),j=useRef(false);useEffect(()=>{if(j.current)return;if(!S.isStepVisible(o.currentStepIndex)){for(let P=0;P<e.steps.length;P++)if(S.isStepVisible(P)){f(P),x(P,e.steps[P].id);break}}j.current=true;},[o.currentStepIndex,e.steps,f,x]),useEffect(()=>{if(!j.current)return;if(!S.isStepVisible(o.currentStepIndex)){let P=null;for(let W=o.currentStepIndex+1;W<e.steps.length;W++)if(S.isStepVisible(W)){P=W;break}if(P===null){for(let W=o.currentStepIndex-1;W>=0;W--)if(S.isStepVisible(W)){P=W;break}}P!==null&&(f(P),x(P,e.steps[P].id));}},[S,o.currentStepIndex,e.steps,f,x]);let{submitWorkflow:q,isSubmitting:We,canSubmit:De}=ue({workflowConfig:e,workflowState:o,workflowContext:I,setSubmitting:d,onWorkflowComplete:g.current,analyticsStartTime:L}),Y=useCallback((R,P)=>{y(R,P,u?.id||"");},[y,u?.id]),Re=useCallback(R=>{m(R,u?.id||"");},[m,u?.id]),qe=useCallback(async R=>{u?.id&&R&&m(R,u.id),I.isLastStep?await q():await $();},[I.isLastStep,q,$,u?.id,m]),Ee=useMemo(()=>({goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}),[K,$,ve,he,xe,Ie,ke,Pe]),we=useMemo(()=>({setValue:Y,setStepData:Re,resetWorkflow:E}),[Y,Re,E]),Te=useMemo(()=>({submitWorkflow:q,isSubmitting:We,canSubmit:De}),[q,We,De]),ze=useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:u,context:I,formConfig:v,conditionsHelpers:S,currentStepMetadata:u?.metadata,...Ee,...we,...Te,persistNow:w.persistNow,isPersisting:w.isPersisting,persistenceError:w.persistenceError}),[o,e,u,I,v,S,Ee,we,Te,w]),Je=useMemo(()=>{if(!u?.id)return {};let R=o?.allData[u.id]||{};if(!v?.allFields)return R;let P=new Set(v.allFields.map(z=>z.id)),W={};for(let[z,He]of Object.entries(R))P.has(z)&&(W[z]=He);return W},[o?.allData,u?.id,v?.allFields]),Xe=useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsx(Oe.Provider,{value:ze,children:jsx(FormProvider,{formConfig:v,defaultValues:Je,onFieldChange:Y,"data-workflow-id":e.id,className:l,onSubmit:qe,children:t},Xe)})}function T(){let t=useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function yt({children:t,workflowConfig:e,...r}){let[n,i]=useState(),s=useMemo(()=>e instanceof U?e.build():e,[e]);return useEffect(()=>{if(typeof window<"u"&&B.shouldDisplayWatermark()){let a=B.getWatermarkMessage();i(a);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(ge,{...r,workflowConfig:s,children:t}),n&&jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var xt=ht.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsx(FormBody,{}):null});var Rt=ht.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:l,currentStep:a}=T(),{submit:g,formState:c}=useFormContext(),o=useMemo(()=>{let y=c.isSubmitting||s.isSubmitting,d=r??y,h=!s.isTransitioning&&!d;return {finalIsSubmitting:d,canGoNext:h}},[c.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=useCallback(async y=>{y?.preventDefault(),o.canGoNext&&await g(y);},[o.canGoNext,g]),m=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:c.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,a,c.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:l.renderConfig?.nextButtonRenderer,props:m,...n})});var Nt=ht.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:l,workflowConfig:a,currentStep:g}=T(),{formState:c}=useFormContext(),o=useMemo(()=>{let y=c.isSubmitting||l.isSubmitting,d=r??y,h=i.currentStepIndex>0&&!l.isTransitioning&&!d;return {finalIsSubmitting:d,canGoPrevious:h}},[c.isSubmitting,l.isSubmitting,l.isTransitioning,i.currentStepIndex,r]),f=useCallback(async y=>{y?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),m=useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:g,stepData:c.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,g,c.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:m,...n})});var _t=ht.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:l,workflowConfig:a,context:g,conditionsHelpers:c}=T(),{formState:o}=useFormContext(),f=useMemo(()=>{let d=o.isSubmitting||l.isSubmitting,h=r??d,x=(!!i?.allowSkip||c.isStepSkippable(l.currentStepIndex))&&!l.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:x}},[o.isSubmitting,l.isSubmitting,l.isTransitioning,l.currentStepIndex,i?.allowSkip,c.isStepSkippable,r]),m=useCallback(async d=>{d?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),y=useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:m,className:e,currentStep:i,stepData:o.values||{},allData:g.allData,context:g}),[f.canSkip,f.finalIsSubmitting,m,e,i,o.values,g.allData,g]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:y,...n})});var $t=ht.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:l,conditionsHelpers:a}=T(),{visibleSteps:g,visibleToOriginalIndexMap:c,originalToVisibleIndexMap:o}=useMemo(()=>{let d=[],h=new Map,x=new Map;return i.steps.forEach((E,p)=>{if(a.isStepVisible(p)){let b=d.length;d.push(E),h.set(b,p),x.set(p,b);}}),{visibleSteps:d,visibleToOriginalIndexMap:h,originalToVisibleIndexMap:x}},[i.steps,a]),f=useCallback(d=>{let h=c.get(d);h!==void 0&&(e?e(h):l(h));},[c,e,l]),m=useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),y=useMemo(()=>({steps:g,currentStepIndex:m,visitedSteps:s.visitedSteps,onStepClick:f,className:r}),[g,m,s.visitedSteps,f,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:y,...n})});var be=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),l=this.compress?this.compressData(s):s;localStorage.setItem(n,l);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},l=JSON.stringify(s),a=this.compress?this.compressData(l):l;localStorage.setItem(i,a);}catch(i){throw new D("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new D(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new D("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new D(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new D("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new D(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new D("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new D(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new D("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new D(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new D("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,l=JSON.parse(s);l.expiresAt&&Date.now()>l.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
2
- export{be as LocalStorageAdapter,B as RilayLicenseManager,yt as Workflow,xt as WorkflowBody,Rt as WorkflowNextButton,D as WorkflowPersistenceError,Nt as WorkflowPreviousButton,ge as WorkflowProvider,_t as WorkflowSkipButton,$t as WorkflowStepper,le as combineWorkflowDataForConditions,ie as debounce,ae as flattenObject,U as flow,ne as generateStorageKey,nt as mergePersistedState,Le as persistedToWorkflowState,te as useConditionEvaluation,X as usePersistence,it as useStepMetadata,oe as useWorkflowAnalytics,pe as useWorkflowConditions,T as useWorkflowContext,ce as useWorkflowNavigation,de as useWorkflowState,ue as useWorkflowSubmission,rt as validatePersistedData,re as workflowStateToPersisted};
1
+ import {ComponentRendererWrapper,IdGenerator,normalizeToArray,deepClone,ensureUnique,getGlobalMonitor,evaluateCondition}from'@rilaykit/core';import {FormBody,useFormContext,form,FormProvider}from'@rilaykit/forms';import ht,{createContext,useMemo,useCallback,useContext,useState,useRef,useEffect,useReducer}from'react';import*as Ce from'@noble/ed25519';import {jsx,jsxs}from'react/jsx-runtime';var U=class t{constructor(e,r,n,i){this.steps=[];this.plugins=[];this.idGenerator=new IdGenerator;this.config=e,this.workflowId=r,this.workflowName=n,this.workflowDescription=i;}static create(e,r,n,i){return new t(e,r,n,i)}createStepFromDefinition(e){return {id:e.id||this.idGenerator.next("step"),title:e.title,description:e.description,formConfig:e.formConfig instanceof form?e.formConfig.build():e.formConfig,allowSkip:e.allowSkip||false,renderer:e.renderer,conditions:e.conditions,metadata:e.metadata,onAfterValidation:e.onAfterValidation}}addStep(e){let r=normalizeToArray(e);for(let n of r){let i=this.createStepFromDefinition(n);this.steps.push(i);}return this}configure(e){return e.analytics&&(this.analytics=e.analytics),e.persistence&&(this.persistenceConfig=e.persistence),this}use(e){this.validatePluginDependencies(e),this.plugins.push(e);try{e.install(this);}catch(r){throw new Error(`Failed to install plugin "${e.name}": ${r instanceof Error?r.message:String(r)}`)}return this}validatePluginDependencies(e){if(!e.dependencies)return;let r=e.dependencies.filter(n=>!this.plugins.some(i=>i.name===n));if(r.length>0)throw new Error(`Plugin "${e.name}" requires missing dependencies: ${r.join(", ")}`)}removePlugin(e){return this.plugins=this.plugins.filter(r=>r.name!==e),this}updateStep(e,r){let n=this.steps.findIndex(i=>i.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);return this.steps[n]={...this.steps[n],...r},this}addStepConditions(e,r){let n=this.steps.findIndex(s=>s.id===e);if(n===-1)throw new Error(`Step with ID "${e}" not found`);let i={...this.steps[n].conditions,...r};return this.steps[n]={...this.steps[n],conditions:i},this}removeStep(e){return this.steps=this.steps.filter(r=>r.id!==e),this}getStep(e){return this.steps.find(r=>r.id===e)}getSteps(){return [...this.steps]}clearSteps(){return this.steps=[],this.idGenerator.reset(),this}clone(e,r){let n=new t(this.config,e||`${this.workflowId}-clone`,r||this.workflowName);return n.steps=deepClone(this.steps),n.analytics=this.analytics?deepClone(this.analytics):void 0,n.persistenceConfig=this.persistenceConfig?deepClone(this.persistenceConfig):void 0,n.plugins=[...this.plugins],n}validate(){let e=[];this.steps.length===0&&e.push("Workflow must have at least one step");let r=this.steps.map(n=>n.id);try{ensureUnique(r,"step");}catch(n){e.push(n instanceof Error?n.message:String(n));}for(let n of this.plugins)if(n.dependencies){let i=n.dependencies.filter(s=>!this.plugins.some(l=>l.name===s));i.length>0&&e.push(`Plugin "${n.name}" requires missing dependencies: ${i.join(", ")}`);}return e}getStats(){let e=this.steps.reduce((n,i)=>n+i.formConfig.allFields.length,0),r=this.steps.map(n=>n.formConfig.allFields.length);return {totalSteps:this.steps.length,totalFields:e,averageFieldsPerStep:this.steps.length>0?e/this.steps.length:0,maxFieldsInStep:r.length>0?Math.max(...r):0,minFieldsInStep:r.length>0?Math.min(...r):0,hasAnalytics:!!this.analytics}}build(){let e=this.validate();if(e.length>0)throw new Error(`Workflow validation failed: ${e.join(", ")}`);return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins,renderConfig:this.config.getWorkflowRenderConfig()}}toJSON(){return {id:this.workflowId,name:this.workflowName,description:this.workflowDescription,steps:this.steps,analytics:this.analytics,persistence:this.persistenceConfig,plugins:this.plugins.map(e=>({name:e.name,version:e.version}))}}fromJSON(e){return this.workflowId=e.workflowId,this.workflowName=e.workflowName,this.workflowDescription=e.workflowDescription,this.steps=e.steps,this.analytics=e.analytics,this.persistenceConfig=e.persistence,this.plugins=e.plugins||[],this}};var et=1751361139160,tt="8fdb6a454550326d331c3b3d1d1f8c707a371bdb6c7ea72a0a1e4ea6f1822620",k=class k{static async setLicenseKey(e){k.licenseKey=e||"",k.licenseKey?k.licenseResult=await k.validateLicense():k.licenseResult={valid:false,error:"MISSING"},k.isInitialized=true;}static async validateLicense(){if(!k.licenseKey)return {valid:false,error:"MISSING"};try{if(!k.licenseKey.startsWith("ril_"))return {valid:!1,error:"FORMAT_INVALID"};let e=k.licenseKey.slice(4),n=k.base64ToString(e).split(".");if(n.length!==3)return {valid:!1,error:"FORMAT_INVALID"};let[i,s,l]=n,a=`${i}.${s}`,S=new TextEncoder().encode(a),p=l.match(/.{2}/g);if(!p)return {valid:!1,error:"INVALID"};let o=new Uint8Array(p.map(W=>Number.parseInt(W,16))),f=k.hexToBytes(tt);if(!await Ce.verify(o,S,f))return {valid:!1,error:"SIGNATURE_INVALID"};let y=k.base64ToString(s.replace(/-/g,"+").replace(/_/g,"/")),u=JSON.parse(y),h=Math.floor(Date.now()/1e3);return u.e<h?{valid:!1,error:"EXPIRED",data:k.decompressPayload(u)}:et>u.e*1e3?{valid:!1,error:"EXPIRED",data:k.decompressPayload(u)}:u.p===void 0||!u.c||!u.i||!u.e||!u.t?{valid:!1,error:"INVALID"}:{valid:!0,data:k.decompressPayload(u)}}catch{return {valid:false,error:"INVALID"}}}static decompressPayload(e){return {plan:{0:"ARCHITECT",1:"FOUNDRY"}[e.p]||"ARCHITECT",company:e.c,customerId:e.i.toString(),expiry:e.e*1e3,iat:e.t*1e3}}static hexToBytes(e){let r=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)r[n/2]=Number.parseInt(e.substring(n,n+2),16);return r}static base64ToString(e){if(typeof atob<"u")return atob(e);if(typeof Buffer<"u")return Buffer.from(e,"base64").toString();let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n="",i=0,s=e.replace(/[^A-Za-z0-9+/]/g,"");for(;i<s.length;){let l=r.indexOf(s.charAt(i++)),a=r.indexOf(s.charAt(i++)),S=r.indexOf(s.charAt(i++)),p=r.indexOf(s.charAt(i++)),o=l<<18|a<<12|S<<6|p;n+=String.fromCharCode(o>>16&255),S!==64&&(n+=String.fromCharCode(o>>8&255)),p!==64&&(n+=String.fromCharCode(o&255));}return n}static getLicenseResult(){return k.isInitialized?k.licenseResult?k.licenseResult:{valid:false,error:"MISSING"}:{valid:false,error:"MISSING"}}static shouldDisplayWatermark(){return typeof window>"u"?false:!k.getLicenseResult().valid}static getWatermarkMessage(){let e=k.getLicenseResult();return {MISSING:"Rilay Workflow - For Trial Use Only",EXPIRED:"Rilay Workflow - License Expired",INVALID:"Rilay Workflow - Invalid License",FORMAT_INVALID:"Rilay Workflow - Invalid License Format",SIGNATURE_INVALID:"Rilay Workflow - Invalid License Signature"}[e.error||"MISSING"]||""}static logLicenseStatus(){let e=k.getLicenseResult();if(e.valid)return;let n={MISSING:"\u{1F527} Rilay Workflow - Trial Mode. Purchase a license at https://rilay.io/pricing",EXPIRED:"\u26A0\uFE0F Rilay Workflow - License Expired. Please renew your license.",INVALID:"\u274C Rilay Workflow - Invalid License. Please check your license key.",FORMAT_INVALID:"\u274C Rilay Workflow - Invalid License Format. Please check your license key.",SIGNATURE_INVALID:"\u274C Rilay Workflow - Invalid License Signature. Please check your license key."}[e.error||"MISSING"];console.warn(`%c${n}`,"color: #f59e0b; font-weight: bold;");}static async getLicenseInfo(){let e=k.getLicenseResult();return !e.valid||!e.data?{}:{plan:e.data.plan,company:e.data.company,expiryDate:new Date(e.data.expiry).toLocaleDateString()}}};k.licenseKey="",k.licenseResult=null,k.isInitialized=false;var B=k;function re(t,e={},r={}){return useMemo(()=>{if(!t)return {visible:r.visible??true,disabled:r.disabled??false,required:r.required??false,readonly:r.readonly??false};let n=i=>{try{let s;return i&&typeof i=="object"&&"build"in i?s=i.build():s=i,evaluateCondition(s,e)}catch(s){return console.warn("Error evaluating condition:",s),false}};return {visible:t.visible?n(t.visible):true,disabled:t.disabled?n(t.disabled):false,required:t.required?n(t.required):false,readonly:t.readonly?n(t.readonly):false}},[t,e,r])}function Ae(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t))if(r[n]={visible:true,disabled:false,required:false,readonly:false},i){let s=l=>{try{return l&&typeof l=="object"&&"build"in l?evaluateCondition(l.build(),e):evaluateCondition(l,e)}catch(a){return console.warn(`Error evaluating condition for field ${n}:`,a),false}};r[n]={visible:i.visible?s(i.visible):true,disabled:i.disabled?s(i.disabled):false,required:i.required?s(i.required):false,readonly:i.readonly?s(i.readonly):false};}return r},[t,e])}function Ne(t,e={}){return useMemo(()=>{let r={};for(let[n,i]of Object.entries(t)){let s=Number.parseInt(n,10);if(r[s]={visible:true,disabled:false,required:false,readonly:false},i){let l=a=>{try{return a&&typeof a=="object"&&"build"in a?evaluateCondition(a.build(),e):evaluateCondition(a,e)}catch(S){return console.warn(`Error evaluating condition for step ${s}:`,S),false}};r[s]={visible:i.visible?l(i.visible):true,disabled:i.disabled?l(i.disabled):false,required:i.required?l(i.required):false,readonly:i.readonly?l(i.readonly):false};}}return r},[t,e])}var E=class extends Error{constructor(r,n,i){super(`[WorkflowPersistence] ${r} (Code: ${n})`);this.code=n;this.cause=i;this.name="WorkflowPersistenceError";}};function ne(t,e,r){return {workflowId:t,currentStepIndex:e.currentStepIndex,allData:{...e.allData},stepData:{...e.stepData},visitedSteps:Array.from(e.visitedSteps),lastSaved:Date.now(),metadata:r}}function Le(t){return {currentStepIndex:t.currentStepIndex,allData:{...t.allData},stepData:{...t.stepData},visitedSteps:new Set(t.visitedSteps),isSubmitting:false,isTransitioning:false}}function rt(t){if(!t||typeof t!="object")return false;let e=["workflowId","currentStepIndex","allData","stepData","visitedSteps","lastSaved"];for(let r of e)if(!(r in t))return false;return !(typeof t.workflowId!="string"||typeof t.currentStepIndex!="number"||typeof t.allData!="object"||typeof t.stepData!="object"||!Array.isArray(t.visitedSteps)||typeof t.lastSaved!="number")}function ie(t,e){return e?`${e}:${t}`:t}function se(t,e){let r=null;return (...n)=>{r&&clearTimeout(r),r=setTimeout(()=>{t(...n);},e);}}function nt(t,e,r="persist"){let n=Le(e);switch(r){case "persist":return {...n,isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};case "current":return {...t,visitedSteps:new Set([...t.visitedSteps,...n.visitedSteps])};case "merge":return {currentStepIndex:t.currentStepIndex,allData:{...n.allData,...t.allData},stepData:{...n.stepData,...t.stepData},visitedSteps:new Set([...n.visitedSteps,...t.visitedSteps]),isSubmitting:t.isSubmitting,isTransitioning:t.isTransitioning};default:return n}}function X({workflowId:t,workflowState:e,adapter:r,options:n={},userId:i}){let[s,l]=useState(false),[a,S]=useState(null),[p,o]=useState(false),f=useRef(r),m=useRef(n),y=useRef({hasPendingChanges:false});useEffect(()=>{f.current=r,m.current=n;},[r,n]);let u=ie(m.current.storageKey||t,i),h=useCallback(()=>{S(null);},[]),v=useCallback((g,I)=>{let L=g instanceof E?g:new E(`${I} failed: ${g.message}`,"OPERATION_FAILED",g);S(L),console.error("[WorkflowPersistence]",L);},[]),W=useCallback(async g=>{h(),l(true);try{let I=ne(t,g,m.current.metadata);await f.current.save(u,I),y.current.lastSavedState={...g},y.current.hasPendingChanges=!1;}catch(I){throw v(I,"Save"),I}finally{l(false);}},[t,u,h,v]),c=useRef(se(async g=>{try{await W(g);}catch(I){console.debug("[WorkflowPersistence] Auto-save failed:",I);}},n.debounceMs||500)),b=useCallback((g,I)=>I?g.currentStepIndex!==I.currentStepIndex||JSON.stringify(g.allData)!==JSON.stringify(I.allData)||JSON.stringify(g.stepData)!==JSON.stringify(I.stepData)||g.visitedSteps.size!==I.visitedSteps.size||!Array.from(g.visitedSteps).every(L=>I.visitedSteps.has(L)):true,[]),R=useCallback(async()=>{h(),o(true);try{let g=await f.current.load(u);return g&&(y.current.lastSavedState={currentStepIndex:g.currentStepIndex,allData:g.allData,stepData:g.stepData,visitedSteps:new Set(g.visitedSteps),isSubmitting:!1,isTransitioning:!1,isInitializing:!1},y.current.hasPendingChanges=!1),g}catch(g){return v(g,"Load"),null}finally{setTimeout(()=>o(false),100);}},[u,h,v]),N=useCallback(async()=>{h();try{await f.current.remove(u),y.current.lastSavedState=void 0,y.current.hasPendingChanges=!1;}catch(g){throw v(g,"Clear"),g}},[u,h,v]),d=useCallback(async()=>{try{return await f.current.exists(u)}catch(g){return v(g,"Exists check"),false}},[u,v]);useEffect(()=>{m.current.autoPersist&&(s||p||e.isInitializing||e.isSubmitting||e.isTransitioning||b(e,y.current.lastSavedState)&&(y.current.hasPendingChanges=true,c.current(e)));},[e,s,p,b]);let x=useCallback(async()=>{await W(e);},[W,e]);return {isPersisting:s,persistenceError:a,persistNow:x,loadPersistedData:R,clearPersistedData:N,hasPersistedData:d}}function it(){let{workflowConfig:t,currentStep:e}=T(),r=useMemo(()=>e?.metadata,[e?.metadata]),n=useMemo(()=>p=>t.steps.find(f=>f.id===p)?.metadata,[t.steps]),i=useMemo(()=>p=>t.steps[p]?.metadata,[t.steps]),s=useMemo(()=>p=>r?p in r:false,[r]),l=useMemo(()=>(p,o)=>r&&p in r?r[p]:o,[r]),a=useMemo(()=>()=>t.steps.map((p,o)=>({id:p.id,title:p.title,index:o,metadata:p.metadata})),[t.steps]),S=useMemo(()=>p=>t.steps.map((o,f)=>({step:o,index:f})).filter(({step:o,index:f})=>p(o.metadata,o.id,f)).map(({step:o})=>o.id),[t.steps]);return {current:r,getByStepId:n,getByStepIndex:i,hasCurrentKey:s,getCurrentValue:l,getAllStepsMetadata:a,findStepsByMetadata:S}}function ae({workflowConfig:t,workflowState:e,workflowContext:r}){let n=useRef(Date.now()),i=useRef(new Map),s=useRef(false),l=useRef(null),a=getGlobalMonitor();useEffect(()=>{t.analytics?.onWorkflowStart&&!s.current&&(s.current=true,t.analytics.onWorkflowStart(t.id,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"start",totalSteps:t.steps.length},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:0,navigationDuration:0,conditionEvaluationDuration:0},"low"));},[t.id,t.analytics,r,a,t.steps.length]),useEffect(()=>{let m=t.steps[e.currentStepIndex];if(m&&l.current!==m.id){if(l.current&&t.analytics?.onStepComplete){let y=i.current.get(l.current);if(y){let u=Date.now()-y;t.analytics.onStepComplete(l.current,u,e.stepData,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_complete",stepId:l.current,duration:u},{timestamp:Date.now(),duration:u,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:u,conditionEvaluationDuration:0},"low");}}l.current=m.id,i.current.set(m.id,Date.now()),t.analytics?.onStepStart&&t.analytics.onStepStart(m.id,Date.now(),r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_start",stepId:m.id,stepIndex:e.currentStepIndex},{timestamp:Date.now(),duration:0,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:0},"low");}},[e.currentStepIndex,t.steps,t.analytics,r,e.stepData,a,t.id]);let S=useCallback((m,y)=>{t.analytics?.onStepSkip&&t.analytics.onStepSkip(m,y,r),a&&a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"step_skip",stepId:m,reason:y},void 0,"medium");},[t.analytics,r,a,t.id]),p=useCallback(m=>{t.analytics?.onError&&t.analytics.onError(m,r),a&&a.trackError(m,`workflow_${t.id}`,{workflowId:t.id,currentStepIndex:e.currentStepIndex,currentStepId:t.steps[e.currentStepIndex]?.id,workflowContext:r});},[t.analytics,r,a,t.id,e.currentStepIndex,t.steps]),o=useCallback((m,y,u)=>{if(!a)return;let h={timestamp:Date.now(),duration:u,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:y,navigationDuration:u,conditionEvaluationDuration:0};a.track("workflow_navigation",`workflow_${t.id}`,{workflowId:t.id,action:"navigation",fromStep:m,toStep:y,direction:y>m?"forward":"backward"},h,u>1e3?"medium":"low");},[a,t.id,t.steps.length]),f=useCallback((m,y)=>{if(!a)return;let u={timestamp:Date.now(),duration:m,workflowId:t.id,stepCount:t.steps.length,currentStepIndex:e.currentStepIndex,navigationDuration:0,conditionEvaluationDuration:m};a.track("condition_evaluation",`workflow_${t.id}`,{workflowId:t.id,conditionsCount:y,currentStepIndex:e.currentStepIndex},u,m>100?"medium":"low");},[a,t.id,t.steps.length,e.currentStepIndex]);return {analyticsStartTime:n,trackStepSkip:S,trackError:p,trackNavigation:o,trackConditionEvaluation:f}}function le(t,e=""){let r={};for(let n in t)if(n in t){let i=t[n],s=e?`${e}.${n}`:n;i!==null&&typeof i=="object"&&!Array.isArray(i)&&!(i instanceof Date)?Object.assign(r,le(i,s)):r[s]=i;}return r}function pe(t,e){let r={...t,...e},n=le(r);return {...r,...n}}function Ve(t,e){return {visible:t.visible,skippable:e===true||t.required}}function ce({workflowConfig:t,workflowState:e,currentStep:r}){let n=useMemo(()=>pe(e.allData,e.stepData),[e.allData,e.stepData]),i=useMemo(()=>{if(r?.conditions)return {visible:r.conditions.visible,required:r.conditions.skippable}},[r?.conditions]),s=re(i,n,{visible:true,disabled:false,required:false,readonly:false}),l=useMemo(()=>Ve(s,r?.allowSkip),[s,r?.allowSkip]),a=useMemo(()=>{let c={};return t.steps.forEach((b,R)=>{b.conditions&&(c[R]={visible:b.conditions.visible,required:b.conditions.skippable});}),c},[t.steps]),S=Ne(a,n),p=useMemo(()=>{let c={};return t.steps.forEach((b,R)=>{let N=S[R];N?c[R]=Ve(N,b.allowSkip):c[R]={visible:true,skippable:b.allowSkip===true};}),c},[t.steps,S]),o=useMemo(()=>{if(!r?.formConfig?.allFields)return {};let c={};for(let b of r.formConfig.allFields)b.conditions&&(c[b.id]=b.conditions);return c},[r?.formConfig?.allFields]),f=Ae(o,n),m=useCallback(c=>c<0||c>=t.steps.length?false:p[c]?.visible??true,[p,t.steps.length]),y=useCallback(c=>c<0||c>=t.steps.length?false:p[c]?.skippable??false,[p,t.steps.length]),u=useCallback(c=>f[c]?.visible??true,[f]),h=useCallback(c=>f[c]?.disabled??false,[f]),v=useCallback(c=>f[c]?.required??false,[f]),W=useCallback(c=>f[c]?.readonly??false,[f]);return {stepConditions:l,fieldConditions:f,allStepConditions:p,isStepVisible:m,isStepSkippable:y,isFieldVisible:u,isFieldDisabled:h,isFieldRequired:v,isFieldReadonly:W}}function de({workflowConfig:t,workflowState:e,workflowContext:r,conditionsHelpers:n,setCurrentStep:i,setTransitioning:s,markStepVisited:l,setStepData:a,onStepChange:S}){let p=useRef(S);p.current=S;let o=t.steps[e.currentStepIndex],f=useCallback(()=>({setStepData:(d,x)=>{a(x,d);},setStepFields:(d,x)=>{let I={...e.allData[d]||{},...x};a(I,d);},getStepData:d=>e.allData[d]||{},setNextStepField:(d,x)=>{let g=e.currentStepIndex+1;if(g<t.steps.length){let I=t.steps[g].id,K={...e.allData[I]||{},[d]:x};a(K,I);}},setNextStepFields:d=>{let x=e.currentStepIndex+1;if(x<t.steps.length){let g=t.steps[x].id,L={...e.allData[g]||{},...d};a(L,g);}},getAllData:()=>({...e.allData}),getSteps:()=>[...t.steps]}),[e.allData,e.currentStepIndex,t.steps,a]),m=useCallback(async d=>{if(d<0||d>=t.steps.length||!n.isStepVisible(d))return false;s(true);try{return p.current&&p.current(e.currentStepIndex,d,r),i(d),l(d,t.steps[d].id),!0}catch(x){return console.error("Step transition failed:",x),t.analytics?.onError&&t.analytics.onError(x,r),false}finally{s(false);}},[t.steps,t.analytics,n,e.currentStepIndex,r,s,i,l]),y=useCallback(d=>{for(let x=d+1;x<t.steps.length;x++)if(n.isStepVisible(x))return x;return null},[t.steps.length,n]),u=useCallback(d=>{for(let x=d-1;x>=0;x--)if(n.isStepVisible(x))return x;return null},[n]),h=useCallback(async()=>{if(o?.onAfterValidation)try{let x=f();await o.onAfterValidation(e.stepData,x,r);}catch(x){return console.error("onAfterValidation failed:",x),t.analytics?.onError&&t.analytics.onError(x,r),false}let d=y(e.currentStepIndex);return d===null?false:m(d)},[o,f,e.stepData,r,t.analytics,e.currentStepIndex,y,m]),v=useCallback(async()=>{let d=u(e.currentStepIndex);return d===null?false:m(d)},[e.currentStepIndex,u,m]),W=useCallback(async()=>!o?.allowSkip&&!n.isStepSkippable(e.currentStepIndex)?false:(t.analytics?.onStepSkip&&t.analytics.onStepSkip(o.id,"user_skip",r),h()),[o,n,e.currentStepIndex,t.analytics,r,h]),c=useCallback(d=>d<0||d>=t.steps.length?false:n.isStepVisible(d),[t.steps.length,n]),b=useCallback(()=>{let d=y(e.currentStepIndex);return d!==null&&c(d)},[e.currentStepIndex,y,c]),R=useCallback(()=>{let d=u(e.currentStepIndex);return d!==null&&c(d)},[e.currentStepIndex,u,c]),N=useCallback(()=>o?.allowSkip===true&&n.isStepSkippable(e.currentStepIndex),[o?.allowSkip,n,e.currentStepIndex]);return {goToStep:m,goNext:h,goPrevious:v,skipStep:W,canGoToStep:c,canGoNext:b,canGoPrevious:R,canSkipCurrentStep:N}}function pt(t,e){switch(e.type){case "SET_CURRENT_STEP":return {...t,currentStepIndex:e.stepIndex};case "SET_STEP_DATA":return {...t,stepData:e.data,allData:{...t.allData,[e.stepId]:e.data}};case "SET_ALL_DATA":return {...t,allData:e.data};case "SET_FIELD_VALUE":{let r={...t.stepData,[e.fieldId]:e.value};return {...t,stepData:r,allData:{...t.allData,[e.stepId]:r}}}case "SET_SUBMITTING":return {...t,isSubmitting:e.isSubmitting};case "SET_TRANSITIONING":return {...t,isTransitioning:e.isTransitioning};case "MARK_STEP_VISITED":return {...t,visitedSteps:new Set([...t.visitedSteps,e.stepId])};case "RESET_WORKFLOW":return {currentStepIndex:0,allData:{},stepData:{},visitedSteps:new Set,isSubmitting:false,isTransitioning:false,isInitializing:false};case "LOAD_PERSISTED_STATE":return {...t,...e.state};case "SET_INITIALIZATION_COMPLETE":return {...t,isInitializing:false};default:return t}}function ue({defaultValues:t={},defaultStepIndex:e,workflowSteps:r,persistence:n}){let i=useMemo(()=>{let c=new Set;if(e&&e>0&&r)for(let b=0;b<e;b++)r[b]&&c.add(r[b].id);return c},[e,r]),s={currentStepIndex:e??0,allData:t,stepData:{},visitedSteps:i,isSubmitting:false,isTransitioning:false,isInitializing:true},[l,a]=useReducer(pt,s),S=n?.adapter?X({workflowId:n.workflowId,workflowState:l,adapter:n.adapter,options:n.options,userId:n.userId}):null,p=useCallback(c=>{a({type:"SET_CURRENT_STEP",stepIndex:c});},[]),o=useCallback((c,b)=>{a({type:"SET_STEP_DATA",data:c,stepId:b});},[]),f=useCallback((c,b,R)=>{a({type:"SET_FIELD_VALUE",fieldId:c,value:b,stepId:R});},[]),m=useCallback(c=>{a({type:"SET_SUBMITTING",isSubmitting:c});},[]),y=useCallback(c=>{a({type:"SET_TRANSITIONING",isTransitioning:c});},[]),u=useCallback((c,b)=>{a({type:"MARK_STEP_VISITED",stepIndex:c,stepId:b});},[]),h=useCallback(()=>{a({type:"RESET_WORKFLOW"});},[]),v=useCallback(()=>{a({type:"SET_INITIALIZATION_COMPLETE"});},[]),W=useCallback(async()=>{if(!S)return v(),false;try{let c=await S.loadPersistedData();if(c){let b={currentStepIndex:c.currentStepIndex,allData:c.allData,stepData:c.stepData,visitedSteps:new Set(c.visitedSteps)};return a({type:"LOAD_PERSISTED_STATE",state:b}),v(),!0}}catch(c){console.error("Failed to load persisted state:",c);}return v(),false},[S,v]);return {workflowState:l,setCurrentStep:p,setStepData:o,setFieldValue:f,setSubmitting:m,setTransitioning:y,markStepVisited:u,resetWorkflow:h,loadPersistedState:W,persistence:S?{isPersisting:S.isPersisting,persistenceError:S.persistenceError,persistNow:S.persistNow,clearPersistedData:S.clearPersistedData,hasPersistedData:S.hasPersistedData}:null}}function fe({workflowConfig:t,workflowState:e,workflowContext:r,setSubmitting:n,onWorkflowComplete:i,analyticsStartTime:s}){let l=useRef(i);l.current=i;let a=useCallback(async()=>{n(true);try{if(l.current&&await l.current(e.allData),t.analytics?.onWorkflowComplete){let p=Date.now()-s.current;t.analytics.onWorkflowComplete(t.id,p,e.allData);}}catch(p){throw console.error("Workflow submission failed:",p),t.analytics?.onError&&t.analytics.onError(p,r),p}finally{n(false);}},[e.allData,t.analytics,t.id,r,s,n]),S=useCallback(()=>e.isSubmitting?false:e.currentStepIndex===t.steps.length-1,[e.isSubmitting,e.currentStepIndex,t.steps.length]);return {submitWorkflow:a,isSubmitting:e.isSubmitting,canSubmit:S()}}var Oe=createContext(null);function ye({children:t,workflowConfig:e,defaultValues:r={},defaultStep:n,onStepChange:i,onWorkflowComplete:s,className:l}){let a=useRef(i),S=useRef(s);a.current=i,S.current=s;let p=useMemo(()=>{if(!n)return 0;let w=e.steps.findIndex(P=>P.id===n);return w===-1?(console.warn(`Default step with ID "${n}" not found. Starting at step 0.`),0):w},[n,e.steps]),{workflowState:o,setCurrentStep:f,setStepData:m,setFieldValue:y,setSubmitting:u,setTransitioning:h,markStepVisited:v,resetWorkflow:W,loadPersistedState:c,persistence:b}=ue({defaultValues:r,defaultStepIndex:p,workflowSteps:e.steps,persistence:e.persistence?{workflowId:e.id,adapter:e.persistence.adapter,options:e.persistence.options,userId:e.persistence.userId}:void 0});useEffect(()=>{e.persistence&&c&&c();},[]);let R=useMemo(()=>({isPersisting:b?.isPersisting??false,persistenceError:b?.persistenceError??null,persistNow:b?.persistNow}),[b?.isPersisting,b?.persistenceError,b?.persistNow]),N=useMemo(()=>({workflowId:e.id,currentStepIndex:o.currentStepIndex,totalSteps:e.steps.length,allData:o.allData,stepData:o.stepData,visitedSteps:o.visitedSteps}),[e.id,e.steps.length,o.currentStepIndex,o.allData,o.stepData,o.visitedSteps]),d=useMemo(()=>e.steps[o.currentStepIndex],[e.steps,o.currentStepIndex]),x=useMemo(()=>d?.formConfig,[d?.formConfig]),g=ce({workflowConfig:e,workflowState:o,currentStep:d}),I=useMemo(()=>{let w=-1;for(let D=0;D<e.steps.length;D++)if(g.isStepVisible(D)){w=D;break}let P=-1;for(let D=e.steps.length-1;D>=0;D--)if(g.isStepVisible(D)){P=D;break}return {...N,isFirstStep:o.currentStepIndex===w,isLastStep:o.currentStepIndex===P}},[N,o.currentStepIndex,g,e.steps.length]),{analyticsStartTime:L}=ae({workflowConfig:e,workflowState:o,workflowContext:I}),{goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}=de({workflowConfig:e,workflowState:o,workflowContext:I,conditionsHelpers:g,setCurrentStep:f,setTransitioning:h,markStepVisited:v,setStepData:m,onStepChange:a.current}),Y=useRef(false);useEffect(()=>{if(Y.current)return;if(!g.isStepVisible(o.currentStepIndex)){for(let P=0;P<e.steps.length;P++)if(g.isStepVisible(P)){f(P),v(P,e.steps[P].id);break}}Y.current=true;},[o.currentStepIndex,e.steps,f,v]),useEffect(()=>{if(!Y.current)return;if(!g.isStepVisible(o.currentStepIndex)){let P=null;for(let D=o.currentStepIndex+1;D<e.steps.length;D++)if(g.isStepVisible(D)){P=D;break}if(P===null){for(let D=o.currentStepIndex-1;D>=0;D--)if(g.isStepVisible(D)){P=D;break}}P!==null&&(f(P),v(P,e.steps[P].id));}},[g,o.currentStepIndex,e.steps,f,v]);let{submitWorkflow:q,isSubmitting:We,canSubmit:De}=fe({workflowConfig:e,workflowState:o,workflowContext:I,setSubmitting:u,onWorkflowComplete:S.current,analyticsStartTime:L}),Q=useCallback((w,P)=>{y(w,P,d?.id||"");},[y,d?.id]),Re=useCallback(w=>{m(w,d?.id||"");},[m,d?.id]),qe=useCallback(async w=>{d?.id&&w&&m(w,d.id),I.isLastStep?await q():await $();},[I.isLastStep,q,$,d?.id,m]),Ee=useMemo(()=>({goToStep:K,goNext:$,goPrevious:ve,skipStep:he,canGoToStep:xe,canGoNext:Ie,canGoPrevious:ke,canSkipCurrentStep:Pe}),[K,$,ve,he,xe,Ie,ke,Pe]),we=useMemo(()=>({setValue:Q,setStepData:Re,resetWorkflow:W}),[Q,Re,W]),Te=useMemo(()=>({submitWorkflow:q,isSubmitting:We,canSubmit:De}),[q,We,De]),ze=useMemo(()=>({workflowState:o,workflowConfig:e,currentStep:d,context:I,formConfig:x,conditionsHelpers:g,currentStepMetadata:d?.metadata,...Ee,...we,...Te,persistNow:R.persistNow,isPersisting:R.isPersisting,persistenceError:R.persistenceError}),[o,e,d,I,x,g,Ee,we,Te,R]),Je=useMemo(()=>{if(!d?.id)return {};let w=o?.allData[d.id]||{};if(!x?.allFields)return w;let P=new Set(x.allFields.map(z=>z.id)),D={};for(let[z,He]of Object.entries(w))P.has(z)&&(D[z]=He);return D},[o?.allData,d?.id,x?.allFields]),Xe=useMemo(()=>o.isInitializing.toString(),[o.isInitializing]);return jsx(Oe.Provider,{value:ze,children:jsx(FormProvider,{formConfig:x,defaultValues:Je,onFieldChange:Q,"data-workflow-id":e.id,className:l,onSubmit:qe,children:t},Xe)})}function T(){let t=useContext(Oe);if(!t)throw new Error("useWorkflowContext must be used within a WorkflowProvider");return t}function yt({children:t,workflowConfig:e,...r}){let[n,i]=useState(),s=useMemo(()=>e instanceof U?e.build():e,[e]);return useEffect(()=>{if(typeof window<"u"&&B.shouldDisplayWatermark()){let a=B.getWatermarkMessage();i(a);}},[]),jsxs("div",{style:{position:"relative"},children:[jsx(ye,{...r,workflowConfig:s,children:t}),n&&jsx("div",{style:{position:"absolute",top:"10px",right:"10px",background:"rgba(0, 0, 0, 0.8)",color:"white",padding:"4px 8px",borderRadius:"4px",fontSize:"12px",fontFamily:"monospace",zIndex:1e3,pointerEvents:"none",opacity:.7},children:n})]})}var xt=ht.memo(function({stepId:e,children:r}){let{currentStep:n}=T();if(!n||e&&n.id!==e)return null;let{formConfig:i,renderer:s}=n;return i?s?s(n):r??jsx(FormBody,{}):null});var Rt=ht.memo(function({className:e,isSubmitting:r,...n}){let{context:i,workflowState:s,workflowConfig:l,currentStep:a}=T(),{submit:S,formState:p}=useFormContext(),o=useMemo(()=>{let y=p.isSubmitting||s.isSubmitting,u=r??y,h=!s.isTransitioning&&!u;return {finalIsSubmitting:u,canGoNext:h}},[p.isSubmitting,s.isSubmitting,s.isTransitioning,r]),f=useCallback(async y=>{y?.preventDefault(),o.canGoNext&&await S(y);},[o.canGoNext,S]),m=useMemo(()=>({isLastStep:i.isLastStep,canGoNext:o.canGoNext,isSubmitting:o.finalIsSubmitting,onSubmit:f,className:e,currentStep:a,stepData:p.values||{},allData:i.allData,context:i}),[i.isLastStep,o.canGoNext,o.finalIsSubmitting,f,e,a,p.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowNextButton",renderer:l.renderConfig?.nextButtonRenderer,props:m,...n})});var Nt=ht.memo(function({className:e,isSubmitting:r,...n}){let{context:i,goPrevious:s,workflowState:l,workflowConfig:a,currentStep:S}=T(),{formState:p}=useFormContext(),o=useMemo(()=>{let y=p.isSubmitting||l.isSubmitting,u=r??y,h=i.currentStepIndex>0&&!l.isTransitioning&&!u;return {finalIsSubmitting:u,canGoPrevious:h}},[p.isSubmitting,l.isSubmitting,l.isTransitioning,i.currentStepIndex,r]),f=useCallback(async y=>{y?.preventDefault(),o.canGoPrevious&&await s();},[o.canGoPrevious,s]),m=useMemo(()=>({canGoPrevious:o.canGoPrevious,isSubmitting:o.finalIsSubmitting,onPrevious:f,className:e,currentStep:S,stepData:p.values||{},allData:i.allData,context:i}),[o.canGoPrevious,o.finalIsSubmitting,f,e,S,p.values,i.allData,i]);return jsx(ComponentRendererWrapper,{name:"WorkflowPreviousButton",renderer:a.renderConfig?.previousButtonRenderer,props:m,...n})});var _t=ht.memo(function({className:e,isSubmitting:r,...n}){let{currentStep:i,skipStep:s,workflowState:l,workflowConfig:a,context:S,conditionsHelpers:p}=T(),{formState:o}=useFormContext(),f=useMemo(()=>{let u=o.isSubmitting||l.isSubmitting,h=r??u,v=(!!i?.allowSkip||p.isStepSkippable(l.currentStepIndex))&&!l.isTransitioning&&!h;return {finalIsSubmitting:h,canSkip:v}},[o.isSubmitting,l.isSubmitting,l.isTransitioning,l.currentStepIndex,i?.allowSkip,p.isStepSkippable,r]),m=useCallback(async u=>{u?.preventDefault(),f.canSkip&&await s();},[f.canSkip,s]),y=useMemo(()=>({canSkip:f.canSkip,isSubmitting:f.finalIsSubmitting,onSkip:m,className:e,currentStep:i,stepData:o.values||{},allData:S.allData,context:S}),[f.canSkip,f.finalIsSubmitting,m,e,i,o.values,S.allData,S]);return jsx(ComponentRendererWrapper,{name:"WorkflowSkipButton",renderer:a.renderConfig?.skipButtonRenderer,props:y,...n})});var $t=ht.memo(function({onStepClick:e,className:r,...n}){let{workflowConfig:i,workflowState:s,goToStep:l,conditionsHelpers:a}=T(),{visibleSteps:S,visibleToOriginalIndexMap:p,originalToVisibleIndexMap:o}=useMemo(()=>{let h=[],v=new Map,W=new Map;return i.steps.forEach((c,b)=>{if(a.isStepVisible(b)){let R=h.length;h.push(c),v.set(R,b),W.set(b,R);}}),{visibleSteps:h,visibleToOriginalIndexMap:v,originalToVisibleIndexMap:W}},[i.steps,a]),f=useCallback(h=>{let v=p.get(h);v!==void 0&&(e?e(v):l(v));},[p,e,l]),m=useMemo(()=>o.get(s.currentStepIndex)??-1,[o,s.currentStepIndex]),y=useMemo(()=>{let h=new Set(S.map(W=>W.id)),v=new Set;for(let W of s.visitedSteps)h.has(W)&&v.add(W);return v},[S,s.visitedSteps]),u=useMemo(()=>({steps:S,currentStepIndex:m,visitedSteps:y,onStepClick:f,className:r}),[S,m,y,f,r]);return jsx(ComponentRendererWrapper,{name:"WorkflowStepper",renderer:i.renderConfig?.stepperRenderer,props:u,...n})});var be=class{constructor(e={}){this.version="1.0.0";this.keyPrefix=e.keyPrefix??"rilay_workflow_",this.compress=e.compress??false,this.maxAge=e.maxAge,this._isAvailable=this.isLocalStorageAvailable();}async save(e,r){if(this._isAvailable)try{let n=this.getStorageKey(e),i={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},s=JSON.stringify(i),l=this.compress?this.compressData(s):s;localStorage.setItem(n,l);}catch(n){if(n instanceof Error)if(n.name==="QuotaExceededError"||n.message.includes("quota")){await this.clearExpiredData();try{let i=this.getStorageKey(e),s={data:{...r,lastSaved:Date.now()},version:this.version,expiresAt:this.maxAge?Date.now()+this.maxAge:void 0},l=JSON.stringify(s),a=this.compress?this.compressData(l):l;localStorage.setItem(i,a);}catch(i){throw new E("localStorage quota exceeded and cleanup failed","QUOTA_EXCEEDED",i)}}else throw new E(`Failed to save to localStorage: ${n.message}`,"SAVE_FAILED",n);else throw new E("Unknown error occurred while saving","SAVE_FAILED")}}async load(e){if(!this._isAvailable)return null;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return null;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),null):{...s.data,visitedSteps:Array.isArray(s.data.visitedSteps)?s.data.visitedSteps:[]}}catch(r){throw r instanceof Error?new E(`Failed to load from localStorage: ${r.message}`,"LOAD_FAILED",r):new E("Unknown error occurred while loading","LOAD_FAILED")}}async remove(e){if(this._isAvailable)try{let r=this.getStorageKey(e);localStorage.removeItem(r);}catch(r){throw r instanceof Error?new E(`Failed to remove from localStorage: ${r.message}`,"REMOVE_FAILED",r):new E("Unknown error occurred while removing","REMOVE_FAILED")}}async exists(e){if(!this._isAvailable)return false;try{let r=this.getStorageKey(e),n=localStorage.getItem(r);if(!n)return !1;let i=this.compress?this.decompressData(n):n,s=JSON.parse(i);return s.expiresAt&&Date.now()>s.expiresAt?(await this.remove(e),!1):!0}catch{return false}}async listKeys(){if(!this._isAvailable)return [];try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix)){let i=n.substring(this.keyPrefix.length);await this.exists(i)&&e.push(i);}}return e}catch(e){throw e instanceof Error?new E(`Failed to list keys: ${e.message}`,"LIST_FAILED",e):new E("Unknown error occurred while listing keys","LIST_FAILED")}}async clear(){try{let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n?.startsWith(this.keyPrefix)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}catch(e){throw e instanceof Error?new E(`Failed to clear localStorage: ${e.message}`,"CLEAR_FAILED",e):new E("Unknown error occurred while clearing","CLEAR_FAILED")}}getStorageKey(e){return `${this.keyPrefix}${e}`}isLocalStorageAvailable(){try{let e="__rilay_test__";return localStorage.setItem(e,"test"),localStorage.removeItem(e),!0}catch{return false}}compressData(e){return btoa(e)}decompressData(e){try{return atob(e)}catch{return e}}async clearExpiredData(){if(!this._isAvailable)return;let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);if(n?.startsWith(this.keyPrefix))try{let i=localStorage.getItem(n);if(i){let s=this.compress?this.decompressData(i):i,l=JSON.parse(s);l.expiresAt&&Date.now()>l.expiresAt&&e.push(n);}}catch{e.push(n);}}for(let r of e)localStorage.removeItem(r);}};
2
+ export{be as LocalStorageAdapter,B as RilayLicenseManager,yt as Workflow,xt as WorkflowBody,Rt as WorkflowNextButton,E as WorkflowPersistenceError,Nt as WorkflowPreviousButton,ye as WorkflowProvider,_t as WorkflowSkipButton,$t as WorkflowStepper,pe as combineWorkflowDataForConditions,se as debounce,le as flattenObject,U as flow,ie as generateStorageKey,nt as mergePersistedState,Le as persistedToWorkflowState,re as useConditionEvaluation,X as usePersistence,it as useStepMetadata,ae as useWorkflowAnalytics,ce as useWorkflowConditions,T as useWorkflowContext,de as useWorkflowNavigation,ue as useWorkflowState,fe as useWorkflowSubmission,rt as validatePersistedData,ne as workflowStateToPersisted};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rilaykit/workflow",
3
- "version": "11.0.0",
3
+ "version": "12.1.0",
4
4
  "description": "Commercial workflow and multi-step form utilities for RilayKit - License required for all use",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -34,8 +34,8 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@noble/ed25519": "^1.7.1",
37
- "@rilaykit/core": "10.0.0",
38
- "@rilaykit/forms": "10.0.0"
37
+ "@rilaykit/forms": "11.1.0",
38
+ "@rilaykit/core": "11.1.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "react": ">=18.0.0",