@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
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { parseJson, serializeJson } from "../json.js";
|
|
2
|
+
import { MessageRefused } from "./channel-messages.js";
|
|
3
|
+
import { invalidInput } from "./dispatch.js";
|
|
4
|
+
import { failureFrame, settleStopped } from "./event-stream.js";
|
|
5
|
+
/** How many values the server sends before the caller must grant more. */
|
|
6
|
+
export const valueWindow = 256;
|
|
7
|
+
/** How many messages the caller sends before the server must grant more. */
|
|
8
|
+
export const messageWindow = 32;
|
|
9
|
+
/** Past this many unsent bytes in the socket's buffer, the server stops pulling values. */
|
|
10
|
+
export const bufferedMark = 1024 * 1024;
|
|
11
|
+
/** How often the server checks whether the socket's buffer drained below the mark. */
|
|
12
|
+
export const bufferedPollMs = 50;
|
|
13
|
+
// WebSocket readyState values; the WebSocket global isn't on every server runtime.
|
|
14
|
+
const connecting = 0;
|
|
15
|
+
const open = 1;
|
|
16
|
+
/**
|
|
17
|
+
* Creates one channel call's side of its websocket.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* Internal. After `accept`, it sends one `{"value":v}` frame per yielded value, then, once
|
|
21
|
+
* the whole call settled, `{"end":null}` or the failure frame, and closes with 1000.
|
|
22
|
+
*
|
|
23
|
+
* Flow control is two credit windows. The server sends at most {@link valueWindow} values
|
|
24
|
+
* the caller hasn't granted back with `{"ready":n}`, and pulls the handler's next value only
|
|
25
|
+
* with credit and while the socket buffers less than {@link bufferedMark} bytes, checking
|
|
26
|
+
* every {@link bufferedPollMs} ms. The caller sends at most {@link messageWindow} messages
|
|
27
|
+
* the handler hasn't read; the server grants `{"ready":n}` once the handler read half a
|
|
28
|
+
* window since the last grant.
|
|
29
|
+
*
|
|
30
|
+
* A binary or malformed frame, a message beyond the caller's credit or a grant for more
|
|
31
|
+
* values than are outstanding ends the call with `INVALID_INPUT`, as does a message that
|
|
32
|
+
* fails validation. Frames arriving after the handler finished are dropped.
|
|
33
|
+
*
|
|
34
|
+
* When the socket closes, or the request goes away before `accept`, the call's signal
|
|
35
|
+
* aborts, `messages` ends after the messages already received, and the handler's pending
|
|
36
|
+
* step is awaited and its iterator returned, as for a stream. A generator suspended at its
|
|
37
|
+
* `yield` for want of credit returns at once.
|
|
38
|
+
*
|
|
39
|
+
* @param requestSignal - The upgrade request's signal, followed until `accept`.
|
|
40
|
+
* @returns The channel's socket side.
|
|
41
|
+
*/
|
|
42
|
+
export function createChannelSocket(requestSignal) {
|
|
43
|
+
const controller = new AbortController();
|
|
44
|
+
let socket;
|
|
45
|
+
let stream;
|
|
46
|
+
let outcome;
|
|
47
|
+
let pending;
|
|
48
|
+
// No more values or frames: the socket closed, the request left or the caller broke the
|
|
49
|
+
// protocol. Set once something has taken charge of settling `stream.finished` too.
|
|
50
|
+
let stopped = false;
|
|
51
|
+
let ending = false;
|
|
52
|
+
let closed = false;
|
|
53
|
+
let refusal;
|
|
54
|
+
let valueCredit = valueWindow;
|
|
55
|
+
let wake;
|
|
56
|
+
let poll;
|
|
57
|
+
const received = [];
|
|
58
|
+
const readers = [];
|
|
59
|
+
let inboxEnded = false;
|
|
60
|
+
let inboxError;
|
|
61
|
+
let messageCredit = messageWindow;
|
|
62
|
+
let readSinceGrant = 0;
|
|
63
|
+
function send(frame) {
|
|
64
|
+
socket.send(frame);
|
|
65
|
+
}
|
|
66
|
+
function read() {
|
|
67
|
+
readSinceGrant += 1;
|
|
68
|
+
if (readSinceGrant >= messageWindow / 2 && !stopped && !ending) {
|
|
69
|
+
send(serializeJson({ ready: readSinceGrant }));
|
|
70
|
+
messageCredit += readSinceGrant;
|
|
71
|
+
readSinceGrant = 0;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// Messages already received are still read; then `messages` ends.
|
|
75
|
+
function endInbox() {
|
|
76
|
+
inboxEnded = true;
|
|
77
|
+
for (const reader of readers.splice(0)) {
|
|
78
|
+
reader.resolve({ done: true, value: undefined });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function receive(message) {
|
|
82
|
+
const reader = readers.shift();
|
|
83
|
+
if (reader) {
|
|
84
|
+
read();
|
|
85
|
+
reader.resolve({ done: false, value: message });
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
received.push(message);
|
|
89
|
+
}
|
|
90
|
+
function stop() {
|
|
91
|
+
if (stopped) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
stopped = true;
|
|
95
|
+
clearTimeout(poll);
|
|
96
|
+
wake?.();
|
|
97
|
+
endInbox();
|
|
98
|
+
if (stream && !ending) {
|
|
99
|
+
ending = true;
|
|
100
|
+
void settleStopped(stream, pending);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function follow() {
|
|
104
|
+
controller.abort(requestSignal.reason);
|
|
105
|
+
}
|
|
106
|
+
// Registered first, so a request that already left stops the socket too.
|
|
107
|
+
controller.signal.addEventListener("abort", stop, { once: true });
|
|
108
|
+
if (requestSignal.aborted) {
|
|
109
|
+
follow();
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
requestSignal.addEventListener("abort", follow, { once: true });
|
|
113
|
+
}
|
|
114
|
+
// Ends the call with `INVALID_INPUT`, whatever the handler and middleware make of it.
|
|
115
|
+
function refuse(issues) {
|
|
116
|
+
if (stopped || ending) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
refusal = invalidInput(issues);
|
|
120
|
+
inboxError = new MessageRefused(issues);
|
|
121
|
+
received.length = 0;
|
|
122
|
+
for (const reader of readers.splice(0)) {
|
|
123
|
+
reader.reject(inboxError);
|
|
124
|
+
}
|
|
125
|
+
controller.abort(new DOMException("Launch channel refused a message", "AbortError"));
|
|
126
|
+
void outcome.then(() => {
|
|
127
|
+
if (!closed) {
|
|
128
|
+
send(failureFrame(refusal));
|
|
129
|
+
socket.close(1000);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function onMessage(event) {
|
|
134
|
+
if (stopped || ending) {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (typeof event.data !== "string") {
|
|
138
|
+
refuse([]);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
let frame;
|
|
142
|
+
try {
|
|
143
|
+
frame = parseJson(event.data);
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
refuse([]);
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (typeof frame !== "object" ||
|
|
150
|
+
frame === null ||
|
|
151
|
+
Array.isArray(frame) ||
|
|
152
|
+
Object.keys(frame).length !== 1) {
|
|
153
|
+
refuse([]);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (Object.hasOwn(frame, "message")) {
|
|
157
|
+
messageCredit -= 1;
|
|
158
|
+
if (messageCredit < 0) {
|
|
159
|
+
refuse([]);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
receive(frame.message);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
if (Object.hasOwn(frame, "ready")) {
|
|
166
|
+
const granted = frame.ready;
|
|
167
|
+
const outstanding = valueWindow - valueCredit;
|
|
168
|
+
if (typeof granted !== "number" ||
|
|
169
|
+
!Number.isSafeInteger(granted) ||
|
|
170
|
+
granted <= 0 ||
|
|
171
|
+
granted > outstanding) {
|
|
172
|
+
refuse([]);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
valueCredit += granted;
|
|
176
|
+
wake?.();
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
refuse([]);
|
|
180
|
+
}
|
|
181
|
+
function onClose() {
|
|
182
|
+
closed = true;
|
|
183
|
+
// Until the whole call settled, middleware included, closing still cancels it; a call that
|
|
184
|
+
// already finished doesn't abort afterwards.
|
|
185
|
+
if (!stopped) {
|
|
186
|
+
controller.abort(new DOMException("Launch channel closed", "AbortError"));
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
async function finish() {
|
|
190
|
+
const reply = await outcome;
|
|
191
|
+
stop();
|
|
192
|
+
if (closed) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (reply.status === 200) {
|
|
196
|
+
send(serializeJson({ end: null }));
|
|
197
|
+
}
|
|
198
|
+
else {
|
|
199
|
+
send(failureFrame(reply));
|
|
200
|
+
}
|
|
201
|
+
socket.close(1000);
|
|
202
|
+
}
|
|
203
|
+
function waitFor(delay) {
|
|
204
|
+
return new Promise((resolve) => {
|
|
205
|
+
wake = resolve;
|
|
206
|
+
if (delay !== undefined) {
|
|
207
|
+
poll = setTimeout(resolve, delay);
|
|
208
|
+
}
|
|
209
|
+
}).then(() => {
|
|
210
|
+
wake = undefined;
|
|
211
|
+
clearTimeout(poll);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
async function pump() {
|
|
215
|
+
const started = stream;
|
|
216
|
+
while (!stopped) {
|
|
217
|
+
if (valueCredit === 0) {
|
|
218
|
+
await waitFor();
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (socket.bufferedAmount >= bufferedMark) {
|
|
222
|
+
await waitFor(bufferedPollMs);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
// A custom iterator's next() may throw instead of rejecting.
|
|
226
|
+
const next = new Promise((resolve) => {
|
|
227
|
+
resolve(started.iterator.next());
|
|
228
|
+
});
|
|
229
|
+
let step;
|
|
230
|
+
pending = next;
|
|
231
|
+
try {
|
|
232
|
+
step = await next;
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
// A stopped channel settles with this failure itself.
|
|
236
|
+
if (!stopped) {
|
|
237
|
+
ending = true;
|
|
238
|
+
started.finished.reject(error);
|
|
239
|
+
await finish();
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (stopped) {
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (step.done) {
|
|
247
|
+
ending = true;
|
|
248
|
+
started.finished.resolve();
|
|
249
|
+
await finish();
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
let frame;
|
|
253
|
+
try {
|
|
254
|
+
frame = serializeJson({ value: step.value });
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
// The handler is still suspended at its yield: return its iterator, then fail with
|
|
258
|
+
// this error, whatever returning throws.
|
|
259
|
+
ending = true;
|
|
260
|
+
void settleStopped(started, Promise.reject(error));
|
|
261
|
+
await finish();
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
send(frame);
|
|
265
|
+
valueCredit -= 1;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
function begin() {
|
|
269
|
+
if (closed) {
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
void pump();
|
|
273
|
+
}
|
|
274
|
+
return {
|
|
275
|
+
inbox: {
|
|
276
|
+
next() {
|
|
277
|
+
if (received.length > 0) {
|
|
278
|
+
const message = received.shift();
|
|
279
|
+
read();
|
|
280
|
+
return Promise.resolve({ done: false, value: message });
|
|
281
|
+
}
|
|
282
|
+
if (inboxError) {
|
|
283
|
+
return Promise.reject(inboxError);
|
|
284
|
+
}
|
|
285
|
+
if (inboxEnded) {
|
|
286
|
+
return Promise.resolve({ done: true, value: undefined });
|
|
287
|
+
}
|
|
288
|
+
return new Promise((resolve, reject) => {
|
|
289
|
+
readers.push({ resolve, reject });
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
refuse,
|
|
293
|
+
},
|
|
294
|
+
signal: controller.signal,
|
|
295
|
+
start(started, settled) {
|
|
296
|
+
stream = started;
|
|
297
|
+
outcome = settled;
|
|
298
|
+
// The request left while the pipeline ran: the handler's body never runs.
|
|
299
|
+
if (controller.signal.aborted) {
|
|
300
|
+
ending = true;
|
|
301
|
+
void settleStopped(started, undefined);
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
accept(accepted) {
|
|
305
|
+
requestSignal.removeEventListener("abort", follow);
|
|
306
|
+
socket = accepted;
|
|
307
|
+
if (stopped) {
|
|
308
|
+
accepted.close(1000);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
accepted.addEventListener("message", onMessage);
|
|
312
|
+
accepted.addEventListener("close", onClose);
|
|
313
|
+
if (accepted.readyState === connecting) {
|
|
314
|
+
accepted.addEventListener("open", begin, { once: true });
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
if (accepted.readyState === open) {
|
|
318
|
+
begin();
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
}
|
package/server/definitions.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type { JsonShape } from "../json.js";
|
|
|
2
2
|
import type { FrameworkCode } from "../client.js";
|
|
3
3
|
import { declaredFailures } from "./errors.js";
|
|
4
4
|
import type { DeclaredFailure } from "./errors.js";
|
|
5
|
+
import type { ResponseControl } from "./response-effects.js";
|
|
5
6
|
/**
|
|
6
7
|
* Registration point for the application's context type.
|
|
7
8
|
*
|
|
@@ -136,9 +137,10 @@ export type OutputOf<S> = S extends Schema<unknown, infer Output> ? Output : und
|
|
|
136
137
|
*/
|
|
137
138
|
export interface ContextDefinition<Value> {
|
|
138
139
|
/**
|
|
139
|
-
* Creates the context for one live server request.
|
|
140
|
+
* Creates the context for one live server request, or for one page Angular prerenders.
|
|
140
141
|
*
|
|
141
|
-
* @param request - The request bound to the new request scope
|
|
142
|
+
* @param request - The request bound to the new request scope: a cookie-less `GET` of
|
|
143
|
+
* the page's URL when Angular prerenders it.
|
|
142
144
|
* @returns The context value, or a promise of it.
|
|
143
145
|
*/
|
|
144
146
|
readonly create: (request: Request) => Value;
|
|
@@ -156,6 +158,10 @@ export interface ContextDefinition<Value> {
|
|
|
156
158
|
* and RPC requests alike, and its value is the `context` middleware and handlers start
|
|
157
159
|
* from. Keep per-request state in the context rather than in module variables.
|
|
158
160
|
*
|
|
161
|
+
* When Angular prerenders a page that calls an RPC, the factory runs at build time with a
|
|
162
|
+
* cookie-less `GET` of the page's URL on a local origin Angular picks, so a prerendered
|
|
163
|
+
* page shows what an anonymous visitor would see.
|
|
164
|
+
*
|
|
159
165
|
* @example
|
|
160
166
|
* ```ts
|
|
161
167
|
* import { defineContext } from "@loozo/angular-launch/server";
|
|
@@ -222,12 +228,17 @@ export type ErrorFactories<Definitions extends ErrorDefinitions> = {
|
|
|
222
228
|
};
|
|
223
229
|
type JsonContract<Value> = 0 extends 1 & Value ? never : [Value] extends [JsonShape<Value>] ? unknown : never;
|
|
224
230
|
type InputContract<Input> = Input extends Schema ? JsonContract<InputOf<Input>> : unknown;
|
|
231
|
+
type MessageContract<Message> = Message extends Schema ? JsonContract<InputOf<Message>> : never;
|
|
225
232
|
type ErrorContract<Definitions extends ErrorDefinitions> = {
|
|
226
233
|
readonly [Code in keyof Definitions]: Code extends FrameworkCode | "__proto__" ? never : Definitions[Code]["message"] extends "" ? never : Definitions[Code] & JsonContract<OutputOf<Definitions[Code]["data"]>>;
|
|
227
234
|
};
|
|
228
235
|
type JsonResult<Value> = Value extends Promise<infer Result> ? Promise<JsonShape<Result>> : JsonShape<Value>;
|
|
229
|
-
/**
|
|
230
|
-
|
|
236
|
+
/**
|
|
237
|
+
* Whether a procedure reads (`"query"`), writes (`"mutation"`), streams values while it
|
|
238
|
+
* runs (`"stream"`) or talks both ways over a websocket (`"channel"`).
|
|
239
|
+
*/
|
|
240
|
+
export type ProcedureKind = "query" | "mutation" | "stream" | "channel";
|
|
241
|
+
type StreamResult<Value> = Value extends AsyncIterable<infer Item> ? AsyncIterable<JsonShape<Item>, void> : never;
|
|
231
242
|
declare const middlewareResult: unique symbol;
|
|
232
243
|
type OptionalKeys<Value> = {
|
|
233
244
|
[Key in keyof Value]-?: {} extends Pick<Value, Key> ? Key : never;
|
|
@@ -283,14 +294,23 @@ export interface CallArgs<ContextValue, Input> {
|
|
|
283
294
|
/**
|
|
284
295
|
* The live request the call runs in, bound to its request scope: the scope's copy of
|
|
285
296
|
* the RPC HTTP request, or, during server rendering, the page request given to Angular.
|
|
297
|
+
* When Angular prerenders a page, it's a cookie-less `GET` of the page's URL.
|
|
286
298
|
*/
|
|
287
299
|
readonly request: Request;
|
|
288
300
|
/**
|
|
289
301
|
* Aborts when the caller goes away: over HTTP when the incoming request's signal
|
|
290
302
|
* aborts, and during server rendering when the page request aborts or `HttpClient`
|
|
291
|
-
* unsubscribes before the call settled.
|
|
303
|
+
* unsubscribes before the call settled. When Angular prerenders a page, the page
|
|
304
|
+
* request aborts when the render's application is destroyed. Advisory: pass it on to work that accepts one.
|
|
292
305
|
*/
|
|
293
306
|
readonly signal: AbortSignal;
|
|
307
|
+
/**
|
|
308
|
+
* The call's cookies and headers. Over HTTP they go on the RPC response; during server
|
|
309
|
+
* rendering, cookies go on the page response and headers are dropped. A prerendered page
|
|
310
|
+
* has no response, so a cookie set while Angular prerenders it fails the build, unless
|
|
311
|
+
* it's set after the app is first stable, such as in a `BEFORE_APP_SERIALIZED` hook.
|
|
312
|
+
*/
|
|
313
|
+
readonly response: ResponseControl;
|
|
294
314
|
}
|
|
295
315
|
/**
|
|
296
316
|
* What a middleware receives: the call's arguments and `next`.
|
|
@@ -331,7 +351,7 @@ export interface MiddlewareArgs<Needs = Context, Input = unknown> extends CallAr
|
|
|
331
351
|
* Continues the call with the context unchanged.
|
|
332
352
|
*
|
|
333
353
|
* @returns The result to return from the middleware. It rejects with whatever the
|
|
334
|
-
* rest of the call threw, including declared errors and `forbidden()`.
|
|
354
|
+
* rest of the call threw, including declared errors and outcomes such as `forbidden()`.
|
|
335
355
|
*/
|
|
336
356
|
(): Promise<MiddlewareResult<{}>>;
|
|
337
357
|
/**
|
|
@@ -347,7 +367,7 @@ export interface MiddlewareArgs<Needs = Context, Input = unknown> extends CallAr
|
|
|
347
367
|
*
|
|
348
368
|
* @param added - The values to add or replace.
|
|
349
369
|
* @returns The result to return from the middleware. It rejects with whatever the
|
|
350
|
-
* rest of the call threw, including declared errors and `forbidden()`.
|
|
370
|
+
* rest of the call threw, including declared errors and outcomes such as `forbidden()`.
|
|
351
371
|
*/
|
|
352
372
|
<Added extends object>(added: Added & AdditionRule<Added>): Promise<MiddlewareResult<Added>>;
|
|
353
373
|
};
|
|
@@ -380,7 +400,8 @@ type AnyMiddleware = {
|
|
|
380
400
|
* in a procedure's `use` to run it for that procedure. A call runs the group's
|
|
381
401
|
* middleware with no input, then validates the input, then runs the procedure's
|
|
382
402
|
* middleware with the validated input, then the handler. Middleware runs for every
|
|
383
|
-
* call, also during server rendering, where `request` is the page request
|
|
403
|
+
* call, also during server rendering, where `request` is the page request, and when
|
|
404
|
+
* Angular prerenders a page, where it's a cookie-less `GET` of the page's URL.
|
|
384
405
|
*
|
|
385
406
|
* `run` must call `next()` exactly once and return its result: calling it twice or
|
|
386
407
|
* returning anything else fails the call with `INTERNAL`. `next(added)` merges `added`
|
|
@@ -393,9 +414,9 @@ type AnyMiddleware = {
|
|
|
393
414
|
* a `User`. `next()` rejects when anything after it throws, so `await next()` in a `try`
|
|
394
415
|
* wraps the rest of the call.
|
|
395
416
|
*
|
|
396
|
-
* Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN
|
|
397
|
-
*
|
|
398
|
-
* to handlers.
|
|
417
|
+
* Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN`, or answer it
|
|
418
|
+
* with `throw notFound()` or `throw redirect(to)`. Any other exception fails it with
|
|
419
|
+
* `INTERNAL` and is logged on the server. Declared errors belong to handlers.
|
|
399
420
|
*
|
|
400
421
|
* @example
|
|
401
422
|
* ```ts
|
|
@@ -432,7 +453,7 @@ type CheckChain<Base, Input, Use> = Use extends readonly [infer First, ...infer
|
|
|
432
453
|
...CheckChain<Flat<Merge<Base, Added>>, Input, Rest>
|
|
433
454
|
] : [never] : [];
|
|
434
455
|
/**
|
|
435
|
-
* A procedure created by a group's `query` or `
|
|
456
|
+
* A procedure created by a group's `query`, `mutation`, `stream` or `channel` builder.
|
|
436
457
|
*
|
|
437
458
|
* @remarks
|
|
438
459
|
* Procedures are values for `defineRpc`. Their types drive the generated client;
|
|
@@ -440,14 +461,20 @@ type CheckChain<Base, Input, Use> = Use extends readonly [infer First, ...infer
|
|
|
440
461
|
*
|
|
441
462
|
* @typeParam Input - The input schema, or `undefined` without input.
|
|
442
463
|
* @typeParam Output - The handler's return type.
|
|
443
|
-
* @typeParam Kind - Whether the procedure is a query or a
|
|
464
|
+
* @typeParam Kind - Whether the procedure is a query, a mutation, a stream or a channel.
|
|
444
465
|
* @typeParam Errors - The declared errors.
|
|
466
|
+
* @typeParam Message - A channel's message schema; `undefined` for the other kinds.
|
|
445
467
|
*/
|
|
446
|
-
export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}> {
|
|
447
|
-
/** Whether the procedure is a `"query"` or a `"
|
|
468
|
+
export interface Procedure<Input, Output, Kind extends ProcedureKind = "query", Errors extends ErrorDefinitions = {}, Message = undefined> {
|
|
469
|
+
/** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
|
|
448
470
|
readonly kind: Kind;
|
|
449
471
|
/** The input schema, or `undefined` for a procedure without input. */
|
|
450
472
|
readonly input: Input;
|
|
473
|
+
/**
|
|
474
|
+
* The schema a channel validates each message from its caller with; `undefined` for the
|
|
475
|
+
* other kinds.
|
|
476
|
+
*/
|
|
477
|
+
readonly message: Message;
|
|
451
478
|
/** The declared errors, as written in the procedure's options. */
|
|
452
479
|
readonly errors: Errors;
|
|
453
480
|
/** The procedure's middleware, in the order it runs. Empty when none was given. */
|
|
@@ -497,7 +524,49 @@ export interface ProcedureOptions<ContextValue, Input, Use extends readonly AnyM
|
|
|
497
524
|
}) => Output & JsonResult<NoInfer<Output>>;
|
|
498
525
|
}
|
|
499
526
|
/**
|
|
500
|
-
* The
|
|
527
|
+
* The options a group's `stream` builder takes: those of `query`, with a handler that
|
|
528
|
+
* returns an async iterable, usually an `async function*`.
|
|
529
|
+
*/
|
|
530
|
+
export interface StreamOptions<ContextValue, Input, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
|
|
531
|
+
/**
|
|
532
|
+
* Runs the stream: each value it yields is sent to the caller as strict JSON, until it
|
|
533
|
+
* returns or throws.
|
|
534
|
+
*/
|
|
535
|
+
readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
|
|
536
|
+
/** One factory per declared error code, creating an error to `throw`. */
|
|
537
|
+
readonly errors: ErrorFactories<Errors>;
|
|
538
|
+
}) => Output & StreamResult<NoInfer<Output>>;
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* The options a group's `channel` builder takes: those of `stream`, with a required
|
|
542
|
+
* `message` schema and a handler that also receives the caller's `messages`.
|
|
543
|
+
*/
|
|
544
|
+
export interface ChannelOptions<ContextValue, Input, Message, Use extends readonly AnyMiddleware[], Output, Errors extends ErrorDefinitions> extends Omit<ProcedureOptions<ContextValue, Input, Use, Output, Errors>, "handler"> {
|
|
545
|
+
/**
|
|
546
|
+
* The schema the server validates each message from the caller with, when the handler
|
|
547
|
+
* reads it. Its caller input type is what the client's `send` takes.
|
|
548
|
+
*/
|
|
549
|
+
readonly message: Message & MessageContract<NoInfer<Message>>;
|
|
550
|
+
/**
|
|
551
|
+
* Runs the channel: each value it yields is sent to the caller as strict JSON, until it
|
|
552
|
+
* returns or throws.
|
|
553
|
+
*/
|
|
554
|
+
readonly handler: (args: CallArgs<ContextAfter<ContextValue, Use>, OutputOf<Input>> & {
|
|
555
|
+
/** One factory per declared error code, creating an error to `throw`. */
|
|
556
|
+
readonly errors: ErrorFactories<Errors>;
|
|
557
|
+
/**
|
|
558
|
+
* The caller's messages, validated with `message` as they're read, in arrival order.
|
|
559
|
+
*
|
|
560
|
+
* @remarks
|
|
561
|
+
* One consumer only: a second iterator throws. Iteration ends when the caller closes
|
|
562
|
+
* the channel. A message that fails validation ends the call with `INVALID_INPUT` and
|
|
563
|
+
* the schema's issues.
|
|
564
|
+
*/
|
|
565
|
+
readonly messages: AsyncIterable<OutputOf<Message>>;
|
|
566
|
+
}) => Output & StreamResult<NoInfer<Output>>;
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* The `query`, `mutation`, `stream` and `channel` builders `defineRpc` passes to its callback.
|
|
501
570
|
*
|
|
502
571
|
* @remarks
|
|
503
572
|
* Function properties rather than methods, so destructuring them is safe.
|
|
@@ -509,14 +578,14 @@ export interface ProcedureBuilder<ContextValue> {
|
|
|
509
578
|
* Defines a procedure that reads data.
|
|
510
579
|
*
|
|
511
580
|
* @remarks
|
|
512
|
-
* The handler receives `{ context, input, errors, request, signal }`: the
|
|
513
|
-
* after the group's and the procedure's middleware, the validated input
|
|
514
|
-
* without an input schema), the error factories for the declared errors,
|
|
515
|
-
* the call runs in and its
|
|
581
|
+
* The handler receives `{ context, input, errors, request, signal, response }`: the
|
|
582
|
+
* context after the group's and the procedure's middleware, the validated input
|
|
583
|
+
* (`undefined` without an input schema), the error factories for the declared errors,
|
|
584
|
+
* the request the call runs in, its abort signal and its response cookies and headers. Inputs and results must be strict JSON; a
|
|
516
585
|
* result that isn't fails the call with `INTERNAL`. Throwing an error created by
|
|
517
|
-
* `errors` returns that declared error,
|
|
518
|
-
* `FORBIDDEN
|
|
519
|
-
* server.
|
|
586
|
+
* `errors` returns that declared error, throwing `forbidden()` fails the call with
|
|
587
|
+
* `FORBIDDEN`, and throwing `notFound()` or `redirect(to)` answers it with that outcome;
|
|
588
|
+
* any other exception fails the call with `INTERNAL` and is logged on the server.
|
|
520
589
|
*
|
|
521
590
|
* An explicit `input` schema must have a concrete type, without `undefined`, `null`,
|
|
522
591
|
* `any` or `unknown` branches, or generation fails: `Schema<string> | undefined` is
|
|
@@ -572,6 +641,65 @@ export interface ProcedureBuilder<ContextValue> {
|
|
|
572
641
|
* @throws TypeError when a declared error is invalid, as for `query`.
|
|
573
642
|
*/
|
|
574
643
|
readonly mutation: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output = unknown, const Errors extends ErrorDefinitions = {}>(options: ProcedureOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "mutation", Errors>;
|
|
644
|
+
/**
|
|
645
|
+
* Defines a procedure that sends values while it runs: a stream.
|
|
646
|
+
*
|
|
647
|
+
* @remarks
|
|
648
|
+
* Takes the same options as `query`, except that the handler returns an async iterable,
|
|
649
|
+
* usually written as `handler: async function* ({ context, input, signal }) { … }`. Each
|
|
650
|
+
* value it yields reaches the caller as soon as it's yielded.
|
|
651
|
+
*
|
|
652
|
+
* The stream's response starts once the handler returned its iterable, so cookies must
|
|
653
|
+
* be set before that: in middleware before `next()`, or in a handler that isn't a
|
|
654
|
+
* generator. Setting one later throws, and later header changes are ignored.
|
|
655
|
+
*
|
|
656
|
+
* @example
|
|
657
|
+
* ```ts
|
|
658
|
+
* watch: stream({
|
|
659
|
+
* input: idSchema,
|
|
660
|
+
* handler: async function* ({ context, input, signal }) {
|
|
661
|
+
* for await (const chat of context.chats.changes(input.id, { signal })) {
|
|
662
|
+
* yield chat;
|
|
663
|
+
* }
|
|
664
|
+
* },
|
|
665
|
+
* }),
|
|
666
|
+
* ```
|
|
667
|
+
*/
|
|
668
|
+
readonly stream: <Input extends Schema | undefined = undefined, const Use extends readonly AnyMiddleware[] = [], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: StreamOptions<ContextValue, Input, Use, Output, Errors>) => Procedure<Input, Output, "stream", Errors>;
|
|
669
|
+
/**
|
|
670
|
+
* Defines a procedure that talks both ways over a websocket: a channel.
|
|
671
|
+
*
|
|
672
|
+
* @remarks
|
|
673
|
+
* Takes a stream's options plus a required `message` schema. The handler is a stream
|
|
674
|
+
* handler that also receives `messages`, the caller's messages validated with `message` as
|
|
675
|
+
* it reads them, written as `handler: async function* ({ context, input, messages }) { … }`.
|
|
676
|
+
* Each value it yields reaches the caller as soon as the caller has room for it; a slow
|
|
677
|
+
* reader pauses the handler at its `yield`, and a handler that stops reading `messages`
|
|
678
|
+
* makes the caller's `send` wait.
|
|
679
|
+
*
|
|
680
|
+
* The call runs over `GET /_rpc/<namespace>/<procedure>?input=…` upgraded to a websocket by
|
|
681
|
+
* the generated `handleUpgrade`, not `handleRequest`. Middleware, input validation and the
|
|
682
|
+
* handler run before the upgrade's `101` response, which carries the call's cookies and
|
|
683
|
+
* headers, so cookies follow a stream's rules: set them in middleware before `next()` or in
|
|
684
|
+
* a handler that isn't a generator. During server rendering a channel fails with
|
|
685
|
+
* `FORBIDDEN` before any middleware runs.
|
|
686
|
+
*
|
|
687
|
+
* @example
|
|
688
|
+
* ```ts
|
|
689
|
+
* talk: channel({
|
|
690
|
+
* input: chatSchema,
|
|
691
|
+
* message: textSchema,
|
|
692
|
+
* handler: async function* ({ context, input, messages, signal }) {
|
|
693
|
+
* yield { kind: "history", messages: await context.chats.history(input.chatId) };
|
|
694
|
+
*
|
|
695
|
+
* for await (const message of messages) {
|
|
696
|
+
* yield { kind: "answer", text: await context.chats.answer(input.chatId, message.text, signal) };
|
|
697
|
+
* }
|
|
698
|
+
* },
|
|
699
|
+
* }),
|
|
700
|
+
* ```
|
|
701
|
+
*/
|
|
702
|
+
readonly channel: <Input extends Schema | undefined = undefined, Message extends Schema = Schema, const Use extends readonly AnyMiddleware[] = [], Output extends AsyncIterable<unknown> = AsyncIterable<unknown>, const Errors extends ErrorDefinitions = {}>(options: ChannelOptions<ContextValue, Input, Message, Use, Output, Errors>) => Procedure<Input, Output, "channel", Errors, Message>;
|
|
575
703
|
}
|
|
576
704
|
/**
|
|
577
705
|
* The minimal shape `defineRpc` accepts for each procedure.
|
|
@@ -581,7 +709,7 @@ export interface ProcedureBuilder<ContextValue> {
|
|
|
581
709
|
* callback; generation rejects any other value.
|
|
582
710
|
*/
|
|
583
711
|
export interface ProcedureDefinition {
|
|
584
|
-
/** Whether the procedure is a `"query"` or a `"
|
|
712
|
+
/** Whether the procedure is a `"query"`, a `"mutation"`, a `"stream"` or a `"channel"`. */
|
|
585
713
|
readonly kind: ProcedureKind;
|
|
586
714
|
}
|
|
587
715
|
/**
|
package/server/definitions.js
CHANGED
|
@@ -12,6 +12,10 @@ import { createErrors, declaredFailures } from "./errors.js";
|
|
|
12
12
|
* and RPC requests alike, and its value is the `context` middleware and handlers start
|
|
13
13
|
* from. Keep per-request state in the context rather than in module variables.
|
|
14
14
|
*
|
|
15
|
+
* When Angular prerenders a page that calls an RPC, the factory runs at build time with a
|
|
16
|
+
* cookie-less `GET` of the page's URL on a local origin Angular picks, so a prerendered
|
|
17
|
+
* page shows what an anonymous visitor would see.
|
|
18
|
+
*
|
|
15
19
|
* @example
|
|
16
20
|
* ```ts
|
|
17
21
|
* import { defineContext } from "@loozo/angular-launch/server";
|
|
@@ -39,7 +43,8 @@ export function defineContext(create) {
|
|
|
39
43
|
* in a procedure's `use` to run it for that procedure. A call runs the group's
|
|
40
44
|
* middleware with no input, then validates the input, then runs the procedure's
|
|
41
45
|
* middleware with the validated input, then the handler. Middleware runs for every
|
|
42
|
-
* call, also during server rendering, where `request` is the page request
|
|
46
|
+
* call, also during server rendering, where `request` is the page request, and when
|
|
47
|
+
* Angular prerenders a page, where it's a cookie-less `GET` of the page's URL.
|
|
43
48
|
*
|
|
44
49
|
* `run` must call `next()` exactly once and return its result: calling it twice or
|
|
45
50
|
* returning anything else fails the call with `INTERNAL`. `next(added)` merges `added`
|
|
@@ -52,9 +57,9 @@ export function defineContext(create) {
|
|
|
52
57
|
* a `User`. `next()` rejects when anything after it throws, so `await next()` in a `try`
|
|
53
58
|
* wraps the rest of the call.
|
|
54
59
|
*
|
|
55
|
-
* Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN
|
|
56
|
-
*
|
|
57
|
-
* to handlers.
|
|
60
|
+
* Refuse a call with `throw forbidden()`, which fails it with `FORBIDDEN`, or answer it
|
|
61
|
+
* with `throw notFound()` or `throw redirect(to)`. Any other exception fails it with
|
|
62
|
+
* `INTERNAL` and is logged on the server. Declared errors belong to handlers.
|
|
58
63
|
*
|
|
59
64
|
* @example
|
|
60
65
|
* ```ts
|
|
@@ -80,12 +85,13 @@ export function defineContext(create) {
|
|
|
80
85
|
export function middleware(run) {
|
|
81
86
|
return { run };
|
|
82
87
|
}
|
|
83
|
-
function procedure(kind, { input, use = [], errors = {}, handler }) {
|
|
88
|
+
function procedure(kind, { input, message, use = [], errors = {}, handler }) {
|
|
84
89
|
const { factories, failures } = createErrors(errors);
|
|
85
90
|
const run = handler;
|
|
86
91
|
return {
|
|
87
92
|
kind,
|
|
88
93
|
input,
|
|
94
|
+
message,
|
|
89
95
|
errors,
|
|
90
96
|
use,
|
|
91
97
|
handler: (args) => run({ ...args, errors: factories }),
|
|
@@ -96,6 +102,8 @@ function procedure(kind, { input, use = [], errors = {}, handler }) {
|
|
|
96
102
|
const builder = {
|
|
97
103
|
query: (options) => procedure("query", options),
|
|
98
104
|
mutation: (options) => procedure("mutation", options),
|
|
105
|
+
stream: (options) => procedure("stream", options),
|
|
106
|
+
channel: (options) => procedure("channel", options),
|
|
99
107
|
};
|
|
100
108
|
/**
|
|
101
109
|
* Defines the RPC group for the route declared in the same directory.
|