effect-atom-svelte 0.4.1 → 0.5.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.
package/README.md CHANGED
@@ -8,14 +8,14 @@ This is a community project by Jarred Norris. It is not part of Effect, and the
8
8
 
9
9
  ## Requirements
10
10
 
11
- - `effect` 4.0.x. The peer range is `~4.0.0`, not `^4.0.0`: the bindings use parts of the atom registry that aren't public API, which a minor release of `effect` can change.
11
+ - `effect` 4.1.x. The peer range is `~4.1.0`, not `^4.1.0`: the bindings use parts of the atom registry that aren't public API, which a minor release of `effect` can change.
12
12
  - Svelte 5.57.2 or later. `experimental.async` is needed for `useAtomSuspense`, `useAtomResult` and server rendering.
13
- - SvelteKit is optional. The docs site and its tests run on SvelteKit 3. On SvelteKit 2, the error hooks in `effect-atom-svelte/sveltekit` work with less detail, and reach `<svelte:boundary>` only with `kit.experimental.handleRenderingErrors` turned on.
13
+ - SvelteKit is optional. The docs site and its tests run on SvelteKit 3. On SvelteKit 2, the error hooks in `effect-atom-svelte/sveltekit` work with less detail, and reach `<svelte:boundary>` only with `kit.experimental.handleRenderingErrors` turned on. `remoteQueryAtom` needs SvelteKit 3 with `experimental.remoteFunctions`.
14
14
 
15
15
  ## Installation
16
16
 
17
17
  ```sh
18
- npm install effect-atom-svelte "effect@~4.0.0"
18
+ npm install effect-atom-svelte "effect@~4.1.0"
19
19
  ```
20
20
 
21
21
  Turn on Svelte's async mode. In SvelteKit 3, pass it to `sveltekit()` in `vite.config.ts`:
package/dist/Form.d.ts CHANGED
@@ -242,7 +242,12 @@ export interface Field<V> {
242
242
  readonly issue: string | undefined;
243
243
  /** Whether the user has left the field. `useForm`'s `attrs.onblur` sets it. */
244
244
  touched: boolean;
245
- /** Whether the value differs from the initial value. */
245
+ /**
246
+ * Whether the value differs from the initial value. A field in an array item compares with that
247
+ * item's initial value, wherever the item has moved, so removing or moving items leaves the
248
+ * others clean. An item added since (by `append` or `replace`) has no initial value: its fields
249
+ * are dirty.
250
+ */
246
251
  readonly dirty: boolean;
247
252
  /**
248
253
  * Whether the form's validation is running or waiting for its debounce: the whole form's flag,
@@ -420,7 +425,9 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
420
425
  readonly submitting: boolean;
421
426
  /**
422
427
  * The last submit's result, holding only failures `mapError` didn't claim. A validation that
423
- * couldn't run at all, such as when the form's runtime failed to build, ends here as a defect.
428
+ * couldn't run at all, such as when the form's runtime failed to build, ends here as a defect, and
429
+ * so does a throw from `payload`, from `mapError` (beside the failure it was given) or from the
430
+ * atom's write, such as an `Atom.fn` that throws before returning its Effect.
424
431
  */
425
432
  readonly submitResult: AsyncResult.AsyncResult<A, E>;
426
433
  /**
@@ -452,7 +459,8 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
452
459
  * call while a submit runs gets that submit's result. A submit that settles after a reset doesn't
453
460
  * touch the fresh form. Instances that submit to the same `Atom.fn` share its one result: if
454
461
  * another instance writes it while this submit runs, this submit resolves with the other's
455
- * result, so give each instance its own atom.
462
+ * result, so give each instance its own atom. When the `RegistryProvider` that holds the form
463
+ * is destroyed mid-submit, the submit resolves as interrupted.
456
464
  */
457
465
  readonly submit: (...args: [Args] extends [undefined] ? [] : [args: Args]) => Promise<Exit.Exit<A, E | ValidationError>>;
458
466
  /**
@@ -466,6 +474,9 @@ export interface Instance<T, D, A, E, Args> extends Group<T> {
466
474
  * Sets several values at once. Not counted as input on any field, so an untouched field's error
467
475
  * waits for its own timing; a touched field whose check it breaks shows its error at once, as
468
476
  * after another field's change. Like any change, it clears external errors where values changed.
477
+ * Array items pair with the current ones by position: each takes the key, touched state and
478
+ * errors of the item at its index, and its `dirty` compares with that item's initial value. To
479
+ * go back to the initial or submitted values, use `reset` or `revertToLastSubmit`.
469
480
  */
470
481
  readonly setValues: (values: T | ((previous: T) => T)) => void;
471
482
  /**
@@ -129,7 +129,9 @@ export declare const useAtomMount: (input: AtomInput<Atom.Atom<unknown>>) => voi
129
129
  * running keeps going (send `Atom.Interrupt` to stop it). A signal that is already aborted settles
130
130
  * the call as interrupted without writing, as `fetch` does. Calls on one `Atom.fn` share its single
131
131
  * result, so a new call supersedes one in flight and every pending call resolves with the latest
132
- * call's result. `Atom.Reset` has no result to wait for, so these modes leave it out of their
132
+ * call's result. A write that throws, as an `Atom.fn` that throws before returning its Effect does,
133
+ * settles the call as that defect: `promiseExit` resolves with `Exit.die`, `promise` rejects with
134
+ * the error. `Atom.Reset` has no result to wait for, so these modes leave it out of their
133
135
  * types and reject it; reset with a `value` mode setter. A reset written while a promise-mode call
134
136
  * is pending settles that promise as interrupted. To cancel a call, send `Atom.Interrupt`.
135
137
  *
@@ -180,11 +182,13 @@ export declare const useAtomRefresh: (input: AtomInput<Atom.Atom<unknown>>) => (
180
182
  /**
181
183
  * Calls `f` on every change while the component lives, and with the current value first when
182
184
  * `immediate` is set. The atom is computed once the component mounts, and never on the server, so a
183
- * derived or effect atom that nothing else reads still runs and reports its changes. A change raised while another component
184
- * is reading an atom reaches `f` on a microtask, so `f` can write `$state` (Svelte forbids that
185
- * during a read). Changes after it wait their turn, so `f` sees every change in order; any other
186
- * change reaches it synchronously. Nothing reaches `f` once the component is destroyed, not even a
187
- * change still waiting for its microtask.
185
+ * derived or effect atom that nothing else reads still runs and reports its changes. If that first
186
+ * computation throws, the error is left to the atom's readers and `f` hears the atom once it
187
+ * recovers; with `immediate`, it throws in the component, as there is no value to call `f` with.
188
+ * A change raised while another component is reading an atom reaches `f` on a microtask, so `f` can
189
+ * write `$state` (Svelte forbids that during a read). Changes after it wait their turn, so `f` sees
190
+ * every change in order; any other change reaches it synchronously. Nothing reaches `f` once the
191
+ * component is destroyed, not even a change still waiting for its microtask.
188
192
  *
189
193
  * **Example** (Saving every change)
190
194
  *
@@ -218,6 +222,11 @@ export declare const useAtomSubscribe: <A>(input: AtomInput<Atom.Atom<A>>, f: (v
218
222
  * its own; requests rendering at the same time share the registry's atoms, and with them the value
219
223
  * the first one applied.
220
224
  *
225
+ * An effect or stream atom given a value still runs on mount, as with `AtomRegistry.make`. To keep
226
+ * the value instead, as for data a `load` function already fetched, pass the entry as
227
+ * `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then runs once
228
+ * it is refreshed, or once an atom its factory reads before returning the effect changes.
229
+ *
221
230
  * **Example** (Starting an atom from a prop)
222
231
  *
223
232
  * ```ts
@@ -235,7 +244,7 @@ export declare const useAtomSubscribe: <A>(input: AtomInput<Atom.Atom<A>>, f: (v
235
244
  * @since 0.1.0
236
245
  * @category hooks
237
246
  */
238
- export declare const useAtomInitialValues: (initialValues: Iterable<readonly [Atom.Atom<unknown>, unknown]>) => void;
247
+ export declare const useAtomInitialValues: (initialValues: Iterable<readonly [Atom.Atom<unknown>, unknown, Atom.InitialValueOptions?]>) => void;
239
248
  /**
240
249
  * Reads an `AtomRef`, following it when the getter returns a different ref. For a writable ref,
241
250
  * `current` can be assigned too, which sets the ref, so `bind:value={name.current}` works; a
@@ -13,6 +13,7 @@ import { queuedByBoundary } from "./internal/boundaries.js";
13
13
  import { onDispose } from "./internal/disposal.js";
14
14
  import { engineOf, initialGetter } from "./internal/form/engineOf.js";
15
15
  import { decodeSeed, encodeSeed, isWaiting, noSeed, revalidatesOnHydrate, } from "./internal/hydration.js";
16
+ import { isRemoteQueryAtom } from "./internal/remoteQueries.js";
16
17
  import { onRenderEnd } from "./internal/renderEnd.js";
17
18
  import { reportReads } from "./internal/scope.svelte.js";
18
19
  import { onTeardown } from "./internal/teardown.svelte.js";
@@ -83,9 +84,10 @@ const notStarted = (result) => result._tag === "Initial" && !result.waiting;
83
84
  const hasServerValue = (atom) => Atom.ServerValueTypeId in atom;
84
85
  /** The atom's node, created if the registry has none yet. */
85
86
  const nodeOf = (registry, atom) =>
86
- // SAFETY: ensureNode returns the implementation's node (Effect 4.0.5), which has
87
+ // SAFETY: ensureNode returns the implementation's node (Effect 4.1.7), which has
87
88
  // preserveInitialValueOnBuild, _value, setValue and failed (set while a first build has thrown)
88
- // beside the Node interface; @effect/atom-react calls its setValue the same way.
89
+ // beside the Node interface, and a setInitialValue that also takes skipInitialRun;
90
+ // @effect/atom-react calls its setValue the same way.
89
91
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- those members are on the implementation only, which Effect doesn't export
90
92
  registry.ensureNode(atom);
91
93
  /** The atom that holds a value given to `atom`: a wrapper such as `withRefresh` passes it on. */
@@ -96,6 +98,22 @@ const initialValueTarget = (atom) => {
96
98
  }
97
99
  return target;
98
100
  };
101
+ /**
102
+ * The atom whose serialization key carries `atom`'s result between server and browser: `atom`
103
+ * itself, or the source of a wrapper that passes its value on, as `Atom.swr` does. `AtomRpc` and
104
+ * `AtomHttpApi` build a query with a `serializationKey` and a `staleTime` that way: the wrapper
105
+ * isn't serializable, its source is.
106
+ */
107
+ const serializableOf = (atom) => {
108
+ let current = atom;
109
+ while (current) {
110
+ if (Atom.isSerializable(current)) {
111
+ return current;
112
+ }
113
+ current = current.initialValueTarget;
114
+ }
115
+ return undefined;
116
+ };
99
117
  /**
100
118
  * Keeps an atom's node in the registry without computing it, as a mount would but without the read.
101
119
  * The registry sweeps a node without listeners, so a listener holds it; letting go schedules the
@@ -149,8 +167,21 @@ const initialNodeOnServer = (registry, atom) => {
149
167
  if (BROWSER) {
150
168
  return undefined;
151
169
  }
152
- const node = nodeOf(registry, initialValueTarget(atom));
153
- return node.preserveInitialValueOnBuild ? node : undefined;
170
+ const target = initialValueTarget(atom);
171
+ const node = nodeOf(registry, target);
172
+ if (!node.preserveInitialValueOnBuild) {
173
+ return undefined;
174
+ }
175
+ // Since Effect 4.1, a value a HydrationBoundary queued for the atom's own node is applied as an
176
+ // initial value too. It isn't one of these: it may be a promise-encoded Initial whose result lands
177
+ // during the render, which the hooks wait for, as they did when Effect applied it as the node's
178
+ // value (4.0). Only a wrapper's source received it as an initial value then, and still does.
179
+ if (target === atom &&
180
+ Atom.isSerializable(atom) &&
181
+ queuedByBoundary(registry, atom[Atom.SerializableTypeId].key)) {
182
+ return undefined;
183
+ }
184
+ return node;
154
185
  };
155
186
  /** Whether, on the server, an atom renders a value from `useAtomInitialValues`. */
156
187
  const initialOnServer = (registry, atom) => initialNodeOnServer(registry, atom) !== undefined;
@@ -216,6 +247,21 @@ const countSeeded = (registry, key) => {
216
247
  // The keys of the atoms useAtomValue has warned about, so the server warns once per key, not per
217
248
  // request.
218
249
  const warnedUnsent = new Set();
250
+ const warnedRemoteQuery = new WeakSet();
251
+ /**
252
+ * In development, warns once per atom that a plain read on the server met a remoteQueryAtom still
253
+ * waiting for its query. SvelteKit sends the query's result with the page anyway, so the browser
254
+ * starts from the value while the server's HTML shows the loading state.
255
+ */
256
+ const warnRemoteQueryRead = (atom, value, hook) => {
257
+ if (!AsyncResult.isAsyncResult(value) ||
258
+ !value.waiting ||
259
+ warnedRemoteQuery.has(atom)) {
260
+ return;
261
+ }
262
+ warnedRemoteQuery.add(atom);
263
+ console.warn(`effect-atom-svelte: ${hook} read a remoteQueryAtom on the server before its query returned, so the server's HTML shows it loading while the browser starts from SvelteKit's result. Read it with await useAtomResult or useAtomSuspense, so the render waits for the query. ${troubleshooting("read-a-remotequeryatom-on-the-server-before-its-query-returned")}`);
264
+ };
219
265
  /**
220
266
  * In development, warns once per key that a plain read on the server met a serializable async atom
221
267
  * still running: only useAtomResult and useAtomSuspense send an atom's result to the browser, so
@@ -224,18 +270,22 @@ const warnedUnsent = new Set();
224
270
  * nothing is computing, such as an Atom.fn nobody called or a value written to the atom.
225
271
  */
226
272
  const warnUnsent = (registry, atom, value, hook) => {
227
- if (!(DEV && Atom.isSerializable(atom) && AsyncResult.isAsyncResult(value)) ||
228
- !value.waiting) {
273
+ if (DEV && isRemoteQueryAtom(atom)) {
274
+ warnRemoteQueryRead(atom, value, hook);
275
+ return;
276
+ }
277
+ const source = DEV ? serializableOf(atom) : undefined;
278
+ if (!(source && AsyncResult.isAsyncResult(value)) || !value.waiting) {
229
279
  return;
230
280
  }
231
- const { key } = atom[Atom.SerializableTypeId];
281
+ const { key } = source[Atom.SerializableTypeId];
232
282
  if (warnedUnsent.has(key) ||
233
283
  queuedByBoundary(registry, key) ||
234
284
  seededOnServer(registry, key)) {
235
285
  return;
236
286
  }
237
287
  warnedUnsent.add(key);
238
- console.warn(`effect-atom-svelte: ${hook} read the serializable atom "${key}" on the server while it was still running, but only useAtomResult and useAtomSuspense send an atom's result to the browser, so it runs again there. Read it with one of them. See https://atom.jarrednorris.dev/hydration#how-the-result-travels`);
288
+ console.warn(`effect-atom-svelte: ${hook} read the serializable atom "${key}" on the server while it was still running, but only useAtomResult and useAtomSuspense send an atom's result to the browser, so it runs again there. Read it with one of them. ${troubleshooting("only-useatomresult-and-useatomsuspense-send-an-atoms-result-to-the-browser")}`);
239
289
  };
240
290
  /**
241
291
  * Reads the getter's atom and follows it. `plainRead` names the plain read, `useAtomValue` or
@@ -500,11 +550,12 @@ export function useAtomSet(input, options) {
500
550
  registry.set(atom, updateFrom(registry.get(atom)));
501
551
  };
502
552
  }
553
+ const settle = (exit) => mode === "promiseExit" ? exit : valueOrThrow(exit);
503
554
  return async (value, writeOptions) => {
504
555
  if (value === Atom.Reset) {
505
556
  // Excluded by the types: a reset result is Initial, which never settles, so the wait would
506
557
  // never end.
507
- throw new TypeError(`useAtomSet's ${mode} mode cannot wait for Atom.Reset; reset with a value mode setter`);
558
+ throw new TypeError(`useAtomSet's ${mode} mode cannot wait for Atom.Reset; reset with a value mode setter. ${troubleshooting("cannot-wait-for-atomreset")}`);
508
559
  }
509
560
  // SAFETY: the overloads offer the promise modes only for an atom that holds an AsyncResult.
510
561
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the implementation signature can't carry the overloads' atom type
@@ -519,7 +570,14 @@ export function useAtomSet(input, options) {
519
570
  else {
520
571
  // oxlint-disable-next-line effecttsgo/global-date -- compared with an AsyncResult's timestamp, which Effect takes from Date.now
521
572
  const start = Date.now();
522
- registry.set(atom, value);
573
+ try {
574
+ registry.set(atom, value);
575
+ }
576
+ catch (error) {
577
+ // As an Atom.fn that throws before returning its Effect does: a defect, so promiseExit mode
578
+ // still resolves, with it.
579
+ return settle(Exit.die(error));
580
+ }
523
581
  // A provider disposing of its registry ends the call without a last result, so the wait ends
524
582
  // there too, as interrupted.
525
583
  const controller = new AbortController();
@@ -536,7 +594,7 @@ export function useAtomSet(input, options) {
536
594
  writeOptions?.signal?.removeEventListener("abort", abort);
537
595
  }
538
596
  }
539
- return mode === "promiseExit" ? exit : valueOrThrow(exit);
597
+ return settle(exit);
540
598
  };
541
599
  }
542
600
  /**
@@ -614,11 +672,13 @@ const orderedDelivery = (f) => {
614
672
  /**
615
673
  * Calls `f` on every change while the component lives, and with the current value first when
616
674
  * `immediate` is set. The atom is computed once the component mounts, and never on the server, so a
617
- * derived or effect atom that nothing else reads still runs and reports its changes. A change raised while another component
618
- * is reading an atom reaches `f` on a microtask, so `f` can write `$state` (Svelte forbids that
619
- * during a read). Changes after it wait their turn, so `f` sees every change in order; any other
620
- * change reaches it synchronously. Nothing reaches `f` once the component is destroyed, not even a
621
- * change still waiting for its microtask.
675
+ * derived or effect atom that nothing else reads still runs and reports its changes. If that first
676
+ * computation throws, the error is left to the atom's readers and `f` hears the atom once it
677
+ * recovers; with `immediate`, it throws in the component, as there is no value to call `f` with.
678
+ * A change raised while another component is reading an atom reaches `f` on a microtask, so `f` can
679
+ * write `$state` (Svelte forbids that during a read). Changes after it wait their turn, so `f` sees
680
+ * every change in order; any other change reaches it synchronously. Nothing reaches `f` once the
681
+ * component is destroyed, not even a change still waiting for its microtask.
622
682
  *
623
683
  * **Example** (Saving every change)
624
684
  *
@@ -644,15 +704,15 @@ export const useAtomSubscribe = (input, f, options) => {
644
704
  const atom = current;
645
705
  // `immediate` calls `f` now, inside this effect; what `f` reads must not re-run it.
646
706
  return untrack(() => {
647
- // registry.subscribe does not compute a node that has never been read, so an atom nothing
648
- // else reads would never run, and a derived atom would never hear its sources. Reading it
649
- // first builds it.
650
- const value = duringRead(() => registry.get(atom));
651
707
  if (options?.immediate === true) {
652
- f(value);
708
+ f(duringRead(() => registry.get(atom)));
653
709
  }
654
710
  const deliver = orderedDelivery(f);
655
- const cancel = registry.subscribe(atom, deliver);
711
+ // Since Effect 4.1, registry.subscribe computes an atom nothing has read yet, so an atom
712
+ // nothing else reads still runs and a derived atom hears its sources. A first computation
713
+ // that throws is left for the atom's readers to report, and `f` hears the atom once it
714
+ // recovers. It counts as a read, so a change the computation raises waits for its microtask.
715
+ const cancel = duringRead(() => registry.subscribe(atom, deliver));
656
716
  dropInitialValueMark(registry, atom);
657
717
  return () => {
658
718
  deliver.stop();
@@ -691,6 +751,11 @@ const serverHolders = new WeakMap();
691
751
  * its own; requests rendering at the same time share the registry's atoms, and with them the value
692
752
  * the first one applied.
693
753
  *
754
+ * An effect or stream atom given a value still runs on mount, as with `AtomRegistry.make`. To keep
755
+ * the value instead, as for data a `load` function already fetched, pass the entry as
756
+ * `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then runs once
757
+ * it is refreshed, or once an atom its factory reads before returning the effect changes.
758
+ *
694
759
  * **Example** (Starting an atom from a prop)
695
760
  *
696
761
  * ```ts
@@ -717,11 +782,11 @@ export const useAtomInitialValues = (initialValues) => {
717
782
  release();
718
783
  }
719
784
  });
720
- for (const [atom, value] of initialValues) {
721
- const node = registry.ensureNode(initialValueTarget(atom));
785
+ for (const [atom, value, options] of initialValues) {
786
+ const node = nodeOf(registry, initialValueTarget(atom));
722
787
  if (!initialValuesApplied.has(node)) {
723
788
  initialValuesApplied.add(node);
724
- node.setInitialValue(value);
789
+ node.setInitialValue(value, options?.skipInitialRun);
725
790
  }
726
791
  if (!BROWSER) {
727
792
  // A registry passed in by the caller outlives the request, and its node may not be swept
@@ -807,7 +872,7 @@ export const useAtomRefPropValue = (input, prop) => {
807
872
  const propRef = $derived(getRef().prop(prop));
808
873
  return useAtomRef(() => propRef);
809
874
  };
810
- const notStartedError = (hook) => new Error(`${hook} read an atom that has not started on the server: its result is Initial and nothing is running it, as for an Atom.fn that has not been called, so the render would wait for it forever. Read it with useAtomValue, which renders Initial, or inside a <svelte:boundary> with a pending snippet, which the server renders instead.`);
875
+ const notStartedError = (hook) => new Error(`${hook} read an atom that has not started on the server: its result is Initial and nothing is running it, as for an Atom.fn that has not been called, so the render would wait for it forever. Read it with useAtomValue, which renders Initial, or inside a <svelte:boundary> with a pending snippet, which the server renders instead. ${troubleshooting("read-an-atom-that-has-not-started-on-the-server")}`);
811
876
  /**
812
877
  * Puts the server's value in the registry as current, so nothing fetches it again (JND-19). Seeding
813
878
  * through `setSerializable` would not: for an atom that wraps another, such as a query with
@@ -836,6 +901,9 @@ const settledSeeds = new WeakSet();
836
901
  * registry, so later requests would skip embedding their seed (JND-17).
837
902
  */
838
903
  const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) => {
904
+ // The atom whose key and schema carry the result: `atom`, or the source a wrapper such as
905
+ // Atom.swr passes its value to. Its own value is sent, as the browser applies the seed to it.
906
+ const owner = serializableOf(atom) ?? atom;
839
907
  // Mounted until the render ends, so the settled node is what the render reads.
840
908
  const release = serverMount(registry, atom);
841
909
  // A render ends before its seeds settle only when it fails, as when a later reader throws during
@@ -876,7 +944,7 @@ const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) =>
876
944
  if (ended) {
877
945
  return noSeed;
878
946
  }
879
- return encodeSeed(key, encode, serverGet(registry, atom));
947
+ return encodeSeed(key, encode, serverGet(registry, owner));
880
948
  })();
881
949
  return claim.own;
882
950
  });
@@ -884,11 +952,12 @@ const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) =>
884
952
  if (suspendOnWaiting) {
885
953
  settledSeeds.add(encoded);
886
954
  }
955
+ // Wrappers of one serializable atom, such as two Atom.swr of one query, send the same result.
887
956
  const claimed = serverSeeds.get(encoded);
888
- if (claimed && claimed !== atom) {
957
+ if (claimed && claimed !== owner) {
889
958
  throw new Error(`Two different atoms share the serialization key "${key}", so the server can't tell whose result to send. Put what tells the copies apart into the key, such as an id, and define atoms at module level. ${troubleshooting("two-different-atoms-share-the-serialization-key")}`);
890
959
  }
891
- serverSeeds.set(encoded, atom);
960
+ serverSeeds.set(encoded, owner);
892
961
  return (async () => {
893
962
  await encoded;
894
963
  })();
@@ -965,10 +1034,11 @@ revalidateOption, suspendOnWaiting = false) => {
965
1034
  const atom = getAtom();
966
1035
  // The server never computes an atom with a server value, so it has no value to pass on, and the
967
1036
  // browser must not ask for one: hydratable throws for a key the server didn't write (JND-58).
968
- if (!Atom.isSerializable(atom) || hasServerValue(atom)) {
1037
+ const source = serializableOf(atom);
1038
+ if (!source || hasServerValue(atom)) {
969
1039
  return undefined;
970
1040
  }
971
- const { decode, encode, key } = atom[Atom.SerializableTypeId];
1041
+ const { decode, encode, key } = source[Atom.SerializableTypeId];
972
1042
  if (!BROWSER) {
973
1043
  return {
974
1044
  done: seedOnServer(registry, atom, key, encode, suspendOnWaiting),
@@ -128,7 +128,7 @@ export interface Inspector {
128
128
  * Starts watching a registry, and returns its inspector: the same one each time it is called for
129
129
  * the same registry.
130
130
  *
131
- * Until then a registry runs as it always does. From then on, in a registry made by Effect 4.0,
131
+ * Until then a registry runs as it always does. From then on, in a registry made by Effect 4.1,
132
132
  * each node reports what happens to it, which costs a little on every read and write, so call it
133
133
  * from developer tools rather than from the app.
134
134
  *
package/dist/Inspector.js CHANGED
@@ -240,7 +240,7 @@ const inspectors = new WeakMap();
240
240
  * Starts watching a registry, and returns its inspector: the same one each time it is called for
241
241
  * the same registry.
242
242
  *
243
- * Until then a registry runs as it always does. From then on, in a registry made by Effect 4.0,
243
+ * Until then a registry runs as it always does. From then on, in a registry made by Effect 4.1,
244
244
  * each node reports what happens to it, which costs a little on every read and write, so call it
245
245
  * from developer tools rather than from the app.
246
246
  *
@@ -8,7 +8,10 @@ import { AtomRegistry } from "effect/reactivity";
8
8
  * Options for a registry created by `provideRegistry` or `RegistryProvider`: the options of
9
9
  * Effect's `AtomRegistry.make`, all optional.
10
10
  *
11
- * - `initialValues`: pairs of an atom and its starting value, such as `[[tokenAtom, token]]`.
11
+ * - `initialValues`: pairs of an atom and its starting value, such as `[[tokenAtom, token]]`. An
12
+ * entry can take options as a third element, as `Atom.initialValue(atom, value, options)` makes:
13
+ * `{ skipInitialRun: true }` keeps an effect or stream atom's value instead of running it on
14
+ * mount.
12
15
  * - `scheduleTask`: schedules the registry's deferred work, such as disposing of atoms nobody
13
16
  * reads. It takes a task and returns a function that cancels it.
14
17
  * - `defaultIdleTTL`: in milliseconds, how long an atom nobody reads is kept before it is disposed
@@ -55,7 +58,8 @@ export interface ProvideRegistryCommon {
55
58
  /**
56
59
  * Run server-rendered async atoms again once the page has hydrated. Defaults to `false`: the
57
60
  * server's value is milliseconds old. Children inherit it; the async hooks' own option overrides
58
- * it. `@effect/atom-react` runs atoms wrapped by `withReactivity` and similar again.
61
+ * it. `@effect/atom-react` runs every hydrated effect or stream atom again unless the atom sets
62
+ * `skipInitialRun`.
59
63
  */
60
64
  readonly revalidateOnHydrate?: boolean | undefined;
61
65
  }
@@ -26,6 +26,7 @@
26
26
  import { DEV } from "esm-env";
27
27
  import type { Snippet } from "svelte";
28
28
 
29
+ import { troubleshooting } from "./internal/troubleshooting.js";
29
30
  import { provideRegistry } from "./RegistryContext.js";
30
31
  import type { ProvideRegistryOptions } from "./RegistryContext.js";
31
32
 
@@ -50,7 +51,7 @@
50
51
  if (changed && !warned) {
51
52
  warned = true;
52
53
  console.warn(
53
- "effect-atom-svelte: RegistryProvider reads its props once, so the new `registry` or `revalidateOnHydrate` is ignored. Remount the provider, for example with {#key}, to apply it."
54
+ `effect-atom-svelte: RegistryProvider reads its props once, so the new \`registry\` or \`revalidateOnHydrate\` is ignored. Remount the provider, for example with {#key}, to apply it. ${troubleshooting("registryprovider-reads-its-props-once")}`
54
55
  );
55
56
  }
56
57
  });
@@ -1,4 +1,5 @@
1
1
  import { createContext } from "svelte";
2
+ import { troubleshooting } from "./internal/troubleshooting.js";
2
3
  /**
3
4
  * Marks a value as a `ScopedAtom`: every scoped atom has this key, set to this same string, as
4
5
  * Effect's own types carry a type id.
@@ -56,7 +57,7 @@ export const make = (f, options) => {
56
57
  const named = name !== undefined && name !== "";
57
58
  const which = named ? `ScopedAtom "${name}"` : "ScopedAtom";
58
59
  const call = named ? `${name}.provide()` : "its provide()";
59
- throw new Error(`${which} used outside of the component that provides it. Call ${call} in a parent component's script.`);
60
+ throw new Error(`${which} used outside of the component that provides it. Call ${call} in a parent component's script. ${troubleshooting("used-outside-of-the-component-that-provides-it")}`);
60
61
  }
61
62
  return get();
62
63
  },
@@ -1,3 +1,4 @@
1
+ import { AsyncResult, Atom } from "effect/reactivity";
1
2
  /**
2
3
  * The part of SvelteKit's `handleError` input that the hooks read. In SvelteKit 3, `kind` is
3
4
  * `"unknown"` for errors thrown by your code, `"app"` for `error(...)`, `"framework"` for
@@ -135,3 +136,90 @@ export interface UnsavedChangesGuardOptions {
135
136
  export declare const useUnsavedChangesGuard: (form: {
136
137
  readonly dirty: boolean;
137
138
  }, options: UnsavedChangesGuardOptions) => void;
139
+ /**
140
+ * The state SvelteKit keeps for a remote query in the browser: `current` holds the value once
141
+ * `ready` is `true`, `loading` is `true` while a fetch is in flight, and `error` is what the last
142
+ * fetch failed with.
143
+ *
144
+ * @stability unstable
145
+ * @since 0.5.0
146
+ * @category models
147
+ */
148
+ export type RemoteQueryState<A> = {
149
+ readonly error: App.Error | undefined;
150
+ readonly loading: boolean;
151
+ } & ({
152
+ readonly current: undefined;
153
+ readonly ready: false;
154
+ } | {
155
+ readonly current: A;
156
+ readonly ready: true;
157
+ });
158
+ /**
159
+ * What `remoteQueryAtom` reads from a remote `query`: SvelteKit's `RemoteQuery` from `$app/server`
160
+ * has these, and more.
161
+ *
162
+ * @stability unstable
163
+ * @since 0.5.0
164
+ * @category models
165
+ */
166
+ export type RemoteQueryLike<A> = PromiseLike<A> & RemoteQueryState<A> & {
167
+ readonly refresh: () => Promise<void>;
168
+ };
169
+ /**
170
+ * What `remoteQueryAtom` reads from a remote `query.live`: SvelteKit's `RemoteLiveQuery` from
171
+ * `$app/server` has these, and more.
172
+ *
173
+ * @stability unstable
174
+ * @since 0.5.0
175
+ * @category models
176
+ */
177
+ export type RemoteLiveQueryLike<A> = PromiseLike<A> & RemoteQueryState<A> & {
178
+ readonly reconnect: () => Promise<void>;
179
+ };
180
+ /**
181
+ * Turns a SvelteKit remote `query` or `query.live` into an atom of its result, which follows every
182
+ * change SvelteKit makes to the query: a refresh, a `.set()`, a command's single-flight update, an
183
+ * optimistic `withOverride` and a live push. Pass a function that calls the query, so the atom calls
184
+ * it in each server render and in the browser. Needs SvelteKit 3 with
185
+ * `experimental.remoteFunctions`.
186
+ *
187
+ * - *Server.* The render calls the query, so SvelteKit sends its result with the page and the
188
+ * browser starts from it without fetching again. Read the atom with `await useAtomResult` or
189
+ * `useAtomSuspense`: `useAtomValue` renders `Initial` on the server, and warns in development.
190
+ * Under a `<svelte:boundary>` with a `pending` snippet, the server renders that, and the browser
191
+ * fetches the query.
192
+ * - *Refresh.* `useAtomRefresh` and `registry.refresh` call the query's `refresh()`, or
193
+ * `reconnect()` for a live query, and the atom is `waiting` until the new value arrives.
194
+ * - *Failure.* A failure holds SvelteKit's `App.Error`, as `handleError` returned it in the
195
+ * browser. On the server it holds SvelteKit's default body, as the library can't run your hook,
196
+ * so a hook that adds fields to it changes the failure between the server's HTML and the browser.
197
+ * - *Arguments.* For a query that takes one, make a family:
198
+ * `Atom.family((id: string) => remoteQueryAtom(() => getTodo(id)))`.
199
+ *
200
+ * **Example** (A todo list from a remote query)
201
+ *
202
+ * ```ts
203
+ * // src/routes/todos/atoms.ts
204
+ * import { remoteQueryAtom } from "effect-atom-svelte/sveltekit";
205
+ * import { getTodos } from "./todos.remote.ts";
206
+ *
207
+ * export const todosAtom = remoteQueryAtom(() => getTodos());
208
+ * ```
209
+ *
210
+ * ```svelte
211
+ * <script lang="ts">
212
+ * import { useAtomRefresh, useAtomResult } from "effect-atom-svelte";
213
+ * import { todosAtom } from "./atoms.ts";
214
+ *
215
+ * const todos = await useAtomResult(todosAtom);
216
+ * const refresh = useAtomRefresh(todosAtom);
217
+ * </script>
218
+ * ```
219
+ *
220
+ * @see {@link https://atom.jarrednorris.dev/sveltekit#remote-queries-as-atoms | Remote queries as atoms}
221
+ * @stability unstable
222
+ * @since 0.5.0
223
+ * @category remote functions
224
+ */
225
+ export declare const remoteQueryAtom: <A>(query: () => RemoteQueryLike<A> | RemoteLiveQueryLike<A>) => Atom.Atom<AsyncResult.AsyncResult<A, App.Error>>;