effect-atom-svelte 0.4.0 → 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/dist/SvelteKit.js CHANGED
@@ -10,11 +10,20 @@
10
10
  *
11
11
  * `useUnsavedChangesGuard` asks before leaving a page with a dirty form.
12
12
  *
13
+ * `remoteQueryAtom` turns a SvelteKit remote `query` or `query.live` into an atom that follows it.
14
+ *
13
15
  * @since 0.1.0
14
16
  */
15
- /// <reference types="@sveltejs/kit" />
16
17
  import { beforeNavigate, goto } from "$app/navigation";
17
- import { Effect } from "effect";
18
+ import { isHttpError, VERSION } from "@sveltejs/kit";
19
+ import { Cause, Effect, Option } from "effect";
20
+ import { AsyncResult, Atom } from "effect/reactivity";
21
+ import { BROWSER } from "esm-env";
22
+ import { untrack } from "svelte";
23
+ import { follow } from "./internal/follow.svelte.js";
24
+ import { assertSupportedKit } from "./internal/kitVersion.js";
25
+ import { markRemoteQueryAtom } from "./internal/remoteQueries.js";
26
+ import { troubleshooting } from "./internal/troubleshooting.js";
18
27
  const tagOf = (error) => {
19
28
  if (typeof error !== "object" || error === null || !("_tag" in error)) {
20
29
  return undefined;
@@ -167,3 +176,160 @@ export const useUnsavedChangesGuard = (form, options) => {
167
176
  })();
168
177
  });
169
178
  };
179
+ const notAQuery = (value) => {
180
+ const returned = typeof value === "object" && value !== null && "ready" in value
181
+ ? "a resource without refresh or reconnect, as from a prerender function"
182
+ : Object.prototype.toString.call(value);
183
+ 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")}`);
184
+ };
185
+ // A remote query or query.live has its state fields and a way to fetch again; a prerender
186
+ // function's result has no refresh.
187
+ const isRemoteResource = (value) => {
188
+ if (typeof value !== "object" || value === null) {
189
+ return false;
190
+ }
191
+ return "ready" in value && ("refresh" in value || "reconnect" in value);
192
+ };
193
+ const checked = (value) => {
194
+ if (!isRemoteResource(value)) {
195
+ throw notAQuery(value);
196
+ }
197
+ return value;
198
+ };
199
+ // SvelteKit's own body for an error, when its `handleError` hook adds nothing: an `error(...)`'s
200
+ // body, or a 500. The hook can't be run from here, so this is what the server render holds.
201
+ const defaultBody = (error) => isHttpError(error) ? error.body : { message: "Internal Error", status: 500 };
202
+ // The query's state, as a result. An error wins over a value: SvelteKit keeps the last value when a
203
+ // refresh fails, and that value becomes the failure's previous success.
204
+ const toResult = (resource) => {
205
+ const { error, loading } = resource;
206
+ if (error !== undefined) {
207
+ return AsyncResult.fail(error, {
208
+ previousSuccess: resource.ready
209
+ ? Option.some(AsyncResult.success(resource.current))
210
+ : Option.none(),
211
+ waiting: loading,
212
+ });
213
+ }
214
+ if (!resource.ready) {
215
+ return AsyncResult.initial(loading);
216
+ }
217
+ return AsyncResult.success(resource.current, { waiting: loading });
218
+ };
219
+ // Whether two results show the same state, so a run of the effect that changed nothing the atom
220
+ // holds doesn't notify its readers.
221
+ const sameResult = (a, b) => {
222
+ if (a._tag !== b._tag || a.waiting !== b.waiting) {
223
+ return false;
224
+ }
225
+ if (a._tag === "Success" && b._tag === "Success") {
226
+ return a.value === b.value;
227
+ }
228
+ if (a._tag === "Failure" && b._tag === "Failure") {
229
+ return (Cause.squash(a.cause) === Cause.squash(b.cause) &&
230
+ Option.getOrUndefined(a.previousSuccess)?.value ===
231
+ Option.getOrUndefined(b.previousSuccess)?.value);
232
+ }
233
+ return true;
234
+ };
235
+ const refreshQuery = (resource) => {
236
+ if ("refresh" in resource) {
237
+ void resource.refresh();
238
+ }
239
+ else {
240
+ void resource.reconnect();
241
+ }
242
+ };
243
+ /**
244
+ * Turns a SvelteKit remote `query` or `query.live` into an atom of its result, which follows every
245
+ * change SvelteKit makes to the query: a refresh, a `.set()`, a command's single-flight update, an
246
+ * optimistic `withOverride` and a live push. Pass a function that calls the query, so the atom calls
247
+ * it in each server render and in the browser. Needs SvelteKit 3 with
248
+ * `experimental.remoteFunctions`.
249
+ *
250
+ * - *Server.* The render calls the query, so SvelteKit sends its result with the page and the
251
+ * browser starts from it without fetching again. Read the atom with `await useAtomResult` or
252
+ * `useAtomSuspense`: `useAtomValue` renders `Initial` on the server, and warns in development.
253
+ * Under a `<svelte:boundary>` with a `pending` snippet, the server renders that, and the browser
254
+ * fetches the query.
255
+ * - *Refresh.* `useAtomRefresh` and `registry.refresh` call the query's `refresh()`, or
256
+ * `reconnect()` for a live query, and the atom is `waiting` until the new value arrives.
257
+ * - *Failure.* A failure holds SvelteKit's `App.Error`, as `handleError` returned it in the
258
+ * browser. On the server it holds SvelteKit's default body, as the library can't run your hook,
259
+ * so a hook that adds fields to it changes the failure between the server's HTML and the browser.
260
+ * - *Arguments.* For a query that takes one, make a family:
261
+ * `Atom.family((id: string) => remoteQueryAtom(() => getTodo(id)))`.
262
+ *
263
+ * **Example** (A todo list from a remote query)
264
+ *
265
+ * ```ts
266
+ * // src/routes/todos/atoms.ts
267
+ * import { remoteQueryAtom } from "effect-atom-svelte/sveltekit";
268
+ * import { getTodos } from "./todos.remote.ts";
269
+ *
270
+ * export const todosAtom = remoteQueryAtom(() => getTodos());
271
+ * ```
272
+ *
273
+ * ```svelte
274
+ * <script lang="ts">
275
+ * import { useAtomRefresh, useAtomResult } from "effect-atom-svelte";
276
+ * import { todosAtom } from "./atoms.ts";
277
+ *
278
+ * const todos = await useAtomResult(todosAtom);
279
+ * const refresh = useAtomRefresh(todosAtom);
280
+ * </script>
281
+ * ```
282
+ *
283
+ * @see {@link https://atom.jarrednorris.dev/sveltekit#remote-queries-as-atoms | Remote queries as atoms}
284
+ * @stability unstable
285
+ * @since 0.5.0
286
+ * @category remote functions
287
+ */
288
+ export const remoteQueryAtom = (query) => {
289
+ assertSupportedKit(VERSION);
290
+ const atom = BROWSER
291
+ ? Atom.readable((get) => {
292
+ const resource = checked(query());
293
+ // Read untracked, so a reactive context the registry reads this in doesn't follow the query.
294
+ let last = untrack(() => toResult(resource));
295
+ let live = true;
296
+ const sync = () => {
297
+ if (!live) {
298
+ return;
299
+ }
300
+ const next = untrack(() => toResult(resource));
301
+ if (!sameResult(last, next)) {
302
+ last = next;
303
+ get.setSelf(next);
304
+ }
305
+ };
306
+ const stop = follow(() => toResult(resource), sync);
307
+ // A navigation renders the next page in a fork, whose effects wait for it to commit, while
308
+ // the fork waits for this atom: settle a pending first result through the query's promise.
309
+ if (last._tag === "Initial" || last.waiting) {
310
+ // A failed fetch is in the query's state too, so either way sync reads it from there.
311
+ Effect.runFork(Effect.promise(() => Promise.resolve(resource)).pipe(Effect.exit, Effect.andThen(Effect.sync(sync))));
312
+ }
313
+ get.addFinalizer(() => {
314
+ live = false;
315
+ stop();
316
+ });
317
+ return last;
318
+ },
319
+ // Asks SvelteKit to fetch again, rather than building the atom again.
320
+ () => {
321
+ refreshQuery(checked(query()));
322
+ })
323
+ : Atom.make(
324
+ // Called as the render reads the atom, so SvelteKit sends the result with the page. A
325
+ // function that returns no query is a defect, not the query's failure.
326
+ Effect.suspend(() => {
327
+ const resource = checked(query());
328
+ return Effect.tryPromise({
329
+ catch: defaultBody,
330
+ try: () => Promise.resolve(resource),
331
+ });
332
+ }));
333
+ markRemoteQueryAtom(atom);
334
+ return atom;
335
+ };
@@ -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
+ });
@@ -9,5 +9,8 @@ export interface Constraints {
9
9
  readonly max?: number | undefined;
10
10
  readonly pattern?: string | undefined;
11
11
  }
12
- /** The HTML constraints for the field at `path` in `schema`'s AST. */
13
- export declare const constraintsAt: (root: SchemaAST.AST, path: IndexPath) => Constraints;
12
+ /**
13
+ * The HTML constraints for the field at `path` in `schema`'s AST. `lengthAt` gives the length of the
14
+ * array at a path, read only for a tuple with elements after its rest.
15
+ */
16
+ export declare const constraintsAt: (root: SchemaAST.AST, path: IndexPath, lengthAt: (path: IndexPath) => number | undefined) => Constraints;
@@ -104,13 +104,31 @@ const unwrap = (ast) => {
104
104
  }
105
105
  return ast;
106
106
  };
107
+ // The element at `index`, picked as Effect's parser picks it (`Arrays.getParser` in `SchemaAST.ts`):
108
+ // a fixed element, else the rest element, except that the elements after the rest are counted back
109
+ // from the array's end. Those need its length; without one, there is no element.
110
+ const elementAt = (node, index, length) => {
111
+ if (index < node.elements.length) {
112
+ return node.elements[index];
113
+ }
114
+ const [rest, ...tail] = node.rest;
115
+ if (tail.length === 0) {
116
+ return rest;
117
+ }
118
+ const len = length();
119
+ if (len === undefined) {
120
+ return undefined;
121
+ }
122
+ const threshold = Math.max(node.elements.length, len - tail.length);
123
+ return index >= threshold ? tail[index - threshold] : rest;
124
+ };
107
125
  // The field at one step below `ast`, with whether its key is optional. In a union, the first member
108
126
  // that has the step.
109
- const step = (ast, segment) => {
127
+ const step = (ast, segment, length) => {
110
128
  const node = unwrap(ast);
111
129
  if (SchemaAST.isUnion(node)) {
112
130
  for (const member of node.types) {
113
- const found = step(member, segment);
131
+ const found = step(member, segment, length);
114
132
  if (found !== undefined) {
115
133
  return found;
116
134
  }
@@ -124,7 +142,7 @@ const step = (ast, segment) => {
124
142
  : { ast: property.type, optional: SchemaAST.isOptional(property.type) };
125
143
  }
126
144
  if (SchemaAST.isArrays(node) && typeof segment === "number") {
127
- const element = node.elements[segment] ?? node.rest[0];
145
+ const element = elementAt(node, segment, length);
128
146
  return element === undefined
129
147
  ? undefined
130
148
  : { ast: element, optional: SchemaAST.isOptional(element) };
@@ -139,19 +157,13 @@ const withoutUndefined = (ast) => {
139
157
  const types = ast.types.filter((member) => member._tag !== "Undefined");
140
158
  return types.length === 1 && types[0] !== undefined ? types[0] : ast;
141
159
  };
142
- /** The HTML constraints for the field at `path` in `schema`'s AST. */
143
- export const constraintsAt = (root, path) => {
144
- let found = {
145
- ast: root,
146
- optional: false,
147
- };
148
- for (const segment of path) {
149
- found &&= step(found.ast, segment);
150
- }
151
- if (found === undefined) {
152
- return {};
153
- }
154
- const { ast, optional } = found;
160
+ // A field's constraints depend only on its node and whether its key is optional, so each is read once.
161
+ const cache = {
162
+ optional: new WeakMap(),
163
+ required: new WeakMap(),
164
+ };
165
+ const none = {};
166
+ const read = (ast, optional) => {
155
167
  const into = {};
156
168
  readNode(withoutUndefined(ast), into);
157
169
  // `required` means "not empty" to a browser, so it is set only where the Schema rejects an empty
@@ -164,3 +176,27 @@ export const constraintsAt = (root, path) => {
164
176
  merge(out, into);
165
177
  return out;
166
178
  };
179
+ /**
180
+ * The HTML constraints for the field at `path` in `schema`'s AST. `lengthAt` gives the length of the
181
+ * array at a path, read only for a tuple with elements after its rest.
182
+ */
183
+ export const constraintsAt = (root, path, lengthAt) => {
184
+ let found = {
185
+ ast: root,
186
+ optional: false,
187
+ };
188
+ for (const [depth, segment] of path.entries()) {
189
+ found &&= step(found.ast, segment, () => lengthAt(path.slice(0, depth)));
190
+ }
191
+ if (found === undefined) {
192
+ return none;
193
+ }
194
+ const { ast, optional } = found;
195
+ const byNode = optional ? cache.optional : cache.required;
196
+ let constraints = byNode.get(ast);
197
+ if (constraints === undefined) {
198
+ constraints = read(ast, optional);
199
+ byNode.set(ast, constraints);
200
+ }
201
+ return constraints;
202
+ };