@loozo/angular-launch 0.0.3 → 0.0.4

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/server/backend.js CHANGED
@@ -2,7 +2,7 @@ import { inject, InjectionToken, REQUEST, REQUEST_CONTEXT, makeEnvironmentProvid
2
2
  import { FetchBackend, HttpBackend, HttpErrorResponse, HttpResponse } from "@angular/common/http";
3
3
  import { Observable } from "rxjs";
4
4
  import { RPC_CALL } from "../generated.js";
5
- import { dispatch, failure, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
5
+ import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
6
6
  const renderFaults = new InjectionToken("Launch render faults");
7
7
  /**
8
8
  * Provides the server-rendering transport that runs RPC calls in-process with the
@@ -21,9 +21,9 @@ const renderFaults = new InjectionToken("Launch render faults");
21
21
  *
22
22
  * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
23
23
  * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
24
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT`, as
25
- * does any intercepted call with a query string, fragment, URL credentials, a method
26
- * other than `POST`, a non-JSON content type, its own `Authorization`,
24
+ * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
25
+ * issues, as does any intercepted call with a query string, fragment, URL credentials, a
26
+ * method other than `POST`, a non-JSON content type, its own `Authorization`,
27
27
  * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
28
28
  *
29
29
  * Without a live request, as during prerendering, calls from generated clients and
@@ -105,20 +105,20 @@ export function provideLaunchServer(registry, application) {
105
105
  request.method !== "POST" ||
106
106
  !isJsonMediaType(contentType) ||
107
107
  authOverride) {
108
- deliver(failure("INVALID_INPUT"));
108
+ deliver(invalidInput());
109
109
  return;
110
110
  }
111
111
  let envelope;
112
112
  try {
113
113
  const body = request.serializeBody();
114
114
  if (typeof body !== "string") {
115
- deliver(failure("INVALID_INPUT"));
115
+ deliver(invalidInput());
116
116
  return;
117
117
  }
118
118
  envelope = JSON.parse(body);
119
119
  }
120
120
  catch {
121
- deliver(failure("INVALID_INPUT"));
121
+ deliver(invalidInput());
122
122
  return;
123
123
  }
124
124
  void dispatch(registry, target.pathname, envelope, context, application, nativeRequest, "rendering").then(deliver);
@@ -87,10 +87,18 @@ export interface Schema<Input = unknown, Output = Input> {
87
87
  /** Absent on success. */
88
88
  readonly issues?: undefined;
89
89
  } | {
90
- /** The problems found, which mark a failure. Not sent to clients. */
90
+ /**
91
+ * The problems found, which mark a failure. For a procedure input, each issue's
92
+ * message and path are sent to the client as `INVALID_INPUT` data.
93
+ */
91
94
  readonly issues: readonly {
92
95
  /** A description of the problem. */
93
96
  readonly message: string;
97
+ /** Where the problem is: property keys, or `{ key }` segments. */
98
+ readonly path?: readonly (PropertyKey | {
99
+ /** The segment's property key. */
100
+ readonly key: PropertyKey;
101
+ })[] | undefined;
94
102
  }[];
95
103
  } | Promise<{
96
104
  /** The validated, possibly transformed value. */
@@ -98,10 +106,18 @@ export interface Schema<Input = unknown, Output = Input> {
98
106
  /** Absent on success. */
99
107
  readonly issues?: undefined;
100
108
  } | {
101
- /** The problems found, which mark a failure. Not sent to clients. */
109
+ /**
110
+ * The problems found, which mark a failure. For a procedure input, each issue's
111
+ * message and path are sent to the client as `INVALID_INPUT` data.
112
+ */
102
113
  readonly issues: readonly {
103
114
  /** A description of the problem. */
104
115
  readonly message: string;
116
+ /** Where the problem is: property keys, or `{ key }` segments. */
117
+ readonly path?: readonly (PropertyKey | {
118
+ /** The segment's property key. */
119
+ readonly key: PropertyKey;
120
+ })[] | undefined;
105
121
  }[];
106
122
  }>;
107
123
  };
@@ -1,4 +1,5 @@
1
1
  import { type FrameworkCode } from "../client.js";
2
+ import { type InputIssue } from "../input-issues.js";
2
3
  import type { ContextDefinition, ContextOf, Group, ProcedureDefinition } from "./definitions.js";
3
4
  /**
4
5
  * The application's RPC groups, keyed by namespace.
@@ -85,7 +86,8 @@ export interface Reply {
85
86
  /** The result, or an `{ error: { code, message, data } }` frame. */
86
87
  readonly body: unknown;
87
88
  }
88
- export declare function failure(code: FrameworkCode): Reply;
89
+ export declare function failure(code: Exclude<FrameworkCode, "INVALID_INPUT">): Reply;
90
+ export declare function invalidInput(issues?: readonly InputIssue[]): Reply;
89
91
  export declare function isJsonMediaType(contentType: string | null): boolean;
90
92
  /**
91
93
  * Runs one procedure call within a request scope and produces its reply.
@@ -100,8 +102,9 @@ export declare function isJsonMediaType(contentType: string | null): boolean;
100
102
  * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
101
103
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
102
104
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
103
- * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
104
- * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
105
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT` with no
106
+ * issues) with input that passes the schema (`INVALID_INPUT` with the schema's issues),
107
+ * or `null` without one (`INVALID_INPUT` with no issues); the group's
105
108
  * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
106
109
  * handler's strict JSON result is returned with status 200, and its declared errors
107
110
  * with their status.
@@ -125,10 +128,10 @@ export declare function dispatch(registry: Registry, path: string, envelope: unk
125
128
  * `handleRequest` in `server.generated.ts`; call that instead.
126
129
  * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
127
130
  * with an `application/json` content type and no query string, otherwise the reply is
128
- * `INVALID_INPUT` and no context is created. A fresh context is then created before the
129
- * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
130
- * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
131
- * `Cache-Control: private, no-store` and `Vary: Cookie`.
131
+ * `INVALID_INPUT` with no issues and no context is created. A fresh context is then
132
+ * created before the body is parsed; if that fails the reply is `INTERNAL`, even when the
133
+ * body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with no issues.
134
+ * Responses are JSON with `Cache-Control: private, no-store` and `Vary: Cookie`.
132
135
  *
133
136
  * @typeParam Definition - The application's context definition.
134
137
  * @param registry - The application's RPC groups.
@@ -1,5 +1,6 @@
1
1
  import { frameworkFailures } from "../client.js";
2
2
  import { serializeJson } from "../json.js";
3
+ import { inputIssues } from "../input-issues.js";
3
4
  import { declaredFailures } from "./errors.js";
4
5
  const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
5
6
  const bindingHeader = "x-loozo-launch-scope";
@@ -72,6 +73,15 @@ export function failure(code) {
72
73
  const frame = frameworkFailures[code];
73
74
  return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
74
75
  }
76
+ export function invalidInput(issues = []) {
77
+ const frame = frameworkFailures.INVALID_INPUT;
78
+ // Both transports publish the same strict JSON, as for declared error data.
79
+ const data = JSON.parse(serializeJson({ issues }));
80
+ return {
81
+ status: frame.status,
82
+ body: { error: { code: "INVALID_INPUT", message: frame.message, data } },
83
+ };
84
+ }
75
85
  export function isJsonMediaType(contentType) {
76
86
  return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
77
87
  }
@@ -88,8 +98,9 @@ export function isJsonMediaType(contentType) {
88
98
  * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
89
99
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
90
100
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
91
- * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT`) with
92
- * input that passes the schema, or `null` without one (`INVALID_INPUT`); the group's
101
+ * a cycle or an accessor); it must then be exactly `{ input }` (`INVALID_INPUT` with no
102
+ * issues) with input that passes the schema (`INVALID_INPUT` with the schema's issues),
103
+ * or `null` without one (`INVALID_INPUT` with no issues); the group's
93
104
  * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
94
105
  * handler's strict JSON result is returned with status 200, and its declared errors
95
106
  * with their status.
@@ -131,18 +142,18 @@ export async function dispatch(registry, path, envelope, scope, application, req
131
142
  Array.isArray(normalized) ||
132
143
  !("input" in normalized) ||
133
144
  Object.keys(normalized).length !== 1) {
134
- return failure("INVALID_INPUT");
145
+ return invalidInput();
135
146
  }
136
147
  let input;
137
148
  if (procedure.input) {
138
149
  const parsed = await procedure.input["~standard"].validate(normalized.input);
139
150
  if (parsed.issues) {
140
- return failure("INVALID_INPUT");
151
+ return invalidInput(inputIssues(parsed.issues));
141
152
  }
142
153
  input = parsed.value;
143
154
  }
144
155
  else if (normalized.input !== null) {
145
- return failure("INVALID_INPUT");
156
+ return invalidInput();
146
157
  }
147
158
  const context = scope.value;
148
159
  for (const guard of group.canActivate) {
@@ -196,10 +207,10 @@ export async function dispatch(registry, path, envelope, scope, application, req
196
207
  * `handleRequest` in `server.generated.ts`; call that instead.
197
208
  * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
198
209
  * with an `application/json` content type and no query string, otherwise the reply is
199
- * `INVALID_INPUT` and no context is created. A fresh context is then created before the
200
- * body is parsed; if that fails the reply is `INTERNAL`, even when the body isn't JSON.
201
- * Otherwise a body that isn't JSON gives `INVALID_INPUT`. Responses are JSON with
202
- * `Cache-Control: private, no-store` and `Vary: Cookie`.
210
+ * `INVALID_INPUT` with no issues and no context is created. A fresh context is then
211
+ * created before the body is parsed; if that fails the reply is `INTERNAL`, even when the
212
+ * body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with no issues.
213
+ * Responses are JSON with `Cache-Control: private, no-store` and `Vary: Cookie`.
203
214
  *
204
215
  * @typeParam Definition - The application's context definition.
205
216
  * @param registry - The application's RPC groups.
@@ -216,7 +227,7 @@ export async function handleRpc(registry, application, request) {
216
227
  if (request.method !== "POST" ||
217
228
  !isJsonMediaType(request.headers.get("content-type")) ||
218
229
  url.search !== "") {
219
- reply = failure("INVALID_INPUT");
230
+ reply = invalidInput();
220
231
  }
221
232
  else {
222
233
  try {
@@ -226,7 +237,7 @@ export async function handleRpc(registry, application, request) {
226
237
  envelope = await request.json();
227
238
  }
228
239
  catch {
229
- return response(failure("INVALID_INPUT"));
240
+ return response(invalidInput());
230
241
  }
231
242
  reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
232
243
  }
@@ -0,0 +1,168 @@
1
+ # TanStack Query
2
+
3
+ `@loozo/angular-launch/tanstack-query` connects Launch procedures to [TanStack Query for Angular](https://tanstack.com/query/latest/docs/framework/angular/overview) (`@tanstack/angular-query`). Generation writes typed query and mutation options and keys for your groups, and server-rendered query data reaches the browser through TanStack's own hydration, with no request on load even with `staleTime: 0`.
4
+
5
+ It's optional. Without it, Launch never imports TanStack.
6
+
7
+ ## Setup
8
+
9
+ Install the adapter. Launch supports `@tanstack/angular-query` `^5.0.0-rc.5` as an optional peer dependency, and is tested with `5.0.0-rc.5`:
10
+
11
+ ```sh
12
+ pnpm add @tanstack/angular-query@5.0.0-rc.5
13
+ ```
14
+
15
+ Turn on the `tanstackQuery` generation option:
16
+
17
+ ```js
18
+ // generate.mjs
19
+ import { generate } from "@loozo/angular-launch/generation";
20
+
21
+ await generate(import.meta.dirname, {
22
+ tsconfig: "tsconfig.app.json",
23
+ scanDirectories: ["src/routes"],
24
+ outDirectory: "generated",
25
+ tanstackQuery: true,
26
+ check: process.argv.includes("--check"),
27
+ });
28
+ ```
29
+
30
+ Each `rpc.generated.ts` then also exports `injectQueries()` and its type `Queries`, for the same groups as its `injectRpc()`. With the option off, generated files are exactly as without this entry point.
31
+
32
+ Add TanStack's provider and `provideLaunchQueries()` to the application's providers, which the server config inherits:
33
+
34
+ ```ts
35
+ // src/config.ts
36
+ import { provideHttpClient } from "@angular/common/http";
37
+ import { provideClientHydration } from "@angular/platform-browser";
38
+ import { provideRouter } from "@angular/router";
39
+ import type { ApplicationConfig } from "@angular/core";
40
+ import { provideLaunchQueries } from "@loozo/angular-launch/tanstack-query";
41
+ import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query";
42
+ import { routes } from "../generated/routes.generated";
43
+
44
+ export const config: ApplicationConfig = {
45
+ providers: [
46
+ provideHttpClient(),
47
+ provideClientHydration(),
48
+ provideRouter(routes),
49
+ provideTanStackQuery(() => new QueryClient()),
50
+ provideLaunchQueries(),
51
+ ],
52
+ };
53
+ ```
54
+
55
+ Pass `provideTanStackQuery` a factory, as above, not a shared client: the factory runs once per application, so every server render gets its own cache and one user's data never reaches another's page. `provideLaunchQueries()` belongs in the application's providers, not a route's or component's. `injectQueries()` throws without it.
56
+
57
+ ## Queries and mutations
58
+
59
+ Call `injectQueries()` in an injection context, like `injectRpc()`, and pass its options to TanStack:
60
+
61
+ ```ts
62
+ // src/routes/+authenticated/todos/page.ts
63
+ import { Component, inject } from "@angular/core";
64
+ import { injectMutation, injectQuery, QueryClient } from "@tanstack/angular-query";
65
+ import { injectQueries, injectRpc } from "./rpc.generated";
66
+
67
+ @Component({/* … */})
68
+ export default class Todos {
69
+ readonly #rpc = injectRpc();
70
+ readonly #queries = injectQueries();
71
+ readonly #client = inject(QueryClient);
72
+ readonly todos = injectQuery(() => this.#queries.todos.list.queryOptions());
73
+ readonly #complete = injectMutation(() =>
74
+ this.#queries.todos.complete.mutationOptions({
75
+ onSuccess: () => this.#client.invalidateQueries({ queryKey: this.#queries.todos.$key() }),
76
+ }),
77
+ );
78
+
79
+ async complete(id: string): Promise<void> {
80
+ try {
81
+ await this.#complete.mutateAsync({ id });
82
+ } catch (error) {
83
+ if (this.#rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
84
+ const missingId: string = error.data.id;
85
+ }
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ Each query procedure has `queryOptions` and each mutation procedure `mutationOptions`, never both:
92
+
93
+ ```ts
94
+ queries.todos.list.queryOptions(overrides?); // a query without input
95
+ queries.todos.byId.queryOptions(input, overrides?); // a query with input
96
+ queries.todos.byId.queryOptions(skipToken); // disabled until there's an input
97
+ queries.todos.add.mutationOptions(overrides?); // variables are the input
98
+ queries.todos.clear.mutationOptions(overrides?); // no input: mutate() takes none
99
+ ```
100
+
101
+ The options work anywhere TanStack takes them: `injectQuery`, `injectMutation`, `QueryClient.fetchQuery`, `ensureQueryData` and the like. `overrides` are any other TanStack options, such as `staleTime`, `select`, `enabled`, `onSuccess` or `onError`. They can't replace the key or the query or mutation function. Queries call the procedure with TanStack's `signal`, so a cancelled query aborts its HTTP request; mutations aren't cancelled.
102
+
103
+ The data is the procedure's output, or `select`'s result. Errors are typed `unknown`: narrow them with the callable's `isError`, as above. The rejection is the callable's own, so `isError` recognizes it.
104
+
105
+ ## Keys
106
+
107
+ Keys start with `"launch"` and the namespace, so a shorter key matches every longer key under it:
108
+
109
+ | Call | Key |
110
+ | ------------------------------------- | ------------------------------------------ |
111
+ | `queries.todos.$key()` | `["launch", "todos"]` |
112
+ | `queries.todos.list.key()` | `["launch", "todos", "list"]` |
113
+ | `queries.todos.byId.key()` | `["launch", "todos", "byId"]` |
114
+ | `queries.todos.byId.key({ id: "1" })` | `["launch", "todos", "byId", { id: "1" }]` |
115
+ | `queries.todos.add.key()` | `["launch", "todos", "add"]` |
116
+
117
+ `queryOptions` uses the full key: with the input as you passed it, or without one for a query without input. A query disabled with `skipToken` is keyed without input. `mutationOptions` uses the mutation's `key()` as its `mutationKey`.
118
+
119
+ Full query keys are tagged with the procedure's output type, so `client.getQueryData(queries.todos.list.key())` and `client.setQueryData(...)` are typed. `$key` can't clash with a procedure: Launch names can't contain `$`.
120
+
121
+ ## Invalidation
122
+
123
+ Nothing is invalidated for you. Invalidate in a mutation's `onSuccess`, by group, procedure or input:
124
+
125
+ ```ts
126
+ onSuccess: () => client.invalidateQueries({ queryKey: queries.todos.$key() }),
127
+ ```
128
+
129
+ Returning the promise, as here, keeps the mutation pending until the refetch finishes. A failed refetch doesn't fail the mutation, though: `invalidateQueries` resolves anyway, and the query keeps its previous data next to the error. To treat it as a failure, for example to tell the user the list may be out of date, pass `throwOnError`:
130
+
131
+ ```ts
132
+ onSuccess: () =>
133
+ client.invalidateQueries({ queryKey: queries.todos.$key() }, { throwOnError: true }),
134
+ ```
135
+
136
+ `mutateAsync` then rejects with the refetch's error, although the write itself succeeded.
137
+
138
+ ## Server rendering and hydration
139
+
140
+ During server rendering, queries run in-process with the page request's context, like direct calls, and Angular waits for them before rendering. TanStack then writes the successful queries' data into the HTML, and the browser's `QueryClient` starts with it. Generated query functions call with `transferCache: false`, so the data appears in the HTML once, as TanStack's, not again in Angular's HTTP transfer cache. Direct calls, such as from resolvers, still use the transfer cache as described in the [package README](../README.md#server-rendering-and-hydration).
141
+
142
+ In the browser, a query with data normally refetches when it mounts if it's stale, which with the default `staleTime: 0` is always. Generated query options default `refetchOnMount` to `false` while the app hydrates, from bootstrap until the app is first stable, the same window Angular's HTTP transfer cache uses. So with `staleTime: 0` the first render shows the server's data and no RPC is made on load. After that, `refetchOnMount` follows your `QueryClient` defaults (`true` unless you change them), invalidation always refetches, and a query mounted later, for example after navigating back or from a `@defer` block that hydrates on interaction, refetches if it's stale. A `refetchOnMount` override replaces the default, including during hydration.
143
+
144
+ The window opens in any browser app, also one without server rendering. Queries without data load regardless, since `refetchOnMount` only applies to data that's already there; but a query with `initialData`, or one you put in the cache before the first page mounts, doesn't refetch on mount until the app is first stable.
145
+
146
+ The limits follow from TanStack's hydration:
147
+
148
+ - 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.
149
+ - Queries are part of the HTML: only return data the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
150
+ - Mutations are refused during server rendering with `FORBIDDEN`, as for direct calls.
151
+ - Prerendering a page that runs a query fails the build, as for direct calls.
152
+
153
+ ## Defaults
154
+
155
+ | Option | Default |
156
+ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
157
+ | `retry` | No retry for an `RpcError` (a framework failure or declared error); for anything else, your `QueryClient` default for the key, or three retries |
158
+ | `refetchOnMount` | `false` while hydrating; then your `QueryClient` default for the key, or `true` |
159
+
160
+ 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.
161
+
162
+ ## Limitations
163
+
164
+ - No infinite queries, optimistic-update helpers, automatic invalidation, mutation cancellation or persistence.
165
+ - Errors aren't dehydrated: a failed server query runs again in the browser.
166
+ - Only `@tanstack/angular-query`, not `@tanstack/angular-query-experimental`.
167
+ - 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.
168
+ - TanStack also exports an `injectQueries` (for running several queries); import one of the two under another name if you need both in a file.
@@ -0,0 +1,5 @@
1
+ export interface QueriesMethod {
2
+ readonly kind: "query" | "mutation";
3
+ readonly input: boolean;
4
+ }
5
+ export declare function createQueries(rpc: Readonly<Record<string, Readonly<Record<string, unknown>>>>, groups: Readonly<Record<string, Readonly<Record<string, QueriesMethod>>>>): unknown;
@@ -0,0 +1,127 @@
1
+ import { inject } from "@angular/core";
2
+ import { QueryClient, skipToken } from "@tanstack/angular-query";
3
+ import { RpcError } from "../client.js";
4
+ import { hydrationWindow } from "./hydration.js";
5
+ // Builds the TanStack factories of a generated injectQueries() over its injectRpc() client.
6
+ export function createQueries(rpc, groups) {
7
+ const hydration = inject(hydrationWindow, { optional: true });
8
+ if (hydration === null) {
9
+ throw new Error("injectQueries() requires provideLaunchQueries() from @loozo/angular-launch/tanstack-query in the application providers");
10
+ }
11
+ const client = inject(QueryClient);
12
+ // An arrow function keeps the null check's narrowing; a function declaration is hoisted.
13
+ const refetchOnMount = (query) => {
14
+ if (hydration.open) {
15
+ return false;
16
+ }
17
+ const defaults = {
18
+ ...client.getDefaultOptions().queries,
19
+ ...client.getQueryDefaults(query.queryKey),
20
+ };
21
+ const fallback = defaults.refetchOnMount;
22
+ if (typeof fallback === "function") {
23
+ return fallback(query);
24
+ }
25
+ if (fallback === undefined) {
26
+ return true;
27
+ }
28
+ return fallback;
29
+ };
30
+ // 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
+ function retryFor(queryKey) {
33
+ return (failures, error) => {
34
+ if (error instanceof RpcError) {
35
+ return false;
36
+ }
37
+ const defaults = {
38
+ ...client.getDefaultOptions().queries,
39
+ ...client.getQueryDefaults(queryKey),
40
+ };
41
+ const fallback = defaults.retry;
42
+ if (typeof fallback === "function") {
43
+ return fallback(failures, error);
44
+ }
45
+ if (typeof fallback === "number") {
46
+ return failures < fallback;
47
+ }
48
+ if (fallback === undefined) {
49
+ return failures < 3;
50
+ }
51
+ return fallback;
52
+ };
53
+ }
54
+ const result = Object.create(null);
55
+ for (const [namespace, methods] of Object.entries(groups)) {
56
+ const group = Object.create(null);
57
+ group["$key"] = () => ["launch", namespace];
58
+ for (const [name, method] of Object.entries(methods)) {
59
+ const callable = rpc[namespace][name];
60
+ const procedureKey = () => ["launch", namespace, name];
61
+ if (method.kind === "mutation") {
62
+ let mutationFn;
63
+ if (method.input) {
64
+ mutationFn = (variables) => callable(variables);
65
+ }
66
+ else {
67
+ mutationFn = () => callable();
68
+ }
69
+ group[name] = {
70
+ key: procedureKey,
71
+ mutationOptions: (overrides = {}) => ({
72
+ ...overrides,
73
+ mutationKey: procedureKey(),
74
+ mutationFn,
75
+ }),
76
+ };
77
+ continue;
78
+ }
79
+ if (!method.input) {
80
+ group[name] = {
81
+ key: procedureKey,
82
+ queryOptions: (overrides = {}) => {
83
+ const queryKey = procedureKey();
84
+ return {
85
+ retry: retryFor(queryKey),
86
+ refetchOnMount,
87
+ ...overrides,
88
+ queryKey,
89
+ queryFn: ({ signal }) => callable({ signal, transferCache: false }),
90
+ };
91
+ },
92
+ };
93
+ continue;
94
+ }
95
+ group[name] = {
96
+ key: (input) => {
97
+ if (input === undefined) {
98
+ return procedureKey();
99
+ }
100
+ return ["launch", namespace, name, input];
101
+ },
102
+ queryOptions: (input, overrides = {}) => {
103
+ if (input === skipToken) {
104
+ const queryKey = procedureKey();
105
+ return {
106
+ retry: retryFor(queryKey),
107
+ refetchOnMount,
108
+ ...overrides,
109
+ queryKey,
110
+ queryFn: skipToken,
111
+ };
112
+ }
113
+ const queryKey = ["launch", namespace, name, input];
114
+ return {
115
+ retry: retryFor(queryKey),
116
+ refetchOnMount,
117
+ ...overrides,
118
+ queryKey,
119
+ queryFn: ({ signal }) => callable(input, { signal, transferCache: false }),
120
+ };
121
+ },
122
+ };
123
+ }
124
+ result[namespace] = group;
125
+ }
126
+ return result;
127
+ }
@@ -0,0 +1,46 @@
1
+ import { InjectionToken } from "@angular/core";
2
+ import type { EnvironmentProviders } from "@angular/core";
3
+ /**
4
+ * Whether the app is still hydrating: open in the browser from bootstrap until the app is
5
+ * first stable, never open on the server.
6
+ *
7
+ * @remarks
8
+ * Internal; provided by {@link provideLaunchQueries} and read by generated query options.
9
+ */
10
+ export declare const hydrationWindow: InjectionToken<{
11
+ open: boolean;
12
+ }>;
13
+ /**
14
+ * Provides what generated `injectQueries()` functions need: the app's hydration window.
15
+ *
16
+ * @remarks
17
+ * Add it to the application's providers next to TanStack's `provideTanStackQuery(...)`,
18
+ * not to a route or component. `injectQueries()` throws without it.
19
+ *
20
+ * In the browser, generated query options don't refetch on mount while the app hydrates,
21
+ * from bootstrap until the app is first stable, so data dehydrated during server rendering
22
+ * is used as is even with `staleTime: 0`. After that, `refetchOnMount` follows your
23
+ * `QueryClient` defaults. This is the same window Angular's HTTP transfer cache uses.
24
+ * The window also opens in a browser app without server rendering: queries without data
25
+ * still load, but ones with `initialData` or already in the cache don't refetch on mount
26
+ * until the app is first stable.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query";
31
+ * import { provideLaunchQueries } from "@loozo/angular-launch/tanstack-query";
32
+ *
33
+ * export const config: ApplicationConfig = {
34
+ * providers: [
35
+ * provideHttpClient(),
36
+ * provideClientHydration(),
37
+ * provideRouter(routes),
38
+ * provideTanStackQuery(() => new QueryClient()),
39
+ * provideLaunchQueries(),
40
+ * ],
41
+ * };
42
+ * ```
43
+ *
44
+ * @returns The providers for the application's root environment injector.
45
+ */
46
+ export declare function provideLaunchQueries(): EnvironmentProviders;
@@ -0,0 +1,70 @@
1
+ import { isPlatformBrowser } from "@angular/common";
2
+ import { APP_BOOTSTRAP_LISTENER, ApplicationRef, inject, InjectionToken, makeEnvironmentProviders, PLATFORM_ID, } from "@angular/core";
3
+ /**
4
+ * Whether the app is still hydrating: open in the browser from bootstrap until the app is
5
+ * first stable, never open on the server.
6
+ *
7
+ * @remarks
8
+ * Internal; provided by {@link provideLaunchQueries} and read by generated query options.
9
+ */
10
+ export const hydrationWindow = new InjectionToken("Launch hydration window");
11
+ /**
12
+ * Provides what generated `injectQueries()` functions need: the app's hydration window.
13
+ *
14
+ * @remarks
15
+ * Add it to the application's providers next to TanStack's `provideTanStackQuery(...)`,
16
+ * not to a route or component. `injectQueries()` throws without it.
17
+ *
18
+ * In the browser, generated query options don't refetch on mount while the app hydrates,
19
+ * from bootstrap until the app is first stable, so data dehydrated during server rendering
20
+ * is used as is even with `staleTime: 0`. After that, `refetchOnMount` follows your
21
+ * `QueryClient` defaults. This is the same window Angular's HTTP transfer cache uses.
22
+ * The window also opens in a browser app without server rendering: queries without data
23
+ * still load, but ones with `initialData` or already in the cache don't refetch on mount
24
+ * until the app is first stable.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query";
29
+ * import { provideLaunchQueries } from "@loozo/angular-launch/tanstack-query";
30
+ *
31
+ * export const config: ApplicationConfig = {
32
+ * providers: [
33
+ * provideHttpClient(),
34
+ * provideClientHydration(),
35
+ * provideRouter(routes),
36
+ * provideTanStackQuery(() => new QueryClient()),
37
+ * provideLaunchQueries(),
38
+ * ],
39
+ * };
40
+ * ```
41
+ *
42
+ * @returns The providers for the application's root environment injector.
43
+ */
44
+ export function provideLaunchQueries() {
45
+ return makeEnvironmentProviders([
46
+ {
47
+ provide: hydrationWindow,
48
+ useFactory: () => ({ open: isPlatformBrowser(inject(PLATFORM_ID)) }),
49
+ },
50
+ {
51
+ // Angular's HTTP transfer cache waits from the same hook. Waiting from a provider
52
+ // factory or an environment initializer resolves before bootstrap registers any
53
+ // pending work, so the window would close before the first page mounts.
54
+ provide: APP_BOOTSTRAP_LISTENER,
55
+ multi: true,
56
+ useFactory: () => {
57
+ const hydration = inject(hydrationWindow);
58
+ const app = inject(ApplicationRef);
59
+ return () => {
60
+ if (!hydration.open) {
61
+ return;
62
+ }
63
+ void app.whenStable().then(() => {
64
+ hydration.open = false;
65
+ });
66
+ };
67
+ },
68
+ },
69
+ ]);
70
+ }
@@ -0,0 +1,2 @@
1
+ export { provideLaunchQueries } from "./hydration.js";
2
+ export type { RpcQueries } from "./queries.js";
@@ -0,0 +1 @@
1
+ export { provideLaunchQueries } from "./hydration.js";