@loozo/angular-launch 0.0.4 → 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.
Files changed (59) hide show
  1. package/README.md +695 -102
  2. package/builders/application.d.ts +4 -0
  3. package/builders/application.js +71 -0
  4. package/builders/options.d.ts +10 -0
  5. package/builders/options.js +64 -0
  6. package/builders/serve.d.ts +8 -0
  7. package/builders/serve.js +248 -0
  8. package/builders.json +15 -0
  9. package/channel.d.ts +53 -0
  10. package/channel.js +231 -0
  11. package/client.d.ts +59 -16
  12. package/client.js +3 -2
  13. package/connect.d.ts +201 -0
  14. package/connect.js +148 -0
  15. package/generated.d.ts +1 -1
  16. package/generated.js +86 -3
  17. package/generation/context-file.d.ts +2 -0
  18. package/generation/context-file.js +3 -0
  19. package/generation/index.js +77 -36
  20. package/index.d.ts +6 -1
  21. package/index.js +2 -0
  22. package/json.d.ts +9 -0
  23. package/json.js +24 -0
  24. package/navigation.d.ts +36 -0
  25. package/navigation.js +47 -0
  26. package/node/index.d.ts +57 -0
  27. package/node/index.js +175 -0
  28. package/outcomes.d.ts +55 -0
  29. package/outcomes.js +100 -0
  30. package/package.json +14 -4
  31. package/schemas/application.json +756 -0
  32. package/schemas/serve.json +153 -0
  33. package/server/backend.d.ts +42 -23
  34. package/server/backend.js +137 -47
  35. package/server/channel-messages.d.ts +54 -0
  36. package/server/channel-messages.js +84 -0
  37. package/server/channel-socket.d.ts +67 -0
  38. package/server/channel-socket.js +322 -0
  39. package/server/definitions.d.ts +463 -181
  40. package/server/definitions.js +90 -103
  41. package/server/dispatch.d.ts +99 -20
  42. package/server/dispatch.js +337 -89
  43. package/server/event-stream.d.ts +63 -0
  44. package/server/event-stream.js +173 -0
  45. package/server/generated.d.ts +1 -0
  46. package/server/generated.js +1 -0
  47. package/server/index.d.ts +6 -3
  48. package/server/index.js +2 -1
  49. package/server/outcomes.d.ts +75 -0
  50. package/server/outcomes.js +90 -0
  51. package/server/response-effects.d.ts +105 -0
  52. package/server/response-effects.js +78 -0
  53. package/server/upgrade.d.ts +58 -0
  54. package/server/upgrade.js +117 -0
  55. package/stream.d.ts +31 -0
  56. package/stream.js +159 -0
  57. package/tanstack-query/README.md +110 -22
  58. package/tanstack-query/generated.js +5 -2
  59. package/tanstack-query/queries.d.ts +8 -6
package/connect.js ADDED
@@ -0,0 +1,148 @@
1
+ import { isPlatformServer } from "@angular/common";
2
+ import { afterNextRender, computed, DestroyRef, effect, inject, PLATFORM_ID, signal, untracked, } from "@angular/core";
3
+ /**
4
+ * Follows a stream or channel as signals. Internal: generated callables expose it as
5
+ * `connect()`.
6
+ *
7
+ * @remarks
8
+ * Must run in an injection context. On the server it never connects: status stays `"idle"`
9
+ * and `value` is `initial()`. In the browser it connects after the next render, and again
10
+ * whenever `input` changes; each connection reads every value as it arrives. A connection
11
+ * closed for a new input or by the injection context's destruction doesn't change `status`
12
+ * or `error`.
13
+ *
14
+ * @param open - Opens one call.
15
+ * @param options - The `connect()` options.
16
+ * @returns The connection; `send` delegates to the open channel.
17
+ */
18
+ export function connect(open, { input = () => null, initial, reduce }) {
19
+ const server = isPlatformServer(inject(PLATFORM_ID));
20
+ const destroyRef = inject(DestroyRef);
21
+ const received = signal(undefined);
22
+ const status = signal("idle");
23
+ const error = signal(undefined);
24
+ const value = computed(() => {
25
+ const latest = received();
26
+ if (latest === undefined) {
27
+ return initial();
28
+ }
29
+ return latest.state;
30
+ });
31
+ let current;
32
+ function close() {
33
+ current?.controller.abort();
34
+ current = undefined;
35
+ }
36
+ function fail(caught) {
37
+ error.set(caught);
38
+ status.set("failed");
39
+ }
40
+ async function follow(call) {
41
+ const { controller, connection } = call;
42
+ let state;
43
+ let first = true;
44
+ try {
45
+ for await (const item of connection) {
46
+ if (controller.signal.aborted) {
47
+ return;
48
+ }
49
+ try {
50
+ if (!reduce) {
51
+ state = item;
52
+ }
53
+ else if (first) {
54
+ // A new call's first value folds into the initial state, not the previous call's.
55
+ state = untracked(() => reduce(initial(), item));
56
+ }
57
+ else {
58
+ const previous = state;
59
+ state = untracked(() => reduce(previous, item));
60
+ }
61
+ }
62
+ catch (thrown) {
63
+ let failure;
64
+ if (thrown instanceof Error) {
65
+ failure = thrown;
66
+ }
67
+ else {
68
+ failure = new Error("Launch connection's reduce threw a non-Error value", {
69
+ cause: thrown,
70
+ });
71
+ }
72
+ // Set before the loop closes the channel, so the sends it rejects carry this error.
73
+ call.failure = { error: failure };
74
+ fail(failure);
75
+ throw failure;
76
+ }
77
+ first = false;
78
+ received.set({ state });
79
+ status.set("open");
80
+ }
81
+ if (!controller.signal.aborted) {
82
+ status.set("ended");
83
+ }
84
+ }
85
+ catch (caught) {
86
+ if (controller.signal.aborted || call.failure !== undefined) {
87
+ return;
88
+ }
89
+ fail(caught);
90
+ }
91
+ }
92
+ function start(next) {
93
+ close();
94
+ if (next === undefined) {
95
+ error.set(undefined);
96
+ status.set("idle");
97
+ return;
98
+ }
99
+ const controller = new AbortController();
100
+ const connection = open(next, controller.signal, () => {
101
+ if (current?.controller === controller && status() === "connecting") {
102
+ status.set("open");
103
+ }
104
+ });
105
+ const call = { controller, connection };
106
+ current = call;
107
+ error.set(undefined);
108
+ status.set("connecting");
109
+ void follow(call);
110
+ }
111
+ if (!server) {
112
+ const rendered = signal(false);
113
+ afterNextRender(() => rendered.set(true));
114
+ effect(() => {
115
+ if (!rendered()) {
116
+ return;
117
+ }
118
+ const next = input();
119
+ untracked(() => start(next));
120
+ });
121
+ destroyRef.onDestroy(close);
122
+ }
123
+ return {
124
+ value,
125
+ status: status.asReadonly(),
126
+ error: error.asReadonly(),
127
+ reconnect() {
128
+ const now = untracked(status);
129
+ if (now === "ended" || now === "failed") {
130
+ start(untracked(input));
131
+ }
132
+ },
133
+ send(message) {
134
+ const now = untracked(status);
135
+ const call = current;
136
+ if (!call || (now !== "connecting" && now !== "open") || !("send" in call.connection)) {
137
+ return Promise.reject(new TypeError("Launch connection isn't open"));
138
+ }
139
+ // A failing `reduce` closes the channel; its sends then reject with what it threw.
140
+ return call.connection.send(message).catch((rejection) => {
141
+ if (call.failure !== undefined) {
142
+ return Promise.reject(call.failure.error);
143
+ }
144
+ return Promise.reject(rejection);
145
+ });
146
+ },
147
+ };
148
+ }
package/generated.d.ts CHANGED
@@ -4,7 +4,7 @@ export declare const RPC_CALL: HttpContextToken<boolean>;
4
4
  export interface ClientMethod {
5
5
  readonly name: string;
6
6
  readonly input: boolean;
7
- readonly kind: "query" | "mutation";
7
+ readonly kind: "query" | "mutation" | "stream" | "channel";
8
8
  readonly errors: readonly ErrorMetadata[];
9
9
  }
10
10
  export declare function injectClient(groups: Readonly<Record<string, {
package/generated.js CHANGED
@@ -1,7 +1,12 @@
1
- import { inject } from "@angular/core";
1
+ import { isPlatformServer } from "@angular/common";
2
+ import { inject, PLATFORM_ID } from "@angular/core";
2
3
  import { HttpClient, HttpContext, HttpContextToken, HttpErrorResponse } from "@angular/common/http";
3
- import { RpcError, recognizedError } from "./client.js";
4
+ import { openChannel } from "./channel.js";
5
+ import { RpcError, recognizedError, } from "./client.js";
6
+ import { connect } from "./connect.js";
4
7
  import { serializeJson } from "./json.js";
8
+ import { recognizedOutcome } from "./outcomes.js";
9
+ import { openStream } from "./stream.js";
5
10
  export const RPC_CALL = new HttpContextToken(() => false);
6
11
  const errorOwners = new WeakMap();
7
12
  function call(http, group, method, input, { signal, transferCache = true } = {}) {
@@ -51,6 +56,11 @@ function call(http, group, method, input, { signal, transferCache = true } = {})
51
56
  reject(converted);
52
57
  return;
53
58
  }
59
+ const outcome = recognizedOutcome(error.error, error.status);
60
+ if (outcome) {
61
+ reject(outcome);
62
+ return;
63
+ }
54
64
  }
55
65
  reject(error);
56
66
  },
@@ -60,19 +70,92 @@ function call(http, group, method, input, { signal, transferCache = true } = {})
60
70
  }
61
71
  });
62
72
  }
73
+ // Streams don't run during server rendering: iterating one fails at once with FORBIDDEN.
74
+ function refusedStream(error) {
75
+ return { next: () => Promise.reject(error) };
76
+ }
77
+ function owner(group, method) {
78
+ return (error) => {
79
+ errorOwners.set(error, { group, method: method.name });
80
+ return error;
81
+ };
82
+ }
83
+ function stream(server, group, method, input, options = {}, opened) {
84
+ const own = owner(group, method);
85
+ // Each iteration is its own request, so iterating again reconnects.
86
+ return {
87
+ [Symbol.asyncIterator]: () => {
88
+ if (server) {
89
+ return refusedStream(own(new RpcError("FORBIDDEN", 403)));
90
+ }
91
+ return openStream(`/_rpc/${group}/${method.name}`, input, method.errors, own, options, opened);
92
+ },
93
+ };
94
+ }
95
+ // Channels don't run during server rendering either: they fail at once with FORBIDDEN.
96
+ function channel(server, group, method, input, options = {}, opened) {
97
+ const own = owner(group, method);
98
+ let path = `/_rpc/${group}/${method.name}`;
99
+ let refused;
100
+ if (server) {
101
+ refused = own(new RpcError("FORBIDDEN", 403));
102
+ }
103
+ else {
104
+ try {
105
+ path += `?input=${encodeURIComponent(serializeJson(input))}`;
106
+ }
107
+ catch (error) {
108
+ refused = error;
109
+ }
110
+ }
111
+ return openChannel(path, method.errors, own, options, opened, refused);
112
+ }
63
113
  export function injectClient(groups) {
64
114
  const http = inject(HttpClient);
115
+ let server = false;
116
+ // Only streams and channels depend on the platform.
117
+ for (const group of Object.values(groups)) {
118
+ if (group.methods.some((method) => method.kind === "stream" || method.kind === "channel")) {
119
+ server = isPlatformServer(inject(PLATFORM_ID));
120
+ break;
121
+ }
122
+ }
65
123
  const result = Object.create(null);
66
124
  for (const [namespace, group] of Object.entries(groups)) {
67
125
  const methods = Object.create(null);
68
126
  for (const method of group.methods) {
69
127
  let invoke;
70
- if (method.input) {
128
+ let open;
129
+ if (method.kind === "stream") {
130
+ open = (input, signal, opened) => stream(server, namespace, method, input, { signal }, opened);
131
+ if (method.input) {
132
+ invoke = (input, options) => stream(server, namespace, method, input, options);
133
+ }
134
+ else {
135
+ invoke = (options) => stream(server, namespace, method, null, options);
136
+ }
137
+ }
138
+ else if (method.kind === "channel") {
139
+ open = (input, signal, opened) => channel(server, namespace, method, input, { signal }, opened);
140
+ if (method.input) {
141
+ invoke = (input, options) => channel(server, namespace, method, input, options);
142
+ }
143
+ else {
144
+ invoke = (options) => channel(server, namespace, method, null, options);
145
+ }
146
+ }
147
+ else if (method.input) {
71
148
  invoke = (input, options) => call(http, namespace, method, input, options);
72
149
  }
73
150
  else {
74
151
  invoke = (options) => call(http, namespace, method, null, options);
75
152
  }
153
+ if (open) {
154
+ const opener = open;
155
+ Object.assign(invoke, {
156
+ connect: (options) => connect(opener, options),
157
+ });
158
+ }
76
159
  methods[method.name] = Object.assign(invoke, {
77
160
  kind: method.kind,
78
161
  isError: (error) => {
@@ -0,0 +1,2 @@
1
+ import type { GenerationSession } from "./index.js";
2
+ export declare const contextFiles: WeakMap<GenerationSession, string>;
@@ -0,0 +1,3 @@
1
+ // The context file each session's last pass discovered, for the serve builder's watcher. Internal:
2
+ // the exports map doesn't reach this module, so it isn't public API.
3
+ export const contextFiles = new WeakMap();
@@ -5,16 +5,47 @@ import { readFile, realpath } from "node:fs/promises";
5
5
  import { dirname, resolve, relative, sep } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { prepareLaunchRoutes, createValidationProgram, validateRoutes, planOutputs, publish, walk, auditPath, launchMarkers, fail, properties, namedImport, genuineImport, specifier, CompilerState, AnchorState, } from "@loozo/angular-router/_generation";
8
+ import { contextFiles } from "./context-file.js";
8
9
  function directCall(node, label) {
9
10
  if (!ts.isCallExpression(node) || node.typeArguments?.length) {
10
11
  fail(node, `${label} requires a direct nongeneric factory call`);
11
12
  }
12
13
  return node;
13
14
  }
14
- function guards(node) {
15
- if (node && (!ts.isArrayLiteralExpression(node) || node.elements.some(ts.isSpreadElement))) {
16
- fail(node, "canActivate must be an explicit inline array without spreads");
17
- }
15
+ const builderShape = "defineRpc requires an arrow function destructuring query, mutation, stream and/or channel, returning a parenthesized object of procedures";
16
+ const builders = ["query", "mutation", "stream", "channel"];
17
+ // `({ query, mutation }) => ({ ... })`: the builder names it binds and its procedures.
18
+ function builderCallback(node) {
19
+ if (!ts.isArrowFunction(node) ||
20
+ node.modifiers?.length ||
21
+ node.typeParameters?.length ||
22
+ node.type ||
23
+ node.parameters.length !== 1) {
24
+ fail(node, builderShape);
25
+ }
26
+ const [parameter] = node.parameters;
27
+ if (!ts.isObjectBindingPattern(parameter.name) ||
28
+ parameter.type ||
29
+ parameter.initializer ||
30
+ parameter.dotDotDotToken) {
31
+ fail(parameter, builderShape);
32
+ }
33
+ const bound = new Set();
34
+ for (const element of parameter.name.elements) {
35
+ if (element.propertyName ||
36
+ element.initializer ||
37
+ element.dotDotDotToken ||
38
+ !ts.isIdentifier(element.name) ||
39
+ !builders.includes(element.name.text) ||
40
+ bound.has(element.name.text)) {
41
+ fail(element, "defineRpc's callback may only destructure query, mutation, stream and channel, without renaming");
42
+ }
43
+ bound.add(element.name.text);
44
+ }
45
+ if (!ts.isParenthesizedExpression(node.body)) {
46
+ fail(node.body, builderShape);
47
+ }
48
+ return { bound, procedures: properties(node.body.expression, "RPC procedures") };
18
49
  }
19
50
  function onlyKeys(fields, allowed, node) {
20
51
  for (const key of fields.keys()) {
@@ -93,14 +124,14 @@ async function groupsOf(sources) {
93
124
  }
94
125
  owners.add(owner);
95
126
  const call = directCall(declaration.call, "defineRpc");
96
- const [namespace, methodsNode, options] = call.arguments;
127
+ const [namespace, build, options] = call.arguments;
97
128
  if (call.arguments.length < 2 ||
98
129
  call.arguments.length > 3 ||
99
130
  !namespace ||
100
131
  !ts.isStringLiteral(namespace) ||
101
132
  !/^[A-Za-z_][A-Za-z0-9_]*$/.test(namespace.text) ||
102
- !methodsNode) {
103
- fail(call, "defineRpc requires a literal identifier namespace, inline methods and optional inline options");
133
+ !build) {
134
+ fail(call, "defineRpc requires a literal identifier namespace, a procedure callback and optional inline options");
104
135
  }
105
136
  if (namespace.text === "__proto__") {
106
137
  fail(namespace, "RPC namespace '__proto__' is reserved");
@@ -112,43 +143,44 @@ async function groupsOf(sources) {
112
143
  namespaces.set(namespace.text, declaration);
113
144
  if (options) {
114
145
  const fields = properties(options, "RPC group options");
115
- onlyKeys(fields, ["canActivate"], options);
116
- guards(fields.get("canActivate"));
146
+ onlyKeys(fields, ["use"], options);
117
147
  }
148
+ const { bound, procedures } = builderCallback(build);
118
149
  const methods = [];
119
- for (const [name, value] of properties(methodsNode, "RPC methods")) {
150
+ for (const [name, value] of procedures) {
120
151
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
121
152
  fail(value, "RPC methods must be identifier names");
122
153
  }
123
154
  if (name === "__proto__") {
124
155
  fail(value, "RPC procedure '__proto__' is reserved");
125
156
  }
126
- const procedure = directCall(value, "query/mutation");
127
- let kind;
128
- for (const candidate of ["query", "mutation"]) {
129
- const imported = namedImport(value.getSourceFile(), procedure.expression, candidate);
130
- if (imported && (await genuineImport(imported, launch.typeEntry, sources.parsed.options))) {
131
- kind = candidate;
132
- }
133
- }
134
- if (!kind) {
135
- fail(procedure, "Procedure must directly call a genuine named query import or mutation import");
157
+ const procedure = directCall(value, "query/mutation/stream/channel");
158
+ // The callback's own binding: its body is an object literal, so nothing can shadow it.
159
+ if (!ts.isIdentifier(procedure.expression) || !bound.has(procedure.expression.text)) {
160
+ fail(procedure, "Procedure must directly call the callback's query, mutation, stream or channel");
136
161
  }
162
+ const kind = procedure.expression.text;
137
163
  if (procedure.arguments.length !== 1) {
138
164
  fail(procedure, `${kind} requires one inline options object`);
139
165
  }
140
166
  const fields = properties(procedure.arguments[0], "Procedure options");
141
- onlyKeys(fields, ["handler", "input", "canActivate", "errors"], procedure);
167
+ if (kind === "channel") {
168
+ onlyKeys(fields, ["handler", "input", "message", "use", "errors"], procedure);
169
+ if (!fields.has("message")) {
170
+ fail(procedure, "channel requires message");
171
+ }
172
+ }
173
+ else {
174
+ onlyKeys(fields, ["handler", "input", "use", "errors"], procedure);
175
+ }
142
176
  if (!fields.has("handler")) {
143
177
  fail(procedure, `${kind} requires handler`);
144
178
  }
145
- guards(fields.get("canActivate"));
146
179
  methods.push({
147
180
  name,
148
181
  input: fields.has("input"),
149
182
  kind,
150
183
  errors: errorMetadata(fields.get("errors")),
151
- call: procedure,
152
184
  });
153
185
  }
154
186
  groups.push({ declaration, owner, namespace: namespace.text, methods });
@@ -171,12 +203,13 @@ function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
171
203
  const server = [
172
204
  launchMarkers["server.generated.ts"],
173
205
  payloadImport(registry, context.file, "context"),
174
- `import { createRequestScope, handleRpc, provideLaunchServer } from '@loozo/angular-launch/_server';`,
206
+ `import type { HandleOptions } from '@loozo/angular-launch/server';`,
207
+ `import { createRequestScope, handleChannelUpgrade, handleRpc, provideLaunchServer } from '@loozo/angular-launch/_server';`,
175
208
  ];
176
209
  for (let index = 0; index < groups.length; index += 1) {
177
210
  server.push(payloadImport(registry, groups[index].declaration.file, `group${index}`));
178
211
  }
179
- server.push(`export const registry = { ${groups.map((group, index) => `${JSON.stringify(group.namespace)}: group${index}`).join(", ")} };`, `export const appBinding = { id: ${JSON.stringify(appId)}, context };`, `export const createContext = (request: Request) => createRequestScope(appBinding, request);`, `export const handleRequest = (request: Request) => handleRpc(registry, appBinding, request);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
212
+ server.push(`export const registry = { ${groups.map((group, index) => `${JSON.stringify(group.namespace)}: group${index}`).join(", ")} };`, `export const appBinding = { id: ${JSON.stringify(appId)}, context };`, `export const createContext = (request: Request) => createRequestScope(appBinding, request);`, `export const handleRequest = (request: Request, options: HandleOptions) => handleRpc(registry, appBinding, request, options);`, `export const handleUpgrade = (request: Request, options: HandleOptions) => handleChannelUpgrade(registry, appBinding, request, options);`, `export const provideServer = () => provideLaunchServer(registry, appBinding);`, "");
180
213
  add(desired, registry, server.join("\n"));
181
214
  const byOwner = new Map(groups.map((group) => [group.owner, group]));
182
215
  for (const owner of sources.declarations) {
@@ -216,7 +249,10 @@ function emitLaunch(sources, desired, context, groups, appId, tanstackQuery) {
216
249
  };
217
250
  queriesMetadata[group.namespace] = Object.create(null);
218
251
  for (const { name, kind, input } of group.methods) {
219
- queriesMetadata[group.namespace][name] = { kind, input };
252
+ // Streams and channels have no TanStack options.
253
+ if (kind !== "stream" && kind !== "channel") {
254
+ queriesMetadata[group.namespace][name] = { kind, input };
255
+ }
220
256
  }
221
257
  }
222
258
  lines.push(`export type Rpc = { ${available.map((group, index) => `readonly ${JSON.stringify(group.namespace)}: Client<typeof group${index}>`).join("; ")} };`, `export function injectRpc(): Rpc { return injectClient(${JSON.stringify(metadata)} as const) as Rpc; }`);
@@ -267,7 +303,7 @@ async function validateBindings(sources, validation, context, groups, compiler)
267
303
  baseUrl: undefined,
268
304
  skipLibCheck: false,
269
305
  };
270
- const anchor = await (compiler?.launchAnchor ?? new AnchorState()).anchor(entryFile, ["defineContext", "defineRpc", "query", "mutation"], canonicalOptions);
306
+ const anchor = await (compiler?.launchAnchor ?? new AnchorState()).anchor(entryFile, ["defineContext", "defineRpc"], canonicalOptions);
271
307
  const actualEntry = program.getSourceFile(entryFile);
272
308
  const actualModule = checker.getSymbolAtLocation(actualEntry);
273
309
  const expectedCalls = new Map();
@@ -277,9 +313,6 @@ async function validateBindings(sources, validation, context, groups, compiler)
277
313
  expectedCalls.set(key(context.call), "defineContext");
278
314
  for (const group of groups) {
279
315
  expectedCalls.set(key(group.declaration.call), "defineRpc");
280
- for (const method of group.methods) {
281
- expectedCalls.set(key(method.call), method.kind);
282
- }
283
316
  }
284
317
  const promises = [];
285
318
  for (const source of program.getSourceFiles()) {
@@ -291,7 +324,7 @@ async function validateBindings(sources, validation, context, groups, compiler)
291
324
  const expected = expectedCalls.get(key(node));
292
325
  let spelling;
293
326
  const invoked = unalias(checker, checker.getSymbolAtLocation(node.expression));
294
- for (const name of ["defineContext", "defineRpc", "query", "mutation"]) {
327
+ for (const name of ["defineContext", "defineRpc"]) {
295
328
  const exported = unalias(checker, checker.getExportsOfModule(actualModule).find((symbol) => symbol.name === name));
296
329
  if (invoked && invoked === exported) {
297
330
  spelling = name;
@@ -302,7 +335,7 @@ async function validateBindings(sources, validation, context, groups, compiler)
302
335
  }
303
336
  if (expected || spelling) {
304
337
  if (!expected || spelling !== expected) {
305
- fail(node, "Launch factory calls must be default declarations or inline group procedures");
338
+ fail(node, "defineContext and defineRpc calls must be default declarations");
306
339
  }
307
340
  const imported = namedImport(source, node.expression, expected);
308
341
  promises.push((async () => {
@@ -339,13 +372,17 @@ async function validateBindings(sources, validation, context, groups, compiler)
339
372
  const source = program.getSourceFile(group.declaration.file);
340
373
  const assignment = source.statements.find(ts.isExportAssignment);
341
374
  const call = assignment.expression;
342
- for (const expression of properties(call.arguments[1], "RPC methods").values()) {
375
+ for (const expression of builderCallback(call.arguments[1]).procedures.values()) {
343
376
  const procedure = expression;
344
377
  const fields = properties(procedure.arguments[0], "Procedure options");
345
378
  const input = fields.get("input");
346
379
  if (input && hasNonConcreteSchemaBranch(checker.getTypeAtLocation(input))) {
347
380
  fail(input, "Explicit query input must have a concrete Standard Schema type (also required for mutations)");
348
381
  }
382
+ const message = fields.get("message");
383
+ if (message && hasNonConcreteSchemaBranch(checker.getTypeAtLocation(message))) {
384
+ fail(message, "A channel's message must have a concrete Standard Schema type");
385
+ }
349
386
  const errors = fields.get("errors");
350
387
  if (errors) {
351
388
  for (const value of properties(errors, "Declared RPC errors").values()) {
@@ -434,7 +471,7 @@ function checkGeneratedDomain(sources, validation, generated) {
434
471
  }));
435
472
  }
436
473
  }
437
- async function runGeneration(workspace, options, stopped, compiler) {
474
+ async function runGeneration(workspace, options, stopped, compiler, discovered = () => undefined) {
438
475
  // The built package root (dist/ in the workspace, the tarball root when installed).
439
476
  const root = fileURLToPath(new URL("../", import.meta.url));
440
477
  const manifest = JSON.parse(await readFile(resolve(root, "package.json"), "utf8"));
@@ -477,6 +514,7 @@ async function runGeneration(workspace, options, stopped, compiler) {
477
514
  throw new Error("Launch generation requires effective strict TypeScript checking: noCheck must be false");
478
515
  }
479
516
  const { context, groups } = await groupsOf(sources);
517
+ discovered(context.file);
480
518
  const appManifest = JSON.parse(await readFile(resolve(application, "package.json"), "utf8"));
481
519
  if (typeof appManifest.name !== "string" || appManifest.name.length === 0) {
482
520
  throw new Error("Launch application package.json requires a name for generated app identity");
@@ -598,7 +636,7 @@ export function createGenerationSession(workspace, { tsconfig, scanDirectories,
598
636
  slot.clear();
599
637
  }
600
638
  }
601
- return {
639
+ const session = {
602
640
  async generate({ check = false } = {}, stopped = () => false) {
603
641
  if (closed) {
604
642
  throw new Error("Generation session is disposed");
@@ -619,7 +657,9 @@ export function createGenerationSession(workspace, { tsconfig, scanDirectories,
619
657
  }
620
658
  return false;
621
659
  }
622
- const work = runGeneration(application, { ...fixed, check }, isStopped, compiler);
660
+ const work = runGeneration(application, { ...fixed, check }, isStopped, compiler, (file) => {
661
+ contextFiles.set(session, file);
662
+ });
623
663
  active = work;
624
664
  try {
625
665
  await work;
@@ -641,4 +681,5 @@ export function createGenerationSession(workspace, { tsconfig, scanDirectories,
641
681
  clear();
642
682
  },
643
683
  };
684
+ return session;
644
685
  }
package/index.d.ts CHANGED
@@ -1,3 +1,8 @@
1
1
  export { RpcError, frameworkFailures } from "./client.js";
2
- export type { CallOptions, MutationCallOptions, Client, ClientProcedure, ClientRpcError, FrameworkCode, } from "./client.js";
2
+ export type { CallOptions, ChannelCallOptions, MutationCallOptions, StreamCallOptions, Client, ClientProcedure, ClientRpcError, FrameworkCode, } from "./client.js";
3
+ export type { Channel } from "./channel.js";
4
+ export type { ChannelConnector, ConnectInput, Connection, ConnectionError, ConnectionStatus, ConnectOptions, OptionalConnectInput, ReducingConnectOptions, StreamConnection, StreamConnector, } from "./connect.js";
3
5
  export type { InputIssue, InvalidInputData } from "./input-issues.js";
6
+ export { RpcNotFound, RpcRedirect } from "./outcomes.js";
7
+ export { rpcNavigationErrors } from "./navigation.js";
8
+ export type { RpcNavigationErrorsOptions } from "./navigation.js";
package/index.js CHANGED
@@ -1 +1,3 @@
1
1
  export { RpcError, frameworkFailures } from "./client.js";
2
+ export { RpcNotFound, RpcRedirect } from "./outcomes.js";
3
+ export { rpcNavigationErrors } from "./navigation.js";
package/json.d.ts CHANGED
@@ -11,3 +11,12 @@ export type JsonShape<Value> = Value extends null | boolean | number | string ?
11
11
  readonly [Key in keyof Value]-?: Key extends string | number ? JsonShape<Value[Key]> : never;
12
12
  } : never;
13
13
  export declare function serializeJson(value: unknown): string;
14
+ /**
15
+ * Parses JSON text that must hold strict JSON: what `JSON.parse` accepts, without the
16
+ * nonfinite numbers it makes of overflowing literals such as `1e400`.
17
+ *
18
+ * @param text - The JSON text.
19
+ * @returns The parsed value.
20
+ * @throws SyntaxError when `text` isn't JSON, and TypeError when it holds a nonfinite number.
21
+ */
22
+ export declare function parseJson(text: string): unknown;
package/json.js CHANGED
@@ -46,3 +46,27 @@ export function serializeJson(value) {
46
46
  visit(value);
47
47
  return JSON.stringify(value);
48
48
  }
49
+ /**
50
+ * Parses JSON text that must hold strict JSON: what `JSON.parse` accepts, without the
51
+ * nonfinite numbers it makes of overflowing literals such as `1e400`.
52
+ *
53
+ * @param text - The JSON text.
54
+ * @returns The parsed value.
55
+ * @throws SyntaxError when `text` isn't JSON, and TypeError when it holds a nonfinite number.
56
+ */
57
+ export function parseJson(text) {
58
+ const value = JSON.parse(text);
59
+ const pending = [value];
60
+ while (pending.length > 0) {
61
+ const current = pending.pop();
62
+ if (typeof current === "number" && !Number.isFinite(current)) {
63
+ throw new TypeError("RPC values must be strict JSON");
64
+ }
65
+ if (typeof current === "object" && current !== null) {
66
+ for (const item of Object.values(current)) {
67
+ pending.push(item);
68
+ }
69
+ }
70
+ }
71
+ return value;
72
+ }
@@ -0,0 +1,36 @@
1
+ import { RedirectCommand, type NavigationError } from "@angular/router";
2
+ /** Options for {@link rpcNavigationErrors}. */
3
+ export interface RpcNavigationErrorsOptions {
4
+ /**
5
+ * The root-relative URL of the app's not-found page, such as
6
+ * `createUrl(notFoundRoute, {})`. It's rendered at the requested URL.
7
+ */
8
+ readonly notFound: `/${string}`;
9
+ }
10
+ /**
11
+ * Creates a navigation error handler that follows RPC redirects and renders not-found
12
+ * outcomes.
13
+ *
14
+ * @remarks
15
+ * Pass it to Angular's `withNavigationErrorHandler`. When a guard or resolver fails with
16
+ * an {@link RpcRedirect}, the navigation goes to its `to` instead; during server
17
+ * rendering Angular then answers the page request with a 302. When it fails with an
18
+ * {@link RpcNotFound}, the navigation renders `notFound` while the address bar keeps the
19
+ * requested URL; during server rendering the page is answered with status 404. Any other
20
+ * error is left to Angular, which fails the navigation as usual.
21
+ *
22
+ * Angular takes one navigation error handler. An app with its own calls this one from it,
23
+ * within the handler's injection context, and returns its result.
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * provideRouter(
28
+ * routes,
29
+ * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFoundRoute, {}) })),
30
+ * );
31
+ * ```
32
+ *
33
+ * @param options - The not-found page's URL.
34
+ * @returns The handler, which must run in an injection context.
35
+ */
36
+ export declare function rpcNavigationErrors({ notFound, }: RpcNavigationErrorsOptions): (error: NavigationError) => RedirectCommand | undefined;