import { getOwner, onSettled, onCleanup, createSignal, type Accessor, untrack, type ComputeFunction, type NoInfer, type Setter, type SignalOptions, type Signal, type Store, type StoreSetter, DEV, } from "solid-js"; import { sharedConfig } from "solid-js/internal"; // isServer moved from solid-js/web (1.x) to @solidjs/web (2.x). // typeof window is a universal fallback compatible with both versions. const isServer: boolean = typeof window === "undefined"; import type { AccessorArray, AnyClass, MaybeAccessor, MaybeAccessorValue, Noop, AnyObject, AnyFunction, } from "./types.ts"; export * from "./types.ts"; // // GENERAL HELPERS: // /** `true` on the server (SSR), `false` in the browser. */ export { isServer }; /** `true` in the browser, `false` on the server. */ export const isClient: boolean = !isServer; /** `true` in the browser with Solid's DEV mode active. */ export const isDev: boolean = isClient && !!DEV; /** `true` when DEV mode is off (i.e. production browser builds and all SSR). */ export const isProd: boolean = !isDev; /** No-operation function — accepts any arguments and returns `undefined`. */ export const noop: Noop = (() => void 0) as Noop; /** A function that always returns `true`. Useful as a default predicate prop. */ export const trueFn: () => boolean = () => true; /** A function that always returns `false`. Useful as a default predicate prop. */ export const falseFn: () => boolean = () => false; /** @deprecated use {@link equalFn} from "solid-js" */ export const defaultEquals: typeof Object.is = Object.is.bind(Object); /** * Signal options that disable equality checking, causing the signal to always * notify subscribers even when the value hasn't changed. Useful for signals * holding mutable objects where structural equality cannot be assumed. */ export const EQUALS_FALSE_OPTIONS: { readonly equals: false } = { equals: false, } as const satisfies SignalOptions; /** * Signal options that allow writes from inside an owned reactive scope * (component body, memo, or effect) without throwing `SIGNAL_WRITE_IN_OWNED_SCOPE` * in Solid 2.0 dev mode. * * Use only for implementation-detail signals that genuinely need to be written * from within a scope — not as a general escape hatch. */ export const INTERNAL_OPTIONS: { readonly ownedWrite: true } = { ownedWrite: true, } as const satisfies SignalOptions; /** * Returns `true` if `v` is an instance of `c`. Checks both `instanceof` and * `constructor` so that values created across different realms (e.g. iframes) match. */ export const ofClass = (v: any, c: AnyClass): boolean => v instanceof c || (v && v.constructor === c); /** Check if value is typeof "object" or "function" */ export function isObject(value: any): value is AnyObject { return value !== null && (typeof value === "object" || typeof value === "function"); } /** Type guard: returns `true` when `i` is neither `null` nor `undefined`. */ export const isNonNullable = (i: T): i is NonNullable => i != null; /** Returns a new array with all `null` and `undefined` items removed. */ export const filterNonNullable = (arr: T): NonNullable[] => arr.filter(isNonNullable); /** Three-way comparison: returns `-1` if `a < b`, `1` if `a > b`, `0` if equal. */ export const compare = (a: any, b: any): number => (a < b ? -1 : a > b ? 1 : 0); /** * Check shallow array equality */ export const arrayEquals = (a: readonly unknown[], b: readonly unknown[]): boolean => a === b || (a.length === b.length && a.every((e, i) => e === b[i])); /** * Returns a function that will call all functions in the order they were chained with the same arguments. */ export function chain(callbacks: { [Symbol.iterator](): IterableIterator<((...args: Args) => any) | undefined>; }): (...args: Args) => void { return (...args: Args) => { for (const callback of callbacks) callback && callback(...args); }; } /** * Returns a function that will call all functions in the reversed order with the same arguments. */ export function reverseChain( callbacks: (((...args: Args) => any) | undefined)[], ): (...args: Args) => void { return (...args: Args) => { for (let i = callbacks.length - 1; i >= 0; i--) { const callback = callbacks[i]; callback && callback(...args); } }; } /** Clamps `n` to the inclusive range `[min, max]`. */ export const clamp = (n: number, min: number, max: number): number => Math.min(Math.max(n, min), max); /** Creates an ID generator with its own isolated counter and per-generator random segment. Each call to the returned function produces a `timestamp-sequence-random` string that is unique within the generator and with high probability unique across independent generators (e.g. separate processes or SSR requests). */ export const createIdGenerator = (): (() => string) => { let seq = 0; const rand = Math.random().toString(36).slice(2, 8); return () => `${Date.now().toString(36)}-${(++seq).toString(36)}-${rand}`; }; /** * Accesses the value of a MaybeAccessor * @example * ```ts * access("foo") // => "foo" * access(() => "foo") // => "foo" * ``` */ export const access = >(v: T): MaybeAccessorValue => typeof v === "function" && !v.length ? v() : (v as any); /** * Wraps `value` in a single-element array. If `value` is already an array it is * returned as-is. Only `null` and `undefined` produce an empty array; other falsy * values such as `0`, `""` and `false` are wrapped. */ export const asArray = (value: T): (T extends any[] ? T[number] : NonNullable)[] => Array.isArray(value) ? (value as any) : value != null ? [value as any] : []; /** * Access an array of MaybeAccessors * @example * const list = [1, 2, () => 3)] // T: MaybeAccessor[] * const newList = accessArray(list) // T: number[] */ export const accessArray = >( list: readonly A[], ): MaybeAccessorValue[] => list.map(v => access(v)); /** * Run the function if the accessed value is not `undefined` nor `null` * @param value * @param fn */ export const withAccess = , V = MaybeAccessorValue>( value: A, fn: (value: NonNullable) => void, ): void => { const _value = access(value); // oxlint-disable-next-line @typescript-eslint/no-unnecessary-condition _value != null && fn(_value as NonNullable); }; /** * Wraps a plain value in a zero-argument accessor `() => value`. * If `v` is already a function it is returned unchanged. */ export const asAccessor = >( v: A, ): Accessor> => (typeof v === "function" ? (v as any) : () => v as any); /** If value is a function – call it with a given arguments – otherwise get the value as is */ export function accessWith( valueOrFn: T, ...args: T extends AnyFunction ? Parameters : never ): T extends AnyFunction ? ReturnType : T { return typeof valueOrFn === "function" ? valueOrFn(...args) : (valueOrFn as any); } /** * A deferred effect compute function. Skips the first reactive run and returns * `initialValue` instead, then calls `fn` on subsequent dependency changes. * Useful as the compute phase of `createEffect(defer(...), apply)` when the * initial run should be suppressed. * * @param deps - a single accessor or an array of accessors to track * @param fn - called with the current input, previous input, and previous return value * @param initialValue - returned on the skipped first run (defaults to `undefined`) */ export function defer( deps: AccessorArray | Accessor, fn: (input: S, prevInput: S, prev: undefined | NoInfer) => Next, initialValue: Next, ): ComputeFunction, NoInfer>; export function defer( deps: AccessorArray | Accessor, fn: (input: S, prevInput: S, prev: undefined | NoInfer) => Next, initialValue?: undefined, ): ComputeFunction>; export function defer( deps: AccessorArray | Accessor, fn: (input: S, prevInput: S, prev: undefined | NoInfer) => Next, initialValue?: Next, ): ComputeFunction> { const isArray = Array.isArray(deps); let prevInput: S; let shouldDefer = true; return ((prevValue: Prev | undefined) => { let input: S; if (isArray) { input = Array(deps.length) as S; for (let i = 0; i < deps.length; i++) (input as any[])[i] = deps[i](); } else input = deps(); if (shouldDefer) { shouldDefer = false; prevInput = input; return initialValue; } const result = untrack(() => fn(input, prevInput, prevValue)); prevInput = input; return result; }) as unknown as ComputeFunction | undefined>; } /** * Get entries of an object */ export const entries = Object.entries as (obj: T) => [keyof T, T[keyof T]][]; /** * Get keys of an object */ export const keys = Object.keys as (object: T) => (keyof T)[]; /** * Solid's `onCleanup` that doesn't warn in development if used outside of a component. */ export const tryOnCleanup: typeof onCleanup = isDev ? fn => (getOwner() ? onCleanup(fn) : fn) : onCleanup; /** * Creates a stack of callbacks that can be pushed to, executed all at once, or cleared. * All callbacks receive the same arguments when `execute` is called; the stack is * automatically cleared after execution. * * @example * ```ts * const stack = createCallbackStack(); * stack.push(s => console.log("a:", s)); * stack.push(s => console.log("b:", s)); * stack.execute("hello"); // logs "a: hello", "b: hello" — stack is now empty * ``` */ export const createCallbackStack = (): { push: (...callbacks: ((arg0: A0, arg1: A1, arg2: A2, arg3: A3) => void)[]) => void; execute: (arg0: A0, arg1: A1, arg2: A2, arg3: A3) => void; clear: VoidFunction; } => { let stack: Array<(arg0: A0, arg1: A1, arg2: A2, arg3: A3) => void> = []; const clear: VoidFunction = () => (stack = []); return { push: (...callbacks) => stack.push(...callbacks), execute(arg0, arg1, arg2, arg3) { stack.forEach(cb => cb(arg0, arg1, arg2, arg3)); clear(); }, clear, }; }; /** * Returns a debounced wrapper around `fn` that batches rapid synchronous calls * into a single invocation. Only the most-recently-passed arguments are forwarded. * The counter resets on cleanup so stale microtasks are silently discarded. * * @example * ```ts * const flush = createMicrotask((value: string) => console.log(value)); * flush("a"); * flush("b"); * flush("c"); // only "c" is logged (in the next microtask) * ``` */ export function createMicrotask(fn: (...a: A) => void): (...a: A) => void { let calls = 0; let args: A; onCleanup(() => (calls = 0)); return (...a: A) => { ((args = a), calls++); queueMicrotask(() => --calls === 0 && fn(...args)); }; } /** * `createSignal` on the client; a plain mutable box on the server. * * Solid 2 treats a setter that runs during a server render as an error in waiting * (`SERVER_WRITE`: the write lands as inert data today and throws in a later release) — server * render is pure, state enters through async sources. Primitives that hold *interactive* * state (a cursor, a toggle, a controlled value) have no async source, so on the server they * keep a plain value instead: reads and updater-form writes behave the same within a request, * and nothing touches the reactive graph. * * The signal is still *created* on the server — hydration ids are handed out per created * primitive, so a server branch that skipped it would misalign keys with the client * ("Hydration key miss"). It is simply never read or written there. * * @param value initial value * @param options signal options (the signal only matters on the client) * @returns a `[get, set]` tuple with `createSignal`'s shape * @see {@link createSignal} */ export function createServerSafeSignal( value: T, options?: SignalOptions, ): ReturnType> { const signal = createSignal(value as Exclude, options); if (!isServer) return signal; const get = () => value; const set = (next?: unknown) => (value = typeof next === "function" ? (next as (prev: T) => T)(value) : (next as T)); return [get, set] as unknown as ReturnType>; } /** * A hydratable version of the {@link createSignal}. It will use the serverValue on the server and the update function on the client. If initialized during hydration it will use serverValue as the initial value and update it once hydration is complete. * * @param serverValue initial value of the state on the server * @param update called once on the client or on hydration to initialize the value * @param options {@link SignalOptions} * @returns * ```ts * [state: Accessor, setState: Setter] * ``` * @see {@link createSignal} */ export function createHydratableSignal( serverValue: T, update: () => T, options?: SignalOptions, ): ReturnType> { if (isServer || sharedConfig.hydrating) { const [state, setState] = createSignal(serverValue as Exclude, options); onSettled(() => { setState(() => update()); }); return [state, setState]; } return createSignal(update() as Exclude, options); } /** @deprecated use {@link createHydratableSignal} instead */ export const createHydrateSignal: typeof createHydratableSignal = createHydratableSignal; /** * Diffs two arrays by reference and calls `handleAdded` / `handleRemoved` for * each item that appeared or disappeared. Items are compared with `===`. * * @param current - the new array * @param prev - the previous array snapshot * @param handleAdded - called once for each item present in `current` but not `prev` * @param handleRemoved - called once for each item present in `prev` but not `current` */ export function handleDiffArray( current: readonly T[], prev: readonly T[], handleAdded: (item: T) => void, handleRemoved: (item: T) => void, ): void { const currLength = current.length; const prevLength = prev.length; let i = 0; if (!prevLength) { for (; i < currLength; i++) handleAdded(current[i]!); return; } if (!currLength) { for (; i < prevLength; i++) handleRemoved(prev[i]!); return; } for (; i < prevLength; i++) { if (prev[i] !== current[i]) break; } let prevEl: T; let currEl: T; prev = prev.slice(i); current = current.slice(i); for (prevEl of prev) { if (!current.includes(prevEl)) handleRemoved(prevEl); } for (currEl of current) { if (!prev.includes(currEl)) handleAdded(currEl); } } /** * Schedules `fn` to run after the browser has painted by nesting two * requestAnimationFrame calls. No-op in non-browser environments. */ export const afterPaint = (fn: () => void): void => { if (typeof requestAnimationFrame === "function") { requestAnimationFrame(() => requestAnimationFrame(fn)); } }; /** * Parse a string as a single JSON value. * * ```ts * const { data } = createSSE<{ status: string }>(url, { transform: json }); * ``` */ export const json = (raw: string): T => JSON.parse(raw) as T; /** * Parse a string as newline-delimited JSON (NDJSON / JSON Lines). * * Each non-empty line is parsed as a separate JSON value and returned as an array. * * ```ts * const { data } = createSSE(url, { transform: ndjson }); * // data() === [{ id: 1, type: "tick" }, { id: 2, type: "tick" }] * ``` */ export const ndjson = (raw: string): T[] => raw .split("\n") .filter(line => line !== "") .map(line => JSON.parse(line) as T); /** * Split a string into individual lines, returning a `string[]`. Empty lines are filtered out. * * ```ts * const { data } = createSSE(url, { transform: lines }); * // data() === ["line one", "line two"] * ``` */ export const lines = (raw: string): string[] => raw.split("\n").filter(line => line !== ""); /** * Parse a string as a number using `Number()` semantics. * * Note: `""` → `0`, non-numeric strings → `NaN`. * * ```ts * const { data } = createSSE(url, { transform: number }); * // data() === 42 * ``` */ export const number = (raw: string): number => Number(raw); /** * Wrap any `(string) => T` transform in a `try/catch`. Returns `fallback` * (default `undefined`) instead of throwing on malformed input. * * ```ts * const { data } = createSSE(url, { transform: safe(json) }); * const { data } = createSSE(url, { transform: safe(number, 0) }); * ``` */ export function safe(transform: (raw: string) => T): (raw: string) => T | undefined; export function safe(transform: (raw: string) => T, fallback: T): (raw: string) => T; export function safe( transform: (raw: string) => T, fallback?: T, ): (raw: string) => T | undefined { return (raw: string): T | undefined => { try { return transform(raw); } catch { return fallback; } }; } /** * Compose two transforms into one: the output of `a` is passed as the input of `b`. * * ```ts * const { data } = createSSE(url, { * transform: pipe(ndjson, rows => rows.filter(r => r.type === "tick")), * }); * ``` */ export function pipe(a: (raw: string) => A, b: (a: A) => B): (raw: string) => B { return (raw: string): B => b(a(raw)); } /** * Check if a wrapper element contains a target element. * Portal-aware: follows SolidJS `_$host` links so elements rendered inside * a `` are correctly treated as children of the portal's anchor. */ export const contains = (wrapper: HTMLElement, target: HTMLElement): boolean => { if (wrapper.contains(target)) return true; let current: HTMLElement | null = target; while (current) { if (current === wrapper) return true; // @ts-expect-error: _$host is a SolidJS-internal property set on portal roots current = current._$host ?? current.parentElement; } return false; }; /** * Returns a singleton value keyed by `key`, shared across every copy of the calling module that * ends up loaded in the same JS realm (a `Symbol.for(key)` slot on `globalThis`, not a module-scope * binding). Use this instead of a plain module-scope `let`/`const` for state that must stay * consistent (ref-counts, active-instance stacks) even if the app's dependency graph ends up with * more than one installed copy of the package — module-scope state would otherwise be split across * copies and go out of sync (e.g. a "topmost instance" check disagreeing between copies). * * ```ts * const registry = globalRegistry("@solid-primitives/my-package:my-state", () => ({ * stack: createSignal([], { ownedWrite: true }), * nextId: 0, * })); * ``` */ export function globalRegistry(key: string, init: () => T): T { const g = globalThis as Record; return (g[Symbol.for(key)] ??= init()); } /** * Wraps a setter function of any signal or store * * ```ts * const [data, setData] = wrapSetter( * createSignal(initialData), * (setter) => (next) => { console.log(next); return setter(next); }, * ); * ``` * If you destructure signal or store in a longer tuple, you need to use a const assertion for the types to work. */ export function wrapSetter( signal: Signal, wrapper: (setter: Setter) => Setter, ): Signal; export function wrapSetter( store: [Store, StoreSetter], wrapper: (setter: StoreSetter) => StoreSetter, ): [Store, StoreSetter]; export function wrapSetter< T, S extends | Signal | [Store, StoreSetter] | [...Signal, ...any[]] | [Store, StoreSetter, ...any[]], >(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S; export function wrapSetter< T, S extends | Signal | [Store, StoreSetter] | readonly [...Signal, ...any[]] | readonly [Store, StoreSetter, ...any[]], >(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S; export function wrapSetter< T, S extends | Signal | [Store, StoreSetter] | [...Signal, ...any[]] | [Store, StoreSetter, ...any[]], >(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S { return [signalOrStore[0], wrapper(signalOrStore[1]), ...signalOrStore.slice(2)] as S; }