@loozo/angular-launch 0.0.5 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +1068 -187
  2. package/builders/application.js +32 -3
  3. package/builders/channel-forwarding.d.ts +15 -0
  4. package/builders/channel-forwarding.js +61 -0
  5. package/builders/options.d.ts +6 -2
  6. package/builders/options.js +16 -5
  7. package/builders/serve.js +198 -140
  8. package/channel.d.ts +55 -0
  9. package/channel.js +232 -0
  10. package/client.d.ts +63 -33
  11. package/connect.d.ts +201 -0
  12. package/connect.js +148 -0
  13. package/generation/index.d.ts +2 -123
  14. package/generation/index.js +3 -669
  15. package/generation/redirects.d.ts +14 -0
  16. package/generation/redirects.js +43 -0
  17. package/generation/run.d.ts +168 -0
  18. package/generation/run.js +659 -0
  19. package/index.d.ts +8 -1
  20. package/index.js +3 -0
  21. package/json.d.ts +9 -0
  22. package/json.js +24 -0
  23. package/launch-queries.d.ts +16 -0
  24. package/launch-queries.js +3 -0
  25. package/navigation.d.ts +36 -0
  26. package/navigation.js +47 -0
  27. package/node/index.d.ts +60 -0
  28. package/node/index.js +178 -0
  29. package/node/upgrade-listener-slot.d.ts +1 -0
  30. package/node/upgrade-listener-slot.js +4 -0
  31. package/outcomes.d.ts +71 -0
  32. package/outcomes.js +146 -0
  33. package/package.json +21 -11
  34. package/redirect-translation.d.ts +53 -0
  35. package/redirect-translation.js +141 -0
  36. package/{generated.d.ts → remote-client.d.ts} +1 -1
  37. package/remote-client.js +179 -0
  38. package/route-types.d.ts +130 -0
  39. package/route-types.js +1 -0
  40. package/route.d.ts +45 -0
  41. package/route.js +113 -0
  42. package/schemas/application.json +19 -3
  43. package/schemas/serve.json +3 -3
  44. package/server/application.d.ts +107 -0
  45. package/server/application.js +108 -0
  46. package/server/backend.d.ts +62 -31
  47. package/server/backend.js +149 -55
  48. package/server/channel-messages.d.ts +54 -0
  49. package/server/channel-messages.js +84 -0
  50. package/server/channel-socket.d.ts +67 -0
  51. package/server/channel-socket.js +322 -0
  52. package/server/definitions.d.ts +270 -294
  53. package/server/definitions.js +35 -115
  54. package/server/dispatch.d.ts +121 -66
  55. package/server/dispatch.js +267 -87
  56. package/server/event-stream.d.ts +63 -0
  57. package/server/event-stream.js +173 -0
  58. package/server/generated.d.ts +3 -1
  59. package/server/generated.js +3 -1
  60. package/server/index.d.ts +6 -3
  61. package/server/index.js +3 -2
  62. package/server/outcomes.d.ts +64 -2
  63. package/server/outcomes.js +85 -4
  64. package/server/read-cookies.d.ts +19 -0
  65. package/server/read-cookies.js +39 -0
  66. package/server/response-effects.d.ts +105 -0
  67. package/server/response-effects.js +78 -0
  68. package/server/stages.d.ts +62 -0
  69. package/server/stages.js +51 -0
  70. package/server/upgrade.d.ts +57 -0
  71. package/server/upgrade.js +116 -0
  72. package/source-text.d.ts +1 -0
  73. package/source-text.js +56 -0
  74. package/stream.d.ts +34 -0
  75. package/stream.js +161 -0
  76. package/tanstack-query/README.md +113 -21
  77. package/tanstack-query/create-queries.d.ts +2 -0
  78. package/tanstack-query/{generated.js → create-queries.js} +13 -11
  79. package/tanstack-query/hydration-window.d.ts +11 -0
  80. package/tanstack-query/hydration-window.js +9 -0
  81. package/tanstack-query/hydration.d.ts +4 -14
  82. package/tanstack-query/hydration.js +9 -12
  83. package/tanstack-query/index.d.ts +1 -1
  84. package/tanstack-query/queries.d.ts +50 -33
  85. package/testing/call-procedure.d.ts +154 -0
  86. package/testing/call-procedure.js +97 -0
  87. package/testing/index.d.ts +2 -0
  88. package/testing/index.js +1 -0
  89. package/generated.js +0 -90
  90. package/generation/context-file.d.ts +0 -2
  91. package/generation/context-file.js +0 -3
  92. package/tanstack-query/generated.d.ts +0 -5
package/server/backend.js CHANGED
@@ -1,12 +1,14 @@
1
- import { inject, InjectionToken, REQUEST, REQUEST_CONTEXT, makeEnvironmentProviders, } from "@angular/core";
1
+ import { DestroyRef, DOCUMENT, inject, InjectionToken, REQUEST, REQUEST_CONTEXT, RESPONSE_INIT, makeEnvironmentProviders, } from "@angular/core";
2
2
  import { FetchBackend, HttpBackend, HttpErrorResponse, HttpResponse } from "@angular/common/http";
3
3
  import { Observable } from "rxjs";
4
- import { RPC_CALL } from "../generated.js";
5
- import { dispatch, failure, invalidInput, isJsonMediaType, assertBoundScope, } from "./dispatch.js";
4
+ import { RPC_CALL } from "../remote-client.js";
5
+ import { parseJson } from "../json.js";
6
+ import { runRenderingCall, failure, invalidInput, isJsonMediaType, assertBoundScope, createRequestScope, } from "./dispatch.js";
7
+ import { createResponseEffects } from "./response-effects.js";
6
8
  const renderFaults = new InjectionToken("Launch render faults");
7
9
  /**
8
- * Provides the server-rendering transport that runs RPC calls in-process with the
9
- * current request's context.
10
+ * Provides the server-rendering transport that runs RPC calls in-process in the current
11
+ * request's scope.
10
12
  *
11
13
  * @remarks
12
14
  * Internal: exported only from `@loozo/angular-launch/_server` for the generated
@@ -14,27 +16,43 @@ const renderFaults = new InjectionToken("Launch render faults");
14
16
  * after `provideHttpClient()`, instead of calling this.
15
17
  *
16
18
  * It replaces Angular's `HttpBackend` on the server. Calls from generated clients, and
17
- * any other request to `/_rpc/` on the current request's origin, are intercepted and
18
- * run in-process in `"rendering"` mode, so mutations are refused with `FORBIDDEN`. All
19
- * other requests, including ones to `/_rpc/` on another origin that don't come from a
20
- * generated client, go to Angular's `FetchBackend`.
19
+ * any other request to `/_rpc/` on the page's origin, are intercepted and run in-process
20
+ * in `"rendering"` mode, so mutations and streams are refused with `FORBIDDEN`. All other
21
+ * requests, including ones to `/_rpc/` on another origin that don't come from a generated
22
+ * client, go to Angular's `FetchBackend`.
21
23
  *
22
- * For intercepted calls, Angular's `REQUEST_CONTEXT` must be the {@link RequestScope}
23
- * created for Angular's `REQUEST`, or the calls fail with `INTERNAL`. A generated-client
24
- * call outside `/_rpc/` on the current request's origin fails with `INVALID_INPUT` with no
25
- * issues, as does any intercepted call with a query string, fragment, URL credentials, a
26
- * method other than `POST`, a non-JSON content type, its own `Authorization`,
27
- * `Proxy-Authorization` or `Cookie` header, or its own credentials setting.
24
+ * For intercepted calls during server rendering, Angular's `REQUEST_CONTEXT` must be the
25
+ * {@link RequestScope} created for Angular's `REQUEST`, or the calls fail with `INTERNAL`.
26
+ * They run in the copy of the package that created the scope, with the application binding
27
+ * it was created for, usually the server entry's: Angular bundles the server entry apart
28
+ * from the server application, and running there gives a page the same stages, handlers
29
+ * and module state as the server's RPCs.
30
+ * A generated-client call outside `/_rpc/` on the page's origin fails with
31
+ * `INVALID_INPUT` with no issues, as does any intercepted call with a query string,
32
+ * fragment, URL credentials, a method other than `POST`, a non-JSON content type, its own
33
+ * `Authorization`, `Proxy-Authorization` or `Cookie` header, or its own credentials
34
+ * setting.
28
35
  *
29
- * Without a live request, as during prerendering, calls from generated clients and
30
- * requests to a relative `/_rpc/` path fail and the fault is recorded for
31
- * {@link finishLaunchRendering}; other requests still go to `FetchBackend`.
36
+ * Cookies an intercepted call sets are appended to `RESPONSE_INIT`'s headers when the
37
+ * call settles, whatever its outcome, so they reach the page response; its other headers
38
+ * are dropped. Angular copies those headers into the page response once the app is first
39
+ * stable, so cookies from a call that settles later, such as one awaited in a
40
+ * `BEFORE_APP_SERIALIZED` hook, are lost. Without `RESPONSE_INIT`, a call that set cookies
41
+ * fails with `INTERNAL`.
32
42
  *
33
- * @param registry - The application's RPC groups.
34
- * @param application - The application binding.
43
+ * Without `REQUEST`, as when Angular prerenders a page, the first intercepted call creates
44
+ * the render's request scope from a cookie-less `GET` of the page's URL, and every call in
45
+ * the render shares it and runs in this copy, with `application`. Its signal aborts when
46
+ * the application is destroyed. A call that doesn't answer 200, or sets a cookie, records a
47
+ * fault for {@link finishLaunchRendering}, as does a context stage that throws, named by
48
+ * its route.
49
+ * Only faults recorded before the app is first stable fail the build.
50
+ *
51
+ * @param application - The application binding: a live scope must belong to it, and
52
+ * prerendering runs its calls with it.
35
53
  * @returns The environment providers for the server application.
36
54
  */
37
- export function provideLaunchServer(registry, application) {
55
+ export function provideLaunchServer(application) {
38
56
  return makeEnvironmentProviders([
39
57
  { provide: renderFaults, useFactory: () => ({}) },
40
58
  {
@@ -42,33 +60,41 @@ export function provideLaunchServer(registry, application) {
42
60
  useFactory: () => {
43
61
  const context = inject(REQUEST_CONTEXT);
44
62
  const nativeRequest = inject(REQUEST);
63
+ const responseInit = inject(RESPONSE_INIT, { optional: true });
45
64
  const fallback = inject(FetchBackend);
46
65
  const faults = inject(renderFaults);
66
+ const document = inject(DOCUMENT);
67
+ const destroyed = new AbortController();
68
+ let prerenderScope;
69
+ inject(DestroyRef).onDestroy(() => destroyed.abort());
70
+ // The first fault is the one the build reports.
71
+ function recordFault(message, cause) {
72
+ faults.fault ??= new Error(`Launch can't prerender this page: ${message}`, { cause });
73
+ }
47
74
  return {
48
75
  handle(request) {
49
76
  const marked = request.context.get(RPC_CALL);
50
- let target;
77
+ const prerendering = !(nativeRequest instanceof Request);
78
+ let page;
51
79
  if (nativeRequest instanceof Request) {
52
- target = new URL(request.urlWithParams, nativeRequest.url);
80
+ page = nativeRequest.url;
53
81
  }
54
82
  else {
55
- target = new URL(request.urlWithParams, "http://launch.invalid");
56
- const localRpc = target.origin === "http://launch.invalid" && target.pathname.startsWith("/_rpc/");
57
- if (!marked && !localRpc) {
58
- return fallback.handle(request);
59
- }
60
- const error = new Error("Launch RPC requires live request context; prerender RPC is unsupported");
61
- faults.unsupportedContext = error;
62
- return new Observable((subscriber) => subscriber.error(error));
83
+ page = document.location.href;
63
84
  }
64
- const ownOrigin = target.origin === new URL(nativeRequest.url).origin;
85
+ const target = new URL(request.urlWithParams, page);
86
+ const ownOrigin = target.origin === new URL(page).origin;
65
87
  const ownRpc = ownOrigin && target.pathname.startsWith("/_rpc/");
66
88
  if (!marked && !ownRpc) {
67
89
  return fallback.handle(request);
68
90
  }
69
91
  return new Observable((subscriber) => {
70
92
  function deliver(reply) {
71
- if (reply.status >= 400) {
93
+ if (prerendering && reply.status !== 200) {
94
+ recordFault(`${target.pathname} answered ${reply.status} ${JSON.stringify(reply.body)}`);
95
+ }
96
+ // Only 200 is a result: a redirect's 303 frame must not reach the caller as data.
97
+ if (reply.status !== 200) {
72
98
  subscriber.error(new HttpErrorResponse({
73
99
  status: reply.status,
74
100
  error: reply.body,
@@ -83,13 +109,17 @@ export function provideLaunchServer(registry, application) {
83
109
  }));
84
110
  subscriber.complete();
85
111
  }
86
- try {
87
- assertBoundScope(context, application, nativeRequest);
88
- }
89
- catch (error) {
90
- console.error("Launch SSR scope binding failed", error);
91
- deliver(failure("INTERNAL"));
92
- return;
112
+ let live;
113
+ if (nativeRequest instanceof Request) {
114
+ try {
115
+ assertBoundScope(context, application, nativeRequest);
116
+ live = { scope: context, request: nativeRequest };
117
+ }
118
+ catch (error) {
119
+ console.error("Launch SSR scope binding failed", error);
120
+ deliver(failure("INTERNAL"));
121
+ return;
122
+ }
93
123
  }
94
124
  const authOverride = request.headers.has("authorization") ||
95
125
  request.headers.has("proxy-authorization") ||
@@ -115,7 +145,7 @@ export function provideLaunchServer(registry, application) {
115
145
  deliver(invalidInput());
116
146
  return;
117
147
  }
118
- envelope = JSON.parse(body);
148
+ envelope = parseJson(body);
119
149
  }
120
150
  catch {
121
151
  deliver(invalidInput());
@@ -123,11 +153,57 @@ export function provideLaunchServer(registry, application) {
123
153
  }
124
154
  // Aborts when the page request does, or when HttpClient unsubscribes first.
125
155
  const call = new AbortController();
156
+ const effects = createResponseEffects();
126
157
  let settled = false;
127
- void dispatch(registry, target.pathname, envelope, context, application, nativeRequest, "rendering", AbortSignal.any([nativeRequest.signal, call.signal])).then((reply) => {
158
+ async function run() {
159
+ let scope;
160
+ let pageRequest;
161
+ if (live) {
162
+ scope = live.scope;
163
+ pageRequest = live.request;
164
+ }
165
+ else {
166
+ prerenderScope ??= createRequestScope(application, new Request(page, { signal: destroyed.signal }));
167
+ scope = prerenderScope;
168
+ pageRequest = scope.request;
169
+ }
170
+ // Runs in the copy of the package that created the scope: for a live page, the
171
+ // server entry's, whose stages and handlers answer this server's RPCs.
172
+ const reply = await runRenderingCall(scope, target.pathname, envelope, pageRequest, AbortSignal.any([pageRequest.signal, call.signal]), effects);
128
173
  settled = true;
174
+ effects.commit();
175
+ // Recorded first, so the build reports the stage rather than the 500.
176
+ if (prerendering && reply.failedStage) {
177
+ recordFault(`the context stage of ${reply.failedStage.route} threw`, reply.failedStage.error);
178
+ }
179
+ if (effects.cookies.length === 0) {
180
+ deliver(reply);
181
+ return;
182
+ }
183
+ // A prerendered page is a file: there's no response to put a cookie on.
184
+ if (prerendering) {
185
+ recordFault(`${target.pathname} set a cookie`);
186
+ deliver(reply);
187
+ return;
188
+ }
189
+ if (responseInit === null) {
190
+ console.error("Launch can't send cookies set during rendering without RESPONSE_INIT");
191
+ deliver(failure("INTERNAL"));
192
+ return;
193
+ }
194
+ // Angular builds the page response, and its redirects, from these headers. It
195
+ // creates them as Headers; keep that object for anyone holding it.
196
+ let headers = responseInit.headers;
197
+ if (!(headers instanceof Headers)) {
198
+ headers = new Headers(headers);
199
+ responseInit.headers = headers;
200
+ }
201
+ for (const cookie of effects.cookies) {
202
+ headers.append("set-cookie", cookie);
203
+ }
129
204
  deliver(reply);
130
- });
205
+ }
206
+ void run();
131
207
  return () => {
132
208
  if (!settled) {
133
209
  call.abort(new DOMException("RPC call aborted", "AbortError"));
@@ -141,14 +217,28 @@ export function provideLaunchServer(registry, application) {
141
217
  ]);
142
218
  }
143
219
  /**
144
- * Waits for the server application to become stable and fails the render if an RPC was
145
- * called without a live request.
220
+ * Waits for the server application to become stable and fails the render if a Launch call
221
+ * failed while Angular prerendered the page.
146
222
  *
147
223
  * @remarks
148
- * Angular's prerendering can swallow resolver errors and still report success. Return
149
- * this from your server bootstrap so a page that calls an RPC during prerendering fails
150
- * the build instead of producing a broken page. The application must include the
151
- * generated `provideServer()`.
224
+ * A prerendered page is written once and served to every visitor, so each Launch call it
225
+ * makes must answer 200 without setting a cookie; a mutation or stream is refused with
226
+ * `FORBIDDEN`, so it fails too. Angular's prerendering can swallow resolver errors and still
227
+ * report success, and a failed `injectQuery` only renders its error state, so return this
228
+ * from your server bootstrap to fail the build instead of producing a broken page. The
229
+ * application must include the generated `provideServer()`. Server-rendered pages are
230
+ * unaffected: their failures reach the caller as usual.
231
+ *
232
+ * It checks once the app is first stable, which covers calls from guards, resolvers and
233
+ * rendering. Angular runs `BEFORE_APP_SERIALIZED` hooks afterwards and only logs their
234
+ * errors, so a call made in one isn't checked and the page is still written; don't make
235
+ * Launch calls there.
236
+ *
237
+ * During Angular's route discovery, which boots the app without its root component, it
238
+ * returns the application at once, without waiting or checking: discovery releases a
239
+ * blocking initial navigation (`withEnabledBlockingInitialNavigation`) only after the
240
+ * bootstrap returns, and waits for stability itself. Calls made then run with the anonymous
241
+ * context, and Angular only logs their failures.
152
242
  *
153
243
  * @example
154
244
  * ```ts
@@ -160,15 +250,19 @@ export function provideLaunchServer(registry, application) {
160
250
  * ```
161
251
  *
162
252
  * @param app - The bootstrapped server application.
163
- * @returns The same application once it is stable.
164
- * @throws The recorded error when an RPC was called without a live request; the
165
- * application is destroyed first.
253
+ * @returns The same application once it is stable, or at once during route discovery.
254
+ * @throws The first recorded fault, naming the call and its reply, the cookie or the
255
+ * context stage that threw, with its error as the cause; the application is destroyed
256
+ * first.
166
257
  */
167
- // Native prerender can swallow resolver errors. Propagate only the unsupported
168
- // Launch context fault after native stability, without manufacturing a request.
169
258
  export async function finishLaunchRendering(app) {
259
+ // Only route discovery bootstraps without a root component.
260
+ const discoveringRoutes = app.components.length === 0;
261
+ if (discoveringRoutes) {
262
+ return app;
263
+ }
170
264
  await app.whenStable();
171
- const fault = app.injector.get(renderFaults).unsupportedContext;
265
+ const fault = app.injector.get(renderFaults).fault;
172
266
  if (fault) {
173
267
  app.destroy();
174
268
  throw fault;
@@ -0,0 +1,54 @@
1
+ import { type InputIssue } from "../input-issues.js";
2
+ import type { Schema } from "./definitions.js";
3
+ /**
4
+ * Where a channel's handler reads its caller's messages from. Internal.
5
+ *
6
+ * @remarks
7
+ * The socket side of a channel creates it before the upgrade is accepted, so the handler can
8
+ * hold its `messages` from the start; messages arrive once the socket is accepted.
9
+ */
10
+ export interface ChannelInbox {
11
+ /**
12
+ * Takes the next unread message as received, before validation.
13
+ *
14
+ * @returns The message, or `done` once the caller closed the channel. Rejects with a
15
+ * {@link MessageRefused} after the caller broke the protocol.
16
+ */
17
+ next(): Promise<IteratorResult<unknown, undefined>>;
18
+ /**
19
+ * Ends the call with `INVALID_INPUT` and `issues`, for a message that failed validation.
20
+ *
21
+ * @param issues - The message schema's issues.
22
+ */
23
+ refuse(issues: readonly InputIssue[]): void;
24
+ }
25
+ /**
26
+ * Why a channel's messages ended: the caller sent a message that failed validation, or broke
27
+ * the protocol. Internal.
28
+ *
29
+ * @remarks
30
+ * `runProcedure` answers it with `INVALID_INPUT` and its issues instead of logging it as an
31
+ * unexpected failure.
32
+ */
33
+ export declare class MessageRefused extends Error {
34
+ readonly issues: readonly InputIssue[];
35
+ /**
36
+ * Creates the refusal.
37
+ *
38
+ * @param issues - The message schema's issues; empty for a protocol violation.
39
+ */
40
+ constructor(issues: readonly InputIssue[]);
41
+ }
42
+ /**
43
+ * The `messages` a channel's handler receives: the inbox's messages, validated with `schema`
44
+ * as they're read, in arrival order.
45
+ *
46
+ * @remarks
47
+ * Internal. One consumer only: a second iterator throws a `TypeError`. A message that fails
48
+ * validation refuses the call through the inbox and throws a {@link MessageRefused}; after
49
+ * that, or after `return()`, iteration is done.
50
+ *
51
+ * @param inbox - Where the messages come from.
52
+ * @param schema - The channel's message schema.
53
+ */
54
+ export declare function channelMessages(inbox: ChannelInbox, schema: Schema): AsyncIterable<unknown>;
@@ -0,0 +1,84 @@
1
+ import { inputIssues } from "../input-issues.js";
2
+ /**
3
+ * Why a channel's messages ended: the caller sent a message that failed validation, or broke
4
+ * the protocol. Internal.
5
+ *
6
+ * @remarks
7
+ * `runProcedure` answers it with `INVALID_INPUT` and its issues instead of logging it as an
8
+ * unexpected failure.
9
+ */
10
+ export class MessageRefused extends Error {
11
+ issues;
12
+ /**
13
+ * Creates the refusal.
14
+ *
15
+ * @param issues - The message schema's issues; empty for a protocol violation.
16
+ */
17
+ constructor(issues) {
18
+ super("Launch channel refused a message");
19
+ this.issues = issues;
20
+ this.name = "MessageRefused";
21
+ }
22
+ }
23
+ /**
24
+ * The `messages` a channel's handler receives: the inbox's messages, validated with `schema`
25
+ * as they're read, in arrival order.
26
+ *
27
+ * @remarks
28
+ * Internal. One consumer only: a second iterator throws a `TypeError`. A message that fails
29
+ * validation refuses the call through the inbox and throws a {@link MessageRefused}; after
30
+ * that, or after `return()`, iteration is done.
31
+ *
32
+ * @param inbox - Where the messages come from.
33
+ * @param schema - The channel's message schema.
34
+ */
35
+ export function channelMessages(inbox, schema) {
36
+ let taken = false;
37
+ let finished = false;
38
+ // Reads run one after another, so an asynchronous schema can't reorder messages.
39
+ let previous = Promise.resolve();
40
+ async function read() {
41
+ if (finished) {
42
+ return { done: true, value: undefined };
43
+ }
44
+ let received;
45
+ try {
46
+ received = await inbox.next();
47
+ }
48
+ catch (error) {
49
+ finished = true;
50
+ throw error;
51
+ }
52
+ if (received.done) {
53
+ finished = true;
54
+ return received;
55
+ }
56
+ const parsed = await schema["~standard"].validate(received.value);
57
+ if (parsed.issues) {
58
+ const issues = inputIssues(parsed.issues);
59
+ finished = true;
60
+ inbox.refuse(issues);
61
+ throw new MessageRefused(issues);
62
+ }
63
+ return { done: false, value: parsed.value };
64
+ }
65
+ return {
66
+ [Symbol.asyncIterator]() {
67
+ if (taken) {
68
+ throw new TypeError("A channel's messages have one consumer: iterate them once");
69
+ }
70
+ taken = true;
71
+ return {
72
+ next() {
73
+ const step = previous.then(read);
74
+ previous = step.catch(() => undefined);
75
+ return step;
76
+ },
77
+ async return() {
78
+ finished = true;
79
+ return { done: true, value: undefined };
80
+ },
81
+ };
82
+ },
83
+ };
84
+ }
@@ -0,0 +1,67 @@
1
+ import { type ChannelInbox } from "./channel-messages.js";
2
+ import { type Reply } from "./dispatch.js";
3
+ import { type StreamStart } from "./event-stream.js";
4
+ /** How many values the server sends before the caller must grant more. */
5
+ export declare const valueWindow = 256;
6
+ /** How many messages the caller sends before the server must grant more. */
7
+ export declare const messageWindow = 32;
8
+ /** Past this many unsent bytes in the socket's buffer, the server stops pulling values. */
9
+ export declare const bufferedMark: number;
10
+ /** How often the server checks whether the socket's buffer drained below the mark. */
11
+ export declare const bufferedPollMs = 50;
12
+ /**
13
+ * One channel call's side of its websocket. Internal.
14
+ *
15
+ * @remarks
16
+ * Created before the call's pipeline runs, so the handler can receive `messages` and the
17
+ * call a signal; `start` and `accept` follow as the call gets there.
18
+ */
19
+ export interface ChannelSocket {
20
+ /** The handler's messages, before validation. */
21
+ readonly inbox: ChannelInbox;
22
+ /**
23
+ * The call's signal: until `accept` it follows the request's signal, then the socket
24
+ * closing. It also aborts when the caller breaks the protocol.
25
+ */
26
+ readonly signal: AbortSignal;
27
+ /**
28
+ * Takes over the started channel: from now on, the caller leaving before `accept` ends it.
29
+ *
30
+ * @param stream - The handler's iterator and the settler of its part of the call.
31
+ * @param outcome - The whole call's reply, from `runProcedure`.
32
+ */
33
+ start(stream: StreamStart, outcome: Promise<Reply>): void;
34
+ /**
35
+ * Runs the started channel's frames on the host's accepted socket.
36
+ *
37
+ * @param socket - The accepted socket, open or still connecting.
38
+ */
39
+ accept(socket: WebSocket): void;
40
+ }
41
+ /**
42
+ * Creates one channel call's side of its websocket.
43
+ *
44
+ * @remarks
45
+ * Internal. After `accept`, it sends one `{"value":v}` frame per yielded value, then, once
46
+ * the whole call settled, `{"end":null}` or the failure frame, and closes with 1000.
47
+ *
48
+ * Flow control is two credit windows. The server sends at most {@link valueWindow} values
49
+ * the caller hasn't granted back with `{"ready":n}`, and pulls the handler's next value only
50
+ * with credit and while the socket buffers less than {@link bufferedMark} bytes, checking
51
+ * every {@link bufferedPollMs} ms. The caller sends at most {@link messageWindow} messages
52
+ * the handler hasn't read; the server grants `{"ready":n}` once the handler read half a
53
+ * window since the last grant.
54
+ *
55
+ * A binary or malformed frame, a message beyond the caller's credit or a grant for more
56
+ * values than are outstanding ends the call with `INVALID_INPUT`, as does a message that
57
+ * fails validation. Frames arriving after the handler finished are dropped.
58
+ *
59
+ * When the socket closes, or the request goes away before `accept`, the call's signal
60
+ * aborts, `messages` ends after the messages already received, and the handler's pending
61
+ * step is awaited and its iterator returned, as for a stream. A generator suspended at its
62
+ * `yield` for want of credit returns at once.
63
+ *
64
+ * @param requestSignal - The upgrade request's signal, followed until `accept`.
65
+ * @returns The channel's socket side.
66
+ */
67
+ export declare function createChannelSocket(requestSignal: AbortSignal): ChannelSocket;