@loozo/angular-launch 0.0.3 → 0.0.5

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.
@@ -1,6 +1,8 @@
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";
5
+ import { outcomeOf } from "./outcomes.js";
4
6
  const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
5
7
  const bindingHeader = "x-loozo-launch-scope";
6
8
  /**
@@ -72,9 +74,105 @@ export function failure(code) {
72
74
  const frame = frameworkFailures[code];
73
75
  return { status: frame.status, body: { error: { code, message: frame.message, data: null } } };
74
76
  }
77
+ export function invalidInput(issues = []) {
78
+ const frame = frameworkFailures.INVALID_INPUT;
79
+ // Both transports publish the same strict JSON, as for declared error data.
80
+ const data = JSON.parse(serializeJson({ issues }));
81
+ return {
82
+ status: frame.status,
83
+ body: { error: { code: "INVALID_INPUT", message: frame.message, data } },
84
+ };
85
+ }
75
86
  export function isJsonMediaType(contentType) {
76
87
  return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
77
88
  }
89
+ /**
90
+ * Runs `chain` in order around `last`, passing each middleware the context the previous
91
+ * one continued with.
92
+ *
93
+ * @remarks
94
+ * Rejects when a middleware throws, calls `next` twice (whether it then returns or
95
+ * throws) or returns anything other than its `next` result. A misused `next` never causes
96
+ * an unhandled rejection: each promise it returns is observed here. When the rest of the
97
+ * call a middleware started fails, that failure is logged unless the middleware rejected
98
+ * with that same value, as an awaited rethrow does: the middleware may have left it
99
+ * detached, or replaced it with another error such as `forbidden()`.
100
+ */
101
+ async function runChain(chain, context, args, last) {
102
+ async function step(index, current) {
103
+ if (index === chain.length) {
104
+ await last(current);
105
+ return;
106
+ }
107
+ const token = {};
108
+ let calls = 0;
109
+ let rest;
110
+ function next(added) {
111
+ calls += 1;
112
+ let continued;
113
+ if (calls > 1) {
114
+ continued = Promise.reject(new Error("Launch middleware called next() more than once"));
115
+ }
116
+ else {
117
+ let merged = current;
118
+ if (added !== undefined) {
119
+ merged = { ...current, ...added };
120
+ }
121
+ continued = step(index + 1, merged).then(() => token);
122
+ rest = continued;
123
+ }
124
+ // A middleware that doesn't await this promise can't leave its rejection unhandled;
125
+ // one that awaits it still sees the rejection.
126
+ continued.catch(() => undefined);
127
+ return continued;
128
+ }
129
+ const run = chain[index].run;
130
+ let returned;
131
+ let thrown;
132
+ try {
133
+ returned = await run({ ...args, context: current, next });
134
+ }
135
+ catch (error) {
136
+ thrown = { error };
137
+ }
138
+ // Whether it already failed or fails later, a failure the middleware didn't rethrow
139
+ // reaches nothing else.
140
+ rest?.catch((error) => {
141
+ if (thrown === undefined || error !== thrown.error) {
142
+ console.error("Launch RPC failed inside next(), and its middleware didn't rethrow it", error);
143
+ }
144
+ });
145
+ if (calls > 1 || (thrown === undefined && returned !== token)) {
146
+ throw new Error("Launch middleware must call next() once and return its result", thrown === undefined ? undefined : { cause: thrown.error });
147
+ }
148
+ if (thrown !== undefined) {
149
+ throw thrown.error;
150
+ }
151
+ }
152
+ await step(0, context);
153
+ }
154
+ async function declaredReply(procedure, error) {
155
+ let declared;
156
+ if (typeof error === "object" && error !== null) {
157
+ declared = procedure[declaredFailures]?.get(error);
158
+ }
159
+ if (!declared || !Object.hasOwn(procedure.errors, declared.code)) {
160
+ throw error;
161
+ }
162
+ const definition = procedure.errors[declared.code];
163
+ if (definition !== declared.definition) {
164
+ throw error;
165
+ }
166
+ const parsed = await definition.data["~standard"].validate(declared.data);
167
+ if (parsed.issues) {
168
+ throw new Error("Declared RPC error data failed validation", { cause: error });
169
+ }
170
+ const data = JSON.parse(serializeJson(parsed.value));
171
+ return {
172
+ status: definition.status,
173
+ body: { error: { code: declared.code, message: definition.message, data } },
174
+ };
175
+ }
78
176
  /**
79
177
  * Runs one procedure call within a request scope and produces its reply.
80
178
  *
@@ -88,11 +186,14 @@ export function isJsonMediaType(contentType) {
88
186
  * path must be `/_rpc/<namespace>/<procedure>` for a registered procedure
89
187
  * (`RPC_NOT_FOUND`); a mutation in `"rendering"` mode is refused (`FORBIDDEN`); the
90
188
  * 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
93
- * guards and then the procedure's guards must return `true` (`FORBIDDEN`). The
94
- * handler's strict JSON result is returned with status 200, and its declared errors
95
- * with their status.
189
+ * a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
190
+ * the group's middleware runs with no input; the input must pass the schema
191
+ * (`INVALID_INPUT` with the schema's issues), or be `null` without one (`INVALID_INPUT`
192
+ * with no issues); the procedure's middleware runs with the validated input; then the
193
+ * handler. The handler's strict JSON result is returned with status 200, and its
194
+ * declared errors with their status. `forbidden()` thrown from middleware or the
195
+ * handler gives `FORBIDDEN`; a middleware that calls `next` twice or doesn't return its
196
+ * result gives `INTERNAL`.
96
197
  *
97
198
  * @param registry - The application's RPC groups.
98
199
  * @param path - The request path.
@@ -102,9 +203,10 @@ export function isJsonMediaType(contentType) {
102
203
  * @param request - The request the scope must be bound to.
103
204
  * @param mode - `"http"` for browser requests (the default) or `"rendering"` for calls
104
205
  * made during server rendering.
206
+ * @param signal - The call's abort signal. Defaults to `request`'s signal.
105
207
  * @returns The reply to send.
106
208
  */
107
- export async function dispatch(registry, path, envelope, scope, application, request, mode = "http") {
209
+ export async function dispatch(registry, path, envelope, scope, application, request, mode = "http", signal = request.signal) {
108
210
  try {
109
211
  assertBoundScope(scope, application, request);
110
212
  const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
@@ -131,109 +233,145 @@ export async function dispatch(registry, path, envelope, scope, application, req
131
233
  Array.isArray(normalized) ||
132
234
  !("input" in normalized) ||
133
235
  Object.keys(normalized).length !== 1) {
134
- return failure("INVALID_INPUT");
236
+ return invalidInput();
135
237
  }
136
- let input;
137
- if (procedure.input) {
138
- const parsed = await procedure.input["~standard"].validate(normalized.input);
139
- if (parsed.issues) {
140
- return failure("INVALID_INPUT");
141
- }
142
- input = parsed.value;
143
- }
144
- else if (normalized.input !== null) {
145
- return failure("INVALID_INPUT");
146
- }
147
- const context = scope.value;
148
- for (const guard of group.canActivate) {
149
- if (!(await guard({ context, request }))) {
150
- return failure("FORBIDDEN");
151
- }
152
- }
153
- for (const guard of procedure.canActivate) {
154
- if (!(await guard({ context, request, input }))) {
155
- return failure("FORBIDDEN");
156
- }
157
- }
158
- let output;
238
+ let reply;
159
239
  try {
160
- output = await procedure.handler({ context, input });
240
+ // Group middleware runs before validation, so it never sees the raw input.
241
+ await runChain(group.use, scope.value, { input: undefined, request, signal }, async (groupContext) => {
242
+ let input;
243
+ if (procedure.input) {
244
+ const parsed = await procedure.input["~standard"].validate(normalized.input);
245
+ if (parsed.issues) {
246
+ reply = invalidInput(inputIssues(parsed.issues));
247
+ return;
248
+ }
249
+ input = parsed.value;
250
+ }
251
+ else if (normalized.input !== null) {
252
+ reply = invalidInput();
253
+ return;
254
+ }
255
+ await runChain(procedure.use, groupContext, { input, request, signal }, async (context) => {
256
+ const output = await procedure.handler({ context, input, request, signal });
257
+ reply = { status: 200, body: JSON.parse(serializeJson(output)) };
258
+ });
259
+ });
161
260
  }
162
261
  catch (error) {
163
- let declared;
164
- if (typeof error === "object" && error !== null) {
165
- declared = procedure[declaredFailures]?.get(error);
166
- }
167
- if (!declared || !Object.hasOwn(procedure.errors, declared.code)) {
168
- throw error;
169
- }
170
- const definition = procedure.errors[declared.code];
171
- if (definition !== declared.definition) {
172
- throw error;
173
- }
174
- const parsed = await definition.data["~standard"].validate(declared.data);
175
- if (parsed.issues) {
176
- throw new Error("Declared RPC error data failed validation", { cause: error });
262
+ const outcome = outcomeOf(error);
263
+ if (outcome?.kind === "forbidden") {
264
+ return failure("FORBIDDEN");
177
265
  }
178
- const data = JSON.parse(serializeJson(parsed.value));
179
- return {
180
- status: definition.status,
181
- body: { error: { code: declared.code, message: definition.message, data } },
182
- };
266
+ return await declaredReply(procedure, error);
267
+ }
268
+ if (!reply) {
269
+ throw new Error("Launch call finished without a reply");
183
270
  }
184
- return { status: 200, body: JSON.parse(serializeJson(output)) };
271
+ return reply;
185
272
  }
186
273
  catch (error) {
187
274
  console.error("Launch RPC failed", error);
188
275
  return failure("INTERNAL");
189
276
  }
190
277
  }
278
+ function hostAllowed(hostname, allowedHosts) {
279
+ for (const allowed of allowedHosts) {
280
+ if (allowed === "*" || allowed === hostname) {
281
+ return true;
282
+ }
283
+ if (allowed.startsWith("*.") && hostname.endsWith(allowed.slice(1))) {
284
+ return true;
285
+ }
286
+ }
287
+ return false;
288
+ }
289
+ /** Why `request` can't be proven same-origin, or `undefined` when it can. */
290
+ function crossSiteReason(request, origins) {
291
+ const site = request.headers.get("sec-fetch-site");
292
+ const origin = request.headers.get("origin");
293
+ if (origin !== null && origins.includes(origin)) {
294
+ return undefined;
295
+ }
296
+ if (site !== null) {
297
+ if (site === "same-origin") {
298
+ return undefined;
299
+ }
300
+ return `Sec-Fetch-Site is ${site}`;
301
+ }
302
+ if (origin !== null) {
303
+ const own = new URL(request.url).origin;
304
+ if (origin === own) {
305
+ return undefined;
306
+ }
307
+ return `Origin ${origin} isn't ${own}`;
308
+ }
309
+ return "neither Sec-Fetch-Site nor Origin was sent";
310
+ }
191
311
  /**
192
312
  * Answers an RPC HTTP request, or returns `null` for any other request.
193
313
  *
194
314
  * @remarks
195
315
  * Internal: exported only from `@loozo/angular-launch/_server` for the generated
196
316
  * `handleRequest` in `server.generated.ts`; call that instead.
197
- * Any path starting with `/_rpc/` is treated as an RPC request. It must be a `POST`
198
- * 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`.
317
+ * Any path starting with `/_rpc/` is treated as an RPC request. Its URL's hostname must
318
+ * be in `allowedHosts`, otherwise the reply is a plain-text 400 `Host not allowed`. It
319
+ * must then be a `POST` with an `application/json` content type and no query string,
320
+ * otherwise the reply is `INVALID_INPUT` with no issues. It must then come from the
321
+ * app's own origin, otherwise the reply is `FORBIDDEN`: an `Origin` listed in `origins`
322
+ * passes; otherwise `Sec-Fetch-Site`, when sent, must be `same-origin`; otherwise
323
+ * `Origin`, when sent, must equal the request URL's origin; a request with neither
324
+ * header is refused. No context is created for any of these refusals. A fresh context
325
+ * is then created before the body is parsed; if that fails the reply is `INTERNAL`, even
326
+ * when the body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with
327
+ * no issues.
328
+ * JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
329
+ * `X-Content-Type-Options: nosniff`.
203
330
  *
204
331
  * @typeParam Definition - The application's context definition.
205
332
  * @param registry - The application's RPC groups.
206
333
  * @param application - The application binding.
207
334
  * @param request - The incoming server request.
335
+ * @param options - The allowed hosts and further allowed origins.
208
336
  * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
209
337
  */
210
- export async function handleRpc(registry, application, request) {
338
+ export async function handleRpc(registry, application, request, { allowedHosts, origins = [] }) {
211
339
  const url = new URL(request.url);
212
340
  if (!url.pathname.startsWith("/_rpc/")) {
213
341
  return null;
214
342
  }
215
- let reply;
343
+ if (!hostAllowed(url.hostname, allowedHosts)) {
344
+ console.error(`Launch refused an RPC for host ${url.hostname}`);
345
+ return new Response("Host not allowed", {
346
+ status: 400,
347
+ headers: { "content-type": "text/plain", "x-content-type-options": "nosniff" },
348
+ });
349
+ }
216
350
  if (request.method !== "POST" ||
217
351
  !isJsonMediaType(request.headers.get("content-type")) ||
218
352
  url.search !== "") {
219
- reply = failure("INVALID_INPUT");
353
+ return response(invalidInput());
354
+ }
355
+ const crossSite = crossSiteReason(request, origins);
356
+ if (crossSite !== undefined) {
357
+ console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
358
+ return response(failure("FORBIDDEN"));
220
359
  }
221
- else {
360
+ let reply;
361
+ try {
362
+ const scope = await createRequestScope(application, request);
363
+ let envelope;
222
364
  try {
223
- const scope = await createRequestScope(application, request);
224
- let envelope;
225
- try {
226
- envelope = await request.json();
227
- }
228
- catch {
229
- return response(failure("INVALID_INPUT"));
230
- }
231
- reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
365
+ envelope = await request.json();
232
366
  }
233
- catch (error) {
234
- console.error("Launch context failed", error);
235
- reply = failure("INTERNAL");
367
+ catch {
368
+ return response(invalidInput());
236
369
  }
370
+ reply = await dispatch(registry, url.pathname, envelope, scope, application, scope.request);
371
+ }
372
+ catch (error) {
373
+ console.error("Launch context failed", error);
374
+ reply = failure("INTERNAL");
237
375
  }
238
376
  return response(reply);
239
377
  }
@@ -244,6 +382,7 @@ function response(reply) {
244
382
  "content-type": "application/json",
245
383
  "cache-control": "private, no-store",
246
384
  vary: "Cookie",
385
+ "x-content-type-options": "nosniff",
247
386
  },
248
387
  });
249
388
  }
package/server/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- export { defineContext, defineRpc, query, mutation } from "./definitions.js";
2
- export type { Register, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, Guard, InputOf, OutputOf, Procedure, ProcedureDefinition, ProcedureGuard, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
1
+ export { defineContext, defineRpc, middleware } from "./definitions.js";
2
+ export { forbidden } from "./outcomes.js";
3
+ export type { Register, CallArgs, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
3
4
  export type { DeclaredFailure } from "./errors.js";
4
5
  export type { JsonShape } from "../json.js";
5
- export type { RequestScope } from "./dispatch.js";
6
+ export type { HandleOptions, RequestScope } from "./dispatch.js";
6
7
  export { finishLaunchRendering } from "./backend.js";
package/server/index.js CHANGED
@@ -1,2 +1,3 @@
1
- export { defineContext, defineRpc, query, mutation } from "./definitions.js";
1
+ export { defineContext, defineRpc, middleware } from "./definitions.js";
2
+ export { forbidden } from "./outcomes.js";
2
3
  export { finishLaunchRendering } from "./backend.js";
@@ -0,0 +1,26 @@
1
+ /** What a thrown outcome asks the server to answer with. Internal. */
2
+ export interface Outcome {
3
+ readonly kind: "forbidden";
4
+ }
5
+ /**
6
+ * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
7
+ * or a handler.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * if (context.user === null) {
12
+ * throw forbidden();
13
+ * }
14
+ * ```
15
+ *
16
+ * @returns The error to `throw`.
17
+ */
18
+ export declare function forbidden(): Error;
19
+ /**
20
+ * Reads the outcome a thrown value carries, if it was created by an outcome factory.
21
+ * Internal.
22
+ *
23
+ * @param error - The thrown value.
24
+ * @returns The outcome, or `undefined` for any other value.
25
+ */
26
+ export declare function outcomeOf(error: unknown): Outcome | undefined;
@@ -0,0 +1,36 @@
1
+ // Keyed with Symbol.for so the brand survives the duplicate module copies a native SSR
2
+ // bundle may load, and non-enumerable so it never reaches JSON.
3
+ const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
4
+ /**
5
+ * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
6
+ * or a handler.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * if (context.user === null) {
11
+ * throw forbidden();
12
+ * }
13
+ * ```
14
+ *
15
+ * @returns The error to `throw`.
16
+ */
17
+ export function forbidden() {
18
+ const error = new Error("RPC forbidden");
19
+ const outcome = { kind: "forbidden" };
20
+ Object.defineProperty(error, outcomeKey, { value: outcome });
21
+ return error;
22
+ }
23
+ /**
24
+ * Reads the outcome a thrown value carries, if it was created by an outcome factory.
25
+ * Internal.
26
+ *
27
+ * @param error - The thrown value.
28
+ * @returns The outcome, or `undefined` for any other value.
29
+ */
30
+ export function outcomeOf(error) {
31
+ if (typeof error !== "object" || error === null) {
32
+ return undefined;
33
+ }
34
+ const descriptor = Object.getOwnPropertyDescriptor(error, outcomeKey);
35
+ return descriptor?.value;
36
+ }
@@ -0,0 +1,164 @@
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 in your `@loozo/angular-launch:application` build target (or pass `tanstackQuery: true` to `generate`):
16
+
17
+ ```json
18
+ "options": {
19
+ "tsconfig": "tsconfig.app.json",
20
+ "scanDirectories": ["src/routes"],
21
+ "outDirectory": "generated",
22
+ "tanstackQuery": true
23
+ }
24
+ ```
25
+
26
+ 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.
27
+
28
+ Add TanStack's provider and `provideLaunchQueries()` to the application's providers, which the server config inherits:
29
+
30
+ ```ts
31
+ // src/config.ts
32
+ import { provideHttpClient } from "@angular/common/http";
33
+ import { provideClientHydration } from "@angular/platform-browser";
34
+ import { provideRouter } from "@angular/router";
35
+ import type { ApplicationConfig } from "@angular/core";
36
+ import { provideLaunchQueries } from "@loozo/angular-launch/tanstack-query";
37
+ import { provideTanStackQuery, QueryClient } from "@tanstack/angular-query";
38
+ import { routes } from "../generated/routes.generated";
39
+
40
+ export const config: ApplicationConfig = {
41
+ providers: [
42
+ provideHttpClient(),
43
+ provideClientHydration(),
44
+ provideRouter(routes),
45
+ provideTanStackQuery(() => new QueryClient()),
46
+ provideLaunchQueries(),
47
+ ],
48
+ };
49
+ ```
50
+
51
+ 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.
52
+
53
+ ## Queries and mutations
54
+
55
+ Call `injectQueries()` in an injection context, like `injectRpc()`, and pass its options to TanStack:
56
+
57
+ ```ts
58
+ // src/routes/+authenticated/todos/page.ts
59
+ import { Component, inject } from "@angular/core";
60
+ import { injectMutation, injectQuery, QueryClient } from "@tanstack/angular-query";
61
+ import { injectQueries, injectRpc } from "./rpc.generated";
62
+
63
+ @Component({/* … */})
64
+ export default class Todos {
65
+ readonly #rpc = injectRpc();
66
+ readonly #queries = injectQueries();
67
+ readonly #client = inject(QueryClient);
68
+ readonly todos = injectQuery(() => this.#queries.todos.list.queryOptions());
69
+ readonly #complete = injectMutation(() =>
70
+ this.#queries.todos.complete.mutationOptions({
71
+ onSuccess: () => this.#client.invalidateQueries({ queryKey: this.#queries.todos.$key() }),
72
+ }),
73
+ );
74
+
75
+ async complete(id: string): Promise<void> {
76
+ try {
77
+ await this.#complete.mutateAsync({ id });
78
+ } catch (error) {
79
+ if (this.#rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
80
+ const missingId: string = error.data.id;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ ```
86
+
87
+ Each query procedure has `queryOptions` and each mutation procedure `mutationOptions`, never both:
88
+
89
+ ```ts
90
+ queries.todos.list.queryOptions(overrides?); // a query without input
91
+ queries.todos.byId.queryOptions(input, overrides?); // a query with input
92
+ queries.todos.byId.queryOptions(skipToken); // disabled until there's an input
93
+ queries.todos.add.mutationOptions(overrides?); // variables are the input
94
+ queries.todos.clear.mutationOptions(overrides?); // no input: mutate() takes none
95
+ ```
96
+
97
+ 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.
98
+
99
+ 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.
100
+
101
+ ## Keys
102
+
103
+ Keys start with `"launch"` and the namespace, so a shorter key matches every longer key under it:
104
+
105
+ | Call | Key |
106
+ | ------------------------------------- | ------------------------------------------ |
107
+ | `queries.todos.$key()` | `["launch", "todos"]` |
108
+ | `queries.todos.list.key()` | `["launch", "todos", "list"]` |
109
+ | `queries.todos.byId.key()` | `["launch", "todos", "byId"]` |
110
+ | `queries.todos.byId.key({ id: "1" })` | `["launch", "todos", "byId", { id: "1" }]` |
111
+ | `queries.todos.add.key()` | `["launch", "todos", "add"]` |
112
+
113
+ `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`.
114
+
115
+ 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 `$`.
116
+
117
+ ## Invalidation
118
+
119
+ Nothing is invalidated for you. Invalidate in a mutation's `onSuccess`, by group, procedure or input:
120
+
121
+ ```ts
122
+ onSuccess: () => client.invalidateQueries({ queryKey: queries.todos.$key() }),
123
+ ```
124
+
125
+ 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`:
126
+
127
+ ```ts
128
+ onSuccess: () =>
129
+ client.invalidateQueries({ queryKey: queries.todos.$key() }, { throwOnError: true }),
130
+ ```
131
+
132
+ `mutateAsync` then rejects with the refetch's error, although the write itself succeeded.
133
+
134
+ ## Server rendering and hydration
135
+
136
+ 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).
137
+
138
+ 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.
139
+
140
+ 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.
141
+
142
+ The limits follow from TanStack's hydration:
143
+
144
+ - 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
+ - Queries are part of the HTML: only return data the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
146
+ - 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.
148
+
149
+ ## Defaults
150
+
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` |
155
+
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.
157
+
158
+ ## Limitations
159
+
160
+ - No infinite queries, optimistic-update helpers, automatic invalidation, mutation cancellation or persistence.
161
+ - Errors aren't dehydrated: a failed server query runs again in the browser.
162
+ - Only `@tanstack/angular-query`, not `@tanstack/angular-query-experimental`.
163
+ - 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.
164
+ - 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;