@loozo/angular-launch 0.0.2 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -27
- package/client.d.ts +33 -15
- package/client.js +31 -14
- package/generated.d.ts +0 -1
- package/generated.js +3 -3
- package/generation/index.d.ts +8 -1
- package/generation/index.js +25 -15
- package/index.d.ts +1 -0
- package/input-issues.d.ts +56 -0
- package/input-issues.js +78 -0
- package/package.json +16 -2
- package/server/backend.d.ts +3 -3
- package/server/backend.js +7 -7
- package/server/definitions.d.ts +20 -3
- package/server/definitions.js +2 -1
- package/server/dispatch.d.ts +12 -9
- package/server/dispatch.js +24 -13
- package/tanstack-query/README.md +168 -0
- package/tanstack-query/generated.d.ts +5 -0
- package/tanstack-query/generated.js +127 -0
- package/tanstack-query/hydration.d.ts +46 -0
- package/tanstack-query/hydration.js +70 -0
- package/tanstack-query/index.d.ts +2 -0
- package/tanstack-query/index.js +1 -0
- package/tanstack-query/queries.d.ts +124 -0
- package/tanstack-query/queries.js +1 -0
package/README.md
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
# @loozo/angular-launch
|
|
2
2
|
|
|
3
|
-
Typed server functions for Angular applications built with [`@loozo/angular-router`](
|
|
3
|
+
Typed server functions for Angular applications built with [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/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.
|
|
4
4
|
|
|
5
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
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.
|
|
9
|
+
**Status:** experimental. MIT license. It currently covers queries, mutations, guards and declared errors, with optional [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) options and keys. 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
|
|
14
|
+
- `@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.
|
|
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
|
+
- 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.4/packages/angular-launch/tanstack-query/README.md).
|
|
17
18
|
|
|
18
19
|
Install both packages:
|
|
19
20
|
|
|
20
21
|
```sh
|
|
21
|
-
pnpm add @loozo/angular-launch @loozo/angular-router@0.0.
|
|
22
|
+
pnpm add @loozo/angular-launch @loozo/angular-router@0.0.6
|
|
22
23
|
```
|
|
23
24
|
|
|
24
25
|
## How it fits together
|
|
@@ -50,7 +51,7 @@ The route tree is the router's. An `rpc.ts` belongs to the route declared in the
|
|
|
50
51
|
|
|
51
52
|
## Setup
|
|
52
53
|
|
|
53
|
-
The [todos example](
|
|
54
|
+
The [todos example](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.4/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
|
|
|
55
56
|
### 1. Define the context
|
|
56
57
|
|
|
@@ -247,7 +248,7 @@ mutation({ input?, canActivate?, errors?, handler });
|
|
|
247
248
|
|
|
248
249
|
The handler receives `{ context, input, errors }` and returns a value or a promise.
|
|
249
250
|
|
|
250
|
-
- **Namespaces and procedure names** are literal ASCII identifiers. `__proto__` is not allowed; `constructor` and `toString` are fine. One `defineRpc` per route
|
|
251
|
+
- **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.
|
|
251
252
|
- **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
253
|
- **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
254
|
- Guards don't narrow types. Use an ordinary function to narrow, such as the example's `requireUser`:
|
|
@@ -301,13 +302,27 @@ Launch itself uses four codes, which you can't declare:
|
|
|
301
302
|
|
|
302
303
|
| Code | Status | When |
|
|
303
304
|
| --------------- | ------ | ----------------------------------------------------------------------------------- |
|
|
304
|
-
| `INVALID_INPUT` | 400 |
|
|
305
|
+
| `INVALID_INPUT` | 400 | The request is malformed, or its input failed schema validation |
|
|
305
306
|
| `FORBIDDEN` | 403 | A guard returned `false`, or a mutation was called during server rendering |
|
|
306
307
|
| `RPC_NOT_FOUND` | 404 | No such procedure |
|
|
307
308
|
| `INTERNAL` | 500 | Anything else: an unexpected exception, an invalid error payload, a non-JSON result |
|
|
308
309
|
|
|
309
310
|
`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
|
|
|
312
|
+
`INVALID_INPUT` has `InvalidInputData`: `{ issues }`, with one `InputIssue` of `{ path, message }` per issue the input schema found, in the schema's order. `path` holds property names and array indexes into the input, such as `["lines", 1, "amount"]`. It's `[]` for the input as a whole, and for an issue whose schema path can't be sent as JSON, such as one with a symbol key. Only messages and paths reach the client, never the received input or other details of the schema library, so write your schema messages for users. A malformed request, such as a body that isn't JSON or an envelope with extra fields, has no issues. Server rendering and HTTP send the same issues. The other three codes have `null` data.
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
try {
|
|
316
|
+
await rpc.todos.add({ title });
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (rpc.todos.add.isError(error) && error.code === "INVALID_INPUT") {
|
|
319
|
+
for (const issue of error.data.issues) {
|
|
320
|
+
showError(issue.path, issue.message); // ["title"], "Title must contain 1–200 characters"
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
311
326
|
## Calling RPCs
|
|
312
327
|
|
|
313
328
|
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:
|
|
@@ -359,7 +374,6 @@ import { injectRpc } from "./rpc.generated";
|
|
|
359
374
|
export default defineRoute("todos", {
|
|
360
375
|
parent,
|
|
361
376
|
resolve: {
|
|
362
|
-
todos: () => injectRpc().todos.list(),
|
|
363
377
|
session: () => injectRpc().session.current(),
|
|
364
378
|
},
|
|
365
379
|
});
|
|
@@ -367,9 +381,13 @@ export default defineRoute("todos", {
|
|
|
367
381
|
|
|
368
382
|
`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
383
|
|
|
384
|
+
### With TanStack Query
|
|
385
|
+
|
|
386
|
+
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.4/packages/angular-launch/tanstack-query/README.md) for setup, keys, invalidation and hydration.
|
|
387
|
+
|
|
370
388
|
## Server rendering and hydration
|
|
371
389
|
|
|
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 }`.
|
|
390
|
+
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.4/packages/angular-launch/tanstack-query/README.md) opt out and are transferred by TanStack instead.
|
|
373
391
|
|
|
374
392
|
The reuse has limits, all of them Angular's transfer cache behaving as designed:
|
|
375
393
|
|
|
@@ -408,9 +426,9 @@ The server bundle includes your dependencies by default, so the host doesn't nee
|
|
|
408
426
|
|
|
409
427
|
The host check covers page rendering only. `handleRequest` runs before Angular and answers RPC requests for any host.
|
|
410
428
|
|
|
411
|
-
Launch calls `/_rpc/<
|
|
429
|
+
Launch calls `/_rpc/<namespace>/<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
430
|
|
|
413
|
-
Browser tabs opened before a deploy keep calling the procedures they were built with. After you
|
|
431
|
+
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.
|
|
414
432
|
|
|
415
433
|
Launch has been verified on Node only.
|
|
416
434
|
|
|
@@ -466,22 +484,23 @@ Export the handler as `reqHandler`; Angular's dev server and build don't look fo
|
|
|
466
484
|
generate(workspace: string, options: GenerationOptions, stopped?: () => boolean): Promise<void>;
|
|
467
485
|
```
|
|
468
486
|
|
|
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
|
-
| `
|
|
487
|
+
| Option | Type | Description |
|
|
488
|
+
| ----------------- | ---------- | ------------------------------------------------------------------------------- |
|
|
489
|
+
| `tsconfig` | `string` | Your app tsconfig, relative to `workspace` |
|
|
490
|
+
| `scanDirectories` | `string[]` | Exactly one route directory, relative to the tsconfig's directory |
|
|
491
|
+
| `outDirectory` | `string` | Where the app-wide generated files go, relative to `workspace` |
|
|
492
|
+
| `tanstackQuery` | `boolean` | Also generate `injectQueries()`; see [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md) |
|
|
493
|
+
| `check` | `boolean` | Verify generated files without writing them; fails if anything is out of date |
|
|
475
494
|
|
|
476
495
|
`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
496
|
|
|
478
497
|
Generation reads your source without running it. It writes the router's files plus:
|
|
479
498
|
|
|
480
|
-
| File | Contents
|
|
481
|
-
| --------------------------------------- |
|
|
482
|
-
| `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups
|
|
483
|
-
| `<outDirectory>/context.generated.d.ts` | Registers your context type
|
|
484
|
-
| `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry
|
|
499
|
+
| File | Contents |
|
|
500
|
+
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
501
|
+
| `rpc.generated.ts` beside each route | `injectRpc()` with the route's own and ancestor groups, plus `injectQueries()` with `tanstackQuery`; none for redirect routes |
|
|
502
|
+
| `<outDirectory>/context.generated.d.ts` | Registers your context type |
|
|
503
|
+
| `<outDirectory>/server.generated.ts` | `createContext`, `handleRequest`, `provideServer`, the registry |
|
|
485
504
|
|
|
486
505
|
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
506
|
|
|
@@ -491,7 +510,7 @@ Generated browser code contains only names, kinds and error metadata, never your
|
|
|
491
510
|
|
|
492
511
|
`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
512
|
|
|
494
|
-
|
|
513
|
+
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: it regenerates before every build, and `node generate.mjs --check` verifies them without writing.
|
|
495
514
|
|
|
496
515
|
`@loozo/angular-launch/generation` is Node-only.
|
|
497
516
|
|
|
@@ -523,7 +542,7 @@ The options are fixed when the session is created. Edits inside the app, includi
|
|
|
523
542
|
## Limitations
|
|
524
543
|
|
|
525
544
|
- No Angular builder or watch mode for Launch yet; run generation yourself before `ng build` or `ng serve`.
|
|
526
|
-
- No subscriptions, optimistic updates
|
|
545
|
+
- 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.4/packages/angular-launch/tanstack-query/README.md#limitations), which has its own limitations.
|
|
527
546
|
- No storage adapters; persistence is your handler's job.
|
|
528
547
|
- No production authentication, CSRF, CORS or caching policy. You provide those.
|
|
529
548
|
- Server work isn't cancelled when the client aborts, and nothing is rolled back.
|
|
@@ -531,9 +550,10 @@ The options are fixed when the session is created. Edits inside the app, includi
|
|
|
531
550
|
|
|
532
551
|
## Further reading
|
|
533
552
|
|
|
534
|
-
- [
|
|
535
|
-
- [`
|
|
536
|
-
- [
|
|
553
|
+
- [TanStack Query](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-launch/tanstack-query/README.md): the optional query and mutation integration
|
|
554
|
+
- [`specs/angular-launch.md`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/specs/angular-launch.md): design and full contract
|
|
555
|
+
- [`examples/angular-launch`](https://github.com/theo-matzavinos/loozo/tree/angular-launch@0.0.4/examples/angular-launch): the todos app. Its cookie identity and in-memory database are test fixtures, not security or deployment guidance.
|
|
556
|
+
- [`@loozo/angular-router`](https://github.com/theo-matzavinos/loozo/blob/angular-launch@0.0.4/packages/angular-router/README.md): routes, codecs and navigation
|
|
537
557
|
|
|
538
558
|
## Developing this package
|
|
539
559
|
|
package/client.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ErrorDefinitions, Group, OutputOf, Procedure, ProcedureKind, Schema } from "./server/definitions.js";
|
|
2
|
+
import { type InvalidInputData } from "./input-issues.js";
|
|
2
3
|
/** Per-call options for a generated query callable. */
|
|
3
4
|
export interface CallOptions {
|
|
4
5
|
/**
|
|
@@ -50,13 +51,15 @@ export interface ErrorMetadata {
|
|
|
50
51
|
* The four error codes Launch itself returns, with their HTTP status and public message.
|
|
51
52
|
*
|
|
52
53
|
* @remarks
|
|
53
|
-
* - `INVALID_INPUT` (400): the request or its input failed validation.
|
|
54
|
+
* - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
|
|
55
|
+
* {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
|
|
54
56
|
* - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
|
|
55
57
|
* server rendering.
|
|
56
58
|
* - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
|
|
57
59
|
* - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
|
|
58
60
|
*
|
|
59
|
-
* These codes are reserved: procedures can't declare
|
|
61
|
+
* The other codes have `null` data. These codes are reserved: procedures can't declare
|
|
62
|
+
* errors with them.
|
|
60
63
|
*/
|
|
61
64
|
export declare const frameworkFailures: {
|
|
62
65
|
readonly INVALID_INPUT: {
|
|
@@ -78,6 +81,7 @@ export declare const frameworkFailures: {
|
|
|
78
81
|
};
|
|
79
82
|
/** One of the error codes Launch itself returns: a key of {@link frameworkFailures}. */
|
|
80
83
|
export type FrameworkCode = keyof typeof frameworkFailures;
|
|
84
|
+
type FrameworkData<Code extends FrameworkCode> = Code extends "INVALID_INPUT" ? InvalidInputData : null;
|
|
81
85
|
/**
|
|
82
86
|
* An error response returned by a procedure: either a Launch framework failure or one
|
|
83
87
|
* of the procedure's declared errors.
|
|
@@ -90,15 +94,18 @@ export type FrameworkCode = keyof typeof frameworkFailures;
|
|
|
90
94
|
* returned by that exact procedure, not `RpcError` instances created elsewhere.
|
|
91
95
|
*
|
|
92
96
|
* @typeParam Code - The error code.
|
|
93
|
-
* @typeParam Data - The error's data:
|
|
94
|
-
* output for declared errors.
|
|
97
|
+
* @typeParam Data - The error's data: {@link InvalidInputData} for `INVALID_INPUT`,
|
|
98
|
+
* `null` for the other framework failures, the data schema's output for declared errors.
|
|
95
99
|
*/
|
|
96
|
-
export declare class RpcError<Code extends string = FrameworkCode, Data = null> extends Error {
|
|
100
|
+
export declare class RpcError<Code extends string = FrameworkCode, Data = Code extends FrameworkCode ? FrameworkData<Code> : null> extends Error {
|
|
97
101
|
/** The framework or declared error code. */
|
|
98
102
|
readonly code: Code;
|
|
99
103
|
/** The HTTP status of the response. */
|
|
100
104
|
readonly status: number;
|
|
101
|
-
/**
|
|
105
|
+
/**
|
|
106
|
+
* The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
|
|
107
|
+
* framework failures, validated data for declared errors.
|
|
108
|
+
*/
|
|
102
109
|
readonly data: Data;
|
|
103
110
|
/**
|
|
104
111
|
* Creates an error with the given code, status and data.
|
|
@@ -115,7 +122,10 @@ export declare class RpcError<Code extends string = FrameworkCode, Data = null>
|
|
|
115
122
|
code: Code,
|
|
116
123
|
/** The HTTP status of the response. */
|
|
117
124
|
status: number,
|
|
118
|
-
/**
|
|
125
|
+
/**
|
|
126
|
+
* The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
|
|
127
|
+
* framework failures, validated data for declared errors.
|
|
128
|
+
*/
|
|
119
129
|
data?: Data, message?: string);
|
|
120
130
|
}
|
|
121
131
|
/**
|
|
@@ -124,14 +134,21 @@ export declare class RpcError<Code extends string = FrameworkCode, Data = null>
|
|
|
124
134
|
* @remarks
|
|
125
135
|
* Internal; not exported from a public entry point. Used by the generated client to
|
|
126
136
|
* convert responses into {@link RpcError}s. The body must be strict JSON shaped
|
|
127
|
-
* exactly as `{ error: { code, message, data
|
|
128
|
-
* status and message.
|
|
137
|
+
* exactly as `{ error: { code, message, data } }`, with the framework code's own
|
|
138
|
+
* status and message. `data` must be exactly {@link InvalidInputData} for
|
|
139
|
+
* `INVALID_INPUT` and `null` for the other codes.
|
|
129
140
|
*
|
|
130
141
|
* @param value - The parsed response body.
|
|
131
142
|
* @param status - The response's HTTP status.
|
|
132
|
-
* @returns The framework code, or `undefined` when the body doesn't match
|
|
143
|
+
* @returns The framework code and data, or `undefined` when the body doesn't match
|
|
144
|
+
* exactly.
|
|
133
145
|
*/
|
|
134
|
-
export declare function recognizedFailure(value: unknown, status: number):
|
|
146
|
+
export declare function recognizedFailure(value: unknown, status: number): {
|
|
147
|
+
/** The framework code. */
|
|
148
|
+
code: FrameworkCode;
|
|
149
|
+
/** The failure's data. */
|
|
150
|
+
data: InvalidInputData | null;
|
|
151
|
+
} | undefined;
|
|
135
152
|
/**
|
|
136
153
|
* Recognizes a response body that is exactly a framework failure or one of the given
|
|
137
154
|
* declared errors.
|
|
@@ -153,11 +170,11 @@ export declare function recognizedError(value: unknown, status: number, declared
|
|
|
153
170
|
code: string;
|
|
154
171
|
/** The error's message. */
|
|
155
172
|
message: string;
|
|
156
|
-
/** The
|
|
173
|
+
/** The error's data as received. */
|
|
157
174
|
data: unknown;
|
|
158
175
|
} | undefined;
|
|
159
176
|
type FrameworkError = {
|
|
160
|
-
[Code in FrameworkCode]: RpcError<Code,
|
|
177
|
+
[Code in FrameworkCode]: RpcError<Code, FrameworkData<Code>>;
|
|
161
178
|
}[FrameworkCode];
|
|
162
179
|
type DeclaredError<Errors extends ErrorDefinitions> = {
|
|
163
180
|
[Code in keyof Errors & string]: RpcError<Code, OutputOf<Errors[Code]["data"]>>;
|
|
@@ -166,8 +183,9 @@ type DeclaredError<Errors extends ErrorDefinitions> = {
|
|
|
166
183
|
* The errors a generated callable for a procedure can reject with as {@link RpcError}s.
|
|
167
184
|
*
|
|
168
185
|
* @remarks
|
|
169
|
-
* A union discriminated by `code`: one member per framework failure with
|
|
170
|
-
*
|
|
186
|
+
* A union discriminated by `code`: one member per framework failure, with
|
|
187
|
+
* {@link InvalidInputData} for `INVALID_INPUT` and `null` data for the others, and one
|
|
188
|
+
* per declared error with its data schema's output type. Import the group
|
|
171
189
|
* with `import type` so server code stays out of the browser bundle.
|
|
172
190
|
*
|
|
173
191
|
* @example
|
package/client.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { serializeJson } from "./json.js";
|
|
2
|
+
import { isInvalidInputData } from "./input-issues.js";
|
|
2
3
|
/**
|
|
3
4
|
* The four error codes Launch itself returns, with their HTTP status and public message.
|
|
4
5
|
*
|
|
5
6
|
* @remarks
|
|
6
|
-
* - `INVALID_INPUT` (400): the request or its input failed validation.
|
|
7
|
+
* - `INVALID_INPUT` (400): the request or its input failed validation. Its data is
|
|
8
|
+
* {@link InvalidInputData}: the input schema's issues, or none for a malformed request.
|
|
7
9
|
* - `FORBIDDEN` (403): a guard returned `false`, or a mutation was called during
|
|
8
10
|
* server rendering.
|
|
9
11
|
* - `RPC_NOT_FOUND` (404): no procedure exists at the requested path.
|
|
10
12
|
* - `INTERNAL` (500): anything else. Details go to the server log, never to the client.
|
|
11
13
|
*
|
|
12
|
-
* These codes are reserved: procedures can't declare
|
|
14
|
+
* The other codes have `null` data. These codes are reserved: procedures can't declare
|
|
15
|
+
* errors with them.
|
|
13
16
|
*/
|
|
14
17
|
export const frameworkFailures = {
|
|
15
18
|
INVALID_INPUT: { status: 400, message: "Invalid RPC input" },
|
|
@@ -29,8 +32,8 @@ export const frameworkFailures = {
|
|
|
29
32
|
* returned by that exact procedure, not `RpcError` instances created elsewhere.
|
|
30
33
|
*
|
|
31
34
|
* @typeParam Code - The error code.
|
|
32
|
-
* @typeParam Data - The error's data:
|
|
33
|
-
* output for declared errors.
|
|
35
|
+
* @typeParam Data - The error's data: {@link InvalidInputData} for `INVALID_INPUT`,
|
|
36
|
+
* `null` for the other framework failures, the data schema's output for declared errors.
|
|
34
37
|
*/
|
|
35
38
|
export class RpcError extends Error {
|
|
36
39
|
code;
|
|
@@ -51,7 +54,10 @@ export class RpcError extends Error {
|
|
|
51
54
|
code,
|
|
52
55
|
/** The HTTP status of the response. */
|
|
53
56
|
status,
|
|
54
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* The error's data: {@link InvalidInputData} for `INVALID_INPUT`, `null` for the other
|
|
59
|
+
* framework failures, validated data for declared errors.
|
|
60
|
+
*/
|
|
55
61
|
data = null, message) {
|
|
56
62
|
if (message === undefined) {
|
|
57
63
|
if (!Object.hasOwn(frameworkFailures, code)) {
|
|
@@ -72,12 +78,14 @@ export class RpcError extends Error {
|
|
|
72
78
|
* @remarks
|
|
73
79
|
* Internal; not exported from a public entry point. Used by the generated client to
|
|
74
80
|
* convert responses into {@link RpcError}s. The body must be strict JSON shaped
|
|
75
|
-
* exactly as `{ error: { code, message, data
|
|
76
|
-
* status and message.
|
|
81
|
+
* exactly as `{ error: { code, message, data } }`, with the framework code's own
|
|
82
|
+
* status and message. `data` must be exactly {@link InvalidInputData} for
|
|
83
|
+
* `INVALID_INPUT` and `null` for the other codes.
|
|
77
84
|
*
|
|
78
85
|
* @param value - The parsed response body.
|
|
79
86
|
* @param status - The response's HTTP status.
|
|
80
|
-
* @returns The framework code, or `undefined` when the body doesn't match
|
|
87
|
+
* @returns The framework code and data, or `undefined` when the body doesn't match
|
|
88
|
+
* exactly.
|
|
81
89
|
*/
|
|
82
90
|
export function recognizedFailure(value, status) {
|
|
83
91
|
try {
|
|
@@ -104,11 +112,16 @@ export function recognizedFailure(value, status) {
|
|
|
104
112
|
}
|
|
105
113
|
for (const code of Object.keys(frameworkFailures)) {
|
|
106
114
|
const expected = frameworkFailures[code];
|
|
107
|
-
if (error.code
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
115
|
+
if (error.code !== code || status !== expected.status || error.message !== expected.message) {
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (code === "INVALID_INPUT") {
|
|
119
|
+
if (isInvalidInputData(error.data)) {
|
|
120
|
+
return { code, data: error.data };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
else if (error.data === null) {
|
|
124
|
+
return { code, data: null };
|
|
112
125
|
}
|
|
113
126
|
}
|
|
114
127
|
return undefined;
|
|
@@ -132,7 +145,11 @@ export function recognizedFailure(value, status) {
|
|
|
132
145
|
export function recognizedError(value, status, declared) {
|
|
133
146
|
const framework = recognizedFailure(value, status);
|
|
134
147
|
if (framework) {
|
|
135
|
-
return {
|
|
148
|
+
return {
|
|
149
|
+
code: framework.code,
|
|
150
|
+
message: frameworkFailures[framework.code].message,
|
|
151
|
+
data: framework.data,
|
|
152
|
+
};
|
|
136
153
|
}
|
|
137
154
|
try {
|
|
138
155
|
serializeJson(value);
|
package/generated.d.ts
CHANGED
package/generated.js
CHANGED
|
@@ -68,10 +68,10 @@ export function injectClient(groups) {
|
|
|
68
68
|
for (const method of group.methods) {
|
|
69
69
|
let invoke;
|
|
70
70
|
if (method.input) {
|
|
71
|
-
invoke = (input, options) => call(http,
|
|
71
|
+
invoke = (input, options) => call(http, namespace, method, input, options);
|
|
72
72
|
}
|
|
73
73
|
else {
|
|
74
|
-
invoke = (options) => call(http,
|
|
74
|
+
invoke = (options) => call(http, namespace, method, null, options);
|
|
75
75
|
}
|
|
76
76
|
methods[method.name] = Object.assign(invoke, {
|
|
77
77
|
kind: method.kind,
|
|
@@ -80,7 +80,7 @@ export function injectClient(groups) {
|
|
|
80
80
|
return false;
|
|
81
81
|
}
|
|
82
82
|
const owner = errorOwners.get(error);
|
|
83
|
-
return owner?.group ===
|
|
83
|
+
return owner?.group === namespace && owner.method === method.name;
|
|
84
84
|
},
|
|
85
85
|
});
|
|
86
86
|
}
|
package/generation/index.d.ts
CHANGED
|
@@ -6,6 +6,13 @@ export interface GenerationOptions {
|
|
|
6
6
|
scanDirectories: string[];
|
|
7
7
|
/** Where the application-wide generated files go, relative to the workspace. */
|
|
8
8
|
outDirectory: string;
|
|
9
|
+
/**
|
|
10
|
+
* Also writes `injectQueries()` and `type Queries` into each `rpc.generated.ts`: TanStack
|
|
11
|
+
* Query options and keys for the same groups as `injectRpc()`. Requires
|
|
12
|
+
* `@tanstack/angular-query` in the application and `provideLaunchQueries()` from
|
|
13
|
+
* `@loozo/angular-launch/tanstack-query` in its providers. Defaults to `false`.
|
|
14
|
+
*/
|
|
15
|
+
tanstackQuery?: boolean;
|
|
9
16
|
/**
|
|
10
17
|
* Verifies the generated files without writing them, failing when any is changed,
|
|
11
18
|
* missing or stale. Defaults to `false`.
|
|
@@ -113,4 +120,4 @@ export declare function generate(workspace: string, options: GenerationOptions,
|
|
|
113
120
|
* passed per call instead.
|
|
114
121
|
* @returns The session. Dispose it when done.
|
|
115
122
|
*/
|
|
116
|
-
export declare function createGenerationSession(workspace: string, { tsconfig, scanDirectories, outDirectory }: Omit<GenerationOptions, "check">): GenerationSession;
|
|
123
|
+
export declare function createGenerationSession(workspace: string, { tsconfig, scanDirectories, outDirectory, tanstackQuery }: Omit<GenerationOptions, "check">): GenerationSession;
|
package/generation/index.js
CHANGED
|
@@ -79,6 +79,7 @@ async function groupsOf(sources) {
|
|
|
79
79
|
}
|
|
80
80
|
const groups = [];
|
|
81
81
|
const owners = new Set();
|
|
82
|
+
const namespaces = new Map();
|
|
82
83
|
for (const declaration of launch.declarations) {
|
|
83
84
|
if (declaration.kind !== "defineRpc") {
|
|
84
85
|
continue;
|
|
@@ -104,6 +105,11 @@ async function groupsOf(sources) {
|
|
|
104
105
|
if (namespace.text === "__proto__") {
|
|
105
106
|
fail(namespace, "RPC namespace '__proto__' is reserved");
|
|
106
107
|
}
|
|
108
|
+
const previous = namespaces.get(namespace.text);
|
|
109
|
+
if (previous) {
|
|
110
|
+
fail(namespace, `Duplicate RPC namespace: ${namespace.text}; also defined in ${previous.file}`);
|
|
111
|
+
}
|
|
112
|
+
namespaces.set(namespace.text, declaration);
|
|
107
113
|
if (options) {
|
|
108
114
|
const fields = properties(options, "RPC group options");
|
|
109
115
|
onlyKeys(fields, ["canActivate"], options);
|
|
@@ -145,13 +151,11 @@ async function groupsOf(sources) {
|
|
|
145
151
|
call: procedure,
|
|
146
152
|
});
|
|
147
153
|
}
|
|
148
|
-
|
|
149
|
-
const id = createHash("sha256").update(`launch-v1\0${identity}`).digest("hex").slice(0, 24);
|
|
150
|
-
groups.push({ declaration, owner, namespace: namespace.text, id, methods });
|
|
154
|
+
groups.push({ declaration, owner, namespace: namespace.text, methods });
|
|
151
155
|
}
|
|
152
156
|
return { context, groups };
|
|
153
157
|
}
|
|
154
|
-
function emitLaunch(sources, desired, context, groups, appId) {
|
|
158
|
+
function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
|
|
155
159
|
const payloads = [];
|
|
156
160
|
function payloadImport(from, target, local, typeOnly = false) {
|
|
157
161
|
payloads.push({ from, target, local });
|
|
@@ -172,7 +176,7 @@ function emitLaunch(sources, desired, context, groups, appId) {
|
|
|
172
176
|
for (let index = 0; index < groups.length; index += 1) {
|
|
173
177
|
server.push(payloadImport(registry, groups[index].declaration.file, `group${index}`));
|
|
174
178
|
}
|
|
175
|
-
server.push(`export const registry = { ${groups.map((group, index) => `${JSON.stringify(group.
|
|
179
|
+
server.push(`export const registry = { ${groups.map((group, index) => `${JSON.stringify(group.namespace)}: group${index}`).join(", ")} };`, `export const appBinding = { id: ${JSON.stringify(appId)}, context };`, `export const createContext = (request: Request) => createRequestScope(appBinding, request);`, `export const handleRequest = (request: Request) => handleRpc(registry, appBinding, request);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
|
|
176
180
|
add(desired, registry, server.join("\n"));
|
|
177
181
|
const byOwner = new Map(groups.map((group) => [group.owner, group]));
|
|
178
182
|
for (const owner of sources.declarations) {
|
|
@@ -180,15 +184,10 @@ function emitLaunch(sources, desired, context, groups, appId) {
|
|
|
180
184
|
continue;
|
|
181
185
|
}
|
|
182
186
|
const available = [];
|
|
183
|
-
const namespaces = new Set();
|
|
184
187
|
let current = owner;
|
|
185
188
|
while (current) {
|
|
186
189
|
const group = byOwner.get(current);
|
|
187
190
|
if (group) {
|
|
188
|
-
if (namespaces.has(group.namespace)) {
|
|
189
|
-
fail(group.declaration.call, `Duplicate RPC namespace in ancestry: ${group.namespace}`);
|
|
190
|
-
}
|
|
191
|
-
namespaces.add(group.namespace);
|
|
192
191
|
available.unshift(group);
|
|
193
192
|
}
|
|
194
193
|
current = current.parent;
|
|
@@ -199,12 +198,15 @@ function emitLaunch(sources, desired, context, groups, appId) {
|
|
|
199
198
|
`import { injectClient } from '@loozo/angular-launch/_generated';`,
|
|
200
199
|
`import type { Client } from '@loozo/angular-launch';`,
|
|
201
200
|
];
|
|
201
|
+
if (tanstackQuery) {
|
|
202
|
+
lines.push(`import { createQueries } from '@loozo/angular-launch/_tanstack-query';`, `import type { RpcQueries } from '@loozo/angular-launch/tanstack-query';`);
|
|
203
|
+
}
|
|
202
204
|
const metadata = Object.create(null);
|
|
205
|
+
const queriesMetadata = Object.create(null);
|
|
203
206
|
for (let index = 0; index < available.length; index += 1) {
|
|
204
207
|
const group = available[index];
|
|
205
208
|
lines.push(payloadImport(file, group.declaration.file, `group${index}`, true));
|
|
206
209
|
metadata[group.namespace] = {
|
|
207
|
-
id: group.id,
|
|
208
210
|
methods: group.methods.map(({ name, input, kind, errors }) => ({
|
|
209
211
|
name,
|
|
210
212
|
input,
|
|
@@ -212,8 +214,16 @@ function emitLaunch(sources, desired, context, groups, appId) {
|
|
|
212
214
|
errors,
|
|
213
215
|
})),
|
|
214
216
|
};
|
|
217
|
+
queriesMetadata[group.namespace] = Object.create(null);
|
|
218
|
+
for (const { name, kind, input } of group.methods) {
|
|
219
|
+
queriesMetadata[group.namespace][name] = { kind, input };
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
lines.push(`export type Rpc = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: Client<typeof group${index}>`).join("; ")} };`, `export function injectRpc(): Rpc { return injectClient(${JSON.stringify(metadata)} as const) as Rpc; }`);
|
|
223
|
+
if (tanstackQuery) {
|
|
224
|
+
lines.push(`export type Queries = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: RpcQueries<typeof group${index}>`).join("; ")} };`, `export function injectQueries(): Queries { return createQueries(injectRpc(), ${JSON.stringify(queriesMetadata)} as const) as Queries; }`);
|
|
215
225
|
}
|
|
216
|
-
lines.push(
|
|
226
|
+
lines.push("");
|
|
217
227
|
add(desired, file, lines.join("\n"));
|
|
218
228
|
}
|
|
219
229
|
return payloads;
|
|
@@ -481,7 +491,7 @@ async function runGeneration(workspace, options, stopped, compiler) {
|
|
|
481
491
|
.update("\0")
|
|
482
492
|
.update(context.call.getSourceFile().text)
|
|
483
493
|
.digest("hex");
|
|
484
|
-
const payloads = emitLaunch(sources, desired, context, groups, appId);
|
|
494
|
+
const payloads = emitLaunch(sources, desired, context, groups, appId, options.tanstackQuery === true);
|
|
485
495
|
await auditPath(sources.output);
|
|
486
496
|
const outputInventory = await walk(sources.output);
|
|
487
497
|
const globals = [
|
|
@@ -572,9 +582,9 @@ export function generate(workspace, options, stopped = () => false) {
|
|
|
572
582
|
* passed per call instead.
|
|
573
583
|
* @returns The session. Dispose it when done.
|
|
574
584
|
*/
|
|
575
|
-
export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory }) {
|
|
585
|
+
export function createGenerationSession(workspace, { tsconfig, scanDirectories, outDirectory, tanstackQuery }) {
|
|
576
586
|
const application = resolve(workspace);
|
|
577
|
-
const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory };
|
|
587
|
+
const fixed = { tsconfig, scanDirectories: [...scanDirectories], outDirectory, tanstackQuery };
|
|
578
588
|
const compiler = {
|
|
579
589
|
discovery: new CompilerState(),
|
|
580
590
|
overlay: new CompilerState(),
|
package/index.d.ts
CHANGED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One problem an input schema found, as sent to the client in `INVALID_INPUT` data.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Only the schema issue's message and path are sent, never vendor details, input
|
|
6
|
+
* values or stacks, so write schema messages for users.
|
|
7
|
+
*/
|
|
8
|
+
export interface InputIssue {
|
|
9
|
+
/**
|
|
10
|
+
* Where the problem is, as property names and array indexes from the procedure's
|
|
11
|
+
* input. Empty for the input as a whole, or when the schema's path can't be
|
|
12
|
+
* represented in JSON, such as a symbol key.
|
|
13
|
+
*/
|
|
14
|
+
readonly path: readonly (string | number)[];
|
|
15
|
+
/** The schema's description of the problem. */
|
|
16
|
+
readonly message: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The data of an `INVALID_INPUT` error.
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* A request that isn't a valid RPC envelope, such as a body that isn't JSON, has no
|
|
23
|
+
* issues.
|
|
24
|
+
*/
|
|
25
|
+
export interface InvalidInputData {
|
|
26
|
+
/** The problems the input schema found, in the schema's order. */
|
|
27
|
+
readonly issues: readonly InputIssue[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Converts Standard Schema issues to the issues sent to the client.
|
|
31
|
+
*
|
|
32
|
+
* @remarks
|
|
33
|
+
* Internal; not exported from a public entry point. A path segment may be a property
|
|
34
|
+
* key or a `{ key }` object. An issue with a segment that isn't a string or a finite
|
|
35
|
+
* number gets the root path `[]`; it isn't stringified.
|
|
36
|
+
*
|
|
37
|
+
* @param issues - The issues a schema returned.
|
|
38
|
+
* @returns Each issue's message and normalized path, in the same order.
|
|
39
|
+
*/
|
|
40
|
+
export declare function inputIssues(issues: readonly {
|
|
41
|
+
readonly message: string;
|
|
42
|
+
readonly path?: readonly (PropertyKey | {
|
|
43
|
+
readonly key: PropertyKey;
|
|
44
|
+
})[] | undefined;
|
|
45
|
+
}[]): InputIssue[];
|
|
46
|
+
/**
|
|
47
|
+
* Checks whether a strict JSON value is exactly {@link InvalidInputData}.
|
|
48
|
+
*
|
|
49
|
+
* @remarks
|
|
50
|
+
* Internal; not exported from a public entry point. Used by the client to recognize
|
|
51
|
+
* `INVALID_INPUT` responses. Extra properties make the value unrecognized.
|
|
52
|
+
*
|
|
53
|
+
* @param value - Received error data, already checked to be strict JSON.
|
|
54
|
+
* @returns `true` when `value` is `{ issues }` with only `{ path, message }` issues.
|
|
55
|
+
*/
|
|
56
|
+
export declare function isInvalidInputData(value: unknown): value is InvalidInputData;
|