@loozo/angular-launch 0.0.5 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +1068 -187
  2. package/builders/application.js +32 -3
  3. package/builders/channel-forwarding.d.ts +15 -0
  4. package/builders/channel-forwarding.js +61 -0
  5. package/builders/options.d.ts +6 -2
  6. package/builders/options.js +16 -5
  7. package/builders/serve.js +198 -140
  8. package/channel.d.ts +55 -0
  9. package/channel.js +232 -0
  10. package/client.d.ts +63 -33
  11. package/connect.d.ts +201 -0
  12. package/connect.js +148 -0
  13. package/generation/index.d.ts +2 -123
  14. package/generation/index.js +3 -669
  15. package/generation/redirects.d.ts +14 -0
  16. package/generation/redirects.js +43 -0
  17. package/generation/run.d.ts +168 -0
  18. package/generation/run.js +659 -0
  19. package/index.d.ts +8 -1
  20. package/index.js +3 -0
  21. package/json.d.ts +9 -0
  22. package/json.js +24 -0
  23. package/launch-queries.d.ts +16 -0
  24. package/launch-queries.js +3 -0
  25. package/navigation.d.ts +36 -0
  26. package/navigation.js +47 -0
  27. package/node/index.d.ts +60 -0
  28. package/node/index.js +178 -0
  29. package/node/upgrade-listener-slot.d.ts +1 -0
  30. package/node/upgrade-listener-slot.js +4 -0
  31. package/outcomes.d.ts +71 -0
  32. package/outcomes.js +146 -0
  33. package/package.json +21 -11
  34. package/redirect-translation.d.ts +53 -0
  35. package/redirect-translation.js +141 -0
  36. package/{generated.d.ts → remote-client.d.ts} +1 -1
  37. package/remote-client.js +179 -0
  38. package/route-types.d.ts +130 -0
  39. package/route-types.js +1 -0
  40. package/route.d.ts +45 -0
  41. package/route.js +113 -0
  42. package/schemas/application.json +19 -3
  43. package/schemas/serve.json +3 -3
  44. package/server/application.d.ts +107 -0
  45. package/server/application.js +108 -0
  46. package/server/backend.d.ts +62 -31
  47. package/server/backend.js +149 -55
  48. package/server/channel-messages.d.ts +54 -0
  49. package/server/channel-messages.js +84 -0
  50. package/server/channel-socket.d.ts +67 -0
  51. package/server/channel-socket.js +322 -0
  52. package/server/definitions.d.ts +270 -294
  53. package/server/definitions.js +35 -115
  54. package/server/dispatch.d.ts +121 -66
  55. package/server/dispatch.js +267 -87
  56. package/server/event-stream.d.ts +63 -0
  57. package/server/event-stream.js +173 -0
  58. package/server/generated.d.ts +3 -1
  59. package/server/generated.js +3 -1
  60. package/server/index.d.ts +6 -3
  61. package/server/index.js +3 -2
  62. package/server/outcomes.d.ts +64 -2
  63. package/server/outcomes.js +85 -4
  64. package/server/read-cookies.d.ts +19 -0
  65. package/server/read-cookies.js +39 -0
  66. package/server/response-effects.d.ts +105 -0
  67. package/server/response-effects.js +78 -0
  68. package/server/stages.d.ts +62 -0
  69. package/server/stages.js +51 -0
  70. package/server/upgrade.d.ts +57 -0
  71. package/server/upgrade.js +116 -0
  72. package/source-text.d.ts +1 -0
  73. package/source-text.js +56 -0
  74. package/stream.d.ts +34 -0
  75. package/stream.js +161 -0
  76. package/tanstack-query/README.md +113 -21
  77. package/tanstack-query/create-queries.d.ts +2 -0
  78. package/tanstack-query/{generated.js → create-queries.js} +13 -11
  79. package/tanstack-query/hydration-window.d.ts +11 -0
  80. package/tanstack-query/hydration-window.js +9 -0
  81. package/tanstack-query/hydration.d.ts +4 -14
  82. package/tanstack-query/hydration.js +9 -12
  83. package/tanstack-query/index.d.ts +1 -1
  84. package/tanstack-query/queries.d.ts +50 -33
  85. package/testing/call-procedure.d.ts +154 -0
  86. package/testing/call-procedure.js +97 -0
  87. package/testing/index.d.ts +2 -0
  88. package/testing/index.js +1 -0
  89. package/generated.js +0 -90
  90. package/generation/context-file.d.ts +0 -2
  91. package/generation/context-file.js +0 -3
  92. package/tanstack-query/generated.d.ts +0 -5
package/README.md CHANGED
@@ -1,102 +1,116 @@
1
1
  # @loozo/angular-launch
2
2
 
3
- Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-router/README.md). You define queries and mutations in an `rpc.ts` file next to a route, and call them from that route's pages and resolvers through a generated, fully typed client.
3
+ Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md). A route declares its server behavior on its own `route.ts`: a context stage, middleware and queries, mutations, streams and channels. The route's pages and resolvers call them through a fully typed client on the route's handle.
4
4
 
5
- Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP requests. During server rendering they run in-process with the current request's context, and hydration reuses their responses through Angular's transfer cache. Errors you declare on a procedure come back typed on the client.
5
+ Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP requests. During server rendering they run in-process in the current request's scope, and hydration reuses their responses through Angular's transfer cache. Errors you declare on a procedure come back typed on the client.
6
6
 
7
7
  Use it when you want typed reads and writes between an Angular SSR app and its own server, without maintaining a separate API layer.
8
8
 
9
- **Status:** experimental. MIT license. It currently covers queries, mutations, middleware and declared errors, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md) options and keys, and Angular builders that generate before `ng build` and while `ng serve` runs. There are no subscriptions, optimistic updates, automatic invalidation or storage adapters.
9
+ **Status:** experimental. MIT license. It currently covers queries, mutations, streams (over server-sent events), channels (over websockets, on Node), middleware, declared errors and redirect and not-found outcomes, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md) options and keys, and Angular builders that generate before `ng build` and while `ng serve` runs. There are no storage adapters, and optimistic updates and invalidation come from TanStack Query through the integration.
10
10
 
11
11
  ## Requirements
12
12
 
13
- - Angular 22 with SSR: `@angular/core` and `@angular/common` `^22.0.0` and `rxjs` `^7.8.2` (the peer dependencies), plus `@angular/router`, `@angular/ssr` and `@angular/platform-server` as in the example. Tested with Angular 22.2.2.
14
- - `@angular/build` `~22.2.0`, for the builders. The range is narrow on purpose: the application builder's options schema is Angular's own at the version Launch was built against, so an option added in a later Angular minor is rejected until Launch is rebuilt against that minor.
13
+ - Angular 22 with SSR: `@angular/core`, `@angular/common` and `@angular/router` `^22.0.0` and `rxjs` `^7.8.2` (the peer dependencies), plus `@angular/ssr` and `@angular/platform-server` as in the example. Tested with Angular 22.3.0.
14
+ - `@angular/build` `~22.3.0`, for the builders. The range is narrow on purpose: the application builder's options schema is Angular's own at the version Launch was built against, so an option added in a later Angular minor is rejected until Launch is rebuilt against that minor. Launch follows the router's [Angular version policy](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#angular-versions) and releases in lockstep with it.
15
15
  - `@loozo/angular-router` at exactly the version Launch pins in its `peerDependencies`, as a dependency of your app. Launch generation writes the router's files too, through an internal router entry point, so the two must match; the exact peer dependency enforces that.
16
16
  - TypeScript 6 with strict checking. Generation rejects a tsconfig where any of `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes`, `strictBindCallApply`, `strictPropertyInitialization`, `strictBuiltinIteratorReturn`, `noImplicitThis` or `useUnknownInCatchVariables` is off, or where `noCheck` is on. `"strict": true` is enough unless a flag is explicitly turned off, including in an extended config. Generation never edits your tsconfig.
17
17
  - A `package.json` with a `name` in the application directory. The name is part of the generated app identity.
18
- - Optionally, `@tanstack/angular-query` `^5.0.0-rc.5` for the [TanStack Query integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md).
18
+ - Optionally, `@tanstack/angular-query` `^5.0.0-rc.5` for the [TanStack Query integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md), and `@angular/localize` for [translated URLs](#translated-urls).
19
19
 
20
20
  Install both packages:
21
21
 
22
22
  ```sh
23
- pnpm add @loozo/angular-launch @loozo/angular-router@0.0.6
23
+ pnpm add @loozo/angular-launch @loozo/angular-router@0.1.0
24
24
  ```
25
25
 
26
26
  ## How it fits together
27
27
 
28
28
  ```text
29
29
  src/
30
- ├── context.ts defineContext: per-request server context
31
30
  └── routes/
32
- ├── route.ts defineRoute("")
31
+ ├── route.ts defineRoute("").context(…): the per-request context
33
32
  └── +authenticated/
34
- ├── route.ts pathless route
35
- ├── rpc.ts defineRpc("session", …)
33
+ ├── route.ts a pathless route: .context(signedIn).remote(… session …)
36
34
  └── todos/
37
- ├── route.ts defineRoute("todos")
38
- ├── rpc.ts defineRpc("todos", …)
39
- ├── page.ts
40
- ├── route.generated.ts generated by the router
41
- └── rpc.generated.ts generated: injectRpc() with session and todos
35
+ ├── route.ts defineRoute("todos").remote(… todos …).resolve(…)
36
+ ├── page.ts injectRoute().remote.todos.list()
37
+ ├── destination.generated.ts generated by the router: URL facts for links and createUrl
38
+ └── route.generated.ts generated: the browser copy, Remote and Context, injectRoute()
42
39
  generated/
43
- ├── routes.generated.ts router: routes for provideRouter
44
- ├── destinations.generated.ts router
45
- ├── context.generated.d.ts registers your context type
46
- └── server.generated.ts createContext, handleRequest, provideServer
40
+ ├── routes.generated.ts router: routes for provideRouter, injectActiveRoute()
41
+ └── server.generated.ts createRequestScope, handleRequest, handleUpgrade, provideServer
47
42
  ```
48
43
 
49
- Generation writes a `route.generated.ts` and an `rpc.generated.ts` beside every route that has a page or descendants with pages, with or without a local group; the tree shows only the ones for `todos`. Redirect routes, and parents left with only redirects below them, get neither.
44
+ Import `defineRoute` from `@loozo/angular-launch` instead of the router in every `route.ts`. It's the router's `defineRoute` with three more steps offered first, `.context()`, `.use()` and `.remote()`, each at most once and in that order, before the router's own steps. All three run only on the server: the router writes each route's browser copy, `route.generated.ts`, without them, and Launch adds the route's procedure metadata, its `Remote` and `Context` types and `remote` on its `injectRoute()` handle. `server.generated.ts` imports the routes themselves, so the server runs the steps.
50
45
 
51
- The route tree is the router's. An `rpc.ts` belongs to the route declared in the same directory, which must be one of the routes that get these files; generation fails for an `rpc.ts` next to a redirect. Each route's `injectRpc()` exposes its own group and its ancestors' groups. File names are examples: generation finds context and RPC files by their default export, not their name.
46
+ A route sees its own namespaces and its ancestors'. App code, server code included, imports a route's `destination` or its `route.generated.ts`, never its `route.ts`.
52
47
 
53
48
  ## Setup
54
49
 
55
- The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.5/examples/angular-launch) is a complete app, and the snippets below are simplified from it. `db` and `sessions` stand for your own server-only modules: the example uses a test cookie instead of sessions, and its in-memory `db.todos.listForUser` also takes a test-only delay flag.
50
+ The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.1.0/examples/angular-launch) is a complete app, and the snippets below are simplified from it. `db` and `sessions` stand for your own server-only modules: the example uses a test cookie instead of sessions, and its in-memory `db.todos.listForUser` also takes a test-only delay flag.
56
51
 
57
- ### 1. Define the context
52
+ ### 1. Declare the context on the root route
58
53
 
59
- One file anywhere in your app's TypeScript sources default-exports `defineContext`. It runs once per live server request and its return value is the `context` every middleware and handler starts from:
54
+ The root route's `.context()` stage builds the context every procedure below it starts from:
60
55
 
61
56
  ```ts
62
- // src/context.ts
63
- import { defineContext } from "@loozo/angular-launch/server";
64
- import { db } from "./database.server";
65
- import { sessions } from "./sessions.server";
57
+ // src/routes/route.ts
58
+ import { defineRoute } from "@loozo/angular-launch";
59
+ import { db } from "../database.server";
60
+ import { sessions } from "../sessions.server";
66
61
 
67
- export default defineContext(async (request: Request) => ({
68
- request,
62
+ export default defineRoute("", {}).context(async ({ request }) => ({
69
63
  db,
70
64
  user: await sessions.authenticate(request),
71
65
  }));
72
66
  ```
73
67
 
74
- Generation registers the awaited return type, so `Context` from `@loozo/angular-launch/server` is your context type everywhere. Keep per-request state in the context rather than in module-level variables; the context is application-wide in type only.
68
+ A stage runs at most once per request scope, and only when a call needs it: a page render that makes no RPC runs none. Keep per-request state in the context rather than in module-level variables.
75
69
 
76
- ### 2. Define RPCs next to a route
70
+ ### 2. Declare procedures on a route
77
71
 
78
72
  ```ts
79
- // src/routes/+authenticated/todos/rpc.ts
80
- import { defineRpc } from "@loozo/angular-launch/server";
81
- import { signedIn } from "../../../auth.server";
73
+ // src/routes/+authenticated/route.ts
74
+ import { defineRoute } from "@loozo/angular-launch";
75
+ import { redirect } from "@loozo/angular-launch/server";
76
+ import { destination as signIn } from "../sign-in/destination.generated";
77
+ import parent from "../route";
78
+
79
+ export default defineRoute("", { parent })
80
+ .context(({ context }) => {
81
+ if (context.user === null) {
82
+ throw redirect(signIn, {});
83
+ }
84
+
85
+ return { ...context, user: context.user }; // `User | null` above, `User` below
86
+ })
87
+ .remote(({ query }) => ({
88
+ session: { current: query({ handler: ({ context }) => ({ user: context.user.id }) }) },
89
+ }));
90
+ ```
91
+
92
+ ```ts
93
+ // src/routes/+authenticated/todos/route.ts
94
+ import { defineRoute } from "@loozo/angular-launch";
82
95
  import { idSchema, titleSchema } from "../../../todo-input.server";
96
+ import parent from "../route";
83
97
 
84
- export default defineRpc(
85
- "todos",
86
- ({ query, mutation }) => ({
87
- list: query({
88
- handler: ({ context }) => context.db.todos.listForUser(context.user.id),
89
- }),
90
- add: mutation({
91
- input: titleSchema,
92
- handler: ({ input, context }) => context.db.todos.addForUser(context.user.id, input.title),
93
- }),
94
- }),
95
- { use: [signedIn] },
96
- );
98
+ export default defineRoute("todos", { parent })
99
+ .remote(({ query, mutation }) => ({
100
+ todos: {
101
+ list: query({
102
+ handler: ({ context }) => context.db.todos.listForUser(context.user.id),
103
+ }),
104
+ add: mutation({
105
+ input: titleSchema,
106
+ handler: ({ input, context }) => context.db.todos.addForUser(context.user.id, input.title),
107
+ }),
108
+ },
109
+ }))
110
+ .resolve({ todos: ({ remote }) => remote.todos.list() });
97
111
  ```
98
112
 
99
- `signedIn` is a [middleware](#middleware) that refuses calls without a user and narrows `context.user` for the handlers.
113
+ The `+authenticated` stage narrows `context.user` for every procedure at or below it, and its redirect refuses them for a signed-out caller. The `todos` route's resolver calls its own procedure through `remote`; see [Calling RPCs](#calling-rpcs).
100
114
 
101
115
  ### 3. Generate
102
116
 
@@ -125,7 +139,7 @@ Generation runs inside two Angular builders that replace your project's `build`
125
139
 
126
140
  `ng build` and `ng serve` then generate first, and `ng serve` regenerates as you edit. `ng run my-app:build:check` verifies the generated files without writing them, for CI. `tsconfig` is the TypeScript config generation reads; `tsConfig` is Angular's own compilation config. They can be the same file.
127
141
 
128
- Include the generated files, declarations included, in your app tsconfig: `"include": ["src/**/*.ts", "generated/**/*.ts"]`. See [Builders](#builders) for the builder options and [Generation](#generation) for what gets written.
142
+ Include the generated files in your app tsconfig: `"include": ["src/**/*.ts", "generated/**/*.ts"]`. See [Builders](#builders) for the builder options and [Generation](#generation) for what gets written.
129
143
 
130
144
  ### 4. Wire the browser and server apps
131
145
 
@@ -144,6 +158,8 @@ export const config: ApplicationConfig = {
144
158
  };
145
159
  ```
146
160
 
161
+ To have pages follow a procedure's [`redirect()` and `notFound()`](#redirects-and-not-found), add [`rpcNavigationErrors`](#navigating-on-outcomes) to `provideRouter`. With [translated URLs](#translated-urls), add `provideRedirectTranslation()` here too.
162
+
147
163
  The server config adds the generated `provideServer()`, after `provideHttpClient()`:
148
164
 
149
165
  ```ts
@@ -159,7 +175,7 @@ export const serverConfig = mergeApplicationConfig(config, {
159
175
  });
160
176
  ```
161
177
 
162
- Wrap the server bootstrap in `finishLaunchRendering`. If an RPC is called during prerendering, where there's no live request, this makes the build fail instead of producing a broken page:
178
+ Wrap the server bootstrap in `finishLaunchRendering`. If an RPC fails while Angular prerenders a page, this makes the build fail instead of producing a broken page (see [Prerendering](#prerendering)):
163
179
 
164
180
  ```ts
165
181
  // src/main.server.ts
@@ -175,7 +191,7 @@ export default async function bootstrap(context: BootstrapContext) {
175
191
  }
176
192
  ```
177
193
 
178
- In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `createContext`. Give `handleRequest` and Angular the same `allowedHosts` list (see [Hosts](#hosts)), and give the web request a signal that aborts when the client goes away (see [Aborted requests](#aborted-requests)). This is the Express server that Angular's SSR setup generates, with Launch added:
194
+ In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `createRequestScope`. Give `handleRequest` and Angular the same `allowedHosts` list (see [Hosts](#hosts)), and give the web request a signal that aborts when the client goes away (see [Aborted requests](#aborted-requests)). This is the Express server that Angular's SSR setup generates, with Launch added:
179
195
 
180
196
  ```ts
181
197
  // src/server.ts
@@ -187,8 +203,9 @@ import {
187
203
  isMainModule,
188
204
  writeResponseToNodeResponse,
189
205
  } from "@angular/ssr/node";
206
+ import { createUpgradeHandler } from "@loozo/angular-launch/node";
190
207
  import express from "express";
191
- import { createContext, handleRequest } from "../generated/server.generated";
208
+ import { createRequestScope, handleRequest, handleUpgrade } from "../generated/server.generated";
192
209
 
193
210
  const browser = join(import.meta.dirname, "../browser");
194
211
  // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
@@ -205,7 +222,8 @@ app.use(async (request, response, next) => {
205
222
 
206
223
  response.once("close", () => {
207
224
  if (!response.writableFinished) {
208
- closed.abort();
225
+ // Once Angular's helper has cancelled a body it was writing.
226
+ queueMicrotask(() => closed.abort());
209
227
  }
210
228
  });
211
229
 
@@ -219,7 +237,7 @@ app.use(async (request, response, next) => {
219
237
  return;
220
238
  }
221
239
 
222
- const scope = await createContext(web);
240
+ const scope = createRequestScope(web); // runs nothing until an RPC needs a stage
223
241
  const page = await angular.handle(scope.request, scope);
224
242
 
225
243
  if (!page) {
@@ -230,118 +248,240 @@ app.use(async (request, response, next) => {
230
248
 
231
249
  await writeResponseToNodeResponse(page, response);
232
250
  } catch (error) {
251
+ // Angular rejects a render whose client left; there's no one to answer.
252
+ if (response.destroyed && error instanceof DOMException && error.name === "AbortError") {
253
+ return;
254
+ }
255
+
233
256
  next(error);
234
257
  }
235
258
  });
236
259
 
260
+ // Channels arrive as websocket upgrades, which Express never sees.
261
+ const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
262
+
237
263
  if (isMainModule(import.meta.url)) {
238
264
  const port = process.env["PORT"] || 4000;
239
-
240
- app.listen(port, (error) => {
265
+ const server = app.listen(port, (error) => {
241
266
  if (error) {
242
267
  throw error;
243
268
  }
244
269
 
245
270
  console.log(`Listening on http://localhost:${port}`);
246
271
  });
272
+
273
+ server.on("upgrade", upgrade);
247
274
  }
248
275
 
249
276
  export const reqHandler = createNodeRequestHandler(app);
250
277
  ```
251
278
 
252
- Angular's dev server and build use the exported `reqHandler`; `listen` only runs when you start the built server yourself (see [Deploying](#deploying)). The server must serve the `browser` build output itself: Angular's engine doesn't serve script or style files. Express isn't required; see [Other server frameworks](#other-server-frameworks).
279
+ Angular's dev server and build use the exported `reqHandler`; `listen` only runs when you start the built server yourself (see [Deploying](#deploying)). The server must serve the `browser` build output itself: Angular's engine doesn't serve script or style files. Express isn't required; see [Other server frameworks](#other-server-frameworks). The upgrade handler only matters if you define [channels](#channels); `ng serve` uses it too. See [Channels on Node](#channels-on-node).
280
+
281
+ Import `server.generated` before any module that reaches a route, as above: with [translated URLs](#translated-urls) that order is required.
253
282
 
254
- Always pass `scope.request` together with `scope`, not your original request. The scope ties the context to the request Angular renders; if they don't match, RPC calls during rendering fail with `INTERNAL` and a server log entry. This catches wiring mistakes only; it doesn't check your authentication.
283
+ Always pass `scope.request` together with `scope`, not your original request. The scope ties the render's stages to the request Angular renders; if they don't match, RPC calls during rendering fail with `INTERNAL` and a server log entry. This catches wiring mistakes only; it doesn't check your authentication.
255
284
 
256
- ## Defining RPCs
285
+ ## Declaring server behavior on routes
257
286
 
258
- `defineRpc(namespace, build, options?)` declares a group. `build` receives the `query` (a read) and `mutation` (a write) builders and returns the group's procedures:
287
+ A route's server steps come before its router steps, each at most once, in this order:
259
288
 
260
289
  ```ts
261
- defineRpc(
262
- "todos",
263
- ({ query, mutation }) => ({
264
- list: query({ input?, use?, errors?, handler }),
265
- add: mutation({ input?, use?, errors?, handler }),
266
- }),
267
- { use? },
268
- );
290
+ defineRoute("todos", { parent })
291
+ .context(stage) // derive this route's context from its ancestors'
292
+ .use(...middleware) // wrap this route's own procedures
293
+ .remote(({ query, mutation, stream, channel }) => ({
294
+ todos: {
295
+ list: query({ input?, use?, errors?, handler }),
296
+ add: mutation({ input?, use?, errors?, handler }),
297
+ watch: stream({ input?, use?, errors?, handler }),
298
+ },
299
+ }))
300
+ .resolve({ … }); // router steps follow, typed with `remote`
269
301
  ```
270
302
 
271
- The handler receives `{ context, input, errors, request, signal }` and returns a value or a promise. `request` is the request the call runs in: the RPC request over HTTP, or the page request during server rendering. `signal` aborts when the caller goes away; see [Calling RPCs](#calling-rpcs).
303
+ ### Context stages
272
304
 
273
- - **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine. One `defineRpc` per route, and each namespace is unique across the app because it names the group's URL.
274
- - **The callback** is read without running it: an arrow function that destructures `query` and/or `mutation` without renaming, returning a parenthesized object literal in which each procedure is a direct `query(...)` or `mutation(...)` call with inline options.
305
+ `.context(stage)` derives a route's context. The stage receives `{ context, request, response, signal }`: the context of the stages above it (`{}` at the first), the request scope's request and signal, and the [cookies and headers](#cookies-and-headers) of the call that first needs it. It returns the route's whole context, an object or a promise of one, which the stages and procedures below receive as it is, type included. To add to the context above, spread it: `({ context }) => ({ ...context, user })`.
306
+
307
+ - **When it runs:** at most once per request scope, and only for an RPC call whose namespace sits at or below it. A call runs the stages from the root down to the route that declared its namespace; a page render that makes no RPC runs none. Its result, failures included, is reused by every later call in the scope, such as every call in one server render.
308
+ - **Refusing:** a stage can `throw forbidden()`, `notFound()` or `redirect(destination, values)`, which answers every call that needs it with that [outcome](#redirects-and-not-found): a signed-out stage on a pathless route refuses its whole subtree. Any other exception fails those calls with `INTERNAL`, logged with the route whose stage threw.
309
+ - **Its value** can be any object type: a union, an object with optional keys or a class instance, which keeps its methods. A key above that the stage doesn't return is gone below it, and so is its type.
310
+ - **Standalone stages** type their argument with `StageArgs` from `@loozo/angular-launch/server` and the context they receive, such as the parent route's `Context` from its `route.generated.ts`:
311
+
312
+ ```ts
313
+ // src/auth.server.ts
314
+ import { redirect, type StageArgs } from "@loozo/angular-launch/server";
315
+ import type { Context } from "./routes/route.generated";
316
+ import { destination as signIn } from "./routes/sign-in/destination.generated";
317
+
318
+ export function signedIn({ context }: StageArgs<Context>) {
319
+ if (context.user === null) {
320
+ throw redirect(signIn, {});
321
+ }
322
+
323
+ return { ...context, user: context.user };
324
+ }
325
+ ```
326
+
327
+ A stage function shared by two routes still runs once per route.
328
+
329
+ ### Procedures
330
+
331
+ `.remote(build)` declares the route's procedures in namespaces. `build` receives the `query` (a read), `mutation` (a write), `stream` (a read that sends values while it runs) and `channel` (a conversation over a websocket) builders. The route and its descendants call them as `route.remote.<namespace>.<procedure>`.
332
+
333
+ The handler receives `{ context, input, errors, request, signal, response }` and returns a value or a promise; a [stream's](#streams) returns an async iterable. `context` is what the stages from the root to this route built. It can also throw a [declared error](#declared-errors) or an [outcome](#redirects-and-not-found). `request` is the request the call runs in: the RPC request over HTTP, the page request during server rendering, or a cookie-less `GET` of the page's URL while Angular [prerenders](#prerendering) it. `signal` aborts when the caller goes away; see [Calling RPCs](#calling-rpcs). `response` sets cookies and headers; see [Cookies and headers](#cookies-and-headers).
334
+
335
+ - **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine. A route may declare several namespaces, and each is unique across the app because it names the procedures' URLs.
336
+ - **The callback** is read without running it: an arrow function that destructures any of `query`, `mutation`, `stream` and `channel` without renaming, returning a parenthesized object literal of namespaces, each an object literal in which each procedure is a direct builder call with inline options.
275
337
  - **Inputs** are [Standard Schema](https://standardschema.dev) V1 schemas, from any library or written by hand. Validation can be async and can transform the value: callers pass the schema's input type, and procedure middleware and handlers receive its output. The `input` schema must have a concrete type without `undefined` or `null` branches, though its caller input type may be a union such as `Schema<string | number, …>`. Omit `input` for a procedure without input.
338
+ - **A namespace belongs to the route that declares it.** A call runs that route's stages and `.use()` middleware, whichever page called it: the session namespace above runs the root and `+authenticated` stages even when `todos` calls it.
276
339
 
277
- Availability isn't authorization: anyone who can reach your server can call any procedure, so protect every group and procedure that needs it with middleware. Route params aren't passed to procedures automatically; pass what you need as input and validate it.
340
+ Availability isn't authorization: anyone who can reach your server can call any procedure, so protect every route and procedure that needs it with a stage or middleware. Route params aren't passed to procedures automatically; pass what you need as input and validate it.
278
341
 
279
342
  ### Middleware
280
343
 
281
- Middleware runs around a call to refuse it, add typed values to its context, or wrap the rest of it:
344
+ Middleware runs around a call to refuse it or wrap the rest of it:
282
345
 
283
346
  ```ts
284
- // src/auth.server.ts
285
- import { forbidden, middleware } from "@loozo/angular-launch/server";
347
+ // src/timing.server.ts
348
+ import { middleware } from "@loozo/angular-launch/server";
286
349
 
287
- export const signedIn = middleware(async ({ context, next }) => {
288
- if (context.user === null) {
289
- throw forbidden();
350
+ export const timing = middleware(async ({ next, response }) => {
351
+ const start = performance.now();
352
+
353
+ try {
354
+ return await next();
355
+ } finally {
356
+ response.headers.append("server-timing", `rpc;dur=${(performance.now() - start).toFixed(1)}`);
290
357
  }
358
+ });
359
+ ```
291
360
 
292
- return next({ user: context.user }); // later middleware and handlers see a non-null user
361
+ List middleware in a route's `.use()` to run it for that route's own procedures, or in a procedure's `use` to run it for that procedure. Middleware used in one place can be a bare async function written in the list, which receives the route's context, and on a procedure the validated input, already typed:
362
+
363
+ ```ts
364
+ defineRoute("todos", { parent }).use(async ({ context, next }) => {
365
+ log(context.user.id); // the stages' User
366
+
367
+ return next();
293
368
  });
294
369
  ```
295
370
 
296
- List middleware in the group's `use` to run it for every procedure in the group, or in a procedure's `use` to run it for that procedure. A call runs, in order:
371
+ A call runs, in order:
297
372
 
298
- 1. the group's middleware, with no input;
299
- 2. input validation;
300
- 3. the procedure's middleware, with the validated input;
301
- 4. the handler.
373
+ 1. the stages from the root to the route that declared the namespace;
374
+ 2. that route's `.use()` middleware, with no input;
375
+ 3. input validation;
376
+ 4. the procedure's middleware, with the validated input;
377
+ 5. the handler.
302
378
 
303
- So a caller that group middleware refuses gets `FORBIDDEN` even when its input is invalid, and can't probe your schemas.
379
+ So a caller that a stage or the route's middleware refuses gets that answer even when its input is invalid, and can't probe your schemas.
304
380
 
305
- - **`next()`** continues the call. `next(values)` also merges `values` into the context by spread, so the context must be a plain object: a class instance would lose its prototype. An addition is a single object type with required keys, since a missing optional value would leave the earlier one in place, and a union could hide such a key in one of its members. Write a value that may be missing as `next({ user: maybeUser })` with a type such as `User | null`, and alternatives as a union value, such as `next({ session: a | b })`. Every `next(...)` in a middleware adds the same keys, so `next({ user: null })` in one branch and `next()` in another is a type error. A value that differs per branch goes in one `next()` call with a union-typed value, such as `next({ user: preview ? null : context.user })` or a variable typed `User | null`. The context is read-only at the top level, so `context.user = null` is a type error: add and replace values through `next()`, where later middleware and handlers see their types. A middleware must call `next` exactly once and return its result; calling it twice or returning anything else fails the call with `INTERNAL`.
306
- - **Wrapping:** `next()` rejects when anything after it throws, declared errors included, so a middleware can time, log or run the rest of the call in a transaction that rolls back:
381
+ - **`next()`** continues the call and resolves to the result the middleware must return. Middleware doesn't change the context: derive values in a [stage](#context-stages). A middleware must call `next` exactly once and return its result; calling it twice or returning anything else fails the call with `INTERNAL`.
382
+ - **Wrapping:** `next()` rejects when anything after it throws, declared errors included, so a middleware can time, log or run the rest of the call in a transaction that rolls back.
383
+ - **Refusing:** `throw forbidden()` fails the call with `FORBIDDEN`, and `throw notFound()` or `throw redirect(destination, values)` answer it with that [outcome](#redirects-and-not-found); a handler can throw them too. Any other exception fails the call with `INTERNAL`. Declared errors belong to handlers.
384
+ - **Needs:** a `middleware()` needs nothing unless you say so, so it fits anywhere. Pass the context it reads as a type argument, or annotate its argument with `MiddlewareArgs<Needs, Input>` to require an input shape too. Written inline, `middleware(…)` doesn't pick up the route's context type either, so write inline middleware as a bare function and keep `middleware()` for middleware you share.
307
385
 
308
386
  ```ts
309
- export const timing = middleware(async ({ next }) => {
310
- const start = performance.now();
387
+ export const audit = middleware<{ user: User }>(async ({ context, next }) => {
388
+ log(context.user.id);
311
389
 
312
- try {
313
- return await next();
314
- } finally {
315
- console.log(`RPC took ${(performance.now() - start).toFixed(1)} ms`);
316
- }
390
+ return next();
317
391
  });
318
- ```
319
-
320
- - **Refusing:** `throw forbidden()` fails the call with `FORBIDDEN`; a handler can throw it too. Any other exception fails the call with `INTERNAL`. Declared errors belong to handlers.
321
- - **Needs:** a middleware without an annotation needs your `Context` and accepts any input, so it fits anywhere. Annotate its argument with `MiddlewareArgs<Needs, Input>` to require values that earlier middleware adds, or an input shape:
322
392
 
323
- ```ts
324
393
  export const ownTodo = middleware(
325
394
  async ({ context, input, next }: MiddlewareArgs<{ user: User; db: Db }, { id: string }>) => {
326
- const todo = await context.db.todos.findForUser(context.user.id, input.id);
327
-
328
- if (todo === null) {
395
+ if ((await context.db.todos.findForUser(context.user.id, input.id)) === null) {
329
396
  throw forbidden();
330
397
  }
331
398
 
332
- return next({ todo });
399
+ return next();
333
400
  },
334
401
  );
335
402
  ```
336
403
 
337
- Each `use` entry must accept the context and input accumulated before it, and the error lands on the entry that doesn't (`… is not assignable to type 'never'`). Group middleware gets no input, so a middleware that needs input only fits on a procedure.
404
+ Each entry must accept the route's context, its own stage included, and the input; the error lands on the entry that doesn't, including a bare function whose annotated argument asks for more. A route's `.use()` gets no input, so a middleware that needs input only fits on a procedure.
405
+
406
+ - **Server rendering:** stages and middleware run for every call, also during server rendering, where `request` is the page request: usually a `GET` navigation with `Sec-Fetch-Site: none` or `cross-site`. Request-shaped checks, such as on the method or `Sec-Fetch-Site`, misfire there, which is why Launch's own [cross-origin check](#cross-origin-requests) isn't middleware and runs over HTTP only.
407
+ - `.use()` isn't inherited through the route tree: a child route's procedures don't run it. There's no dedupe: middleware listed in both `.use()` and a procedure runs twice.
408
+
409
+ ### Cookies and headers
410
+
411
+ Stages, middleware and handlers set cookies and headers through `response`:
412
+
413
+ ```ts
414
+ login: mutation({
415
+ input: credentialsSchema,
416
+ errors: { WRONG_CREDENTIALS: { status: 401, message: "Wrong email or password", data: nullSchema } },
417
+ handler: async ({ input, context, response, errors }) => {
418
+ const session = await context.sessions.signIn(input.email, input.password);
419
+
420
+ if (session === null) {
421
+ throw errors.WRONG_CREDENTIALS(null);
422
+ }
423
+
424
+ // Defaults: Path=/; HttpOnly; Secure; SameSite=Lax
425
+ response.setCookie("session", session.token, { maxAge: 60 * 60 * 24 * 30 });
426
+
427
+ return { user: session.userId };
428
+ },
429
+ }),
430
+ logout: mutation({
431
+ handler: async ({ context, response }) => {
432
+ await context.sessions.end(context.sessionToken);
433
+ response.deleteCookie("session");
434
+
435
+ return null;
436
+ },
437
+ }),
438
+ ```
439
+
440
+ - **`response.setCookie(name, value, options?)`** adds a `Set-Cookie` header. Options are `path` (default `/`), `domain`, `maxAge` in whole seconds, `expires`, `httpOnly` (default `true`), `secure` (default `true`) and `sameSite` (`"lax"` by default, `"strict"` or `"none"`, which needs `secure`). Browsers keep `Secure` cookies from `http://localhost`, so the defaults work in development; a plain-HTTP deployment on another hostname needs `secure: false`. Values aren't encoded for you: encode anything outside printable ASCII, or with spaces, `"`, `,`, `;` or `\`, first. An invalid name, value or option throws a `TypeError`, which fails the call with `INTERNAL`.
441
+ - **`response.deleteCookie(name, options?)`** expires a cookie. Pass the `path`, `domain` and security options it was set with, or the browser keeps it.
442
+ - **`response.headers`** is a `Headers` object for the RPC response. Launch's own headers (`Content-Type`, `Cache-Control`, `Vary`, `X-Content-Type-Options`) replace any you set, and the status comes from the call's outcome, never from `response`. Use `setCookie` for cookies: a `Set-Cookie` header written here is dropped during server rendering like any other header.
443
+ - **Every outcome** carries them, failures included: a cookie set before a declared error, `forbidden()` or an `INTERNAL` failure is still sent. What a cookie records has usually happened by then, such as a session a middleware refreshed before the handler failed. So set a cookie after the steps that make it true, as `login` above does: a failure before that sends none.
444
+ - **During server rendering**, cookies go on the page response, including a redirect Angular answers with, and headers are dropped, since a page's headers mustn't depend on which queries it ran. Angular copies the page's headers once the app is first stable, so only calls that settle before then send their cookies: those from guards, resolvers and rendering do, while a call made later, such as one awaited in a `BEFORE_APP_SERIALIZED` hook, still runs but its cookies are lost. Hydration reuses transferred results without calling the server, so the page response is the only chance to send such a cookie. Every call in a render shares the render's request scope, whose stages read the page request's cookies, so a cookie one call sets isn't visible to later calls. A failed initial navigation, such as a resolver whose RPC fails, makes `angular.handle` return `null`, and the cookies set during that render are lost with the page. Handle the failure in the route if they matter, so the page renders and carries them.
445
+ - **When they're sent:** once the call settled, or for a [stream](#streams) once its handler returned its iterable. After that, setting a cookie throws and header changes are ignored, so a wrapping middleware such as `timing` above can add a header after `await next()` for queries and mutations, and it's ignored for streams.
446
+ - **A stage's cookies** go to the call that ran it, once per scope: the first call that needs the stage carries them, and later calls reuse the stage's result without setting them again.
447
+
448
+ A stage can refresh a session cookie. It runs once per request scope, so the refresh runs once per page render or RPC request, however many calls need it:
449
+
450
+ ```ts
451
+ // src/session.server.ts
452
+ import type { StageArgs } from "@loozo/angular-launch/server";
453
+ import type { Context } from "./routes/route.generated"; // the root's sessions and token
454
+
455
+ export function session({ context, response }: StageArgs<Context>) {
456
+ const current = context.sessions.read(context.token);
457
+
458
+ if (current !== null && current.expiresSoon) {
459
+ response.setCookie("session", context.sessions.extend(current), { maxAge: 60 * 60 * 24 * 30 });
460
+ }
461
+
462
+ return { ...context, user: current?.user ?? null };
463
+ }
464
+ ```
465
+
466
+ Concurrent RPC requests from the browser each have their own scope, so each can still refresh. Your session store has to accept that, with a sliding expiry or by keeping the old token valid for a short while. That also keeps the session usable when a refreshed cookie never arrives, as after a failed render.
467
+
468
+ `readCookies(request)` from `@loozo/angular-launch/server` reads a request's cookies, such as the root's `token` the stage above reads:
469
+
470
+ ```ts
471
+ // src/routes/route.ts
472
+ import { defineRoute } from "@loozo/angular-launch";
473
+ import { readCookies } from "@loozo/angular-launch/server";
474
+ import { sessions } from "../sessions.server";
475
+
476
+ export default defineRoute("", {}).context(({ request }) => ({
477
+ sessions,
478
+ token: readCookies(request).get("session") ?? null,
479
+ }));
480
+ ```
338
481
 
339
- - **Server rendering:** middleware runs for every call, also during server rendering, where `request` is the page request: usually a `GET` navigation with `Sec-Fetch-Site: none` or `cross-site`. Request-shaped checks, such as on the method or `Sec-Fetch-Site`, misfire there, which is why Launch's own [cross-origin check](#cross-origin-requests) isn't middleware and runs over HTTP only.
340
- - There's no dedupe: middleware listed in both the group and a procedure runs twice. Middleware isn't inherited through the route tree.
341
- - **Known limits:**
342
- - Casting an addition to `object` or `{}`, or deliberately widening a middleware's result type, hides the keys it adds, so the context type no longer matches what runs.
343
- - Only the top level of the context is read-only. Writing to a nested object, such as `context.session.user = null`, can still invalidate a narrowing nested inside it.
344
- - Separate `next({ user: null })` and `next({ user: context.user })` calls don't infer `User | null` when `context.user` is a `User`; write the single-call form above.
482
+ - **It returns** a read-only `Map` of cookie values by name: `get` returns `undefined` for a cookie the request doesn't carry, and `Object.fromEntries(cookies)` gives a plain object, such as for a log. Values come as the browser sent them, without decoding, as `setCookie` doesn't encode them.
483
+ - **A repeated name** reads as its first occurrence in the header. Browsers usually send the cookie with the longer path first, such as one set for `/todos` before one set for `/`, but the header doesn't say which path or domain each came from, so don't rely on which one wins: give cookies that mustn't collide distinct names. Pairs without a name are skipped.
484
+ - **It reads the request you pass**, so during server rendering every call sees the page request's cookies, not the ones calls set earlier in the render, and a prerendered page reads none.
345
485
 
346
486
  ### JSON values
347
487
 
@@ -373,12 +513,12 @@ Each error needs an identifier code, an integer literal `status` from 400 to 599
373
513
 
374
514
  Launch itself uses four codes, which you can't declare:
375
515
 
376
- | Code | Status | When |
377
- | --------------- | ------ | ----------------------------------------------------------------------------------------------------------------- |
378
- | `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
379
- | `FORBIDDEN` | 403 | `forbidden()` was thrown, the request wasn't proven same-origin, or a mutation was called during server rendering |
380
- | `RPC_NOT_FOUND` | 404 | No such procedure |
381
- | `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
516
+ | Code | Status | When |
517
+ | --------------- | ------ | --------------------------------------------------------------------------------------------------------------------------- |
518
+ | `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
519
+ | `FORBIDDEN` | 403 | `forbidden()` was thrown, the request wasn't proven same-origin, or a mutation or stream was called during server rendering |
520
+ | `RPC_NOT_FOUND` | 404 | No such procedure |
521
+ | `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
382
522
 
383
523
  `INTERNAL` never exposes details to the client; they go to the server log. Your own `NOT_FOUND` is fine, but `__proto__` can't be an error code.
384
524
 
@@ -386,9 +526,9 @@ Launch itself uses four codes, which you can't declare:
386
526
 
387
527
  ```ts
388
528
  try {
389
- await rpc.todos.add({ title });
529
+ await remote.todos.add({ title });
390
530
  } catch (error) {
391
- if (rpc.todos.add.isError(error) && error.code === "INVALID_INPUT") {
531
+ if (remote.todos.add.isError(error) && error.code === "INVALID_INPUT") {
392
532
  for (const issue of error.data.issues) {
393
533
  showError(issue.path, issue.message); // ["title"], "Title must contain 1–200 characters"
394
534
  }
@@ -396,24 +536,149 @@ try {
396
536
  }
397
537
  ```
398
538
 
539
+ ### Redirects and not found
540
+
541
+ A page that can't be shown, because the visitor must sign in first or the thing it shows doesn't exist, is answered with an outcome from `@loozo/angular-launch/server` instead of an error code. Stages, middleware and handlers throw them:
542
+
543
+ ```ts
544
+ // src/routes/+authenticated/route.ts
545
+ import { defineRoute } from "@loozo/angular-launch";
546
+ import { redirect } from "@loozo/angular-launch/server";
547
+ import { destination as signIn } from "../sign-in/destination.generated";
548
+ import parent from "../route";
549
+
550
+ // Every procedure at or below this route answers a signed-out caller with the redirect.
551
+ export default defineRoute("", { parent }).context(({ context }) => {
552
+ if (context.user === null) {
553
+ throw redirect(signIn, {});
554
+ }
555
+
556
+ return { ...context, user: context.user };
557
+ });
558
+ ```
559
+
560
+ ```ts
561
+ import { notFound } from "@loozo/angular-launch/server";
562
+
563
+ get: query({
564
+ input: idSchema,
565
+ handler: async ({ input, context }) => {
566
+ const todo = await context.db.todos.findForUser(context.user.id, input.id);
567
+
568
+ // Another user's todo is missing too.
569
+ if (todo === null) {
570
+ throw notFound();
571
+ }
572
+
573
+ return todo;
574
+ },
575
+ }),
576
+ ```
577
+
578
+ - **`redirect(destination, values)`** goes to `createUrl(destination, values)`, and takes the same arguments: a `destination` from a `destination.generated.ts`, and its params, search and fragment, `{}` for none. Wrong values fail to type-check, and a URL string is a type error, so only declared pages are targets: to send the visitor on afterwards, declare a search key such as `next` on the sign-in route and pass `redirect(signIn, { search: { next: createUrl(todos, {}) } })`. An external redirect, such as to an OAuth provider, is data your page acts on.
579
+ - **On the wire** a redirect is a 303 with `{ "redirect": { "to": "/sign-in" } }` and no `Location` header (with [translated URLs](#translated-urls), also its `words`), so `fetch` hands it to the client instead of following it, and not-found is a 404 with `{ "notFound": null }`. Only status 200 is a result: a handler that returns `{ redirect: { to } }` returns data.
580
+ - **On the client** the call rejects with `RpcRedirect` (with its `to`) or `RpcNotFound` from `@loozo/angular-launch`. They aren't `RpcError`s, so `isError` is false for them. Nothing navigates for you, except in a guard or resolver with [`rpcNavigationErrors`](#navigating-on-outcomes).
581
+ - **Not-found isn't `RPC_NOT_FOUND`**, which means no such procedure, and it doesn't take a declared `NOT_FOUND` code. Use `notFound()` when the page can't be shown, and a declared error when the page handles the case itself, as the example's `complete` does.
582
+
583
+ ### Streams
584
+
585
+ A stream sends values while it runs, such as a list that changes or an answer that's still being written. Its handler returns an async iterable, usually written as an `async function*`:
586
+
587
+ ```ts
588
+ export default defineRoute("live", { parent }).remote(({ stream }) => ({
589
+ live: {
590
+ watch: stream({
591
+ handler: async function* ({ context, signal }) {
592
+ yield* context.db.todos.watchForUser(context.user.id, signal);
593
+ },
594
+ }),
595
+ },
596
+ }));
597
+ ```
598
+
599
+ Write the handler as `handler: async function* (…) { … }`: generation doesn't accept method shorthand (`async *handler() { … }`). A stream takes the same `input`, `use` and `errors` options as a query. It's a read, and it doesn't run during server rendering (see [Calling streams](#calling-streams)).
600
+
601
+ - **Values** must be strict JSON, like results, and each reaches the caller as soon as it's yielded. A value that isn't ends the stream with `INTERNAL`. The handler returns nothing: returning a value is a type error.
602
+ - **Yield the current state first.** A caller that reconnects starts a new call and the handler starts over, so a stream of snapshots loses nothing across a reconnect, while a stream of changes loses those made in between.
603
+ - **Stages and middleware** run once per stream, before the handler, with one context. `next()` settles when the stream ends: it resolves when the handler finishes or the caller goes away, and rejects when the handler throws. Wrapping middleware therefore spans the whole stream; one that opens a transaction keeps it open as long as the stream runs. Nothing is checked again while the stream runs, so a handler that must notice a revoked session checks before each value.
604
+ - **Cookies and headers** are sent with the stream's response, which starts once the handler returned its iterable. Set them in a stage, in middleware before `next()`, or in a handler that isn't a generator, before it returns one: an `async function*` handler's body runs after the response started, so setting a cookie there throws and ends the stream with `INTERNAL`. See [Cookies and headers](#cookies-and-headers).
605
+ - **Failures** before the handler returns its iterable, such as a refusing stage or middleware or invalid input, are ordinary responses with their status, as for a query. After that the response has started: a declared error, an outcome or any other exception ends the stream with that error. An `async function*` handler's body only runs once the response has started, so outcomes it throws arrive as an `error` event, such as `{"status":404,"notFound":null}`.
606
+ - **Cancellation:** when the caller stops reading or goes away, the handler's `signal` aborts and the generator is asked to return, which runs its `finally` blocks once it next yields. A generator waiting on something that ignores the signal finishes that wait first, and middleware's `next()` resolves only once the generator has returned. Hosts cancel a response body when its client goes away while it's being sent, but a client that leaves earlier, while the stages or middleware still run, is noticed only through the request's signal. Keep the server entry's [abort wiring](#aborted-requests), or such a stream runs until it ends by itself.
607
+
608
+ A stream is called with a `POST` like any procedure. Its response is `text/event-stream`: one `value` event per value, then one `end` or `error` event, and a `: keep-alive` comment every 15 seconds so proxies don't close an idle connection. Every `data` line is strict JSON:
609
+
610
+ ```text
611
+ event: value
612
+ data: [{"id":"1","title":"Review todos","completed":false}]
613
+
614
+ event: error
615
+ data: {"status":404,"error":{"code":"NOT_FOUND","message":"Todo does not exist","data":{"id":"1"}}}
616
+ ```
617
+
618
+ ### Channels
619
+
620
+ A channel is a stream that also listens: the caller sends messages while the handler yields values, over one websocket. Use it for a conversation, such as a chat or an editor that sends edits and gets the document back. Its options are a stream's plus a required `message` schema, and its handler also receives `messages`:
621
+
622
+ ```ts
623
+ export default defineRoute("live", { parent }).remote(({ channel }) => ({
624
+ live: {
625
+ // The user's todos now, then again after each title the caller sends is added.
626
+ add: channel({
627
+ message: titleSchema,
628
+ handler: async function* ({ context, messages }) {
629
+ yield await context.db.todos.snapshotForUser(context.user.id);
630
+
631
+ for await (const { title } of messages) {
632
+ await context.db.todos.addForUser(context.user.id, title);
633
+ yield await context.db.todos.snapshotForUser(context.user.id);
634
+ }
635
+ },
636
+ }),
637
+ },
638
+ }));
639
+ ```
640
+
641
+ Everything in [Streams](#streams) applies: values are strict JSON, the handler is written `handler: async function* (…)`, yields the current state first and returns nothing, stages and middleware run once and `next()` settles when the channel ends, cookies must be set before the handler returns its iterable, and the handler's `signal` aborts and its generator is returned when the caller goes away. `input`, if any, is read once, when the channel opens; `message` follows the same concrete-type rule as `input`, and its caller input type is what the client's `send` takes. Channels don't run during server rendering: they fail with `FORBIDDEN` before any stage or middleware.
642
+
643
+ - **Messages** are validated with `message` as the handler reads them, in the order they arrived. A message that fails validation ends the call with `INVALID_INPUT` and the schema's issues, also when the handler catches the error. `messages` has one consumer: a second iterator throws. It ends when the caller closes the channel, after the messages already received, so a handler waiting on it returns normally; its `signal` aborts at the same time.
644
+ - **Flow control** keeps both sides bounded. The server sends at most 256 values the caller hasn't read, and the caller at most 32 messages the handler hasn't read; each side grants more as it reads half its window. A caller that stops reading pauses the handler at its `yield` (it returns at once if the caller then leaves), and a handler that stops reading `messages` makes the caller's `send` wait. The server also stops pulling values while the socket buffers more than 1 MiB of unsent data, checking every 50 ms. Throughput is about 256 values per network round trip.
645
+ - **Failures** before the handler returns its iterable, such as a refusing stage or middleware, invalid input or a missing procedure (`RPC_NOT_FOUND`), still upgrade the socket, which receives the failure and closes, so the client sees the procedure's own error. Host, shape and [origin](#cross-origin-requests) checks happen earlier, before any stage runs, and are refused with a plain HTTP response as for any RPC; a browser doesn't expose that response, so the client sees only a `TypeError`. The server log says why.
646
+ - **Input rides in the URL** (`?input=…`), so it's limited by the server's header size: Node refuses headers over 16 KiB with 431, which the client sees as a `TypeError`. Send large data as messages.
647
+ - **Ending:** once the handler ends, the server sends the end or the error and closes. A message the caller sends while that's on its way is dropped.
648
+
649
+ A channel is a `GET /_rpc/<namespace>/<procedure>?input=<encoded strict JSON>` upgraded to a websocket by the generated `handleUpgrade`; `handleRequest` answers a channel's path with `RPC_NOT_FOUND`, and `handleUpgrade` answers any other procedure the same way. Every frame is strict JSON text:
650
+
651
+ ```text
652
+ caller → server {"message":{"title":"Buy milk"}} one message
653
+ {"ready":128} "I've read 128 more values"
654
+ server → caller {"value":[{"id":"1","title":"Buy milk","completed":false}]}
655
+ {"ready":16} "the handler read 16 more messages"
656
+ {"end":null}, or a failure such as {"status":410,"error":{"code":"GONE","message":"Gone","data":null}}
657
+ then the server closes with 1000
658
+ ```
659
+
660
+ A binary or malformed frame, a message beyond the caller's credit, or a grant for more values than were sent ends the call with `INVALID_INPUT` without issues. Failure frames are exactly a stream's `error` event data.
661
+
399
662
  ## Calling RPCs
400
663
 
401
- Each route that has a page or descendants with pages gets an `rpc.generated.ts` with `injectRpc()`, even without its own group; redirect routes don't. Call it in an injection context:
664
+ A route's handle carries its client: `injectRoute().remote` from the route's `route.generated.ts` has the route's own namespaces and its ancestors'. Call `injectRoute()` in an injection context, such as a field initializer; reading `remote` and calling it later, from an event or after an `await`, is fine:
402
665
 
403
666
  ```ts
404
667
  import { Component } from "@angular/core";
405
- import { injectRpc } from "./rpc.generated";
668
+ import { injectRoute } from "./route.generated";
406
669
 
407
670
  @Component({/* … */})
408
671
  export default class Todos {
409
- readonly #rpc = injectRpc();
672
+ readonly route = injectRoute();
410
673
 
411
674
  async complete(id: string): Promise<void> {
675
+ const { todos } = this.route.remote;
676
+
412
677
  try {
413
- await this.#rpc.todos.complete({ id });
414
- await this.#rpc.todos.list(); // read again explicitly; nothing is invalidated for you
678
+ await todos.complete({ id });
679
+ await todos.list(); // read again explicitly; nothing is invalidated for you
415
680
  } catch (error) {
416
- if (this.#rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
681
+ if (todos.complete.isError(error) && error.code === "NOT_FOUND") {
417
682
  const missingId: string = error.data.id;
418
683
  }
419
684
  }
@@ -421,46 +686,183 @@ export default class Todos {
421
686
  }
422
687
  ```
423
688
 
424
- Every call returns a promise. Procedures with input take the input first and options second; procedures without input take only options:
689
+ Every query and mutation call returns a promise; [streams](#calling-streams) return an async iterable and [channels](#calling-channels) an open channel, and both can be followed as signals with [`connect()`](#following-streams-and-channels-with-connect). Procedures with input take the input first and options second; procedures without input take only options:
425
690
 
426
691
  ```ts
427
- await rpc.todos.list();
428
- await rpc.todos.list({ signal, transferCache: false });
429
- await rpc.todos.add({ title }, { signal });
692
+ await remote.todos.list();
693
+ await remote.todos.list({ signal, transferCache: false });
694
+ await remote.todos.add({ title }, { signal });
430
695
  ```
431
696
 
432
- | Option | Effect |
433
- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
434
- | `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server's middleware and handler see their `signal` abort, but aborting is advisory: work that ignores it finishes, and a write may already have committed. |
435
- | `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
697
+ | Option | Effect |
698
+ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
699
+ | `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server's stages, middleware and handler see their `signal` abort, but aborting is advisory: work that ignores it finishes, and a write may already have committed. |
700
+ | `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
436
701
 
437
- `isError(error)` is true only for errors returned by that exact procedure, and narrows them to its declared errors plus the four framework codes. Network failures and aborts are not `RpcError`s. For a type, use `ClientRpcError<typeof group.procedures.complete>` from `@loozo/angular-launch`. Each callable also has a literal `kind` of `"query"` or `"mutation"`.
702
+ `isError(error)` is true only for errors returned by that exact procedure, and narrows them to its declared errors plus the four framework codes. Network failures, aborts and the [outcomes](#redirects-and-not-found) `RpcRedirect` and `RpcNotFound` are not `RpcError`s. Each callable also has a literal `kind` of `"query"`, `"mutation"`, `"stream"` or `"channel"`.
438
703
 
439
- Route resolvers can call RPCs too, which is how a page gets its data during SSR:
704
+ Route resolvers, guards and titles kept on a route get the same client as `remote`, which is how a page gets its data during SSR:
440
705
 
441
706
  ```ts
442
707
  // src/routes/+authenticated/todos/route.ts
443
- import { defineRoute } from "@loozo/angular-router";
444
- import parent from "../route";
445
- import { injectRpc } from "./rpc.generated";
708
+ export default defineRoute("todos", { parent })
709
+ .remote(/* … */)
710
+ .resolve({ session: ({ remote }) => remote.session.current() });
711
+ ```
446
712
 
447
- export default defineRoute("todos", {
448
- parent,
449
- resolve: {
450
- session: () => injectRpc().session.current(),
451
- },
452
- });
713
+ A route copy exports its client's type as `Remote`, for example to type a result: `Awaited<ReturnType<Remote["todos"]["list"]>>` with `import type { Remote } from "./route.generated"`. It names the server's types through the route's declaration, erased, so no server code reaches the browser bundle.
714
+
715
+ A narrowed [active route](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md) handle carries the same `remote`, so a shell can call the active page's procedures. Its client is built with the injector of the `injectActiveRoute()` caller, not the route's: providers a route adds, such as an `HttpClient` interceptor, reach only that route's own `injectRoute()`.
716
+
717
+ ### Navigating on outcomes
718
+
719
+ `rpcNavigationErrors({ notFound })` from `@loozo/angular-launch` is a navigation error handler for Angular's `withNavigationErrorHandler`:
720
+
721
+ ```ts
722
+ // src/config.ts
723
+ import { provideRouter, withNavigationErrorHandler } from "@angular/router";
724
+ import { rpcNavigationErrors } from "@loozo/angular-launch";
725
+ import { createUrl } from "@loozo/angular-router";
726
+ import { destination as notFound } from "./routes/not-found/destination.generated";
727
+
728
+ provideRouter(
729
+ routes,
730
+ withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
731
+ );
732
+ ```
733
+
734
+ When a guard or resolver's call rejects with `RpcRedirect`, the navigation goes to its `to` instead; during server rendering Angular answers the page request with a 302 to it. When it rejects with `RpcNotFound`, the `notFound` page is rendered while the address bar keeps the requested URL; during server rendering the page is answered with status 404. Other errors are left to Angular.
735
+
736
+ - Only navigation acts on outcomes. A call from a component, a click handler or a TanStack query just rejects.
737
+ - With Angular's `withErrorBoundaries`, an outcome thrown while a page renders, such as from a resource its template reads, reaches the boundary's error component as its `error` input. `rpcNavigationErrors` never sees it, so it neither redirects nor answers 404.
738
+ - Angular takes one navigation error handler. If your app has its own, call the function `rpcNavigationErrors` returns from it, inside that handler's injection context, and return its result.
739
+ - The 404 needs the route's `RenderMode.Server`. While Angular prerenders a page, an outcome fails the build instead; see [Prerendering](#prerendering).
740
+
741
+ ### Calling streams
742
+
743
+ In a component, follow a stream with [`connect()`](#following-streams-and-channels-with-connect), which handles rendering, reconnecting on input changes and cleanup. Underneath, a stream's callable returns an async iterable instead of a promise, and takes only `signal` as an option:
744
+
745
+ ```ts
746
+ for await (const todos of remote.live.watch({ signal })) {
747
+ this.todos.set(todos);
748
+ }
749
+ ```
750
+
751
+ Each iteration sends a new request; leaving the loop early or aborting `signal` closes it. Iteration:
752
+
753
+ - ends after the stream's last value;
754
+ - throws an `RpcError` that the callable's `isError` recognizes, for a framework or declared error, and an `RpcRedirect` or `RpcNotFound` for an outcome, whether the stream was refused or ended with it;
755
+ - throws an `AbortError` when `signal` aborts;
756
+ - throws a `TypeError` when the connection fails or closes before the stream ended.
757
+
758
+ Nothing reconnects for you. To reconnect, iterate again, typically after a `TypeError` and a pause; retrying doesn't help after an `RpcError`. Each reconnect is a new call in a fresh request scope, and the stream starts over from the handler's first value.
759
+
760
+ Streams use the browser's `fetch`, not `HttpClient`, so HTTP interceptors don't see them. An `HttpClient` request keeps the app from becoming stable until it completes and keeps its whole response in memory, which an open stream would do for as long as it runs. Cookies are sent as for any same-origin request.
761
+
762
+ Streams don't run during server rendering: there, iterating one fails at once with `FORBIDDEN`, before any stage or middleware runs. Render the page from a query, then follow the stream in the browser; an open stream doesn't keep the app from becoming stable.
763
+
764
+ TanStack Query options aren't generated for streams; see the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md#limitations).
765
+
766
+ ### Calling channels
767
+
768
+ A channel's callable opens the websocket at once and returns the channel: iterate it for the handler's values and `send` messages to it. It takes only `signal` as an option:
769
+
770
+ ```ts
771
+ const adding = remote.live.add({ signal });
772
+
773
+ const sending = (async () => {
774
+ for (const title of titles) {
775
+ await adding.send({ title }); // typed by the channel's message schema
776
+ }
777
+ })();
778
+
779
+ for await (const todos of adding) {
780
+ this.todos.set(todos); // typed by what the handler yields
781
+ }
782
+ ```
783
+
784
+ - **Read while you send.** Each side's window fills when the other stops reading: the server stops at 256 values you haven't read, and `send` waits once 32 messages are unread on the server. So read in a loop that runs alongside your sends, as above. Awaiting a batch of sends before reading stalls for good once both windows fill: with a handler that yields once per message, `for (const title of thousandTitles) await adding.send({ title })` followed by the read loop never gets to the loop. Its sends stop after about 290: 256 values wait unread, so the handler stops at its next `yield` and reads no more messages, and the next 32 wait unread on the server. [`connect()`](#following-streams-and-channels-with-connect) always reads, so it can't stall this way.
785
+ - **`send`** resolves once the message is handed to the socket. Messages sent before the socket opens, or while the server has no room, wait in order. It rejects with the channel's closing error if the channel closes first (an `AbortError` after `signal` aborts, a `TypeError` after the channel ended or the connection closed), with a `TypeError` once the channel is closed, and with a `TypeError` for a message that isn't strict JSON.
786
+ - **Iteration** works like a stream's: it ends after the handler's last value, throws the callable's own `RpcError` or an `RpcRedirect` or `RpcNotFound` for a failure, an `AbortError` when `signal` aborts and a `TypeError` when the connection closes early, the server refused the handshake or sent a malformed frame. Values that arrive before you read them are kept, up to the server's window; aborting `signal` drops the ones not read yet, also after the handler ended. Reads may overlap: each settles in order. A channel has one iterator: iterating it twice throws. Leaving the loop early, as `break` does, or aborting `signal` closes the socket, and the handler sees its `messages` end and its `signal` abort.
787
+ - **Nothing reconnects for you,** and each call is new: a new request scope, the handler's first value again.
788
+
789
+ Channels use the browser's `WebSocket`, with the URL resolved against the page as `ws:` or `wss:`, and send the page's cookies. HTTP interceptors don't see them, and an open channel doesn't keep the app from becoming stable. During server rendering a channel fails at once with `FORBIDDEN`, without connecting. TanStack Query options aren't generated for channels.
790
+
791
+ ### Following streams and channels with `connect()`
792
+
793
+ A stream's or channel's callable also has `connect()`, which follows it as signals. Call it in an injection context, such as a field initializer:
794
+
795
+ ```ts
796
+ @Component({
797
+ template: `
798
+ <ul>
799
+ @for (todo of todos.value(); track todo.id) {
800
+ <li>{{ todo.title }}</li>
801
+ }
802
+ </ul>
803
+ @if (todos.status() === "failed") {
804
+ <p>Lost the live list. <button (click)="todos.reconnect()">Reconnect</button></p>
805
+ }
806
+ <form (submit)="add($event, title)">
807
+ <input #title required maxlength="200" />
808
+ <button [disabled]="adding.status() !== 'open'">Add</button>
809
+ </form>
810
+ `,
811
+ })
812
+ export default class Live {
813
+ readonly #route = injectRoute();
814
+ // The server renders the resolver's list; after hydration the stream follows it.
815
+ protected readonly todos = this.#route.remote.live.watch.connect({
816
+ initial: () => this.#route.data().todos,
817
+ });
818
+ protected readonly adding = this.#route.remote.live.add.connect({ initial: () => null });
819
+
820
+ protected async add(event: SubmitEvent, input: HTMLInputElement): Promise<void> {
821
+ event.preventDefault();
822
+
823
+ try {
824
+ await this.adding.send({ title: input.value.trim() });
825
+ input.value = "";
826
+ } catch {
827
+ // adding.status() and adding.error() say why.
828
+ }
829
+ }
830
+ }
453
831
  ```
454
832
 
455
- `Client<typeof group>` from `@loozo/angular-launch` gives you the client type for a group, for example to type a result: `Awaited<ReturnType<Client<typeof group>["list"]>>`. Import the group with `import type` so server code stays out of the browser bundle.
833
+ The options are:
834
+
835
+ | Option | Effect |
836
+ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
837
+ | `input` | Read reactively. A change closes the connection and opens a new one; `undefined` keeps it closed with status `"idle"`. Required for a procedure with input, returning its input. A procedure without input connects by default; a function returning `null` connects and `undefined` keeps it closed. |
838
+ | `initial` | The value until the first value arrives, read reactively until then; also what the server renders. |
839
+ | `reduce` | Optional. `(state, value) => state` folds each value into the state, starting from `initial()` for each new call. Without it, the state is the latest value. |
840
+
841
+ It returns a connection:
842
+
843
+ | Member | Meaning |
844
+ | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
845
+ | `value` | A signal of the state. It's kept through failures and reconnects until a value from the new call replaces it. |
846
+ | `status` | A signal of `"idle"` (no input, or on the server), `"connecting"`, `"open"`, `"ended"` (the handler ended) or `"failed"`. |
847
+ | `error` | A signal of what failed it while `"failed"`: the procedure's `RpcError` (narrow it with the callable's `isError`), an `RpcRedirect` or `RpcNotFound`, a `TypeError` for a lost or refused connection, or the `Error` `reduce` threw (anything else it throws becomes an `Error` with it as `cause`); `undefined` otherwise. |
848
+ | `reconnect()` | After `"ended"` or `"failed"`, opens a new call, starting from the handler's first value. Does nothing otherwise. |
849
+ | `send()` | Channels only. Waits while connecting and for the server's room while open, and resolves once the message is handed to the socket. Rejects with a `TypeError` while idle, ended or failed; with the same error `error()` shows when the connection fails while it waits, also when `reduce` throws; and with an `AbortError` when Launch closes the call first, for a new input, `reconnect()` or the injection context's destruction. |
850
+
851
+ On the server it never connects: `status` is `"idle"` and `value` is `initial()`. In the browser it connects after the next render. It doesn't use `HttpClient` or Angular's pending tasks, so an open connection never keeps the app from becoming stable, and destroying the injection context closes it. It reads every value as it arrives, so channel sends never stall the way they can [when you iterate yourself](#calling-channels).
852
+
853
+ - A failed connection keeps showing the last value; show `status()` or `error()` next to it so the page doesn't look current.
854
+ - Every change of `input` reconnects, without a debounce.
855
+ - The first render shows `initial()`, also after hydration, until the first value arrives.
856
+ - `reduce` runs untracked and must be pure; what it throws fails the connection.
857
+ - A `send` you don't await or catch surfaces its rejection as an unhandled rejection.
456
858
 
457
859
  ### With TanStack Query
458
860
 
459
- With the `tanstackQuery` generation option, each `rpc.generated.ts` also exports `injectQueries()`: typed query and mutation options and keys for the same groups, for `@tanstack/angular-query`. See the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation and hydration.
861
+ With the `tanstackQuery` generation option, each route's handle also has `queries`, and its copy exports `Queries`: typed query and mutation options and keys for the same namespaces as `remote`, for `@tanstack/angular-query`. See the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation, optimistic updates and hydration.
460
862
 
461
863
  ## Server rendering and hydration
462
864
 
463
- During server rendering, calls run directly on the server with the context created for that page request. Queries are stored in Angular's HTTP transfer cache, so hydration reuses the responses instead of calling the server again. After the app is stable, calls are ordinary HTTP requests, each with a fresh context. Opt a query out with `{ transferCache: false }`. Queries run through [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
865
+ During server rendering, calls run directly on the server with the context created for that page request. Queries are stored in Angular's HTTP transfer cache, so hydration reuses the responses instead of calling the server again. After the app is stable, calls are ordinary HTTP requests, each with a fresh context. Opt a query out with `{ transferCache: false }`. Queries run through [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
464
866
 
465
867
  The reuse has limits, all of them Angular's transfer cache behaving as designed:
466
868
 
@@ -468,14 +870,437 @@ The reuse has limits, all of them Angular's transfer cache behaving as designed:
468
870
  - The cache serves calls made before the app first becomes stable. RPCs called later, for example from a `@defer` block that hydrates on interaction or when it enters the viewport, go over HTTP.
469
871
  - Launch relies on your app's transfer cache settings. `withNoHttpTransferCache()`, or a `withHttpTransferCacheOptions` `filter` that rejects `/_rpc/` requests, turns reuse off without any error, and every query runs again in the browser.
470
872
 
471
- Mutations are refused during server rendering with `FORBIDDEN`, before any middleware, validation or the handler runs. Rendering should only read.
873
+ Outcomes in a guard or resolver become a 302 or a 404 page with [`rpcNavigationErrors`](#navigating-on-outcomes), and both have caveats:
874
+
875
+ - A server-rendered not-found page calls the procedure again over HTTP during hydration, because only successes transfer, so its handler runs twice. A redirect doesn't: the browser follows the 302.
876
+ - Any other failure of a guard or resolver during server rendering, such as `FORBIDDEN`, `INTERNAL`, a declared error, or an outcome without `rpcNavigationErrors`, fails the initial navigation. Angular then renders no page and `angular.handle` returns `null`, so your server's fallback answers, such as the example's plain 404, without the cookies calls set during the render. Handle such errors in the route if the page should show something, or throw an outcome instead.
472
877
 
473
- Middleware and handlers run during server rendering too, with the page request as `request`. Their `signal` aborts when the page request aborts, or when `HttpClient` unsubscribes from the call before it settled.
878
+ Mutations are refused during server rendering with `FORBIDDEN`, before any stage, middleware, validation or the handler runs. Rendering should only read. Streams are refused the same way, since they don't finish; see [Calling streams](#calling-streams).
474
879
 
475
- RPCs need a live request. Prerendering a page that calls an RPC fails the build (with `finishLaunchRendering` in place); static pages that don't call RPCs prerender normally. Blocking initial navigation (`withEnabledBlockingInitialNavigation`) combined with a root resolver that calls an RPC isn't supported.
880
+ Stages, middleware and handlers run during server rendering too, with the page request as `request`. A render's calls share one request scope, so each stage runs at most once per render. They run in the server entry's copy of your server code, the one that answers RPCs: Angular bundles the server entry apart from the server application that renders, so a module both import, such as your database client, is loaded once in each, and Launch runs a render's calls in the copy that created its request scope. A page and an RPC therefore see the same module state, such as an in-memory store or a connection pool. The other copy still evaluates the module, so whatever it starts at import time, such as a pool's connections or a timer, starts twice: create those on first use instead. While Angular [prerenders](#prerendering) a page, its calls run in the server application's copy. Their `signal` aborts when the page request aborts, or when `HttpClient` unsubscribes from the call before it settled. Cookies they set go on the page response through Angular's `RESPONSE_INIT`, and headers are dropped; see [Cookies and headers](#cookies-and-headers).
476
881
 
477
882
  Transferred responses end up in the HTML. Only return data that the user may see, and serve personalized pages with `Cache-Control: private, no-store`.
478
883
 
884
+ ### Prerendering
885
+
886
+ A page Angular prerenders at build time can call queries:
887
+
888
+ ```ts
889
+ // src/rendering.ts
890
+ export const rendering: ServerRoute[] = [
891
+ { path: "about", renderMode: RenderMode.Prerender },
892
+ { path: "**", renderMode: RenderMode.Server },
893
+ ];
894
+ ```
895
+
896
+ Angular prerenders without a request, so Launch creates the page's request scope from a cookie-less `GET` of the page's URL, and every call in that render shares it. A prerendered page shows what an anonymous visitor would see: a stage or middleware that needs a signed-in user refuses, and that fails the build.
897
+
898
+ Every call made while prerendering must succeed. With [`finishLaunchRendering`](#4-wire-the-browser-and-server-apps) in place, the build fails and names the call when one answers with anything but a result: a declared error, a framework code (such as `FORBIDDEN` from a stage or middleware, or for a mutation or stream), `notFound()` or `redirect()`. It also fails when a call sets a cookie, since a prerendered page is a file with no response to carry it, and when a context stage throws: the error names the stage's route and has the stage's error as its `cause`. Without it, Angular can write the page with the failure rendered into it, or skip the page and still report success.
899
+
900
+ Launch checks once the app is first stable, which covers calls from guards, resolvers and rendering. That's the last point where a render can still fail: Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their errors. So a call made later, such as one awaited in such a hook, isn't checked, and the page is written whether it fails or sets a cookie. Don't make Launch calls there.
901
+
902
+ The results reach the browser inside the page, as during server rendering: through Angular's transfer cache, or TanStack's hydration. Loading the page makes no RPC. Every call after that, such as a refetch, an invalidation or a client-side navigation to the page, is an ordinary HTTP request to your server, with the visitor's own request scope. So:
903
+
904
+ - Queries on a prerendered page should answer the same for everyone. One that reads the user shows the anonymous answer in the HTML, then the visitor's after its next call.
905
+ - Everything a prerendered call returns is in a file served to every visitor.
906
+ - The app still needs its server. A static deployment (`outputMode: "static"`) can't answer `/_rpc/`, so there, a client-side navigation to a prerendered page that calls an RPC fails.
907
+ - Context stages run at build time, at most once per prerendered page, in Angular's prerender workers, so whatever they use, such as a database, must be reachable from the build. The request's URL has the page's path on a local origin Angular picks, such as `http://localhost:<port>`; don't build absolute links from it.
908
+ - `ng serve` renders prerendered routes on every request the same way, anonymously whatever cookies the browser sends.
909
+ - With [translated URLs](#translated-urls), prerendered calls run in that locale's server app, so `createUrl` in a procedure returns the locale's words there, unlike on a live server.
910
+ - Angular's prerender timeout doesn't reach handlers: their `signal` aborts when the render's application is destroyed, or when `HttpClient` unsubscribes from the call.
911
+
912
+ Blocking initial navigation (`withEnabledBlockingInitialNavigation`) works with `finishLaunchRendering`. With it, Angular also runs the initial navigation to `/` while it discovers your routes at build time, so resolvers on the routes that match `/`, such as the root route's, make their calls then, once, with the anonymous context. A call refused there, such as one that needs a signed-in user, doesn't fail the build: Angular logs the error and still finds every route. Pages you prerender still fail the build for it, as above, and server-rendered pages make the call again with each visitor's context. Angular documents blocking initial navigation for server rendering without hydration, and Launch apps hydrate: hydration is what enables the HTTP transfer cache.
913
+
914
+ ## Translated URLs
915
+
916
+ The router can [translate static URL segments](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#translated-urls) per Angular localize build, so the German build serves `/de/anmelden` where the source build serves `/en/sign-in`. A Launch app turns it on in its application builder, and Launch then also puts every RPC redirect in the page's language: a German visitor sent to sign in lands on `/de/anmelden`, whether the redirect reaches them through a call in the browser or as the 302 that answers a server-rendered page.
917
+
918
+ Set it up in this order:
919
+
920
+ 1. Turn on `translateSegments` with Angular's `i18n`, `localize` and the `@angular/localize/init` polyfill, as the router's guide describes, and add `"types": ["@angular/localize"]` to the app tsconfig. With several locales, serve one at a time from a development configuration such as `"localize": ["de"]`: Angular's dev server doesn't localize a multi-locale `localize: true` build.
921
+
922
+ ```jsonc
923
+ // angular.json (excerpt)
924
+ "i18n": { "sourceLocale": "en", "locales": { "de": "src/locale/messages.de.xlf" } },
925
+ "build": {
926
+ "builder": "@loozo/angular-launch:application",
927
+ "options": {
928
+ "translateSegments": true,
929
+ "localize": true,
930
+ "i18nMissingTranslation": "error",
931
+ "polyfills": ["@angular/localize/init"]
932
+ // …the rest as in Setup
933
+ }
934
+ }
935
+ ```
936
+
937
+ 2. Import `server.generated` in `server.ts` before any import that reaches a route: an authored module that imports a `destination.generated.ts` or `route.generated.ts`, directly or through other modules. The setup above already does. Angular runs no polyfills in the server entry, so `server.generated.ts` first installs a `$localize` that returns each message's source text, and any destination copy evaluated before it fails the build, or the server's start, with `ReferenceError: $localize is not defined`.
938
+
939
+ The server entry must stay in the source language: if something else installs a `$localize` there first that translates, such as `loadTranslations` or a catalog loaded at runtime, Launch keeps it, and redirects are then built from translated words. That isn't supported. A word the page's build doesn't know stays as it is, so the German page can't match the URL; and a translated word that happens to be another route's canonical word is translated again, which reaches the wrong page: with `sign-in` → `anmelden` and a route whose canonical word is `anmelden`, a German visitor sent to sign in lands on that route's German path instead.
940
+
941
+ 3. Add `provideRedirectTranslation()` from the generated `redirects.generated.ts` to the config both apps share. Generation fails until some application file imports it; it can't check that both the browser and the server app install it, so put it in `config.ts`, which `config.server.ts` merges:
942
+
943
+ ```ts
944
+ // src/config.ts
945
+ import { provideRedirectTranslation } from "../generated/redirects.generated";
946
+
947
+ export const config: ApplicationConfig = {
948
+ providers: [
949
+ provideHttpClient(),
950
+ provideClientHydration(),
951
+ provideRouter(
952
+ routes,
953
+ withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
954
+ ),
955
+ provideRedirectTranslation(),
956
+ ],
957
+ };
958
+ ```
959
+
960
+ An app that leaves it out redirects German visitors to the source-language path, which the German build can't match: navigation stays where it was, and the server answers a guarded German page as if it had no page.
961
+
962
+ Procedures don't change. `redirect(signIn, {})` builds the source-language URL on the server, whose code Angular never localizes, and the redirect frame also lists which of its path segments, counted from 0, are static words: `{ "redirect": { "to": "/sign-in", "words": [0] } }`. The page's own build, in the browser or rendering a live request, swaps those segments for its words when its generated client recognizes the frame, so `RpcRedirect.to` is `/anmelden` in the German build: exactly what `createUrl(signIn, {})` returns there. Parameter and catchall values, the search and the fragment stay as they are, as they do in that build's `createUrl`.
963
+
964
+ A destination in a [named outlet](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#named-outlets) counts its anchor's segments first, then its group's, and its outlet name is never a word, even when it's spelled like one. `redirect(item, { params: { team: "products", id: "3" } })` for `item/$id` in the `detail` outlet below `teams/$team` is `{ "to": "/teams/products/(detail:item/3)", "words": [0, 2] }`; the German build makes it `/mannschaften/products/(detail:artikel/3)`, and `/(chat:chat/7)` at the root becomes `/(chat:plaudern/7)`.
965
+
966
+ Which page a translated URL reaches is the router's: Launch's redirect equals the German link byte for byte, and generation rejects a catalog that puts one route's translated path under a catchall Angular tries first, where the source words don't ([Translated URLs](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#translated-urls)).
967
+
968
+ What stays in the source language:
969
+
970
+ - The wire frame, and what every `HttpInterceptor` sees of it, in the browser and during server rendering. With the option on, an interceptor or a test that compares redirect bodies exactly sees `words` too.
971
+ - URLs inside search values: `redirect(signIn, { search: { next: createUrl(todos, {}) } })` sends the visitor on to the source-language `next` after signing in, which the German build can't match. Pass an id instead and build the URL in the page.
972
+ - URLs a procedure returns as data, sets in a `Location` header through `response`, logs, or sends by email or webhook, and redirects your `server.ts` issues itself. While prerendering, procedures run in the localized server app, so `createUrl` there returns that locale's words: return ids and build URLs in the page.
973
+ - [`callProcedure`](#testing-handlers-stages-and-middleware) results, which never carry `words`.
974
+
975
+ A browser still running the client of a build from before the option was turned on doesn't recognize a frame with `words` and rejects with Angular's `HttpErrorResponse` until it reloads.
976
+
977
+ **Language switcher and hreflang.** The router's `localeUrls(destination, values)` and the active route's `localeUrls` signal work in a Launch app as they do with the router's own builders: Launch's application and serve builders hand the router every configured locale's base href and words, from the catalogs generation just checked, so the German sign-in page `/de/anmelden` links to `/en/sign-in`. Use the router's [switcher and hreflang snippets](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#translated-urls) as they are; its rules for which locales are listed, what's carried and when the list is empty apply unchanged. Live server rendering, prerendering and the browser all see the same list. A localized build gets it without `translateSegments` too, with your source words under each locale's base. The builders pass it as Angular's `define.loozoRouterLocales`, so that key is reserved in your own `define`, in the build and the serve options.
978
+
979
+ `ng serve` also watches the catalogs: an edit runs the router's per-locale checks again and logs a `Locale de: …` error without stopping the server. Angular's dev server applies a catalog at its next rebuild, not at the edit. A single-locale `ng serve` (`"localize": ["de"]`) gets the switcher's list with its own locale at the dev server's unprefixed base, `/anmelden`, and the list keeps the words `ng serve` started with: after an edit that changes them, it logs `Locale words changed (route.segment.guarded in de). Links from localeUrls keep the words ng serve started with until you restart it.` Restart it to refresh the list. The other locales' links point at builds this dev server doesn't serve, so check them in a production build.
980
+
981
+ ## Testing
982
+
983
+ Point Angular's unit-test builder at the Launch application target, the same way `ng new` points it at the official one:
984
+
985
+ ```json
986
+ "test": {
987
+ "builder": "@angular/build:unit-test",
988
+ "options": { "buildTarget": "app:build", "tsConfig": "tsconfig.spec.json" }
989
+ }
990
+ ```
991
+
992
+ `ng test` doesn't run generation; it uses the generated files already on disk. After you add, move or remove routes or procedures, run `ng build` first, or keep `ng serve` running. `ng test` warns that the `buildTarget` uses `@loozo/angular-launch:application`, "which is not supported". The warning is expected: the unit-test builder reads the target's options, and Angular ignores Launch's own ones.
993
+
994
+ Give specs their own `tsconfig.spec.json` with `"types": ["vitest/globals"]`, and exclude `src/**/*.spec.ts` from the application tsconfig, which also keeps them out of generation's type check. With `vitest/globals`, the imports from `vitest` below are optional.
995
+
996
+ The specs below run in this package's CI against the [snippets app](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.1.0/packages/angular-launch/snippets), whose `todos` route has a `list` query and a `complete` mutation with a declared `NOT_FOUND`, behind a `signedIn` stage.
997
+
998
+ ### Testing components and resolvers
999
+
1000
+ A route's client needs only `HttpClient`: a query or mutation is a `POST /_rpc/<namespace>/<procedure>` with the body `{ "input": … }`, `null` for a procedure without input. So Angular's HTTP testing providers work, and `HttpTestingController` answers the calls. `injectRoute()` needs its route's activated record, so test a page, or a component inside one, through the router: navigate with `RouterTestingHarness` over the generated routes, answer the resolver's calls, then use the page's `route.remote` or the component it rendered:
1001
+
1002
+ `snippets/src/routes/todos/todo-item.spec.ts`
1003
+
1004
+ ```ts
1005
+ import { provideHttpClient } from "@angular/common/http";
1006
+ import { HttpTestingController, provideHttpClientTesting } from "@angular/common/http/testing";
1007
+ import { TestBed } from "@angular/core/testing";
1008
+ import { By } from "@angular/platform-browser";
1009
+ import { provideRouter } from "@angular/router";
1010
+ import { RouterTestingHarness } from "@angular/router/testing";
1011
+ import { beforeEach, describe, expect, it, vi } from "vitest";
1012
+ import { routes } from "../../../generated/routes.generated.js";
1013
+ import TodosPage from "./page.js";
1014
+ import { TodoItem } from "./todo-item.js";
1015
+
1016
+ // TodoItem reads the todos route's handle, so it renders inside the page the router shows.
1017
+ async function renderedItem() {
1018
+ const http = TestBed.inject(HttpTestingController);
1019
+ const harness = await RouterTestingHarness.create();
1020
+ const navigation = harness.navigateByUrl("/todos", TodosPage);
1021
+
1022
+ await vi.waitFor(() =>
1023
+ http.expectOne("/_rpc/todos/list").flush([{ id: "1", title: "Buy milk", completed: false }]),
1024
+ );
1025
+ await navigation;
1026
+ harness.detectChanges();
1027
+
1028
+ return harness.fixture.debugElement.query(By.directive(TodoItem)).componentInstance as TodoItem;
1029
+ }
1030
+
1031
+ describe("TodoItem", () => {
1032
+ beforeEach(() => {
1033
+ TestBed.configureTestingModule({
1034
+ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter(routes)],
1035
+ });
1036
+ });
1037
+
1038
+ it("completes the todo", async () => {
1039
+ const item = await renderedItem();
1040
+ const http = TestBed.inject(HttpTestingController);
1041
+ const completing = item.complete();
1042
+ const call = http.expectOne({ method: "POST", url: "/_rpc/todos/complete" });
1043
+
1044
+ expect(call.request.body).toEqual({ input: { id: "1" } });
1045
+ call.flush({ id: "1", title: "Buy milk", completed: true });
1046
+ await completing;
1047
+
1048
+ expect(item.status()).toBe("Completed");
1049
+ http.verify();
1050
+ });
1051
+
1052
+ it("handles the procedure's declared NOT_FOUND error", async () => {
1053
+ const item = await renderedItem();
1054
+ const http = TestBed.inject(HttpTestingController);
1055
+ const completing = item.complete();
1056
+
1057
+ // Status and message must match the declaration, or the client doesn't recognize the error.
1058
+ http
1059
+ .expectOne("/_rpc/todos/complete")
1060
+ .flush(
1061
+ { error: { code: "NOT_FOUND", message: "Todo does not exist", data: { id: "1" } } },
1062
+ { status: 404, statusText: "Not Found" },
1063
+ );
1064
+ await completing;
1065
+
1066
+ expect(item.status()).toBe("This todo no longer exists.");
1067
+ });
1068
+ });
1069
+ ```
1070
+
1071
+ Answer a call with what the server would send:
1072
+
1073
+ | Outcome | Body | Status |
1074
+ | --------------- | -------------------------------------------------------------------------------------- | ---------------- |
1075
+ | Result | the result | 200, the default |
1076
+ | Declared error | `{ error: { code, message, data } }`, with the declared `message` | the declared one |
1077
+ | `INVALID_INPUT` | `{ error: { code: "INVALID_INPUT", message: "Invalid RPC input", data: { issues } } }` | 400 |
1078
+ | `FORBIDDEN` | `{ error: { code: "FORBIDDEN", message: "RPC forbidden", data: null } }` | 403 |
1079
+ | `RPC_NOT_FOUND` | `{ error: { code: "RPC_NOT_FOUND", message: "RPC not found", data: null } }` | 404 |
1080
+ | `INTERNAL` | `{ error: { code: "INTERNAL", message: "Internal server error", data: null } }` | 500 |
1081
+ | `redirect()` | `{ redirect: { to } }`, plus `words` with [translated URLs](#translated-urls) | 303 |
1082
+ | `notFound()` | `{ notFound: null }` | 404 |
1083
+
1084
+ Pass the status as `flush(body, { status, statusText })`. The client recognizes an error only when its code, status and message all match, the procedure's declaration for a declared error and the table for Launch's own codes, and its data has the shape shown. A failing status whose body is neither a recognized error nor an outcome rejects with Angular's `HttpErrorResponse`, so a mistyped message makes `isError` false without any other sign. A body flushed with a success status is a result, whatever it contains.
1085
+
1086
+ A resolver calls its procedure while Angular navigates. Navigate through the generated routes with `RouterTestingHarness`, as the [router's guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#testing-pages) shows, and answer the call while the navigation waits for it:
1087
+
1088
+ `snippets/src/routes/todos/route.spec.ts`
1089
+
1090
+ ```ts
1091
+ import { provideHttpClient } from "@angular/common/http";
1092
+ import { HttpTestingController, provideHttpClientTesting } from "@angular/common/http/testing";
1093
+ import { TestBed } from "@angular/core/testing";
1094
+ import { provideRouter } from "@angular/router";
1095
+ import { RouterTestingHarness } from "@angular/router/testing";
1096
+ import { describe, expect, it, vi } from "vitest";
1097
+ import { routes } from "../../../generated/routes.generated.js";
1098
+ import TodosPage from "./page.js";
1099
+
1100
+ describe("todos route", () => {
1101
+ it("resolves the list before showing the page", async () => {
1102
+ TestBed.configureTestingModule({
1103
+ providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter(routes)],
1104
+ });
1105
+
1106
+ const http = TestBed.inject(HttpTestingController);
1107
+ const harness = await RouterTestingHarness.create();
1108
+ const navigation = harness.navigateByUrl("/todos", TodosPage);
1109
+
1110
+ // The resolver calls the procedure once the navigation reaches it.
1111
+ await vi.waitFor(() => {
1112
+ const call = http.expectOne({ method: "POST", url: "/_rpc/todos/list" });
1113
+
1114
+ expect(call.request.body).toEqual({ input: null });
1115
+ call.flush([{ id: "1", title: "Buy milk", completed: false }]);
1116
+ });
1117
+
1118
+ const page = await navigation;
1119
+
1120
+ expect(page.route.data().todos).toEqual([{ id: "1", title: "Buy milk", completed: false }]);
1121
+ expect(harness.routeNativeElement?.querySelector("li")?.textContent).toContain("Buy milk");
1122
+ });
1123
+ });
1124
+ ```
1125
+
1126
+ [Streams](#calling-streams) and [channels](#calling-channels) use the browser's `fetch` and `WebSocket`, not `HttpClient`, so `HttpTestingController` doesn't see them. A component that uses `route.queries` also needs the TanStack providers; see the [TanStack Query guide](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md#setup).
1127
+
1128
+ ### Testing handlers, stages and middleware
1129
+
1130
+ To test a procedure, call it with `callProcedure` from `@loozo/angular-launch/testing`. Pass the authored route, the default export of its `route.ts`, one of the route's own namespaces, the procedure's name and the context your root route's stage returns. The root stage doesn't run, so what it provides, such as the user or a database client, can be a fake. The rest of the [call order](#middleware) runs as on the server: the stages below the root, the route's middleware, input validation, the procedure's middleware and the handler.
1131
+
1132
+ `snippets/src/routes/todos/procedures.spec.ts`
1133
+
1134
+ ```ts
1135
+ import { callProcedure } from "@loozo/angular-launch/testing";
1136
+ import { describe, expect, it } from "vitest";
1137
+ import type { Todo } from "../../todos.server.js";
1138
+ import todos from "./route.js";
1139
+
1140
+ // What the root route's stage returns, with a store holding one todo in place of the real one.
1141
+ function rootContext(user: { id: string } | null) {
1142
+ const milk: Todo = { id: "1", title: "Buy milk", completed: false };
1143
+
1144
+ return {
1145
+ user,
1146
+ todos: {
1147
+ async listForUser() {
1148
+ return [milk];
1149
+ },
1150
+ async completeForUser(_user: string, id: string) {
1151
+ if (id !== milk.id) {
1152
+ return null;
1153
+ }
1154
+
1155
+ return { ...milk, completed: true };
1156
+ },
1157
+ },
1158
+ };
1159
+ }
1160
+
1161
+ describe("todos.complete", () => {
1162
+ it("completes the user's todo", async () => {
1163
+ const call = await callProcedure(todos, "todos", "complete", {
1164
+ context: rootContext({ id: "alice" }),
1165
+ input: { id: "1" },
1166
+ });
1167
+
1168
+ expect(call).toMatchObject({
1169
+ status: 200,
1170
+ result: { id: "1", title: "Buy milk", completed: true },
1171
+ });
1172
+ });
1173
+
1174
+ it("answers NOT_FOUND for a todo the user doesn't have", async () => {
1175
+ const call = await callProcedure(todos, "todos", "complete", {
1176
+ context: rootContext({ id: "alice" }),
1177
+ input: { id: "2" },
1178
+ });
1179
+
1180
+ expect(call).toMatchObject({
1181
+ status: 404,
1182
+ error: { code: "NOT_FOUND", message: "Todo does not exist", data: { id: "2" } },
1183
+ });
1184
+
1185
+ // The declared error's data is typed once its code narrows it.
1186
+ if ("error" in call && call.error.code === "NOT_FOUND") {
1187
+ const id: string = call.error.data.id;
1188
+
1189
+ expect(id).toBe("2");
1190
+ }
1191
+ });
1192
+
1193
+ it("refuses callers without a session through the signedIn stage", async () => {
1194
+ const call = await callProcedure(todos, "todos", "complete", {
1195
+ context: rootContext(null),
1196
+ input: { id: "1" },
1197
+ });
1198
+
1199
+ expect(call).toMatchObject({ status: 403, error: { code: "FORBIDDEN" } });
1200
+ });
1201
+
1202
+ it("rejects input the schema refuses", async () => {
1203
+ const call = await callProcedure(todos, "todos", "complete", {
1204
+ context: rootContext({ id: "alice" }),
1205
+ // The input is typed, so input the schema refuses needs a cast.
1206
+ input: { id: 1 } as never,
1207
+ });
1208
+
1209
+ expect(call).toMatchObject({
1210
+ status: 400,
1211
+ error: {
1212
+ code: "INVALID_INPUT",
1213
+ data: { issues: [{ path: ["id"], message: "Expected a todo id" }] },
1214
+ },
1215
+ });
1216
+ });
1217
+ });
1218
+
1219
+ describe("todos.list", () => {
1220
+ it("lists the user's todos", async () => {
1221
+ const call = await callProcedure(todos, "todos", "list", {
1222
+ context: rootContext({ id: "alice" }),
1223
+ });
1224
+
1225
+ expect(call).toMatchObject({ status: 200, result: [{ id: "1" }], cookies: [] });
1226
+ });
1227
+ });
1228
+ ```
1229
+
1230
+ - The call settles to what the browser would get, the bodies in the table above with their status: `{ status: 200, result }`, `{ status, error: { code, message, data } }`, `{ status: 303, redirect: { to } }` (never with `words`, even in a [translated](#translated-urls) app: `to` is whatever `createUrl` gives in the graph the test imports) or `{ status: 404, notFound: null }`. It also has `cookies`, the `Set-Cookie` values the call set, and `headers`, the headers it set. Narrow with `"error" in call`, then by `call.error.code`, to reach a declared error's typed data. An unexpected failure is `INTERNAL`, and Launch logs it with `console.error` as the server does.
1231
+ - `context`, `input` and the result are typed from the route: `context` as the root route's stage returns it (`{}` without one), so input the schema refuses needs a cast.
1232
+ - Stages, middleware and the handler receive a `POST` to `http://localhost/_rpc/<namespace>/<procedure>` as their `request`. Pass `request` to give them your own, with headers or an abort signal.
1233
+ - A namespace belongs to the route whose `.remote()` declares it: call an ancestor's namespace through the ancestor's route. Streams and channels can't be called this way.
1234
+ - The root route is the topmost route that uses `.context()`, `.use()` or `.remote()`, normally `src/routes/route.ts`.
1235
+ - Specs import `route.ts`, which application code mustn't. That's fine because the application tsconfig excludes them, as above.
1236
+
1237
+ `callProcedure` skips what only an HTTP request goes through: the host, origin and method checks, and the root stage. To test those too, call the generated `handleRequest` with a web `Request`, as your server does, and assert on the status and body the browser would get:
1238
+
1239
+ `snippets/src/routes/todos/http.spec.ts`
1240
+
1241
+ ```ts
1242
+ // @vitest-environment node
1243
+ // Server code: Node's Request keeps the Origin header, which happy-dom's Request drops.
1244
+ import { describe, expect, it } from "vitest";
1245
+ import { handleRequest } from "../../../generated/server.generated.js";
1246
+
1247
+ describe("POST /_rpc/todos/complete", () => {
1248
+ it("completes the todo of the user the session cookie names", async () => {
1249
+ const request = new Request("http://localhost/_rpc/todos/complete", {
1250
+ method: "POST",
1251
+ headers: {
1252
+ "content-type": "application/json",
1253
+ origin: "http://localhost",
1254
+ cookie: "session=alice-session",
1255
+ },
1256
+ body: JSON.stringify({ input: { id: "1" } }),
1257
+ });
1258
+
1259
+ const response = await handleRequest(request, { allowedHosts: ["localhost"] });
1260
+
1261
+ expect(response?.status).toBe(200);
1262
+ expect(await response?.json()).toEqual({ id: "1", title: "Buy milk", completed: true });
1263
+ });
1264
+ });
1265
+ ```
1266
+
1267
+ - Run the file in Node with `// @vitest-environment node`: it's server code. Angular's unit-test builder otherwise runs specs in a DOM emulation, happy-dom when it's installed and jsdom if not. happy-dom's `Request` drops the `Origin` header, so Launch's [cross-origin check](#cross-origin-requests) would refuse every call with `FORBIDDEN`.
1268
+ - Send `Origin` with the request URL's origin, and pass a matching `allowedHosts`.
1269
+ - The call uses your real stages and what they import. Angular's unit-test builder rejects `vi.mock()` for relative imports, so you can't replace a module a stage imports, such as your database client.
1270
+
1271
+ A standalone stage is a function of `StageArgs`, so you can test it on its own with a context you build; a middleware's `run` likewise takes the call's arguments and a `next` you watch:
1272
+
1273
+ `snippets/src/auth.server.spec.ts`
1274
+
1275
+ ```ts
1276
+ import { describe, expect, it, vi } from "vitest";
1277
+ import { signedIn } from "./auth.server.js";
1278
+ import { todos } from "./todos.server.js";
1279
+
1280
+ function args(user: { id: string } | null) {
1281
+ const request = new Request("http://localhost/_rpc/todos/list", { method: "POST" });
1282
+
1283
+ return {
1284
+ context: { todos, user },
1285
+ request,
1286
+ signal: request.signal,
1287
+ response: { headers: new Headers(), setCookie: vi.fn(), deleteCookie: vi.fn() },
1288
+ };
1289
+ }
1290
+
1291
+ describe("signedIn", () => {
1292
+ it("narrows the context to the signed-in user", () => {
1293
+ expect(signedIn(args({ id: "alice" }))).toEqual({ todos, user: { id: "alice" } });
1294
+ });
1295
+
1296
+ it("refuses a caller without a user", () => {
1297
+ expect(() => signedIn(args(null))).toThrow();
1298
+ });
1299
+ });
1300
+ ```
1301
+
1302
+ `forbidden()`, `notFound()` and `redirect()` throw plain `Error`s, not types a test can check, so a test that calls a stage directly checks that it threw. To check which outcome it answered with, call a procedure behind it with `callProcedure`, as `procedures.spec.ts` above does for `FORBIDDEN`.
1303
+
479
1304
  ## Deploying
480
1305
 
481
1306
  With `outputMode: "server"`, `ng build` writes the browser files and a bundled server:
@@ -503,7 +1328,45 @@ Launch calls `/_rpc/<namespace>/<procedure>` from the root of the domain, even w
503
1328
 
504
1329
  Browser tabs opened before a deploy keep calling the procedures they were built with. After you rename a namespace or procedure, or change an input schema, those calls fail with `RPC_NOT_FOUND` or `INVALID_INPUT` until the page reloads. The same applies while old and new servers run side by side during a rolling deploy.
505
1330
 
506
- Launch has been verified on Node, and with a platform-neutral server build (below) on Deno and Cloudflare's workerd, run locally.
1331
+ Launch has been verified on Node, and with a platform-neutral server build (below) on Deno and Cloudflare's workerd, run locally. Streams have been verified on Node, under `ng serve` and on Deno. Channels have been verified on the built Node server and under `ng serve` in Chromium, Firefox and WebKit.
1332
+
1333
+ ### Streams behind proxies
1334
+
1335
+ Stream responses carry `Cache-Control: private, no-store, no-transform` and `X-Accel-Buffering: no`, which tell compression middleware that honors `no-transform` and buffering proxies such as nginx to pass them through as they're written. Go's reverse proxy, which Tailscale Serve uses, passes `text/event-stream` responses through as they're written anyway. Each open stream holds a connection: over HTTP/1.1, browsers open at most 6 per origin, so several open streams can hold up other requests. Over HTTP/2, usually with HTTPS, they share one connection.
1336
+
1337
+ ### Channels on Node
1338
+
1339
+ Channels arrive as websocket upgrades, which Node hands to the HTTP server's `upgrade` listeners instead of its request handler. `createUpgradeHandler` from `@loozo/angular-launch/node` turns the generated `handleUpgrade` into such a listener. Create it once, at your server module's top level, and attach it to the server that serves the app: with Express, the server `app.listen()` returns, as in the [server entry](#4-wire-the-browser-and-server-apps); with plain Node:
1340
+
1341
+ ```ts
1342
+ // src/server.ts
1343
+ import { createServer } from "node:http";
1344
+ import { createUpgradeHandler } from "@loozo/angular-launch/node";
1345
+ import { handleUpgrade } from "../generated/server.generated";
1346
+
1347
+ const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
1348
+
1349
+ if (isMainModule(import.meta.url)) {
1350
+ const server = createServer(reqHandler).listen(port);
1351
+
1352
+ server.on("upgrade", upgrade);
1353
+ }
1354
+ ```
1355
+
1356
+ Pass `handleUpgrade` the same `allowedHosts` and `origins` as `handleRequest`: it checks [hosts](#hosts) and [origins](#cross-origin-requests) the same way, before a context exists. The listener builds a web `Request` from the upgrade (the protocol from the socket, the host from `Host`; like Angular's default, it trusts no proxy headers), writes refusals to the socket as plain HTTP responses, and accepts the rest with [`ws`](https://github.com/websockets/ws), with the call's headers and cookies on the `101`. Upgrades outside `/_rpc/` are left to the server's other `upgrade` listeners. It pings each open socket every 15 seconds and drops one that doesn't answer, and closes a socket whose message is over `maxPayload` bytes with 1009, which the client sees as a `TypeError`:
1357
+
1358
+ ```ts
1359
+ createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }), {
1360
+ maxPayload: 64 * 1024, // defaults to 1 MiB
1361
+ });
1362
+ ```
1363
+
1364
+ Under `ng serve`, `listen` doesn't run, so your code never attaches the listener. Launch's serve builder forwards channel upgrades to it instead: on the dev server's first request it adds one `upgrade` listener to the dev server, which passes `/_rpc/` upgrades to the latest listener `createUpgradeHandler` created and leaves every other upgrade, such as Vite's live-reload socket, to the dev server. The dev server loads your server module with the first request that reaches your server, such as a page, and again with the first such request after you edit server code; each load creates a new listener, which takes over. Rebuilding alone doesn't load it. With live reload, the default, the reload that follows a server edit is that request, so the reloaded page's channels reach the new code. With `--live-reload=false`, or for an upgrade sent before any page request since the rebuild, the previously loaded module keeps answering until a page request loads the new one. Channels already open stay on the code they started with. A channel upgrade that arrives while no listener exists, because the module hasn't loaded yet or creates none, is answered with a plain-text 503, and the dev server logs one warning naming `createUpgradeHandler`; the client sees a `TypeError`. An upgrade that arrives before the dev server has answered any request isn't forwarded, which doesn't happen in a browser, since the page loads first.
1365
+
1366
+ - **Memory:** an open channel holds at most about 1 MiB of unsent values plus 32 unread messages of up to `maxPayload` each. How many channels may be open at once is up to your host or proxy.
1367
+ - **Leaving early:** a client that leaves while the context or middleware still run ends the call before its handler starts when its browser closes the connection (Chromium and WebKit do); Firefox's leaving isn't noticed until the upgrade is accepted, when the socket closes at once.
1368
+ - **HTTP/2:** Node's `http2` server doesn't accept websockets over HTTP/2 (RFC 8441) by default. Browsers then open the channel over HTTP/1.1, so serve that too.
1369
+ - **Other frameworks:** the listener needs the Node `upgrade` event. Express and plain Node give it as shown; Hono's `@hono/node-server` needs its own upgrade wiring, which isn't covered here.
507
1370
 
508
1371
  ### Hosts
509
1372
 
@@ -535,7 +1398,7 @@ List a sibling site's origin the same way to let it call. Only HTTP requests are
535
1398
  ```ts
536
1399
  // src/server.ts
537
1400
  import { AngularAppEngine, createRequestHandler } from "@angular/ssr";
538
- import { createContext, handleRequest } from "../generated/server.generated";
1401
+ import { createRequestScope, handleRequest } from "../generated/server.generated";
539
1402
 
540
1403
  const allowedHosts = ["app.example.com"];
541
1404
  const angular = new AngularAppEngine({ allowedHosts });
@@ -547,7 +1410,7 @@ export const reqHandler = createRequestHandler(async (request: Request) => {
547
1410
  return rpc;
548
1411
  }
549
1412
 
550
- const scope = await createContext(request);
1413
+ const scope = createRequestScope(request);
551
1414
  const page = await angular.handle(scope.request, scope);
552
1415
 
553
1416
  return page ?? new Response("Not found", { status: 404 });
@@ -556,7 +1419,8 @@ export const reqHandler = createRequestHandler(async (request: Request) => {
556
1419
 
557
1420
  - Import from `@angular/ssr`, not `@angular/ssr/node`. `AngularAppEngine` doesn't read `NG_ALLOWED_HOSTS` or `NG_TRUST_PROXY_HEADERS`: pass `allowedHosts`, and `trustProxyHeaders` if you're behind a proxy (it's off by default), to its constructor, and the same hosts to `handleRequest`. List them in the entry as above, or read them from your platform's configuration.
558
1421
  - The bundle neither serves the `browser` files nor starts a server. Point your platform's static hosting at `dist/<app>/browser` and its request handler at the exported `reqHandler`.
559
- - Nothing polyfills Node modules for you, so your context, handlers and their dependencies must run on the platform. In-memory state lasts only as long as the platform keeps an instance alive.
1422
+ - Nothing polyfills Node modules for you, so your stages, handlers and their dependencies must run on the platform. In-memory state lasts only as long as the platform keeps an instance alive.
1423
+ - `handleUpgrade` takes a web `Request` and runs a channel on any standard `WebSocket` the platform accepts, sending `headers` on its `101` response, but it hasn't been verified on Deno or workerd, and neither has workerd's `bufferedAmount`, which the server's flow control reads.
560
1424
 
561
1425
  ### Aborted requests
562
1426
 
@@ -567,7 +1431,7 @@ const closed = new AbortController();
567
1431
 
568
1432
  response.once("close", () => {
569
1433
  if (!response.writableFinished) {
570
- closed.abort();
1434
+ queueMicrotask(() => closed.abort());
571
1435
  }
572
1436
  });
573
1437
 
@@ -575,11 +1439,21 @@ const native = createWebRequestFromNodeRequest(request);
575
1439
  const web = new Request(native, { signal: AbortSignal.any([native.signal, closed.signal]) });
576
1440
  ```
577
1441
 
578
- Pass `web` to both `handleRequest` and `createContext`, so page renders get the same signal. Without this wiring everything works, but handlers never see an abort over HTTP.
1442
+ Pass `web` to both `handleRequest` and `createRequestScope`, so page renders get the same signal. Without this wiring everything works, but query and mutation handlers never see an abort over HTTP, and a [stream](#streams) whose client left before it started runs until it ends by itself. A stream that's already being sent stops either way, since Angular's helper cancels its body when the response closes.
1443
+
1444
+ The abort waits a microtask because this listener runs before the one Angular's `writeResponseToNodeResponse` adds for the same `close` event later. Aborting right away fails a stream's body before Angular's helper cancels it, and the helper then logs that failure as `DOMException [AbortError]` whenever a client leaves a stream.
1445
+
1446
+ Angular rejects a page render whose request aborted with an `AbortError`. When the response is gone by then, nobody is left to answer, so the server entry returns instead of passing the error to `next`, which would log it. Every other error still reaches `next`:
1447
+
1448
+ ```ts
1449
+ if (response.destroyed && error instanceof DOMException && error.name === "AbortError") {
1450
+ return;
1451
+ }
1452
+ ```
579
1453
 
580
1454
  ### Other server frameworks
581
1455
 
582
- `handleRequest` and `createContext` take a web `Request`, so any framework that gives you one works. `AngularNodeAppEngine` also accepts a web `Request`. With [Hono](https://hono.dev) on Node:
1456
+ `handleRequest` and `createRequestScope` take a web `Request`, so any framework that gives you one works. `AngularNodeAppEngine` also accepts a web `Request`. With [Hono](https://hono.dev) on Node:
583
1457
 
584
1458
  ```ts
585
1459
  // src/server.ts
@@ -589,7 +1463,7 @@ import { AngularNodeAppEngine, isMainModule } from "@angular/ssr/node";
589
1463
  import { serve } from "@hono/node-server";
590
1464
  import { serveStatic } from "@hono/node-server/serve-static";
591
1465
  import { Hono } from "hono";
592
- import { createContext, handleRequest } from "../generated/server.generated";
1466
+ import { createRequestScope, handleRequest } from "../generated/server.generated";
593
1467
 
594
1468
  const browser = fileURLToPath(new URL("../browser", import.meta.url));
595
1469
  // An explicit list stops Angular reading NG_ALLOWED_HOSTS, so read it here.
@@ -606,7 +1480,7 @@ app.all("*", async (c) => {
606
1480
  return rpc;
607
1481
  }
608
1482
 
609
- const scope = await createContext(c.req.raw);
1483
+ const scope = createRequestScope(c.req.raw);
610
1484
  const page = await angular.handle(scope.request, scope);
611
1485
 
612
1486
  return page ?? c.notFound();
@@ -623,7 +1497,7 @@ if (isMainModule(import.meta.url)) {
623
1497
  export const reqHandler = createRequestHandler(app.fetch);
624
1498
  ```
625
1499
 
626
- Export the handler as `reqHandler`; Angular's dev server and build don't look for a default export. Whether `@hono/node-server` aborts `c.req.raw.signal` when a client disconnects is unverified, so don't rely on handlers seeing an abort there. Under `ng serve`, `serveStatic` logs that the `browser` directory doesn't exist. That's expected: the dev server serves those files itself.
1500
+ Export the handler as `reqHandler`; Angular's dev server and build don't look for a default export. [Channels](#channels-on-node) need their own upgrade wiring with Hono, which isn't covered here. Whether `@hono/node-server` aborts `c.req.raw.signal` when a client disconnects is unverified, so don't rely on handlers seeing an abort there. Under `ng serve`, `serveStatic` logs that the `browser` directory doesn't exist. That's expected: the dev server serves those files itself.
627
1501
 
628
1502
  ## Generation
629
1503
 
@@ -633,33 +1507,35 @@ The [builders](#builders) run generation for you. Underneath, it's a Node functi
633
1507
  generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
634
1508
  ```
635
1509
 
636
- | Option | Type | Description |
637
- | ----------------- | ---------- | ------------------------------------------------------------------------------- |
638
- | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
639
- | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
640
- | `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
641
- | `tanstackQuery` | `boolean` | Also generate `injectQueries()`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md) |
642
- | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
1510
+ | Option | Type | Description |
1511
+ | ------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- |
1512
+ | `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
1513
+ | `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
1514
+ | `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
1515
+ | `tanstackQuery` | `boolean` | Also add `route.queries`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md) |
1516
+ | `translateSegments` | `boolean` | Translate static segments per Angular localize build; see [Translated URLs](#translated-urls) |
1517
+ | `localization` | `Localization` | The build's `i18n` and polyfills, required with `translateSegments`; the builders read it from the project |
1518
+ | `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
643
1519
 
644
1520
  `workspace` is the absolute path of the application directory (the one with its `package.json`). The tsconfig, scan directory and output directory must all be inside it. `stopped` lets a caller cancel: if it returns `true` before writing starts, nothing is written.
645
1521
 
646
- Generation reads your source without running it. It writes the router's files plus:
1522
+ Generation reads your source without running it. It writes the router's files, with Launch's additions, plus its own:
647
1523
 
648
- | File | Contents |
649
- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
650
- | `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups, plus `injectQueries()` with `tanstackQuery`; none for redirect routes |
651
- | `<outDirectory>/context.generated.d.ts` | Registers your context type |
652
- | `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
1524
+ | File | Contents |
1525
+ | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1526
+ | `route.generated.ts` beside each route | The router's browser copy without the server steps, carrying the route's procedure metadata, `Remote`, `Context` and `remote` on `injectRoute()`; `Queries` and `queries` with `tanstackQuery` |
1527
+ | `<outDirectory>/server.generated.ts` | `createRequestScope`, `handleRequest`, `handleUpgrade` and `provideServer`, bound to every route with a server step |
1528
+ | `<outDirectory>/redirects.generated.ts` | With `translateSegments` only: `provideRedirectTranslation`, every static route word with the router's message for it |
653
1529
 
654
- Each file starts with an ownership marker comment. Generation only replaces or removes files with those exact names and markers, fails rather than overwrite an unmarked file or a symlink in their place, and removes stale ones. Unchanged files aren't rewritten. Everything is validated before anything is written, so a run that fails validation changes nothing. Files are then written one at a time, with no rollback: a write error partway through, such as an unwritable file, or an interrupted run can leave some files updated and others not. The next successful run repairs them.
1530
+ Each file carries an ownership marker comment. Generation only replaces or removes files with those exact names and markers, fails rather than overwrite an unmarked file or a symlink in their place, and removes stale ones, including the `rpc.generated.ts` and `context.generated.d.ts` files an earlier Launch version wrote. Unchanged files aren't rewritten. Everything is validated before anything is written, so a run that fails validation changes nothing. Files are then written one at a time, with no rollback: a write error partway through, such as an unwritable file, or an interrupted run can leave some files updated and others not. The next successful run repairs them.
655
1531
 
656
- Before writing, generation type-checks the generated files, your route and RPC declarations, and any file that directly imports a generated file, using `skipLibCheck: false`. Other files are left to your Angular build.
1532
+ Before writing, generation type-checks the generated files, your route declarations, and any file that directly imports a generated file, using `skipLibCheck: false`. Other files are left to your Angular build.
657
1533
 
658
- Generated browser code contains only names, kinds and error metadata, never your schemas, handlers or context. Keep server-only modules out of anything a page imports at runtime; the example names them `*.server.ts`.
1534
+ Generated browser code contains only names, kinds and error metadata, never your schemas, stages, middleware or handlers: a route copy drops the server steps and the imports only they used, and names their types through an erased `import type` of its own `route.ts`. Keep server-only modules out of anything a page imports at runtime; the example names them `*.server.ts`. Each route copy loads with the record that reads it: a top-level route's with `routes.generated.ts`, in the startup bundle, and a nested route's with its parent's lazily loaded children, as the router's [lazy route children](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md#lazy-route-children) describes.
659
1535
 
660
- `server.generated.ts` binds Launch's internal `createRequestScope`, `handleRpc` and `provideLaunchServer` to your app. It imports them from `@loozo/angular-launch/_server`, an entry point for generated code only that isn't public API and can change in any release; use the generated functions instead. The app identity comes from the `package.json` name, the generation tsconfig's path within the app, and the context file's path and contents, so moving the whole app directory doesn't change it.
1536
+ `server.generated.ts` binds Launch's internal `bindApplication`, `createRequestScope`, `handleRpc`, `handleChannelUpgrade` and `provideLaunchServer` to your app. It imports them from `@loozo/angular-launch/_server`, an entry point for generated code only that isn't public API and can change in any release; use the generated functions instead. The app identity comes from the `package.json` name and the generation tsconfig's and output directory's paths within the app, so neither route edits nor moving the whole app directory change it.
661
1537
 
662
- RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you rename a namespace or procedure. Moving an `rpc.ts` or the generation tsconfig doesn't change them. The example doesn't commit generated files: every build regenerates them, and its `check` configuration (`ng run todos:build:check`) verifies them without writing.
1538
+ RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you rename a namespace or procedure. Moving a route or the generation tsconfig doesn't change them. The example doesn't commit generated files: every build regenerates them, and its `check` configuration (`ng run todos:build:check`) verifies them without writing.
663
1539
 
664
1540
  `@loozo/angular-launch/generation` is Node-only.
665
1541
 
@@ -667,7 +1543,7 @@ RPC URLs are `/_rpc/<namespace>/<procedure>`, so they change only when you renam
667
1543
 
668
1544
  #### `@loozo/angular-launch:application`
669
1545
 
670
- All `@angular/build:application` options, plus the generation options above (`tsconfig`, `scanDirectories`, `outDirectory`, `tanstackQuery` and `check`, which default to `false`). It takes those out and passes every other option through unchanged.
1546
+ All `@angular/build:application` options, plus the generation options above (`tsconfig`, `scanDirectories`, `outDirectory`, and `tanstackQuery`, `translateSegments` and `check`, which default to `false`). It takes those out and passes every other option through unchanged. With `translateSegments`, it reads `localization` from the project's `i18n` and the build's `polyfills`, so it must run as a project target.
671
1547
 
672
1548
  The builder runs generation once, then the official application build. Invalid options stop the build before generation starts. Generation errors, including drift with `check: true`, are logged and fail the build before the Angular build runs. `watch: true` is rejected; use the serve builder for watching.
673
1549
 
@@ -682,7 +1558,7 @@ All `@angular/build:dev-server` options, set in `angular.json` or on the command
682
1558
 
683
1559
  Invalid options stop the serve builder before it generates anything, and so does an invalid build target. The build target must not resolve `check: true`, because serving always writes generated files. The initial generation must succeed before the dev server starts; if it fails, the error is logged and the builder reports a failed build.
684
1560
 
685
- The builder then watches the scan directory and the context file, wherever the last generation found it, and regenerates when files are added, changed or removed there. A pass starts once changes have been quiet for 150 ms, so saving several files at once or renaming a directory runs one pass. Passes run one at a time; changes during a pass cause one more. A failed pass is logged and the server keeps running; the next change retries. When it starts watching a context file outside the scan directory, it runs one more pass once that watch is live, so an edit made while the file was being found isn't lost. A plain rename of the context file is followed, but a move that passes through a missing or broken context, such as delete-then-create or a file that's broken at its new path, is picked up only on the next change in the scan directory or a restart. Other files, such as a module your context imports, don't trigger generation; Angular's build still checks them.
1561
+ The builder then watches the scan directory, and with `translateSegments` the catalogs too, and regenerates when files are added, changed or removed there. A pass starts once changes have been quiet for 150 ms, so saving several files at once or renaming a directory runs one pass. Passes run one at a time; changes during a pass cause one more. A failed pass is logged and the server keeps running; the next change retries. Other files, such as a server module a stage imports, don't trigger generation: route copies name their types through their route's declaration, not as text, so there's nothing to regenerate, and Angular's build still checks them. A route edit rebuilds twice, once for the edit and once for its regenerated copy, so the first reload can briefly pair new server code with the old copy.
686
1562
 
687
1563
  Polling is on by default because Angular 22.2.2's native file watcher misses edits to files inside a renamed directory, which leaves the dev server serving stale output. It costs some idle CPU. Set `"poll": false` in the serve target to go back to native file events; Angular's own configuration then applies, including a `poll` on the build target. A positive number overrides the build target's `poll`; `0` is rejected. On the command line, `--poll` accepts milliseconds only. `poll` configures Angular's dev-server watcher; Launch's own watcher uses native file events.
688
1564
 
@@ -713,19 +1589,24 @@ The options are fixed when the session is created. Edits inside the app, includi
713
1589
 
714
1590
  ## Limitations
715
1591
 
716
- - No subscriptions, optimistic updates or automatic invalidation. Beyond hydration, the only query cache is TanStack Query's, through the optional [integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md#limitations), which has its own limitations.
1592
+ - Streams and channels don't reconnect or resume on their own (`connect()` reconnects when asked or when its input changes), and HTTP interceptors don't see them. Channels carry strict JSON text only, one call per socket, with no acknowledgements.
1593
+ - Beyond hydration, the only query cache is TanStack Query's, through the optional [integration](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md#limitations), which has its own limitations. Optimistic updates and invalidation are TanStack's too, as its guide [shows](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md#optimistic-updates); Launch adds no helpers for them. Without it, nothing is invalidated for you.
717
1594
  - No storage adapters; persistence is your handler's job.
718
1595
  - No production authentication, CORS or caching policy. You provide those. Cross-origin RPCs are refused (see [Cross-origin requests](#cross-origin-requests)); there's no CSRF token scheme.
1596
+ - No success status other than 200: a result is always 200, and other statuses come from failures and outcomes. During server rendering, a cookie set by one call isn't visible to later calls in the same render, a failed initial navigation loses the render's cookies, and headers are dropped.
719
1597
  - Aborting is advisory: handlers get a `signal`, but work that ignores it finishes, a write may already have committed, and nothing is rolled back.
720
1598
  - Middleware is server-side only: there's no client middleware (use an Angular HTTP interceptor), and no dedupe of middleware listed twice.
721
- - One RPC group per route, and one context per application.
1599
+ - Redirects go to declared destinations only: an external destination, such as an OAuth provider, is data your page acts on, and a redirect target's search keys must be declared on its route. Outcomes act only in navigation, through `rpcNavigationErrors`, and nothing maps `FORBIDDEN` to a page: a stage that guards a page's reads throws `redirect()` or `notFound()` instead.
1600
+ - A route can't opt out of its ancestors' stages, and a stage's failure fails every later call in the same request scope, such as the rest of a server render.
1601
+ - An active-route handle's `remote` and `queries` use the `injectActiveRoute()` caller's injector, so providers a route adds reach only its own `injectRoute()`.
1602
+ - Middleware written inline in `.use()` doesn't infer the route's context type; give it the keys it reads.
722
1603
 
723
1604
  ## Further reading
724
1605
 
725
- - [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
726
- - [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/specs/angular-launch.md): design and full contract
727
- - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.5/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
728
- - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.5/packages/angular-router/README.md): routes, codecs and navigation
1606
+ - [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
1607
+ - [`SPEC.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-launch/SPEC.md): the full contract, including every edge case
1608
+ - [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.1.0/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
1609
+ - [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.1.0/packages/angular-router/README.md): routes, codecs and navigation
729
1610
 
730
1611
  ## Developing this package
731
1612