@loozo/angular-launch 0.0.5 → 0.0.6
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 +463 -42
- package/channel.d.ts +53 -0
- package/channel.js +231 -0
- package/client.d.ts +50 -10
- package/connect.d.ts +201 -0
- package/connect.js +148 -0
- package/generated.d.ts +1 -1
- package/generated.js +86 -3
- package/generation/index.js +25 -9
- package/index.d.ts +6 -1
- package/index.js +2 -0
- package/json.d.ts +9 -0
- package/json.js +24 -0
- package/navigation.d.ts +36 -0
- package/navigation.js +47 -0
- package/node/index.d.ts +57 -0
- package/node/index.js +175 -0
- package/outcomes.d.ts +55 -0
- package/outcomes.js +100 -0
- package/package.json +9 -3
- package/server/backend.d.ts +42 -23
- package/server/backend.js +127 -48
- package/server/channel-messages.d.ts +54 -0
- package/server/channel-messages.js +84 -0
- package/server/channel-socket.d.ts +67 -0
- package/server/channel-socket.js +322 -0
- package/server/definitions.d.ts +152 -24
- package/server/definitions.js +13 -5
- package/server/dispatch.d.ts +62 -11
- package/server/dispatch.js +156 -36
- package/server/event-stream.d.ts +63 -0
- package/server/event-stream.js +173 -0
- package/server/generated.d.ts +1 -0
- package/server/generated.js +1 -0
- package/server/index.d.ts +4 -2
- package/server/index.js +1 -1
- package/server/outcomes.d.ts +51 -2
- package/server/outcomes.js +58 -4
- package/server/response-effects.d.ts +105 -0
- package/server/response-effects.js +78 -0
- package/server/upgrade.d.ts +58 -0
- package/server/upgrade.js +117 -0
- package/stream.d.ts +31 -0
- package/stream.js +159 -0
- package/tanstack-query/README.md +101 -9
- package/tanstack-query/generated.js +5 -2
- package/tanstack-query/queries.d.ts +8 -6
package/connect.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { isPlatformServer } from "@angular/common";
|
|
2
|
+
import { afterNextRender, computed, DestroyRef, effect, inject, PLATFORM_ID, signal, untracked, } from "@angular/core";
|
|
3
|
+
/**
|
|
4
|
+
* Follows a stream or channel as signals. Internal: generated callables expose it as
|
|
5
|
+
* `connect()`.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Must run in an injection context. On the server it never connects: status stays `"idle"`
|
|
9
|
+
* and `value` is `initial()`. In the browser it connects after the next render, and again
|
|
10
|
+
* whenever `input` changes; each connection reads every value as it arrives. A connection
|
|
11
|
+
* closed for a new input or by the injection context's destruction doesn't change `status`
|
|
12
|
+
* or `error`.
|
|
13
|
+
*
|
|
14
|
+
* @param open - Opens one call.
|
|
15
|
+
* @param options - The `connect()` options.
|
|
16
|
+
* @returns The connection; `send` delegates to the open channel.
|
|
17
|
+
*/
|
|
18
|
+
export function connect(open, { input = () => null, initial, reduce }) {
|
|
19
|
+
const server = isPlatformServer(inject(PLATFORM_ID));
|
|
20
|
+
const destroyRef = inject(DestroyRef);
|
|
21
|
+
const received = signal(undefined);
|
|
22
|
+
const status = signal("idle");
|
|
23
|
+
const error = signal(undefined);
|
|
24
|
+
const value = computed(() => {
|
|
25
|
+
const latest = received();
|
|
26
|
+
if (latest === undefined) {
|
|
27
|
+
return initial();
|
|
28
|
+
}
|
|
29
|
+
return latest.state;
|
|
30
|
+
});
|
|
31
|
+
let current;
|
|
32
|
+
function close() {
|
|
33
|
+
current?.controller.abort();
|
|
34
|
+
current = undefined;
|
|
35
|
+
}
|
|
36
|
+
function fail(caught) {
|
|
37
|
+
error.set(caught);
|
|
38
|
+
status.set("failed");
|
|
39
|
+
}
|
|
40
|
+
async function follow(call) {
|
|
41
|
+
const { controller, connection } = call;
|
|
42
|
+
let state;
|
|
43
|
+
let first = true;
|
|
44
|
+
try {
|
|
45
|
+
for await (const item of connection) {
|
|
46
|
+
if (controller.signal.aborted) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
if (!reduce) {
|
|
51
|
+
state = item;
|
|
52
|
+
}
|
|
53
|
+
else if (first) {
|
|
54
|
+
// A new call's first value folds into the initial state, not the previous call's.
|
|
55
|
+
state = untracked(() => reduce(initial(), item));
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const previous = state;
|
|
59
|
+
state = untracked(() => reduce(previous, item));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch (thrown) {
|
|
63
|
+
let failure;
|
|
64
|
+
if (thrown instanceof Error) {
|
|
65
|
+
failure = thrown;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
failure = new Error("Launch connection's reduce threw a non-Error value", {
|
|
69
|
+
cause: thrown,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
// Set before the loop closes the channel, so the sends it rejects carry this error.
|
|
73
|
+
call.failure = { error: failure };
|
|
74
|
+
fail(failure);
|
|
75
|
+
throw failure;
|
|
76
|
+
}
|
|
77
|
+
first = false;
|
|
78
|
+
received.set({ state });
|
|
79
|
+
status.set("open");
|
|
80
|
+
}
|
|
81
|
+
if (!controller.signal.aborted) {
|
|
82
|
+
status.set("ended");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
catch (caught) {
|
|
86
|
+
if (controller.signal.aborted || call.failure !== undefined) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
fail(caught);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function start(next) {
|
|
93
|
+
close();
|
|
94
|
+
if (next === undefined) {
|
|
95
|
+
error.set(undefined);
|
|
96
|
+
status.set("idle");
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const controller = new AbortController();
|
|
100
|
+
const connection = open(next, controller.signal, () => {
|
|
101
|
+
if (current?.controller === controller && status() === "connecting") {
|
|
102
|
+
status.set("open");
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
const call = { controller, connection };
|
|
106
|
+
current = call;
|
|
107
|
+
error.set(undefined);
|
|
108
|
+
status.set("connecting");
|
|
109
|
+
void follow(call);
|
|
110
|
+
}
|
|
111
|
+
if (!server) {
|
|
112
|
+
const rendered = signal(false);
|
|
113
|
+
afterNextRender(() => rendered.set(true));
|
|
114
|
+
effect(() => {
|
|
115
|
+
if (!rendered()) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const next = input();
|
|
119
|
+
untracked(() => start(next));
|
|
120
|
+
});
|
|
121
|
+
destroyRef.onDestroy(close);
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
value,
|
|
125
|
+
status: status.asReadonly(),
|
|
126
|
+
error: error.asReadonly(),
|
|
127
|
+
reconnect() {
|
|
128
|
+
const now = untracked(status);
|
|
129
|
+
if (now === "ended" || now === "failed") {
|
|
130
|
+
start(untracked(input));
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
send(message) {
|
|
134
|
+
const now = untracked(status);
|
|
135
|
+
const call = current;
|
|
136
|
+
if (!call || (now !== "connecting" && now !== "open") || !("send" in call.connection)) {
|
|
137
|
+
return Promise.reject(new TypeError("Launch connection isn't open"));
|
|
138
|
+
}
|
|
139
|
+
// A failing `reduce` closes the channel; its sends then reject with what it threw.
|
|
140
|
+
return call.connection.send(message).catch((rejection) => {
|
|
141
|
+
if (call.failure !== undefined) {
|
|
142
|
+
return Promise.reject(call.failure.error);
|
|
143
|
+
}
|
|
144
|
+
return Promise.reject(rejection);
|
|
145
|
+
});
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
package/generated.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export declare const RPC_CALL: HttpContextToken<boolean>;
|
|
|
4
4
|
export interface ClientMethod {
|
|
5
5
|
readonly name: string;
|
|
6
6
|
readonly input: boolean;
|
|
7
|
-
readonly kind: "query" | "mutation";
|
|
7
|
+
readonly kind: "query" | "mutation" | "stream" | "channel";
|
|
8
8
|
readonly errors: readonly ErrorMetadata[];
|
|
9
9
|
}
|
|
10
10
|
export declare function injectClient(groups: Readonly<Record<string, {
|
package/generated.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isPlatformServer } from "@angular/common";
|
|
2
|
+
import { inject, PLATFORM_ID } from "@angular/core";
|
|
2
3
|
import { HttpClient, HttpContext, HttpContextToken, HttpErrorResponse } from "@angular/common/http";
|
|
3
|
-
import {
|
|
4
|
+
import { openChannel } from "./channel.js";
|
|
5
|
+
import { RpcError, recognizedError, } from "./client.js";
|
|
6
|
+
import { connect } from "./connect.js";
|
|
4
7
|
import { serializeJson } from "./json.js";
|
|
8
|
+
import { recognizedOutcome } from "./outcomes.js";
|
|
9
|
+
import { openStream } from "./stream.js";
|
|
5
10
|
export const RPC_CALL = new HttpContextToken(() => false);
|
|
6
11
|
const errorOwners = new WeakMap();
|
|
7
12
|
function call(http, group, method, input, { signal, transferCache = true } = {}) {
|
|
@@ -51,6 +56,11 @@ function call(http, group, method, input, { signal, transferCache = true } = {})
|
|
|
51
56
|
reject(converted);
|
|
52
57
|
return;
|
|
53
58
|
}
|
|
59
|
+
const outcome = recognizedOutcome(error.error, error.status);
|
|
60
|
+
if (outcome) {
|
|
61
|
+
reject(outcome);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
54
64
|
}
|
|
55
65
|
reject(error);
|
|
56
66
|
},
|
|
@@ -60,19 +70,92 @@ function call(http, group, method, input, { signal, transferCache = true } = {})
|
|
|
60
70
|
}
|
|
61
71
|
});
|
|
62
72
|
}
|
|
73
|
+
// Streams don't run during server rendering: iterating one fails at once with FORBIDDEN.
|
|
74
|
+
function refusedStream(error) {
|
|
75
|
+
return { next: () => Promise.reject(error) };
|
|
76
|
+
}
|
|
77
|
+
function owner(group, method) {
|
|
78
|
+
return (error) => {
|
|
79
|
+
errorOwners.set(error, { group, method: method.name });
|
|
80
|
+
return error;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function stream(server, group, method, input, options = {}, opened) {
|
|
84
|
+
const own = owner(group, method);
|
|
85
|
+
// Each iteration is its own request, so iterating again reconnects.
|
|
86
|
+
return {
|
|
87
|
+
[Symbol.asyncIterator]: () => {
|
|
88
|
+
if (server) {
|
|
89
|
+
return refusedStream(own(new RpcError("FORBIDDEN", 403)));
|
|
90
|
+
}
|
|
91
|
+
return openStream(`/_rpc/${group}/${method.name}`, input, method.errors, own, options, opened);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
// Channels don't run during server rendering either: they fail at once with FORBIDDEN.
|
|
96
|
+
function channel(server, group, method, input, options = {}, opened) {
|
|
97
|
+
const own = owner(group, method);
|
|
98
|
+
let path = `/_rpc/${group}/${method.name}`;
|
|
99
|
+
let refused;
|
|
100
|
+
if (server) {
|
|
101
|
+
refused = own(new RpcError("FORBIDDEN", 403));
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
try {
|
|
105
|
+
path += `?input=${encodeURIComponent(serializeJson(input))}`;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
refused = error;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return openChannel(path, method.errors, own, options, opened, refused);
|
|
112
|
+
}
|
|
63
113
|
export function injectClient(groups) {
|
|
64
114
|
const http = inject(HttpClient);
|
|
115
|
+
let server = false;
|
|
116
|
+
// Only streams and channels depend on the platform.
|
|
117
|
+
for (const group of Object.values(groups)) {
|
|
118
|
+
if (group.methods.some((method) => method.kind === "stream" || method.kind === "channel")) {
|
|
119
|
+
server = isPlatformServer(inject(PLATFORM_ID));
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
65
123
|
const result = Object.create(null);
|
|
66
124
|
for (const [namespace, group] of Object.entries(groups)) {
|
|
67
125
|
const methods = Object.create(null);
|
|
68
126
|
for (const method of group.methods) {
|
|
69
127
|
let invoke;
|
|
70
|
-
|
|
128
|
+
let open;
|
|
129
|
+
if (method.kind === "stream") {
|
|
130
|
+
open = (input, signal, opened) => stream(server, namespace, method, input, { signal }, opened);
|
|
131
|
+
if (method.input) {
|
|
132
|
+
invoke = (input, options) => stream(server, namespace, method, input, options);
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
invoke = (options) => stream(server, namespace, method, null, options);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
else if (method.kind === "channel") {
|
|
139
|
+
open = (input, signal, opened) => channel(server, namespace, method, input, { signal }, opened);
|
|
140
|
+
if (method.input) {
|
|
141
|
+
invoke = (input, options) => channel(server, namespace, method, input, options);
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
invoke = (options) => channel(server, namespace, method, null, options);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
else if (method.input) {
|
|
71
148
|
invoke = (input, options) => call(http, namespace, method, input, options);
|
|
72
149
|
}
|
|
73
150
|
else {
|
|
74
151
|
invoke = (options) => call(http, namespace, method, null, options);
|
|
75
152
|
}
|
|
153
|
+
if (open) {
|
|
154
|
+
const opener = open;
|
|
155
|
+
Object.assign(invoke, {
|
|
156
|
+
connect: (options) => connect(opener, options),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
76
159
|
methods[method.name] = Object.assign(invoke, {
|
|
77
160
|
kind: method.kind,
|
|
78
161
|
isError: (error) => {
|
package/generation/index.js
CHANGED
|
@@ -12,7 +12,8 @@ function directCall(node, label) {
|
|
|
12
12
|
}
|
|
13
13
|
return node;
|
|
14
14
|
}
|
|
15
|
-
const builderShape = "defineRpc requires an arrow function destructuring query and/or
|
|
15
|
+
const builderShape = "defineRpc requires an arrow function destructuring query, mutation, stream and/or channel, returning a parenthesized object of procedures";
|
|
16
|
+
const builders = ["query", "mutation", "stream", "channel"];
|
|
16
17
|
// `({ query, mutation }) => ({ ... })`: the builder names it binds and its procedures.
|
|
17
18
|
function builderCallback(node) {
|
|
18
19
|
if (!ts.isArrowFunction(node) ||
|
|
@@ -35,9 +36,9 @@ function builderCallback(node) {
|
|
|
35
36
|
element.initializer ||
|
|
36
37
|
element.dotDotDotToken ||
|
|
37
38
|
!ts.isIdentifier(element.name) ||
|
|
38
|
-
(element.name.text
|
|
39
|
+
!builders.includes(element.name.text) ||
|
|
39
40
|
bound.has(element.name.text)) {
|
|
40
|
-
fail(element, "defineRpc's callback may only destructure query and
|
|
41
|
+
fail(element, "defineRpc's callback may only destructure query, mutation, stream and channel, without renaming");
|
|
41
42
|
}
|
|
42
43
|
bound.add(element.name.text);
|
|
43
44
|
}
|
|
@@ -153,17 +154,25 @@ async function groupsOf(sources) {
|
|
|
153
154
|
if (name === "__proto__") {
|
|
154
155
|
fail(value, "RPC procedure '__proto__' is reserved");
|
|
155
156
|
}
|
|
156
|
-
const procedure = directCall(value, "query/mutation");
|
|
157
|
+
const procedure = directCall(value, "query/mutation/stream/channel");
|
|
157
158
|
// The callback's own binding: its body is an object literal, so nothing can shadow it.
|
|
158
159
|
if (!ts.isIdentifier(procedure.expression) || !bound.has(procedure.expression.text)) {
|
|
159
|
-
fail(procedure, "Procedure must directly call the callback's query or
|
|
160
|
+
fail(procedure, "Procedure must directly call the callback's query, mutation, stream or channel");
|
|
160
161
|
}
|
|
161
162
|
const kind = procedure.expression.text;
|
|
162
163
|
if (procedure.arguments.length !== 1) {
|
|
163
164
|
fail(procedure, `${kind} requires one inline options object`);
|
|
164
165
|
}
|
|
165
166
|
const fields = properties(procedure.arguments[0], "Procedure options");
|
|
166
|
-
|
|
167
|
+
if (kind === "channel") {
|
|
168
|
+
onlyKeys(fields, ["handler", "input", "message", "use", "errors"], procedure);
|
|
169
|
+
if (!fields.has("message")) {
|
|
170
|
+
fail(procedure, "channel requires message");
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
onlyKeys(fields, ["handler", "input", "use", "errors"], procedure);
|
|
175
|
+
}
|
|
167
176
|
if (!fields.has("handler")) {
|
|
168
177
|
fail(procedure, `${kind} requires handler`);
|
|
169
178
|
}
|
|
@@ -195,12 +204,12 @@ function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
|
|
|
195
204
|
launchMarkers["server.generated.ts"],
|
|
196
205
|
payloadImport(registry, context.file, "context"),
|
|
197
206
|
`import type { HandleOptions } from '@loozo/angular-launch/server';`,
|
|
198
|
-
`import { createRequestScope, handleRpc, provideLaunchServer } from '@loozo/angular-launch/_server';`,
|
|
207
|
+
`import { createRequestScope, handleChannelUpgrade, handleRpc, provideLaunchServer } from '@loozo/angular-launch/_server';`,
|
|
199
208
|
];
|
|
200
209
|
for (let index = 0; index < groups.length; index += 1) {
|
|
201
210
|
server.push(payloadImport(registry, groups[index].declaration.file, `group${index}`));
|
|
202
211
|
}
|
|
203
|
-
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, options: HandleOptions) => handleRpc(registry, appBinding, request, options);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
|
|
212
|
+
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, options: HandleOptions) => handleRpc(registry, appBinding, request, options);`, `export const handleUpgrade = (request: Request, options: HandleOptions) => handleChannelUpgrade(registry, appBinding, request, options);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
|
|
204
213
|
add(desired, registry, server.join("\n"));
|
|
205
214
|
const byOwner = new Map(groups.map((group) => [group.owner, group]));
|
|
206
215
|
for (const owner of sources.declarations) {
|
|
@@ -240,7 +249,10 @@ function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
|
|
|
240
249
|
};
|
|
241
250
|
queriesMetadata[group.namespace] = Object.create(null);
|
|
242
251
|
for (const { name, kind, input } of group.methods) {
|
|
243
|
-
|
|
252
|
+
// Streams and channels have no TanStack options.
|
|
253
|
+
if (kind !== "stream" && kind !== "channel") {
|
|
254
|
+
queriesMetadata[group.namespace][name] = { kind, input };
|
|
255
|
+
}
|
|
244
256
|
}
|
|
245
257
|
}
|
|
246
258
|
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; }`);
|
|
@@ -367,6 +379,10 @@ async function validateBindings(sources, validation, context, groups, compiler)
|
|
|
367
379
|
if (input && hasNonConcreteSchemaBranch(checker.getTypeAtLocation(input))) {
|
|
368
380
|
fail(input, "Explicit query input must have a concrete Standard Schema type (also required for mutations)");
|
|
369
381
|
}
|
|
382
|
+
const message = fields.get("message");
|
|
383
|
+
if (message && hasNonConcreteSchemaBranch(checker.getTypeAtLocation(message))) {
|
|
384
|
+
fail(message, "A channel's message must have a concrete Standard Schema type");
|
|
385
|
+
}
|
|
370
386
|
const errors = fields.get("errors");
|
|
371
387
|
if (errors) {
|
|
372
388
|
for (const value of properties(errors, "Declared RPC errors").values()) {
|
package/index.d.ts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
export { RpcError, frameworkFailures } from "./client.js";
|
|
2
|
-
export type { CallOptions, MutationCallOptions, Client, ClientProcedure, ClientRpcError, FrameworkCode, } from "./client.js";
|
|
2
|
+
export type { CallOptions, ChannelCallOptions, MutationCallOptions, StreamCallOptions, Client, ClientProcedure, ClientRpcError, FrameworkCode, } from "./client.js";
|
|
3
|
+
export type { Channel } from "./channel.js";
|
|
4
|
+
export type { ChannelConnector, ConnectInput, Connection, ConnectionError, ConnectionStatus, ConnectOptions, OptionalConnectInput, ReducingConnectOptions, StreamConnection, StreamConnector, } from "./connect.js";
|
|
3
5
|
export type { InputIssue, InvalidInputData } from "./input-issues.js";
|
|
6
|
+
export { RpcNotFound, RpcRedirect } from "./outcomes.js";
|
|
7
|
+
export { rpcNavigationErrors } from "./navigation.js";
|
|
8
|
+
export type { RpcNavigationErrorsOptions } from "./navigation.js";
|
package/index.js
CHANGED
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
|
+
}
|
package/navigation.d.ts
ADDED
|
@@ -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
|
|
6
|
+
* `createUrl(notFoundRoute, {})`. 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(notFoundRoute, {}) })),
|
|
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(notFoundRoute, {}) })),
|
|
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
|
+
}
|
package/node/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* import { createServer } from "node:http";
|
|
40
|
+
* import { createUpgradeHandler } from "@loozo/angular-launch/node";
|
|
41
|
+
* import { handleUpgrade } from "../generated/server.generated";
|
|
42
|
+
*
|
|
43
|
+
* const upgrade = createUpgradeHandler((request) => handleUpgrade(request, { allowedHosts }));
|
|
44
|
+
*
|
|
45
|
+
* if (isMainModule(import.meta.url)) {
|
|
46
|
+
* const server = createServer(reqHandler).listen(port);
|
|
47
|
+
*
|
|
48
|
+
* server.on("upgrade", upgrade);
|
|
49
|
+
* }
|
|
50
|
+
* ```
|
|
51
|
+
*
|
|
52
|
+
* @param handle - Answers one upgrade request: the generated `handleUpgrade`, with your
|
|
53
|
+
* options.
|
|
54
|
+
* @param options - The largest message a caller may send.
|
|
55
|
+
* @returns The listener.
|
|
56
|
+
*/
|
|
57
|
+
export declare function createUpgradeHandler(handle: (request: Request) => Promise<Response | Upgrade | null>, { maxPayload }?: UpgradeHandlerOptions): UpgradeListener;
|