@loozo/angular-launch 0.0.5 → 0.0.6

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.
Files changed (47) hide show
  1. package/README.md +463 -42
  2. package/channel.d.ts +53 -0
  3. package/channel.js +231 -0
  4. package/client.d.ts +50 -10
  5. package/connect.d.ts +201 -0
  6. package/connect.js +148 -0
  7. package/generated.d.ts +1 -1
  8. package/generated.js +86 -3
  9. package/generation/index.js +25 -9
  10. package/index.d.ts +6 -1
  11. package/index.js +2 -0
  12. package/json.d.ts +9 -0
  13. package/json.js +24 -0
  14. package/navigation.d.ts +36 -0
  15. package/navigation.js +47 -0
  16. package/node/index.d.ts +57 -0
  17. package/node/index.js +175 -0
  18. package/outcomes.d.ts +55 -0
  19. package/outcomes.js +100 -0
  20. package/package.json +9 -3
  21. package/server/backend.d.ts +42 -23
  22. package/server/backend.js +127 -48
  23. package/server/channel-messages.d.ts +54 -0
  24. package/server/channel-messages.js +84 -0
  25. package/server/channel-socket.d.ts +67 -0
  26. package/server/channel-socket.js +322 -0
  27. package/server/definitions.d.ts +152 -24
  28. package/server/definitions.js +13 -5
  29. package/server/dispatch.d.ts +62 -11
  30. package/server/dispatch.js +156 -36
  31. package/server/event-stream.d.ts +63 -0
  32. package/server/event-stream.js +173 -0
  33. package/server/generated.d.ts +1 -0
  34. package/server/generated.js +1 -0
  35. package/server/index.d.ts +4 -2
  36. package/server/index.js +1 -1
  37. package/server/outcomes.d.ts +51 -2
  38. package/server/outcomes.js +58 -4
  39. package/server/response-effects.d.ts +105 -0
  40. package/server/response-effects.js +78 -0
  41. package/server/upgrade.d.ts +58 -0
  42. package/server/upgrade.js +117 -0
  43. package/stream.d.ts +31 -0
  44. package/stream.js +159 -0
  45. package/tanstack-query/README.md +101 -9
  46. package/tanstack-query/generated.js +5 -2
  47. package/tanstack-query/queries.d.ts +8 -6
@@ -0,0 +1,117 @@
1
+ import { parseJson } from "../json.js";
2
+ import { createChannelSocket } from "./channel-socket.js";
3
+ import { createRequestScope, crossSiteReason, dispatch, failure, hostAllowed, hostRefusal, invalidInput, response, responseHeaders, } from "./dispatch.js";
4
+ import { failureFrame } from "./event-stream.js";
5
+ import { createResponseEffects } from "./response-effects.js";
6
+ /** The `{ input }` envelope a channel's query carries, or `undefined` when it's malformed. */
7
+ function queryEnvelope(url) {
8
+ const entries = [...url.searchParams];
9
+ if (entries.length !== 1 || entries[0][0] !== "input") {
10
+ return undefined;
11
+ }
12
+ try {
13
+ return { input: parseJson(entries[0][1]) };
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ function upgrade(effects, accept) {
20
+ return { headers: responseHeaders({}, effects), accept };
21
+ }
22
+ // A call that failed before it started still upgrades, so the client sees its frame.
23
+ function refusedUpgrade(effects, reply) {
24
+ return upgrade(effects, (socket) => {
25
+ function fail() {
26
+ socket.send(failureFrame(reply));
27
+ socket.close(1000);
28
+ }
29
+ if (socket.readyState === 0) {
30
+ socket.addEventListener("open", fail, { once: true });
31
+ return;
32
+ }
33
+ fail();
34
+ });
35
+ }
36
+ /**
37
+ * Answers a websocket upgrade request for a channel, or returns `null` for any other
38
+ * request.
39
+ *
40
+ * @remarks
41
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
42
+ * `handleUpgrade` in `server.generated.ts`; call that instead.
43
+ *
44
+ * Any path starting with `/_rpc/` is a channel request. Before any context exists, the
45
+ * request is refused with an HTTP response, as `handleRequest` refuses RPCs: a plain-text 400
46
+ * `Host not allowed` when its hostname isn't in `allowedHosts`; `INVALID_INPUT` with no issues
47
+ * unless it's a `GET` with `Upgrade: websocket` and a query of exactly `input` holding JSON;
48
+ * and `FORBIDDEN` unless it's proven same-origin by `handleRequest`'s rules.
49
+ *
50
+ * A fresh context is then created and the call dispatched: `RPC_NOT_FOUND` for a path that
51
+ * isn't a channel, then group middleware, input validation, procedure middleware and the
52
+ * handler, which returns its iterable. From then on the result is an {@link Upgrade} carrying
53
+ * the call's headers and cookies; setting a cookie later throws. A failure before that,
54
+ * including a context factory that throws (`INTERNAL`), is an `Upgrade` too, whose socket
55
+ * receives the failure frame and closes with 1000.
56
+ *
57
+ * Until the socket is accepted the call's signal follows `request.signal`; a request that
58
+ * aborts before the handler is reached skips the handler, and one that aborts after it
59
+ * returned its iterable returns that iterator before its body ran. Either way the socket,
60
+ * if accepted, closes without a frame. Afterwards the signal follows the socket closing.
61
+ *
62
+ * @typeParam Definition - The application's context definition.
63
+ * @param registry - The application's RPC groups.
64
+ * @param application - The application binding.
65
+ * @param request - The upgrade request, as a web `Request`.
66
+ * @param options - The allowed hosts and further allowed origins.
67
+ * @returns A refusal response, the upgrade, or `null` when the path doesn't start with
68
+ * `/_rpc/`.
69
+ */
70
+ export async function handleChannelUpgrade(registry, application, request, { allowedHosts, origins = [] }) {
71
+ const url = new URL(request.url);
72
+ if (!url.pathname.startsWith("/_rpc/")) {
73
+ return null;
74
+ }
75
+ if (!hostAllowed(url.hostname, allowedHosts)) {
76
+ return hostRefusal(url.hostname);
77
+ }
78
+ const envelope = queryEnvelope(url);
79
+ if (request.method !== "GET" ||
80
+ request.headers.get("upgrade")?.toLowerCase() !== "websocket" ||
81
+ envelope === undefined) {
82
+ return response(invalidInput());
83
+ }
84
+ const crossSite = crossSiteReason(request, origins);
85
+ if (crossSite !== undefined) {
86
+ console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
87
+ return response(failure("FORBIDDEN"));
88
+ }
89
+ const effects = createResponseEffects();
90
+ const socket = createChannelSocket(request.signal);
91
+ let reply;
92
+ try {
93
+ const scope = await createRequestScope(application, request);
94
+ const started = Promise.withResolvers();
95
+ const outcome = dispatch(registry, url.pathname, envelope, scope, application, scope.request, "socket", socket.signal, effects, started.resolve, socket.inbox);
96
+ // Failures before the handler returned its iterable are frames on an upgraded socket.
97
+ const first = await Promise.race([outcome, started.promise]);
98
+ if ("iterator" in first) {
99
+ // The 101 carries the cookies; the rest of the call is the channel itself.
100
+ effects.commit();
101
+ socket.start(first, outcome);
102
+ return upgrade(effects, (accepted) => socket.accept(accepted));
103
+ }
104
+ // The caller left before the handler ran: nobody reads a frame, the socket just closes.
105
+ if (socket.signal.aborted) {
106
+ effects.commit();
107
+ return upgrade(effects, (accepted) => socket.accept(accepted));
108
+ }
109
+ reply = first;
110
+ }
111
+ catch (error) {
112
+ console.error("Launch context failed", error);
113
+ reply = failure("INTERNAL");
114
+ }
115
+ effects.commit();
116
+ return refusedUpgrade(effects, reply);
117
+ }
package/stream.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { RpcError, type ErrorMetadata, type StreamCallOptions } from "./client.js";
2
+ /**
3
+ * The rejection for a failure frame: an `RpcError` passed through `own`, an `RpcRedirect`
4
+ * or an `RpcNotFound`, or `undefined` when the frame is none of them.
5
+ *
6
+ * @remarks
7
+ * Internal. Streams and channels recognize their failure frames with it.
8
+ */
9
+ export declare function failureRejection(body: unknown, status: number, declared: readonly ErrorMetadata[], own: (error: RpcError<string, unknown>) => RpcError<string, unknown>): Error | undefined;
10
+ /**
11
+ * Runs one stream call over `fetch` and yields its values.
12
+ *
13
+ * @remarks
14
+ * Internal. Not `HttpClient`: every `HttpClient` request is an Angular pending task until
15
+ * it completes, and its fetch backend keeps the whole body, so an open stream would keep
16
+ * the app unstable and grow without bound.
17
+ *
18
+ * Ends after the `end` event. Throws an `RpcError`, passed through `own`, for an error
19
+ * event or a recognized error response, and an `RpcRedirect` or `RpcNotFound` for a
20
+ * redirect or not-found one; an `AbortError` when `signal` aborts; and a
21
+ * `TypeError` when the connection fails, the body ends without its `end` event or an
22
+ * event is malformed. Returning early, as `break` does, closes the request.
23
+ *
24
+ * @param url - The procedure's `/_rpc/<namespace>/<procedure>` path.
25
+ * @param input - The caller's input, or `null`.
26
+ * @param declared - The procedure's declared error metadata.
27
+ * @param own - Associates a converted error with its procedure for `isError`.
28
+ * @param options - The call options.
29
+ * @param opened - Called once the response turned out to be the stream's events.
30
+ */
31
+ export declare function openStream(url: string, input: unknown, declared: readonly ErrorMetadata[], own: (error: RpcError<string, unknown>) => RpcError<string, unknown>, { signal }: StreamCallOptions, opened?: () => void): AsyncGenerator<unknown, void, undefined>;
package/stream.js ADDED
@@ -0,0 +1,159 @@
1
+ import { RpcError, recognizedError } from "./client.js";
2
+ import { parseJson, serializeJson } from "./json.js";
3
+ import { recognizedOutcome } from "./outcomes.js";
4
+ /**
5
+ * Takes the complete events off the front of `buffer`, dropping comments.
6
+ *
7
+ * @param buffer - Text received so far and not yet taken.
8
+ * @param from - Where to look for the first event's end: no event ends before it.
9
+ * @throws TypeError for an event that isn't exactly an `event:` line and a `data:` line,
10
+ * which Launch servers never send.
11
+ */
12
+ function takeEvents(buffer, from) {
13
+ const events = [];
14
+ let rest = buffer;
15
+ let end = rest.indexOf("\n\n", from);
16
+ while (end !== -1) {
17
+ const lines = rest.slice(0, end).split("\n");
18
+ rest = rest.slice(end + 2);
19
+ end = rest.indexOf("\n\n");
20
+ if (lines.every((line) => line.startsWith(":"))) {
21
+ continue;
22
+ }
23
+ if (lines.length !== 2 || !lines[0].startsWith("event: ") || !lines[1].startsWith("data: ")) {
24
+ throw new TypeError("Launch stream sent a malformed event");
25
+ }
26
+ events.push({ name: lines[0].slice("event: ".length), data: lines[1].slice("data: ".length) });
27
+ }
28
+ return { events, rest };
29
+ }
30
+ /** Parses an event's data, which a Launch server always sends as strict JSON. */
31
+ function eventData(data) {
32
+ try {
33
+ return parseJson(data);
34
+ }
35
+ catch {
36
+ throw new TypeError("Launch stream sent an event whose data isn't JSON");
37
+ }
38
+ }
39
+ /**
40
+ * The rejection for a failure frame: an `RpcError` passed through `own`, an `RpcRedirect`
41
+ * or an `RpcNotFound`, or `undefined` when the frame is none of them.
42
+ *
43
+ * @remarks
44
+ * Internal. Streams and channels recognize their failure frames with it.
45
+ */
46
+ export function failureRejection(body, status, declared, own) {
47
+ const frame = recognizedError(body, status, declared);
48
+ if (frame) {
49
+ return own(new RpcError(frame.code, status, frame.data, frame.message));
50
+ }
51
+ return recognizedOutcome(body, status);
52
+ }
53
+ /**
54
+ * Runs one stream call over `fetch` and yields its values.
55
+ *
56
+ * @remarks
57
+ * Internal. Not `HttpClient`: every `HttpClient` request is an Angular pending task until
58
+ * it completes, and its fetch backend keeps the whole body, so an open stream would keep
59
+ * the app unstable and grow without bound.
60
+ *
61
+ * Ends after the `end` event. Throws an `RpcError`, passed through `own`, for an error
62
+ * event or a recognized error response, and an `RpcRedirect` or `RpcNotFound` for a
63
+ * redirect or not-found one; an `AbortError` when `signal` aborts; and a
64
+ * `TypeError` when the connection fails, the body ends without its `end` event or an
65
+ * event is malformed. Returning early, as `break` does, closes the request.
66
+ *
67
+ * @param url - The procedure's `/_rpc/<namespace>/<procedure>` path.
68
+ * @param input - The caller's input, or `null`.
69
+ * @param declared - The procedure's declared error metadata.
70
+ * @param own - Associates a converted error with its procedure for `isError`.
71
+ * @param options - The call options.
72
+ * @param opened - Called once the response turned out to be the stream's events.
73
+ */
74
+ export async function* openStream(url, input, declared, own, { signal }, opened = () => undefined) {
75
+ if (signal?.aborted) {
76
+ throw new DOMException("RPC stream aborted", "AbortError");
77
+ }
78
+ const request = new AbortController();
79
+ function abort() {
80
+ request.abort(new DOMException("RPC stream aborted", "AbortError"));
81
+ }
82
+ signal?.addEventListener("abort", abort, { once: true });
83
+ try {
84
+ const response = await fetch(url, {
85
+ method: "POST",
86
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
87
+ body: serializeJson({ input }),
88
+ signal: request.signal,
89
+ });
90
+ if (!response.ok) {
91
+ let body;
92
+ try {
93
+ body = await response.json();
94
+ }
95
+ catch (error) {
96
+ // Aborting while the body arrives isn't a transport failure.
97
+ if (request.signal.aborted) {
98
+ throw error;
99
+ }
100
+ throw new TypeError(`Launch stream request failed with status ${response.status}`);
101
+ }
102
+ const error = failureRejection(body, response.status, declared, own);
103
+ if (!error) {
104
+ throw new TypeError(`Launch stream request failed with status ${response.status}`);
105
+ }
106
+ throw error;
107
+ }
108
+ const mediaType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();
109
+ const isEventStream = mediaType === "text/event-stream";
110
+ if (!isEventStream || !response.body) {
111
+ throw new TypeError("Launch stream response isn't an event stream");
112
+ }
113
+ opened();
114
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
115
+ let buffer = "";
116
+ while (true) {
117
+ const chunk = await reader.read();
118
+ if (chunk.done) {
119
+ throw new TypeError("Launch stream ended without its end event");
120
+ }
121
+ // The rest holds no complete event, so one can only end in what just arrived.
122
+ const taken = takeEvents(buffer + chunk.value, Math.max(0, buffer.length - 1));
123
+ buffer = taken.rest;
124
+ for (const event of taken.events) {
125
+ // Events that arrived together aren't delivered after an abort.
126
+ if (signal?.aborted) {
127
+ throw new DOMException("RPC stream aborted", "AbortError");
128
+ }
129
+ if (event.name === "value") {
130
+ yield eventData(event.data);
131
+ continue;
132
+ }
133
+ if (event.name === "end" && event.data === "null") {
134
+ return;
135
+ }
136
+ if (event.name !== "error") {
137
+ throw new TypeError("Launch stream sent a malformed event");
138
+ }
139
+ const frame = eventData(event.data);
140
+ let error;
141
+ if (typeof frame === "object" && frame !== null && "status" in frame) {
142
+ const { status, ...body } = frame;
143
+ if (typeof status === "number") {
144
+ error = failureRejection(body, status, declared, own);
145
+ }
146
+ }
147
+ if (!error) {
148
+ throw new TypeError("Launch stream sent an unrecognized error");
149
+ }
150
+ throw error;
151
+ }
152
+ }
153
+ }
154
+ finally {
155
+ signal?.removeEventListener("abort", abort);
156
+ // Closes the request when iteration ended early, failed or the stream ended.
157
+ request.abort(new DOMException("RPC stream closed", "AbortError"));
158
+ }
159
+ }
@@ -116,7 +116,7 @@ Full query keys are tagged with the procedure's output type, so `client.getQuery
116
116
 
117
117
  ## Invalidation
118
118
 
119
- Nothing is invalidated for you. Invalidate in a mutation's `onSuccess`, by group, procedure or input:
119
+ Launch invalidates nothing itself; TanStack does, with the keys above. Invalidate in a mutation's `onSuccess`, by group, procedure or input:
120
120
 
121
121
  ```ts
122
122
  onSuccess: () => client.invalidateQueries({ queryKey: queries.todos.$key() }),
@@ -129,7 +129,96 @@ onSuccess: () =>
129
129
  client.invalidateQueries({ queryKey: queries.todos.$key() }, { throwOnError: true }),
130
130
  ```
131
131
 
132
- `mutateAsync` then rejects with the refetch's error, although the write itself succeeded.
132
+ `mutateAsync` then rejects with the refetch's error, although the write itself succeeded, and TanStack runs the mutation's `onError` for it. Don't combine this with an [optimistic update](#optimistic-updates): its rollback would undo a write that succeeded.
133
+
134
+ ### After every write
135
+
136
+ To read every Launch query on screen again after any write, give the `QueryClient` a `MutationCache`, as the example does:
137
+
138
+ ```ts
139
+ provideTanStackQuery(() => {
140
+ // Writes whose onSettled has run: their server call is done.
141
+ const settled = new WeakSet<object>();
142
+
143
+ return new QueryClient({
144
+ mutationCache: new MutationCache({
145
+ onSettled: (_data, _error, _input, _result, mutation, { client }) => {
146
+ settled.add(mutation);
147
+
148
+ const unsettled = client.getMutationCache().findAll({
149
+ mutationKey: ["launch"],
150
+ status: "pending",
151
+ predicate: (other) => !settled.has(other),
152
+ });
153
+
154
+ // A write still on its way reads for this one when it settles.
155
+ if (unsettled.length > 0) {
156
+ return undefined;
157
+ }
158
+
159
+ return client.invalidateQueries({ queryKey: ["launch"] });
160
+ },
161
+ }),
162
+ });
163
+ }),
164
+ ```
165
+
166
+ - Every Launch key starts with `"launch"`, so this matches every Launch query and mutation, of every group, and nothing else in the cache. Only active queries, ones a component observes, refetch; the others are marked stale and refetch when they next mount.
167
+ - `onSettled` also runs after a failed write, which can still mean the data changed: a declared `NOT_FOUND` for a todo deleted elsewhere does.
168
+ - TanStack awaits the cache's callbacks, before the mutation's own, so the mutation stays pending until the read finishes.
169
+ - Skipping while another write is still on its way keeps an earlier write's read from replacing a later write's optimistic data, and the last write reads once for all. Count only writes that haven't reached `onSettled`: a mutation stays pending until its callbacks finish, so with `isMutating() > 1` two writes that settle together, in different scopes, each see the other and both skip the read.
170
+ - Don't pass `throwOnError` here, for the reason above. To tell the user the read failed, show the query's own error next to its data: `todos.isError()` while `todos.data()` is still there.
171
+
172
+ ## Optimistic updates
173
+
174
+ Launch adds nothing here either: TanStack's `onMutate` and `onError` work on the generated options, typed by the procedure. The [todos example](https://github.com/theo-matzavinos/loozo/blob/main/examples/angular-launch/src/routes/+authenticated/todos/page.ts) completes and deletes todos this way:
175
+
176
+ ```ts
177
+ const key = queries.todos.list.key();
178
+
179
+ injectMutation(() =>
180
+ queries.todos.complete.mutationOptions({
181
+ scope: { id: "todos" },
182
+ onMutate: async ({ id }, { client }) => {
183
+ // A read in flight would replace the optimistic data when it lands.
184
+ await client.cancelQueries({ queryKey: key });
185
+
186
+ const before = client.getQueryData(key)?.todos.find((todo) => todo.id === id);
187
+
188
+ client.setQueryData(key, (list) => markCompleted(list, id));
189
+
190
+ return { before };
191
+ },
192
+ onError: (error, { id }, result, { client }) => {
193
+ // The server says it's gone: show that instead of the todo as it was.
194
+ if (rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
195
+ client.setQueryData(key, (list) => withoutTodo(list, id));
196
+
197
+ return;
198
+ }
199
+
200
+ const before = result?.before;
201
+
202
+ if (before !== undefined) {
203
+ client.setQueryData(key, (list) => withTodo(list, before));
204
+ }
205
+ },
206
+ }),
207
+ );
208
+ ```
209
+
210
+ `markCompleted`, `withoutTodo` and `withTodo` stand for updates of your procedure's output; the example's are on its page. The list is read again by the [`MutationCache` above](#after-every-write), or by your own `onSettled`.
211
+
212
+ - The key is tagged with the procedure's output, so `getQueryData` and `setQueryData` are typed, and `onMutate`'s result reaches `onError` typed, without annotations. `context.client` is the `QueryClient`.
213
+ - `cancelQueries` aborts the query's HTTP request, since generated queries pass TanStack's `signal`, so the handler sees its `signal` abort.
214
+ - The declared errors decide the rollback. The rejection is the callable's own, so `isError` recognizes the write's declared errors and framework codes, and nothing else: not a failed read of the list. Anything it doesn't recognize, such as a network failure, leaves the write's outcome unknown; restore the row and let the read tell.
215
+ - Undo the row you changed, not a snapshot of the whole list: with two writes pending, restoring the first's snapshot would also undo the second's change.
216
+ - Mutations with the same `scope` id reach the server one at a time, in order. TanStack still runs each `onMutate` at once, so the page shows every pending write.
217
+ - Don't let two pending writes change the same row: the second's `onMutate` saves the first's optimistic row, and if both fail, its rollback restores that. The example disables a row's controls while a write to it is pending.
218
+ - A read that starts while a write is pending replaces its optimistic data with the server's older state. The example disables Refresh while any write is pending. A refetch on window focus can do the same; the read after the last write corrects it.
219
+ - During server rendering, mutations are refused with `FORBIDDEN`, so none of this runs. A click made before the app hydrates is replayed by Angular's event replay, which `provideClientHydration()` turns on with incremental hydration, and the write then runs as above. Until then there's no feedback.
220
+
221
+ For an add, which needs the id the server gives it, TanStack's other approach fits better: render the pending mutation's `variables()` instead of writing to the cache.
133
222
 
134
223
  ## Server rendering and hydration
135
224
 
@@ -144,20 +233,23 @@ The limits follow from TanStack's hydration:
144
233
  - Only successful queries reach the browser. A query that fails during server rendering, with a declared error or a framework code, runs again over HTTP in the browser, with a fresh context. The handler runs twice, and the page shows whatever the second call returns.
145
234
  - Queries are part of the HTML: only return data the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
146
235
  - Mutations are refused during server rendering with `FORBIDDEN`, as for direct calls.
147
- - Prerendering a page that runs a query fails the build, as for direct calls.
236
+ - A query that rejects with `RpcRedirect` or `RpcNotFound` doesn't navigate: only guards and resolvers do, through [`rpcNavigationErrors`](../README.md#navigating-on-outcomes). Read the error and act on it in the page.
237
+ - A prerendered page dehydrates its queries like a server-rendered one, from an anonymous context; a query that fails while prerendering fails the build, as for direct calls. See [Prerendering](../README.md#prerendering).
148
238
 
149
239
  ## Defaults
150
240
 
151
- | Option | Default |
152
- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
153
- | `retry` | No retry for an `RpcError` (a framework failure or declared error); for anything else, your `QueryClient` default for the key, or three retries |
154
- | `refetchOnMount` | `false` while hydrating; then your `QueryClient` default for the key, or `true` |
241
+ | Option | Default |
242
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
243
+ | `retry` | No retry for an `RpcError` (a framework failure or declared error), an `RpcRedirect` or an `RpcNotFound`; for anything else, your `QueryClient` default for the key, or three retries |
244
+ | `refetchOnMount` | `false` while hydrating; then your `QueryClient` default for the key, or `true` |
155
245
 
156
- Everything else is TanStack's or your `QueryClient`'s. Overrides replace either default per call. Your `QueryClient` defaults still apply through them: a default `retry` decides retries for errors other than an `RpcError`, and a default `refetchOnMount` applies after hydration. On the server, TanStack's adapter defaults `retry` to `false`, so a failed query doesn't retry during server rendering.
246
+ Everything else is TanStack's or your `QueryClient`'s. Overrides replace either default per call. Your `QueryClient` defaults still apply through them: a default `retry` decides retries for errors other than those three, and a default `refetchOnMount` applies after hydration. On the server, TanStack's adapter defaults `retry` to `false`, so a failed query doesn't retry during server rendering.
157
247
 
158
248
  ## Limitations
159
249
 
160
- - No infinite queries, optimistic-update helpers, automatic invalidation, mutation cancellation or persistence.
250
+ - No infinite queries, mutation cancellation or persistence. Optimistic updates and invalidation are TanStack's, as [above](#invalidation): Launch adds no helpers for them.
251
+ - No options for [streams](../README.md#calling-streams): `injectQueries()` leaves them out. TanStack's `streamedQuery` keeps a query fetching until its stream ends, and the Angular adapter keeps the app from becoming stable while a query is fetching, which would hold hydration open as long as the stream runs. It's also still `experimental_streamedQuery` in query-core 5.104. Follow the stream with [`connect()`](../README.md#following-streams-and-channels-with-connect) instead.
252
+ - No options for [channels](../README.md#calling-channels) either, for the same reasons; use `connect()`.
161
253
  - Errors aren't dehydrated: a failed server query runs again in the browser.
162
254
  - Only `@tanstack/angular-query`, not `@tanstack/angular-query-experimental`.
163
255
  - No special handling for `@defer`: queries in a deferred block follow the same window, so ones that mount after the app is stable refetch when stale.
@@ -1,6 +1,7 @@
1
1
  import { inject } from "@angular/core";
2
2
  import { QueryClient, skipToken } from "@tanstack/angular-query";
3
3
  import { RpcError } from "../client.js";
4
+ import { RpcNotFound, RpcRedirect } from "../outcomes.js";
4
5
  import { hydrationWindow } from "./hydration.js";
5
6
  // Builds the TanStack factories of a generated injectQueries() over its injectRpc() client.
6
7
  export function createQueries(rpc, groups) {
@@ -28,10 +29,12 @@ export function createQueries(rpc, groups) {
28
29
  return fallback;
29
30
  };
30
31
  // Resolved per call, in query-core's merge order, so the client's default (the adapter's
31
- // `false` on the server) applies to everything but an RpcError.
32
+ // `false` on the server) applies to everything but the server's answers.
32
33
  function retryFor(queryKey) {
33
34
  return (failures, error) => {
34
- if (error instanceof RpcError) {
35
+ if (error instanceof RpcError ||
36
+ error instanceof RpcRedirect ||
37
+ error instanceof RpcNotFound) {
35
38
  return false;
36
39
  }
37
40
  const defaults = {
@@ -79,7 +79,7 @@ type MutationProcedure<Namespace, Name, Input, Output> = {
79
79
  key(): ProcedureKey<Namespace, Name>;
80
80
  };
81
81
  type Variables<Input> = Input extends Schema<infer Caller, unknown> ? Caller : void;
82
- type ProcedureQueries<Namespace, Name, Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer _Errors> ? Kind extends "query" ? QueryProcedure<Namespace, Name, Input, Awaited<Output>> : MutationProcedure<Namespace, Name, Input, Awaited<Output>> : never;
82
+ type ProcedureQueries<Namespace, Name, Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer _Errors, infer _Message> ? Kind extends "query" ? QueryProcedure<Namespace, Name, Input, Awaited<Output>> : MutationProcedure<Namespace, Name, Input, Awaited<Output>> : never;
83
83
  /**
84
84
  * The TanStack Query factories for an RPC group: query or mutation options and keys per
85
85
  * procedure, plus the group's key.
@@ -93,10 +93,10 @@ type ProcedureQueries<Namespace, Name, Value> = Value extends Procedure<infer In
93
93
  * `signal` and `transferCache: false`, since TanStack transfers the data itself. Errors are
94
94
  * typed `unknown`: narrow them with the callable's `isError`.
95
95
  *
96
- * Query options default `retry` to never for an `RpcError` and to your `QueryClient`
97
- * default, or three retries, for anything else, and `refetchOnMount` to `false` while the
98
- * app hydrates and to your `QueryClient` default, or `true`, after. Overrides replace
99
- * either default.
96
+ * Query options default `retry` to never for an `RpcError`, `RpcRedirect` or
97
+ * `RpcNotFound` and to your `QueryClient` default, or three retries, for anything else,
98
+ * and `refetchOnMount` to `false` while the app hydrates and to your `QueryClient`
99
+ * default, or `true`, after. Overrides replace either default.
100
100
  *
101
101
  * @example
102
102
  * ```ts
@@ -119,6 +119,8 @@ export type RpcQueries<Value> = Value extends Group<infer Namespace, infer Proce
119
119
  */
120
120
  $key(): GroupKey<Namespace>;
121
121
  } & {
122
- readonly [Name in keyof Procedures]: ProcedureQueries<Namespace, Name, Procedures[Name]>;
122
+ readonly [Name in keyof Procedures as Procedures[Name] extends {
123
+ readonly kind: "stream" | "channel";
124
+ } ? never : Name]: ProcedureQueries<Namespace, Name, Procedures[Name]>;
123
125
  } : never;
124
126
  export {};