Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

refactor(channel): run target-message on createMachine (#6036)

teofb311529664c
diff --git a/apps/web/package.json b/apps/web/package.json
index 8b8a006d09..b5982fbab5 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -85,6 +85,7 @@
"@macro-inc/collaboration": "workspace:*",
"@macro-inc/email-renderer": "workspace:*",
"@macro-inc/lexical-core": "workspace:*",
+ "@macro-inc/machine": "workspace:*",
"@macro-inc/observability": "workspace:*",
"@macro-inc/spreadsheet": "workspace:*",
"@normy/query-core": "^0.21.0",
diff --git a/apps/web/src/features/channel/Channel/create-target-message-controller.ts b/apps/web/src/features/channel/Channel/create-target-message-controller.ts
index 526c3d9770..cc29f55143 100644
--- a/apps/web/src/features/channel/Channel/create-target-message-controller.ts
+++ b/apps/web/src/features/channel/Channel/create-target-message-controller.ts
@@ -1,10 +1,23 @@
+import { createSolidMachine } from '@macro-inc/machine/solid';
import { queryClient } from '@queries/client';
import {
getMessageTimelineQueryKey,
type MessageTimelineData,
} from '@queries/messages/timeline';
-import { type Accessor, createEffect, on, onCleanup } from 'solid-js';
-import { createStore } from 'solid-js/store';
+import { type Accessor, untrack } from 'solid-js';
+import { match } from 'ts-pattern';
+import {
+ activeTargetMessageId,
+ activeTargetMessageReplyId,
+ type Command,
+ type Event,
+ hasPendingElementScroll,
+ initialState,
+ pendingScrollTargetId,
+ pendingTargetReplyId,
+ type State,
+ targetMessageDef,
+} from './target-message';
/**
* How long a navigation target keeps its accent highlight after its scroll
@@ -27,180 +40,99 @@ export type TargetMessageController = ReturnType<
typeof createTargetMessageController
>;
-type TargetMessageData = {
- activeTargetMessageId: string | undefined;
- activeTargetMessageReplyId: string | undefined;
- loadAroundMessageId: string | undefined;
- pendingScrollTargetId: string | undefined;
- pendingTargetReplyId: string | undefined;
-};
-
+/**
+ * Runner for the target-message machine. All decisions live in
+ * `target-message.ts`; this file owns the three things that touch the
+ * world: the flash timer, cache restoration, and the readiness condition.
+ * No effects: readiness is a derivation the selectors consume.
+ */
export function createTargetMessageController(
options: CreateTargetMessageControllerOptions
) {
- const initialTargetMessageData: TargetMessageData = {
- activeTargetMessageId: options.initialTargetMessageId,
- activeTargetMessageReplyId: options.initialTargetMessageReplyId,
- loadAroundMessageId: options.initialTargetMessageId,
- pendingScrollTargetId: options.initialTargetMessageId,
- pendingTargetReplyId: options.initialTargetMessageReplyId,
- };
-
- const [targetMessageData, setTargetMessageData] =
- createStore<TargetMessageData>(initialTargetMessageData);
-
- let flashTimeout: ReturnType<typeof setTimeout> | undefined;
-
- const cancelFlash = () => {
- if (flashTimeout === undefined) return;
- clearTimeout(flashTimeout);
- flashTimeout = undefined;
- };
-
- /**
- * Whether a target element still owes the viewport a scroll — the root row,
- * a nested reply, or both. A nested target acknowledges its outer row early
- * (see the effect below) so the reply's own scroll can begin, so the root's
- * pending id alone does not answer this.
- */
- const hasPendingElementScroll = () =>
- targetMessageData['pendingScrollTargetId'] !== undefined ||
- targetMessageData['pendingTargetReplyId'] !== undefined;
-
- const syncFlash = () => {
- cancelFlash();
-
- const activeTargetMessageId = targetMessageData['activeTargetMessageId'];
-
- if (!activeTargetMessageId || hasPendingElementScroll()) return;
-
- flashTimeout = setTimeout(() => {
- flashTimeout = undefined;
- clearActiveTarget(activeTargetMessageId);
- }, TARGETED_MESSAGE_FLASH_MS);
- };
-
- // Highlight and scroll-state changes go through this function so the flash
- // timer stays synchronized. loadAroundMessageId does not affect highlighting,
- // so it can be updated directly with setTargetMessageData.
- const updateTargetMessageData = (patch: Partial<TargetMessageData>) => {
- setTargetMessageData(patch);
- syncFlash();
- };
-
- onCleanup(cancelFlash);
-
- const hasMessageLoaded = (messageId: string) =>
- options.messageKeys().includes(messageId);
-
- const goToMessage = (messageId: string, replyId?: string) => {
- const isSameTarget =
- targetMessageData['activeTargetMessageId'] === messageId;
- const isSameReplyTarget =
- targetMessageData['activeTargetMessageReplyId'] === replyId;
- const isPending = targetMessageData['pendingScrollTargetId'] === messageId;
-
- if (isSameTarget && isSameReplyTarget && isPending) return;
-
- updateTargetMessageData({
- activeTargetMessageId: messageId,
- activeTargetMessageReplyId: replyId,
- // TODO: need a better approach where the load around should be undefined
- // the current approach is a hack to fix rapid navigation race condition
- loadAroundMessageId: hasMessageLoaded(messageId)
- ? targetMessageData['loadAroundMessageId']
- : messageId,
- pendingScrollTargetId: messageId,
- pendingTargetReplyId: replyId,
- });
- };
-
- const completePendingScroll = (messageId: string) => {
- if (targetMessageData['pendingScrollTargetId'] !== messageId) return;
- updateTargetMessageData({ pendingScrollTargetId: undefined });
- };
-
- const completePendingReplyScroll = (messageId: string, replyId: string) => {
- if (targetMessageData['activeTargetMessageId'] !== messageId) return;
- if (targetMessageData['pendingTargetReplyId'] !== replyId) return;
- updateTargetMessageData({ pendingTargetReplyId: undefined });
- };
-
- createEffect(
- on(
- [
- options.isReady,
- () => targetMessageData['pendingScrollTargetId'],
- options.messageKeys,
- ],
- ([isReady, pendingTargetId]) => {
- if (!isReady || !pendingTargetId) return;
- if (!hasMessageLoaded(pendingTargetId)) return;
-
- // Channel keeps a pending target's row mounted. Scrolling the whole
- // row first can land on the wrong part of a tall thread and creates a
- // visible intermediate position, so the measured root/reply element
- // performs the only viewport movement.
- const nestedTarget = !!targetMessageData['pendingTargetReplyId'];
-
- const restoredDefaultPagination =
- restoreDefaultChannelPaginationAfterTargetLoad(
+ const machine = createSolidMachine<State, Event, Command>({
+ initial: initialState({
+ messageId: options.initialTargetMessageId,
+ replyId: options.initialTargetMessageReplyId,
+ }),
+ def: targetMessageDef,
+
+ scopes: {
+ flashing: (_s, dispatch) => {
+ const timer = setTimeout(
+ () => dispatch({ t: 'flash-elapsed' }),
+ TARGETED_MESSAGE_FLASH_MS
+ );
+ return () => clearTimeout(timer);
+ },
+ },
+
+ execute: (cmd, dispatch) => {
+ match(cmd)
+ .with({ t: 'restore-default-pagination' }, (cmd) => {
+ const restored = restoreDefaultChannelPaginationAfterTargetLoad(
options.channelId(),
- targetMessageData['loadAroundMessageId']
+ cmd.loadAround
);
- if (restoredDefaultPagination) {
- setTargetMessageData('loadAroundMessageId', undefined);
- }
- // Nested replies acknowledge the outer row immediately so their own
- // measured-element scroll can begin. Root messages stay pending until
- // ChannelThread positions the message inside its potentially tall row.
- if (nestedTarget) completePendingScroll(pendingTargetId);
- }
- )
- );
-
- const reset = () => {
- updateTargetMessageData({
- activeTargetMessageId: undefined,
- activeTargetMessageReplyId: undefined,
- loadAroundMessageId: undefined,
- pendingScrollTargetId: undefined,
- pendingTargetReplyId: undefined,
- });
+ if (restored) dispatch({ t: 'pagination-restored' });
+ })
+ .exhaustive();
+ },
+
+ inspect: import.meta.env.DEV
+ ? (from, e, result) =>
+ console.debug('target-message', {
+ from: from.t,
+ event: e.t,
+ to: result === 'ignored' ? 'ignored' : result.state.t,
+ })
+ : undefined,
+ });
+
+ const state = machine.state;
+
+ // A function, not a memo: Channel.tsx constructs this controller before
+ // `messageIndex` exists, so eagerly reading `messageKeys` would throw.
+ // Accessors run after setup and track these inputs from there.
+ const ready = () => {
+ const s = state();
+ return (
+ s.t === 'targeting' &&
+ options.isReady() &&
+ options.messageKeys().includes(s.target.messageId)
+ );
};
- /**
- * Clear the active target (and any pending scroll) if it still points at
- * `messageId`; no-op if navigation has since moved elsewhere. Leaves
- * `loadAroundMessageId` untouched so pagination is not disturbed.
- */
- function clearActiveTarget(messageId: string) {
- if (targetMessageData['activeTargetMessageId'] !== messageId) return;
- updateTargetMessageData({
- activeTargetMessageId: undefined,
- activeTargetMessageReplyId: undefined,
- pendingScrollTargetId: undefined,
- pendingTargetReplyId: undefined,
- });
- }
-
return {
- activeTargetMessageId: () => targetMessageData['activeTargetMessageId'],
- activeTargetMessageReplyId: () =>
- targetMessageData['activeTargetMessageReplyId'],
- loadAroundMessageId: () => targetMessageData['loadAroundMessageId'],
- pendingScrollTargetId: () => targetMessageData['pendingScrollTargetId'],
- pendingTargetReplyId: () => targetMessageData['pendingTargetReplyId'],
- hasPendingElementScroll,
-
- goToMessage,
- completePendingScroll,
- completePendingReplyScroll,
- clearActiveTarget,
- reset,
+ activeTargetMessageId: () => activeTargetMessageId(state()),
+ activeTargetMessageReplyId: () => activeTargetMessageReplyId(state()),
+ loadAroundMessageId: () => state().loadAround,
+ pendingScrollTargetId: () => pendingScrollTargetId(state(), ready()),
+ pendingTargetReplyId: () => pendingTargetReplyId(state()),
+ hasPendingElementScroll: () => hasPendingElementScroll(state(), ready()),
+
+ goToMessage: (messageId: string, replyId?: string) =>
+ machine.dispatch({
+ t: 'navigate',
+ target: { messageId, replyId },
+ targetLoaded: untrack(() => options.messageKeys().includes(messageId)),
+ ready: untrack(ready),
+ }),
+ completePendingScroll: (messageId: string) =>
+ machine.dispatch({ t: 'root-scroll-done', messageId }),
+ completePendingReplyScroll: (messageId: string, replyId: string) =>
+ machine.dispatch({ t: 'reply-scroll-done', messageId, replyId }),
+ clearActiveTarget: (messageId: string) =>
+ machine.dispatch({ t: 'release', messageId }),
+ reset: () => machine.dispatch({ t: 'reset' }),
};
}
+/**
+ * Promote the around-query's data to the default channel query once the
+ * target has been positioned, so subsequent pagination continues from the
+ * loaded window instead of refetching from the bottom. Returns whether
+ * anything was restored. Idempotent: the around variant is removed on success.
+ */
export function restoreDefaultChannelPaginationAfterTargetLoad(
channelId: string,
loadAroundMessageId: string | undefined
@@ -219,8 +151,6 @@ export function restoreDefaultChannelPaginationAfterTargetLoad(
if (!aroundData) return false;
queryClient.setQueryData(defaultKey, aroundData);
- // Remove the around-query variant so it doesn't linger in cache across
- // component mounts.
queryClient.removeQueries({ queryKey: aroundKey });
return true;
}
diff --git a/apps/web/src/features/channel/Channel/target-message.ts b/apps/web/src/features/channel/Channel/target-message.ts
new file mode 100644
index 0000000000..5a85e09da2
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/target-message.ts
@@ -0,0 +1,244 @@
+import type { MachineDef, Transition } from '@macro-inc/machine';
+import { match } from 'ts-pattern';
+
+/**
+ * Target-message navigation (deep link / click-to-message) as a state machine.
+ *
+ * Pure: no solid-js, no timers, no cache. The runner in
+ * `create-target-message-controller.ts` owns the flash timer, the readiness
+ * condition, and cache restoration. This module owns every decision about
+ * what a navigation means.
+ *
+ * Lifecycle: navigate → targeting → flashing → idle
+ *
+ * Only occurrences change state: a navigation, a scroll acknowledgement from
+ * ChannelThread, the flash timer, a release, a reset. Whether the ThreadList
+ * is *ready* (navigation handle present, initial scroll done, target in the
+ * loaded window) is a condition over inputs the runner owns, so it is not a
+ * state — it is passed into the selectors that depend on it.
+ *
+ * The ChannelThread contract this encodes (Channel.tsx derives ChannelThread's
+ * props from `pendingScrollTargetId` and `pendingTargetReplyId`):
+ *
+ * - A root-only target (`replyId` absent) is positioned by ChannelThread as
+ * soon as it sees `pendingScrollTargetId`, and acked with `root-scroll-done`.
+ * - A nested target (`replyId` present) must not scroll the whole row first.
+ * ChannelThread scrolls the reply's measured element only once
+ * `pendingScrollTargetId` clears while `pendingTargetReplyId` is set. That
+ * clearing is readiness itself, so the reply scroll is the only viewport
+ * movement, and ChannelThread never acks the root row of a nested target.
+ *
+ * `loadAround` is pagination context, not control state: it selects which
+ * messages query Channel.tsx reads from and survives highlight release so
+ * pagination isn't disturbed. Only `reset` and a successful restore clear it.
+ * The restore is issued when the scroll is acknowledged — the one occurrence
+ * at which the row is guaranteed mounted and the around data present.
+ */
+
+export type Target = {
+ readonly messageId: string;
+ readonly replyId?: string | undefined;
+};
+
+type WithLoadAround = { readonly loadAround: string | undefined };
+
+export type State = WithLoadAround &
+ (
+ | { readonly t: 'idle' }
+ /** Navigated; the target's scroll has not been acknowledged. */
+ | { readonly t: 'targeting'; readonly target: Target }
+ /** Positioned. Highlight is showing; released when the flash elapses. */
+ | { readonly t: 'flashing'; readonly target: Target }
+ );
+
+export type Event =
+ /**
+ * `targetLoaded`: the message is already in the loaded window.
+ * `ready`: the ThreadList is ready for the *current* target (see runner);
+ * needed only for the dedupe rule, which mirrors `pendingScrollTargetId`.
+ */
+ | {
+ readonly t: 'navigate';
+ readonly target: Target;
+ readonly targetLoaded: boolean;
+ readonly ready: boolean;
+ }
+ | { readonly t: 'root-scroll-done'; readonly messageId: string }
+ | {
+ readonly t: 'reply-scroll-done';
+ readonly messageId: string;
+ readonly replyId: string;
+ }
+ | { readonly t: 'flash-elapsed' }
+ /** The around-query's data was promoted to the default query. */
+ | { readonly t: 'pagination-restored' }
+ /** Release the highlight if it still points at `messageId`; leaves `loadAround` alone. */
+ | { readonly t: 'release'; readonly messageId: string }
+ /** Channel changed. Clears everything including `loadAround`. */
+ | { readonly t: 'reset' };
+
+export type Command = {
+ readonly t: 'restore-default-pagination';
+ readonly loadAround: string;
+};
+
+type Result = Transition<State, Command> | undefined;
+
+const RESET: Transition<State, Command> = {
+ state: { t: 'idle', loadAround: undefined },
+};
+
+function navigate(s: State, e: Extract<Event, { t: 'navigate' }>): Result {
+ return {
+ state: {
+ t: 'targeting',
+ target: e.target,
+ // A target already inside the loaded window keeps the current around
+ // anchor, so a rapid second navigation doesn't re-center pagination
+ // while the first around-query is still in flight. This was a
+ // documented hack; it is now a table row with a test.
+ loadAround: e.targetLoaded ? s.loadAround : e.target.messageId,
+ },
+ };
+}
+
+/** Scroll acknowledged: flash, and promote the around window if one is anchored. */
+function flash(s: Extract<State, { t: 'targeting' }>): Result {
+ return {
+ state: { t: 'flashing', target: s.target, loadAround: s.loadAround },
+ commands:
+ s.loadAround === undefined
+ ? []
+ : [{ t: 'restore-default-pagination', loadAround: s.loadAround }],
+ };
+}
+
+function release(s: State): Result {
+ return { state: { t: 'idle', loadAround: s.loadAround } };
+}
+
+function clearLoadAround(s: State): Result {
+ return { state: { ...s, loadAround: undefined } };
+}
+
+const isSameTarget = (a: Target, b: Target) =>
+ a.messageId === b.messageId && a.replyId === b.replyId;
+
+const isRoot = (t: Target) => t.replyId === undefined;
+
+export const targetMessageDef: MachineDef<State, Event, Command> = {
+ idle: {
+ on: (s, e) =>
+ match(e)
+ .with({ t: 'navigate' }, (e) => navigate(s, e))
+ .with({ t: 'pagination-restored' }, () => clearLoadAround(s))
+ .with({ t: 'reset' }, () => RESET)
+ .with(
+ { t: 'root-scroll-done' },
+ { t: 'reply-scroll-done' },
+ { t: 'flash-elapsed' },
+ { t: 'release' },
+ () => undefined
+ )
+ .exhaustive(),
+ },
+
+ targeting: {
+ on: (s, e) =>
+ match(e)
+ .with({ t: 'navigate' }, (e) =>
+ isSameTarget(s.target, e.target) &&
+ pendingScrollTargetId(s, e.ready) !== undefined
+ ? undefined
+ : navigate(s, e)
+ )
+ .with({ t: 'root-scroll-done' }, (e) =>
+ isRoot(s.target) && e.messageId === s.target.messageId
+ ? flash(s)
+ : undefined
+ )
+ .with({ t: 'reply-scroll-done' }, (e) =>
+ e.messageId === s.target.messageId && e.replyId === s.target.replyId
+ ? flash(s)
+ : undefined
+ )
+ .with({ t: 'pagination-restored' }, () => clearLoadAround(s))
+ .with({ t: 'release' }, (e) =>
+ e.messageId === s.target.messageId ? release(s) : undefined
+ )
+ .with({ t: 'reset' }, () => RESET)
+ .with({ t: 'flash-elapsed' }, () => undefined)
+ .exhaustive(),
+ },
+
+ flashing: {
+ on: (s, e) =>
+ match(e)
+ .with({ t: 'navigate' }, (e) => navigate(s, e))
+ .with({ t: 'flash-elapsed' }, () => release(s))
+ .with({ t: 'pagination-restored' }, () => clearLoadAround(s))
+ .with({ t: 'release' }, (e) =>
+ e.messageId === s.target.messageId ? release(s) : undefined
+ )
+ .with({ t: 'reset' }, () => RESET)
+ .with(
+ { t: 'root-scroll-done' },
+ { t: 'reply-scroll-done' },
+ () => undefined
+ )
+ .exhaustive(),
+ },
+};
+
+export function initialState(init: {
+ readonly messageId?: string | undefined;
+ readonly replyId?: string | undefined;
+}): State {
+ if (init.messageId === undefined) return { t: 'idle', loadAround: undefined };
+ return {
+ t: 'targeting',
+ target: { messageId: init.messageId, replyId: init.replyId },
+ loadAround: init.messageId,
+ };
+}
+
+export const activeTargetMessageId = (s: State): string | undefined =>
+ match(s)
+ .with({ t: 'idle' }, () => undefined)
+ .with({ t: 'targeting' }, { t: 'flashing' }, (s) => s.target.messageId)
+ .exhaustive();
+
+export const activeTargetMessageReplyId = (s: State): string | undefined =>
+ match(s)
+ .with({ t: 'idle' }, () => undefined)
+ .with({ t: 'targeting' }, { t: 'flashing' }, (s) => s.target.replyId)
+ .exhaustive();
+
+/**
+ * The root row ChannelThread should position, if any. A root-only target is
+ * pending until acknowledged. A nested target's root row is pending only
+ * until the ThreadList is ready; readiness clears it so the reply scroll can
+ * begin.
+ */
+export const pendingScrollTargetId = (
+ s: State,
+ ready: boolean
+): string | undefined =>
+ match(s)
+ .with({ t: 'targeting' }, (s) =>
+ isRoot(s.target) || !ready ? s.target.messageId : undefined
+ )
+ .with({ t: 'idle' }, { t: 'flashing' }, () => undefined)
+ .exhaustive();
+
+/** The reply ChannelThread should position once the root row clears. */
+export const pendingTargetReplyId = (s: State): string | undefined =>
+ match(s)
+ .with({ t: 'targeting' }, (s) => s.target.replyId)
+ .with({ t: 'idle' }, { t: 'flashing' }, () => undefined)
+ .exhaustive();
+
+/** Any scroll still owed to the target (root or reply). Used by Channel.tsx for keep-mounted. */
+export const hasPendingElementScroll = (s: State, ready: boolean): boolean =>
+ pendingScrollTargetId(s, ready) !== undefined ||
+ pendingTargetReplyId(s) !== undefined;
diff --git a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts
index 39465d91f9..367cb713f2 100644
--- a/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts
+++ b/apps/web/src/features/channel/Channel/tests/create-target-message-controller.test.ts
@@ -1,7 +1,3 @@
-vi.mock('@queries/messages/subscription', () => ({
- useMessageSubscription: () => {},
-}));
-
import { queryClient } from '@queries/client';
import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -10,13 +6,16 @@ vi.mock('@service-storage/client', () => ({
storageServiceClient: {},
}));
+vi.mock('@queries/messages/subscription', () => ({
+ useMessageSubscription: () => {},
+}));
+
import {
getMessageTimelineQueryKey,
type MessageTimelineData,
} from '@queries/messages/timeline';
import {
createTargetMessageController,
- restoreDefaultChannelPaginationAfterTargetLoad,
TARGETED_MESSAGE_FLASH_MS,
} from '../create-target-message-controller';
@@ -25,227 +24,180 @@ afterEach(() => {
vi.useRealTimers();
});
-function createController(
- input?: Partial<{
- channelId: string;
- initialTargetMessageId: string;
- initialTargetMessageReplyId: string;
- messageKeys: string[];
- withNavigation: boolean;
- didInitialScroll: boolean;
- }>
-) {
- const [messageKeys, setMessageKeys] = createSignal(input?.messageKeys ?? []);
- const [didInitialScroll, setDidInitialScroll] = createSignal(
- input?.didInitialScroll ?? false
- );
-
- const controller = createTargetMessageController({
- channelId: () => input?.channelId ?? 'channel-1',
- initialTargetMessageId: input?.initialTargetMessageId,
- initialTargetMessageReplyId: input?.initialTargetMessageReplyId,
- messageKeys,
- isReady: () => !!input?.withNavigation && didInitialScroll(),
- });
+const CHANNEL = 'ch1';
- return {
- controller,
- setMessageKeys,
- setDidInitialScroll,
- };
-}
+function mount(init?: { targetMessageId?: string; targetReplyId?: string }) {
+ return createRoot((dispose) => {
+ const [keys, setKeys] = createSignal<string[]>([]);
+ const [isReady, setIsReady] = createSignal(false);
-describe('createTargetMessageController', () => {
- it('preserves the current load-around target when navigating to an already loaded message', () => {
- createRoot((dispose) => {
- const { controller } = createController({
- initialTargetMessageId: 'message-1',
- messageKeys: ['message-2'],
- });
+ const controller = createTargetMessageController({
+ channelId: () => CHANNEL,
+ initialTargetMessageId: init?.targetMessageId,
+ initialTargetMessageReplyId: init?.targetReplyId,
+ messageKeys: keys,
+ isReady,
+ });
- controller.goToMessage('message-2');
+ const ready = (loaded: string[]) => {
+ setKeys(loaded);
+ setIsReady(true);
+ };
- expect(controller.activeTargetMessageId()).toBe('message-2');
- expect(controller.pendingScrollTargetId()).toBe('message-2');
- expect(controller.loadAroundMessageId()).toBe('message-1');
- dispose();
- });
+ return { controller, ready, setKeys, dispose };
});
+}
- it('switches load-around target when navigating to a missing message', () => {
+describe('construction', () => {
+ it('does not read ThreadList inputs during construct (Channel.tsx TDZ)', () => {
createRoot((dispose) => {
- const { controller } = createController({
- initialTargetMessageId: 'message-1',
- });
-
- controller.goToMessage('message-9');
-
- expect(controller.activeTargetMessageId()).toBe('message-9');
- expect(controller.pendingScrollTargetId()).toBe('message-9');
- expect(controller.loadAroundMessageId()).toBe('message-9');
+ const boom = (): never => {
+ throw new Error('read during construct');
+ };
+ expect(() =>
+ createTargetMessageController({
+ channelId: () => CHANNEL,
+ initialTargetMessageId: 'm1',
+ initialTargetMessageReplyId: 'r1',
+ messageKeys: boom,
+ isReady: boom,
+ })
+ ).not.toThrow();
dispose();
});
});
+});
- it('lets a nested reply perform the only viewport scroll', async () => {
- let dispose = () => {};
- let controller: ReturnType<typeof createTargetMessageController>;
-
- createRoot((rootDispose) => {
- dispose = rootDispose;
- controller = createController({
- initialTargetMessageId: 'message-1',
- initialTargetMessageReplyId: 'reply-4',
- messageKeys: ['message-1'],
- withNavigation: true,
- didInitialScroll: true,
- }).controller;
- });
-
- await Promise.resolve();
-
- expect(controller!.pendingScrollTargetId()).toBeUndefined();
- expect(controller!.pendingTargetReplyId()).toBe('reply-4');
- // The outer row is acknowledged early so the reply can scroll itself, but
- // an element still owes the viewport a scroll. Anything gated on that —
- // the kept-mounted row, the ThreadList fallback — must stay armed, or a
- // reply that never lands leaves the channel parked where it mounted.
- expect(controller!.hasPendingElementScroll()).toBe(true);
-
- controller!.completePendingReplyScroll('message-1', 'reply-4');
- expect(controller!.hasPendingElementScroll()).toBe(false);
+describe('flash timer', () => {
+ it('releases the target after TARGETED_MESSAGE_FLASH_MS', () => {
+ vi.useFakeTimers();
+ const { controller, ready, dispose } = mount();
+ ready(['m1']);
+ controller.goToMessage('m1');
+ controller.completePendingScroll('m1');
+ expect(controller.activeTargetMessageId()).toBe('m1');
+
+ vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS - 1);
+ expect(controller.activeTargetMessageId()).toBe('m1');
+ vi.advanceTimersByTime(1);
+ expect(controller.activeTargetMessageId()).toBeUndefined();
dispose();
});
- it('keeps a root target pending until its element is positioned within the row', async () => {
- let dispose = () => {};
- let controller: ReturnType<typeof createTargetMessageController>;
-
- createRoot((rootDispose) => {
- dispose = rootDispose;
- controller = createController({
- initialTargetMessageId: 'message-1',
- messageKeys: ['message-1'],
- withNavigation: true,
- didInitialScroll: true,
- }).controller;
- });
-
- await Promise.resolve();
-
- expect(controller!.pendingScrollTargetId()).toBe('message-1');
-
- controller!.completePendingScroll('message-1');
- expect(controller!.pendingScrollTargetId()).toBeUndefined();
+ it('a navigate mid-flash disposes the timer; the new target flashes on its own clock', () => {
+ vi.useFakeTimers();
+ const { controller, ready, dispose } = mount();
+ ready(['m1', 'm2']);
+ controller.goToMessage('m1');
+ controller.completePendingScroll('m1');
+ vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS / 2);
+
+ controller.goToMessage('m2');
+ controller.completePendingScroll('m2');
+ vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS / 2 + 1);
+ expect(controller.activeTargetMessageId()).toBe('m2');
+
+ vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS / 2);
+ expect(controller.activeTargetMessageId()).toBeUndefined();
dispose();
});
- it('releases a root target after the accent flash once its scroll completes', async () => {
+ it('unmount cancels a running flash', () => {
vi.useFakeTimers();
- let dispose = () => {};
- let controller!: ReturnType<typeof createTargetMessageController>;
-
- createRoot((rootDispose) => {
- dispose = rootDispose;
- controller = createController({
- messageKeys: ['message-1'],
- }).controller;
- });
- await Promise.resolve();
-
- controller.goToMessage('message-1');
- controller.completePendingScroll('message-1');
- await Promise.resolve();
- expect(controller.activeTargetMessageId()).toBe('message-1');
-
- vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS);
- expect(controller.activeTargetMessageId()).toBeUndefined();
+ const { controller, ready, dispose } = mount();
+ ready(['m1']);
+ controller.goToMessage('m1');
+ controller.completePendingScroll('m1');
dispose();
+ expect(() =>
+ vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS)
+ ).not.toThrow();
+ controller.reset();
+ expect(controller.activeTargetMessageId()).toBe('m1');
});
+});
- it('holds the flash until a nested reply target completes its scroll', async () => {
- vi.useFakeTimers();
- let dispose = () => {};
- let controller!: ReturnType<typeof createTargetMessageController>;
-
- createRoot((rootDispose) => {
- dispose = rootDispose;
- controller = createController({
- initialTargetMessageId: 'message-1',
- initialTargetMessageReplyId: 'reply-4',
- messageKeys: ['message-1'],
- withNavigation: true,
- didInitialScroll: true,
- }).controller;
+describe('readiness', () => {
+ it('clears a nested target root row only once the ThreadList is ready', () => {
+ const { controller, ready, dispose } = mount({
+ targetMessageId: 'm1',
+ targetReplyId: 'r1',
});
- await Promise.resolve();
+ expect(controller.pendingScrollTargetId()).toBe('m1');
+ expect(controller.pendingTargetReplyId()).toBe('r1');
+ expect(controller.hasPendingElementScroll()).toBe(true);
- // The outer row is acknowledged, but the reply scroll is still pending —
- // the flash countdown must not start yet.
+ ready(['m1']);
expect(controller.pendingScrollTargetId()).toBeUndefined();
- vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS);
- expect(controller.activeTargetMessageId()).toBe('message-1');
-
- controller.completePendingReplyScroll('message-1', 'reply-4');
- await Promise.resolve();
- vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS);
- expect(controller.activeTargetMessageId()).toBeUndefined();
- expect(controller.activeTargetMessageReplyId()).toBeUndefined();
+ expect(controller.pendingTargetReplyId()).toBe('r1');
+ expect(controller.hasPendingElementScroll()).toBe(true);
dispose();
});
- it('cancels the flash when navigation moves to a new target', async () => {
- vi.useFakeTimers();
- let dispose = () => {};
- let controller!: ReturnType<typeof createTargetMessageController>;
-
- createRoot((rootDispose) => {
- dispose = rootDispose;
- controller = createController({
- messageKeys: ['message-1', 'message-2'],
- }).controller;
+ it('waits for the target to be in the loaded window', () => {
+ const { controller, ready, setKeys, dispose } = mount({
+ targetMessageId: 'm1',
+ targetReplyId: 'r1',
});
- await Promise.resolve();
-
- controller.goToMessage('message-1');
- controller.completePendingScroll('message-1');
- controller.goToMessage('message-2');
- vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS);
- expect(controller.activeTargetMessageId()).toBe('message-2');
+ ready(['m0']);
+ expect(controller.pendingScrollTargetId()).toBe('m1');
+ setKeys(['m0', 'm1']);
+ expect(controller.pendingScrollTargetId()).toBeUndefined();
+ dispose();
+ });
- controller.completePendingScroll('message-2');
- await Promise.resolve();
- vi.advanceTimersByTime(TARGETED_MESSAGE_FLASH_MS);
- expect(controller.activeTargetMessageId()).toBeUndefined();
+ it('never clears a root-only target on readiness; only its ack does', () => {
+ const { controller, ready, dispose } = mount({ targetMessageId: 'm1' });
+ ready(['m1']);
+ expect(controller.pendingScrollTargetId()).toBe('m1');
+ controller.completePendingScroll('m1');
+ expect(controller.pendingScrollTargetId()).toBeUndefined();
+ expect(controller.hasPendingElementScroll()).toBe(false);
dispose();
});
+});
- it('copies around-target query data into the default query key', () => {
- const aroundData = {
- pageParams: [null],
- pages: [
- {
- items: [],
- next_cursor: { id: 'next', created_at: '2024-01-01T00:00:00Z' },
- previous_cursor: { id: 'prev', created_at: '2024-01-01T00:00:00Z' },
- },
- ],
- } as MessageTimelineData;
+describe('pagination restore', () => {
+ const aroundData: MessageTimelineData = {
+ pageParams: [null],
+ pages: [
+ {
+ items: [],
+ next_cursor: { id: 'next', created_at: '2024-01-01T00:00:00Z' },
+ previous_cursor: { id: 'prev', created_at: '2024-01-01T00:00:00Z' },
+ },
+ ],
+ };
+ it('promotes the around-query to the default query on the scroll ack and clears the anchor', () => {
queryClient.setQueryData(
- getMessageTimelineQueryKey(
- { type: 'channel', id: 'channel-1' },
- 'message-9'
- ),
+ getMessageTimelineQueryKey({ type: 'channel', id: CHANNEL }, 'm1'),
aroundData
);
+ const { controller, ready, dispose } = mount({ targetMessageId: 'm1' });
+ ready(['m1']);
+ expect(controller.loadAroundMessageId()).toBe('m1');
- restoreDefaultChannelPaginationAfterTargetLoad('channel-1', 'message-9');
-
+ controller.completePendingScroll('m1');
expect(
queryClient.getQueryData(
- getMessageTimelineQueryKey({ type: 'channel', id: 'channel-1' }, null)
+ getMessageTimelineQueryKey({ type: 'channel', id: CHANNEL }, null)
)
).toEqual(aroundData);
+ expect(
+ queryClient.getQueryData(
+ getMessageTimelineQueryKey({ type: 'channel', id: CHANNEL }, 'm1')
+ )
+ ).toBeUndefined();
+ expect(controller.loadAroundMessageId()).toBeUndefined();
+ dispose();
+ });
+
+ it('keeps the anchor when there is nothing to restore', () => {
+ const { controller, ready, dispose } = mount({ targetMessageId: 'm1' });
+ ready(['m1']);
+ controller.completePendingScroll('m1');
+ expect(controller.loadAroundMessageId()).toBe('m1');
+ dispose();
});
});
diff --git a/apps/web/src/features/channel/Channel/tests/target-message.test.ts b/apps/web/src/features/channel/Channel/tests/target-message.test.ts
new file mode 100644
index 0000000000..26502c6799
--- /dev/null
+++ b/apps/web/src/features/channel/Channel/tests/target-message.test.ts
@@ -0,0 +1,373 @@
+import { simulate, step } from '@macro-inc/machine';
+import { describe, expect, it } from 'vitest';
+import {
+ activeTargetMessageId,
+ activeTargetMessageReplyId,
+ type Command,
+ type Event,
+ hasPendingElementScroll,
+ initialState,
+ pendingScrollTargetId,
+ pendingTargetReplyId,
+ type State,
+ type Target,
+ targetMessageDef,
+} from '../target-message';
+
+const ROOT: Target = { messageId: 'm1', replyId: undefined };
+const NESTED: Target = { messageId: 'm1', replyId: 'r1' };
+const OTHER: Target = { messageId: 'm2', replyId: undefined };
+
+const idle = (loadAround?: string): State => ({ t: 'idle', loadAround });
+const targeting = (target: Target, loadAround?: string): State => ({
+ t: 'targeting',
+ target,
+ loadAround,
+});
+const flashing = (target: Target, loadAround?: string): State => ({
+ t: 'flashing',
+ target,
+ loadAround,
+});
+
+const nav = (target: Target, targetLoaded: boolean, ready = false): Event => ({
+ t: 'navigate',
+ target,
+ targetLoaded,
+ ready,
+});
+const rootDone = (messageId = 'm1'): Event => ({
+ t: 'root-scroll-done',
+ messageId,
+});
+const replyDone = (messageId = 'm1', replyId = 'r1'): Event => ({
+ t: 'reply-scroll-done',
+ messageId,
+ replyId,
+});
+const RESTORED: Event = { t: 'pagination-restored' };
+const ELAPSED: Event = { t: 'flash-elapsed' };
+const RESET: Event = { t: 'reset' };
+const release = (messageId = 'm1'): Event => ({ t: 'release', messageId });
+
+const RESTORE = (loadAround: string): Command => ({
+ t: 'restore-default-pagination',
+ loadAround,
+});
+
+type Expected = { state: State; commands?: Command[] } | undefined;
+
+function check(from: State, event: Event, expected: Expected) {
+ const result = step(targetMessageDef, from, event);
+ if (expected === undefined) {
+ expect(result).toBeUndefined();
+ return;
+ }
+ expect(result?.state).toEqual(expected.state);
+ expect(result?.commands ?? []).toEqual(expected.commands ?? []);
+}
+
+describe('navigate', () => {
+ it.each<[string, State, Event, Expected]>([
+ [
+ 'unloaded target anchors pagination on itself',
+ idle(),
+ nav(ROOT, false),
+ { state: targeting(ROOT, 'm1') },
+ ],
+ [
+ 'loaded target keeps the existing anchor (rapid-navigation rule)',
+ idle('m0'),
+ nav(ROOT, true),
+ { state: targeting(ROOT, 'm0') },
+ ],
+ [
+ 'loaded target with no anchor leaves it unset',
+ idle(),
+ nav(ROOT, true),
+ { state: targeting(ROOT, undefined) },
+ ],
+ [
+ 'same root target while pending dedupes',
+ targeting(ROOT),
+ nav(ROOT, true),
+ undefined,
+ ],
+ [
+ 'same root target dedupes even once ready (root row still pending)',
+ targeting(ROOT),
+ nav(ROOT, true, true),
+ undefined,
+ ],
+ [
+ 'same nested target before readiness dedupes',
+ targeting(NESTED),
+ nav(NESTED, true, false),
+ undefined,
+ ],
+ [
+ 'same nested target after readiness re-navigates (root row no longer pending)',
+ targeting(NESTED, 'm1'),
+ nav(NESTED, true, true),
+ { state: targeting(NESTED, 'm1') },
+ ],
+ [
+ 'different reply on the same message is a new target',
+ targeting(ROOT),
+ nav(NESTED, true),
+ { state: targeting(NESTED, undefined) },
+ ],
+ [
+ 'navigating during a flash re-targets (timer is disposed by the runner)',
+ flashing(ROOT, 'm1'),
+ nav(ROOT, true),
+ { state: targeting(ROOT, 'm1') },
+ ],
+ [
+ 'superseding a pending target re-anchors when the new one is unloaded',
+ targeting(ROOT, 'm1'),
+ nav(OTHER, false),
+ { state: targeting(OTHER, 'm2') },
+ ],
+ ])('%s', (_name, from, event, expected) => check(from, event, expected));
+});
+
+describe('root-scroll-done', () => {
+ it.each<[string, State, Event, Expected]>([
+ [
+ 'root-only target → flashing, restoring the anchored window',
+ targeting(ROOT, 'm1'),
+ rootDone(),
+ { state: flashing(ROOT, 'm1'), commands: [RESTORE('m1')] },
+ ],
+ [
+ 'root-only target without an anchor → flashing, nothing to restore',
+ targeting(ROOT),
+ rootDone(),
+ { state: flashing(ROOT) },
+ ],
+ ['wrong row is ignored', targeting(ROOT), rootDone('m9'), undefined],
+ [
+ 'nested target ignores a root ack (its root row is never positioned)',
+ targeting(NESTED),
+ rootDone(),
+ undefined,
+ ],
+ ['ignored while flashing', flashing(ROOT), rootDone(), undefined],
+ ['ignored while idle', idle(), rootDone(), undefined],
+ ])('%s', (_name, from, event, expected) => check(from, event, expected));
+});
+
+describe('reply-scroll-done', () => {
+ it.each<[string, State, Event, Expected]>([
+ [
+ 'nested target → flashing, restoring the anchored window',
+ targeting(NESTED, 'm1'),
+ replyDone(),
+ { state: flashing(NESTED, 'm1'), commands: [RESTORE('m1')] },
+ ],
+ [
+ 'wrong reply is ignored',
+ targeting(NESTED),
+ replyDone('m1', 'r9'),
+ undefined,
+ ],
+ [
+ 'wrong message is ignored',
+ targeting(NESTED),
+ replyDone('m9', 'r1'),
+ undefined,
+ ],
+ [
+ 'root-only target ignores a reply ack',
+ targeting(ROOT),
+ replyDone(),
+ undefined,
+ ],
+ ['ignored while flashing', flashing(NESTED), replyDone(), undefined],
+ ])('%s', (_name, from, event, expected) => check(from, event, expected));
+});
+
+describe('pagination-restored', () => {
+ it.each<[string, State]>([
+ ['idle', idle('m1')],
+ ['targeting', targeting(ROOT, 'm1')],
+ ['flashing', flashing(ROOT, 'm1')],
+ ])(
+ 'clears the anchor and preserves everything else while %s',
+ (_name, from) => {
+ check(from, RESTORED, { state: { ...from, loadAround: undefined } });
+ }
+ );
+});
+
+describe('flash-elapsed', () => {
+ it('releases the highlight and keeps the pagination anchor', () =>
+ check(flashing(ROOT, 'm1'), ELAPSED, { state: idle('m1') }));
+
+ it.each<[string, State]>([
+ ['idle', idle()],
+ ['targeting', targeting(ROOT)],
+ ])('is ignored while %s (no timer exists there)', (_name, from) =>
+ check(from, ELAPSED, undefined)
+ );
+});
+
+describe('release', () => {
+ it.each<[string, State, Event, Expected]>([
+ [
+ 'matching targeting → idle, anchor kept',
+ targeting(ROOT, 'm1'),
+ release(),
+ { state: idle('m1') },
+ ],
+ [
+ 'matching flashing → idle',
+ flashing(ROOT, 'm1'),
+ release(),
+ { state: idle('m1') },
+ ],
+ ['non-matching is ignored', flashing(ROOT), release('m9'), undefined],
+ ['idle is ignored', idle('m1'), release(), undefined],
+ ])('%s', (_name, from, event, expected) => check(from, event, expected));
+});
+
+describe('reset', () => {
+ it.each<[string, State]>([
+ ['idle', idle('m1')],
+ ['targeting', targeting(NESTED, 'm1')],
+ ['flashing', flashing(ROOT, 'm1')],
+ ])('clears everything including the anchor from %s', (_name, from) =>
+ check(from, RESET, { state: idle() })
+ );
+});
+
+describe('selectors — the ChannelThread contract', () => {
+ const channelThreadProps = (s: State, ready: boolean) => {
+ const scroll = pendingScrollTargetId(s, ready);
+ const reply = pendingTargetReplyId(s);
+ return {
+ targetMessageId: reply === undefined ? scroll : undefined,
+ targetReplyId: scroll === undefined ? reply : undefined,
+ };
+ };
+
+ it.each<
+ [
+ string,
+ State,
+ boolean,
+ {
+ scroll?: string;
+ reply?: string;
+ message?: string;
+ replyProp?: string;
+ any: boolean;
+ },
+ ]
+ >([
+ ['idle: nothing', idle(), true, { any: false }],
+ [
+ 'root, not ready: ChannelThread positions the row',
+ targeting(ROOT),
+ false,
+ { scroll: 'm1', message: 'm1', any: true },
+ ],
+ [
+ 'root, ready: still positions the row (readiness does not clear a root target)',
+ targeting(ROOT),
+ true,
+ { scroll: 'm1', message: 'm1', any: true },
+ ],
+ [
+ 'nested, not ready: both set, so ChannelThread stays idle',
+ targeting(NESTED),
+ false,
+ { scroll: 'm1', reply: 'r1', any: true },
+ ],
+ [
+ 'nested, ready: root cleared, reply scroll begins',
+ targeting(NESTED),
+ true,
+ { reply: 'r1', replyProp: 'r1', any: true },
+ ],
+ ['flashing: nothing pending', flashing(NESTED), true, { any: false }],
+ ])('%s', (_name, s, ready, expected) => {
+ expect(pendingScrollTargetId(s, ready)).toBe(expected.scroll);
+ expect(pendingTargetReplyId(s)).toBe(expected.reply);
+ expect(hasPendingElementScroll(s, ready)).toBe(expected.any);
+ expect(channelThreadProps(s, ready)).toEqual({
+ targetMessageId: expected.message,
+ targetReplyId: expected.replyProp,
+ });
+ });
+
+ it('exposes the active target in every non-idle state', () => {
+ for (const s of [targeting(NESTED), flashing(NESTED)]) {
+ expect(activeTargetMessageId(s)).toBe('m1');
+ expect(activeTargetMessageReplyId(s)).toBe('r1');
+ }
+ expect(activeTargetMessageId(idle())).toBeUndefined();
+ expect(activeTargetMessageReplyId(idle())).toBeUndefined();
+ });
+});
+
+describe('initialState', () => {
+ it('starts idle without a target', () =>
+ expect(initialState({})).toEqual(idle()));
+
+ it('starts targeting and anchored on an initial target', () =>
+ expect(initialState({ messageId: 'm1', replyId: 'r1' })).toEqual(
+ targeting(NESTED, 'm1')
+ ));
+});
+
+describe('sequences', () => {
+ const states = (run: ReturnType<typeof simulate<State, Event, Command>>) =>
+ run.steps.map((s) =>
+ s.result === 'ignored' ? 'ignored' : s.result.state.t
+ );
+
+ it('root-only deep link: ack → flash (restoring) → release', () => {
+ const run = simulate(targetMessageDef, initialState({ messageId: 'm1' }), [
+ rootDone(),
+ RESTORED,
+ ELAPSED,
+ ]);
+ expect(run.commands).toEqual([RESTORE('m1')]);
+ expect(states(run)).toEqual(['flashing', 'flashing', 'idle']);
+ expect(run.state).toEqual(idle());
+ });
+
+ it('nested deep link: reply ack → flash (restoring) → release; a root ack is ignored', () => {
+ const run = simulate(
+ targetMessageDef,
+ initialState({ messageId: 'm1', replyId: 'r1' }),
+ [rootDone(), replyDone(), RESTORED, ELAPSED]
+ );
+ expect(states(run)).toEqual(['ignored', 'flashing', 'flashing', 'idle']);
+ expect(run.commands).toEqual([RESTORE('m1')]);
+ expect(run.state).toEqual(idle());
+ });
+
+ it('rapid navigation: a loaded second target keeps the first anchor in flight', () => {
+ const run = simulate(targetMessageDef, idle(), [
+ nav({ messageId: 'a' }, false),
+ nav({ messageId: 'b' }, true),
+ ]);
+ expect(run.state).toEqual(targeting({ messageId: 'b' }, 'a'));
+ });
+
+ it('a failed restore leaves the anchor so the around-query stays the source', () => {
+ const run = simulate(targetMessageDef, targeting(ROOT, 'm1'), [
+ rootDone(),
+ ELAPSED,
+ ]);
+ expect(run.state).toEqual(idle('m1'));
+ });
+
+ it('channel change mid-flight resets everything', () => {
+ const run = simulate(targetMessageDef, targeting(NESTED, 'm1'), [RESET]);
+ expect(run.state).toEqual(idle());
+ });
+});
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 30905c7c74..07fe9a7ddd 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -33,6 +33,7 @@ export default defineConfig({
'../../packages/email-renderer/vitest.config.ts',
'../../packages/collaboration/vitest.collab.config.ts',
'../../packages/collaboration/vitest.transport.config.ts',
+ '../../packages/machine/vitest.config.ts',
{
// Core package tests
extends: './src/lib/core/vitest.config.ts',
diff --git a/bun.lock b/bun.lock
index 1340a059a5..045a73ff4c 100644
--- a/bun.lock
+++ b/bun.lock
@@ -52,6 +52,7 @@
"@macro-inc/collaboration": "workspace:*",
"@macro-inc/email-renderer": "workspace:*",
"@macro-inc/lexical-core": "workspace:*",
+ "@macro-inc/machine": "workspace:*",
"@macro-inc/observability": "workspace:*",
"@macro-inc/spreadsheet": "workspace:*",
"@normy/query-core": "^0.21.0",
@@ -280,6 +281,25 @@
"loro-crdt": "^1.4.4",
},
},
+ "packages/machine": {
+ "name": "@macro-inc/machine",
+ "version": "0.1.0",
+ "devDependencies": {
+ "@biomejs/biome": "2.4.12",
+ "@types/node": "^24.8.0",
+ "jsdom": "^26.1.0",
+ "solid-js": "^1.9.7",
+ "typescript": "^5.9.3",
+ "vite-plugin-solid": "^2.11.8",
+ "vitest": "5.0.1",
+ },
+ "peerDependencies": {
+ "solid-js": "^1.9.7",
+ },
+ "optionalPeers": [
+ "solid-js",
+ ],
+ },
"packages/observability": {
"name": "@macro-inc/observability",
"version": "0.0.1",
@@ -1162,6 +1182,8 @@
"@macro-inc/lexical-core": ["@macro-inc/lexical-core@workspace:packages/lexical-core"],
+ "@macro-inc/machine": ["@macro-inc/machine@workspace:packages/machine"],
+
"@macro-inc/observability": ["@macro-inc/observability@workspace:packages/observability"],
"@macro-inc/spreadsheet": ["@macro-inc/spreadsheet@workspace:packages/spreadsheet"],
@@ -3730,6 +3752,8 @@
"@macro-inc/lexical-core/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.js" } }, "sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ=="],
+ "@macro-inc/machine/@biomejs/biome": ["@biomejs/[email protected]", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.12", "@biomejs/cli-darwin-x64": "2.4.12", "@biomejs/cli-linux-arm64": "2.4.12", "@biomejs/cli-linux-arm64-musl": "2.4.12", "@biomejs/cli-linux-x64": "2.4.12", "@biomejs/cli-linux-x64-musl": "2.4.12", "@biomejs/cli-win32-arm64": "2.4.12", "@biomejs/cli-win32-x64": "2.4.12" }, "bin": { "biome": "bin/biome" } }, "sha512-Rro7adQl3NLq/zJCIL98eElXKI8eEiBtoeu5TbXF/U3qbjuSc7Jb5rjUbeHHcquDWeSf3HnGP7XI5qGrlRk/pA=="],
+
"@microlabs/otel-cf-workers/@opentelemetry/exporter-trace-otlp-http": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.0", "@opentelemetry/otlp-exporter-base": "0.200.0", "@opentelemetry/otlp-transformer": "0.200.0", "@opentelemetry/resources": "2.0.0", "@opentelemetry/sdk-trace-base": "2.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Goi//m/7ZHeUedxTGVmEzH19NgqJY+Bzr6zXo1Rni1+hwqaksEyJ44gdlEMREu6dzX1DlAaH/qSykSVzdrdafA=="],
"@opentelemetry/exporter-logs-otlp-http/@opentelemetry/otlp-exporter-base": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/otlp-transformer": "0.220.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CXYo8UD5Mn9YbgebO2EL4wejtA+gxLmLiu6HCk2KH2BR7XhFN6/6p1UlCb23DYCjeYkndevLHuejCCN1yx4+OQ=="],
@@ -4180,6 +4204,22 @@
"@macro-inc/lexical-core/@types/node/undici-types": ["[email protected]", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-darwin-arm64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BnMU4Pc3ciEVteVpZ0BK33MLr7X57F5w1dwDLDn+/iy/yTrA4Q/N2yftidFtsA4vrDh0FMXDpacNV/Tl3fbmng=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-darwin-x64": ["@biomejs/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-x9uJ0bI1rJsWICp3VH8w/5PnAVD3A7SqzDpbrfoUQX1QyWrK5jSU4fRLo/wSgGeplCivbxBRKmt5Xq4/nWvq8A=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-linux-arm64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-tOwuCuZZtKi1jVzbk/5nXmIsziOB6yqN8c9r9QM0EJYPU6DpQWf11uBOSCfFKKM4H3d9ZoarvlgMfbcuD051Pw=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-linux-arm64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-FhfpkAAlKL6kwvcVap0Hgp4AhZmtd3YImg0kK1jd7C/aSoh4SfsB2f++yG1rU0lr8Y5MCFJrcSkmssiL9Xnnig=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-linux-x64": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-8pFeAnLU9QdW9jCIslB/v82bI0lhBmz2ZAKc8pVMFPO0t0wAHsoEkrUQUbMkIorTRIjbqyNZHA3lEXavsPWYSw=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-linux-x64-musl": ["@biomejs/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-dwTIgZrGutzhkQCuvHynCkyW6hJxUuyZqKKO0YNfaS2GUoRO+tOvxXZqZB6SkWAOdfZTzwaw8IEdUnIkHKHoew=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-win32-arm64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-B0DLnx0vA9ya/3v7XyCaP+/lCpnbWbMOfUFFve+xb5OxyYvdHaS55YsSddr228Y+JAFk58agCuZTsqNiw2a6ig=="],
+
+ "@macro-inc/machine/@biomejs/biome/@biomejs/cli-win32-x64": ["@biomejs/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-yMckRzTyZ83hkk8iDFWswqSdU8tvZxspJKnYNh7JZr/zhZNOlzH13k4ecboU6MurKExCe2HUkH75pGI/O2JwGA=="],
+
"@microlabs/otel-cf-workers/@opentelemetry/exporter-trace-otlp-http/@opentelemetry/core": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-SLX36allrcnVaPYG3R78F/UZZsBsvbc7lMCLx37LyH5MJ1KAAZ2E3mW9OAD3zGz0G8q/BtoS5VUrjzDydhD6LQ=="],
"@microlabs/otel-cf-workers/@opentelemetry/exporter-trace-otlp-http/@opentelemetry/resources": ["@opentelemetry/[email protected]", "", { "dependencies": { "@opentelemetry/core": "2.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-rnZr6dML2z4IARI4zPGQV4arDikF/9OXZQzrC01dLmn0CZxU5U5OLd/m1T7YkGRj5UitjeoCtg/zorlgMQcdTg=="],
diff --git a/nix-support/node_modules-hashes.json b/nix-support/node_modules-hashes.json
index 8ee42c9185..d55ad49a93 100644
--- a/nix-support/node_modules-hashes.json
+++ b/nix-support/node_modules-hashes.json
@@ -1,6 +1,6 @@
{
"nodeModules": {
- "aarch64-darwin": "sha256-S3hF8ZlTysAMr0Zp+guiEQozHtFm3+dzCZXk7Qw0zTA=",
- "x86_64-linux": "sha256-pyjgL1H15A9TeViVupsA0TqSQvWViJG+Cs3s/ZJfAJg="
+ "aarch64-darwin": "sha256-ocV7mJdXeLh+LKFwv5nDtNqYS0btPkEj0XxPiEWta84=",
+ "x86_64-linux": "sha256-8Hv/bFFhoVNM6FugB655Z/VpLYK2Mle0VxzWIsZbaBI="
}
}
diff --git a/package.json b/package.json
index 546aef1d61..bcdab69d8e 100644
--- a/package.json
+++ b/package.json
@@ -68,6 +68,7 @@
"packages/observability",
"packages/email-renderer",
"packages/collaboration",
+ "packages/machine",
"packages/loro-mirror",
"packages/lexical-core",
"services/ai-editing-worker",
diff --git a/packages/machine/README.md b/packages/machine/README.md
new file mode 100644
index 0000000000..13a575fae8
--- /dev/null
+++ b/packages/machine/README.md
@@ -0,0 +1,72 @@
+# Machine
+
+`@macro-inc/machine` runs a pure, typed transition table in plain TypeScript.
+The core has no runtime dependencies. Solid integration is available separately
+from `@macro-inc/machine/solid`.
+
+```ts
+import { createMachine } from '@macro-inc/machine';
+
+const machine = createMachine({ initial, def, scopes, execute });
+const initialSnapshot = machine.getState();
+const unsubscribe = machine.subscribe((state) => console.log(state));
+machine.dispatch(event);
+unsubscribe();
+machine.dispose();
+```
+
+A definition returns the next state and optional commands, or `undefined` to
+ignore an event. `step` and `simulate` exercise those decisions without running
+scopes or commands.
+
+Scopes start work and optionally return a cleanup function. Every accepted
+transition cleans up the previous scope, enters the next state, starts its
+scope, notifies subscribers, then executes commands in order. This also applies
+to transitions with the same state tag. Ignored events leave the scope alone.
+The outgoing cleanup can still read the old state through `getState()`.
+
+Nested dispatches from scopes, cleanups, subscribers, and commands queue until
+the current transition finishes. The initial scope runs before `createMachine`
+returns, including any events it sends. Subscriptions receive future accepted
+transitions; use `getState()` to read the initial snapshot.
+
+Disposal cleans up the active scope, removes subscriptions, and makes subsequent
+dispatches no-ops. Call it when the machine is no longer needed.
+
+## Solid
+
+```ts
+import { createSolidMachine } from '@macro-inc/machine/solid';
+
+const machine = createSolidMachine({ initial, def, scopes, execute });
+machine.state(); // Reactive snapshot.
+machine.matches('flashing'); // Reactive read narrowed to that state.
+machine.dispatch(event);
+```
+
+The adapter owns its machine and disposes it when its Solid owner is disposed.
+Outside a Solid owner, call `machine.dispose()` explicitly. Scope callbacks
+normally return cleanup directly, just as they do in the core.
+
+Use `solidScope` when a callback needs Solid computations or context. Register
+cleanup with `onCleanup` inside this callback. Configure it under the owner
+whose context it should inherit:
+
+```ts
+import { createSolidMachine, solidScope } from '@macro-inc/machine/solid';
+import { onCleanup } from 'solid-js';
+
+const machine = createSolidMachine({
+ initial,
+ def,
+ scopes: {
+ flashing: solidScope((_state, dispatch) => {
+ const timer = setTimeout(() => dispatch({ t: 'flash-elapsed' }), 1000);
+ onCleanup(() => clearTimeout(timer));
+ }),
+ },
+});
+```
+
+Each invocation gets a fresh Solid root. Leaving the state disposes that root,
+including its computations and cleanups. The core only receives its disposer.
diff --git a/packages/machine/biome.jsonc b/packages/machine/biome.jsonc
new file mode 100644
index 0000000000..60adc29e35
--- /dev/null
+++ b/packages/machine/biome.jsonc
@@ -0,0 +1,11 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.12/schema.json",
+ "root": true,
+ "extends": ["../../biome.base.jsonc"],
+ "vcs": {
+ "root": "../.."
+ },
+ "files": {
+ "includes": ["**/*.{ts,tsx,js,jsx,json}", "!**/*.d.ts", "!**/node_modules"]
+ }
+}
diff --git a/packages/machine/package.json b/packages/machine/package.json
new file mode 100644
index 0000000000..89879602f6
--- /dev/null
+++ b/packages/machine/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@macro-inc/machine",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts",
+ "./solid": "./src/solid.ts"
+ },
+ "scripts": {
+ "lint": "biome check .",
+ "test": "vitest run --config vitest.config.ts",
+ "type-check": "tsc --noEmit --project tsconfig.json"
+ },
+ "peerDependencies": {
+ "solid-js": "^1.9.7"
+ },
+ "peerDependenciesMeta": {
+ "solid-js": {
+ "optional": true
+ }
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.12",
+ "@types/node": "^24.8.0",
+ "jsdom": "^26.1.0",
+ "solid-js": "^1.9.7",
+ "typescript": "^5.9.3",
+ "vite-plugin-solid": "^2.11.8",
+ "vitest": "5.0.1"
+ }
+}
diff --git a/packages/machine/src/create-machine.test.ts b/packages/machine/src/create-machine.test.ts
new file mode 100644
index 0000000000..55c34f6948
--- /dev/null
+++ b/packages/machine/src/create-machine.test.ts
@@ -0,0 +1,408 @@
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import {
+ createMachine,
+ DispatchCycleError,
+ MAX_CHAINED_DISPATCHES,
+ type MachineDef,
+ type MachineOptions,
+} from './index';
+
+// Importing the public core entry point must never load Solid.
+vi.mock('solid-js', () => {
+ throw new Error('The machine core must not import Solid');
+});
+
+type S = { t: 'a' } | { t: 'b'; n: number } | { t: 'c' };
+type E =
+ | { t: 'go-b'; n: number }
+ | { t: 'go-c' }
+ | { t: 'go-a' }
+ | { t: 'noop' };
+type C = { t: 'cmd'; n: number };
+
+const def: MachineDef<S, E, C> = {
+ a: {
+ on: (_s, e) =>
+ e.t === 'go-b'
+ ? { state: { t: 'b', n: e.n }, commands: [{ t: 'cmd', n: e.n }] }
+ : undefined,
+ },
+ b: {
+ on: (s, e) => {
+ switch (e.t) {
+ case 'go-b':
+ return { state: { t: 'b', n: e.n } };
+ case 'go-c':
+ return { state: { t: 'c' }, commands: [{ t: 'cmd', n: s.n }] };
+ default:
+ return undefined;
+ }
+ },
+ },
+ c: { on: (_s, e) => (e.t === 'go-a' ? { state: { t: 'a' } } : undefined) },
+};
+
+function create(options: Partial<MachineOptions<S, E, C>> = {}) {
+ const machine = createMachine<S, E, C>({
+ initial: { t: 'a' },
+ def,
+ ...options,
+ });
+ onTestFinished(machine.dispose);
+ return machine;
+}
+
+describe('createMachine', () => {
+ it('runs without a Solid owner or a DOM', () => {
+ expect(typeof document).toBe('undefined');
+ const machine = create();
+ expect(machine.getState()).toEqual({ t: 'a' });
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(machine.getState()).toEqual({ t: 'b', n: 1 });
+ });
+
+ it('reports ignored events without notifying or restarting the scope', () => {
+ const inspect = vi.fn();
+ const cleanup = vi.fn();
+ const scope = vi.fn(() => cleanup);
+ const listener = vi.fn();
+ const machine = create({ inspect, scopes: { a: scope } });
+ const initial = machine.getState();
+ machine.subscribe(listener);
+ machine.dispatch({ t: 'noop' });
+ expect(inspect).toHaveBeenCalledWith(initial, { t: 'noop' }, 'ignored');
+ expect(machine.getState()).toBe(initial);
+ expect(listener).not.toHaveBeenCalled();
+ expect(scope).toHaveBeenCalledOnce();
+ expect(cleanup).not.toHaveBeenCalled();
+ });
+
+ it('cleans up, enters, publishes, and executes commands in order', () => {
+ const order: string[] = [];
+ const machine = create({
+ def: {
+ ...def,
+ a: {
+ on: () => ({
+ state: { t: 'b', n: 7 },
+ commands: [
+ { t: 'cmd', n: 1 },
+ { t: 'cmd', n: 2 },
+ ],
+ }),
+ },
+ },
+ scopes: {
+ a: () => () => {
+ order.push(`leave ${machine.getState().t}`);
+ },
+ b: () => {
+ order.push('enter b');
+ },
+ },
+ execute: (cmd) => {
+ order.push(`command ${cmd.n} in ${machine.getState().t}`);
+ },
+ });
+ machine.subscribe((state) => order.push(`notify ${state.t}`));
+ machine.dispatch({ t: 'go-b', n: 7 });
+ expect(order).toEqual([
+ 'leave a',
+ 'enter b',
+ 'notify b',
+ 'command 1 in b',
+ 'command 2 in b',
+ ]);
+ });
+
+ it('restarts scopes on same-tag transitions with a fresh payload', () => {
+ const log: string[] = [];
+ const machine = create({
+ initial: { t: 'b', n: 1 },
+ scopes: {
+ b: (state) => {
+ log.push(`enter ${state.n}`);
+ return () => {
+ log.push(`leave ${state.n}`);
+ };
+ },
+ },
+ });
+ machine.dispatch({ t: 'go-b', n: 2 });
+ machine.dispose();
+ expect(log).toEqual(['enter 1', 'leave 1', 'enter 2', 'leave 2']);
+ });
+
+ it('restarts even when an accepted transition returns the same object', () => {
+ const cleanup = vi.fn();
+ const scope = vi.fn(() => cleanup);
+ const machine = create({
+ def: { ...def, a: { on: (state) => ({ state }) } },
+ scopes: { a: scope },
+ });
+ const listener = vi.fn();
+ machine.subscribe(listener);
+ machine.dispatch({ t: 'noop' });
+ expect(scope).toHaveBeenCalledTimes(2);
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(listener).toHaveBeenCalledWith(machine.getState());
+ });
+
+ it('finishes the initial scope before draining its events', () => {
+ const order: string[] = [];
+ const machine = create({
+ scopes: {
+ a: (_state, dispatch) => {
+ dispatch({ t: 'go-b', n: 3 });
+ order.push('initial mounted');
+ return () => {
+ order.push('initial cleaned up');
+ };
+ },
+ b: () => {
+ order.push('b mounted');
+ },
+ },
+ });
+ expect(machine.getState()).toEqual({ t: 'b', n: 3 });
+ expect(order).toEqual([
+ 'initial mounted',
+ 'initial cleaned up',
+ 'b mounted',
+ ]);
+ });
+
+ it('queues events from scopes until scope entry and commands finish', () => {
+ const order: string[] = [];
+ const machine = create({
+ scopes: {
+ b: (_state, dispatch) => {
+ dispatch({ t: 'go-c' });
+ order.push('b mounted');
+ },
+ c: () => {
+ order.push('c mounted');
+ },
+ },
+ execute: () => {
+ order.push(`command in ${machine.getState().t}`);
+ },
+ });
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(order).toEqual([
+ 'b mounted',
+ 'command in b',
+ 'c mounted',
+ 'command in c',
+ ]);
+ });
+
+ it('queues events from commands', () => {
+ const machine = create({
+ execute: (cmd, dispatch) => {
+ if (cmd.n === 1) dispatch({ t: 'go-c' });
+ },
+ });
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(machine.getState()).toEqual({ t: 'c' });
+ });
+
+ it('queues events from outgoing cleanups', () => {
+ const machine = create({
+ initial: { t: 'b', n: 1 },
+ scopes: {
+ b: (_state, dispatch) => () => dispatch({ t: 'go-a' }),
+ },
+ });
+ machine.dispatch({ t: 'go-c' });
+ expect(machine.getState()).toEqual({ t: 'a' });
+ });
+
+ it('finishes notifying all subscribers before processing their events', () => {
+ const order: string[] = [];
+ const machine = create();
+ machine.subscribe((state) => {
+ order.push(`first ${state.t}`);
+ if (state.t === 'b') machine.dispatch({ t: 'go-c' });
+ });
+ machine.subscribe((state) => {
+ order.push(`second ${state.t} reads ${machine.getState().t}`);
+ });
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(order).toEqual([
+ 'first b',
+ 'second b reads b',
+ 'first c',
+ 'second c reads c',
+ ]);
+ });
+
+ it('subscribes to future transitions and stops on unsubscribe', () => {
+ const machine = create();
+ const listener = vi.fn();
+ const unsubscribe = machine.subscribe(listener);
+ expect(listener).not.toHaveBeenCalled();
+ machine.dispatch({ t: 'go-b', n: 4 });
+ unsubscribe();
+ unsubscribe();
+ machine.dispatch({ t: 'go-c' });
+ expect(listener).toHaveBeenCalledExactlyOnceWith({ t: 'b', n: 4 });
+ });
+
+ it('defers new subscribers and respects unsubscribe during notification', () => {
+ const machine = create();
+ const removed = vi.fn();
+ const added = vi.fn();
+ machine.subscribe(() => {
+ unsubscribe();
+ machine.subscribe(added);
+ });
+ const unsubscribe = machine.subscribe(removed);
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(removed).not.toHaveBeenCalled();
+ expect(added).not.toHaveBeenCalled();
+ machine.dispatch({ t: 'go-c' });
+ expect(added).toHaveBeenCalledExactlyOnceWith({ t: 'c' });
+ });
+
+ it('disposes once and ignores cleanup, late, and queued dispatches', () => {
+ const cleanup = vi.fn();
+ const machine = create({
+ initial: { t: 'b', n: 1 },
+ scopes: {
+ b: (_state, dispatch) => () => {
+ cleanup();
+ dispatch({ t: 'go-c' });
+ },
+ },
+ });
+ const listener = vi.fn();
+ machine.subscribe(listener);
+ machine.dispose();
+ machine.dispose();
+ machine.subscribe(listener);
+ machine.dispatch({ t: 'go-c' });
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(listener).not.toHaveBeenCalled();
+ expect(machine.getState()).toEqual({ t: 'b', n: 1 });
+ });
+
+ it('cancels a timer when its state is left or its machine is disposed', () => {
+ vi.useFakeTimers();
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ const machine = create({
+ initial: { t: 'b', n: 1 },
+ scopes: {
+ b: (_state, dispatch) => {
+ const timer = setTimeout(() => dispatch({ t: 'go-c' }), 100);
+ return () => clearTimeout(timer);
+ },
+ },
+ });
+ machine.dispatch({ t: 'go-b', n: 2 });
+ expect(vi.getTimerCount()).toBe(1);
+ machine.dispose();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.advanceTimersByTime(100);
+ expect(machine.getState()).toEqual({ t: 'b', n: 2 });
+ });
+
+ it('stops a transition if its outgoing cleanup disposes the machine', () => {
+ const entered = vi.fn();
+ const execute = vi.fn();
+ const machine = create({
+ scopes: {
+ a: () => () => machine.dispose(),
+ b: entered,
+ },
+ execute,
+ });
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(machine.getState()).toEqual({ t: 'a' });
+ expect(entered).not.toHaveBeenCalled();
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('releases cleanup returned after a scope disposes the machine', () => {
+ const cleanup = vi.fn();
+ const execute = vi.fn();
+ const machine = create({
+ scopes: {
+ b: () => {
+ machine.dispose();
+ return cleanup;
+ },
+ },
+ execute,
+ });
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('stops notifications, commands, and queued events on subscriber disposal', () => {
+ const execute = vi.fn();
+ const nextListener = vi.fn();
+ const machine = create({ execute });
+ machine.subscribe(() => {
+ machine.dispatch({ t: 'go-c' });
+ machine.dispose();
+ });
+ machine.subscribe(nextListener);
+ machine.dispatch({ t: 'go-b', n: 1 });
+ expect(nextListener).not.toHaveBeenCalled();
+ expect(execute).not.toHaveBeenCalled();
+ expect(machine.getState()).toEqual({ t: 'b', n: 1 });
+ });
+
+ it('discards queued events after a command throws', () => {
+ const machine = create({
+ execute: (_cmd, dispatch) => {
+ dispatch({ t: 'go-c' });
+ throw new Error('command failed');
+ },
+ });
+ expect(() => machine.dispatch({ t: 'go-b', n: 1 })).toThrow(
+ 'command failed'
+ );
+ machine.dispatch({ t: 'noop' });
+ expect(machine.getState()).toEqual({ t: 'b', n: 1 });
+ });
+
+ it('reports a dispatch cycle and cleans up when construction fails', () => {
+ type L = { t: 'x' } | { t: 'y' };
+ type LE = { t: 'flip' };
+ const loop: MachineDef<L, LE> = {
+ x: { on: () => ({ state: { t: 'y' } }) },
+ y: { on: () => ({ state: { t: 'x' } }) },
+ };
+ let entered = 0;
+ let cleanedUp = 0;
+ const scope = (_state: L, dispatch: (event: LE) => void) => {
+ entered++;
+ dispatch({ t: 'flip' });
+ return () => {
+ cleanedUp++;
+ };
+ };
+ let error: unknown;
+ try {
+ createMachine<L, LE>({
+ initial: { t: 'x' },
+ def: loop,
+ scopes: { x: scope, y: scope },
+ });
+ } catch (cause) {
+ error = cause;
+ }
+ expect(error).toBeInstanceOf(DispatchCycleError);
+ const trail = (error as DispatchCycleError).trail;
+ expect(trail.length).toBeGreaterThan(0);
+ expect(trail.length).toBeLessThanOrEqual(20);
+ expect(trail.every((event) => (event as LE).t === 'flip')).toBe(true);
+ expect(entered).toBe(MAX_CHAINED_DISPATCHES + 1);
+ expect(cleanedUp).toBe(entered);
+ });
+});
diff --git a/packages/machine/src/create-machine.ts b/packages/machine/src/create-machine.ts
new file mode 100644
index 0000000000..dab30c40ba
--- /dev/null
+++ b/packages/machine/src/create-machine.ts
@@ -0,0 +1,134 @@
+import { step } from './simulate';
+import type { Cleanup, Machine, MachineOptions, MachineScope } from './types';
+
+/** Maximum events processed in one synchronous drain before assuming a cycle. */
+export const MAX_CHAINED_DISPATCHES = 1000;
+
+const TRAIL_LENGTH = 20;
+
+export class DispatchCycleError extends Error {
+ constructor(readonly trail: readonly unknown[]) {
+ super(
+ `createMachine: ${MAX_CHAINED_DISPATCHES} chained dispatches without settling. ` +
+ 'A scope, command, subscriber, or cleanup is dispatching in a cycle. ' +
+ `Last ${trail.length} events are attached as \`trail\`.`
+ );
+ this.name = 'DispatchCycleError';
+ }
+}
+
+/**
+ * Run a pure definition using ordinary TypeScript state. Scopes own cleanup,
+ * commands perform individual actions, and all nested events are serialized.
+ * The caller owns disposal; UI adapters can tie it to their own lifecycle.
+ */
+export function createMachine<S extends { t: string }, E, C = never>(
+ options: MachineOptions<S, E, C>
+): Machine<S, E> {
+ let state = options.initial;
+ let disposed = false;
+ let draining = false;
+ let disposeScope: Cleanup | undefined;
+ const listeners = new Set<(state: S) => void>();
+ const queue: E[] = [];
+ const trail: E[] = [];
+
+ const dispatch = (event: E): void => {
+ if (disposed) return;
+ queue.push(event);
+ if (!draining) drain();
+ };
+
+ const unmountScope = () => {
+ const cleanup = disposeScope;
+ disposeScope = undefined;
+ cleanup?.();
+ };
+
+ const mountScope = () => {
+ // The state tag selects the callback typed for exactly this state.
+ const scope = options.scopes?.[state.t as S['t']] as
+ | MachineScope<S, E>
+ | undefined;
+ const cleanup = scope?.(state, dispatch);
+ // A callback can dispose the machine before returning its cleanup.
+ if (disposed) cleanup?.();
+ else disposeScope = cleanup ?? undefined;
+ };
+
+ const apply = (event: E) => {
+ const result = step(options.def, state, event);
+ options.inspect?.(state, event, result ?? 'ignored');
+ if (result === undefined || disposed) return;
+
+ // The outgoing cleanup still sees its own state through getState().
+ unmountScope();
+ if (disposed) return;
+ state = result.state;
+ mountScope();
+
+ // Snapshot the listeners so subscribing during notification takes effect
+ // on the next transition. Unsubscribing takes effect immediately.
+ for (const listener of [...listeners]) {
+ if (disposed) return;
+ if (listeners.has(listener)) listener(state);
+ }
+
+ for (const command of result.commands ?? []) {
+ if (disposed) return;
+ options.execute?.(command, dispatch);
+ }
+ };
+
+ const drain = () => {
+ draining = true;
+ let steps = 0;
+ try {
+ while (queue.length > 0) {
+ if (++steps > MAX_CHAINED_DISPATCHES) {
+ throw new DispatchCycleError([...trail]);
+ }
+ const event = queue.shift() as E;
+ trail.push(event);
+ if (trail.length > TRAIL_LENGTH) trail.shift();
+ apply(event);
+ }
+ } finally {
+ draining = false;
+ // Failed transitions must not replay queued events on the next dispatch.
+ queue.length = 0;
+ }
+ };
+
+ const dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ queue.length = 0;
+ listeners.clear();
+ unmountScope();
+ };
+
+ // An initial scope can send events before createMachine returns. Finish
+ // mounting it before draining, and release its resources if startup fails.
+ try {
+ draining = true;
+ mountScope();
+ draining = false;
+ if (queue.length > 0) drain();
+ } catch (error) {
+ dispose();
+ throw error;
+ }
+
+ return {
+ getState: () => state,
+ dispatch,
+ subscribe: (listener) => {
+ if (!disposed) listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ dispose,
+ };
+}
diff --git a/packages/machine/src/index.ts b/packages/machine/src/index.ts
new file mode 100644
index 0000000000..47e9a0fd59
--- /dev/null
+++ b/packages/machine/src/index.ts
@@ -0,0 +1,20 @@
+export {
+ createMachine,
+ DispatchCycleError,
+ MAX_CHAINED_DISPATCHES,
+} from './create-machine';
+export {
+ type Simulation,
+ type SimulationStep,
+ simulate,
+ step,
+} from './simulate';
+export type {
+ Cleanup,
+ Machine,
+ MachineDef,
+ MachineOptions,
+ MachineScope,
+ MachineScopes,
+ Transition,
+} from './types';
diff --git a/packages/machine/src/simulate.ts b/packages/machine/src/simulate.ts
new file mode 100644
index 0000000000..27544d05f3
--- /dev/null
+++ b/packages/machine/src/simulate.ts
@@ -0,0 +1,56 @@
+import type { MachineDef, Transition } from './types';
+
+/**
+ * Pure helpers for exercising a `MachineDef` as values. No Solid, no owner,
+ * no timers — importable from any test or from `domain/` code.
+ *
+ * These do not run scopes or `execute`. Events that a command would have
+ * produced in the runner (e.g. a restore succeeding) must be supplied
+ * explicitly in the event list; that is the point — the reducer is tested
+ * against what it would be told, not against how the world tells it.
+ */
+
+/** Apply one event to one state. */
+export function step<S extends { t: string }, E, C>(
+ def: MachineDef<S, E, C>,
+ state: S,
+ event: E
+): Transition<S, C> | undefined {
+ const entry = def[state.t as S['t']];
+ const on = entry.on as (s: S, e: E) => Transition<S, C> | undefined;
+ return on(state, event);
+}
+
+export type SimulationStep<S, E, C> = {
+ readonly from: S;
+ readonly event: E;
+ readonly result: Transition<S, C> | 'ignored';
+};
+
+export type Simulation<S, E, C> = {
+ readonly state: S;
+ /** Every command emitted along the way, in order. */
+ readonly commands: readonly C[];
+ readonly steps: readonly SimulationStep<S, E, C>[];
+};
+
+/** Apply a sequence of events, collecting emitted commands and the per-step trace. */
+export function simulate<S extends { t: string }, E, C>(
+ def: MachineDef<S, E, C>,
+ initial: S,
+ events: readonly E[]
+): Simulation<S, E, C> {
+ let state = initial;
+ const commands: C[] = [];
+ const steps: SimulationStep<S, E, C>[] = [];
+
+ for (const event of events) {
+ const result = step(def, state, event);
+ steps.push({ from: state, event, result: result ?? 'ignored' });
+ if (result === undefined) continue;
+ state = result.state;
+ if (result.commands !== undefined) commands.push(...result.commands);
+ }
+
+ return { state, commands, steps };
+}
diff --git a/packages/machine/src/solid.test.ts b/packages/machine/src/solid.test.ts
new file mode 100644
index 0000000000..fad223898a
--- /dev/null
+++ b/packages/machine/src/solid.test.ts
@@ -0,0 +1,256 @@
+// @vitest-environment jsdom
+import {
+ createComponent,
+ createComputed,
+ createContext,
+ createRoot,
+ createSignal,
+ onCleanup,
+ useContext,
+} from 'solid-js';
+import { describe, expect, it, onTestFinished, vi } from 'vitest';
+import type { MachineDef } from './index';
+import { createSolidMachine, type SolidMachine, solidScope } from './solid';
+
+type S = { t: 'idle' } | { t: 'active'; id: number };
+type E = { t: 'start'; id: number } | { t: 'stop' };
+type C = { t: 'started' };
+
+const def: MachineDef<S, E, C> = {
+ idle: {
+ on: (_state, event) =>
+ event.t === 'start'
+ ? { state: { t: 'active', id: event.id }, commands: [{ t: 'started' }] }
+ : undefined,
+ },
+ active: {
+ on: (_state, event) => ({
+ state:
+ event.t === 'start' ? { t: 'active', id: event.id } : { t: 'idle' },
+ }),
+ },
+};
+
+function run<T>(fn: (dispose: () => void) => T) {
+ return createRoot((dispose) => {
+ onTestFinished(dispose);
+ return fn(dispose);
+ });
+}
+
+describe('createSolidMachine', () => {
+ it('publishes reactive snapshots and narrowed matches before commands run', () =>
+ run(() => {
+ const observed: Array<number | undefined> = [];
+ const commands: S[] = [];
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'idle' },
+ def,
+ execute: () => commands.push(machine.state()),
+ });
+ createComputed(() => observed.push(machine.matches('active')?.id));
+ machine.dispatch({ t: 'start', id: 7 });
+ machine.dispatch({ t: 'start', id: 8 });
+ machine.dispatch({ t: 'stop' });
+ expect(observed).toEqual([undefined, 7, 8, undefined]);
+ expect(commands).toEqual([{ t: 'active', id: 7 }]);
+ expect(machine.matches('idle')).toEqual({ t: 'idle' });
+ }));
+
+ it('initializes the signal from the settled initial scope', () =>
+ run(() => {
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'idle' },
+ def,
+ scopes: { idle: (_state, dispatch) => dispatch({ t: 'start', id: 2 }) },
+ });
+ expect(machine.state()).toEqual({ t: 'active', id: 2 });
+ }));
+
+ it('queues dispatches from reactive consumers until commands finish', () =>
+ run(() => {
+ const commands: S[] = [];
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'idle' },
+ def,
+ execute: () => commands.push(machine.state()),
+ });
+ createComputed(() => {
+ if (machine.matches('active')) machine.dispatch({ t: 'stop' });
+ });
+ machine.dispatch({ t: 'start', id: 1 });
+ expect(commands).toEqual([{ t: 'active', id: 1 }]);
+ expect(machine.state()).toEqual({ t: 'idle' });
+ }));
+
+ it('does not subscribe a dispatch caller to signals read by callbacks', () =>
+ run(() => {
+ const [trigger, setTrigger] = createSignal(0);
+ const [external, setExternal] = createSignal(0);
+ let runs = 0;
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'idle' },
+ def,
+ inspect: () => {
+ external();
+ },
+ });
+ createComputed(() => {
+ runs++;
+ machine.dispatch({ t: 'start', id: trigger() });
+ });
+ setExternal(1);
+ expect(runs).toBe(1);
+ setTrigger(1);
+ expect(runs).toBe(2);
+ }));
+
+ it('disposes with its owner and ignores later dispatches', () =>
+ run((dispose) => {
+ const cleanup = vi.fn();
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'active', id: 1 },
+ def,
+ scopes: { active: () => cleanup },
+ });
+ dispose();
+ machine.dispatch({ t: 'stop' });
+ machine.dispose();
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(machine.state()).toEqual({ t: 'active', id: 1 });
+ }));
+
+ it('supports explicit disposal without a Solid owner', () => {
+ const cleanup = vi.fn();
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'active', id: 1 },
+ def,
+ scopes: { active: () => cleanup },
+ });
+ onTestFinished(machine.dispose);
+ machine.dispose();
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+});
+
+describe('solidScope', () => {
+ it('registers cleanup once when a callback returns onCleanup directly', () =>
+ run((dispose) => {
+ const cleanup = vi.fn();
+ createSolidMachine<S, E, C>({
+ initial: { t: 'active', id: 1 },
+ def,
+ scopes: { active: solidScope(() => onCleanup(cleanup)) },
+ });
+ dispose();
+ expect(cleanup).toHaveBeenCalledOnce();
+ }));
+
+ it('reads the current state during entry before subscribers are notified', () =>
+ run(() => {
+ let seen: S | undefined;
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'idle' },
+ def,
+ scopes: {
+ active: solidScope(() => {
+ seen = machine.state();
+ }),
+ },
+ });
+ machine.dispatch({ t: 'start', id: 1 });
+ expect(seen).toEqual({ t: 'active', id: 1 });
+ }));
+
+ it('disposes computations on exit and recreates them for a fresh payload', () =>
+ run((dispose) => {
+ const [input, setInput] = createSignal(0);
+ const reads: Array<[number, number]> = [];
+ const cleanup = vi.fn();
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'active', id: 1 },
+ def,
+ scopes: {
+ active: solidScope((state) => {
+ createComputed(() => reads.push([state.id, input()]));
+ onCleanup(cleanup);
+ }),
+ },
+ });
+ setInput(1);
+ machine.dispatch({ t: 'start', id: 2 });
+ setInput(2);
+ machine.dispatch({ t: 'stop' });
+ setInput(3);
+ dispose();
+ expect(reads).toEqual([
+ [1, 0],
+ [1, 1],
+ [2, 1],
+ [2, 2],
+ ]);
+ expect(cleanup).toHaveBeenCalledTimes(2);
+ }));
+
+ it('runs outgoing Solid cleanup while the adapter still reads the old state', () =>
+ run(() => {
+ let seen: S | undefined;
+ const machine = createSolidMachine<S, E, C>({
+ initial: { t: 'active', id: 1 },
+ def,
+ scopes: {
+ active: solidScope(() => {
+ onCleanup(() => {
+ seen = machine.state();
+ });
+ }),
+ },
+ });
+ machine.dispatch({ t: 'stop' });
+ expect(seen).toEqual({ t: 'active', id: 1 });
+ }));
+
+ it('captures context from configuration, even when dispatched outside it', () => {
+ const Context = createContext('default');
+ const seen: string[] = [];
+ const machine = run(() => {
+ let machine!: SolidMachine<S, E>;
+ createComponent(Context.Provider, {
+ value: 'configured',
+ get children() {
+ machine = createSolidMachine<S, E, C>({
+ initial: { t: 'idle' },
+ def,
+ scopes: {
+ active: solidScope(() => {
+ seen.push(useContext(Context));
+ }),
+ },
+ });
+ return null;
+ },
+ });
+ return machine;
+ });
+ machine.dispatch({ t: 'start', id: 1 });
+ expect(seen).toEqual(['configured']);
+ });
+
+ it('cleans up a Solid root if its callback throws during construction', () =>
+ run(() => {
+ const cleanup = vi.fn();
+ expect(() =>
+ createSolidMachine<S, E, C>({
+ initial: { t: 'active', id: 1 },
+ def,
+ scopes: {
+ active: solidScope(() => {
+ onCleanup(cleanup);
+ throw new Error('scope failed');
+ }),
+ },
+ })
+ ).toThrow('scope failed');
+ expect(cleanup).toHaveBeenCalledOnce();
+ }));
+});
diff --git a/packages/machine/src/solid.ts b/packages/machine/src/solid.ts
new file mode 100644
index 0000000000..28dec30f71
--- /dev/null
+++ b/packages/machine/src/solid.ts
@@ -0,0 +1,74 @@
+import {
+ type Accessor,
+ createRoot,
+ createSignal,
+ getOwner,
+ onCleanup,
+ untrack,
+} from 'solid-js';
+import { createMachine } from './create-machine';
+import type { Machine, MachineOptions, MachineScope } from './types';
+
+export type SolidMachine<S extends { t: string }, E> = Pick<
+ Machine<S, E>,
+ 'dispatch' | 'dispose'
+> & {
+ readonly state: Accessor<S>;
+ /** Read and narrow the reactive snapshot: `machine.matches('flashing')`. */
+ readonly matches: <K extends S['t']>(
+ tag: K
+ ) => Extract<S, { t: K }> | undefined;
+};
+
+/** Create a machine whose snapshots are reactive and whose owner disposes it. */
+export function createSolidMachine<S extends { t: string }, E, C = never>(
+ options: MachineOptions<S, E, C>
+): SolidMachine<S, E> {
+ const machine = untrack(() => createMachine(options));
+ const [snapshot, setState] = createSignal(machine.getState());
+ const unsubscribe = machine.subscribe((next) => setState(() => next));
+ const state = () => {
+ // Track published snapshots while keeping imperative reads inside scope
+ // entry/cleanup consistent with the core's current state.
+ snapshot();
+ return machine.getState();
+ };
+ const dispose = () => {
+ unsubscribe();
+ machine.dispose();
+ };
+ if (getOwner() !== null) onCleanup(dispose);
+
+ return {
+ state,
+ dispatch: (event) => untrack(() => machine.dispatch(event)),
+ dispose,
+ matches: <K extends S['t']>(tag: K) => {
+ const snapshot = state();
+ return snapshot.t === tag
+ ? (snapshot as Extract<S, { t: K }>)
+ : undefined;
+ },
+ };
+}
+
+/**
+ * Give a scope a Solid root for computations and context. Register cleanup
+ * with onCleanup inside the callback. Capture the owner when configuring the
+ * scope, so later dispatches inherit that context too.
+ */
+export function solidScope<S, E>(
+ scope: (state: S, dispatch: (event: E) => void) => void
+): MachineScope<S, E> {
+ const owner = getOwner();
+ return (state, dispatch) =>
+ createRoot((dispose) => {
+ try {
+ scope(state, (event) => untrack(() => dispatch(event)));
+ return dispose;
+ } catch (error) {
+ dispose();
+ throw error;
+ }
+ }, owner);
+}
diff --git a/packages/machine/src/types.ts b/packages/machine/src/types.ts
new file mode 100644
index 0000000000..7d82ad8dd9
--- /dev/null
+++ b/packages/machine/src/types.ts
@@ -0,0 +1,63 @@
+/** Cleanup for a scope or subscription. */
+export type Cleanup = () => void;
+
+/** Next state and the commands to execute after entering it. */
+export type Transition<S, C> = {
+ readonly state: S;
+ readonly commands?: readonly C[];
+};
+
+/**
+ * Pure transition handlers, exhaustively keyed by state. Returning `undefined`
+ * ignores an event and leaves the current state and scope untouched.
+ */
+export type MachineDef<S extends { t: string }, E, C = never> = {
+ readonly [K in S['t']]: {
+ readonly on: (
+ s: Extract<S, { t: K }>,
+ e: E
+ ) => Transition<S, C> | undefined;
+ };
+};
+
+/** Start work for a state instance and optionally return its cleanup. */
+export type MachineScope<S, E> = (
+ state: S,
+ dispatch: (event: E) => void
+) => Cleanup | void;
+
+/**
+ * Work with a state lifetime. Every accepted transition cleans up the old
+ * scope and starts the next, including transitions with the same `t`. The
+ * state passed to a scope stays constant for that scope's lifetime.
+ */
+export type MachineScopes<S extends { t: string }, E> = {
+ readonly [K in S['t']]?: MachineScope<Extract<S, { t: K }>, E>;
+};
+
+export type MachineOptions<S extends { t: string }, E, C = never> = {
+ readonly initial: S;
+ readonly def: MachineDef<S, E, C>;
+ readonly scopes?: MachineScopes<S, E> | undefined;
+ /** Execute commands in order after entering and publishing the next state. */
+ readonly execute?: ((cmd: C, dispatch: (e: E) => void) => void) | undefined;
+ /** Observe every event, including ignored ones, before applying its result. */
+ readonly inspect?:
+ | ((from: S, e: E, result: Transition<S, C> | 'ignored') => void)
+ | undefined;
+};
+
+/** A running machine with an explicit lifetime and synchronous state access. */
+export type Machine<S, E> = {
+ readonly getState: () => S;
+ /** Nested dispatches queue until the current transition has completed. */
+ readonly dispatch: (event: E) => void;
+ /**
+ * Subscribe to future accepted transitions, after scope entry and before
+ * commands. Read `getState()` for the initial snapshot. Ignored events do
+ * not notify subscribers.
+ */
+ readonly subscribe: (listener: (state: S) => void) => Cleanup;
+ /** Clean up once, remove subscriptions, and ignore subsequent dispatches. */
+ readonly dispose: Cleanup;
+};
diff --git a/packages/machine/tsconfig.json b/packages/machine/tsconfig.json
new file mode 100644
index 0000000000..592c815d4a
--- /dev/null
+++ b/packages/machine/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "allowImportingTsExtensions": true,
+ "esModuleInterop": true,
+ "exactOptionalPropertyTypes": true,
+ "forceConsistentCasingInFileNames": true,
+ "isolatedModules": true,
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "noEmit": true,
+ "noUncheckedIndexedAccess": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "target": "ESNext",
+ "types": ["@types/node", "vite/client"]
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/packages/machine/vitest.config.ts b/packages/machine/vitest.config.ts
new file mode 100644
index 0000000000..151f867463
--- /dev/null
+++ b/packages/machine/vitest.config.ts
@@ -0,0 +1,20 @@
+import solidPlugin from 'vite-plugin-solid';
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ plugins: [solidPlugin()],
+ resolve: {
+ dedupe: ['solid-js'],
+ conditions: ['browser', 'development'],
+ },
+ ssr: {
+ resolve: {
+ conditions: ['browser', 'development'],
+ },
+ },
+ test: {
+ environment: 'node',
+ include: ['src/**/*.{test,spec}.ts'],
+ name: 'machine',
+ },
+});