@loozo/angular-launch 0.0.5 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +1068 -187
  2. package/builders/application.js +32 -3
  3. package/builders/channel-forwarding.d.ts +15 -0
  4. package/builders/channel-forwarding.js +61 -0
  5. package/builders/options.d.ts +6 -2
  6. package/builders/options.js +16 -5
  7. package/builders/serve.js +198 -140
  8. package/channel.d.ts +55 -0
  9. package/channel.js +232 -0
  10. package/client.d.ts +63 -33
  11. package/connect.d.ts +201 -0
  12. package/connect.js +148 -0
  13. package/generation/index.d.ts +2 -123
  14. package/generation/index.js +3 -669
  15. package/generation/redirects.d.ts +14 -0
  16. package/generation/redirects.js +43 -0
  17. package/generation/run.d.ts +168 -0
  18. package/generation/run.js +659 -0
  19. package/index.d.ts +8 -1
  20. package/index.js +3 -0
  21. package/json.d.ts +9 -0
  22. package/json.js +24 -0
  23. package/launch-queries.d.ts +16 -0
  24. package/launch-queries.js +3 -0
  25. package/navigation.d.ts +36 -0
  26. package/navigation.js +47 -0
  27. package/node/index.d.ts +60 -0
  28. package/node/index.js +178 -0
  29. package/node/upgrade-listener-slot.d.ts +1 -0
  30. package/node/upgrade-listener-slot.js +4 -0
  31. package/outcomes.d.ts +71 -0
  32. package/outcomes.js +146 -0
  33. package/package.json +21 -11
  34. package/redirect-translation.d.ts +53 -0
  35. package/redirect-translation.js +141 -0
  36. package/{generated.d.ts → remote-client.d.ts} +1 -1
  37. package/remote-client.js +179 -0
  38. package/route-types.d.ts +130 -0
  39. package/route-types.js +1 -0
  40. package/route.d.ts +45 -0
  41. package/route.js +113 -0
  42. package/schemas/application.json +19 -3
  43. package/schemas/serve.json +3 -3
  44. package/server/application.d.ts +107 -0
  45. package/server/application.js +108 -0
  46. package/server/backend.d.ts +62 -31
  47. package/server/backend.js +149 -55
  48. package/server/channel-messages.d.ts +54 -0
  49. package/server/channel-messages.js +84 -0
  50. package/server/channel-socket.d.ts +67 -0
  51. package/server/channel-socket.js +322 -0
  52. package/server/definitions.d.ts +270 -294
  53. package/server/definitions.js +35 -115
  54. package/server/dispatch.d.ts +121 -66
  55. package/server/dispatch.js +267 -87
  56. package/server/event-stream.d.ts +63 -0
  57. package/server/event-stream.js +173 -0
  58. package/server/generated.d.ts +3 -1
  59. package/server/generated.js +3 -1
  60. package/server/index.d.ts +6 -3
  61. package/server/index.js +3 -2
  62. package/server/outcomes.d.ts +64 -2
  63. package/server/outcomes.js +85 -4
  64. package/server/read-cookies.d.ts +19 -0
  65. package/server/read-cookies.js +39 -0
  66. package/server/response-effects.d.ts +105 -0
  67. package/server/response-effects.js +78 -0
  68. package/server/stages.d.ts +62 -0
  69. package/server/stages.js +51 -0
  70. package/server/upgrade.d.ts +57 -0
  71. package/server/upgrade.js +116 -0
  72. package/source-text.d.ts +1 -0
  73. package/source-text.js +56 -0
  74. package/stream.d.ts +34 -0
  75. package/stream.js +161 -0
  76. package/tanstack-query/README.md +113 -21
  77. package/tanstack-query/create-queries.d.ts +2 -0
  78. package/tanstack-query/{generated.js → create-queries.js} +13 -11
  79. package/tanstack-query/hydration-window.d.ts +11 -0
  80. package/tanstack-query/hydration-window.js +9 -0
  81. package/tanstack-query/hydration.d.ts +4 -14
  82. package/tanstack-query/hydration.js +9 -12
  83. package/tanstack-query/index.d.ts +1 -1
  84. package/tanstack-query/queries.d.ts +50 -33
  85. package/testing/call-procedure.d.ts +154 -0
  86. package/testing/call-procedure.js +97 -0
  87. package/testing/index.d.ts +2 -0
  88. package/testing/index.js +1 -0
  89. package/generated.js +0 -90
  90. package/generation/context-file.d.ts +0 -2
  91. package/generation/context-file.js +0 -3
  92. package/tanstack-query/generated.d.ts +0 -5
package/json.d.ts CHANGED
@@ -11,3 +11,12 @@ export type JsonShape<Value> = Value extends null | boolean | number | string ?
11
11
  readonly [Key in keyof Value]-?: Key extends string | number ? JsonShape<Value[Key]> : never;
12
12
  } : never;
13
13
  export declare function serializeJson(value: unknown): string;
14
+ /**
15
+ * Parses JSON text that must hold strict JSON: what `JSON.parse` accepts, without the
16
+ * nonfinite numbers it makes of overflowing literals such as `1e400`.
17
+ *
18
+ * @param text - The JSON text.
19
+ * @returns The parsed value.
20
+ * @throws SyntaxError when `text` isn't JSON, and TypeError when it holds a nonfinite number.
21
+ */
22
+ export declare function parseJson(text: string): unknown;
package/json.js CHANGED
@@ -46,3 +46,27 @@ export function serializeJson(value) {
46
46
  visit(value);
47
47
  return JSON.stringify(value);
48
48
  }
49
+ /**
50
+ * Parses JSON text that must hold strict JSON: what `JSON.parse` accepts, without the
51
+ * nonfinite numbers it makes of overflowing literals such as `1e400`.
52
+ *
53
+ * @param text - The JSON text.
54
+ * @returns The parsed value.
55
+ * @throws SyntaxError when `text` isn't JSON, and TypeError when it holds a nonfinite number.
56
+ */
57
+ export function parseJson(text) {
58
+ const value = JSON.parse(text);
59
+ const pending = [value];
60
+ while (pending.length > 0) {
61
+ const current = pending.pop();
62
+ if (typeof current === "number" && !Number.isFinite(current)) {
63
+ throw new TypeError("RPC values must be strict JSON");
64
+ }
65
+ if (typeof current === "object" && current !== null) {
66
+ for (const item of Object.values(current)) {
67
+ pending.push(item);
68
+ }
69
+ }
70
+ }
71
+ return value;
72
+ }
@@ -0,0 +1,16 @@
1
+ import { InjectionToken } from "@angular/core";
2
+ /**
3
+ * Builds a route's TanStack factories over its client.
4
+ *
5
+ * @remarks
6
+ * Internal. `provideLaunchQueries()` provides it, so the root entry builds `route.queries`
7
+ * without importing `@tanstack/*` itself.
8
+ */
9
+ export type CreateQueries = (remote: Readonly<Record<string, Readonly<Record<string, unknown>>>>, namespaces: Readonly<Record<string, Readonly<Record<string, QueriesMethod>>>>) => unknown;
10
+ /** What a route's TanStack factories need to know about one query or mutation. */
11
+ export interface QueriesMethod {
12
+ readonly kind: "query" | "mutation";
13
+ readonly input: boolean;
14
+ }
15
+ /** Internal: provided by `provideLaunchQueries()`, read by `route.queries`. */
16
+ export declare const launchQueries: InjectionToken<CreateQueries>;
@@ -0,0 +1,3 @@
1
+ import { InjectionToken } from "@angular/core";
2
+ /** Internal: provided by `provideLaunchQueries()`, read by `route.queries`. */
3
+ export const launchQueries = new InjectionToken("Launch route queries");
@@ -0,0 +1,36 @@
1
+ import { RedirectCommand, type NavigationError } from "@angular/router";
2
+ /** Options for {@link rpcNavigationErrors}. */
3
+ export interface RpcNavigationErrorsOptions {
4
+ /**
5
+ * The root-relative URL of the app's not-found page, such as `createUrl(notFound, {})`
6
+ * with the not-found route's generated `destination`. It's rendered at the requested URL.
7
+ */
8
+ readonly notFound: `/${string}`;
9
+ }
10
+ /**
11
+ * Creates a navigation error handler that follows RPC redirects and renders not-found
12
+ * outcomes.
13
+ *
14
+ * @remarks
15
+ * Pass it to Angular's `withNavigationErrorHandler`. When a guard or resolver fails with
16
+ * an {@link RpcRedirect}, the navigation goes to its `to` instead; during server
17
+ * rendering Angular then answers the page request with a 302. When it fails with an
18
+ * {@link RpcNotFound}, the navigation renders `notFound` while the address bar keeps the
19
+ * requested URL; during server rendering the page is answered with status 404. Any other
20
+ * error is left to Angular, which fails the navigation as usual.
21
+ *
22
+ * Angular takes one navigation error handler. An app with its own calls this one from it,
23
+ * within the handler's injection context, and returns its result.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * provideRouter(
28
+ * routes,
29
+ * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
30
+ * );
31
+ * ```
32
+ *
33
+ * @param options - The not-found page's URL.
34
+ * @returns The handler, which must run in an injection context.
35
+ */
36
+ export declare function rpcNavigationErrors({ notFound, }: RpcNavigationErrorsOptions): (error: NavigationError) => RedirectCommand | undefined;
package/navigation.js ADDED
@@ -0,0 +1,47 @@
1
+ import { inject, RESPONSE_INIT } from "@angular/core";
2
+ import { RedirectCommand, Router } from "@angular/router";
3
+ import { RpcNotFound, RpcRedirect } from "./outcomes.js";
4
+ /**
5
+ * Creates a navigation error handler that follows RPC redirects and renders not-found
6
+ * outcomes.
7
+ *
8
+ * @remarks
9
+ * Pass it to Angular's `withNavigationErrorHandler`. When a guard or resolver fails with
10
+ * an {@link RpcRedirect}, the navigation goes to its `to` instead; during server
11
+ * rendering Angular then answers the page request with a 302. When it fails with an
12
+ * {@link RpcNotFound}, the navigation renders `notFound` while the address bar keeps the
13
+ * requested URL; during server rendering the page is answered with status 404. Any other
14
+ * error is left to Angular, which fails the navigation as usual.
15
+ *
16
+ * Angular takes one navigation error handler. An app with its own calls this one from it,
17
+ * within the handler's injection context, and returns its result.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * provideRouter(
22
+ * routes,
23
+ * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
24
+ * );
25
+ * ```
26
+ *
27
+ * @param options - The not-found page's URL.
28
+ * @returns The handler, which must run in an injection context.
29
+ */
30
+ export function rpcNavigationErrors({ notFound, }) {
31
+ return (error) => {
32
+ const router = inject(Router);
33
+ const cause = error.error;
34
+ if (cause instanceof RpcRedirect) {
35
+ return new RedirectCommand(router.parseUrl(cause.to));
36
+ }
37
+ if (!(cause instanceof RpcNotFound)) {
38
+ return undefined;
39
+ }
40
+ // Angular builds the page response from this object once the app is stable.
41
+ const response = inject(RESPONSE_INIT, { optional: true });
42
+ if (response !== null) {
43
+ response.status = 404;
44
+ }
45
+ return new RedirectCommand(router.parseUrl(notFound), { browserUrl: error.url });
46
+ };
47
+ }
@@ -0,0 +1,60 @@
1
+ /// <reference types="node" preserve="true" />
2
+ import { type IncomingMessage } from "node:http";
3
+ import type { Duplex } from "node:stream";
4
+ import type { Upgrade } from "../server/upgrade.js";
5
+ /** Options for {@link createUpgradeHandler}. */
6
+ export interface UpgradeHandlerOptions {
7
+ /**
8
+ * The largest message a caller may send, in bytes. A bigger frame closes the socket with
9
+ * 1009, which the browser client reports as a `TypeError`. Defaults to 1 MiB.
10
+ */
11
+ readonly maxPayload?: number;
12
+ }
13
+ /**
14
+ * A Node `upgrade` listener, for `server.on("upgrade", listener)`.
15
+ *
16
+ * @param request - The upgrade request.
17
+ * @param socket - The request's socket.
18
+ * @param head - The first bytes of the upgraded stream, if any arrived with the request.
19
+ */
20
+ export type UpgradeListener = (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
21
+ /**
22
+ * Creates the Node `upgrade` listener that runs the app's channels.
23
+ *
24
+ * @remarks
25
+ * Create it once, at your server module's top level, and attach it to the HTTP server that
26
+ * serves the app with `server.on("upgrade", listener)`; with Express, to the server
27
+ * `app.listen()` returns.
28
+ *
29
+ * For each upgrade request it builds a web `Request` (the protocol from the socket, the host
30
+ * from `Host`; proxy headers aren't trusted) whose signal aborts when the client leaves before
31
+ * the socket is accepted, and passes it to `handle`. A `null` result leaves the socket to the
32
+ * server's other `upgrade` listeners, such as a dev server's. A `Response` is written to the
33
+ * socket, which then closes. An `Upgrade` is accepted with `ws`, with its headers on the `101`,
34
+ * unless the client already left. Accepted sockets are pinged every 15 s and terminated when
35
+ * they miss the answer.
36
+ *
37
+ * Under `ng serve`, Launch's serve builder forwards `/_rpc/` upgrades to the latest listener
38
+ * created, so attaching it where your built server listens is all the wiring there is.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * import { createServer } from "node:http";
43
+ * import { createUpgradeHandler } from "@loozo/angular-launch/node";
44
+ * import { handleUpgrade } from "../generated/server.generated";
45
+ *
46
+ * const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
47
+ *
48
+ * if (isMainModule(import.meta.url)) {
49
+ * const server = createServer(reqHandler).listen(port);
50
+ *
51
+ * server.on("upgrade", upgrade);
52
+ * }
53
+ * ```
54
+ *
55
+ * @param handle - Answers one upgrade request: the generated `handleUpgrade`, with your
56
+ * options.
57
+ * @param options - The largest message a caller may send.
58
+ * @returns The listener.
59
+ */
60
+ export declare function createUpgradeHandler(handle: (request: Request) => Promise<Response | Upgrade | null>, { maxPayload }?: UpgradeHandlerOptions): UpgradeListener;
package/node/index.js ADDED
@@ -0,0 +1,178 @@
1
+ /// <reference types="node" preserve="true" />
2
+ import { STATUS_CODES } from "node:http";
3
+ import { WebSocketServer } from "ws";
4
+ import { upgradeListenerSlot } from "./upgrade-listener-slot.js";
5
+ const pingMs = 15_000;
6
+ // The upgrade request as a web Request. Like Angular's createWebRequestFromNodeRequest by
7
+ // default, it trusts no proxy headers: the protocol comes from the socket, the host from Host.
8
+ function webRequest(incoming, signal) {
9
+ const headers = new Headers();
10
+ for (const [name, value] of Object.entries(incoming.headers)) {
11
+ // HTTP/2 pseudo-headers aren't headers.
12
+ if (name.startsWith(":")) {
13
+ continue;
14
+ }
15
+ if (typeof value === "string") {
16
+ headers.append(name, value);
17
+ }
18
+ else if (Array.isArray(value)) {
19
+ for (const item of value) {
20
+ headers.append(name, item);
21
+ }
22
+ }
23
+ }
24
+ const encrypted = "encrypted" in incoming.socket && incoming.socket.encrypted === true;
25
+ let protocol = "http";
26
+ if (encrypted) {
27
+ protocol = "https";
28
+ }
29
+ return new Request(`${protocol}://${incoming.headers.host}${incoming.url}`, {
30
+ method: incoming.method,
31
+ headers,
32
+ signal,
33
+ });
34
+ }
35
+ // A refusal on the raw socket: status line, headers, body, then the connection closes.
36
+ async function writeResponse(socket, response) {
37
+ const body = Buffer.from(await response.arrayBuffer());
38
+ let head = `HTTP/1.1 ${response.status} ${STATUS_CODES[response.status] ?? ""}\r\n`;
39
+ for (const [name, value] of response.headers) {
40
+ if (name !== "content-length" && name !== "connection") {
41
+ head += `${name}: ${value}\r\n`;
42
+ }
43
+ }
44
+ head += `content-length: ${body.length}\r\nconnection: close\r\n\r\n`;
45
+ if (!socket.destroyed) {
46
+ socket.end(Buffer.concat([Buffer.from(head, "latin1"), body]));
47
+ }
48
+ }
49
+ function ignore() { }
50
+ // Terminates a socket that didn't answer the previous ping.
51
+ function keepAlive(socket) {
52
+ let alive = true;
53
+ const timer = setInterval(() => {
54
+ if (!alive) {
55
+ socket.terminate();
56
+ return;
57
+ }
58
+ alive = false;
59
+ socket.ping();
60
+ }, pingMs);
61
+ socket.on("pong", () => {
62
+ alive = true;
63
+ });
64
+ socket.on("close", () => clearInterval(timer));
65
+ }
66
+ /**
67
+ * Creates the Node `upgrade` listener that runs the app's channels.
68
+ *
69
+ * @remarks
70
+ * Create it once, at your server module's top level, and attach it to the HTTP server that
71
+ * serves the app with `server.on("upgrade", listener)`; with Express, to the server
72
+ * `app.listen()` returns.
73
+ *
74
+ * For each upgrade request it builds a web `Request` (the protocol from the socket, the host
75
+ * from `Host`; proxy headers aren't trusted) whose signal aborts when the client leaves before
76
+ * the socket is accepted, and passes it to `handle`. A `null` result leaves the socket to the
77
+ * server's other `upgrade` listeners, such as a dev server's. A `Response` is written to the
78
+ * socket, which then closes. An `Upgrade` is accepted with `ws`, with its headers on the `101`,
79
+ * unless the client already left. Accepted sockets are pinged every 15 s and terminated when
80
+ * they miss the answer.
81
+ *
82
+ * Under `ng serve`, Launch's serve builder forwards `/_rpc/` upgrades to the latest listener
83
+ * created, so attaching it where your built server listens is all the wiring there is.
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * import { createServer } from "node:http";
88
+ * import { createUpgradeHandler } from "@loozo/angular-launch/node";
89
+ * import { handleUpgrade } from "../generated/server.generated";
90
+ *
91
+ * const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
92
+ *
93
+ * if (isMainModule(import.meta.url)) {
94
+ * const server = createServer(reqHandler).listen(port);
95
+ *
96
+ * server.on("upgrade", upgrade);
97
+ * }
98
+ * ```
99
+ *
100
+ * @param handle - Answers one upgrade request: the generated `handleUpgrade`, with your
101
+ * options.
102
+ * @param options - The largest message a caller may send.
103
+ * @returns The listener.
104
+ */
105
+ export function createUpgradeHandler(handle, { maxPayload = 1024 * 1024 } = {}) {
106
+ const server = new WebSocketServer({ noServer: true, clientTracking: false, maxPayload });
107
+ const accepted = new WeakMap();
108
+ server.on("headers", (lines, incoming) => {
109
+ for (const [name, value] of accepted.get(incoming) ?? []) {
110
+ lines.push(`${name}: ${value}`);
111
+ }
112
+ });
113
+ async function upgrade(incoming, socket, head) {
114
+ const leave = new AbortController();
115
+ function left() {
116
+ leave.abort(new DOMException("The client left before its channel was accepted", "AbortError"));
117
+ }
118
+ // Browsers that leave early send FIN, or the connection resets.
119
+ socket.once("end", left);
120
+ socket.once("close", left);
121
+ socket.on("error", left);
122
+ function release() {
123
+ socket.off("end", left);
124
+ socket.off("close", left);
125
+ socket.off("error", left);
126
+ }
127
+ // Nothing else owns a socket Launch closes itself: a reset while it closes must not go
128
+ // unhandled.
129
+ function releaseToClose() {
130
+ release();
131
+ socket.on("error", ignore);
132
+ socket.once("close", () => socket.off("error", ignore));
133
+ }
134
+ let result;
135
+ try {
136
+ result = await handle(webRequest(incoming, leave.signal));
137
+ }
138
+ catch (error) {
139
+ console.error("Launch couldn't answer an upgrade request", error);
140
+ result = new Response("Bad request", {
141
+ status: 400,
142
+ headers: { "content-type": "text/plain" },
143
+ });
144
+ }
145
+ if (result === null) {
146
+ release();
147
+ return;
148
+ }
149
+ if (result instanceof Response) {
150
+ releaseToClose();
151
+ await writeResponse(socket, result);
152
+ return;
153
+ }
154
+ if (leave.signal.aborted || socket.destroyed) {
155
+ releaseToClose();
156
+ socket.destroy();
157
+ return;
158
+ }
159
+ const call = result;
160
+ accepted.set(incoming, call.headers);
161
+ // Until accepted, a client leaving still ends the call, also when ws refuses the handshake.
162
+ server.handleUpgrade(incoming, socket, head, (websocket) => {
163
+ release();
164
+ accepted.delete(incoming);
165
+ // A frame over maxPayload or a broken connection emits an error, then the socket closes.
166
+ websocket.on("error", () => undefined);
167
+ keepAlive(websocket);
168
+ // ws implements the WHATWG WebSocket interface Launch uses.
169
+ call.accept(websocket);
170
+ });
171
+ }
172
+ const listener = (incoming, socket, head) => {
173
+ void upgrade(incoming, socket, head);
174
+ };
175
+ // Where `ng serve` finds the app's listener; the latest one created wins.
176
+ globalThis[upgradeListenerSlot] = listener;
177
+ return listener;
178
+ }
@@ -0,0 +1 @@
1
+ export declare const upgradeListenerSlot: unique symbol;
@@ -0,0 +1,4 @@
1
+ // The process-global slot where createUpgradeHandler stores the listener it creates, latest
2
+ // first, and where the serve builder's dev-server middleware finds it. Its own module so the
3
+ // builder reads it without loading ws.
4
+ export const upgradeListenerSlot = Symbol.for("@loozo/angular-launch/upgrade-listener/v1");
package/outcomes.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ import { type TranslateRedirect } from "./redirect-translation.js";
2
+ /**
3
+ * Whether `to` is a root-relative URL that stays on the app's origin.
4
+ *
5
+ * @remarks
6
+ * Internal. `//host` and `/\host` start with a slash but name another host, and the URL
7
+ * parser strips tabs and newlines, so the check resolves `to` against an origin instead
8
+ * of reading it.
9
+ */
10
+ export declare function isRootRelative(to: unknown): to is `/${string}`;
11
+ /**
12
+ * The rejection of a call whose stage, middleware or handler threw `redirect()`.
13
+ *
14
+ * @remarks
15
+ * Generated callables reject with it for a response that is exactly a redirect frame, and
16
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} turns it
17
+ * into a navigation to {@link RpcRedirect.to}; anywhere else, nothing navigates for you.
18
+ *
19
+ * With `translateSegments` and `provideRedirectTranslation()` installed, `to` is in the
20
+ * page's language, in the browser and while rendering a live request: it equals the page's
21
+ * own `createUrl` for the same destination and values. The wire frame and every
22
+ * `HttpInterceptor` see the canonical URL with its `words`.
23
+ */
24
+ export declare class RpcRedirect extends Error {
25
+ /**
26
+ * The root-relative URL the server redirected to, such as `/sign-in`, in this build's
27
+ * language for a translated app.
28
+ */
29
+ readonly to: `/${string}`;
30
+ /**
31
+ * Creates a redirect rejection.
32
+ *
33
+ * @param to - The root-relative URL the server redirected to.
34
+ */
35
+ constructor(
36
+ /**
37
+ * The root-relative URL the server redirected to, such as `/sign-in`, in this build's
38
+ * language for a translated app.
39
+ */
40
+ to: `/${string}`);
41
+ }
42
+ /**
43
+ * The rejection of a call whose middleware or handler threw `notFound()`.
44
+ *
45
+ * @remarks
46
+ * Generated callables reject with it for a response that is exactly a not-found frame, and
47
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} renders
48
+ * the app's not-found page instead; anywhere else, nothing navigates for you. It isn't an
49
+ * `RpcError`: `RPC_NOT_FOUND` is a missing procedure, this is a missing resource.
50
+ */
51
+ export declare class RpcNotFound extends Error {
52
+ /** Creates a not-found rejection. */
53
+ constructor();
54
+ }
55
+ /**
56
+ * Recognizes a response body that is exactly a redirect or not-found frame.
57
+ *
58
+ * @remarks
59
+ * Internal. A redirect is status 303 with exactly `{ redirect: { to } }` or
60
+ * `{ redirect: { to, words } }`, where `to` is root-relative and `words` lists, strictly
61
+ * increasing, the ordinals of its path segments that hold static words, on a path `createUrl`
62
+ * writes (`targetSegments`); not-found is status 404 with exactly
63
+ * `{ notFound: null }`. The body must be strict JSON. A redirect with `words` goes through
64
+ * `translate` when one is given; anything else keeps its `to`.
65
+ *
66
+ * @param value - The parsed response body.
67
+ * @param status - The response's HTTP status.
68
+ * @param translate - Puts a frame's listed words in this build's language.
69
+ * @returns The rejection to use, or `undefined` when the body doesn't match exactly.
70
+ */
71
+ export declare function recognizedOutcome(value: unknown, status: number, translate?: TranslateRedirect): RpcRedirect | RpcNotFound | undefined;
package/outcomes.js ADDED
@@ -0,0 +1,146 @@
1
+ import { serializeJson } from "./json.js";
2
+ import { targetSegments } from "./redirect-translation.js";
3
+ const base = "http://launch.invalid";
4
+ /**
5
+ * Whether `to` is a root-relative URL that stays on the app's origin.
6
+ *
7
+ * @remarks
8
+ * Internal. `//host` and `/\host` start with a slash but name another host, and the URL
9
+ * parser strips tabs and newlines, so the check resolves `to` against an origin instead
10
+ * of reading it.
11
+ */
12
+ export function isRootRelative(to) {
13
+ if (typeof to !== "string" || !to.startsWith("/")) {
14
+ return false;
15
+ }
16
+ let resolved;
17
+ try {
18
+ resolved = new URL(to, base);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ return resolved.origin === base;
24
+ }
25
+ /**
26
+ * The rejection of a call whose stage, middleware or handler threw `redirect()`.
27
+ *
28
+ * @remarks
29
+ * Generated callables reject with it for a response that is exactly a redirect frame, and
30
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} turns it
31
+ * into a navigation to {@link RpcRedirect.to}; anywhere else, nothing navigates for you.
32
+ *
33
+ * With `translateSegments` and `provideRedirectTranslation()` installed, `to` is in the
34
+ * page's language, in the browser and while rendering a live request: it equals the page's
35
+ * own `createUrl` for the same destination and values. The wire frame and every
36
+ * `HttpInterceptor` see the canonical URL with its `words`.
37
+ */
38
+ export class RpcRedirect extends Error {
39
+ to;
40
+ /**
41
+ * Creates a redirect rejection.
42
+ *
43
+ * @param to - The root-relative URL the server redirected to.
44
+ */
45
+ constructor(
46
+ /**
47
+ * The root-relative URL the server redirected to, such as `/sign-in`, in this build's
48
+ * language for a translated app.
49
+ */
50
+ to) {
51
+ super(`RPC redirected to ${to}`);
52
+ this.to = to;
53
+ this.name = "RpcRedirect";
54
+ }
55
+ }
56
+ /**
57
+ * The rejection of a call whose middleware or handler threw `notFound()`.
58
+ *
59
+ * @remarks
60
+ * Generated callables reject with it for a response that is exactly a not-found frame, and
61
+ * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} renders
62
+ * the app's not-found page instead; anywhere else, nothing navigates for you. It isn't an
63
+ * `RpcError`: `RPC_NOT_FOUND` is a missing procedure, this is a missing resource.
64
+ */
65
+ export class RpcNotFound extends Error {
66
+ /** Creates a not-found rejection. */
67
+ constructor() {
68
+ super("RPC answered not found");
69
+ this.name = "RpcNotFound";
70
+ }
71
+ }
72
+ // Valid `words`: a non-empty array of strictly increasing integer ordinals of `to`'s path
73
+ // segments, on a path createUrl writes.
74
+ function validWords(words, to) {
75
+ if (!Array.isArray(words) || words.length === 0) {
76
+ return false;
77
+ }
78
+ const segments = targetSegments(to);
79
+ if (segments === undefined) {
80
+ return false;
81
+ }
82
+ let previous = -1;
83
+ for (const at of words) {
84
+ if (!Number.isInteger(at) || at <= previous || at >= segments.length) {
85
+ return false;
86
+ }
87
+ previous = at;
88
+ }
89
+ return true;
90
+ }
91
+ /**
92
+ * Recognizes a response body that is exactly a redirect or not-found frame.
93
+ *
94
+ * @remarks
95
+ * Internal. A redirect is status 303 with exactly `{ redirect: { to } }` or
96
+ * `{ redirect: { to, words } }`, where `to` is root-relative and `words` lists, strictly
97
+ * increasing, the ordinals of its path segments that hold static words, on a path `createUrl`
98
+ * writes (`targetSegments`); not-found is status 404 with exactly
99
+ * `{ notFound: null }`. The body must be strict JSON. A redirect with `words` goes through
100
+ * `translate` when one is given; anything else keeps its `to`.
101
+ *
102
+ * @param value - The parsed response body.
103
+ * @param status - The response's HTTP status.
104
+ * @param translate - Puts a frame's listed words in this build's language.
105
+ * @returns The rejection to use, or `undefined` when the body doesn't match exactly.
106
+ */
107
+ export function recognizedOutcome(value, status, translate) {
108
+ try {
109
+ serializeJson(value);
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ if (typeof value !== "object" || value === null || Object.keys(value).length !== 1) {
115
+ return undefined;
116
+ }
117
+ if (status === 404 && "notFound" in value && value.notFound === null) {
118
+ return new RpcNotFound();
119
+ }
120
+ if (status !== 303 || !("redirect" in value)) {
121
+ return undefined;
122
+ }
123
+ const redirect = value.redirect;
124
+ if (typeof redirect !== "object" || redirect === null || !("to" in redirect)) {
125
+ return undefined;
126
+ }
127
+ const keys = Object.keys(redirect).length;
128
+ const hasWords = "words" in redirect;
129
+ if (keys !== (hasWords ? 2 : 1) || !isRootRelative(redirect.to)) {
130
+ return undefined;
131
+ }
132
+ if (!hasWords) {
133
+ return new RpcRedirect(redirect.to);
134
+ }
135
+ if (!validWords(redirect.words, redirect.to)) {
136
+ return undefined;
137
+ }
138
+ if (!translate) {
139
+ return new RpcRedirect(redirect.to);
140
+ }
141
+ const translated = translate(redirect.to, redirect.words);
142
+ if (!isRootRelative(translated)) {
143
+ return undefined;
144
+ }
145
+ return new RpcRedirect(translated);
146
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loozo/angular-launch",
3
- "version": "0.0.5",
3
+ "version": "0.1.0",
4
4
  "description": "Typed queries, mutations and declared errors on Angular's native router, HTTP and SSR pipeline.",
5
5
  "bugs": "https://github.com/theo-matzavinos/loozo/issues",
6
6
  "license": "MIT",
@@ -24,9 +24,17 @@
24
24
  "types": "./server/generated.d.ts",
25
25
  "default": "./server/generated.js"
26
26
  },
27
- "./_generated": {
28
- "types": "./generated.d.ts",
29
- "default": "./generated.js"
27
+ "./_source-text": {
28
+ "types": "./source-text.d.ts",
29
+ "default": "./source-text.js"
30
+ },
31
+ "./_redirects": {
32
+ "types": "./redirect-translation.d.ts",
33
+ "default": "./redirect-translation.js"
34
+ },
35
+ "./node": {
36
+ "types": "./node/index.d.ts",
37
+ "default": "./node/index.js"
30
38
  },
31
39
  "./generation": {
32
40
  "types": "./generation/index.d.ts",
@@ -36,9 +44,9 @@
36
44
  "types": "./tanstack-query/index.d.ts",
37
45
  "default": "./tanstack-query/index.js"
38
46
  },
39
- "./_tanstack-query": {
40
- "types": "./tanstack-query/generated.d.ts",
41
- "default": "./tanstack-query/generated.js"
47
+ "./testing": {
48
+ "types": "./testing/index.d.ts",
49
+ "default": "./testing/index.js"
42
50
  },
43
51
  "./package.json": "./package.json"
44
52
  },
@@ -47,15 +55,17 @@
47
55
  "registry": "https://registry.npmjs.org/"
48
56
  },
49
57
  "dependencies": {
50
- "@angular-devkit/architect": "0.2202.2",
58
+ "@angular-devkit/architect": "0.2202.6",
51
59
  "chokidar": "5.0.0",
52
- "typescript": "6.0.3"
60
+ "typescript": "6.0.3",
61
+ "ws": "8.21.3"
53
62
  },
54
63
  "peerDependencies": {
55
- "@angular/build": "~22.2.0",
64
+ "@angular/build": "~22.3.0",
56
65
  "@angular/common": "^22.0.0",
57
66
  "@angular/core": "^22.0.0",
58
- "@loozo/angular-router": "0.0.6",
67
+ "@angular/router": "^22.0.0",
68
+ "@loozo/angular-router": "0.1.0",
59
69
  "@tanstack/angular-query": "^5.0.0-rc.5",
60
70
  "rxjs": "^7.8.2"
61
71
  },