@loozo/angular-launch 0.0.6 → 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 (85) hide show
  1. package/README.md +715 -255
  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 +3 -1
  9. package/channel.js +3 -2
  10. package/client.d.ts +14 -24
  11. package/generation/index.d.ts +2 -123
  12. package/generation/index.js +3 -685
  13. package/generation/redirects.d.ts +14 -0
  14. package/generation/redirects.js +43 -0
  15. package/generation/run.d.ts +168 -0
  16. package/generation/run.js +659 -0
  17. package/index.d.ts +2 -0
  18. package/index.js +1 -0
  19. package/launch-queries.d.ts +16 -0
  20. package/launch-queries.js +3 -0
  21. package/navigation.d.ts +3 -3
  22. package/navigation.js +1 -1
  23. package/node/index.d.ts +3 -0
  24. package/node/index.js +6 -3
  25. package/node/upgrade-listener-slot.d.ts +1 -0
  26. package/node/upgrade-listener-slot.js +4 -0
  27. package/outcomes.d.ts +23 -7
  28. package/outcomes.js +58 -12
  29. package/package.json +15 -11
  30. package/redirect-translation.d.ts +53 -0
  31. package/redirect-translation.js +141 -0
  32. package/{generated.js → remote-client.js} +27 -21
  33. package/route-types.d.ts +130 -0
  34. package/route-types.js +1 -0
  35. package/route.d.ts +45 -0
  36. package/route.js +113 -0
  37. package/schemas/application.json +19 -3
  38. package/schemas/serve.json +3 -3
  39. package/server/application.d.ts +107 -0
  40. package/server/application.js +108 -0
  41. package/server/backend.d.ts +25 -13
  42. package/server/backend.js +39 -24
  43. package/server/channel-messages.d.ts +1 -1
  44. package/server/channel-messages.js +1 -1
  45. package/server/channel-socket.d.ts +1 -1
  46. package/server/definitions.d.ts +146 -298
  47. package/server/definitions.js +29 -117
  48. package/server/dispatch.d.ts +67 -63
  49. package/server/dispatch.js +121 -61
  50. package/server/event-stream.d.ts +2 -2
  51. package/server/event-stream.js +1 -1
  52. package/server/generated.d.ts +2 -1
  53. package/server/generated.js +2 -1
  54. package/server/index.d.ts +3 -2
  55. package/server/index.js +2 -1
  56. package/server/outcomes.d.ts +26 -13
  57. package/server/outcomes.js +43 -16
  58. package/server/read-cookies.d.ts +19 -0
  59. package/server/read-cookies.js +39 -0
  60. package/server/response-effects.d.ts +2 -2
  61. package/server/stages.d.ts +62 -0
  62. package/server/stages.js +51 -0
  63. package/server/upgrade.d.ts +11 -12
  64. package/server/upgrade.js +13 -14
  65. package/source-text.d.ts +1 -0
  66. package/source-text.js +56 -0
  67. package/stream.d.ts +6 -3
  68. package/stream.js +8 -6
  69. package/tanstack-query/README.md +15 -15
  70. package/tanstack-query/create-queries.d.ts +2 -0
  71. package/tanstack-query/{generated.js → create-queries.js} +8 -9
  72. package/tanstack-query/hydration-window.d.ts +11 -0
  73. package/tanstack-query/hydration-window.js +9 -0
  74. package/tanstack-query/hydration.d.ts +4 -14
  75. package/tanstack-query/hydration.js +9 -12
  76. package/tanstack-query/index.d.ts +1 -1
  77. package/tanstack-query/queries.d.ts +42 -27
  78. package/testing/call-procedure.d.ts +154 -0
  79. package/testing/call-procedure.js +97 -0
  80. package/testing/index.d.ts +2 -0
  81. package/testing/index.js +1 -0
  82. package/generation/context-file.d.ts +0 -2
  83. package/generation/context-file.js +0 -3
  84. package/tanstack-query/generated.d.ts +0 -5
  85. /package/{generated.d.ts → remote-client.d.ts} +0 -0
@@ -6,8 +6,36 @@ import { declaredFailures } from "./errors.js";
6
6
  import { eventStream } from "./event-stream.js";
7
7
  import { outcomeOf } from "./outcomes.js";
8
8
  import { createResponseEffects, } from "./response-effects.js";
9
- const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v1");
9
+ import { createStageRunner } from "./stages.js";
10
+ // Shared by every copy of the package, so a scope one copy created runs its stages when
11
+ // another copy dispatches with it. The value holds the scope's stage runner and its
12
+ // rendering-call function.
13
+ const scopeMarker = Symbol.for("@loozo/angular-launch/private-request-scope/v3");
10
14
  const bindingHeader = "x-loozo-launch-scope";
15
+ /**
16
+ * Runs one call made while rendering a page in the copy of the package that created
17
+ * `scope`, with that copy's application binding.
18
+ *
19
+ * @remarks
20
+ * Internal; not exported from a public entry point. Angular bundles the server entry, which
21
+ * creates the scope and answers RPCs, apart from the server application, which renders, so
22
+ * modules both import exist once in each bundle. Running the call in the creating copy
23
+ * runs the stages, middleware and handlers of the bundle that answers RPCs, so a page and
24
+ * an RPC of one server share their module state. The call otherwise runs as
25
+ * {@link runProcedure} in `"rendering"` mode, which checks the scope again.
26
+ *
27
+ * @param scope - A scope that passed {@link assertBoundScope} for the rendering application.
28
+ * @param path - The request path.
29
+ * @param envelope - The parsed request body.
30
+ * @param request - The page request the scope is bound to.
31
+ * @param signal - The call's abort signal.
32
+ * @param effects - Collects the call's cookies and headers.
33
+ * @returns The reply to deliver.
34
+ */
35
+ export function runRenderingCall(scope, path, envelope, request, signal, effects) {
36
+ const state = scope[scopeMarker];
37
+ return state.render(path, envelope, request, signal, effects);
38
+ }
11
39
  /**
12
40
  * Checks whether a value has the shape of a {@link RequestScope}.
13
41
  *
@@ -19,50 +47,56 @@ const bindingHeader = "x-loozo-launch-scope";
19
47
  * @returns `true` for values carrying the request scope brand and fields.
20
48
  */
21
49
  export function isRequestScope(value) {
22
- return (typeof value === "object" &&
23
- value !== null &&
24
- scopeMarker in value &&
25
- value[scopeMarker] === true &&
50
+ if (typeof value !== "object" || value === null || !(scopeMarker in value)) {
51
+ return false;
52
+ }
53
+ const runner = value[scopeMarker];
54
+ return (typeof runner === "object" &&
55
+ runner !== null &&
56
+ "run" in runner &&
57
+ typeof runner.run === "function" &&
58
+ "render" in runner &&
59
+ typeof runner.render === "function" &&
26
60
  "request" in value &&
27
61
  value.request instanceof Request &&
28
62
  "appId" in value &&
29
63
  typeof value.appId === "string" &&
30
64
  "binding" in value &&
31
- typeof value.binding === "string" &&
32
- "value" in value);
65
+ typeof value.binding === "string");
33
66
  }
34
67
  /**
35
- * Creates the context for a live server request and binds them into a
36
- * {@link RequestScope}.
68
+ * Binds a live server request into a {@link RequestScope}, running nothing.
37
69
  *
38
70
  * @remarks
39
71
  * Internal: exported only from `@loozo/angular-launch/_server` for the generated
40
- * `createContext` in `server.generated.ts`; call that instead.
72
+ * `createRequestScope` in `server.generated.ts`; call that instead.
41
73
  * The scope's `request` is a clone of `request` with an added
42
- * `x-loozo-launch-scope` header, so the original stays usable. The context factory
43
- * receives that clone.
74
+ * `x-loozo-launch-scope` header, so the original stays usable. Stages receive that clone
75
+ * and its signal. Calls made while rendering with the scope run with `application`, in
76
+ * this copy of the package: see {@link runRenderingCall}.
44
77
  *
45
- * @typeParam Definition - The application's context definition.
46
78
  * @param application - The application binding.
47
79
  * @param request - The live server request.
48
80
  * @returns The request scope.
49
- * @throws Rejects with whatever the context factory throws or rejects with, or with a
50
- * `TypeError` when `request`'s body was already read and can't be cloned.
81
+ * @throws TypeError when `request`'s body was already read and can't be cloned.
51
82
  */
52
- export async function createRequestScope(application, request) {
83
+ export function createRequestScope(application, request) {
53
84
  const binding = crypto.randomUUID();
54
85
  const headers = new Headers(request.headers);
55
86
  headers.set(bindingHeader, binding);
56
87
  // Keep the caller's body usable and its signal linked via native Request clones.
57
88
  const boundRequest = new Request(request.clone(), { headers });
58
- const value = await application.context.create(boundRequest);
59
- return {
89
+ const run = createStageRunner({ request: boundRequest, signal: boundRequest.signal });
90
+ const scope = {
60
91
  appId: application.id,
61
92
  binding,
62
93
  request: boundRequest,
63
- value: value,
64
- [scopeMarker]: true,
94
+ [scopeMarker]: {
95
+ run,
96
+ render: (path, envelope, pageRequest, signal, effects) => runProcedure(path, envelope, scope, application, pageRequest, "rendering", signal, effects),
97
+ },
65
98
  };
99
+ return scope;
66
100
  }
67
101
  export function assertBoundScope(scope, application, request) {
68
102
  if (!isRequestScope(scope) ||
@@ -73,7 +107,7 @@ export function assertBoundScope(scope, application, request) {
73
107
  throw new Error("Launch request/application scope binding mismatch");
74
108
  }
75
109
  }
76
- function outcomeReply(outcome) {
110
+ function outcomeReply(outcome, application) {
77
111
  if (outcome.kind === "forbidden") {
78
112
  return failure("FORBIDDEN");
79
113
  }
@@ -81,6 +115,11 @@ function outcomeReply(outcome) {
81
115
  return { status: 404, body: { notFound: null } };
82
116
  }
83
117
  // No Location header: fetch then hands the 303 to the client instead of following it.
118
+ // A translated app's page builds swap the listed static words into their own language; any
119
+ // other frame keeps exactly `{ to }`.
120
+ if (application.translateSegments && outcome.words.length > 0) {
121
+ return { status: 303, body: { redirect: { to: outcome.to, words: outcome.words } } };
122
+ }
84
123
  return { status: 303, body: { redirect: { to: outcome.to } } };
85
124
  }
86
125
  export function failure(code) {
@@ -100,8 +139,7 @@ export function isJsonMediaType(contentType) {
100
139
  return contentType?.split(";", 1)[0].trim().toLowerCase() === "application/json";
101
140
  }
102
141
  /**
103
- * Runs `chain` in order around `last`, passing each middleware the context the previous
104
- * one continued with.
142
+ * Runs `chain` in order around `last`, passing each middleware the call's context.
105
143
  *
106
144
  * @remarks
107
145
  * Rejects when a middleware throws, calls `next` twice (whether it then returns or
@@ -112,26 +150,22 @@ export function isJsonMediaType(contentType) {
112
150
  * detached, or replaced it with another error such as `forbidden()`.
113
151
  */
114
152
  async function runChain(chain, context, args, last) {
115
- async function step(index, current) {
153
+ async function step(index) {
116
154
  if (index === chain.length) {
117
- await last(current);
155
+ await last();
118
156
  return;
119
157
  }
120
158
  const token = {};
121
159
  let calls = 0;
122
160
  let rest;
123
- function next(added) {
161
+ function next() {
124
162
  calls += 1;
125
163
  let continued;
126
164
  if (calls > 1) {
127
165
  continued = Promise.reject(new Error("Launch middleware called next() more than once"));
128
166
  }
129
167
  else {
130
- let merged = current;
131
- if (added !== undefined) {
132
- merged = { ...current, ...added };
133
- }
134
- continued = step(index + 1, merged).then(() => token);
168
+ continued = step(index + 1).then(() => token);
135
169
  rest = continued;
136
170
  }
137
171
  // A middleware that doesn't await this promise can't leave its rejection unhandled;
@@ -139,11 +173,19 @@ async function runChain(chain, context, args, last) {
139
173
  continued.catch(() => undefined);
140
174
  return continued;
141
175
  }
142
- const run = chain[index].run;
176
+ const entry = chain[index];
177
+ let run;
178
+ // A bare function is the middleware's `run`.
179
+ if (typeof entry === "function") {
180
+ run = entry;
181
+ }
182
+ else {
183
+ run = entry.run;
184
+ }
143
185
  let returned;
144
186
  let thrown;
145
187
  try {
146
- returned = await run({ ...args, context: current, next });
188
+ returned = await run({ ...args, context, next });
147
189
  }
148
190
  catch (error) {
149
191
  thrown = { error };
@@ -162,7 +204,7 @@ async function runChain(chain, context, args, last) {
162
204
  throw thrown.error;
163
205
  }
164
206
  }
165
- await step(0, context);
207
+ await step(0);
166
208
  }
167
209
  async function declaredReply(procedure, error) {
168
210
  let declared;
@@ -202,13 +244,17 @@ async function declaredReply(procedure, error) {
202
244
  * `RPC_NOT_FOUND`; the
203
245
  * envelope must be strict JSON (`INTERNAL` otherwise, such as for `{ input: undefined }`,
204
246
  * a cycle or an accessor), and exactly `{ input }` (`INVALID_INPUT` with no issues);
205
- * the group's middleware runs with no input; the input must pass the schema
247
+ * the owning route's stages run, root first, each at most once per scope (a stage that
248
+ * throws `forbidden()`, `notFound()` or `redirect()` answers with that outcome, and any
249
+ * other failure gives `INTERNAL` with the reply's `failedStage` naming it); the owning
250
+ * route's `.use()` middleware runs with no input; the input must pass the schema
206
251
  * (`INVALID_INPUT` with the schema's issues), or be `null` without one (`INVALID_INPUT`
207
252
  * with no issues); the procedure's middleware runs with the validated input; then the
208
253
  * handler. The handler's strict JSON result is returned with status 200, and its
209
254
  * declared errors with their status. `forbidden()` thrown from middleware or the
210
255
  * handler gives `FORBIDDEN`, `notFound()` a 404 with `{ notFound: null }` and
211
- * `redirect(to)` a 303 with `{ redirect: { to } }`; a middleware that calls `next` twice
256
+ * `redirect()` a 303 with `{ redirect: { to } }` (plus `words` in a translated application);
257
+ * a middleware that calls `next` twice
212
258
  * or doesn't return its result gives `INTERNAL`.
213
259
  *
214
260
  * A stream's handler returns an iterable instead of a result. Its iterator goes to
@@ -220,13 +266,12 @@ async function declaredReply(procedure, error) {
220
266
  * `inbox` and validated with its message schema. A message that fails validation, or a
221
267
  * protocol violation the inbox reports, ends the call with `INVALID_INPUT`.
222
268
  *
223
- * Middleware and handlers set cookies and headers through `effects.control`; the caller
224
- * commits and applies them.
269
+ * Stages, middleware and handlers set cookies and headers through `effects.control`; the
270
+ * caller commits and applies them. A stage writes to the call that first ran it.
225
271
  *
226
- * @param registry - The application's RPC groups.
227
272
  * @param path - The request path.
228
273
  * @param envelope - The parsed request body.
229
- * @param scope - The request scope whose context the call receives.
274
+ * @param scope - The request scope whose stages the call runs.
230
275
  * @param application - The application binding the scope must belong to.
231
276
  * @param request - The request the scope must be bound to.
232
277
  * @param mode - `"http"` for browser requests (the default), `"socket"` for websocket
@@ -238,23 +283,23 @@ async function declaredReply(procedure, error) {
238
283
  * @param inbox - A channel's incoming messages.
239
284
  * @returns The reply to send.
240
285
  */
241
- export async function dispatch(registry, path, envelope, scope, application, request, mode = "http", signal = request.signal, effects = createResponseEffects(), start, inbox) {
286
+ export async function runProcedure(path, envelope, scope, application, request, mode = "http", signal = request.signal, effects = createResponseEffects(), start, inbox) {
242
287
  try {
243
288
  assertBoundScope(scope, application, request);
244
289
  const parts = /^\/_rpc\/([A-Za-z_][A-Za-z0-9_]*)\/([A-Za-z_][A-Za-z0-9_]*)$/.exec(path);
245
- if (!parts || !Object.hasOwn(registry, parts[1])) {
290
+ if (!parts || !Object.hasOwn(application.namespaces, parts[1])) {
246
291
  return failure("RPC_NOT_FOUND");
247
292
  }
248
- const group = registry[parts[1]];
249
- if (!Object.hasOwn(group.procedures, parts[2])) {
293
+ const namespace = application.namespaces[parts[1]];
294
+ if (!Object.hasOwn(namespace.procedures, parts[2])) {
250
295
  return failure("RPC_NOT_FOUND");
251
296
  }
252
- const procedure = group.procedures[parts[2]];
297
+ const procedure = namespace.procedures[parts[2]];
253
298
  if (procedure.kind !== "query" &&
254
299
  procedure.kind !== "mutation" &&
255
300
  procedure.kind !== "stream" &&
256
301
  procedure.kind !== "channel") {
257
- throw new Error("Launch registry contains an unsupported procedure");
302
+ throw new Error("Launch application contains an unsupported procedure");
258
303
  }
259
304
  // Rendering never performs writes, even for unmarked HttpClient calls or
260
305
  // callers/interceptors that relabel a generated method or enable caching. Streams
@@ -278,9 +323,27 @@ export async function dispatch(registry, path, envelope, scope, application, req
278
323
  }
279
324
  let reply;
280
325
  const response = effects.control;
326
+ let context = {};
327
+ if (namespace.stages.length > 0) {
328
+ const stages = namespace.stages;
329
+ const state = scope[scopeMarker];
330
+ const staged = await state.run(stages, response);
331
+ if ("failed" in staged) {
332
+ const outcome = outcomeOf(staged.error);
333
+ if (outcome !== undefined) {
334
+ return outcomeReply(outcome, application);
335
+ }
336
+ console.error("Launch context stage failed", staged.error);
337
+ return {
338
+ ...failure("INTERNAL"),
339
+ failedStage: { route: staged.failed.route, error: staged.error },
340
+ };
341
+ }
342
+ context = staged.context;
343
+ }
281
344
  try {
282
- // Group middleware runs before validation, so it never sees the raw input.
283
- await runChain(group.use, scope.value, { input: undefined, request, signal, response }, async (groupContext) => {
345
+ // The route's middleware runs before validation, so it never sees the raw input.
346
+ await runChain(namespace.use, context, { input: undefined, request, signal, response }, async () => {
284
347
  let input;
285
348
  if (procedure.input) {
286
349
  const parsed = await procedure.input["~standard"].validate(normalized.input);
@@ -294,7 +357,7 @@ export async function dispatch(registry, path, envelope, scope, application, req
294
357
  reply = invalidInput();
295
358
  return;
296
359
  }
297
- await runChain(procedure.use, groupContext, { input, request, signal, response }, async (context) => {
360
+ await runChain(procedure.use, context, { input, request, signal, response }, async () => {
298
361
  const args = { context, input, request, signal, response };
299
362
  if (isChannel) {
300
363
  // The caller left while the pipeline ran: the handler doesn't run, and the
@@ -327,7 +390,7 @@ export async function dispatch(registry, path, envelope, scope, application, req
327
390
  catch (error) {
328
391
  const outcome = outcomeOf(error);
329
392
  if (outcome !== undefined) {
330
- return outcomeReply(outcome);
393
+ return outcomeReply(outcome, application);
331
394
  }
332
395
  // The caller sent a bad message: its own fault, not an unexpected failure.
333
396
  if (error instanceof MessageRefused) {
@@ -399,14 +462,13 @@ export function crossSiteReason(request, origins) {
399
462
  * app's own origin, otherwise the reply is `FORBIDDEN`: an `Origin` listed in `origins`
400
463
  * passes; otherwise `Sec-Fetch-Site`, when sent, must be `same-origin`; otherwise
401
464
  * `Origin`, when sent, must equal the request URL's origin; a request with neither
402
- * header is refused. No context is created for any of these refusals. A fresh context
403
- * is then created before the body is parsed; if that fails the reply is `INTERNAL`, even
404
- * when the body isn't JSON. Otherwise a body that isn't JSON gives `INVALID_INPUT` with
405
- * no issues.
465
+ * header is refused. No stage runs for any of these refusals. A fresh request scope is
466
+ * then created, which runs nothing, and a body that isn't JSON gives `INVALID_INPUT` with
467
+ * no issues before any stage runs.
406
468
  * JSON responses carry `Cache-Control: private, no-store`, `Vary: Cookie` and
407
469
  * `X-Content-Type-Options: nosniff`.
408
470
  *
409
- * Once the call reached `dispatch`, its response carries the headers and cookies the
471
+ * Once the call reached {@link runProcedure}, its response carries the headers and cookies the
410
472
  * call set, whatever its outcome. Launch's own headers replace the call's headers of the
411
473
  * same name, and each cookie adds a `Set-Cookie` header.
412
474
  *
@@ -418,14 +480,12 @@ export function crossSiteReason(request, origins) {
418
480
  * ones set when the handler returned its iterable: setting a cookie later throws, and
419
481
  * later header changes are ignored.
420
482
  *
421
- * @typeParam Definition - The application's context definition.
422
- * @param registry - The application's RPC groups.
423
483
  * @param application - The application binding.
424
484
  * @param request - The incoming server request.
425
485
  * @param options - The allowed hosts and further allowed origins.
426
486
  * @returns The RPC response, or `null` when the path doesn't start with `/_rpc/`.
427
487
  */
428
- export async function handleRpc(registry, application, request, { allowedHosts, origins = [] }) {
488
+ export async function handleRpc(application, request, { allowedHosts, origins = [] }) {
429
489
  const url = new URL(request.url);
430
490
  if (!url.pathname.startsWith("/_rpc/")) {
431
491
  return null;
@@ -446,7 +506,7 @@ export async function handleRpc(registry, application, request, { allowedHosts,
446
506
  const effects = createResponseEffects();
447
507
  let reply;
448
508
  try {
449
- const scope = await createRequestScope(application, request);
509
+ const scope = createRequestScope(application, request);
450
510
  let envelope;
451
511
  try {
452
512
  envelope = parseJson(await request.text());
@@ -458,7 +518,7 @@ export async function handleRpc(registry, application, request, { allowedHosts,
458
518
  const cancel = new AbortController();
459
519
  const signal = AbortSignal.any([scope.request.signal, cancel.signal]);
460
520
  const started = Promise.withResolvers();
461
- const outcome = dispatch(registry, url.pathname, envelope, scope, application, scope.request, "http", signal, effects, started.resolve);
521
+ const outcome = runProcedure(url.pathname, envelope, scope, application, scope.request, "http", signal, effects, started.resolve);
462
522
  // Failures before a stream's handler returned are ordinary replies.
463
523
  const first = await Promise.race([outcome, started.promise]);
464
524
  if ("iterator" in first) {
@@ -469,7 +529,7 @@ export async function handleRpc(registry, application, request, { allowedHosts,
469
529
  reply = first;
470
530
  }
471
531
  catch (error) {
472
- console.error("Launch context failed", error);
532
+ console.error("Launch request scope failed", error);
473
533
  reply = failure("INTERNAL");
474
534
  }
475
535
  effects.commit();
@@ -5,7 +5,7 @@ export declare const keepAliveMs = 15000;
5
5
  * A stream whose handler returned its iterable: the response can start.
6
6
  *
7
7
  * @remarks
8
- * Internal. `dispatch` hands it over and waits for `finished`: resolving it ends the
8
+ * Internal. `runProcedure` hands it over and waits for `finished`: resolving it ends the
9
9
  * handler's part of the call, rejecting it fails the call with that error.
10
10
  */
11
11
  export interface StreamStart {
@@ -55,7 +55,7 @@ export declare function failureFrame(reply: Reply): string;
55
55
  * threw, so middleware that wraps the stream never cleans up under a running handler.
56
56
  *
57
57
  * @param start - The started stream.
58
- * @param outcome - The whole call's reply, from `dispatch`.
58
+ * @param outcome - The whole call's reply, from `runProcedure`.
59
59
  * @param cancel - Aborted when the body is cancelled.
60
60
  * @param signal - The call's signal: it follows `cancel` and the request's signal.
61
61
  * @returns The response body.
@@ -70,7 +70,7 @@ export function failureFrame(reply) {
70
70
  * threw, so middleware that wraps the stream never cleans up under a running handler.
71
71
  *
72
72
  * @param start - The started stream.
73
- * @param outcome - The whole call's reply, from `dispatch`.
73
+ * @param outcome - The whole call's reply, from `runProcedure`.
74
74
  * @param cancel - Aborted when the body is cancelled.
75
75
  * @param signal - The call's signal: it follows `cancel` and the request's signal.
76
76
  * @returns The response body.
@@ -1,3 +1,4 @@
1
- export { createRequestScope, handleRpc } from "./dispatch.js";
1
+ export { bindApplication } from "./application.js";
2
+ export { createRequestScope, handleRpc, runProcedure } from "./dispatch.js";
2
3
  export { handleChannelUpgrade } from "./upgrade.js";
3
4
  export { provideLaunchServer } from "./backend.js";
@@ -1,4 +1,5 @@
1
1
  // Internal entry point for the generated server.generated.ts; not public API.
2
- export { createRequestScope, handleRpc } from "./dispatch.js";
2
+ export { bindApplication } from "./application.js";
3
+ export { createRequestScope, handleRpc, runProcedure } from "./dispatch.js";
3
4
  export { handleChannelUpgrade } from "./upgrade.js";
4
5
  export { provideLaunchServer } from "./backend.js";
package/server/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- export { defineContext, defineRpc, middleware } from "./definitions.js";
1
+ export { middleware } from "./definitions.js";
2
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";
3
+ export { readCookies } from "./read-cookies.js";
4
+ export type { CallArgs, ChannelOptions, ErrorDefinition, ErrorDefinitions, ErrorFactories, ErrorStatus, InputOf, MiddlewareDefinition, MiddlewareArgs, MiddlewareResult, OutputOf, Procedure, ProcedureBuilder, ProcedureDefinition, ProcedureKind, ProcedureOptions, StageArgs, StreamOptions, Schema, } from "./definitions.js";
4
5
  export type { DeclaredFailure } from "./errors.js";
5
6
  export type { CookieOptions, ResponseControl } from "./response-effects.js";
6
7
  export type { JsonShape } from "../json.js";
package/server/index.js CHANGED
@@ -1,3 +1,4 @@
1
- export { defineContext, defineRpc, middleware } from "./definitions.js";
1
+ export { middleware } from "./definitions.js";
2
2
  export { forbidden, notFound, redirect } from "./outcomes.js";
3
+ export { readCookies } from "./read-cookies.js";
3
4
  export { finishLaunchRendering } from "./backend.js";
@@ -1,3 +1,4 @@
1
+ import { type AnyRoute, type Destination, type SearchOf, type UrlValues } from "@loozo/angular-router/_core";
1
2
  /** What a thrown outcome asks the server to answer with. Internal. */
2
3
  export type Outcome = {
3
4
  readonly kind: "forbidden";
@@ -5,7 +6,8 @@ export type Outcome = {
5
6
  readonly kind: "notFound";
6
7
  } | {
7
8
  readonly kind: "redirect";
8
- readonly to: string;
9
+ readonly to: `/${string}`;
10
+ readonly words: readonly number[];
9
11
  };
10
12
  /**
11
13
  * Creates an error that refuses the call with `FORBIDDEN` when thrown from middleware
@@ -42,29 +44,40 @@ export declare function forbidden(): Error;
42
44
  */
43
45
  export declare function notFound(): Error;
44
46
  /**
45
- * Creates an error that answers the call with a redirect to `to` when thrown from
46
- * middleware or a handler.
47
+ * Creates an error that answers the call with a redirect to an app destination when thrown
48
+ * from middleware or a handler.
47
49
  *
48
50
  * @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.
51
+ * The redirect goes to `createUrl(destination, values)`; both arguments are typed exactly as
52
+ * `createUrl`'s, so `values` is required (`{}` for none). The caller's call rejects with
53
+ * `RpcRedirect` from `@loozo/angular-launch`. In a guard or resolver, `rpcNavigationErrors()`
54
+ * navigates to its `to` instead, which during server rendering answers the page request with
55
+ * a 302. Nothing navigates outside navigation. Only declared destinations are targets: a
56
+ * redirect target's search keys must be declared on its route, and an external redirect
57
+ * (OAuth, for example) is data the page acts on.
58
+ *
59
+ * With `translateSegments`, the server still builds the canonical URL and the frame also
60
+ * lists which of its path segments are static words, counted in order across a named outlet's
61
+ * anchor and group, so the page's own build can put them in its language.
54
62
  *
55
63
  * @example
56
64
  * ```ts
65
+ * // signIn: the sign-in route's `destination`, from its destination.generated.ts
57
66
  * if (context.user === null) {
58
- * throw redirect(createUrl(signIn, {}));
67
+ * throw redirect(signIn, {});
59
68
  * }
69
+ *
70
+ * throw redirect(todo, { params: { id: 2 }, fragment: "title" });
60
71
  * ```
61
72
  *
62
- * @param to - The root-relative URL to go to, such as `/sign-in?next=%2Ftodos`.
73
+ * @param destination - A genuine destination imported from a `destination.generated.ts`.
74
+ * @param values - Its params, search and fragment, as `createUrl` takes them.
63
75
  * @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/`.
76
+ * @throws TypeError for anything but a genuine destination from this package instance, and
77
+ * for values `createUrl` refuses; a codec's own failure propagates unchanged, as from
78
+ * `createUrl`.
66
79
  */
67
- export declare function redirect(to: `/${string}`): Error;
80
+ export declare function redirect<Target extends AnyRoute, SearchKeys extends keyof SearchOf<NoInfer<Target>> = never>(destination: Destination<Target>, values: UrlValues<NoInfer<Target>, SearchKeys>): Error;
68
81
  /**
69
82
  * Reads the outcome a thrown value carries, if it was created by an outcome factory.
70
83
  * Internal.
@@ -1,4 +1,4 @@
1
- import { isRootRelative } from "../outcomes.js";
1
+ import { createUrl, destinationRecord, } from "@loozo/angular-router/_core";
2
2
  // Keyed with Symbol.for so the brand survives the duplicate module copies a native SSR
3
3
  // bundle may load, and non-enumerable so it never reaches JSON.
4
4
  const outcomeKey = Symbol.for("@loozo/angular-launch/outcome/v1");
@@ -46,33 +46,60 @@ export function notFound() {
46
46
  return outcomeError("RPC not found outcome", { kind: "notFound" });
47
47
  }
48
48
  /**
49
- * Creates an error that answers the call with a redirect to `to` when thrown from
50
- * middleware or a handler.
49
+ * Creates an error that answers the call with a redirect to an app destination when thrown
50
+ * from middleware or a handler.
51
51
  *
52
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.
53
+ * The redirect goes to `createUrl(destination, values)`; both arguments are typed exactly as
54
+ * `createUrl`'s, so `values` is required (`{}` for none). The caller's call rejects with
55
+ * `RpcRedirect` from `@loozo/angular-launch`. In a guard or resolver, `rpcNavigationErrors()`
56
+ * navigates to its `to` instead, which during server rendering answers the page request with
57
+ * a 302. Nothing navigates outside navigation. Only declared destinations are targets: a
58
+ * redirect target's search keys must be declared on its route, and an external redirect
59
+ * (OAuth, for example) is data the page acts on.
60
+ *
61
+ * With `translateSegments`, the server still builds the canonical URL and the frame also
62
+ * lists which of its path segments are static words, counted in order across a named outlet's
63
+ * anchor and group, so the page's own build can put them in its language.
58
64
  *
59
65
  * @example
60
66
  * ```ts
67
+ * // signIn: the sign-in route's `destination`, from its destination.generated.ts
61
68
  * if (context.user === null) {
62
- * throw redirect(createUrl(signIn, {}));
69
+ * throw redirect(signIn, {});
63
70
  * }
71
+ *
72
+ * throw redirect(todo, { params: { id: 2 }, fragment: "title" });
64
73
  * ```
65
74
  *
66
- * @param to - The root-relative URL to go to, such as `/sign-in?next=%2Ftodos`.
75
+ * @param destination - A genuine destination imported from a `destination.generated.ts`.
76
+ * @param values - Its params, search and fragment, as `createUrl` takes them.
67
77
  * @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/`.
78
+ * @throws TypeError for anything but a genuine destination from this package instance, and
79
+ * for values `createUrl` refuses; a codec's own failure propagates unchanged, as from
80
+ * `createUrl`.
70
81
  */
71
- export function redirect(to) {
72
- if (!isRootRelative(to)) {
73
- throw new TypeError(`redirect() takes a root-relative URL, not ${JSON.stringify(to)}`);
82
+ export function redirect(destination, values) {
83
+ const record = destinationRecord(destination);
84
+ const to = createUrl(destination, values);
85
+ const params = values.params;
86
+ const words = [];
87
+ let position = 0;
88
+ // createUrl writes one path segment per static or scalar segment and one per catchall
89
+ // element, in order: in a named outlet, the anchor's before the group's.
90
+ for (const segment of [...(record.url.branch?.anchor ?? []), ...record.url.segments]) {
91
+ if (segment.kind === "static") {
92
+ words.push(position);
93
+ position += 1;
94
+ }
95
+ else if (segment.kind === "scalar") {
96
+ position += 1;
97
+ }
98
+ else {
99
+ position += params[segment.name].length;
100
+ }
74
101
  }
75
- return outcomeError("RPC redirect outcome", { kind: "redirect", to });
102
+ return outcomeError("RPC redirect outcome", { kind: "redirect", to, words });
76
103
  }
77
104
  /**
78
105
  * Reads the outcome a thrown value carries, if it was created by an outcome factory.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Reads the request's cookies from its `Cookie` header.
3
+ *
4
+ * @remarks
5
+ * Values are returned as sent, without decoding, as `setCookie` doesn't encode. A repeated
6
+ * name keeps its first occurrence in the header. The header doesn't carry the cookies' paths
7
+ * or domains, so which cookie that is depends on the browser's order. Pairs without a name
8
+ * are skipped. During server rendering every call reads the page request, so a cookie set
9
+ * earlier in the render isn't seen.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const token = readCookies(request).get("session");
14
+ * ```
15
+ *
16
+ * @param request - The request, such as `request` in a stage, middleware or handler.
17
+ * @returns A new map of cookie values by name.
18
+ */
19
+ export declare function readCookies(request: Request): ReadonlyMap<string, string>;