@loozo/angular-launch 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +546 -2
- package/client.d.ts +232 -0
- package/client.js +169 -0
- package/generated.d.ts +13 -0
- package/generated.js +90 -0
- package/generation/index.d.ts +116 -0
- package/generation/index.js +634 -0
- package/index.d.ts +2 -0
- package/index.js +1 -0
- package/json.d.ts +13 -0
- package/json.js +48 -0
- package/package.json +48 -4
- package/server/backend.d.ts +58 -0
- package/server/backend.js +166 -0
- package/server/definitions.d.ts +486 -0
- package/server/definitions.js +170 -0
- package/server/dispatch.d.ts +140 -0
- package/server/dispatch.js +249 -0
- package/server/errors.d.ts +21 -0
- package/server/errors.js +32 -0
- package/server/generated.d.ts +2 -0
- package/server/generated.js +3 -0
- package/server/index.d.ts +6 -0
- package/server/index.js +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Theophilos Matzavinos
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,547 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loozo/angular-launch
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed server functions for Angular applications built with [`@loozo/angular-router`](../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.
|
|
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.
|
|
6
|
+
|
|
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
|
+
|
|
9
|
+
**Status:** experimental. Version `0.0.2`, MIT license. It currently covers queries, mutations, guards and declared errors. There's no builder or watch mode yet, and no subscriptions, optimistic updates, automatic invalidation or storage adapters.
|
|
10
|
+
|
|
11
|
+
## Requirements
|
|
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
|
+
- `@loozo/angular-router` at exactly the version Launch was released with (`0.0.4` for Launch `0.0.2`), 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.
|
|
15
|
+
- 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.
|
|
16
|
+
- A `package.json` with a `name` in the application directory. The name is part of the generated app identity.
|
|
17
|
+
|
|
18
|
+
Install both packages:
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
pnpm add @loozo/angular-launch @loozo/angular-router@0.0.4
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## How it fits together
|
|
25
|
+
|
|
26
|
+
```text
|
|
27
|
+
src/
|
|
28
|
+
├── context.ts defineContext: per-request server context
|
|
29
|
+
└── routes/
|
|
30
|
+
├── route.ts defineRoute("")
|
|
31
|
+
└── +authenticated/
|
|
32
|
+
├── route.ts pathless route
|
|
33
|
+
├── rpc.ts defineRpc("session", …)
|
|
34
|
+
└── todos/
|
|
35
|
+
├── route.ts defineRoute("todos")
|
|
36
|
+
├── rpc.ts defineRpc("todos", …)
|
|
37
|
+
├── page.ts
|
|
38
|
+
├── route.generated.ts generated by the router
|
|
39
|
+
└── rpc.generated.ts generated: injectRpc() with session and todos
|
|
40
|
+
generated/
|
|
41
|
+
├── routes.generated.ts router: routes for provideRouter
|
|
42
|
+
├── destinations.generated.ts router
|
|
43
|
+
├── context.generated.d.ts registers your context type
|
|
44
|
+
└── server.generated.ts createContext, handleRequest, provideServer
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
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.
|
|
48
|
+
|
|
49
|
+
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.
|
|
50
|
+
|
|
51
|
+
## Setup
|
|
52
|
+
|
|
53
|
+
The [todos example](../../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.
|
|
54
|
+
|
|
55
|
+
### 1. Define the context
|
|
56
|
+
|
|
57
|
+
One file anywhere in your app's TypeScript sources default-exports `defineContext`. It runs once per live server request and its return value is what every handler and guard receives as `context`:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
// src/context.ts
|
|
61
|
+
import { defineContext } from "@loozo/angular-launch/server";
|
|
62
|
+
import { db } from "./database.server";
|
|
63
|
+
import { sessions } from "./sessions.server";
|
|
64
|
+
|
|
65
|
+
export default defineContext(async (request: Request) => ({
|
|
66
|
+
request,
|
|
67
|
+
db,
|
|
68
|
+
user: await sessions.authenticate(request),
|
|
69
|
+
}));
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
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.
|
|
73
|
+
|
|
74
|
+
### 2. Define RPCs next to a route
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// src/routes/+authenticated/todos/rpc.ts
|
|
78
|
+
import { defineRpc, mutation, query } from "@loozo/angular-launch/server";
|
|
79
|
+
import { isSignedIn, requireUser } from "../../../auth.server";
|
|
80
|
+
import { idSchema, titleSchema } from "../../../todo-input.server";
|
|
81
|
+
|
|
82
|
+
export default defineRpc(
|
|
83
|
+
"todos",
|
|
84
|
+
{
|
|
85
|
+
list: query({
|
|
86
|
+
handler: ({ context }) => context.db.todos.listForUser(requireUser(context).id),
|
|
87
|
+
}),
|
|
88
|
+
add: mutation({
|
|
89
|
+
input: titleSchema,
|
|
90
|
+
handler: ({ input, context }) =>
|
|
91
|
+
context.db.todos.addForUser(requireUser(context).id, input.title),
|
|
92
|
+
}),
|
|
93
|
+
},
|
|
94
|
+
{ canActivate: [isSignedIn] },
|
|
95
|
+
);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### 3. Generate
|
|
99
|
+
|
|
100
|
+
Generation is a Node function. The example calls it from a small script:
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
// generate.mjs
|
|
104
|
+
import { generate } from "@loozo/angular-launch/generation";
|
|
105
|
+
|
|
106
|
+
await generate(import.meta.dirname, {
|
|
107
|
+
tsconfig: "tsconfig.app.json",
|
|
108
|
+
scanDirectories: ["src/routes"],
|
|
109
|
+
outDirectory: "generated",
|
|
110
|
+
check: process.argv.includes("--check"),
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Run it before the Angular build. Launch apps use Angular's own `@angular/build:application` builder, not the router's companion builders, which don't accept Launch files:
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
"scripts": {
|
|
118
|
+
"generate": "node generate.mjs",
|
|
119
|
+
"build": "pnpm generate && ng build"
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Include the generated files, declarations included, in your app tsconfig: `"include": ["src/**/*.ts", "generated/**/*.ts"]`. See [Generation](#generation) for the options and what gets written.
|
|
124
|
+
|
|
125
|
+
### 4. Wire the browser and server apps
|
|
126
|
+
|
|
127
|
+
The browser config is ordinary Angular:
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
// src/config.ts
|
|
131
|
+
import { provideHttpClient } from "@angular/common/http";
|
|
132
|
+
import { provideClientHydration } from "@angular/platform-browser";
|
|
133
|
+
import { provideRouter } from "@angular/router";
|
|
134
|
+
import type { ApplicationConfig } from "@angular/core";
|
|
135
|
+
import { routes } from "../generated/routes.generated";
|
|
136
|
+
|
|
137
|
+
export const config: ApplicationConfig = {
|
|
138
|
+
providers: [provideHttpClient(), provideClientHydration(), provideRouter(routes)],
|
|
139
|
+
};
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
The server config adds the generated `provideServer()`, after `provideHttpClient()`:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
// src/config.server.ts
|
|
146
|
+
import { mergeApplicationConfig } from "@angular/core";
|
|
147
|
+
import { provideServerRendering, withRoutes } from "@angular/ssr";
|
|
148
|
+
import { provideServer } from "../generated/server.generated";
|
|
149
|
+
import { config } from "./config";
|
|
150
|
+
import { rendering } from "./rendering";
|
|
151
|
+
|
|
152
|
+
export const serverConfig = mergeApplicationConfig(config, {
|
|
153
|
+
providers: [provideServerRendering(withRoutes(rendering)), provideServer()],
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
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:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
// src/main.server.ts
|
|
161
|
+
import { bootstrapApplication, type BootstrapContext } from "@angular/platform-browser";
|
|
162
|
+
import { finishLaunchRendering } from "@loozo/angular-launch/server";
|
|
163
|
+
import { App } from "./app";
|
|
164
|
+
import { serverConfig } from "./config.server";
|
|
165
|
+
|
|
166
|
+
export default async function bootstrap(context: BootstrapContext) {
|
|
167
|
+
const app = await bootstrapApplication(App, serverConfig, context);
|
|
168
|
+
|
|
169
|
+
return finishLaunchRendering(app);
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
In the server entry, let `handleRequest` answer RPC requests (it returns `null` for anything else), and render pages with a request scope from `createContext`. This is the Express server that Angular's SSR setup generates, with Launch added:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
// src/server.ts
|
|
177
|
+
import { join } from "node:path";
|
|
178
|
+
import {
|
|
179
|
+
AngularNodeAppEngine,
|
|
180
|
+
createNodeRequestHandler,
|
|
181
|
+
createWebRequestFromNodeRequest,
|
|
182
|
+
isMainModule,
|
|
183
|
+
writeResponseToNodeResponse,
|
|
184
|
+
} from "@angular/ssr/node";
|
|
185
|
+
import express from "express";
|
|
186
|
+
import { createContext, handleRequest } from "../generated/server.generated";
|
|
187
|
+
|
|
188
|
+
const browser = join(import.meta.dirname, "../browser");
|
|
189
|
+
const angular = new AngularNodeAppEngine();
|
|
190
|
+
const app = express();
|
|
191
|
+
|
|
192
|
+
app.use(express.static(browser, { maxAge: "1y", index: false, redirect: false }));
|
|
193
|
+
|
|
194
|
+
app.use(async (request, response, next) => {
|
|
195
|
+
try {
|
|
196
|
+
const web = createWebRequestFromNodeRequest(request);
|
|
197
|
+
const rpc = await handleRequest(web);
|
|
198
|
+
|
|
199
|
+
if (rpc) {
|
|
200
|
+
await writeResponseToNodeResponse(rpc, response);
|
|
201
|
+
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const scope = await createContext(web);
|
|
206
|
+
const page = await angular.handle(scope.request, scope);
|
|
207
|
+
|
|
208
|
+
if (!page) {
|
|
209
|
+
next();
|
|
210
|
+
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
await writeResponseToNodeResponse(page, response);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
next(error);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
if (isMainModule(import.meta.url)) {
|
|
221
|
+
const port = process.env["PORT"] || 4000;
|
|
222
|
+
|
|
223
|
+
app.listen(port, (error) => {
|
|
224
|
+
if (error) {
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
console.log(`Listening on http://localhost:${port}`);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export const reqHandler = createNodeRequestHandler(app);
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
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).
|
|
236
|
+
|
|
237
|
+
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.
|
|
238
|
+
|
|
239
|
+
## Defining RPCs
|
|
240
|
+
|
|
241
|
+
`defineRpc(namespace, procedures, options?)` declares a group. Each procedure is a `query` (a read) or a `mutation` (a write):
|
|
242
|
+
|
|
243
|
+
```ts
|
|
244
|
+
query({ input?, canActivate?, errors?, handler });
|
|
245
|
+
mutation({ input?, canActivate?, errors?, handler });
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
The handler receives `{ context, input, errors }` and returns a value or a promise.
|
|
249
|
+
|
|
250
|
+
- **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine. One `defineRpc` per route; a namespace can't repeat within one route's ancestry, but unrelated branches may reuse it.
|
|
251
|
+
- **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 guards 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.
|
|
252
|
+
- **Guards** return `boolean` or `Promise<boolean>`; `false` fails the call with `FORBIDDEN`. Group guards (in `defineRpc` options) get `{ context, request }`; procedure guards also get the validated `input`. Guards are never inherited through the route tree. A call runs input validation, then the group's guards, then the procedure's guards, then the handler.
|
|
253
|
+
- Guards don't narrow types. Use an ordinary function to narrow, such as the example's `requireUser`:
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
// src/auth.server.ts
|
|
257
|
+
import type { Context, Guard } from "@loozo/angular-launch/server";
|
|
258
|
+
|
|
259
|
+
export const isSignedIn: Guard = ({ context }) => context.user !== null;
|
|
260
|
+
|
|
261
|
+
export function requireUser(context: Context): { id: string } {
|
|
262
|
+
if (context.user === null) {
|
|
263
|
+
throw new Error("User required");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return context.user;
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Availability isn't authorization: anyone who can reach your server can call any procedure, so every group and procedure needs its own guards. Route params aren't passed to procedures automatically; pass what you need as input and validate it.
|
|
271
|
+
|
|
272
|
+
### JSON values
|
|
273
|
+
|
|
274
|
+
Inputs and results must be strict JSON. `Date`, `undefined`, `NaN` and `Infinity`, functions, class instances, sparse arrays and cycles are rejected, so convert them explicitly (for example, a date to an ISO string). Rendering and HTTP use the same encoding, so a value that works during SSR also works in the browser. Plain and readonly interfaces work as input and result types without index signatures, and keep their declared types on the client.
|
|
275
|
+
|
|
276
|
+
### Declared errors
|
|
277
|
+
|
|
278
|
+
Declare the errors a procedure can return, then throw them from the handler:
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
complete: mutation({
|
|
282
|
+
input: idSchema,
|
|
283
|
+
errors: {
|
|
284
|
+
NOT_FOUND: { status: 404, message: "Todo does not exist", data: idSchema },
|
|
285
|
+
},
|
|
286
|
+
handler: async ({ input, context, errors }) => {
|
|
287
|
+
const todo = await context.db.todos.completeForUser(requireUser(context).id, input.id);
|
|
288
|
+
|
|
289
|
+
if (todo === null) {
|
|
290
|
+
throw errors.NOT_FOUND({ id: input.id });
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return todo;
|
|
294
|
+
},
|
|
295
|
+
}),
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
Each error needs an identifier code, an integer literal `status` from 400 to 599, a non-empty literal `message` and a `data` schema; use a `Schema<null>` for errors without data. The error map must be written inline. The server validates the data with the schema before sending it.
|
|
299
|
+
|
|
300
|
+
Launch itself uses four codes, which you can't declare:
|
|
301
|
+
|
|
302
|
+
| Code | Status | When |
|
|
303
|
+
| --------------- | ------ | ----------------------------------------------------------------------------------- |
|
|
304
|
+
| `INVALID_INPUT` | 400 | Input failed schema validation |
|
|
305
|
+
| `FORBIDDEN` | 403 | A guard returned `false`, or a mutation was called during server rendering |
|
|
306
|
+
| `RPC_NOT_FOUND` | 404 | No such procedure |
|
|
307
|
+
| `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
|
|
308
|
+
|
|
309
|
+
`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.
|
|
310
|
+
|
|
311
|
+
## Calling RPCs
|
|
312
|
+
|
|
313
|
+
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:
|
|
314
|
+
|
|
315
|
+
```ts
|
|
316
|
+
import { Component } from "@angular/core";
|
|
317
|
+
import { injectRpc } from "./rpc.generated";
|
|
318
|
+
|
|
319
|
+
@Component({/* … */})
|
|
320
|
+
export default class Todos {
|
|
321
|
+
readonly #rpc = injectRpc();
|
|
322
|
+
|
|
323
|
+
async complete(id: string): Promise<void> {
|
|
324
|
+
try {
|
|
325
|
+
await this.#rpc.todos.complete({ id });
|
|
326
|
+
await this.#rpc.todos.list(); // read again explicitly; nothing is invalidated for you
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (this.#rpc.todos.complete.isError(error) && error.code === "NOT_FOUND") {
|
|
329
|
+
const missingId: string = error.data.id;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
Every call returns a promise. Procedures with input take the input first and options second; procedures without input take only options:
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
await rpc.todos.list();
|
|
340
|
+
await rpc.todos.list({ signal, transferCache: false });
|
|
341
|
+
await rpc.todos.add({ title }, { signal });
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
| Option | Effect |
|
|
345
|
+
| --------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
346
|
+
| `signal` | Abort the HTTP request; the call rejects with an `AbortError`. The server may still finish the work, including a write. |
|
|
347
|
+
| `transferCache` | Queries default to `true`. Mutations only accept `false` and never use the transfer cache. |
|
|
348
|
+
|
|
349
|
+
`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"`.
|
|
350
|
+
|
|
351
|
+
Route resolvers can call RPCs too, which is how a page gets its data during SSR:
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
// src/routes/+authenticated/todos/route.ts
|
|
355
|
+
import { defineRoute } from "@loozo/angular-router";
|
|
356
|
+
import parent from "../route";
|
|
357
|
+
import { injectRpc } from "./rpc.generated";
|
|
358
|
+
|
|
359
|
+
export default defineRoute("todos", {
|
|
360
|
+
parent,
|
|
361
|
+
resolve: {
|
|
362
|
+
todos: () => injectRpc().todos.list(),
|
|
363
|
+
session: () => injectRpc().session.current(),
|
|
364
|
+
},
|
|
365
|
+
});
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
`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.
|
|
369
|
+
|
|
370
|
+
## Server rendering and hydration
|
|
371
|
+
|
|
372
|
+
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 }`.
|
|
373
|
+
|
|
374
|
+
The reuse has limits, all of them Angular's transfer cache behaving as designed:
|
|
375
|
+
|
|
376
|
+
- Only successful responses transfer. A query that fails during server rendering, with a declared error or a framework code, runs again over HTTP during hydration, with a fresh context. The handler runs twice, and the browser shows whatever the second call returns.
|
|
377
|
+
- 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.
|
|
378
|
+
- 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.
|
|
379
|
+
|
|
380
|
+
Mutations are refused during server rendering with `FORBIDDEN`, before validation, guards or the handler run. Rendering should only read.
|
|
381
|
+
|
|
382
|
+
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.
|
|
383
|
+
|
|
384
|
+
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`.
|
|
385
|
+
|
|
386
|
+
## Deploying
|
|
387
|
+
|
|
388
|
+
With `outputMode: "server"`, `ng build` writes the browser files and a bundled server:
|
|
389
|
+
|
|
390
|
+
```text
|
|
391
|
+
dist/<app>/
|
|
392
|
+
├── browser/ scripts, styles and index.csr.html
|
|
393
|
+
└── server/server.mjs your server.ts with Angular, Launch and their dependencies
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
Copy `dist/<app>` to the host and start the server with Node:
|
|
397
|
+
|
|
398
|
+
```sh
|
|
399
|
+
PORT=8080 NG_ALLOWED_HOSTS=example.com node dist/<app>/server/server.mjs
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
The server bundle includes your dependencies by default, so the host doesn't need `node_modules`. `AngularNodeAppEngine` reads two environment variables:
|
|
403
|
+
|
|
404
|
+
| Variable | Effect |
|
|
405
|
+
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
406
|
+
| `NG_ALLOWED_HOSTS` | Comma-separated hostnames allowed to render pages, in addition to `security.allowedHosts` in `angular.json`. Pages for other hosts get a 400. |
|
|
407
|
+
| `NG_TRUST_PROXY_HEADERS` | Comma-separated `Forwarded` and `X-Forwarded-*` headers that Angular should trust. Set it only behind a proxy that overwrites those headers. Off by default. |
|
|
408
|
+
|
|
409
|
+
The host check covers page rendering only. `handleRequest` runs before Angular and answers RPC requests for any host.
|
|
410
|
+
|
|
411
|
+
Launch calls `/_rpc/<group>/<procedure>` from the root of the domain, even when the app has a different `<base href>`. If the app is served under a path prefix, route `/_rpc/` to the same server.
|
|
412
|
+
|
|
413
|
+
Browser tabs opened before a deploy keep calling the procedures they were built with. After you move an `rpc.ts`, rename a 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.
|
|
414
|
+
|
|
415
|
+
Launch has been verified on Node only.
|
|
416
|
+
|
|
417
|
+
### Other server frameworks
|
|
418
|
+
|
|
419
|
+
`handleRequest` and `createContext` take a web `Request`, so any framework that gives you one works. `AngularNodeAppEngine` also accepts a web `Request`, and keeps the environment variables above. With [Hono](https://hono.dev) on Node:
|
|
420
|
+
|
|
421
|
+
```ts
|
|
422
|
+
// src/server.ts
|
|
423
|
+
import { fileURLToPath } from "node:url";
|
|
424
|
+
import { createRequestHandler } from "@angular/ssr";
|
|
425
|
+
import { AngularNodeAppEngine, isMainModule } from "@angular/ssr/node";
|
|
426
|
+
import { serve } from "@hono/node-server";
|
|
427
|
+
import { serveStatic } from "@hono/node-server/serve-static";
|
|
428
|
+
import { Hono } from "hono";
|
|
429
|
+
import { createContext, handleRequest } from "../generated/server.generated";
|
|
430
|
+
|
|
431
|
+
const browser = fileURLToPath(new URL("../browser", import.meta.url));
|
|
432
|
+
const angular = new AngularNodeAppEngine();
|
|
433
|
+
const app = new Hono();
|
|
434
|
+
|
|
435
|
+
app.use("*", serveStatic({ root: browser }));
|
|
436
|
+
|
|
437
|
+
app.all("*", async (c) => {
|
|
438
|
+
const rpc = await handleRequest(c.req.raw);
|
|
439
|
+
|
|
440
|
+
if (rpc) {
|
|
441
|
+
return rpc;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const scope = await createContext(c.req.raw);
|
|
445
|
+
const page = await angular.handle(scope.request, scope);
|
|
446
|
+
|
|
447
|
+
return page ?? c.notFound();
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
if (isMainModule(import.meta.url)) {
|
|
451
|
+
const port = Number(process.env["PORT"] ?? 4000);
|
|
452
|
+
|
|
453
|
+
serve({ fetch: app.fetch, port }, ({ port }) => {
|
|
454
|
+
console.log(`Listening on http://localhost:${port}`);
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export const reqHandler = createRequestHandler(app.fetch);
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
Export the handler as `reqHandler`; Angular's dev server and build don't look for a default export. Under `ng serve`, `serveStatic` logs that the `browser` directory doesn't exist. That's expected: the dev server serves those files itself.
|
|
462
|
+
|
|
463
|
+
## Generation
|
|
464
|
+
|
|
465
|
+
```ts
|
|
466
|
+
generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
| Option | Type | Description |
|
|
470
|
+
| ----------------- | ---------- | ----------------------------------------------------------------------------- |
|
|
471
|
+
| `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
|
|
472
|
+
| `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
|
|
473
|
+
| `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
|
|
474
|
+
| `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
|
|
475
|
+
|
|
476
|
+
`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.
|
|
477
|
+
|
|
478
|
+
Generation reads your source without running it. It writes the router's files plus:
|
|
479
|
+
|
|
480
|
+
| File | Contents |
|
|
481
|
+
| --------------------------------------- | -------------------------------------------------------------------------------- |
|
|
482
|
+
| `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups; none for redirect routes |
|
|
483
|
+
| `<outDirectory>/context.generated.d.ts` | Registers your context type |
|
|
484
|
+
| `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
|
|
485
|
+
|
|
486
|
+
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.
|
|
487
|
+
|
|
488
|
+
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.
|
|
489
|
+
|
|
490
|
+
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`.
|
|
491
|
+
|
|
492
|
+
`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.
|
|
493
|
+
|
|
494
|
+
Wire IDs come from each group's file path relative to the generation tsconfig's directory. Moving or renaming an `rpc.ts` changes its URL, and moving the generation tsconfig to another directory changes every group's URL. Renaming a namespace or procedure doesn't change the group ID. The example doesn't commit generated files: it regenerates before every build, and `node generate.mjs --check` verifies them without writing.
|
|
495
|
+
|
|
496
|
+
`@loozo/angular-launch/generation` is Node-only.
|
|
497
|
+
|
|
498
|
+
### Generation sessions
|
|
499
|
+
|
|
500
|
+
`generate` starts from scratch on every call. A long-running tool that regenerates repeatedly (for example, after file changes) can create a session instead, which reuses compiler work between calls:
|
|
501
|
+
|
|
502
|
+
```js
|
|
503
|
+
import { createGenerationSession } from "@loozo/angular-launch/generation";
|
|
504
|
+
|
|
505
|
+
const session = createGenerationSession(workspace, {
|
|
506
|
+
tsconfig: "tsconfig.app.json",
|
|
507
|
+
scanDirectories: ["src/routes"],
|
|
508
|
+
outDirectory: "generated",
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
try {
|
|
512
|
+
await session.generate();
|
|
513
|
+
// …after the next change:
|
|
514
|
+
await session.generate();
|
|
515
|
+
await session.generate({ check: true });
|
|
516
|
+
} finally {
|
|
517
|
+
await session.dispose();
|
|
518
|
+
}
|
|
519
|
+
```
|
|
520
|
+
|
|
521
|
+
The options are fixed when the session is created. Edits inside the app, including moves, are picked up by the next call; to move the app directory itself, dispose the session and create a new one. A session doesn't watch files and isn't coordinated with Angular's own watcher: you decide when to call `generate`, and must not start a second call before the previous one settles, since overlapping calls are rejected. A failed call doesn't break the session; the next call starts clean. After you change dependencies, create a new session. `dispose()` stops publishing from any active call, waits for it, and makes later calls reject. Don't run two sessions or generators against the same output at once.
|
|
522
|
+
|
|
523
|
+
## Limitations
|
|
524
|
+
|
|
525
|
+
- No Angular builder or watch mode for Launch yet; run generation yourself before `ng build` or `ng serve`.
|
|
526
|
+
- No subscriptions, optimistic updates, automatic invalidation, or query cache beyond hydration.
|
|
527
|
+
- No storage adapters; persistence is your handler's job.
|
|
528
|
+
- No production authentication, CSRF, CORS or caching policy. You provide those.
|
|
529
|
+
- Server work isn't cancelled when the client aborts, and nothing is rolled back.
|
|
530
|
+
- One RPC group per route, and one context per application.
|
|
531
|
+
|
|
532
|
+
## Further reading
|
|
533
|
+
|
|
534
|
+
- [`specs/angular-launch.md`](../../specs/angular-launch.md): design and full contract
|
|
535
|
+
- [`examples/angular-launch`](../../examples/angular-launch/): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
|
|
536
|
+
- [`@loozo/angular-router`](../angular-router/README.md): routes, codecs and navigation
|
|
537
|
+
|
|
538
|
+
## Developing this package
|
|
539
|
+
|
|
540
|
+
```sh
|
|
541
|
+
pnpm run build # tsc
|
|
542
|
+
pnpm run typecheck
|
|
543
|
+
pnpm run test # node --test
|
|
544
|
+
node tests/packed.mjs /absolute/new-directory # packed consumer check; directory must not exist
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
The packed check keeps its consumer, pnpm store and temporary files inside the directory you pass.
|