@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
@@ -0,0 +1,62 @@
1
+ import type { StageArgs } from "./definitions.js";
2
+ import type { ResponseControl } from "./response-effects.js";
3
+ /**
4
+ * One route occurrence's `.context()` stage. It receives the context of the stages above it
5
+ * and returns the route's whole context, which replaces it.
6
+ *
7
+ * @remarks
8
+ * Internal; not exported from an entry point. The application binding makes one per
9
+ * authored route that declares a stage, so a stage function shared by two routes still
10
+ * runs once per route.
11
+ */
12
+ export interface Stage {
13
+ /** The authored stage function. */
14
+ readonly run: (args: StageArgs<object>) => object | PromiseLike<object>;
15
+ /** The declaring route's file, workspace-relative, for diagnostics. */
16
+ readonly route: string;
17
+ }
18
+ /**
19
+ * The part of {@link StageArgs} owned by the request scope.
20
+ *
21
+ * @remarks
22
+ * Internal; not exported from an entry point.
23
+ */
24
+ export type StageScope = Pick<StageArgs<object>, "request" | "signal">;
25
+ /**
26
+ * What running a chain of stages settles to: the last stage's context, or the stage that
27
+ * failed with what it threw.
28
+ *
29
+ * @remarks
30
+ * Internal; not exported from an entry point. Plain data, so it crosses package copies.
31
+ * A propagated failure is the failing stage's own result object, so the stage it names is
32
+ * the one that threw however many chains reuse it.
33
+ */
34
+ export type StageResult = {
35
+ /** The context the chain's last stage returned. */
36
+ readonly context: object;
37
+ } | {
38
+ /** The stage that threw or rejected. */
39
+ readonly failed: Stage;
40
+ /** What it threw or rejected with, unchanged. */
41
+ readonly error: unknown;
42
+ };
43
+ /**
44
+ * Runs `chain` from its first stage for one call and settles to its {@link StageResult}.
45
+ *
46
+ * @remarks
47
+ * Internal; not exported from an entry point.
48
+ * Each stage runs at most once per runner, for the first call that reaches it and with that
49
+ * call's `response`; later chains sharing a stage reuse its memoized result, failures
50
+ * included. A stage must always have the same stages before it. The promise never rejects.
51
+ */
52
+ export type StageRunner = (chain: readonly [Stage, ...Stage[]], response: ResponseControl) => Promise<StageResult>;
53
+ /**
54
+ * Creates the stage runner for one request scope.
55
+ *
56
+ * @remarks
57
+ * Internal; not exported from an entry point.
58
+ *
59
+ * @param scope - The request and signal every stage of the scope receives.
60
+ * @returns The scope's stage runner.
61
+ */
62
+ export declare function createStageRunner(scope: StageScope): StageRunner;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Creates the stage runner for one request scope.
3
+ *
4
+ * @remarks
5
+ * Internal; not exported from an entry point.
6
+ *
7
+ * @param scope - The request and signal every stage of the scope receives.
8
+ * @returns The scope's stage runner.
9
+ */
10
+ export function createStageRunner(scope) {
11
+ // Each stage's result: the context it returned, or the first failure up to it.
12
+ const memo = new Map();
13
+ return (chain, response) => {
14
+ let parent;
15
+ for (const stage of chain) {
16
+ let entry = memo.get(stage);
17
+ if (entry === undefined) {
18
+ if (parent === undefined) {
19
+ // The first stage is called now, synchronously, and receives `{}`.
20
+ entry = settle(stage, invoke(stage, { ...scope, response, context: {} }));
21
+ }
22
+ else {
23
+ entry = parent.then((result) => {
24
+ // An ancestor failed: pass its own result on, so it keeps naming that stage.
25
+ if ("failed" in result) {
26
+ return result;
27
+ }
28
+ const { context } = result;
29
+ return settle(stage, invoke(stage, { ...scope, response, context }));
30
+ });
31
+ }
32
+ // Stored before it settles, so a failure is memoized too.
33
+ memo.set(stage, entry);
34
+ }
35
+ parent = entry;
36
+ }
37
+ // A non-empty chain always sets it.
38
+ return parent;
39
+ };
40
+ }
41
+ function settle(stage, own) {
42
+ return own.then((context) => ({ context }), (error) => ({ failed: stage, error }));
43
+ }
44
+ function invoke(stage, args) {
45
+ try {
46
+ return Promise.resolve(stage.run(args));
47
+ }
48
+ catch (error) {
49
+ return Promise.reject(error);
50
+ }
51
+ }
@@ -0,0 +1,57 @@
1
+ import type { ApplicationBinding } from "./application.js";
2
+ import { type HandleOptions } 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 stage runs, 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 request scope is then created and the call run: `RPC_NOT_FOUND` for a path that
39
+ * isn't a channel, then the owning route's stages and `.use()` middleware, input
40
+ * validation, procedure middleware and the handler, which returns its iterable. From then
41
+ * on the result is an {@link Upgrade} carrying the call's headers and cookies, including
42
+ * the stages'; setting a cookie later throws. A failure before that, including a stage
43
+ * that throws (`INTERNAL`), is an `Upgrade` too, whose socket receives the failure frame
44
+ * and closes with 1000.
45
+ *
46
+ * Until the socket is accepted the call's signal follows `request.signal`; a request that
47
+ * aborts before the handler is reached skips the handler, and one that aborts after it
48
+ * returned its iterable returns that iterator before its body ran. Either way the socket,
49
+ * if accepted, closes without a frame. Afterwards the signal follows the socket closing.
50
+ *
51
+ * @param application - The application binding.
52
+ * @param request - The upgrade request, as a web `Request`.
53
+ * @param options - The allowed hosts and further allowed origins.
54
+ * @returns A refusal response, the upgrade, or `null` when the path doesn't start with
55
+ * `/_rpc/`.
56
+ */
57
+ export declare function handleChannelUpgrade(application: ApplicationBinding, request: Request, { allowedHosts, origins }: HandleOptions): Promise<Response | Upgrade | null>;
@@ -0,0 +1,116 @@
1
+ import { parseJson } from "../json.js";
2
+ import { createChannelSocket } from "./channel-socket.js";
3
+ import { createRequestScope, crossSiteReason, runProcedure, failure, hostAllowed, hostRefusal, invalidInput, response, responseHeaders, } from "./dispatch.js";
4
+ import { failureFrame } from "./event-stream.js";
5
+ import { createResponseEffects } from "./response-effects.js";
6
+ /** The `{ input }` envelope a channel's query carries, or `undefined` when it's malformed. */
7
+ function queryEnvelope(url) {
8
+ const entries = [...url.searchParams];
9
+ if (entries.length !== 1 || entries[0][0] !== "input") {
10
+ return undefined;
11
+ }
12
+ try {
13
+ return { input: parseJson(entries[0][1]) };
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ function upgrade(effects, accept) {
20
+ return { headers: responseHeaders({}, effects), accept };
21
+ }
22
+ // A call that failed before it started still upgrades, so the client sees its frame.
23
+ function refusedUpgrade(effects, reply) {
24
+ return upgrade(effects, (socket) => {
25
+ function fail() {
26
+ socket.send(failureFrame(reply));
27
+ socket.close(1000);
28
+ }
29
+ if (socket.readyState === 0) {
30
+ socket.addEventListener("open", fail, { once: true });
31
+ return;
32
+ }
33
+ fail();
34
+ });
35
+ }
36
+ /**
37
+ * Answers a websocket upgrade request for a channel, or returns `null` for any other
38
+ * request.
39
+ *
40
+ * @remarks
41
+ * Internal: exported only from `@loozo/angular-launch/_server` for the generated
42
+ * `handleUpgrade` in `server.generated.ts`; call that instead.
43
+ *
44
+ * Any path starting with `/_rpc/` is a channel request. Before any stage runs, the
45
+ * request is refused with an HTTP response, as `handleRequest` refuses RPCs: a plain-text 400
46
+ * `Host not allowed` when its hostname isn't in `allowedHosts`; `INVALID_INPUT` with no issues
47
+ * unless it's a `GET` with `Upgrade: websocket` and a query of exactly `input` holding JSON;
48
+ * and `FORBIDDEN` unless it's proven same-origin by `handleRequest`'s rules.
49
+ *
50
+ * A fresh request scope is then created and the call run: `RPC_NOT_FOUND` for a path that
51
+ * isn't a channel, then the owning route's stages and `.use()` middleware, input
52
+ * validation, procedure middleware and the handler, which returns its iterable. From then
53
+ * on the result is an {@link Upgrade} carrying the call's headers and cookies, including
54
+ * the stages'; setting a cookie later throws. A failure before that, including a stage
55
+ * that throws (`INTERNAL`), is an `Upgrade` too, whose socket receives the failure frame
56
+ * and closes with 1000.
57
+ *
58
+ * Until the socket is accepted the call's signal follows `request.signal`; a request that
59
+ * aborts before the handler is reached skips the handler, and one that aborts after it
60
+ * returned its iterable returns that iterator before its body ran. Either way the socket,
61
+ * if accepted, closes without a frame. Afterwards the signal follows the socket closing.
62
+ *
63
+ * @param application - The application binding.
64
+ * @param request - The upgrade request, as a web `Request`.
65
+ * @param options - The allowed hosts and further allowed origins.
66
+ * @returns A refusal response, the upgrade, or `null` when the path doesn't start with
67
+ * `/_rpc/`.
68
+ */
69
+ export async function handleChannelUpgrade(application, request, { allowedHosts, origins = [] }) {
70
+ const url = new URL(request.url);
71
+ if (!url.pathname.startsWith("/_rpc/")) {
72
+ return null;
73
+ }
74
+ if (!hostAllowed(url.hostname, allowedHosts)) {
75
+ return hostRefusal(url.hostname);
76
+ }
77
+ const envelope = queryEnvelope(url);
78
+ if (request.method !== "GET" ||
79
+ request.headers.get("upgrade")?.toLowerCase() !== "websocket" ||
80
+ envelope === undefined) {
81
+ return response(invalidInput());
82
+ }
83
+ const crossSite = crossSiteReason(request, origins);
84
+ if (crossSite !== undefined) {
85
+ console.error(`Launch refused a cross-origin RPC: ${crossSite}`);
86
+ return response(failure("FORBIDDEN"));
87
+ }
88
+ const effects = createResponseEffects();
89
+ const socket = createChannelSocket(request.signal);
90
+ let reply;
91
+ try {
92
+ const scope = createRequestScope(application, request);
93
+ const started = Promise.withResolvers();
94
+ const outcome = runProcedure(url.pathname, envelope, scope, application, scope.request, "socket", socket.signal, effects, started.resolve, socket.inbox);
95
+ // Failures before the handler returned its iterable are frames on an upgraded socket.
96
+ const first = await Promise.race([outcome, started.promise]);
97
+ if ("iterator" in first) {
98
+ // The 101 carries the cookies; the rest of the call is the channel itself.
99
+ effects.commit();
100
+ socket.start(first, outcome);
101
+ return upgrade(effects, (accepted) => socket.accept(accepted));
102
+ }
103
+ // The caller left before the handler ran: nobody reads a frame, the socket just closes.
104
+ if (socket.signal.aborted) {
105
+ effects.commit();
106
+ return upgrade(effects, (accepted) => socket.accept(accepted));
107
+ }
108
+ reply = first;
109
+ }
110
+ catch (error) {
111
+ console.error("Launch request scope failed", error);
112
+ reply = failure("INTERNAL");
113
+ }
114
+ effects.commit();
115
+ return refusedUpgrade(effects, reply);
116
+ }
@@ -0,0 +1 @@
1
+ export {};
package/source-text.js ADDED
@@ -0,0 +1,56 @@
1
+ // Installs a source-text `$localize` tag in the unlocalized server host, so the destination
2
+ // copies a translated app's server.generated.ts reaches evaluate to canonical URLs. Internal:
3
+ // exported only as `@loozo/angular-launch/_source-text`, which a translated app's generated
4
+ // server.generated.ts imports first. Side effects only.
5
+ //
6
+ // Angular never runs polyfills in the SSR host entry, and inlining replaces
7
+ // `@angular/localize/init` with a `{ locale }` object in the bundles that do run them. Importing
8
+ // that init module here would print Angular's "Direct import" warning and, in each localized
9
+ // server application that also reaches server.generated.ts, replace the `.locale` Angular sets.
10
+ // So this tag mirrors `ɵ$localize` from `@angular/localize` 22.2 without importing it: it applies
11
+ // a `translate` hook when one was attached, strips a leading `:meaning|description@@id:` block
12
+ // from each part (honoring `\:` escapes, as Angular's `findEndOfBlock` does) and joins the parts
13
+ // with their expressions. It touches only `globalThis.$localize`, never a bare `$localize`
14
+ // identifier, so Angular's inliner has nothing to rewrite here.
15
+ const host = globalThis;
16
+ // Where a part's leading metadata block ends: the index of its closing ":".
17
+ function endOfBlock(cooked, raw) {
18
+ for (let at = 1, rawAt = 1; at < cooked.length; at++, rawAt++) {
19
+ if (raw[rawAt] === "\\") {
20
+ rawAt++;
21
+ }
22
+ else if (cooked[at] === ":") {
23
+ return at;
24
+ }
25
+ }
26
+ throw new Error(`Unterminated $localize metadata block in "${raw}".`);
27
+ }
28
+ function stripBlock(cooked, raw) {
29
+ if (raw.charAt(0) !== ":") {
30
+ return cooked;
31
+ }
32
+ return cooked.substring(endOfBlock(cooked, raw) + 1);
33
+ }
34
+ // An existing tag, such as Angular's own from an earlier `@angular/localize/init`, is kept.
35
+ if (typeof host.$localize !== "function") {
36
+ const existing = host.$localize;
37
+ const tag = (parts, ...expressions) => {
38
+ let messageParts = parts;
39
+ let values = expressions;
40
+ if (tag.translate) {
41
+ [messageParts, values] = tag.translate(messageParts, values);
42
+ }
43
+ let message = stripBlock(messageParts[0], messageParts.raw[0]);
44
+ for (let index = 1; index < messageParts.length; index++) {
45
+ // `+`, as Angular's tag joins them: its conversion differs from String() for some objects.
46
+ message +=
47
+ values[index - 1] + stripBlock(messageParts[index], messageParts.raw[index]);
48
+ }
49
+ return message;
50
+ };
51
+ if (typeof existing === "object" && existing !== null && typeof existing.locale === "string") {
52
+ tag.locale = existing.locale;
53
+ }
54
+ host.$localize = tag;
55
+ }
56
+ export {};
package/stream.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { RpcError, type ErrorMetadata, type StreamCallOptions } from "./client.js";
2
+ import type { TranslateRedirect } from "./redirect-translation.js";
3
+ /**
4
+ * The rejection for a failure frame: an `RpcError` passed through `own`, an `RpcRedirect`
5
+ * or an `RpcNotFound`, or `undefined` when the frame is none of them.
6
+ *
7
+ * @remarks
8
+ * Internal. Streams and channels recognize their failure frames with it; `translate` puts a
9
+ * redirect's listed words in this build's language.
10
+ */
11
+ export declare function failureRejection(body: unknown, status: number, declared: readonly ErrorMetadata[], own: (error: RpcError<string, unknown>) => RpcError<string, unknown>, translate?: TranslateRedirect): Error | undefined;
12
+ /**
13
+ * Runs one stream call over `fetch` and yields its values.
14
+ *
15
+ * @remarks
16
+ * Internal. Not `HttpClient`: every `HttpClient` request is an Angular pending task until
17
+ * it completes, and its fetch backend keeps the whole body, so an open stream would keep
18
+ * the app unstable and grow without bound.
19
+ *
20
+ * Ends after the `end` event. Throws an `RpcError`, passed through `own`, for an error
21
+ * event or a recognized error response, and an `RpcRedirect` or `RpcNotFound` for a
22
+ * redirect or not-found one; an `AbortError` when `signal` aborts; and a
23
+ * `TypeError` when the connection fails, the body ends without its `end` event or an
24
+ * event is malformed. Returning early, as `break` does, closes the request.
25
+ *
26
+ * @param url - The procedure's `/_rpc/<namespace>/<procedure>` path.
27
+ * @param input - The caller's input, or `null`.
28
+ * @param declared - The procedure's declared error metadata.
29
+ * @param own - Associates a converted error with its procedure for `isError`.
30
+ * @param options - The call options.
31
+ * @param opened - Called once the response turned out to be the stream's events.
32
+ * @param translate - Puts a redirect's listed words in this build's language.
33
+ */
34
+ export declare function openStream(url: string, input: unknown, declared: readonly ErrorMetadata[], own: (error: RpcError<string, unknown>) => RpcError<string, unknown>, { signal }: StreamCallOptions, opened?: () => void, translate?: TranslateRedirect): AsyncGenerator<unknown, void, undefined>;
package/stream.js ADDED
@@ -0,0 +1,161 @@
1
+ import { RpcError, recognizedError } from "./client.js";
2
+ import { parseJson, serializeJson } from "./json.js";
3
+ import { recognizedOutcome } from "./outcomes.js";
4
+ /**
5
+ * Takes the complete events off the front of `buffer`, dropping comments.
6
+ *
7
+ * @param buffer - Text received so far and not yet taken.
8
+ * @param from - Where to look for the first event's end: no event ends before it.
9
+ * @throws TypeError for an event that isn't exactly an `event:` line and a `data:` line,
10
+ * which Launch servers never send.
11
+ */
12
+ function takeEvents(buffer, from) {
13
+ const events = [];
14
+ let rest = buffer;
15
+ let end = rest.indexOf("\n\n", from);
16
+ while (end !== -1) {
17
+ const lines = rest.slice(0, end).split("\n");
18
+ rest = rest.slice(end + 2);
19
+ end = rest.indexOf("\n\n");
20
+ if (lines.every((line) => line.startsWith(":"))) {
21
+ continue;
22
+ }
23
+ if (lines.length !== 2 || !lines[0].startsWith("event: ") || !lines[1].startsWith("data: ")) {
24
+ throw new TypeError("Launch stream sent a malformed event");
25
+ }
26
+ events.push({ name: lines[0].slice("event: ".length), data: lines[1].slice("data: ".length) });
27
+ }
28
+ return { events, rest };
29
+ }
30
+ /** Parses an event's data, which a Launch server always sends as strict JSON. */
31
+ function eventData(data) {
32
+ try {
33
+ return parseJson(data);
34
+ }
35
+ catch {
36
+ throw new TypeError("Launch stream sent an event whose data isn't JSON");
37
+ }
38
+ }
39
+ /**
40
+ * The rejection for a failure frame: an `RpcError` passed through `own`, an `RpcRedirect`
41
+ * or an `RpcNotFound`, or `undefined` when the frame is none of them.
42
+ *
43
+ * @remarks
44
+ * Internal. Streams and channels recognize their failure frames with it; `translate` puts a
45
+ * redirect's listed words in this build's language.
46
+ */
47
+ export function failureRejection(body, status, declared, own, translate) {
48
+ const frame = recognizedError(body, status, declared);
49
+ if (frame) {
50
+ return own(new RpcError(frame.code, status, frame.data, frame.message));
51
+ }
52
+ return recognizedOutcome(body, status, translate);
53
+ }
54
+ /**
55
+ * Runs one stream call over `fetch` and yields its values.
56
+ *
57
+ * @remarks
58
+ * Internal. Not `HttpClient`: every `HttpClient` request is an Angular pending task until
59
+ * it completes, and its fetch backend keeps the whole body, so an open stream would keep
60
+ * the app unstable and grow without bound.
61
+ *
62
+ * Ends after the `end` event. Throws an `RpcError`, passed through `own`, for an error
63
+ * event or a recognized error response, and an `RpcRedirect` or `RpcNotFound` for a
64
+ * redirect or not-found one; an `AbortError` when `signal` aborts; and a
65
+ * `TypeError` when the connection fails, the body ends without its `end` event or an
66
+ * event is malformed. Returning early, as `break` does, closes the request.
67
+ *
68
+ * @param url - The procedure's `/_rpc/<namespace>/<procedure>` path.
69
+ * @param input - The caller's input, or `null`.
70
+ * @param declared - The procedure's declared error metadata.
71
+ * @param own - Associates a converted error with its procedure for `isError`.
72
+ * @param options - The call options.
73
+ * @param opened - Called once the response turned out to be the stream's events.
74
+ * @param translate - Puts a redirect's listed words in this build's language.
75
+ */
76
+ export async function* openStream(url, input, declared, own, { signal }, opened = () => undefined, translate) {
77
+ if (signal?.aborted) {
78
+ throw new DOMException("RPC stream aborted", "AbortError");
79
+ }
80
+ const request = new AbortController();
81
+ function abort() {
82
+ request.abort(new DOMException("RPC stream aborted", "AbortError"));
83
+ }
84
+ signal?.addEventListener("abort", abort, { once: true });
85
+ try {
86
+ const response = await fetch(url, {
87
+ method: "POST",
88
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
89
+ body: serializeJson({ input }),
90
+ signal: request.signal,
91
+ });
92
+ if (!response.ok) {
93
+ let body;
94
+ try {
95
+ body = await response.json();
96
+ }
97
+ catch (error) {
98
+ // Aborting while the body arrives isn't a transport failure.
99
+ if (request.signal.aborted) {
100
+ throw error;
101
+ }
102
+ throw new TypeError(`Launch stream request failed with status ${response.status}`);
103
+ }
104
+ const error = failureRejection(body, response.status, declared, own, translate);
105
+ if (!error) {
106
+ throw new TypeError(`Launch stream request failed with status ${response.status}`);
107
+ }
108
+ throw error;
109
+ }
110
+ const mediaType = response.headers.get("content-type")?.split(";", 1)[0].trim().toLowerCase();
111
+ const isEventStream = mediaType === "text/event-stream";
112
+ if (!isEventStream || !response.body) {
113
+ throw new TypeError("Launch stream response isn't an event stream");
114
+ }
115
+ opened();
116
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
117
+ let buffer = "";
118
+ while (true) {
119
+ const chunk = await reader.read();
120
+ if (chunk.done) {
121
+ throw new TypeError("Launch stream ended without its end event");
122
+ }
123
+ // The rest holds no complete event, so one can only end in what just arrived.
124
+ const taken = takeEvents(buffer + chunk.value, Math.max(0, buffer.length - 1));
125
+ buffer = taken.rest;
126
+ for (const event of taken.events) {
127
+ // Events that arrived together aren't delivered after an abort.
128
+ if (signal?.aborted) {
129
+ throw new DOMException("RPC stream aborted", "AbortError");
130
+ }
131
+ if (event.name === "value") {
132
+ yield eventData(event.data);
133
+ continue;
134
+ }
135
+ if (event.name === "end" && event.data === "null") {
136
+ return;
137
+ }
138
+ if (event.name !== "error") {
139
+ throw new TypeError("Launch stream sent a malformed event");
140
+ }
141
+ const frame = eventData(event.data);
142
+ let error;
143
+ if (typeof frame === "object" && frame !== null && "status" in frame) {
144
+ const { status, ...body } = frame;
145
+ if (typeof status === "number") {
146
+ error = failureRejection(body, status, declared, own, translate);
147
+ }
148
+ }
149
+ if (!error) {
150
+ throw new TypeError("Launch stream sent an unrecognized error");
151
+ }
152
+ throw error;
153
+ }
154
+ }
155
+ }
156
+ finally {
157
+ signal?.removeEventListener("abort", abort);
158
+ // Closes the request when iteration ended early, failed or the stream ended.
159
+ request.abort(new DOMException("RPC stream closed", "AbortError"));
160
+ }
161
+ }