@scandit/web-datacapture-core
Version:
Scandit Data Capture SDK for the Web
1 lines • 2.36 kB
JavaScript
import {a}from'./chunk-XR65N6EG.js';var c=class{constructor(t,e){this._listeners=new Set;this._pendingTransitions=new Map;this._taskQueue=[];this._isProcessingQueue=false;this._currentState=t,this._initialState=t,this._validTransitions=new Set(e.map(i=>`${i.from}->${i.to}`));}get currentState(){return this._currentState}get isInitializing(){return this._currentState!==this._initialState}addListener(t){this._listeners.add(t);}removeListener(t){this._listeners.delete(t);}canTransitionTo(t){let e=`${this._currentState}->${t}`;return this._validTransitions.has(e)&&!this._pendingTransitions.has(e)}transitionTo(t,e){if(!this.canTransitionTo(t))throw new Error(`Invalid transition from '${this._currentState}' to '${t}'`);let i=this._currentState;this._currentState=t,this.notifyListeners(this._currentState,i,e);}async enqueueTask(t){return new Promise((e,i)=>{this._taskQueue.push({execute:t,resolve:e,reject:i}),this.processQueue();})}async processQueue(){if(!(this._isProcessingQueue||this._taskQueue.length===0)){for(this._isProcessingQueue=true;this._taskQueue.length>0;){let t=this._taskQueue.shift();try{let e=await t.execute();t.resolve(e);}catch(e){t.reject(e);}}this._isProcessingQueue=false;}}async executeAsyncTransition(t){return this.enqueueTask(async()=>{let{targetState:e,action:i,onSuccess:s,onError:r}=t,a=`${this._currentState}->${e}`;if(!this.canTransitionTo(e))throw new Error(`Invalid async transition from '${this._currentState}' to '${e}'`);this.transitionTo(e);try{let n=i();this._pendingTransitions.set(a,n);let o=await n;return s&&this.canTransitionTo(s)&&this.transitionTo(s,{result:o}),o}catch(n){throw r&&this.canTransitionTo(r)&&this.transitionTo(r,{error:n}),n}finally{this._pendingTransitions.delete(a);}})}async waitForState(t,e){if(this._currentState!==t)return new Promise((i,s)=>{let r;e!==void 0&&(r=setTimeout(()=>{this.removeListener(a),s(new Error(`Timeout waiting for state '${t}' after ${e}ms`));},e));let a=n=>{n===t&&(r&&clearTimeout(r),this.removeListener(a),i());};this.addListener(a);})}async reset(t){return this.enqueueTask(async()=>{let e=this._currentState;this._currentState=t,this._pendingTransitions.clear(),this.notifyListeners(this._currentState,e,{reset:true});})}notifyListeners(t,e,i){for(let s of this._listeners)try{s(t,e,i);}catch(r){a.warn("State machine listener error:",r);}}};export{c as a};