---
source: framec/tests/typescript_snapshots.rs
expression: "compile_fixture(\"03_persist\", \"typescript\")"
---
class CounterFrameEvent {
    public _message: string;
    public _parameters: any[];

    constructor(message: string, parameters: any[]) {
        this._message = message;
        this._parameters = parameters;
    }
}


class CounterFrameContext {
    public event: CounterFrameEvent;
    public _return: any;
    public _data: Record<string, any>;
    public _transitioned: boolean;

    constructor(event: CounterFrameEvent, default_return: any) {
        this.event = event;
        this._return = default_return;
        this._data = {  };
        this._transitioned = false;
    }
}


class CounterCompartment {
    public state: string;
    public state_args: any[];
    public state_vars: Record<string, any>;
    public enter_args: any[];
    public exit_args: any[];
    public forward_event: any;
    public parent_compartment: CounterCompartment | null;

    constructor(state: string, parent_compartment: CounterCompartment | null = null) {
        this.state = state;
        this.state_args = [];
        this.state_vars = {  };
        this.enter_args = [];
        this.exit_args = [];
        this.forward_event = null;
        this.parent_compartment = parent_compartment;
    }

    public copy(): CounterCompartment {
        const c = new CounterCompartment(this.state, this.parent_compartment);
        c.state_args = {...this.state_args};
        c.state_vars = {...this.state_vars};
        c.enter_args = {...this.enter_args};
        c.exit_args = {...this.exit_args};
        c.forward_event = this.forward_event;
        return c;
    }
}


export class Counter {
    private _state_stack: Array<any>;
    private __compartment: CounterCompartment;
    private __next_compartment: CounterCompartment | null;
    private _context_stack: Array<any>;
    private count: number = 0;

    constructor() {
        this._state_stack = [];
        this._context_stack = [];
        this.__compartment = this.__prepareEnter("Counting", [], []);
        this.__next_compartment = null;
    }

    _frame_init(): void {
        const __e = new CounterFrameEvent("$>", this.__compartment.enter_args);
        const __ctx = new CounterFrameContext(__e, null);
        this._context_stack.push(__ctx);
        this.__kernel(__e);
        this._context_stack.pop();
    }

    static _create(): Counter {
        const c = new Counter();
        c._frame_init();
        return c;
    }

    static readonly _HSM_CHAIN: Record<string, string[]> = {
        "Counting": ["Counting"],
    };
    private __prepareEnter(leaf: string, state_args: any[], enter_args: any[]): CounterCompartment {
        let comp: CounterCompartment | null = null;
        for (const name of Counter._HSM_CHAIN[leaf]) {
            const new_comp = new CounterCompartment(name);
            new_comp.state_args = [...state_args];
            new_comp.enter_args = [...enter_args];
            new_comp.parent_compartment = comp;
            comp = new_comp;
        }
        return comp!;
    }

    private __prepareExit(exit_args: any[]) {
        let comp: CounterCompartment | null = this.__compartment;
        while (comp !== null) {
            comp.exit_args = [...exit_args];
            comp = comp.parent_compartment;
        }
    }

    private __kernel(__e: CounterFrameEvent) {
        // Route event to current state.
        this.__router(__e);
        // Drain any transitions queued by the handler.
        while (this.__next_compartment !== null) {
            const next_compartment = this.__next_compartment;
            this.__next_compartment = null;
            // Exit the current (leaf) state.
            const exit_event = new CounterFrameEvent("<$", this.__compartment.exit_args);
            this.__router(exit_event);
            // Switch to the new compartment.
            this.__compartment = next_compartment;
            // Three-branch forward-event handling.
            const forward_event = next_compartment.forward_event;
            next_compartment.forward_event = null;
            if (forward_event === null) {
                // No forwarded event — synthesize a fresh $>.
                const enter_event = new CounterFrameEvent("$>", this.__compartment.enter_args);
                this.__router(enter_event);
            } else if (forward_event._message === "$>") {
                // Forwarded event IS $> — dispatch directly so the
                // destination's $> handler receives the caller's payload.
                this.__router(forward_event);
            } else {
                // Forwarded event is not $> — initialize the destination
                // with a fresh $>, then dispatch the forward.
                const enter_event = new CounterFrameEvent("$>", this.__compartment.enter_args);
                this.__router(enter_event);
                this.__router(forward_event);
            }
            for (const ctx of this._context_stack) {
                ctx._transitioned = true;
            }
        }
    }

    private __router(__e: CounterFrameEvent) {
        const handler_name = `_state_${this.__compartment.state}`;
        const handler = (this as any)[handler_name];
        if (handler) {
            handler.call(this, __e, this.__compartment);
        }
    }

    private __transition(next_compartment: CounterCompartment) {
        this.__next_compartment = next_compartment;
    }

    public increment(by: number) {
        const __e = new CounterFrameEvent("increment", [by]);
        const __ctx = new CounterFrameContext(__e, null);
        this._context_stack.push(__ctx);
        try {
            this.__kernel(__e);
        } finally {
            this._context_stack.pop();
        }
    }

    public value(): number {
        const __e = new CounterFrameEvent("value", []);
        const __ctx = new CounterFrameContext(__e, null);
        __ctx._return = 0;
        this._context_stack.push(__ctx);
        try {
            this.__kernel(__e);
            return this._context_stack.pop()!._return;
        } catch (__frame_err) {
            this._context_stack.pop();
            throw __frame_err;
        }
    }

    private _state_Counting(__e: CounterFrameEvent, compartment: CounterCompartment) {
        if (__e._message === "increment") {
            this._s_Counting_hdl_user_increment(__e, compartment);
            return;
        }
        if (__e._message === "value") {
            this._s_Counting_hdl_user_value(__e, compartment);
            return;
        }
    }

    private _s_Counting_hdl_user_increment(__e: CounterFrameEvent, compartment: CounterCompartment) {
        const by = __e._parameters[0];
        self.count = self.count + by
    }

    private _s_Counting_hdl_user_value(__e: CounterFrameEvent, compartment: CounterCompartment) {
        this._context_stack[this._context_stack.length - 1]._return = self.count;
    }

    public snapshot(): string {
        if (this._context_stack.length > 0) { throw new Error("E700: system not quiescent"); }
        const serializeComp = (c: any): any => {
            if (!c) return null;
            return {
                state: c.state,
                state_args: {...c.state_args},
                state_vars: {...c.state_vars},
                enter_args: {...c.enter_args},
                exit_args: {...c.exit_args},
                forward_event: c.forward_event,
                parent_compartment: serializeComp(c.parent_compartment),
            };
        };
        return JSON.stringify({
            _compartment: serializeComp(this.__compartment),
            _state_stack: this._state_stack.map((c: any) => serializeComp(c)),
            count: this.count,
        });
    }

    public restore(json: string) {
        const deserializeComp = (data: any): CounterCompartment | null => {
            if (!data) return null;
            const comp = new CounterCompartment(data.state);
            comp.state_args = {...(data.state_args || {})};
            comp.state_vars = {...(data.state_vars || {})};
            comp.enter_args = {...(data.enter_args || {})};
            comp.exit_args = {...(data.exit_args || {})};
            comp.forward_event = data.forward_event;
            comp.parent_compartment = deserializeComp(data.parent_compartment);
            return comp;
        };
        const _parsed = JSON.parse(json);
        this.__compartment = deserializeComp(_parsed._compartment);
        this.__next_compartment = null;
        this._state_stack = (_parsed._state_stack || []).map((c: any) => deserializeComp(c));
        this._context_stack = [];
        this.count = _parsed.count;
    }
}
