@solid-primitives/utils 7.0.0-next.4 → 7.0.0-next.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,289 +1,306 @@
1
1
  /* @ts-self-types="./index.d.ts" */
2
2
  import { AccessReturnTypes, AccessorArray, AnyClass, AnyFunction, AnyObject, AnyStatic, DeepPartialAny, Directive, ExtractIfPossible, Falsy, FalsyValue, ItemsOf, ItemsOfMany, Many, MaybeAccessor, MaybeAccessorValue, Modify, ModifyDeep, Narrow, NoInfer, NonIterable, Noop, OnAccessEffectFunction, Position, PrimitiveValue, RequiredKeys, SetterParam, Simplify, Size, Tail, Truthy, UnboxLazy, UnionToIntersection, Values } from "./types.js";
3
3
  import { Accessor, ComputeFunction, NoInfer as NoInfer$1, Setter, Signal, SignalOptions, Store, StoreSetter, createSignal, onCleanup } from "solid-js";
4
-
5
- //#region src/index.d.ts
6
4
  declare const isServer: boolean;
7
5
  /** `true` in the browser, `false` on the server. */
8
- declare const isClient: boolean;
6
+ export declare const isClient: boolean;
9
7
  /** `true` in the browser with Solid's DEV mode active. */
10
- declare const isDev: boolean;
8
+ export declare const isDev: boolean;
11
9
  /** `true` when DEV mode is off (i.e. production browser builds and all SSR). */
12
- declare const isProd: boolean;
10
+ export declare const isProd: boolean;
13
11
  /** No-operation function — accepts any arguments and returns `undefined`. */
14
- declare const noop: Noop;
12
+ export declare const noop: Noop;
15
13
  /** A function that always returns `true`. Useful as a default predicate prop. */
16
- declare const trueFn: () => boolean;
14
+ export declare const trueFn: () => boolean;
17
15
  /** A function that always returns `false`. Useful as a default predicate prop. */
18
- declare const falseFn: () => boolean;
16
+ export declare const falseFn: () => boolean;
19
17
  /** @deprecated use {@link equalFn} from "solid-js" */
20
- declare const defaultEquals: typeof Object.is;
18
+ export declare const defaultEquals: typeof Object.is;
21
19
  /**
22
- * Signal options that disable equality checking, causing the signal to always
23
- * notify subscribers even when the value hasn't changed. Useful for signals
24
- * holding mutable objects where structural equality cannot be assumed.
25
- */
26
- declare const EQUALS_FALSE_OPTIONS: {
20
+ * Signal options that disable equality checking, causing the signal to always
21
+ * notify subscribers even when the value hasn't changed. Useful for signals
22
+ * holding mutable objects where structural equality cannot be assumed.
23
+ */
24
+ export declare const EQUALS_FALSE_OPTIONS: {
27
25
  readonly equals: false;
28
26
  };
29
27
  /**
30
- * Signal options that allow writes from inside an owned reactive scope
31
- * (component body, memo, or effect) without throwing `SIGNAL_WRITE_IN_OWNED_SCOPE`
32
- * in Solid 2.0 dev mode.
33
- *
34
- * Use only for implementation-detail signals that genuinely need to be written
35
- * from within a scope — not as a general escape hatch.
36
- */
37
- declare const INTERNAL_OPTIONS: {
28
+ * Signal options that allow writes from inside an owned reactive scope
29
+ * (component body, memo, or effect) without throwing `SIGNAL_WRITE_IN_OWNED_SCOPE`
30
+ * in Solid 2.0 dev mode.
31
+ *
32
+ * Use only for implementation-detail signals that genuinely need to be written
33
+ * from within a scope — not as a general escape hatch.
34
+ */
35
+ export declare const INTERNAL_OPTIONS: {
38
36
  readonly ownedWrite: true;
39
37
  };
40
38
  /**
41
- * Returns `true` if `v` is an instance of `c`. Checks both `instanceof` and
42
- * `constructor` so that values created across different realms (e.g. iframes) match.
43
- */
44
- declare const ofClass: (v: any, c: AnyClass) => boolean;
39
+ * Returns `true` if `v` is an instance of `c`. Checks both `instanceof` and
40
+ * `constructor` so that values created across different realms (e.g. iframes) match.
41
+ */
42
+ export declare const ofClass: (v: any, c: AnyClass) => boolean;
45
43
  /** Check if value is typeof "object" or "function" */
46
- declare function isObject(value: any): value is AnyObject;
44
+ export declare function isObject(value: any): value is AnyObject;
47
45
  /** Type guard: returns `true` when `i` is neither `null` nor `undefined`. */
48
- declare const isNonNullable: <T>(i: T) => i is NonNullable<T>;
46
+ export declare const isNonNullable: <T>(i: T) => i is NonNullable<T>;
49
47
  /** Returns a new array with all `null` and `undefined` items removed. */
50
- declare const filterNonNullable: <T extends readonly unknown[]>(arr: T) => NonNullable<T[number]>[];
48
+ export declare const filterNonNullable: <T extends readonly unknown[]>(arr: T) => NonNullable<T[number]>[];
51
49
  /** Three-way comparison: returns `-1` if `a < b`, `1` if `a > b`, `0` if equal. */
52
- declare const compare: (a: any, b: any) => number;
50
+ export declare const compare: (a: any, b: any) => number;
53
51
  /**
54
- * Check shallow array equality
55
- */
56
- declare const arrayEquals: (a: readonly unknown[], b: readonly unknown[]) => boolean;
52
+ * Check shallow array equality
53
+ */
54
+ export declare const arrayEquals: (a: readonly unknown[], b: readonly unknown[]) => boolean;
57
55
  /**
58
- * Returns a function that will call all functions in the order they were chained with the same arguments.
59
- */
60
- declare function chain<Args extends [] | any[]>(callbacks: {
56
+ * Returns a function that will call all functions in the order they were chained with the same arguments.
57
+ */
58
+ export declare function chain<Args extends [] | any[]>(callbacks: {
61
59
  [Symbol.iterator](): IterableIterator<((...args: Args) => any) | undefined>;
62
60
  }): (...args: Args) => void;
63
61
  /**
64
- * Returns a function that will call all functions in the reversed order with the same arguments.
65
- */
66
- declare function reverseChain<Args extends [] | any[]>(callbacks: (((...args: Args) => any) | undefined)[]): (...args: Args) => void;
62
+ * Returns a function that will call all functions in the reversed order with the same arguments.
63
+ */
64
+ export declare function reverseChain<Args extends [] | any[]>(callbacks: (((...args: Args) => any) | undefined)[]): (...args: Args) => void;
67
65
  /** Clamps `n` to the inclusive range `[min, max]`. */
68
- declare const clamp: (n: number, min: number, max: number) => number;
66
+ export declare const clamp: (n: number, min: number, max: number) => number;
69
67
  /** 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). */
70
- declare const createIdGenerator: () => (() => string);
68
+ export declare const createIdGenerator: () => (() => string);
71
69
  /**
72
- * Accesses the value of a MaybeAccessor
73
- * @example
74
- * ```ts
75
- * access("foo") // => "foo"
76
- * access(() => "foo") // => "foo"
77
- * ```
78
- */
79
- declare const access: <T extends MaybeAccessor<any>>(v: T) => MaybeAccessorValue<T>;
70
+ * Accesses the value of a MaybeAccessor
71
+ * @example
72
+ * ```ts
73
+ * access("foo") // => "foo"
74
+ * access(() => "foo") // => "foo"
75
+ * ```
76
+ */
77
+ export declare const access: <T extends MaybeAccessor<any>>(v: T) => MaybeAccessorValue<T>;
80
78
  /**
81
- * Wraps `value` in a single-element array. If `value` is already an array it is
82
- * returned as-is. Falsy values (except `0` and `false`) produce an empty array.
83
- */
84
- declare const asArray: <T>(value: T) => (T extends any[] ? T[number] : NonNullable<T>)[];
79
+ * Wraps `value` in a single-element array. If `value` is already an array it is
80
+ * returned as-is. Falsy values (except `0` and `false`) produce an empty array.
81
+ */
82
+ export declare const asArray: <T>(value: T) => (T extends any[] ? T[number] : NonNullable<T>)[];
85
83
  /**
86
- * Access an array of MaybeAccessors
87
- * @example
88
- * const list = [1, 2, () => 3)] // T: MaybeAccessor<number>[]
89
- * const newList = accessArray(list) // T: number[]
90
- */
91
- declare const accessArray: <A extends MaybeAccessor<any>>(list: readonly A[]) => MaybeAccessorValue<A>[];
84
+ * Access an array of MaybeAccessors
85
+ * @example
86
+ * const list = [1, 2, () => 3)] // T: MaybeAccessor<number>[]
87
+ * const newList = accessArray(list) // T: number[]
88
+ */
89
+ export declare const accessArray: <A extends MaybeAccessor<any>>(list: readonly A[]) => MaybeAccessorValue<A>[];
92
90
  /**
93
- * Run the function if the accessed value is not `undefined` nor `null`
94
- * @param value
95
- * @param fn
96
- */
97
- declare const withAccess: <T, A extends MaybeAccessor<T>, V = MaybeAccessorValue<A>>(value: A, fn: (value: NonNullable<V>) => void) => void;
91
+ * Run the function if the accessed value is not `undefined` nor `null`
92
+ * @param value
93
+ * @param fn
94
+ */
95
+ export declare const withAccess: <T, A extends MaybeAccessor<T>, V = MaybeAccessorValue<A>>(value: A, fn: (value: NonNullable<V>) => void) => void;
98
96
  /**
99
- * Wraps a plain value in a zero-argument accessor `() => value`.
100
- * If `v` is already a function it is returned unchanged.
101
- */
102
- declare const asAccessor: <A extends MaybeAccessor<unknown>>(v: A) => Accessor<MaybeAccessorValue<A>>;
97
+ * Wraps a plain value in a zero-argument accessor `() => value`.
98
+ * If `v` is already a function it is returned unchanged.
99
+ */
100
+ export declare const asAccessor: <A extends MaybeAccessor<unknown>>(v: A) => Accessor<MaybeAccessorValue<A>>;
103
101
  /** If value is a function – call it with a given arguments – otherwise get the value as is */
104
- declare function accessWith<T>(valueOrFn: T, ...args: T extends AnyFunction ? Parameters<T> : never): T extends AnyFunction ? ReturnType<T> : T;
102
+ export declare function accessWith<T>(valueOrFn: T, ...args: T extends AnyFunction ? Parameters<T> : never): T extends AnyFunction ? ReturnType<T> : T;
105
103
  /**
106
- * A deferred effect compute function. Skips the first reactive run and returns
107
- * `initialValue` instead, then calls `fn` on subsequent dependency changes.
108
- * Useful as the compute phase of `createEffect(defer(...), apply)` when the
109
- * initial run should be suppressed.
110
- *
111
- * @param deps - a single accessor or an array of accessors to track
112
- * @param fn - called with the current input, previous input, and previous return value
113
- * @param initialValue - returned on the skipped first run (defaults to `undefined`)
114
- */
115
- declare function defer<S, Next extends Prev, Prev = Next>(deps: AccessorArray<S> | Accessor<S>, fn: (input: S, prevInput: S, prev: undefined | NoInfer$1<Prev>) => Next, initialValue: Next): ComputeFunction<undefined | NoInfer$1<Next>, NoInfer$1<Next>>;
116
- declare function defer<S, Next extends Prev, Prev = Next>(deps: AccessorArray<S> | Accessor<S>, fn: (input: S, prevInput: S, prev: undefined | NoInfer$1<Prev>) => Next, initialValue?: undefined): ComputeFunction<undefined | NoInfer$1<Next>>;
104
+ * A deferred effect compute function. Skips the first reactive run and returns
105
+ * `initialValue` instead, then calls `fn` on subsequent dependency changes.
106
+ * Useful as the compute phase of `createEffect(defer(...), apply)` when the
107
+ * initial run should be suppressed.
108
+ *
109
+ * @param deps - a single accessor or an array of accessors to track
110
+ * @param fn - called with the current input, previous input, and previous return value
111
+ * @param initialValue - returned on the skipped first run (defaults to `undefined`)
112
+ */
113
+ export declare function defer<S, Next extends Prev, Prev = Next>(deps: AccessorArray<S> | Accessor<S>, fn: (input: S, prevInput: S, prev: undefined | NoInfer$1<Prev>) => Next, initialValue: Next): ComputeFunction<undefined | NoInfer$1<Next>, NoInfer$1<Next>>;
114
+ export declare function defer<S, Next extends Prev, Prev = Next>(deps: AccessorArray<S> | Accessor<S>, fn: (input: S, prevInput: S, prev: undefined | NoInfer$1<Prev>) => Next, initialValue?: undefined): ComputeFunction<undefined | NoInfer$1<Next>>;
117
115
  /**
118
- * Get entries of an object
119
- */
120
- declare const entries: <T extends object>(obj: T) => [keyof T, T[keyof T]][];
116
+ * Get entries of an object
117
+ */
118
+ export declare const entries: <T extends object>(obj: T) => [keyof T, T[keyof T]][];
121
119
  /**
122
- * Get keys of an object
123
- */
124
- declare const keys: <T extends object>(object: T) => (keyof T)[];
120
+ * Get keys of an object
121
+ */
122
+ export declare const keys: <T extends object>(object: T) => (keyof T)[];
125
123
  /**
126
- * Solid's `onCleanup` that doesn't warn in development if used outside of a component.
127
- */
128
- declare const tryOnCleanup: typeof onCleanup;
124
+ * Solid's `onCleanup` that doesn't warn in development if used outside of a component.
125
+ */
126
+ export declare const tryOnCleanup: typeof onCleanup;
129
127
  /**
130
- * Creates a stack of callbacks that can be pushed to, executed all at once, or cleared.
131
- * All callbacks receive the same arguments when `execute` is called; the stack is
132
- * automatically cleared after execution.
133
- *
134
- * @example
135
- * ```ts
136
- * const stack = createCallbackStack<string>();
137
- * stack.push(s => console.log("a:", s));
138
- * stack.push(s => console.log("b:", s));
139
- * stack.execute("hello"); // logs "a: hello", "b: hello" — stack is now empty
140
- * ```
141
- */
142
- declare const createCallbackStack: <A0 = void, A1 = void, A2 = void, A3 = void>() => {
128
+ * Creates a stack of callbacks that can be pushed to, executed all at once, or cleared.
129
+ * All callbacks receive the same arguments when `execute` is called; the stack is
130
+ * automatically cleared after execution.
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * const stack = createCallbackStack<string>();
135
+ * stack.push(s => console.log("a:", s));
136
+ * stack.push(s => console.log("b:", s));
137
+ * stack.execute("hello"); // logs "a: hello", "b: hello" — stack is now empty
138
+ * ```
139
+ */
140
+ export declare const createCallbackStack: <A0 = void, A1 = void, A2 = void, A3 = void>() => {
143
141
  push: (...callbacks: ((arg0: A0, arg1: A1, arg2: A2, arg3: A3) => void)[]) => void;
144
142
  execute: (arg0: A0, arg1: A1, arg2: A2, arg3: A3) => void;
145
143
  clear: VoidFunction;
146
144
  };
147
145
  /**
148
- * Returns a debounced wrapper around `fn` that batches rapid synchronous calls
149
- * into a single invocation. Only the most-recently-passed arguments are forwarded.
150
- * The counter resets on cleanup so stale microtasks are silently discarded.
151
- *
152
- * @example
153
- * ```ts
154
- * const flush = createMicrotask((value: string) => console.log(value));
155
- * flush("a");
156
- * flush("b");
157
- * flush("c"); // only "c" is logged (in the next microtask)
158
- * ```
159
- */
160
- declare function createMicrotask<A extends any[] | []>(fn: (...a: A) => void): (...a: A) => void;
146
+ * Returns a debounced wrapper around `fn` that batches rapid synchronous calls
147
+ * into a single invocation. Only the most-recently-passed arguments are forwarded.
148
+ * The counter resets on cleanup so stale microtasks are silently discarded.
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * const flush = createMicrotask((value: string) => console.log(value));
153
+ * flush("a");
154
+ * flush("b");
155
+ * flush("c"); // only "c" is logged (in the next microtask)
156
+ * ```
157
+ */
158
+ export declare function createMicrotask<A extends any[] | []>(fn: (...a: A) => void): (...a: A) => void;
161
159
  /**
162
- * 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.
163
- *
164
- * @param serverValue initial value of the state on the server
165
- * @param update called once on the client or on hydration to initialize the value
166
- * @param options {@link SignalOptions}
167
- * @returns
168
- * ```ts
169
- * [state: Accessor<T>, setState: Setter<T>]
170
- * ```
171
- * @see {@link createSignal}
172
- */
173
- declare function createHydratableSignal<T>(serverValue: T, update: () => T, options?: SignalOptions<T>): ReturnType<typeof createSignal<T>>;
160
+ * `createSignal` on the client; a plain mutable box on the server.
161
+ *
162
+ * Solid 2 treats a setter that runs during a server render as an error in waiting
163
+ * (`SERVER_WRITE`: the write lands as inert data today and throws in a later release) — server
164
+ * render is pure, state enters through async sources. Primitives that hold *interactive*
165
+ * state (a cursor, a toggle, a controlled value) have no async source, so on the server they
166
+ * keep a plain value instead: reads and updater-form writes behave the same within a request,
167
+ * and nothing touches the reactive graph.
168
+ *
169
+ * The signal is still *created* on the server — hydration ids are handed out per created
170
+ * primitive, so a server branch that skipped it would misalign keys with the client
171
+ * ("Hydration key miss"). It is simply never read or written there.
172
+ *
173
+ * @param value initial value
174
+ * @param options signal options (the signal only matters on the client)
175
+ * @returns a `[get, set]` tuple with `createSignal`'s shape
176
+ * @see {@link createSignal}
177
+ */
178
+ export declare function createServerSafeSignal<T>(value: T, options?: SignalOptions<T>): ReturnType<typeof createSignal<T>>;
179
+ /**
180
+ * 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.
181
+ *
182
+ * @param serverValue initial value of the state on the server
183
+ * @param update called once on the client or on hydration to initialize the value
184
+ * @param options {@link SignalOptions}
185
+ * @returns
186
+ * ```ts
187
+ * [state: Accessor<T>, setState: Setter<T>]
188
+ * ```
189
+ * @see {@link createSignal}
190
+ */
191
+ export declare function createHydratableSignal<T>(serverValue: T, update: () => T, options?: SignalOptions<T>): ReturnType<typeof createSignal<T>>;
174
192
  /** @deprecated use {@link createHydratableSignal} instead */
175
- declare const createHydrateSignal: typeof createHydratableSignal;
193
+ export declare const createHydrateSignal: typeof createHydratableSignal;
176
194
  /**
177
- * Diffs two arrays by reference and calls `handleAdded` / `handleRemoved` for
178
- * each item that appeared or disappeared. Items are compared with `===`.
179
- *
180
- * @param current - the new array
181
- * @param prev - the previous array snapshot
182
- * @param handleAdded - called once for each item present in `current` but not `prev`
183
- * @param handleRemoved - called once for each item present in `prev` but not `current`
184
- */
185
- declare function handleDiffArray<T>(current: readonly T[], prev: readonly T[], handleAdded: (item: T) => void, handleRemoved: (item: T) => void): void;
195
+ * Diffs two arrays by reference and calls `handleAdded` / `handleRemoved` for
196
+ * each item that appeared or disappeared. Items are compared with `===`.
197
+ *
198
+ * @param current - the new array
199
+ * @param prev - the previous array snapshot
200
+ * @param handleAdded - called once for each item present in `current` but not `prev`
201
+ * @param handleRemoved - called once for each item present in `prev` but not `current`
202
+ */
203
+ export declare function handleDiffArray<T>(current: readonly T[], prev: readonly T[], handleAdded: (item: T) => void, handleRemoved: (item: T) => void): void;
186
204
  /**
187
- * Schedules `fn` to run after the browser has painted by nesting two
188
- * requestAnimationFrame calls. No-op in non-browser environments.
189
- */
190
- declare const afterPaint: (fn: () => void) => void;
205
+ * Schedules `fn` to run after the browser has painted by nesting two
206
+ * requestAnimationFrame calls. No-op in non-browser environments.
207
+ */
208
+ export declare const afterPaint: (fn: () => void) => void;
191
209
  /**
192
- * Parse a string as a single JSON value.
193
- *
194
- * ```ts
195
- * const { data } = createSSE<{ status: string }>(url, { transform: json });
196
- * ```
197
- */
198
- declare const json: <T>(raw: string) => T;
210
+ * Parse a string as a single JSON value.
211
+ *
212
+ * ```ts
213
+ * const { data } = createSSE<{ status: string }>(url, { transform: json });
214
+ * ```
215
+ */
216
+ export declare const json: <T>(raw: string) => T;
199
217
  /**
200
- * Parse a string as newline-delimited JSON (NDJSON / JSON Lines).
201
- *
202
- * Each non-empty line is parsed as a separate JSON value and returned as an array.
203
- *
204
- * ```ts
205
- * const { data } = createSSE<TickEvent[]>(url, { transform: ndjson });
206
- * // data() === [{ id: 1, type: "tick" }, { id: 2, type: "tick" }]
207
- * ```
208
- */
209
- declare const ndjson: <T>(raw: string) => T[];
218
+ * Parse a string as newline-delimited JSON (NDJSON / JSON Lines).
219
+ *
220
+ * Each non-empty line is parsed as a separate JSON value and returned as an array.
221
+ *
222
+ * ```ts
223
+ * const { data } = createSSE<TickEvent[]>(url, { transform: ndjson });
224
+ * // data() === [{ id: 1, type: "tick" }, { id: 2, type: "tick" }]
225
+ * ```
226
+ */
227
+ export declare const ndjson: <T>(raw: string) => T[];
210
228
  /**
211
- * Split a string into individual lines, returning a `string[]`. Empty lines are filtered out.
212
- *
213
- * ```ts
214
- * const { data } = createSSE<string[]>(url, { transform: lines });
215
- * // data() === ["line one", "line two"]
216
- * ```
217
- */
218
- declare const lines: (raw: string) => string[];
229
+ * Split a string into individual lines, returning a `string[]`. Empty lines are filtered out.
230
+ *
231
+ * ```ts
232
+ * const { data } = createSSE<string[]>(url, { transform: lines });
233
+ * // data() === ["line one", "line two"]
234
+ * ```
235
+ */
236
+ export declare const lines: (raw: string) => string[];
219
237
  /**
220
- * Parse a string as a number using `Number()` semantics.
221
- *
222
- * Note: `""` → `0`, non-numeric strings → `NaN`.
223
- *
224
- * ```ts
225
- * const { data } = createSSE<number>(url, { transform: number });
226
- * // data() === 42
227
- * ```
228
- */
229
- declare const number: (raw: string) => number;
238
+ * Parse a string as a number using `Number()` semantics.
239
+ *
240
+ * Note: `""` → `0`, non-numeric strings → `NaN`.
241
+ *
242
+ * ```ts
243
+ * const { data } = createSSE<number>(url, { transform: number });
244
+ * // data() === 42
245
+ * ```
246
+ */
247
+ export declare const number: (raw: string) => number;
230
248
  /**
231
- * Wrap any `(string) => T` transform in a `try/catch`. Returns `fallback`
232
- * (default `undefined`) instead of throwing on malformed input.
233
- *
234
- * ```ts
235
- * const { data } = createSSE<MyEvent>(url, { transform: safe(json) });
236
- * const { data } = createSSE<number>(url, { transform: safe(number, 0) });
237
- * ```
238
- */
239
- declare function safe<T>(transform: (raw: string) => T): (raw: string) => T | undefined;
240
- declare function safe<T>(transform: (raw: string) => T, fallback: T): (raw: string) => T;
249
+ * Wrap any `(string) => T` transform in a `try/catch`. Returns `fallback`
250
+ * (default `undefined`) instead of throwing on malformed input.
251
+ *
252
+ * ```ts
253
+ * const { data } = createSSE<MyEvent>(url, { transform: safe(json) });
254
+ * const { data } = createSSE<number>(url, { transform: safe(number, 0) });
255
+ * ```
256
+ */
257
+ export declare function safe<T>(transform: (raw: string) => T): (raw: string) => T | undefined;
258
+ export declare function safe<T>(transform: (raw: string) => T, fallback: T): (raw: string) => T;
241
259
  /**
242
- * Compose two transforms into one: the output of `a` is passed as the input of `b`.
243
- *
244
- * ```ts
245
- * const { data } = createSSE<RawEvent[]>(url, {
246
- * transform: pipe(ndjson<RawEvent>, rows => rows.filter(r => r.type === "tick")),
247
- * });
248
- * ```
249
- */
250
- declare function pipe<A, B>(a: (raw: string) => A, b: (a: A) => B): (raw: string) => B;
260
+ * Compose two transforms into one: the output of `a` is passed as the input of `b`.
261
+ *
262
+ * ```ts
263
+ * const { data } = createSSE<RawEvent[]>(url, {
264
+ * transform: pipe(ndjson<RawEvent>, rows => rows.filter(r => r.type === "tick")),
265
+ * });
266
+ * ```
267
+ */
268
+ export declare function pipe<A, B>(a: (raw: string) => A, b: (a: A) => B): (raw: string) => B;
251
269
  /**
252
- * Check if a wrapper element contains a target element.
253
- * Portal-aware: follows SolidJS `_$host` links so elements rendered inside
254
- * a `<Portal>` are correctly treated as children of the portal's anchor.
255
- */
256
- declare const contains: (wrapper: HTMLElement, target: HTMLElement) => boolean;
270
+ * Check if a wrapper element contains a target element.
271
+ * Portal-aware: follows SolidJS `_$host` links so elements rendered inside
272
+ * a `<Portal>` are correctly treated as children of the portal's anchor.
273
+ */
274
+ export declare const contains: (wrapper: HTMLElement, target: HTMLElement) => boolean;
257
275
  /**
258
- * Returns a singleton value keyed by `key`, shared across every copy of the calling module that
259
- * ends up loaded in the same JS realm (a `Symbol.for(key)` slot on `globalThis`, not a module-scope
260
- * binding). Use this instead of a plain module-scope `let`/`const` for state that must stay
261
- * consistent (ref-counts, active-instance stacks) even if the app's dependency graph ends up with
262
- * more than one installed copy of the package — module-scope state would otherwise be split across
263
- * copies and go out of sync (e.g. a "topmost instance" check disagreeing between copies).
264
- *
265
- * ```ts
266
- * const registry = globalRegistry("@solid-primitives/my-package:my-state", () => ({
267
- * stack: createSignal<string[]>([], { ownedWrite: true }),
268
- * nextId: 0,
269
- * }));
270
- * ```
271
- */
272
- declare function globalRegistry<T>(key: string, init: () => T): T;
276
+ * Returns a singleton value keyed by `key`, shared across every copy of the calling module that
277
+ * ends up loaded in the same JS realm (a `Symbol.for(key)` slot on `globalThis`, not a module-scope
278
+ * binding). Use this instead of a plain module-scope `let`/`const` for state that must stay
279
+ * consistent (ref-counts, active-instance stacks) even if the app's dependency graph ends up with
280
+ * more than one installed copy of the package — module-scope state would otherwise be split across
281
+ * copies and go out of sync (e.g. a "topmost instance" check disagreeing between copies).
282
+ *
283
+ * ```ts
284
+ * const registry = globalRegistry("@solid-primitives/my-package:my-state", () => ({
285
+ * stack: createSignal<string[]>([], { ownedWrite: true }),
286
+ * nextId: 0,
287
+ * }));
288
+ * ```
289
+ */
290
+ export declare function globalRegistry<T>(key: string, init: () => T): T;
273
291
  /**
274
- * Wraps a setter function of any signal or store
275
- *
276
- * ```ts
277
- * const [data, setData] = wrapSetter(
278
- * createSignal(initialData),
279
- * (setter) => (next) => { console.log(next); return setter(next); },
280
- * );
281
- * ```
282
- * If you destructure signal or store in a longer tuple, you need to use a const assertion for the types to work.
283
- */
284
- declare function wrapSetter<T>(signal: Signal<T>, wrapper: (setter: Setter<T>) => Setter<T>): Signal<T>;
285
- declare function wrapSetter<T>(store: [Store<T>, StoreSetter<T>], wrapper: (setter: StoreSetter<T>) => StoreSetter<T>): [Store<T>, StoreSetter<T>];
286
- declare function wrapSetter<T, S extends Signal<T> | [Store<T>, StoreSetter<T>] | [...Signal<T>, ...any[]] | [Store<T>, StoreSetter<T>, ...any[]]>(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S;
287
- declare function wrapSetter<T, S extends Signal<T> | [Store<T>, StoreSetter<T>] | readonly [...Signal<T>, ...any[]] | readonly [Store<T>, StoreSetter<T>, ...any[]]>(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S;
288
- //#endregion
289
- export { AccessReturnTypes, AccessorArray, AnyClass, AnyFunction, AnyObject, AnyStatic, DeepPartialAny, Directive, EQUALS_FALSE_OPTIONS, ExtractIfPossible, Falsy, FalsyValue, INTERNAL_OPTIONS, ItemsOf, ItemsOfMany, Many, MaybeAccessor, MaybeAccessorValue, Modify, ModifyDeep, Narrow, NoInfer, NonIterable, Noop, OnAccessEffectFunction, Position, PrimitiveValue, RequiredKeys, SetterParam, Simplify, Size, Tail, Truthy, UnboxLazy, UnionToIntersection, Values, access, accessArray, accessWith, afterPaint, arrayEquals, asAccessor, asArray, chain, clamp, compare, contains, createCallbackStack, createHydratableSignal, createHydrateSignal, createIdGenerator, createMicrotask, defaultEquals, defer, entries, falseFn, filterNonNullable, globalRegistry, handleDiffArray, isClient, isDev, isNonNullable, isObject, isProd, isServer, json, keys, lines, ndjson, noop, number, ofClass, pipe, reverseChain, safe, trueFn, tryOnCleanup, withAccess, wrapSetter };
292
+ * Wraps a setter function of any signal or store
293
+ *
294
+ * ```ts
295
+ * const [data, setData] = wrapSetter(
296
+ * createSignal(initialData),
297
+ * (setter) => (next) => { console.log(next); return setter(next); },
298
+ * );
299
+ * ```
300
+ * If you destructure signal or store in a longer tuple, you need to use a const assertion for the types to work.
301
+ */
302
+ export declare function wrapSetter<T>(signal: Signal<T>, wrapper: (setter: Setter<T>) => Setter<T>): Signal<T>;
303
+ export declare function wrapSetter<T>(store: [Store<T>, StoreSetter<T>], wrapper: (setter: StoreSetter<T>) => StoreSetter<T>): [Store<T>, StoreSetter<T>];
304
+ export declare function wrapSetter<T, S extends Signal<T> | [Store<T>, StoreSetter<T>] | [...Signal<T>, ...any[]] | [Store<T>, StoreSetter<T>, ...any[]]>(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S;
305
+ export declare function wrapSetter<T, S extends Signal<T> | [Store<T>, StoreSetter<T>] | readonly [...Signal<T>, ...any[]] | readonly [Store<T>, StoreSetter<T>, ...any[]]>(signalOrStore: S, wrapper: (setter: S[1]) => S[1]): S;
306
+ export { AccessReturnTypes, AccessorArray, AnyClass, AnyFunction, AnyObject, AnyStatic, DeepPartialAny, Directive, ExtractIfPossible, Falsy, FalsyValue, ItemsOf, ItemsOfMany, Many, MaybeAccessor, MaybeAccessorValue, Modify, ModifyDeep, Narrow, NoInfer, NonIterable, Noop, OnAccessEffectFunction, Position, PrimitiveValue, RequiredKeys, SetterParam, Simplify, Size, Tail, Truthy, UnboxLazy, UnionToIntersection, Values, isServer };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /* @ts-self-types="./index.d.ts" */
2
2
  import { DEV, createSignal, getOwner, onCleanup, onSettled, sharedConfig, untrack } from "solid-js";
3
- //#region src/index.ts
3
+ // src/index.ts
4
4
  const isServer = typeof window === "undefined";
5
5
  /** `true` in the browser, `false` on the server. */
6
6
  const isClient = !isServer;
@@ -104,7 +104,8 @@ const accessArray = (list) => list.map((v) => access(v));
104
104
  * @param fn
105
105
  */
106
106
  const withAccess = (value, fn) => {
107
- fn(access(value));
107
+ const _value = access(value);
108
+ _value != null && fn(_value);
108
109
  };
109
110
  /**
110
111
  * Wraps a plain value in a zero-argument accessor `() => value`.
@@ -195,6 +196,32 @@ function createMicrotask(fn) {
195
196
  };
196
197
  }
197
198
  /**
199
+ * `createSignal` on the client; a plain mutable box on the server.
200
+ *
201
+ * Solid 2 treats a setter that runs during a server render as an error in waiting
202
+ * (`SERVER_WRITE`: the write lands as inert data today and throws in a later release) — server
203
+ * render is pure, state enters through async sources. Primitives that hold *interactive*
204
+ * state (a cursor, a toggle, a controlled value) have no async source, so on the server they
205
+ * keep a plain value instead: reads and updater-form writes behave the same within a request,
206
+ * and nothing touches the reactive graph.
207
+ *
208
+ * The signal is still *created* on the server — hydration ids are handed out per created
209
+ * primitive, so a server branch that skipped it would misalign keys with the client
210
+ * ("Hydration key miss"). It is simply never read or written there.
211
+ *
212
+ * @param value initial value
213
+ * @param options signal options (the signal only matters on the client)
214
+ * @returns a `[get, set]` tuple with `createSignal`'s shape
215
+ * @see {@link createSignal}
216
+ */
217
+ function createServerSafeSignal(value, options) {
218
+ const signal = createSignal(value, options);
219
+ if (!isServer) return signal;
220
+ const get = () => value;
221
+ const set = (next) => value = typeof next === "function" ? next(value) : next;
222
+ return [get, set];
223
+ }
224
+ /**
198
225
  * 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.
199
226
  *
200
227
  * @param serverValue initial value of the state on the server
@@ -207,8 +234,7 @@ function createMicrotask(fn) {
207
234
  * @see {@link createSignal}
208
235
  */
209
236
  function createHydratableSignal(serverValue, update, options) {
210
- if (isServer) return createSignal(serverValue, options);
211
- if (sharedConfig.hydrating) {
237
+ if (isServer || sharedConfig.hydrating) {
212
238
  const [state, setState] = createSignal(serverValue, options);
213
239
  onSettled(() => {
214
240
  setState(() => update());
@@ -355,5 +381,4 @@ function wrapSetter(signalOrStore, wrapper) {
355
381
  ...signalOrStore.slice(2)
356
382
  ];
357
383
  }
358
- //#endregion
359
- export { EQUALS_FALSE_OPTIONS, INTERNAL_OPTIONS, access, accessArray, accessWith, afterPaint, arrayEquals, asAccessor, asArray, chain, clamp, compare, contains, createCallbackStack, createHydratableSignal, createHydrateSignal, createIdGenerator, createMicrotask, defaultEquals, defer, entries, falseFn, filterNonNullable, globalRegistry, handleDiffArray, isClient, isDev, isNonNullable, isObject, isProd, isServer, json, keys, lines, ndjson, noop, number, ofClass, pipe, reverseChain, safe, trueFn, tryOnCleanup, withAccess, wrapSetter };
384
+ export { EQUALS_FALSE_OPTIONS, INTERNAL_OPTIONS, access, accessArray, accessWith, afterPaint, arrayEquals, asAccessor, asArray, chain, clamp, compare, contains, createCallbackStack, createHydratableSignal, createHydrateSignal, createIdGenerator, createMicrotask, createServerSafeSignal, defaultEquals, defer, entries, falseFn, filterNonNullable, globalRegistry, handleDiffArray, isClient, isDev, isNonNullable, isObject, isProd, isServer, json, keys, lines, ndjson, noop, number, ofClass, pipe, reverseChain, safe, trueFn, tryOnCleanup, withAccess, wrapSetter };