effect-atom-svelte 0.4.1 → 0.5.1

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.
@@ -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
  *
@@ -140,16 +140,28 @@ export interface Inspector {
140
140
  * ```ts
141
141
  * import { getRegistry } from "effect-atom-svelte";
142
142
  * import { inspect } from "effect-atom-svelte/inspector";
143
+ * import type { Event } from "effect-atom-svelte/inspector";
144
+ * import { onMount } from "svelte";
143
145
  *
144
- * const events = [];
145
- * inspect(getRegistry()).subscribe((event) => events.push(event));
146
- * setInterval(() => {
147
- * for (const event of events.splice(0)) {
148
- * if (event._tag === "Built") {
149
- * console.log(event.node.atom.label?.[0], event.cause._tag);
146
+ * const registry = getRegistry();
147
+ *
148
+ * // In onMount, so the server's registries aren't watched.
149
+ * onMount(() => {
150
+ * const inspector = inspect(registry);
151
+ * const queued: Event[] = [];
152
+ * const stop = inspector.subscribe((event) => queued.push(event));
153
+ * const timer = setInterval(() => {
154
+ * for (const event of queued.splice(0)) {
155
+ * if (event._tag === "Built") {
156
+ * console.log(event.node.atom.label?.[0], event.cause._tag);
157
+ * }
150
158
  * }
151
- * }
152
- * }, 1000);
159
+ * }, 1000);
160
+ * return () => {
161
+ * stop();
162
+ * clearInterval(timer);
163
+ * };
164
+ * });
153
165
  * ```
154
166
  *
155
167
  * @stability unstable
@@ -256,8 +268,9 @@ export interface ScopeSnapshot {
256
268
  /**
257
269
  * An event a scope passes on: the inspector's `Event` for a node in the scope, with the node's
258
270
  * `id`, or `ScopeChanged` once its atoms, edges or hooks have changed, after the registry's work,
259
- * to take a new `snapshot()`. A node's `NodeAdded` arrives before the node is linked into the
260
- * scope, so it isn't passed on; the `ScopeChanged` that follows is.
271
+ * to take a new `snapshot()`. Calling `snapshot()` in the listener is safe on a `ScopeChanged`;
272
+ * the other events arrive while the registry is still updating. A node's `NodeAdded` arrives before
273
+ * the node is linked into the scope, so it isn't passed on; the `ScopeChanged` that follows is.
261
274
  *
262
275
  * @stability unstable
263
276
  * @since 0.2.0
@@ -307,11 +320,14 @@ export interface InspectorScope {
307
320
  * const scope = provideInspectorScope();
308
321
  * $effect(() =>
309
322
  * scope.subscribe((event) => {
310
- * if (event._tag === "ScopeChanged") {
311
- * draw(scope.snapshot());
312
- * } else if (event._tag === "Updated") {
313
- * pulse(event.id);
314
- * }
323
+ * // Draw on the next frame: a listener mustn't write Svelte state.
324
+ * requestAnimationFrame(() => {
325
+ * if (event._tag === "ScopeChanged") {
326
+ * draw(scope.snapshot());
327
+ * } else if (event._tag === "Updated") {
328
+ * pulse(event.id);
329
+ * }
330
+ * });
315
331
  * })
316
332
  * );
317
333
  * ```
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
  *
@@ -252,16 +252,28 @@ const inspectors = new WeakMap();
252
252
  * ```ts
253
253
  * import { getRegistry } from "effect-atom-svelte";
254
254
  * import { inspect } from "effect-atom-svelte/inspector";
255
+ * import type { Event } from "effect-atom-svelte/inspector";
256
+ * import { onMount } from "svelte";
255
257
  *
256
- * const events = [];
257
- * inspect(getRegistry()).subscribe((event) => events.push(event));
258
- * setInterval(() => {
259
- * for (const event of events.splice(0)) {
260
- * if (event._tag === "Built") {
261
- * console.log(event.node.atom.label?.[0], event.cause._tag);
258
+ * const registry = getRegistry();
259
+ *
260
+ * // In onMount, so the server's registries aren't watched.
261
+ * onMount(() => {
262
+ * const inspector = inspect(registry);
263
+ * const queued: Event[] = [];
264
+ * const stop = inspector.subscribe((event) => queued.push(event));
265
+ * const timer = setInterval(() => {
266
+ * for (const event of queued.splice(0)) {
267
+ * if (event._tag === "Built") {
268
+ * console.log(event.node.atom.label?.[0], event.cause._tag);
269
+ * }
262
270
  * }
263
- * }
264
- * }, 1000);
271
+ * }, 1000);
272
+ * return () => {
273
+ * stop();
274
+ * clearInterval(timer);
275
+ * };
276
+ * });
265
277
  * ```
266
278
  *
267
279
  * @stability unstable
@@ -538,11 +550,14 @@ class Scope {
538
550
  * const scope = provideInspectorScope();
539
551
  * $effect(() =>
540
552
  * scope.subscribe((event) => {
541
- * if (event._tag === "ScopeChanged") {
542
- * draw(scope.snapshot());
543
- * } else if (event._tag === "Updated") {
544
- * pulse(event.id);
545
- * }
553
+ * // Draw on the next frame: a listener mustn't write Svelte state.
554
+ * requestAnimationFrame(() => {
555
+ * if (event._tag === "ScopeChanged") {
556
+ * draw(scope.snapshot());
557
+ * } else if (event._tag === "Updated") {
558
+ * pulse(event.id);
559
+ * }
560
+ * });
546
561
  * })
547
562
  * );
548
563
  * ```
@@ -8,7 +8,11 @@ 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. The registry disposes of an atom nothing reads, starting value included, so give an
15
+ * atom that is read later `Atom.keepAlive`.
12
16
  * - `scheduleTask`: schedules the registry's deferred work, such as disposing of atoms nobody
13
17
  * reads. It takes a task and returns a function that cancels it.
14
18
  * - `defaultIdleTTL`: in milliseconds, how long an atom nobody reads is kept before it is disposed
@@ -23,7 +27,9 @@ import { AtomRegistry } from "effect/reactivity";
23
27
  */
24
28
  export type RegistryOptions = NonNullable<Parameters<typeof AtomRegistry.make>[0]>;
25
29
  /**
26
- * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`.
30
+ * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`. Call it while a
31
+ * component initializes, as Svelte reads context only then, and keep the registry it returns for
32
+ * later, such as for an event handler.
27
33
  *
28
34
  * In the browser a shared default registry is used when none is provided. On the server there is
29
35
  * no default: one module-level registry would share atom state between concurrent requests.
@@ -53,9 +59,12 @@ export declare const getRegistry: () => AtomRegistry.AtomRegistry;
53
59
  */
54
60
  export interface ProvideRegistryCommon {
55
61
  /**
56
- * Run server-rendered async atoms again once the page has hydrated. Defaults to `false`: the
57
- * 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.
62
+ * Run server-rendered async atoms again once the page has hydrated. Defaults to `false`: on a
63
+ * page rendered per request the server's result is milliseconds old. Set it on a prerendered
64
+ * page, whose results are as old as the build. It applies to atoms the hooks hydrate, not to a
65
+ * `HydrationBoundary`'s. Children inherit it; the async hooks' own option overrides it.
66
+ * `@effect/atom-react` runs every hydrated effect or stream atom again unless the atom sets
67
+ * `skipInitialRun`.
59
68
  */
60
69
  readonly revalidateOnHydrate?: boolean | undefined;
61
70
  }
@@ -14,7 +14,9 @@ import { troubleshooting } from "./internal/troubleshooting.js";
14
14
  const [getContextRegistry, setContextRegistry, hasContextRegistry] = createContext();
15
15
  let browserRegistry;
16
16
  /**
17
- * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`.
17
+ * Returns the registry from the nearest `provideRegistry` or `RegistryProvider`. Call it while a
18
+ * component initializes, as Svelte reads context only then, and keep the registry it returns for
19
+ * later, such as for an event handler.
18
20
  *
19
21
  * In the browser a shared default registry is used when none is provided. On the server there is
20
22
  * no default: one module-level registry would share atom state between concurrent requests.
@@ -4,7 +4,8 @@
4
4
  browser one per mount of the provider, disposed of when it unmounts. A root layout's provider
5
5
  stays mounted, so its registry lasts the whole visit. Takes the AtomRegistry.make options, or an
6
6
  existing `registry`, and `revalidateOnHydrate` to run server-rendered async atoms again once the
7
- page has hydrated.
7
+ page has hydrated. `revalidateOnHydrate` applies to atoms the hooks hydrate, not to a
8
+ `HydrationBoundary`'s.
8
9
 
9
10
  The props are read once, when the provider sets up: changing them later doesn't change the
10
11
  registry or create a new one. Development builds warn when `registry` or `revalidateOnHydrate`
@@ -26,6 +27,7 @@
26
27
  import { DEV } from "esm-env";
27
28
  import type { Snippet } from "svelte";
28
29
 
30
+ import { troubleshooting } from "./internal/troubleshooting.js";
29
31
  import { provideRegistry } from "./RegistryContext.js";
30
32
  import type { ProvideRegistryOptions } from "./RegistryContext.js";
31
33
 
@@ -50,7 +52,7 @@
50
52
  if (changed && !warned) {
51
53
  warned = true;
52
54
  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."
55
+ `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
56
  );
55
57
  }
56
58
  });
@@ -8,7 +8,8 @@ type Props = ProvideRegistryOptions & {
8
8
  * browser one per mount of the provider, disposed of when it unmounts. A root layout's provider
9
9
  * stays mounted, so its registry lasts the whole visit. Takes the AtomRegistry.make options, or an
10
10
  * existing `registry`, and `revalidateOnHydrate` to run server-rendered async atoms again once the
11
- * page has hydrated.
11
+ * page has hydrated. `revalidateOnHydrate` applies to atoms the hooks hydrate, not to a
12
+ * `HydrationBoundary`'s.
12
13
  *
13
14
  * The props are read once, when the provider sets up: changing them later doesn't change the
14
15
  * registry or create a new one. Development builds warn when `registry` or `revalidateOnHydrate`
@@ -50,8 +50,9 @@ export interface MakeOptions {
50
50
  * Creates a scoped atom from a factory, which runs once per providing component.
51
51
  *
52
52
  * Each provider gets its own atom, so a factory that makes a serializable atom gives every copy of
53
- * one input the same key, and two such providers on a server-rendered page make the render throw:
54
- * two different atoms share the serialization key. For a value from the server, return a family's
53
+ * one input the same key: two providers given the same input make two atoms with one key, and the
54
+ * server render throws once both are read with `useAtomResult` or `useAtomSuspense`. For a value
55
+ * from the server, return a family's
55
56
  * atom instead, `ScopedAtom.make((id: string) => userAtom(id))`, so every provider of one input
56
57
  * holds the same atom.
57
58
  *
@@ -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.
@@ -12,8 +13,9 @@ export const TypeId = "~effect-atom-svelte/ScopedAtom";
12
13
  * Creates a scoped atom from a factory, which runs once per providing component.
13
14
  *
14
15
  * Each provider gets its own atom, so a factory that makes a serializable atom gives every copy of
15
- * one input the same key, and two such providers on a server-rendered page make the render throw:
16
- * two different atoms share the serialization key. For a value from the server, return a family's
16
+ * one input the same key: two providers given the same input make two atoms with one key, and the
17
+ * server render throws once both are read with `useAtomResult` or `useAtomSuspense`. For a value
18
+ * from the server, return a family's
17
19
  * atom instead, `ScopedAtom.make((id: string) => userAtom(id))`, so every provider of one input
18
20
  * holds the same atom.
19
21
  *
@@ -56,7 +58,7 @@ export const make = (f, options) => {
56
58
  const named = name !== undefined && name !== "";
57
59
  const which = named ? `ScopedAtom "${name}"` : "ScopedAtom";
58
60
  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.`);
61
+ 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
62
  }
61
63
  return get();
62
64
  },
@@ -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
@@ -31,6 +32,11 @@ export interface EffectErrorBody {
31
32
  /**
32
33
  * SvelteKit 2's `handleError` input: no `kind`, and always a message, which the hooks fall back on.
33
34
  *
35
+ * The hooks take the fields of SvelteKit's input they read and return the fields they set, so they
36
+ * type-check against `HandleClientError` and `HandleServerError` once `App.Error` declares
37
+ * `tag?: string`. In SvelteKit 2, whose `App.Error` requires a message, they are typed to return
38
+ * one for this input, as they then always set one.
39
+ *
34
40
  * @stability unstable
35
41
  * @since 0.2.1
36
42
  * @category models
@@ -72,8 +78,8 @@ export declare function handleClientError(input: CaughtError): EffectErrorBody |
72
78
  /**
73
79
  * A server `handleError` hook (`src/hooks.server.ts`) that keeps the `_tag` of errors thrown by
74
80
  * your code but not their message, which could expose details of the server to users: the
75
- * message stays SvelteKit's `"Internal Error"`. It logs errors with `console.error`.
76
- * Server errors reach a boundary's `failed` snippet when it renders on the server. Made for
81
+ * message stays SvelteKit's `"Internal Error"`. It logs each error with `console.error`, and the
82
+ * error reaches a boundary's `failed` snippet when that boundary renders on the server. Made for
77
83
  * SvelteKit 3: SvelteKit 2 doesn't say which errors are its own, so there every error is logged.
78
84
  *
79
85
  * **Example** (Using it as the server hook)
@@ -127,7 +133,6 @@ export interface UnsavedChangesGuardOptions {
127
133
  * });
128
134
  * ```
129
135
  *
130
- * @see {@link https://atom.jarrednorris.dev/forms | Forms}
131
136
  * @stability unstable
132
137
  * @since 0.4.0
133
138
  * @category forms
@@ -135,3 +140,89 @@ export interface UnsavedChangesGuardOptions {
135
140
  export declare const useUnsavedChangesGuard: (form: {
136
141
  readonly dirty: boolean;
137
142
  }, options: UnsavedChangesGuardOptions) => void;
143
+ /**
144
+ * The state SvelteKit keeps for a remote query in the browser: `current` holds the value once
145
+ * `ready` is `true`, `loading` is `true` while a fetch is in flight, and `error` is what the last
146
+ * fetch failed with.
147
+ *
148
+ * @stability unstable
149
+ * @since 0.5.0
150
+ * @category models
151
+ */
152
+ export type RemoteQueryState<A> = {
153
+ readonly error: App.Error | undefined;
154
+ readonly loading: boolean;
155
+ } & ({
156
+ readonly current: undefined;
157
+ readonly ready: false;
158
+ } | {
159
+ readonly current: A;
160
+ readonly ready: true;
161
+ });
162
+ /**
163
+ * What `remoteQueryAtom` reads from a remote `query`: SvelteKit's `RemoteQuery` from `$app/server`
164
+ * has these, and more.
165
+ *
166
+ * @stability unstable
167
+ * @since 0.5.0
168
+ * @category models
169
+ */
170
+ export type RemoteQueryLike<A> = PromiseLike<A> & RemoteQueryState<A> & {
171
+ readonly refresh: () => Promise<void>;
172
+ };
173
+ /**
174
+ * What `remoteQueryAtom` reads from a remote `query.live`: SvelteKit's `RemoteLiveQuery` from
175
+ * `$app/server` has these, and more.
176
+ *
177
+ * @stability unstable
178
+ * @since 0.5.0
179
+ * @category models
180
+ */
181
+ export type RemoteLiveQueryLike<A> = PromiseLike<A> & RemoteQueryState<A> & {
182
+ readonly reconnect: () => Promise<void>;
183
+ };
184
+ /**
185
+ * Turns a SvelteKit remote `query` or `query.live` into an atom of its result, which follows every
186
+ * change SvelteKit makes to the query: a refresh, a `.set()`, a command's single-flight update, an
187
+ * optimistic `withOverride` and a live push. Pass a function that calls the query, so the atom calls
188
+ * it in each server render and in the browser. Needs SvelteKit 3 with
189
+ * `experimental.remoteFunctions`.
190
+ *
191
+ * - *Server.* The render calls the query, so SvelteKit sends its result with the page and the
192
+ * browser starts from it without fetching again. Read the atom with `await useAtomResult` or
193
+ * `useAtomSuspense`: `useAtomValue` renders `Initial` on the server, and warns in development.
194
+ * Under a `<svelte:boundary>` with a `pending` snippet, the server renders that, and the browser
195
+ * fetches the query.
196
+ * - *Refresh.* `useAtomRefresh` and `registry.refresh` call the query's `refresh()`, or
197
+ * `reconnect()` for a live query, and the atom is `waiting` until the new value arrives.
198
+ * - *Failure.* A failure holds SvelteKit's `App.Error`, as `handleError` returned it in the
199
+ * browser. On the server it holds SvelteKit's default body, as the library can't run your hook,
200
+ * so a hook that adds fields to it changes the failure between the server's HTML and the browser.
201
+ * - *Arguments.* For a query that takes one, make a family:
202
+ * `Atom.family((id: string) => remoteQueryAtom(() => getTodo(id)))`.
203
+ *
204
+ * **Example** (A todo list from a remote query)
205
+ *
206
+ * ```ts
207
+ * // src/routes/todos/atoms.ts
208
+ * import { remoteQueryAtom } from "effect-atom-svelte/sveltekit";
209
+ * import { getTodos } from "./todos.remote.ts";
210
+ *
211
+ * export const todosAtom = remoteQueryAtom(() => getTodos());
212
+ * ```
213
+ *
214
+ * ```svelte
215
+ * <script lang="ts">
216
+ * import { useAtomRefresh, useAtomResult } from "effect-atom-svelte";
217
+ * import { todosAtom } from "./atoms.ts";
218
+ *
219
+ * const todos = await useAtomResult(todosAtom);
220
+ * const refresh = useAtomRefresh(todosAtom);
221
+ * </script>
222
+ * ```
223
+ *
224
+ * @stability unstable
225
+ * @since 0.5.0
226
+ * @category remote functions
227
+ */
228
+ export declare const remoteQueryAtom: <A>(query: () => RemoteQueryLike<A> | RemoteLiveQueryLike<A>) => Atom.Atom<AsyncResult.AsyncResult<A, App.Error>>;
package/dist/SvelteKit.js CHANGED
@@ -2,19 +2,24 @@
2
2
  * SvelteKit helpers. Import them from `effect-atom-svelte/sveltekit`.
3
3
  *
4
4
  * `handleClientError` and `handleServerError` are `handleError` hooks that keep an Effect error's
5
- * `_tag`, so a `<svelte:boundary>` `failed` snippet can tell typed errors apart. They take the
6
- * fields of SvelteKit's input they read and return the fields they set, so they type-check against
7
- * `HandleClientError` and `HandleServerError` once `App.Error` declares `tag?: string`. In
8
- * SvelteKit 2, whose `App.Error` requires a message, they are typed to return one when there is no
9
- * `kind`, as they then always set one.
5
+ * `_tag`, so a `<svelte:boundary>` `failed` snippet can tell typed errors apart.
10
6
  *
11
7
  * `useUnsavedChangesGuard` asks before leaving a page with a dirty form.
12
8
  *
9
+ * `remoteQueryAtom` turns a SvelteKit remote `query` or `query.live` into an atom that follows it.
10
+ *
13
11
  * @since 0.1.0
14
12
  */
15
- /// <reference types="@sveltejs/kit" />
16
13
  import { beforeNavigate, goto } from "$app/navigation";
17
- import { Effect } from "effect";
14
+ import { isHttpError, VERSION } from "@sveltejs/kit";
15
+ import { Cause, Effect, Option } from "effect";
16
+ import { AsyncResult, Atom } from "effect/reactivity";
17
+ import { BROWSER } from "esm-env";
18
+ import { untrack } from "svelte";
19
+ import { follow } from "./internal/follow.svelte.js";
20
+ import { assertSupportedKit } from "./internal/kitVersion.js";
21
+ import { markRemoteQueryAtom } from "./internal/remoteQueries.js";
22
+ import { troubleshooting } from "./internal/troubleshooting.js";
18
23
  const tagOf = (error) => {
19
24
  if (typeof error !== "object" || error === null || !("_tag" in error)) {
20
25
  return undefined;
@@ -103,7 +108,6 @@ const bypassFor = 2000;
103
108
  * });
104
109
  * ```
105
110
  *
106
- * @see {@link https://atom.jarrednorris.dev/forms | Forms}
107
111
  * @stability unstable
108
112
  * @since 0.4.0
109
113
  * @category forms
@@ -167,3 +171,159 @@ export const useUnsavedChangesGuard = (form, options) => {
167
171
  })();
168
172
  });
169
173
  };
174
+ const notAQuery = (value) => {
175
+ const returned = typeof value === "object" && value !== null && "ready" in value
176
+ ? "a resource without refresh or reconnect, as from a prerender function"
177
+ : Object.prototype.toString.call(value);
178
+ return new Error(`remoteQueryAtom's function must return a remote query or query.live, as in remoteQueryAtom(() => getTodos()), and it returned ${returned}. ${troubleshooting("remotequeryatoms-function-must-return-a-remote-query")}`);
179
+ };
180
+ // A remote query or query.live has its state fields and a way to fetch again; a prerender
181
+ // function's result has no refresh.
182
+ const isRemoteResource = (value) => {
183
+ if (typeof value !== "object" || value === null) {
184
+ return false;
185
+ }
186
+ return "ready" in value && ("refresh" in value || "reconnect" in value);
187
+ };
188
+ const checked = (value) => {
189
+ if (!isRemoteResource(value)) {
190
+ throw notAQuery(value);
191
+ }
192
+ return value;
193
+ };
194
+ // SvelteKit's own body for an error, when its `handleError` hook adds nothing: an `error(...)`'s
195
+ // body, or a 500. The hook can't be run from here, so this is what the server render holds.
196
+ const defaultBody = (error) => isHttpError(error) ? error.body : { message: "Internal Error", status: 500 };
197
+ // The query's state, as a result. An error wins over a value: SvelteKit keeps the last value when a
198
+ // refresh fails, and that value becomes the failure's previous success.
199
+ const toResult = (resource) => {
200
+ const { error, loading } = resource;
201
+ if (error !== undefined) {
202
+ return AsyncResult.fail(error, {
203
+ previousSuccess: resource.ready
204
+ ? Option.some(AsyncResult.success(resource.current))
205
+ : Option.none(),
206
+ waiting: loading,
207
+ });
208
+ }
209
+ if (!resource.ready) {
210
+ return AsyncResult.initial(loading);
211
+ }
212
+ return AsyncResult.success(resource.current, { waiting: loading });
213
+ };
214
+ // Whether two results show the same state, so a run of the effect that changed nothing the atom
215
+ // holds doesn't notify its readers.
216
+ const sameResult = (a, b) => {
217
+ if (a._tag !== b._tag || a.waiting !== b.waiting) {
218
+ return false;
219
+ }
220
+ if (a._tag === "Success" && b._tag === "Success") {
221
+ return a.value === b.value;
222
+ }
223
+ if (a._tag === "Failure" && b._tag === "Failure") {
224
+ return (Cause.squash(a.cause) === Cause.squash(b.cause) &&
225
+ Option.getOrUndefined(a.previousSuccess)?.value ===
226
+ Option.getOrUndefined(b.previousSuccess)?.value);
227
+ }
228
+ return true;
229
+ };
230
+ const refreshQuery = (resource) => {
231
+ if ("refresh" in resource) {
232
+ void resource.refresh();
233
+ }
234
+ else {
235
+ void resource.reconnect();
236
+ }
237
+ };
238
+ /**
239
+ * Turns a SvelteKit remote `query` or `query.live` into an atom of its result, which follows every
240
+ * change SvelteKit makes to the query: a refresh, a `.set()`, a command's single-flight update, an
241
+ * optimistic `withOverride` and a live push. Pass a function that calls the query, so the atom calls
242
+ * it in each server render and in the browser. Needs SvelteKit 3 with
243
+ * `experimental.remoteFunctions`.
244
+ *
245
+ * - *Server.* The render calls the query, so SvelteKit sends its result with the page and the
246
+ * browser starts from it without fetching again. Read the atom with `await useAtomResult` or
247
+ * `useAtomSuspense`: `useAtomValue` renders `Initial` on the server, and warns in development.
248
+ * Under a `<svelte:boundary>` with a `pending` snippet, the server renders that, and the browser
249
+ * fetches the query.
250
+ * - *Refresh.* `useAtomRefresh` and `registry.refresh` call the query's `refresh()`, or
251
+ * `reconnect()` for a live query, and the atom is `waiting` until the new value arrives.
252
+ * - *Failure.* A failure holds SvelteKit's `App.Error`, as `handleError` returned it in the
253
+ * browser. On the server it holds SvelteKit's default body, as the library can't run your hook,
254
+ * so a hook that adds fields to it changes the failure between the server's HTML and the browser.
255
+ * - *Arguments.* For a query that takes one, make a family:
256
+ * `Atom.family((id: string) => remoteQueryAtom(() => getTodo(id)))`.
257
+ *
258
+ * **Example** (A todo list from a remote query)
259
+ *
260
+ * ```ts
261
+ * // src/routes/todos/atoms.ts
262
+ * import { remoteQueryAtom } from "effect-atom-svelte/sveltekit";
263
+ * import { getTodos } from "./todos.remote.ts";
264
+ *
265
+ * export const todosAtom = remoteQueryAtom(() => getTodos());
266
+ * ```
267
+ *
268
+ * ```svelte
269
+ * <script lang="ts">
270
+ * import { useAtomRefresh, useAtomResult } from "effect-atom-svelte";
271
+ * import { todosAtom } from "./atoms.ts";
272
+ *
273
+ * const todos = await useAtomResult(todosAtom);
274
+ * const refresh = useAtomRefresh(todosAtom);
275
+ * </script>
276
+ * ```
277
+ *
278
+ * @stability unstable
279
+ * @since 0.5.0
280
+ * @category remote functions
281
+ */
282
+ export const remoteQueryAtom = (query) => {
283
+ assertSupportedKit(VERSION);
284
+ const atom = BROWSER
285
+ ? Atom.readable((get) => {
286
+ const resource = checked(query());
287
+ // Read untracked, so a reactive context the registry reads this in doesn't follow the query.
288
+ let last = untrack(() => toResult(resource));
289
+ let live = true;
290
+ const sync = () => {
291
+ if (!live) {
292
+ return;
293
+ }
294
+ const next = untrack(() => toResult(resource));
295
+ if (!sameResult(last, next)) {
296
+ last = next;
297
+ get.setSelf(next);
298
+ }
299
+ };
300
+ const stop = follow(() => toResult(resource), sync);
301
+ // A navigation renders the next page in a fork, whose effects wait for it to commit, while
302
+ // the fork waits for this atom: settle a pending first result through the query's promise.
303
+ if (last._tag === "Initial" || last.waiting) {
304
+ // A failed fetch is in the query's state too, so either way sync reads it from there.
305
+ Effect.runFork(Effect.promise(() => Promise.resolve(resource)).pipe(Effect.exit, Effect.andThen(Effect.sync(sync))));
306
+ }
307
+ get.addFinalizer(() => {
308
+ live = false;
309
+ stop();
310
+ });
311
+ return last;
312
+ },
313
+ // Asks SvelteKit to fetch again, rather than building the atom again.
314
+ () => {
315
+ refreshQuery(checked(query()));
316
+ })
317
+ : Atom.make(
318
+ // Called as the render reads the atom, so SvelteKit sends the result with the page. A
319
+ // function that returns no query is a defect, not the query's failure.
320
+ Effect.suspend(() => {
321
+ const resource = checked(query());
322
+ return Effect.tryPromise({
323
+ catch: defaultBody,
324
+ try: () => Promise.resolve(resource),
325
+ });
326
+ }));
327
+ markRemoteQueryAtom(atom);
328
+ return atom;
329
+ };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, scoped atoms,
3
- * and Effect Atom's own modules.
2
+ * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, forms, scoped
3
+ * atoms, and Effect Atom's own modules.
4
4
  *
5
5
  * @since 0.1.0
6
6
  */
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, scoped atoms,
3
- * and Effect Atom's own modules.
2
+ * Svelte 5 bindings for Effect Atom: the hooks, components and registry an app uses, forms, scoped
3
+ * atoms, and Effect Atom's own modules.
4
4
  *
5
5
  * @since 0.1.0
6
6
  */
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Runs `read` in a pre effect of its own root, so it is owned by no component, and calls `changed`
3
+ * after every run, untracked. Returns the function that stops it. The effect's first run waits for
4
+ * Svelte's next flush, and during a navigation's fork for the fork to commit, so a caller that needs
5
+ * a value sooner reads it itself.
6
+ */
7
+ export declare const follow: (read: () => void, changed: () => void) => (() => void);
@@ -0,0 +1,15 @@
1
+ // Follows Svelte state that lives outside any component, such as a SvelteKit remote query's.
2
+ // Internal: not exported from the package.
3
+ import { untrack } from "svelte";
4
+ /**
5
+ * Runs `read` in a pre effect of its own root, so it is owned by no component, and calls `changed`
6
+ * after every run, untracked. Returns the function that stops it. The effect's first run waits for
7
+ * Svelte's next flush, and during a navigation's fork for the fork to commit, so a caller that needs
8
+ * a value sooner reads it itself.
9
+ */
10
+ export const follow = (read, changed) => $effect.root(() => {
11
+ $effect.pre(() => {
12
+ read();
13
+ untrack(changed);
14
+ });
15
+ });