gjendje 0.1.0

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.
@@ -0,0 +1,316 @@
1
+ type Scope = 'render' | 'tab' | 'local' | 'url' | 'server' | 'bucket';
2
+ interface Adapter<T> {
3
+ get(): T;
4
+ set(value: T): void;
5
+ subscribe(listener: Listener<T>): Unsubscribe;
6
+ /** Resolves when the adapter is ready to read/write. Sync adapters resolve immediately. */
7
+ ready: Promise<void>;
8
+ destroy?(): void;
9
+ }
10
+ interface ReadonlyInstance<T> {
11
+ /** Current value */
12
+ get(): T;
13
+ /** Read the current value without any reactive implications */
14
+ peek(): T;
15
+ /** Subscribe to all changes. Returns an unsubscribe function. */
16
+ subscribe(listener: Listener<T>): Unsubscribe;
17
+ /** Which scope this instance uses */
18
+ readonly scope: Scope;
19
+ /** The key this instance was created with */
20
+ readonly key: string;
21
+ /** Whether this instance has been destroyed */
22
+ readonly isDestroyed: boolean;
23
+ /**
24
+ * Resolves when the adapter is fully initialized.
25
+ * Resolves immediately for synchronous scopes.
26
+ */
27
+ readonly ready: Promise<void>;
28
+ /**
29
+ * Resolves when the most recent write has been persisted to storage.
30
+ * For synchronous scopes this resolves immediately.
31
+ * For async scopes (e.g. bucket) this resolves once the adapter is ready
32
+ * and the write has landed.
33
+ */
34
+ readonly settled: Promise<void>;
35
+ /**
36
+ * Resolves when SSR hydration is complete and the real stored value
37
+ * has been read. Resolves immediately when not in SSR mode.
38
+ */
39
+ readonly hydrated: Promise<void>;
40
+ /**
41
+ * Resolves when destroy() has been called and teardown is complete.
42
+ */
43
+ readonly destroyed: Promise<void>;
44
+ /** Tear down listeners and storage resources */
45
+ destroy(): void;
46
+ }
47
+ interface BaseInstance<T> extends ReadonlyInstance<T> {
48
+ /** Update value — accepts a value or an updater function */
49
+ set(value: T | ((prev: T) => T)): void;
50
+ /** Reset to default value */
51
+ reset(): void;
52
+ /**
53
+ * Register an interceptor that runs before each set/reset.
54
+ * The interceptor receives `(next, prev)` and returns the value to actually store.
55
+ * Return `prev` to reject the update. Multiple interceptors run in registration order.
56
+ */
57
+ intercept(fn: (next: T, prev: T) => T): Unsubscribe;
58
+ /**
59
+ * Register a post-set tap that fires after each set/reset.
60
+ * Receives `(next, prev)`. Return value is ignored.
61
+ * Multiple hooks run in registration order.
62
+ */
63
+ use(fn: (next: T, prev: T) => void): Unsubscribe;
64
+ }
65
+ type Enhancer<TIn, TOut extends TIn> = (instance: TIn) => TOut;
66
+ interface StateInstance<T> extends BaseInstance<T> {
67
+ /**
68
+ * Watch a specific key within an object value.
69
+ * Listener only fires when that key's value changes.
70
+ */
71
+ watch<K extends T extends object ? keyof T : never>(key: K, listener: (value: T[K & keyof T]) => void): Unsubscribe;
72
+ }
73
+ interface BucketOptions {
74
+ /**
75
+ * Name of the storage bucket. Each name is isolated — keys in one
76
+ * bucket never conflict with keys in another.
77
+ */
78
+ name: string;
79
+ /**
80
+ * Whether the bucket should persist under storage pressure.
81
+ * Defaults to false.
82
+ */
83
+ persisted?: boolean;
84
+ /**
85
+ * Expiry duration or Unix timestamp in ms.
86
+ * Examples: '7d', '24h', '30m', or a timestamp.
87
+ */
88
+ expires?: string | number;
89
+ /**
90
+ * Maximum storage quota for this bucket.
91
+ * Examples: '10mb', '50mb', or a byte count.
92
+ */
93
+ quota?: string | number;
94
+ /**
95
+ * Scope to use if the Storage Buckets API is not available.
96
+ * Defaults to 'local'.
97
+ */
98
+ fallback?: 'local' | 'tab';
99
+ }
100
+ interface StateOptions<T> {
101
+ /** Initial / default value */
102
+ default: T;
103
+ /** Where state should live. Defaults to 'render'. */
104
+ scope?: Scope;
105
+ /**
106
+ * Storage bucket options. Required when scope is 'bucket'.
107
+ * Ignored for all other scopes.
108
+ */
109
+ bucket?: BucketOptions;
110
+ /**
111
+ * Custom serializer. Defaults to JSON.stringify / JSON.parse.
112
+ * Only used by adapters that persist to string-based storage.
113
+ */
114
+ serialize?: Serializer<T>;
115
+ /**
116
+ * Enable SSR safety. When true:
117
+ * - On server: silently falls back to 'render' scope
118
+ * - On client before hydration: uses default value to match server output
119
+ * - On client after hydration: reads real storage and emits update if different
120
+ */
121
+ ssr?: boolean;
122
+ /**
123
+ * Schema version for migrations. Defaults to 1.
124
+ */
125
+ version?: number;
126
+ /**
127
+ * Validate a value read from storage. Falls back to default on failure.
128
+ * Runs after migration.
129
+ */
130
+ validate?: (value: unknown) => value is T;
131
+ /**
132
+ * Migration functions keyed by the version they migrate FROM.
133
+ *
134
+ * Example: { 1: (old) => ({ ...old, newField: 'default' }) }
135
+ */
136
+ migrate?: Record<number, (old: unknown) => unknown>;
137
+ /**
138
+ * Override the global prefix for this instance.
139
+ * - `string`: use this prefix instead of the global one
140
+ * - `false`: disable prefixing entirely for this instance
141
+ */
142
+ prefix?: string | false;
143
+ /**
144
+ * Broadcast changes to other tabs via BroadcastChannel.
145
+ * When true, any set() call is also sent to other open tabs,
146
+ * and incoming changes from other tabs update this instance.
147
+ *
148
+ * Works with any persistent scope (local, tab, bucket).
149
+ */
150
+ sync?: boolean;
151
+ /**
152
+ * Selectively persist only the specified keys of an object value.
153
+ * Non-listed keys are kept in memory but excluded from storage writes.
154
+ * On read, persisted keys are merged with the default value.
155
+ *
156
+ * Only meaningful for object-typed state with a persistent scope.
157
+ */
158
+ persist?: Array<keyof T & string>;
159
+ }
160
+ interface Serializer<T> {
161
+ stringify(value: T): string;
162
+ parse(raw: string): T;
163
+ }
164
+ type Listener<T> = (value: T) => void;
165
+ type Unsubscribe = () => void;
166
+
167
+ declare function withServerSession<T>(fn: () => T): Promise<T>;
168
+
169
+ /**
170
+ * Runs all state updates inside fn as a single batch.
171
+ * Subscribers are notified once after all updates complete,
172
+ * rather than once per individual update.
173
+ *
174
+ * Nested batch() calls are safe — notifications flush only
175
+ * when the outermost batch completes.
176
+ *
177
+ * ```ts
178
+ * batch(() => {
179
+ * firstName.set('John')
180
+ * lastName.set('Doe')
181
+ * age.set(30)
182
+ * })
183
+ * // subscribers fire once, not three times
184
+ * ```
185
+ */
186
+ declare function batch(fn: () => void): void;
187
+
188
+ interface CollectionInstance<T> extends BaseInstance<T[]> {
189
+ /** Read the current value without any reactive implications */
190
+ peek(): T[];
191
+ /**
192
+ * Watch a specific key across all items.
193
+ * Fires whenever any item's value for that key changes.
194
+ * Receives the full updated array.
195
+ */
196
+ watch<K extends T extends object ? keyof T : never>(key: K, listener: (items: T[]) => void): Unsubscribe;
197
+ /** Add one or more items to the end of the collection */
198
+ add(...items: T[]): void;
199
+ /**
200
+ * Remove all items matching the predicate.
201
+ * Pass `{ one: true }` to remove only the first match.
202
+ */
203
+ remove(predicate: (item: T) => boolean, options?: {
204
+ one?: boolean;
205
+ }): void;
206
+ /**
207
+ * Update all items matching the predicate with a partial patch or updater.
208
+ * Pass `{ one: true }` to update only the first match.
209
+ */
210
+ update(predicate: (item: T) => boolean, patch: Partial<T> | ((item: T) => T), options?: {
211
+ one?: boolean;
212
+ }): void;
213
+ /** Find the first item matching the predicate */
214
+ find(predicate: (item: T) => boolean): T | undefined;
215
+ /** Find all items matching the predicate */
216
+ findAll(predicate: (item: T) => boolean): T[];
217
+ /** True if any item matches the predicate */
218
+ has(predicate: (item: T) => boolean): boolean;
219
+ /** Number of items in the collection */
220
+ readonly size: number;
221
+ /** Remove all items */
222
+ clear(): void;
223
+ }
224
+ /**
225
+ * Reactive array state with first-class mutation methods.
226
+ * Supports all the same scopes, SSR, validation, and migration as state().
227
+ *
228
+ * ```ts
229
+ * const todos = collection('todos', {
230
+ * default: [] as Todo[],
231
+ * scope: 'local',
232
+ * })
233
+ *
234
+ * todos.add({ id: '1', text: 'Buy milk', done: false })
235
+ * todos.update((t) => t.id === '1', { done: true })
236
+ * todos.remove((t) => t.done)
237
+ * todos.get() // Todo[]
238
+ * ```
239
+ */
240
+ declare function collection<T>(key: string, options: StateOptions<T[]>): CollectionInstance<T>;
241
+
242
+ type DepValues$1<T extends ReadonlyArray<BaseInstance<unknown>>> = {
243
+ [K in keyof T]: T[K] extends BaseInstance<infer V> ? V : never;
244
+ };
245
+ /**
246
+ * A read-only reactive value derived from one or more dependencies.
247
+ * Extends ReadonlyInstance — has get, peek, subscribe, ready, and identity,
248
+ * but no set or reset since the value is always determined by its sources.
249
+ */
250
+ interface ComputedInstance<T> extends ReadonlyInstance<T> {
251
+ }
252
+ /**
253
+ * Derive a reactive value from one or more state dependencies.
254
+ * Recomputes only when a dependency changes. Cached between changes.
255
+ * Participates in batch() — notifications are deferred like any other state.
256
+ *
257
+ * ```ts
258
+ * const firstName = state('firstName', { default: 'Jane' })
259
+ * const lastName = state('lastName', { default: 'Doe' })
260
+ *
261
+ * const fullName = computed([firstName, lastName], ([first, last]) => {
262
+ * return `${first} ${last}`.trim()
263
+ * })
264
+ *
265
+ * fullName.get() // 'Jane Doe'
266
+ * fullName.subscribe(name => console.log(name))
267
+ * ```
268
+ */
269
+ declare function computed<TDeps extends ReadonlyArray<BaseInstance<unknown>>, TResult>(deps: TDeps, fn: (values: DepValues$1<TDeps>) => TResult): ComputedInstance<TResult>;
270
+
271
+ type DepValues<T extends ReadonlyArray<BaseInstance<unknown>>> = {
272
+ [K in keyof T]: T[K] extends BaseInstance<infer V> ? V : never;
273
+ };
274
+ type Cleanup = () => void;
275
+ interface EffectHandle {
276
+ /** Stop the effect and run the last cleanup function if any */
277
+ stop(): void;
278
+ }
279
+ /**
280
+ * Run a side effect when state dependencies change.
281
+ * Runs immediately with current values, then re-runs on any change.
282
+ *
283
+ * The callback can return a cleanup function that runs before the next
284
+ * execution and when the effect is stopped.
285
+ *
286
+ * ```ts
287
+ * const stop = effect([theme, fontSize], ([t, f]) => {
288
+ * document.body.setAttribute('data-theme', t)
289
+ * document.documentElement.style.fontSize = `${f}px`
290
+ *
291
+ * return () => {
292
+ * document.body.removeAttribute('data-theme')
293
+ * }
294
+ * })
295
+ *
296
+ * // Later — stop listening and clean up
297
+ * stop()
298
+ * ```
299
+ */
300
+ declare function effect<TDeps extends ReadonlyArray<BaseInstance<unknown>>>(deps: TDeps, fn: (values: DepValues<TDeps>) => Cleanup | undefined): EffectHandle;
301
+
302
+ /**
303
+ * Create a stateful value.
304
+ *
305
+ * Same key + same scope always returns the same instance.
306
+ * Change scope to move state anywhere.
307
+ *
308
+ * ```ts
309
+ * const theme = state('theme', { default: 'light', scope: 'local' })
310
+ * const filters = state('filters', { default: {}, scope: 'url' })
311
+ * const user = state('user', { default: null, scope: 'server' })
312
+ * ```
313
+ */
314
+ declare function state<T>(key: string, options: StateOptions<T>): StateInstance<T>;
315
+
316
+ export { type Adapter as A, type BaseInstance as B, type CollectionInstance as C, type EffectHandle as E, type Listener as L, type ReadonlyInstance as R, type Scope as S, type Unsubscribe as U, type BucketOptions as a, type ComputedInstance as b, type Enhancer as c, type Serializer as d, type StateInstance as e, type StateOptions as f, batch as g, collection as h, computed as i, effect as j, state as s, withServerSession as w };
package/dist/index.cjs ADDED
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ var chunkGGB5QBDR_cjs = require('./chunk-GGB5QBDR.cjs');
4
+
5
+
6
+
7
+ Object.defineProperty(exports, "batch", {
8
+ enumerable: true,
9
+ get: function () { return chunkGGB5QBDR_cjs.batch; }
10
+ });
11
+ Object.defineProperty(exports, "collection", {
12
+ enumerable: true,
13
+ get: function () { return chunkGGB5QBDR_cjs.collection; }
14
+ });
15
+ Object.defineProperty(exports, "computed", {
16
+ enumerable: true,
17
+ get: function () { return chunkGGB5QBDR_cjs.computed; }
18
+ });
19
+ Object.defineProperty(exports, "configure", {
20
+ enumerable: true,
21
+ get: function () { return chunkGGB5QBDR_cjs.configure; }
22
+ });
23
+ Object.defineProperty(exports, "effect", {
24
+ enumerable: true,
25
+ get: function () { return chunkGGB5QBDR_cjs.effect; }
26
+ });
27
+ Object.defineProperty(exports, "state", {
28
+ enumerable: true,
29
+ get: function () { return chunkGGB5QBDR_cjs.state; }
30
+ });
31
+ Object.defineProperty(exports, "withServerSession", {
32
+ enumerable: true,
33
+ get: function () { return chunkGGB5QBDR_cjs.withServerSession; }
34
+ });
35
+ Object.defineProperty(exports, "withWatch", {
36
+ enumerable: true,
37
+ get: function () { return chunkGGB5QBDR_cjs.withWatch; }
38
+ });
39
+ //# sourceMappingURL=index.cjs.map
40
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.cjs"}
@@ -0,0 +1,90 @@
1
+ import { S as Scope, U as Unsubscribe, B as BaseInstance } from './factory-CIj-6WlO.cjs';
2
+ export { A as Adapter, a as BucketOptions, C as CollectionInstance, b as ComputedInstance, E as EffectHandle, c as Enhancer, L as Listener, R as ReadonlyInstance, d as Serializer, e as StateInstance, f as StateOptions, g as batch, h as collection, i as computed, j as effect, s as state, w as withServerSession } from './factory-CIj-6WlO.cjs';
3
+
4
+ type LogLevel = 'silent' | 'warn' | 'error' | 'debug';
5
+ interface ErrorContext {
6
+ key: string;
7
+ scope: Scope;
8
+ error: unknown;
9
+ }
10
+ interface DestroyContext {
11
+ key: string;
12
+ scope: Scope;
13
+ }
14
+ interface MigrateContext {
15
+ key: string;
16
+ scope: Scope;
17
+ fromVersion: number;
18
+ toVersion: number;
19
+ data: unknown;
20
+ }
21
+ interface QuotaExceededContext {
22
+ key: string;
23
+ scope: Scope;
24
+ error: unknown;
25
+ }
26
+ interface HydrateContext {
27
+ key: string;
28
+ scope: Scope;
29
+ serverValue: unknown;
30
+ clientValue: unknown;
31
+ }
32
+ interface SyncContext {
33
+ key: string;
34
+ scope: Scope;
35
+ value: unknown;
36
+ source: 'remote';
37
+ }
38
+ interface RegisterContext {
39
+ key: string;
40
+ scope: Scope;
41
+ }
42
+ interface SteadConfig {
43
+ /** Default scope for all state instances. Defaults to `'render'`. */
44
+ defaultScope?: Scope | undefined;
45
+ /** Enforce a naming pattern for state keys. */
46
+ keyPattern?: RegExp | undefined;
47
+ /** Control log verbosity for internal warnings and errors. Defaults to `'warn'`. */
48
+ logLevel?: LogLevel | undefined;
49
+ /** Cap the total number of registered state instances. */
50
+ maxKeys?: number | undefined;
51
+ /** Prepends to all storage keys (e.g. `myapp:theme`) */
52
+ prefix?: string | undefined;
53
+ /** Require a validate option for persisted scopes (local, tab, bucket). */
54
+ requireValidation?: boolean | undefined;
55
+ /** Enable SSR mode globally for all instances. */
56
+ ssr?: boolean | undefined;
57
+ /** Enable cross-tab sync globally for all syncable scopes. */
58
+ sync?: boolean | undefined;
59
+ /** Warn when two state() calls use the same key + scope. */
60
+ warnOnDuplicate?: boolean | undefined;
61
+ /** Fires when any instance is destroyed. */
62
+ onDestroy?: ((context: DestroyContext) => void) | undefined;
63
+ /** Global error handler for storage/migration/validation failures. */
64
+ onError?: ((context: ErrorContext) => void) | undefined;
65
+ /** Fires after SSR hydration completes for an instance. */
66
+ onHydrate?: ((context: HydrateContext) => void) | undefined;
67
+ /** Fires after a migration chain runs during read. */
68
+ onMigrate?: ((context: MigrateContext) => void) | undefined;
69
+ /** Fires when a storage write fails due to quota. */
70
+ onQuotaExceeded?: ((context: QuotaExceededContext) => void) | undefined;
71
+ /** Fires when a new state instance is registered. */
72
+ onRegister?: ((context: RegisterContext) => void) | undefined;
73
+ /** Fires when a cross-tab sync event updates a value. */
74
+ onSync?: ((context: SyncContext) => void) | undefined;
75
+ }
76
+ declare function configure(config: SteadConfig): void;
77
+
78
+ interface WithWatch<T> {
79
+ /**
80
+ * Watch a specific key within an object value.
81
+ * The listener only fires when that key's value changes,
82
+ * using Object.is for comparison.
83
+ *
84
+ * Returns an unsubscribe function.
85
+ */
86
+ watch<K extends T extends object ? keyof T : never>(key: K, listener: (value: T[K & keyof T]) => void): Unsubscribe;
87
+ }
88
+ declare function withWatch<TIn extends BaseInstance<any>>(instance: TIn): TIn & WithWatch<TIn extends BaseInstance<infer T> ? T : unknown>;
89
+
90
+ export { BaseInstance, type DestroyContext, type ErrorContext, type HydrateContext, type LogLevel, type MigrateContext, type QuotaExceededContext, type RegisterContext, Scope, type SteadConfig, type SyncContext, Unsubscribe, type WithWatch, configure, withWatch };
@@ -0,0 +1,90 @@
1
+ import { S as Scope, U as Unsubscribe, B as BaseInstance } from './factory-CIj-6WlO.js';
2
+ export { A as Adapter, a as BucketOptions, C as CollectionInstance, b as ComputedInstance, E as EffectHandle, c as Enhancer, L as Listener, R as ReadonlyInstance, d as Serializer, e as StateInstance, f as StateOptions, g as batch, h as collection, i as computed, j as effect, s as state, w as withServerSession } from './factory-CIj-6WlO.js';
3
+
4
+ type LogLevel = 'silent' | 'warn' | 'error' | 'debug';
5
+ interface ErrorContext {
6
+ key: string;
7
+ scope: Scope;
8
+ error: unknown;
9
+ }
10
+ interface DestroyContext {
11
+ key: string;
12
+ scope: Scope;
13
+ }
14
+ interface MigrateContext {
15
+ key: string;
16
+ scope: Scope;
17
+ fromVersion: number;
18
+ toVersion: number;
19
+ data: unknown;
20
+ }
21
+ interface QuotaExceededContext {
22
+ key: string;
23
+ scope: Scope;
24
+ error: unknown;
25
+ }
26
+ interface HydrateContext {
27
+ key: string;
28
+ scope: Scope;
29
+ serverValue: unknown;
30
+ clientValue: unknown;
31
+ }
32
+ interface SyncContext {
33
+ key: string;
34
+ scope: Scope;
35
+ value: unknown;
36
+ source: 'remote';
37
+ }
38
+ interface RegisterContext {
39
+ key: string;
40
+ scope: Scope;
41
+ }
42
+ interface SteadConfig {
43
+ /** Default scope for all state instances. Defaults to `'render'`. */
44
+ defaultScope?: Scope | undefined;
45
+ /** Enforce a naming pattern for state keys. */
46
+ keyPattern?: RegExp | undefined;
47
+ /** Control log verbosity for internal warnings and errors. Defaults to `'warn'`. */
48
+ logLevel?: LogLevel | undefined;
49
+ /** Cap the total number of registered state instances. */
50
+ maxKeys?: number | undefined;
51
+ /** Prepends to all storage keys (e.g. `myapp:theme`) */
52
+ prefix?: string | undefined;
53
+ /** Require a validate option for persisted scopes (local, tab, bucket). */
54
+ requireValidation?: boolean | undefined;
55
+ /** Enable SSR mode globally for all instances. */
56
+ ssr?: boolean | undefined;
57
+ /** Enable cross-tab sync globally for all syncable scopes. */
58
+ sync?: boolean | undefined;
59
+ /** Warn when two state() calls use the same key + scope. */
60
+ warnOnDuplicate?: boolean | undefined;
61
+ /** Fires when any instance is destroyed. */
62
+ onDestroy?: ((context: DestroyContext) => void) | undefined;
63
+ /** Global error handler for storage/migration/validation failures. */
64
+ onError?: ((context: ErrorContext) => void) | undefined;
65
+ /** Fires after SSR hydration completes for an instance. */
66
+ onHydrate?: ((context: HydrateContext) => void) | undefined;
67
+ /** Fires after a migration chain runs during read. */
68
+ onMigrate?: ((context: MigrateContext) => void) | undefined;
69
+ /** Fires when a storage write fails due to quota. */
70
+ onQuotaExceeded?: ((context: QuotaExceededContext) => void) | undefined;
71
+ /** Fires when a new state instance is registered. */
72
+ onRegister?: ((context: RegisterContext) => void) | undefined;
73
+ /** Fires when a cross-tab sync event updates a value. */
74
+ onSync?: ((context: SyncContext) => void) | undefined;
75
+ }
76
+ declare function configure(config: SteadConfig): void;
77
+
78
+ interface WithWatch<T> {
79
+ /**
80
+ * Watch a specific key within an object value.
81
+ * The listener only fires when that key's value changes,
82
+ * using Object.is for comparison.
83
+ *
84
+ * Returns an unsubscribe function.
85
+ */
86
+ watch<K extends T extends object ? keyof T : never>(key: K, listener: (value: T[K & keyof T]) => void): Unsubscribe;
87
+ }
88
+ declare function withWatch<TIn extends BaseInstance<any>>(instance: TIn): TIn & WithWatch<TIn extends BaseInstance<infer T> ? T : unknown>;
89
+
90
+ export { BaseInstance, type DestroyContext, type ErrorContext, type HydrateContext, type LogLevel, type MigrateContext, type QuotaExceededContext, type RegisterContext, Scope, type SteadConfig, type SyncContext, Unsubscribe, type WithWatch, configure, withWatch };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { batch, collection, computed, configure, effect, state, withServerSession, withWatch } from './chunk-347V4L7H.js';
2
+ //# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+
3
+ var chunkGGB5QBDR_cjs = require('../chunk-GGB5QBDR.cjs');
4
+ var react = require('react');
5
+
6
+ function useStore(key, options) {
7
+ const instance = chunkGGB5QBDR_cjs.state(key, options);
8
+ const value = react.useSyncExternalStore(
9
+ react.useCallback((onStoreChange) => instance.subscribe(onStoreChange), [instance]),
10
+ () => instance.get(),
11
+ () => options.default
12
+ );
13
+ const set = react.useCallback(
14
+ (valueOrUpdater) => {
15
+ instance.set(valueOrUpdater);
16
+ },
17
+ [instance]
18
+ );
19
+ return [value, set];
20
+ }
21
+ function useStateInstance(key, options) {
22
+ const instance = chunkGGB5QBDR_cjs.state(key, options);
23
+ react.useSyncExternalStore(
24
+ react.useCallback((onStoreChange) => instance.subscribe(onStoreChange), [instance]),
25
+ () => instance.get(),
26
+ () => options.default
27
+ );
28
+ return instance;
29
+ }
30
+ function useSharedState(instance) {
31
+ const value = react.useSyncExternalStore(
32
+ react.useCallback((onStoreChange) => instance.subscribe(onStoreChange), [instance]),
33
+ () => instance.get(),
34
+ () => instance.get()
35
+ );
36
+ const set = react.useCallback(
37
+ (valueOrUpdater) => {
38
+ instance.set(valueOrUpdater);
39
+ },
40
+ [instance]
41
+ );
42
+ return [value, set];
43
+ }
44
+ function useWatch(instance, key) {
45
+ const getSnapshot = react.useCallback(() => instance.get()[key], [instance, key]);
46
+ return react.useSyncExternalStore(
47
+ react.useCallback(
48
+ (onStoreChange) => {
49
+ return instance.watch(key, onStoreChange);
50
+ },
51
+ [instance, key]
52
+ ),
53
+ getSnapshot
54
+ );
55
+ }
56
+ function useReady(instance) {
57
+ const [isReady, setIsReady] = react.useState(false);
58
+ react.useEffect(() => {
59
+ let cancelled = false;
60
+ instance.ready.then(() => {
61
+ if (!cancelled) setIsReady(true);
62
+ }).catch(() => {
63
+ });
64
+ return () => {
65
+ cancelled = true;
66
+ };
67
+ }, [instance]);
68
+ return isReady;
69
+ }
70
+ function useSettled(instance) {
71
+ const [isSettled, setIsSettled] = react.useState(false);
72
+ react.useEffect(() => {
73
+ let cancelled = false;
74
+ setIsSettled(false);
75
+ instance.settled.then(() => {
76
+ if (!cancelled) setIsSettled(true);
77
+ }).catch(() => {
78
+ });
79
+ return () => {
80
+ cancelled = true;
81
+ };
82
+ }, [instance]);
83
+ return isSettled;
84
+ }
85
+ function useHydrated(instance) {
86
+ const [isHydrated, setIsHydrated] = react.useState(false);
87
+ react.useEffect(() => {
88
+ let cancelled = false;
89
+ instance.hydrated.then(() => {
90
+ if (!cancelled) setIsHydrated(true);
91
+ }).catch(() => {
92
+ });
93
+ return () => {
94
+ cancelled = true;
95
+ };
96
+ }, [instance]);
97
+ return isHydrated;
98
+ }
99
+ function useBucket(key, options) {
100
+ const mergedOptions = { ...options, scope: "bucket" };
101
+ const instance = chunkGGB5QBDR_cjs.state(key, mergedOptions);
102
+ const [value, set] = useStore(key, mergedOptions);
103
+ const isReady = useReady(instance);
104
+ return [value, set, isReady];
105
+ }
106
+ function useCollection(key, options) {
107
+ const col = chunkGGB5QBDR_cjs.collection(key, options);
108
+ react.useSyncExternalStore(
109
+ react.useCallback((onStoreChange) => col.subscribe(onStoreChange), [col]),
110
+ () => col.get(),
111
+ () => options.default
112
+ );
113
+ return col;
114
+ }
115
+
116
+ Object.defineProperty(exports, "batch", {
117
+ enumerable: true,
118
+ get: function () { return chunkGGB5QBDR_cjs.batch; }
119
+ });
120
+ Object.defineProperty(exports, "collection", {
121
+ enumerable: true,
122
+ get: function () { return chunkGGB5QBDR_cjs.collection; }
123
+ });
124
+ Object.defineProperty(exports, "computed", {
125
+ enumerable: true,
126
+ get: function () { return chunkGGB5QBDR_cjs.computed; }
127
+ });
128
+ Object.defineProperty(exports, "effect", {
129
+ enumerable: true,
130
+ get: function () { return chunkGGB5QBDR_cjs.effect; }
131
+ });
132
+ Object.defineProperty(exports, "state", {
133
+ enumerable: true,
134
+ get: function () { return chunkGGB5QBDR_cjs.state; }
135
+ });
136
+ Object.defineProperty(exports, "withServerSession", {
137
+ enumerable: true,
138
+ get: function () { return chunkGGB5QBDR_cjs.withServerSession; }
139
+ });
140
+ exports.useBucket = useBucket;
141
+ exports.useCollection = useCollection;
142
+ exports.useHydrated = useHydrated;
143
+ exports.useReady = useReady;
144
+ exports.useSettled = useSettled;
145
+ exports.useSharedState = useSharedState;
146
+ exports.useStateInstance = useStateInstance;
147
+ exports.useStore = useStore;
148
+ exports.useWatch = useWatch;
149
+ //# sourceMappingURL=index.cjs.map
150
+ //# sourceMappingURL=index.cjs.map