solid2-signals
v0.0.6
Published
Priority scheduling for Solid 2 signals and stores, with a vite-import-replacer based Vite preset
Readme
solid2-signals
Priority-aware signals and stores for SolidJS 2. Keep time-sensitive UI updates responsive when other state changes trigger asynchronous computations.
solid2-signals provides drop-in-style signal and draft-store factories with two write priorities:
| Factory | Priority | Typical use |
| --- | --- | --- |
| createSignal | Normal | Data, counters, results, async-dependent state |
| createSyncSignal | Sync first | Menus, selections, immediate interaction feedback |
| createStore | Normal | Structured app state |
| createSyncStore | Sync first | UI state that should publish ahead of normal writes |
Writes are batched automatically. The scheduler publishes sync-priority writes first and normal writes afterward; in most applications you never call flushWrites().
Install
npm install solid2-signalsThis package requires SolidJS 2 (solid-js >=2.0.0-rc.17 <3) and is not intended for Solid 1. Use one compatible Solid 2 runtime throughout your application.
Basic usage
Import the factories directly from solid2-signals/priority (or solid2-signals, which exports the same runtime API):
import {
createSignal,
createSyncSignal,
createStore,
createSyncStore
} from "solid2-signals/priority";
const [count, setCount] = createSignal(0);
const [menuOpen, setMenuOpen] = createSyncSignal(false);
const [data, setData] = createStore({ items: 0 });
const [ui, setUI] = createSyncStore({ selected: "" });
function onAction() {
setMenuOpen(open => !open);
setCount(n => n + 1);
setData(draft => { draft.items += 1; });
setUI(draft => { draft.selected = "item-1"; });
// No manual flush required.
}These factories use Solid 2's signal tuple and draft callback store interfaces. They do not replace createMemo, Loading, isPending, or other Solid APIs.
Why sync priority matters with an async memo
For example, closing a menu and incrementing a count in one event can trigger an asynchronous memo. The menu can render its new state before the normal update's async work resolves:
import { createMemo, Loading } from "solid-js";
import { createSignal, createSyncSignal } from "solid2-signals/priority";
function Example() {
const [count, setCount] = createSignal(1);
const [open, setOpen] = createSyncSignal(true);
const doubled = createMemo(async () => {
const value = count(); // Capture dependency before awaiting.
await new Promise(resolve => setTimeout(resolve, 1000));
return value * 2;
});
const closeAndIncrement = () => {
setOpen(false);
setCount(n => n + 1);
};
return (
<>
<button onClick={closeAndIncrement}>Close menu + increment</button>
<div>{open() ? "Menu open" : "Menu closed"}</div>
<Loading fallback={<span>Computing…</span>}>
<span>Double: {doubled()}</span>
</Loading>
</>
);
}The sync UI update gets its own flush ahead of the normal lane. Its independence matters: subscribers that also depend on a pending async value can still be held by Solid's transition rules.
Use with Vite — keep existing Solid imports
The optional Vite preset automatically redirects named imports of createSignal and createStore from solid-js to solid2-signals/priority. Your application and eligible third-party packages can keep their source imports unchanged:
import { createSignal, createStore, createMemo } from "solid-js";
// createSignal and createStore are redirected.
// createMemo remains native Solid 2.Install the Vite integration dependencies in your application:
npm install -D vite @solidjs/vite-plugin vite-import-replacer@^0.0.3// vite.config.ts
import { defineConfig } from "vite";
import solid from "@solidjs/vite-plugin";
import { prioritySignals } from "solid2-signals/vite";
export default defineConfig({
plugins: [
prioritySignals(),
solid()
]
});Default: all eligible third-party packages are included, not just your application files. Solid's runtime packages, solid2-signals, and the generic replacement tool are protected from rewriting. This makes adoption convenient when you do not know the full dependency list, but may increase processing time on large projects.
createSyncSignal and createSyncStore remain explicit imports:
import { createSyncSignal, createSyncStore } from "solid2-signals/priority";Fine-grained dependency selection
When you know which third-party packages should be transformed, name only those packages to reduce the dependency scan and avoid changing unrelated libraries:
prioritySignals({
dependencies: {
include: ["@acme/ui", "my-solid-widgets"]
}
});include here refers to the npm package owner of the file being transformed, not the module name being imported.
You can also exclude a specific package while keeping broad coverage, or restrict rewriting to application source only:
// All eligible dependencies except these additional packages
prioritySignals({
dependencies: { exclude: ["legacy-widget"] }
});
// App-only: no third-party dependency imports are changed
prioritySignals({ dependencies: false });| Dependency option | What it transforms |
| --- | --- |
| Omitted (default), or "all" | App + all eligible dependency owners, except protected owners |
| { include: ["@acme/ui"] } | App + only the named dependency owners |
| { exclude: ["legacy-widget"] } | App + eligible dependencies except that owner and protected owners |
| false or { include: [] } | App only |
What broad coverage means: the plugin attempts to transform supported static named imports and re-exports in eligible dependency source files. It does not rewrite CommonJS require(), dynamic imports, namespace member access (Solid.createSignal), or already-optimized vendor bundles. Some packages may be externalized or precompiled before a transform can reach their original imports. The broad mode is therefore not a guarantee that every library in your dependency graph uses these factories.
Choose factories and files
prioritySignals({
replace: ["createSignal"], // Keep createStore native
include: { glob: "src/**/*.tsx" },
exclude: { glob: "src/**/*.test.tsx" }
});include and exclude are file matchers, not package selectors. They match paths relative to each importing package's root. When set, include also restricts which files can be transformed in selected dependencies, so an app-specific src/** pattern may exclude files from a dependency whose layout differs.
The accepted matcher forms are an exact path string, RegExp, { glob: string }, { regex: string, flags?: string }, or an array of those forms. Arbitrary callback predicates are not supported. A named import's local alias is preserved, as in createSignal as signal.
Signals: setter values and reads
Signal updater callbacks execute immediately, once, in call order. Setters return the calculated value. Imperative getters expose the latest staged write even before reactive publication:
const [count, setCount] = createSignal(0);
const [urgent, setUrgent] = createSyncSignal(0);
setUrgent(10);
const result = setCount(n => n + urgent()); // 10
setUrgent(12);
console.log(result); // 10 (not recalculated)
console.log(count()); // 10, staged read
console.log(urgent()); // 12, staged readConsecutive updates to the same signal use that signal's latest staged value:
setCount(n => n + 1); // returns 11
setCount(n => n + 1); // returns 12Tracked accessors in JSX, memos, and effect compute callbacks read the committed Solid value rather than the staged value. An effect can therefore observe an intermediate sync-only snapshot before normal state publishes. This difference is intentional; it means timing is not identical to native createSignal in every context.
Stores
Both stores use Solid 2's draft callback setter, not Solid 1's path-based setter:
const [state, setState] = createSyncStore({
position: { x: 0, y: 0 },
labels: [] as string[]
});
setState(draft => {
draft.position.x = 50;
draft.labels.push("selected");
});Store drafts run in their priority commit phase, unlike immediate signal updater evaluation. Stores do not expose staged read-your-writes values, and their setters do not return a computed value.
API & TypeScript reference
The two runtime import paths (solid2-signals and solid2-signals/priority) export the same API:
| Export | Type / contract |
| --- | --- |
| createSignal | typeof import("solid-js").createSignal — normal write lane |
| createSyncSignal | typeof import("solid-js").createSignal — sync write lane |
| createStore | typeof import("solid-js").createStore — normal draft-store lane |
| createSyncStore | typeof import("solid-js").createStore — sync draft-store lane |
| flushWrites | () => void — explicitly drain queued writes |
| hasPendingWrites | () => boolean — true if queued writes remain |
All four factories use Solid 2's TypeScript types, including the generic type inference of the underlying Solid factories. The runtime differences and limitations described here still apply.
From solid2-signals/vite:
export type ReplaceableFactory = "createSignal" | "createStore";
export type FileMatcher =
| string
| RegExp
| { glob: string }
| { regex: string; flags?: string };
export interface PrioritySignalsOptions {
replace?: readonly ReplaceableFactory[];
dependencies?:
| "all"
| false
| {
include?: readonly string[];
exclude?: readonly string[];
};
include?: FileMatcher | readonly FileMatcher[];
exclude?: FileMatcher | readonly FileMatcher[];
ssr?: boolean;
}
export function prioritySignals(
options?: PrioritySignalsOptions
): PrioritySignalsVitePlugin;PrioritySignalsVitePlugin is the return type of the generic Vite plugin service. replace defaults to both factories. replace: [] disables replacement rules. Dependency scope defaults to "all", and SSR transformations default to off.
Advanced controls
Normally the scheduler flushes automatically during a microtask. For tests or explicit scheduling control:
import { flushWrites, hasPendingWrites } from "solid2-signals/priority";
setCount(n => n + 1);
if (hasPendingWrites()) flushWrites();flushWrites() creates priority flush boundaries; it is not needed after ordinary setters. Follow Solid 2's restrictions on writes inside owned components/computations, and invoke explicit flushes outside their initialization scopes.
SSR
By default the Vite preset transforms the client environment only. It exposes ssr: true for advanced integrations, but the priority scheduler uses a shared module-level queue without per-request isolation. Do not enable SSR rewriting until your application handles that isolation safely. Vite SSR externalization can also prevent some dependency transforms.
Compatibility and limitations
- Only supported named
createSignal/createStoreimports and re-exports fromsolid-js(pluscreateSignalfrom@solidjs/signals) are redirected; other Solid APIs stay native. - Function-valued signal overloads, all hydration modes, and every edge case of native setter compatibility or pending async transitions are not guaranteed. This package aims for familiar usage rather than a claim of complete native equivalence.
- Sync and normal updates publish in separate flushes; reactive observers can see sync-only intermediate state.
- The global Vite preset intentionally excludes Solid internals, the replacement runtime, and the generic replacer. Broad dependency mode trades potentially longer optimization time for less configuration.
- Only client-side scheduling has been validated; server-side concurrent request isolation is not provided.
License
MIT
