@loozo/angular-launch 0.0.1 → 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/README.md +129 -20
- package/client.d.ts +232 -0
- package/client.js +169 -0
- package/generation/index.d.ts +116 -0
- package/{dist/generation → generation}/index.js +74 -3
- package/index.d.ts +2 -0
- package/index.js +1 -0
- package/{dist/json.d.ts → json.d.ts} +9 -3
- package/package.json +15 -28
- package/server/backend.d.ts +58 -0
- package/{dist/server → server}/backend.js +54 -0
- package/server/definitions.d.ts +486 -0
- package/server/definitions.js +170 -0
- package/server/dispatch.d.ts +140 -0
- package/{dist/server → server}/dispatch.js +76 -0
- package/{dist/server → server}/errors.d.ts +10 -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/dist/client.d.ts +0 -62
- package/dist/client.js +0 -97
- package/dist/generation/index.d.ts +0 -13
- package/dist/server/backend.d.ts +0 -4
- package/dist/server/definitions.d.ts +0 -108
- package/dist/server/definitions.js +0 -25
- package/dist/server/dispatch.d.ts +0 -27
- package/dist/server/index.d.ts +0 -5
- package/dist/server/index.js +0 -3
- /package/{dist/generated.d.ts → generated.d.ts} +0 -0
- /package/{dist/generated.js → generated.js} +0 -0
- /package/{dist/json.js → json.js} +0 -0
- /package/{dist/server → server}/errors.js +0 -0
package/README.md
CHANGED
|
@@ -6,19 +6,19 @@ Calls go through Angular's `HttpClient`. In the browser they're ordinary HTTP re
|
|
|
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. Version `0.0.
|
|
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
10
|
|
|
11
11
|
## Requirements
|
|
12
12
|
|
|
13
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.
|
|
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
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
16
|
- A `package.json` with a `name` in the application directory. The name is part of the generated app identity.
|
|
17
17
|
|
|
18
18
|
Install both packages:
|
|
19
19
|
|
|
20
20
|
```sh
|
|
21
|
-
pnpm add @loozo/angular-launch @loozo/angular-router@0.0.
|
|
21
|
+
pnpm add @loozo/angular-launch @loozo/angular-router@0.0.4
|
|
22
22
|
```
|
|
23
23
|
|
|
24
24
|
## How it fits together
|
|
@@ -170,44 +170,70 @@ export default async function bootstrap(context: BootstrapContext) {
|
|
|
170
170
|
}
|
|
171
171
|
```
|
|
172
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
|
|
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
174
|
|
|
175
175
|
```ts
|
|
176
176
|
// src/server.ts
|
|
177
|
+
import { join } from "node:path";
|
|
177
178
|
import {
|
|
178
179
|
AngularNodeAppEngine,
|
|
179
180
|
createNodeRequestHandler,
|
|
180
181
|
createWebRequestFromNodeRequest,
|
|
182
|
+
isMainModule,
|
|
181
183
|
writeResponseToNodeResponse,
|
|
182
184
|
} from "@angular/ssr/node";
|
|
185
|
+
import express from "express";
|
|
183
186
|
import { createContext, handleRequest } from "../generated/server.generated";
|
|
184
187
|
|
|
188
|
+
const browser = join(import.meta.dirname, "../browser");
|
|
185
189
|
const angular = new AngularNodeAppEngine();
|
|
190
|
+
const app = express();
|
|
186
191
|
|
|
187
|
-
|
|
188
|
-
const web = createWebRequestFromNodeRequest(request);
|
|
189
|
-
const rpc = await handleRequest(web);
|
|
192
|
+
app.use(express.static(browser, { maxAge: "1y", index: false, redirect: false }));
|
|
190
193
|
|
|
191
|
-
|
|
192
|
-
|
|
194
|
+
app.use(async (request, response, next) => {
|
|
195
|
+
try {
|
|
196
|
+
const web = createWebRequestFromNodeRequest(request);
|
|
197
|
+
const rpc = await handleRequest(web);
|
|
193
198
|
|
|
194
|
-
|
|
195
|
-
|
|
199
|
+
if (rpc) {
|
|
200
|
+
await writeResponseToNodeResponse(rpc, response);
|
|
196
201
|
|
|
197
|
-
|
|
198
|
-
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
199
204
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
response.end("Not found");
|
|
205
|
+
const scope = await createContext(web);
|
|
206
|
+
const page = await angular.handle(scope.request, scope);
|
|
203
207
|
|
|
204
|
-
|
|
205
|
-
|
|
208
|
+
if (!page) {
|
|
209
|
+
next();
|
|
206
210
|
|
|
207
|
-
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
await writeResponseToNodeResponse(page, response);
|
|
215
|
+
} catch (error) {
|
|
216
|
+
next(error);
|
|
217
|
+
}
|
|
208
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);
|
|
209
233
|
```
|
|
210
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
|
+
|
|
211
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.
|
|
212
238
|
|
|
213
239
|
## Defining RPCs
|
|
@@ -345,12 +371,95 @@ export default defineRoute("todos", {
|
|
|
345
371
|
|
|
346
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 }`.
|
|
347
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
|
+
|
|
348
380
|
Mutations are refused during server rendering with `FORBIDDEN`, before validation, guards or the handler run. Rendering should only read.
|
|
349
381
|
|
|
350
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.
|
|
351
383
|
|
|
352
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`.
|
|
353
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
|
+
|
|
354
463
|
## Generation
|
|
355
464
|
|
|
356
465
|
```ts
|
|
@@ -380,7 +489,7 @@ Before writing, generation type-checks the generated files, your route and RPC d
|
|
|
380
489
|
|
|
381
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`.
|
|
382
491
|
|
|
383
|
-
`server.generated.ts` binds
|
|
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.
|
|
384
493
|
|
|
385
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.
|
|
386
495
|
|
package/client.d.ts
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import type { ErrorDefinitions, Group, OutputOf, Procedure, ProcedureKind, Schema } from "./server/definitions.js";
|
|
2
|
+
/** Per-call options for a generated query callable. */
|
|
3
|
+
export interface CallOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Aborts the call: the HTTP request is cancelled and the promise rejects with a
|
|
6
|
+
* `DOMException` named `AbortError`.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* An already aborted signal rejects without sending a request. Aborting doesn't
|
|
10
|
+
* cancel server work that has already started.
|
|
11
|
+
*/
|
|
12
|
+
readonly signal?: AbortSignal;
|
|
13
|
+
/**
|
|
14
|
+
* Whether Angular's HTTP transfer cache may store this call's response during server
|
|
15
|
+
* rendering and reuse it during hydration. Defaults to `true`.
|
|
16
|
+
*/
|
|
17
|
+
readonly transferCache?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Per-call options for a generated mutation callable. */
|
|
20
|
+
export interface MutationCallOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Aborts the call: the HTTP request is cancelled and the promise rejects with a
|
|
23
|
+
* `DOMException` named `AbortError`.
|
|
24
|
+
*
|
|
25
|
+
* @remarks
|
|
26
|
+
* Aborting doesn't cancel server work that has already started, so the write may
|
|
27
|
+
* still complete.
|
|
28
|
+
*/
|
|
29
|
+
readonly signal?: AbortSignal;
|
|
30
|
+
/** Only `false` is accepted: mutations never use the HTTP transfer cache. */
|
|
31
|
+
readonly transferCache?: false;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Browser-safe metadata for one declared error of a procedure.
|
|
35
|
+
*
|
|
36
|
+
* @remarks
|
|
37
|
+
* Internal; not exported from a public entry point. Generation writes these entries
|
|
38
|
+
* into each `rpc.generated.ts` so the client can recognize the procedure's declared
|
|
39
|
+
* error responses without the server's schemas.
|
|
40
|
+
*/
|
|
41
|
+
export interface ErrorMetadata {
|
|
42
|
+
/** The declared error code, such as `"NOT_FOUND"`. */
|
|
43
|
+
readonly code: string;
|
|
44
|
+
/** The HTTP status the error is sent with, from 400 to 599. */
|
|
45
|
+
readonly status: number;
|
|
46
|
+
/** The declared public message sent with every instance of the error. */
|
|
47
|
+
readonly message: string;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The four error codes Launch itself returns, with their HTTP status and public message.
|
|
51
|
+
*
|
|
52
|
+
* @remarks
|
|
53
|
+
* - `INVALID_INPUT` (400): the request or its input failed validation.
|
|
54
|
+
* - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
|
|
55
|
+
* server rendering.
|
|
56
|
+
* - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
|
|
57
|
+
* - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
|
|
58
|
+
*
|
|
59
|
+
* These codes are reserved: procedures can't declare errors with them.
|
|
60
|
+
*/
|
|
61
|
+
export declare const frameworkFailures: {
|
|
62
|
+
readonly INVALID_INPUT: {
|
|
63
|
+
readonly status: 400;
|
|
64
|
+
readonly message: "Invalid RPC input";
|
|
65
|
+
};
|
|
66
|
+
readonly FORBIDDEN: {
|
|
67
|
+
readonly status: 403;
|
|
68
|
+
readonly message: "RPC forbidden";
|
|
69
|
+
};
|
|
70
|
+
readonly RPC_NOT_FOUND: {
|
|
71
|
+
readonly status: 404;
|
|
72
|
+
readonly message: "RPC not found";
|
|
73
|
+
};
|
|
74
|
+
readonly INTERNAL: {
|
|
75
|
+
readonly status: 500;
|
|
76
|
+
readonly message: "Internal server error";
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
/** One of the error codes Launch itself returns: a key of {@link frameworkFailures}. */
|
|
80
|
+
export type FrameworkCode = keyof typeof frameworkFailures;
|
|
81
|
+
/**
|
|
82
|
+
* An error response returned by a procedure: either a Launch framework failure or one
|
|
83
|
+
* of the procedure's declared errors.
|
|
84
|
+
*
|
|
85
|
+
* @remarks
|
|
86
|
+
* Generated callables reject with an `RpcError` only for a response that exactly
|
|
87
|
+
* matches a framework failure or one of that procedure's declared errors. Network
|
|
88
|
+
* failures, aborts and unrecognized responses reject with the original error instead.
|
|
89
|
+
* Use the callable's `isError` to narrow a caught value: it recognizes only errors
|
|
90
|
+
* returned by that exact procedure, not `RpcError` instances created elsewhere.
|
|
91
|
+
*
|
|
92
|
+
* @typeParam Code - The error code.
|
|
93
|
+
* @typeParam Data - The error's data: `null` for framework failures, the data schema's
|
|
94
|
+
* output for declared errors.
|
|
95
|
+
*/
|
|
96
|
+
export declare class RpcError<Code extends string = FrameworkCode, Data = null> extends Error {
|
|
97
|
+
/** The framework or declared error code. */
|
|
98
|
+
readonly code: Code;
|
|
99
|
+
/** The HTTP status of the response. */
|
|
100
|
+
readonly status: number;
|
|
101
|
+
/** The error's data: `null` for framework failures, validated data for declared errors. */
|
|
102
|
+
readonly data: Data;
|
|
103
|
+
/**
|
|
104
|
+
* Creates an error with the given code, status and data.
|
|
105
|
+
*
|
|
106
|
+
* @param code - The error code.
|
|
107
|
+
* @param status - The HTTP status of the response.
|
|
108
|
+
* @param data - The error's data. Defaults to `null`.
|
|
109
|
+
* @param message - The public message. Defaults to the framework message when `code`
|
|
110
|
+
* is a {@link FrameworkCode}.
|
|
111
|
+
* @throws TypeError when `message` is omitted and `code` isn't a framework code.
|
|
112
|
+
*/
|
|
113
|
+
constructor(
|
|
114
|
+
/** The framework or declared error code. */
|
|
115
|
+
code: Code,
|
|
116
|
+
/** The HTTP status of the response. */
|
|
117
|
+
status: number,
|
|
118
|
+
/** The error's data: `null` for framework failures, validated data for declared errors. */
|
|
119
|
+
data?: Data, message?: string);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Recognizes a response body that is exactly a Launch framework failure.
|
|
123
|
+
*
|
|
124
|
+
* @remarks
|
|
125
|
+
* Internal; not exported from a public entry point. Used by the generated client to
|
|
126
|
+
* convert responses into {@link RpcError}s. The body must be strict JSON shaped
|
|
127
|
+
* exactly as `{ error: { code, message, data: null } }`, with the framework code's own
|
|
128
|
+
* status and message.
|
|
129
|
+
*
|
|
130
|
+
* @param value - The parsed response body.
|
|
131
|
+
* @param status - The response's HTTP status.
|
|
132
|
+
* @returns The framework code, or `undefined` when the body doesn't match exactly.
|
|
133
|
+
*/
|
|
134
|
+
export declare function recognizedFailure(value: unknown, status: number): FrameworkCode | undefined;
|
|
135
|
+
/**
|
|
136
|
+
* Recognizes a response body that is exactly a framework failure or one of the given
|
|
137
|
+
* declared errors.
|
|
138
|
+
*
|
|
139
|
+
* @remarks
|
|
140
|
+
* Internal; not exported from a public entry point. Used by the generated client to
|
|
141
|
+
* convert responses into {@link RpcError}s. A declared error matches only when its
|
|
142
|
+
* code, status and message all equal one entry of `declared`. Entries using framework
|
|
143
|
+
* codes are ignored.
|
|
144
|
+
*
|
|
145
|
+
* @param value - The parsed response body.
|
|
146
|
+
* @param status - The response's HTTP status.
|
|
147
|
+
* @param declared - The procedure's declared error metadata.
|
|
148
|
+
* @returns The recognized code, message and data, or `undefined` when the body doesn't
|
|
149
|
+
* match exactly.
|
|
150
|
+
*/
|
|
151
|
+
export declare function recognizedError(value: unknown, status: number, declared: readonly ErrorMetadata[]): {
|
|
152
|
+
/** The framework or declared error code. */
|
|
153
|
+
code: string;
|
|
154
|
+
/** The error's message. */
|
|
155
|
+
message: string;
|
|
156
|
+
/** The declared error's data as received, or `null` for a framework failure. */
|
|
157
|
+
data: unknown;
|
|
158
|
+
} | undefined;
|
|
159
|
+
type FrameworkError = {
|
|
160
|
+
[Code in FrameworkCode]: RpcError<Code, null>;
|
|
161
|
+
}[FrameworkCode];
|
|
162
|
+
type DeclaredError<Errors extends ErrorDefinitions> = {
|
|
163
|
+
[Code in keyof Errors & string]: RpcError<Code, OutputOf<Errors[Code]["data"]>>;
|
|
164
|
+
}[keyof Errors & string];
|
|
165
|
+
/**
|
|
166
|
+
* The errors a generated callable for a procedure can reject with as {@link RpcError}s.
|
|
167
|
+
*
|
|
168
|
+
* @remarks
|
|
169
|
+
* A union discriminated by `code`: one member per framework failure with `null` data,
|
|
170
|
+
* and one per declared error with its data schema's output type. Import the group
|
|
171
|
+
* with `import type` so server code stays out of the browser bundle.
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```ts
|
|
175
|
+
* import type { ClientRpcError } from "@loozo/angular-launch";
|
|
176
|
+
* import type todos from "./rpc";
|
|
177
|
+
*
|
|
178
|
+
* type CompleteError = ClientRpcError<typeof todos.procedures.complete>;
|
|
179
|
+
* ```
|
|
180
|
+
*
|
|
181
|
+
* @typeParam Value - A procedure created by `query` or `mutation`.
|
|
182
|
+
*/
|
|
183
|
+
export type ClientRpcError<Value> = Value extends Procedure<infer _Input, infer _Output, infer _Kind, infer Errors> ? FrameworkError | DeclaredError<Errors> : never;
|
|
184
|
+
type Options<Kind extends ProcedureKind> = Kind extends "mutation" ? MutationCallOptions : CallOptions;
|
|
185
|
+
type Callable<Input, Output, Kind extends ProcedureKind> = Input extends Schema<infer Caller, unknown> ? (input: Caller, options?: Options<Kind>) => Promise<Output> : (options?: Options<Kind>) => Promise<Output>;
|
|
186
|
+
/**
|
|
187
|
+
* The generated client callable for a procedure.
|
|
188
|
+
*
|
|
189
|
+
* @remarks
|
|
190
|
+
* The type of `Client<typeof group>["name"]`. A procedure with an input schema is called as
|
|
191
|
+
* `(input, options?)`, where `input` is the schema's input type; one without input is
|
|
192
|
+
* called as `(options?)`. Every call
|
|
193
|
+
* returns a promise of the handler's awaited result. Queries take {@link CallOptions}
|
|
194
|
+
* and mutations take {@link MutationCallOptions}.
|
|
195
|
+
*
|
|
196
|
+
* @typeParam Value - A procedure created by `query` or `mutation`.
|
|
197
|
+
*/
|
|
198
|
+
export type ClientProcedure<Value> = Value extends Procedure<infer Input, infer Output, infer Kind, infer Errors> ? Callable<Input, Awaited<Output>, Kind> & {
|
|
199
|
+
/** Whether the procedure is a `"query"` or a `"mutation"`. */
|
|
200
|
+
readonly kind: Kind;
|
|
201
|
+
/**
|
|
202
|
+
* Whether `error` is an {@link RpcError} returned by this exact procedure.
|
|
203
|
+
*
|
|
204
|
+
* @param error - A value caught from a call.
|
|
205
|
+
* @returns `true` only for errors this procedure's calls rejected with, narrowed to
|
|
206
|
+
* its framework failures and declared errors.
|
|
207
|
+
*/
|
|
208
|
+
isError(error: unknown): error is FrameworkError | DeclaredError<Errors>;
|
|
209
|
+
} : never;
|
|
210
|
+
/**
|
|
211
|
+
* The generated client for an RPC group: one callable per procedure.
|
|
212
|
+
*
|
|
213
|
+
* @remarks
|
|
214
|
+
* Generated `injectRpc()` functions return an object of these, keyed by namespace.
|
|
215
|
+
* Call `injectRpc()` in an Angular injection context where `HttpClient` is provided;
|
|
216
|
+
* the clients it returns can be called later, outside an injection context. Import the
|
|
217
|
+
* group with `import type` so server code stays out of the browser bundle.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* import type { Client } from "@loozo/angular-launch";
|
|
222
|
+
* import type todos from "./rpc";
|
|
223
|
+
*
|
|
224
|
+
* type Todos = Awaited<ReturnType<Client<typeof todos>["list"]>>;
|
|
225
|
+
* ```
|
|
226
|
+
*
|
|
227
|
+
* @typeParam Value - A group created by `defineRpc`.
|
|
228
|
+
*/
|
|
229
|
+
export type Client<Value> = Value extends Group<string, infer Procedures> ? {
|
|
230
|
+
readonly [Key in keyof Procedures]: ClientProcedure<Procedures[Key]>;
|
|
231
|
+
} : never;
|
|
232
|
+
export {};
|
package/client.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { serializeJson } from "./json.js";
|
|
2
|
+
/**
|
|
3
|
+
* The four error codes Launch itself returns, with their HTTP status and public message.
|
|
4
|
+
*
|
|
5
|
+
* @remarks
|
|
6
|
+
* - `INVALID_INPUT` (400): the request or its input failed validation.
|
|
7
|
+
* - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
|
|
8
|
+
* server rendering.
|
|
9
|
+
* - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
|
|
10
|
+
* - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
|
|
11
|
+
*
|
|
12
|
+
* These codes are reserved: procedures can't declare errors with them.
|
|
13
|
+
*/
|
|
14
|
+
export const frameworkFailures = {
|
|
15
|
+
INVALID_INPUT: { status: 400, message: "Invalid RPC input" },
|
|
16
|
+
FORBIDDEN: { status: 403, message: "RPC forbidden" },
|
|
17
|
+
RPC_NOT_FOUND: { status: 404, message: "RPC not found" },
|
|
18
|
+
INTERNAL: { status: 500, message: "Internal server error" },
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* An error response returned by a procedure: either a Launch framework failure or one
|
|
22
|
+
* of the procedure's declared errors.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* Generated callables reject with an `RpcError` only for a response that exactly
|
|
26
|
+
* matches a framework failure or one of that procedure's declared errors. Network
|
|
27
|
+
* failures, aborts and unrecognized responses reject with the original error instead.
|
|
28
|
+
* Use the callable's `isError` to narrow a caught value: it recognizes only errors
|
|
29
|
+
* returned by that exact procedure, not `RpcError` instances created elsewhere.
|
|
30
|
+
*
|
|
31
|
+
* @typeParam Code - The error code.
|
|
32
|
+
* @typeParam Data - The error's data: `null` for framework failures, the data schema's
|
|
33
|
+
* output for declared errors.
|
|
34
|
+
*/
|
|
35
|
+
export class RpcError extends Error {
|
|
36
|
+
code;
|
|
37
|
+
status;
|
|
38
|
+
data;
|
|
39
|
+
/**
|
|
40
|
+
* Creates an error with the given code, status and data.
|
|
41
|
+
*
|
|
42
|
+
* @param code - The error code.
|
|
43
|
+
* @param status - The HTTP status of the response.
|
|
44
|
+
* @param data - The error's data. Defaults to `null`.
|
|
45
|
+
* @param message - The public message. Defaults to the framework message when `code`
|
|
46
|
+
* is a {@link FrameworkCode}.
|
|
47
|
+
* @throws TypeError when `message` is omitted and `code` isn't a framework code.
|
|
48
|
+
*/
|
|
49
|
+
constructor(
|
|
50
|
+
/** The framework or declared error code. */
|
|
51
|
+
code,
|
|
52
|
+
/** The HTTP status of the response. */
|
|
53
|
+
status,
|
|
54
|
+
/** The error's data: `null` for framework failures, validated data for declared errors. */
|
|
55
|
+
data = null, message) {
|
|
56
|
+
if (message === undefined) {
|
|
57
|
+
if (!Object.hasOwn(frameworkFailures, code)) {
|
|
58
|
+
throw new TypeError("Declared RPC errors require their public message");
|
|
59
|
+
}
|
|
60
|
+
message = frameworkFailures[code].message;
|
|
61
|
+
}
|
|
62
|
+
super(message);
|
|
63
|
+
this.code = code;
|
|
64
|
+
this.status = status;
|
|
65
|
+
this.data = data;
|
|
66
|
+
this.name = "RpcError";
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Recognizes a response body that is exactly a Launch framework failure.
|
|
71
|
+
*
|
|
72
|
+
* @remarks
|
|
73
|
+
* Internal; not exported from a public entry point. Used by the generated client to
|
|
74
|
+
* convert responses into {@link RpcError}s. The body must be strict JSON shaped
|
|
75
|
+
* exactly as `{ error: { code, message, data: null } }`, with the framework code's own
|
|
76
|
+
* status and message.
|
|
77
|
+
*
|
|
78
|
+
* @param value - The parsed response body.
|
|
79
|
+
* @param status - The response's HTTP status.
|
|
80
|
+
* @returns The framework code, or `undefined` when the body doesn't match exactly.
|
|
81
|
+
*/
|
|
82
|
+
export function recognizedFailure(value, status) {
|
|
83
|
+
try {
|
|
84
|
+
serializeJson(value);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
if (typeof value !== "object" ||
|
|
90
|
+
value === null ||
|
|
91
|
+
!("error" in value) ||
|
|
92
|
+
Object.keys(value).length !== 1) {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
const error = value.error;
|
|
96
|
+
if (typeof error !== "object" ||
|
|
97
|
+
error === null ||
|
|
98
|
+
!("code" in error) ||
|
|
99
|
+
!("message" in error) ||
|
|
100
|
+
!("data" in error) ||
|
|
101
|
+
Object.keys(error).length !== 3 ||
|
|
102
|
+
typeof error.code !== "string") {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
for (const code of Object.keys(frameworkFailures)) {
|
|
106
|
+
const expected = frameworkFailures[code];
|
|
107
|
+
if (error.code === code &&
|
|
108
|
+
status === expected.status &&
|
|
109
|
+
error.message === expected.message &&
|
|
110
|
+
error.data === null) {
|
|
111
|
+
return code;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Recognizes a response body that is exactly a framework failure or one of the given
|
|
118
|
+
* declared errors.
|
|
119
|
+
*
|
|
120
|
+
* @remarks
|
|
121
|
+
* Internal; not exported from a public entry point. Used by the generated client to
|
|
122
|
+
* convert responses into {@link RpcError}s. A declared error matches only when its
|
|
123
|
+
* code, status and message all equal one entry of `declared`. Entries using framework
|
|
124
|
+
* codes are ignored.
|
|
125
|
+
*
|
|
126
|
+
* @param value - The parsed response body.
|
|
127
|
+
* @param status - The response's HTTP status.
|
|
128
|
+
* @param declared - The procedure's declared error metadata.
|
|
129
|
+
* @returns The recognized code, message and data, or `undefined` when the body doesn't
|
|
130
|
+
* match exactly.
|
|
131
|
+
*/
|
|
132
|
+
export function recognizedError(value, status, declared) {
|
|
133
|
+
const framework = recognizedFailure(value, status);
|
|
134
|
+
if (framework) {
|
|
135
|
+
return { code: framework, message: frameworkFailures[framework].message, data: null };
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
serializeJson(value);
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
if (typeof value !== "object" ||
|
|
144
|
+
value === null ||
|
|
145
|
+
!("error" in value) ||
|
|
146
|
+
Object.keys(value).length !== 1) {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
const error = value.error;
|
|
150
|
+
if (typeof error !== "object" ||
|
|
151
|
+
error === null ||
|
|
152
|
+
!("code" in error) ||
|
|
153
|
+
!("message" in error) ||
|
|
154
|
+
!("data" in error) ||
|
|
155
|
+
Object.keys(error).length !== 3 ||
|
|
156
|
+
typeof error.code !== "string" ||
|
|
157
|
+
typeof error.message !== "string") {
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
for (const definition of declared) {
|
|
161
|
+
if (!Object.hasOwn(frameworkFailures, definition.code) &&
|
|
162
|
+
definition.code === error.code &&
|
|
163
|
+
definition.status === status &&
|
|
164
|
+
definition.message === error.message) {
|
|
165
|
+
return { code: error.code, message: error.message, data: error.data };
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|