@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,173 @@
|
|
|
1
|
+
import { serializeJson } from "../json.js";
|
|
2
|
+
/** How often a stream sends a comment, so idle proxies keep its connection open. */
|
|
3
|
+
export const keepAliveMs = 15_000;
|
|
4
|
+
/**
|
|
5
|
+
* Ends the handler's part of a stream or channel that stopped early, such as when its caller
|
|
6
|
+
* went away.
|
|
7
|
+
*
|
|
8
|
+
* @remarks
|
|
9
|
+
* Internal. Lets the handler's pending step finish, then asks the iterator to return, which
|
|
10
|
+
* runs a generator's `finally` blocks. The step's failure, if any, settles the call, but only
|
|
11
|
+
* after that cleanup ran.
|
|
12
|
+
*
|
|
13
|
+
* @param start - The started stream or channel.
|
|
14
|
+
* @param pending - The handler's last requested step, if any.
|
|
15
|
+
*/
|
|
16
|
+
export async function settleStopped(start, pending) {
|
|
17
|
+
let failure;
|
|
18
|
+
try {
|
|
19
|
+
const step = await pending;
|
|
20
|
+
if (step?.done) {
|
|
21
|
+
start.finished.resolve();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
failure = { error };
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
await start.iterator.return?.();
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (failure === undefined) {
|
|
33
|
+
failure = { error };
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
console.error("Launch stream failed while returning", error);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (failure === undefined) {
|
|
40
|
+
start.finished.resolve();
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
start.finished.reject(failure.error);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The frame that ends a failed stream or channel: the reply's body with its status, as
|
|
48
|
+
* `{ status, error }`, `{ status, redirect }` or `{ status, notFound }`.
|
|
49
|
+
*
|
|
50
|
+
* @param reply - The call's failure reply.
|
|
51
|
+
* @returns The frame as strict JSON text.
|
|
52
|
+
*/
|
|
53
|
+
export function failureFrame(reply) {
|
|
54
|
+
return serializeJson({ status: reply.status, ...reply.body });
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The `text/event-stream` body of a started stream.
|
|
58
|
+
*
|
|
59
|
+
* @remarks
|
|
60
|
+
* Internal. Sends one `value` event per yielded value, then, once the whole call settled
|
|
61
|
+
* (`outcome`, middleware included), one `end` event or one `error` event whose data is
|
|
62
|
+
* the reply's frame with its status: `{ status, error }`, `{ status, redirect }` or
|
|
63
|
+
* `{ status, notFound }`. A comment goes out every {@link keepAliveMs}.
|
|
64
|
+
*
|
|
65
|
+
* Pull-based, so a slow reader pauses the handler. A yielded value that isn't strict JSON
|
|
66
|
+
* fails the call. The stream stops when `signal` aborts, which it does when the host
|
|
67
|
+
* cancels the body or aborts the request: the body errors, the handler's pending step is
|
|
68
|
+
* awaited and the iterator asked to return, which runs a generator's `finally` blocks once
|
|
69
|
+
* it next yields. The handler's part of the call then ends, with the failure if that step
|
|
70
|
+
* threw, so middleware that wraps the stream never cleans up under a running handler.
|
|
71
|
+
*
|
|
72
|
+
* @param start - The started stream.
|
|
73
|
+
* @param outcome - The whole call's reply, from `dispatch`.
|
|
74
|
+
* @param cancel - Aborted when the body is cancelled.
|
|
75
|
+
* @param signal - The call's signal: it follows `cancel` and the request's signal.
|
|
76
|
+
* @returns The response body.
|
|
77
|
+
*/
|
|
78
|
+
export function eventStream(start, outcome, cancel, signal) {
|
|
79
|
+
const encoder = new TextEncoder();
|
|
80
|
+
let closed = false;
|
|
81
|
+
// Set once something has taken charge of settling `start.finished`.
|
|
82
|
+
let ending = false;
|
|
83
|
+
let pending;
|
|
84
|
+
let keepAlive;
|
|
85
|
+
let stopped;
|
|
86
|
+
function stop() {
|
|
87
|
+
closed = true;
|
|
88
|
+
clearInterval(keepAlive);
|
|
89
|
+
signal.removeEventListener("abort", stopped);
|
|
90
|
+
}
|
|
91
|
+
async function finish(controller) {
|
|
92
|
+
const reply = await outcome;
|
|
93
|
+
if (closed) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (reply.status === 200) {
|
|
97
|
+
controller.enqueue(encoder.encode("event: end\ndata: null\n\n"));
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
controller.enqueue(encoder.encode(`event: error\ndata: ${failureFrame(reply)}\n\n`));
|
|
101
|
+
}
|
|
102
|
+
stop();
|
|
103
|
+
controller.close();
|
|
104
|
+
}
|
|
105
|
+
return new ReadableStream({
|
|
106
|
+
start(controller) {
|
|
107
|
+
stopped = () => {
|
|
108
|
+
if (closed) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
stop();
|
|
112
|
+
controller.error(signal.reason);
|
|
113
|
+
if (!ending) {
|
|
114
|
+
ending = true;
|
|
115
|
+
void settleStopped(start, pending);
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
// The request may already be gone, such as while middleware ran.
|
|
119
|
+
if (signal.aborted) {
|
|
120
|
+
stopped();
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
signal.addEventListener("abort", stopped, { once: true });
|
|
124
|
+
keepAlive = setInterval(() => {
|
|
125
|
+
controller.enqueue(encoder.encode(": keep-alive\n\n"));
|
|
126
|
+
}, keepAliveMs);
|
|
127
|
+
},
|
|
128
|
+
async pull(controller) {
|
|
129
|
+
// A custom iterator's next() may throw instead of rejecting.
|
|
130
|
+
const next = new Promise((resolve) => {
|
|
131
|
+
resolve(start.iterator.next());
|
|
132
|
+
});
|
|
133
|
+
let step;
|
|
134
|
+
pending = next;
|
|
135
|
+
try {
|
|
136
|
+
step = await next;
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
// A stopped stream settles with this failure itself.
|
|
140
|
+
if (!closed) {
|
|
141
|
+
ending = true;
|
|
142
|
+
start.finished.reject(error);
|
|
143
|
+
await finish(controller);
|
|
144
|
+
}
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (closed) {
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (step.done) {
|
|
151
|
+
ending = true;
|
|
152
|
+
start.finished.resolve();
|
|
153
|
+
await finish(controller);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
let data;
|
|
157
|
+
try {
|
|
158
|
+
data = serializeJson(step.value);
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
// The handler is still suspended at its yield.
|
|
162
|
+
ending = true;
|
|
163
|
+
void Promise.resolve(start.iterator.return?.()).then(() => start.finished.reject(error), start.finished.reject);
|
|
164
|
+
await finish(controller);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
controller.enqueue(encoder.encode(`event: value\ndata: ${data}\n\n`));
|
|
168
|
+
},
|
|
169
|
+
cancel(reason) {
|
|
170
|
+
cancel.abort(reason);
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
}
|
package/server/generated.d.ts
CHANGED
package/server/generated.js
CHANGED
package/server/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { defineContext, defineRpc, middleware } from "./definitions.js";
|
|
2
|
-
export { forbidden } from "./outcomes.js";
|
|
3
|
-
export type { Register, CallArgs, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, Schema, } from "./definitions.js";
|
|
2
|
+
export { forbidden, notFound, redirect } from "./outcomes.js";
|
|
3
|
+
export type { Register, CallArgs, ChannelOptions, Context, ContextOf, ContextDefinition, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, Group, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, StreamOptions, Schema, } from "./definitions.js";
|
|
4
4
|
export type { DeclaredFailure } from "./errors.js";
|
|
5
|
+
export type { CookieOptions, ResponseControl } from "./response-effects.js";
|
|
5
6
|
export type { JsonShape } from "../json.js";
|
|
6
7
|
export type { HandleOptions, RequestScope } from "./dispatch.js";
|
|
8
|
+
export type { Upgrade } from "./upgrade.js";
|
|
7
9
|
export { finishLaunchRendering } from "./backend.js";
|
package/server/index.js
CHANGED
package/server/outcomes.d.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
/** What a thrown outcome asks the server to answer with. Internal. */
|
|
2
|
-
export
|
|
2
|
+
export type Outcome = {
|
|
3
3
|
readonly kind: "forbidden";
|
|
4
|
-
}
|
|
4
|
+
} | {
|
|
5
|
+
readonly kind: "notFound";
|
|
6
|
+
} | {
|
|
7
|
+
readonly kind: "redirect";
|
|
8
|
+
readonly to: string;
|
|
9
|
+
};
|
|
5
10
|
/**
|
|
6
11
|
* Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
|
|
7
12
|
* or a handler.
|
|
@@ -16,6 +21,50 @@ export interface Outcome {
|
|
|
16
21
|
* @returns The error to `throw`.
|
|
17
22
|
*/
|
|
18
23
|
export declare function forbidden(): Error;
|
|
24
|
+
/**
|
|
25
|
+
* Creates an error that answers the call as not found when thrown from middleware or a
|
|
26
|
+
* handler.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* The caller's call rejects with `RpcNotFound` from `@loozo/angular-launch`. In a guard or
|
|
30
|
+
* resolver, `rpcNavigationErrors()` renders the app's not-found page at the requested URL,
|
|
31
|
+
* with status 404 during server rendering. It isn't an error code: use it for a missing
|
|
32
|
+
* resource the page can't show, and a declared error for one the page handles itself.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* ```ts
|
|
36
|
+
* if (chat === null) {
|
|
37
|
+
* throw notFound();
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*
|
|
41
|
+
* @returns The error to `throw`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function notFound(): Error;
|
|
44
|
+
/**
|
|
45
|
+
* Creates an error that answers the call with a redirect to `to` when thrown from
|
|
46
|
+
* middleware or a handler.
|
|
47
|
+
*
|
|
48
|
+
* @remarks
|
|
49
|
+
* The caller's call rejects with `RpcRedirect` from `@loozo/angular-launch`. In a guard or
|
|
50
|
+
* resolver, `rpcNavigationErrors()` navigates to `to` instead, which during server
|
|
51
|
+
* rendering answers the page request with a 302. Nothing navigates outside navigation.
|
|
52
|
+
* Only root-relative app URLs, such as `createUrl` builds, are accepted; an external
|
|
53
|
+
* redirect (OAuth, for example) is data the page acts on.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* if (context.user === null) {
|
|
58
|
+
* throw redirect(createUrl(signIn, {}));
|
|
59
|
+
* }
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* @param to - The root-relative URL to go to, such as `/sign-in?next=%2Ftodos`.
|
|
63
|
+
* @returns The error to `throw`.
|
|
64
|
+
* @throws TypeError when `to` isn't a root-relative URL of the same origin, such as
|
|
65
|
+
* `https://example.com/`, `//example.com/` or `/\example.com/`.
|
|
66
|
+
*/
|
|
67
|
+
export declare function redirect(to: `/${string}`): Error;
|
|
19
68
|
/**
|
|
20
69
|
* Reads the outcome a thrown value carries, if it was created by an outcome factory.
|
|
21
70
|
* Internal.
|
package/server/outcomes.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
|
+
import { isRootRelative } from "../outcomes.js";
|
|
1
2
|
// Keyed with Symbol.for so the brand survives the duplicate module copies a native SSR
|
|
2
3
|
// bundle may load, and non-enumerable so it never reaches JSON.
|
|
3
4
|
const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
|
|
5
|
+
function outcomeError(message, outcome) {
|
|
6
|
+
const error = new Error(message);
|
|
7
|
+
Object.defineProperty(error, outcomeKey, { value: outcome });
|
|
8
|
+
return error;
|
|
9
|
+
}
|
|
4
10
|
/**
|
|
5
11
|
* Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
|
|
6
12
|
* or a handler.
|
|
@@ -15,10 +21,58 @@ const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
|
|
|
15
21
|
* @returns The error to `throw`.
|
|
16
22
|
*/
|
|
17
23
|
export function forbidden() {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
24
|
+
return outcomeError("RPC forbidden", { kind: "forbidden" });
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Creates an error that answers the call as not found when thrown from middleware or a
|
|
28
|
+
* handler.
|
|
29
|
+
*
|
|
30
|
+
* @remarks
|
|
31
|
+
* The caller's call rejects with `RpcNotFound` from `@loozo/angular-launch`. In a guard or
|
|
32
|
+
* resolver, `rpcNavigationErrors()` renders the app's not-found page at the requested URL,
|
|
33
|
+
* with status 404 during server rendering. It isn't an error code: use it for a missing
|
|
34
|
+
* resource the page can't show, and a declared error for one the page handles itself.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* if (chat === null) {
|
|
39
|
+
* throw notFound();
|
|
40
|
+
* }
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* @returns The error to `throw`.
|
|
44
|
+
*/
|
|
45
|
+
export function notFound() {
|
|
46
|
+
return outcomeError("RPC not found outcome", { kind: "notFound" });
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Creates an error that answers the call with a redirect to `to` when thrown from
|
|
50
|
+
* middleware or a handler.
|
|
51
|
+
*
|
|
52
|
+
* @remarks
|
|
53
|
+
* The caller's call rejects with `RpcRedirect` from `@loozo/angular-launch`. In a guard or
|
|
54
|
+
* resolver, `rpcNavigationErrors()` navigates to `to` instead, which during server
|
|
55
|
+
* rendering answers the page request with a 302. Nothing navigates outside navigation.
|
|
56
|
+
* Only root-relative app URLs, such as `createUrl` builds, are accepted; an external
|
|
57
|
+
* redirect (OAuth, for example) is data the page acts on.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* if (context.user === null) {
|
|
62
|
+
* throw redirect(createUrl(signIn, {}));
|
|
63
|
+
* }
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* @param to - The root-relative URL to go to, such as `/sign-in?next=%2Ftodos`.
|
|
67
|
+
* @returns The error to `throw`.
|
|
68
|
+
* @throws TypeError when `to` isn't a root-relative URL of the same origin, such as
|
|
69
|
+
* `https://example.com/`, `//example.com/` or `/\example.com/`.
|
|
70
|
+
*/
|
|
71
|
+
export function redirect(to) {
|
|
72
|
+
if (!isRootRelative(to)) {
|
|
73
|
+
throw new TypeError(`redirect() takes a root-relative URL, not ${JSON.stringify(to)}`);
|
|
74
|
+
}
|
|
75
|
+
return outcomeError("RPC redirect outcome", { kind: "redirect", to });
|
|
22
76
|
}
|
|
23
77
|
/**
|
|
24
78
|
* Reads the outcome a thrown value carries, if it was created by an outcome factory.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The attributes of a cookie set with {@link ResponseControl.setCookie}.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* The defaults make a first-party session cookie: `Path=/; HttpOnly; Secure; SameSite=Lax`.
|
|
6
|
+
* Browsers keep `Secure` cookies from `http://localhost` too, so the defaults also work in
|
|
7
|
+
* development; a plain-HTTP deployment on another hostname needs `secure: false`.
|
|
8
|
+
*/
|
|
9
|
+
export interface CookieOptions {
|
|
10
|
+
/** The cookie's path. Defaults to `/`. */
|
|
11
|
+
readonly path?: string;
|
|
12
|
+
/** The cookie's domain. Defaults to none, so the cookie is host-only. */
|
|
13
|
+
readonly domain?: string;
|
|
14
|
+
/** Seconds until the cookie expires, as an integer. Defaults to none: a session cookie. */
|
|
15
|
+
readonly maxAge?: number;
|
|
16
|
+
/** When the cookie expires. Defaults to none: a session cookie. */
|
|
17
|
+
readonly expires?: Date;
|
|
18
|
+
/** Hides the cookie from page scripts. Defaults to `true`. */
|
|
19
|
+
readonly httpOnly?: boolean;
|
|
20
|
+
/** Sends the cookie over HTTPS only. Defaults to `true`. */
|
|
21
|
+
readonly secure?: boolean;
|
|
22
|
+
/** The cookie's `SameSite` attribute. Defaults to `"lax"`; `"none"` needs `secure`. */
|
|
23
|
+
readonly sameSite?: "lax" | "strict" | "none";
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The response effects of one call: cookies and headers, as `response` in middleware and
|
|
27
|
+
* handler arguments.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Over HTTP, cookies and headers go on the RPC response for every outcome, failures
|
|
31
|
+
* included. Launch's own headers (`Content-Type`, `Cache-Control`, `Vary`,
|
|
32
|
+
* `X-Content-Type-Options`, and a stream's `X-Accel-Buffering`) replace the same headers
|
|
33
|
+
* set here, and the status can't be set.
|
|
34
|
+
*
|
|
35
|
+
* During server rendering, cookies go on the page response, a redirect included, and
|
|
36
|
+
* headers are dropped: a page's headers mustn't depend on which queries it ran. Angular
|
|
37
|
+
* copies the page's headers once the app is first stable, so the cookies of a call that
|
|
38
|
+
* settles later, such as one awaited in a `BEFORE_APP_SERIALIZED` hook, are lost. A page
|
|
39
|
+
* Angular prerenders has no response, so a cookie set before the app is first stable fails
|
|
40
|
+
* the build.
|
|
41
|
+
*
|
|
42
|
+
* The effects are sent once the call settled, or, for a stream, once its handler returned
|
|
43
|
+
* its iterable. After that, setting a cookie throws, and header changes are ignored. So a
|
|
44
|
+
* stream sets its cookies in middleware before `next()`, or in a handler that isn't a
|
|
45
|
+
* generator, before it returns its iterable: an `async function*` handler's body runs
|
|
46
|
+
* after its response started.
|
|
47
|
+
*
|
|
48
|
+
* Its members are function properties, so destructuring them is safe.
|
|
49
|
+
*/
|
|
50
|
+
export interface ResponseControl {
|
|
51
|
+
/**
|
|
52
|
+
* Headers for the RPC response. Ignored during server rendering.
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* Use {@link ResponseControl.setCookie} for cookies: a `Set-Cookie` header written here
|
|
56
|
+
* is dropped during server rendering like any other header.
|
|
57
|
+
*/
|
|
58
|
+
readonly headers: Headers;
|
|
59
|
+
/**
|
|
60
|
+
* Sets a cookie on the response.
|
|
61
|
+
*
|
|
62
|
+
* @param name - The cookie name: an HTTP token.
|
|
63
|
+
* @param value - The cookie value, already encoded: printable ASCII without spaces,
|
|
64
|
+
* `"`, `,`, `;` or `\`.
|
|
65
|
+
* @param options - The cookie's attributes.
|
|
66
|
+
* @throws TypeError for an invalid name, value or attribute, or `"none"` same-site
|
|
67
|
+
* without `secure`; Error after the response was sent.
|
|
68
|
+
*/
|
|
69
|
+
readonly setCookie: (name: string, value: string, options?: CookieOptions) => void;
|
|
70
|
+
/**
|
|
71
|
+
* Deletes a cookie by setting it expired.
|
|
72
|
+
*
|
|
73
|
+
* @remarks
|
|
74
|
+
* Pass the path, domain and security attributes the cookie was set with, or the browser
|
|
75
|
+
* keeps it.
|
|
76
|
+
*
|
|
77
|
+
* @param name - The cookie name.
|
|
78
|
+
* @param options - The attributes the cookie was set with.
|
|
79
|
+
* @throws As {@link ResponseControl.setCookie}.
|
|
80
|
+
*/
|
|
81
|
+
readonly deleteCookie: (name: string, options?: Omit<CookieOptions, "maxAge" | "expires">) => void;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The response effects one call collects. Internal.
|
|
85
|
+
*
|
|
86
|
+
* @remarks
|
|
87
|
+
* The transport that created them passes `control` to `dispatch`, calls `commit` when it
|
|
88
|
+
* produces the response, and reads `cookies` and `headers` then.
|
|
89
|
+
*/
|
|
90
|
+
export interface ResponseEffects {
|
|
91
|
+
/** The view middleware and handlers receive as `response`. */
|
|
92
|
+
readonly control: ResponseControl;
|
|
93
|
+
/** The serialized `Set-Cookie` values, in order. */
|
|
94
|
+
readonly cookies: readonly string[];
|
|
95
|
+
/** The headers set through `control`. */
|
|
96
|
+
readonly headers: Headers;
|
|
97
|
+
/** Marks the response as sent: setting a cookie throws from now on. */
|
|
98
|
+
commit(): void;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Creates the response effects for one call. Internal.
|
|
102
|
+
*
|
|
103
|
+
* @returns Effects with no cookies or headers.
|
|
104
|
+
*/
|
|
105
|
+
export declare function createResponseEffects(): ResponseEffects;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// RFC 9110 token.
|
|
2
|
+
const cookieName = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
3
|
+
// RFC 6265 cookie-octet.
|
|
4
|
+
const cookieValue = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]*$/;
|
|
5
|
+
// RFC 6265 path-value and domain: any CHAR except controls and ";".
|
|
6
|
+
const attributeValue = /^[\x20-\x3A\x3C-\x7E]+$/;
|
|
7
|
+
function serializeCookie(name, value, options) {
|
|
8
|
+
const { path = "/", domain, maxAge, expires, httpOnly = true, secure = true, sameSite = "lax", } = options;
|
|
9
|
+
if (!cookieName.test(name)) {
|
|
10
|
+
throw new TypeError(`Invalid cookie name ${JSON.stringify(name)}`);
|
|
11
|
+
}
|
|
12
|
+
if (!cookieValue.test(value)) {
|
|
13
|
+
throw new TypeError(`Invalid value for cookie ${name}; encode it first`);
|
|
14
|
+
}
|
|
15
|
+
if (!attributeValue.test(path) || (domain !== undefined && !attributeValue.test(domain))) {
|
|
16
|
+
throw new TypeError(`Invalid path or domain for cookie ${name}`);
|
|
17
|
+
}
|
|
18
|
+
if (maxAge !== undefined && !Number.isInteger(maxAge)) {
|
|
19
|
+
throw new TypeError(`Cookie ${name}'s maxAge must be an integer`);
|
|
20
|
+
}
|
|
21
|
+
if (expires !== undefined && Number.isNaN(expires.getTime())) {
|
|
22
|
+
throw new TypeError(`Cookie ${name}'s expires is an invalid date`);
|
|
23
|
+
}
|
|
24
|
+
if (sameSite === "none" && !secure) {
|
|
25
|
+
throw new TypeError(`Cookie ${name} needs secure for sameSite "none"`);
|
|
26
|
+
}
|
|
27
|
+
let cookie = `${name}=${value}; Path=${path}`;
|
|
28
|
+
if (domain !== undefined) {
|
|
29
|
+
cookie += `; Domain=${domain}`;
|
|
30
|
+
}
|
|
31
|
+
if (maxAge !== undefined) {
|
|
32
|
+
cookie += `; Max-Age=${maxAge}`;
|
|
33
|
+
}
|
|
34
|
+
if (expires !== undefined) {
|
|
35
|
+
cookie += `; Expires=${expires.toUTCString()}`;
|
|
36
|
+
}
|
|
37
|
+
if (httpOnly) {
|
|
38
|
+
cookie += "; HttpOnly";
|
|
39
|
+
}
|
|
40
|
+
if (secure) {
|
|
41
|
+
cookie += "; Secure";
|
|
42
|
+
}
|
|
43
|
+
const sameSiteNames = { lax: "Lax", strict: "Strict", none: "None" };
|
|
44
|
+
return `${cookie}; SameSite=${sameSiteNames[sameSite]}`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Creates the response effects for one call. Internal.
|
|
48
|
+
*
|
|
49
|
+
* @returns Effects with no cookies or headers.
|
|
50
|
+
*/
|
|
51
|
+
export function createResponseEffects() {
|
|
52
|
+
const cookies = [];
|
|
53
|
+
const headers = new Headers();
|
|
54
|
+
let committed = false;
|
|
55
|
+
function add(cookie) {
|
|
56
|
+
if (committed) {
|
|
57
|
+
throw new Error("Launch already sent this call's response; a stream sets cookies in middleware " +
|
|
58
|
+
"before next(), or in its handler before it returns its iterable");
|
|
59
|
+
}
|
|
60
|
+
cookies.push(cookie);
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
control: {
|
|
64
|
+
headers,
|
|
65
|
+
setCookie(name, value, options = {}) {
|
|
66
|
+
add(serializeCookie(name, value, options));
|
|
67
|
+
},
|
|
68
|
+
deleteCookie(name, options = {}) {
|
|
69
|
+
add(serializeCookie(name, "", { ...options, maxAge: 0, expires: new Date(0) }));
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
cookies,
|
|
73
|
+
headers,
|
|
74
|
+
commit() {
|
|
75
|
+
committed = true;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { ContextDefinition } from "./definitions.js";
|
|
2
|
+
import { type ApplicationBinding, type HandleOptions, type Registry } from "./dispatch.js";
|
|
3
|
+
/**
|
|
4
|
+
* A channel call that passed its checks: the host upgrades the request to a websocket and
|
|
5
|
+
* hands Launch the socket.
|
|
6
|
+
*
|
|
7
|
+
* @remarks
|
|
8
|
+
* Returned by the generated `handleUpgrade`. Send `headers` on the `101` response, then call
|
|
9
|
+
* `accept` with the socket. A call that failed before its handler returned its iterable is an
|
|
10
|
+
* `Upgrade` too: its socket gets the failure frame and closes, so the browser client sees the
|
|
11
|
+
* procedure's own error. `@loozo/angular-launch/node` does all of this for Node servers.
|
|
12
|
+
*/
|
|
13
|
+
export interface Upgrade {
|
|
14
|
+
/** Headers for the `101` response: the call's headers, and a `Set-Cookie` per cookie. */
|
|
15
|
+
readonly headers: Headers;
|
|
16
|
+
/**
|
|
17
|
+
* Runs the call on the socket the host accepted for this request.
|
|
18
|
+
*
|
|
19
|
+
* @param socket - The accepted socket, open or still connecting. Call this once, before or
|
|
20
|
+
* as the `101` goes out; if the caller left before, close the socket instead.
|
|
21
|
+
*/
|
|
22
|
+
readonly accept: (socket: WebSocket) => void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Answers a websocket upgrade request for a channel, or returns `null` for any other
|
|
26
|
+
* request.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* Internal: exported only from `@loozo/angular-launch/_server` for the generated
|
|
30
|
+
* `handleUpgrade` in `server.generated.ts`; call that instead.
|
|
31
|
+
*
|
|
32
|
+
* Any path starting with `/_rpc/` is a channel request. Before any context exists, the
|
|
33
|
+
* request is refused with an HTTP response, as `handleRequest` refuses RPCs: a plain-text 400
|
|
34
|
+
* `Host not allowed` when its hostname isn't in `allowedHosts`; `INVALID_INPUT` with no issues
|
|
35
|
+
* unless it's a `GET` with `Upgrade: websocket` and a query of exactly `input` holding JSON;
|
|
36
|
+
* and `FORBIDDEN` unless it's proven same-origin by `handleRequest`'s rules.
|
|
37
|
+
*
|
|
38
|
+
* A fresh context is then created and the call dispatched: `RPC_NOT_FOUND` for a path that
|
|
39
|
+
* isn't a channel, then group middleware, input validation, procedure middleware and the
|
|
40
|
+
* handler, which returns its iterable. From then on the result is an {@link Upgrade} carrying
|
|
41
|
+
* the call's headers and cookies; setting a cookie later throws. A failure before that,
|
|
42
|
+
* including a context factory that throws (`INTERNAL`), is an `Upgrade` too, whose socket
|
|
43
|
+
* receives the failure frame and closes with 1000.
|
|
44
|
+
*
|
|
45
|
+
* Until the socket is accepted the call's signal follows `request.signal`; a request that
|
|
46
|
+
* aborts before the handler is reached skips the handler, and one that aborts after it
|
|
47
|
+
* returned its iterable returns that iterator before its body ran. Either way the socket,
|
|
48
|
+
* if accepted, closes without a frame. Afterwards the signal follows the socket closing.
|
|
49
|
+
*
|
|
50
|
+
* @typeParam Definition - The application's context definition.
|
|
51
|
+
* @param registry - The application's RPC groups.
|
|
52
|
+
* @param application - The application binding.
|
|
53
|
+
* @param request - The upgrade request, as a web `Request`.
|
|
54
|
+
* @param options - The allowed hosts and further allowed origins.
|
|
55
|
+
* @returns A refusal response, the upgrade, or `null` when the path doesn't start with
|
|
56
|
+
* `/_rpc/`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function handleChannelUpgrade<Definition extends ContextDefinition<unknown>>(registry: Registry, application: ApplicationBinding<Definition>, request: Request, { allowedHosts, origins }: HandleOptions): Promise<Response | Upgrade | null>;
|