@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
@@ -0,0 +1,16 @@
1
+ import { InjectionToken } from "@angular/core";
2
+ /**
3
+ * Builds a route's TanStack factories over its client.
4
+ *
5
+ * @remarks
6
+ * Internal. `provideLaunchQueries()` provides it, so the root entry builds `route.queries`
7
+ * without importing `@tanstack/*` itself.
8
+ */
9
+ export type CreateQueries = (remote: Readonly<Record<string, Readonly<Record<string, unknown>>>>, namespaces: Readonly<Record<string, Readonly<Record<string, QueriesMethod>>>>) => unknown;
10
+ /** What a route's TanStack factories need to know about one query or mutation. */
11
+ export interface QueriesMethod {
12
+ readonly kind: "query" | "mutation";
13
+ readonly input: boolean;
14
+ }
15
+ /** Internal: provided by `provideLaunchQueries()`, read by `route.queries`. */
16
+ export declare const launchQueries: InjectionToken<CreateQueries>;
@@ -0,0 +1,3 @@
1
+ import { InjectionToken } from "@angular/core";
2
+ /** Internal: provided by `provideLaunchQueries()`, read by `route.queries`. */
3
+ export const launchQueries = new InjectionToken("Launch route queries");
package/navigation.d.ts CHANGED
@@ -2,8 +2,8 @@ import { RedirectCommand, type NavigationError } from "@angular/router";
2
2
  /** Options for {@link rpcNavigationErrors}. */
3
3
  export interface RpcNavigationErrorsOptions {
4
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.
5
+ * The root-relative URL of the app's not-found page, such as `createUrl(notFound, {})`
6
+ * with the not-found route's generated `destination`. It's rendered at the requested URL.
7
7
  */
8
8
  readonly notFound: `/${string}`;
9
9
  }
@@ -26,7 +26,7 @@ export interface RpcNavigationErrorsOptions {
26
26
  * ```ts
27
27
  * provideRouter(
28
28
  * routes,
29
- * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFoundRoute, {}) })),
29
+ * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
30
30
  * );
31
31
  * ```
32
32
  *
package/navigation.js CHANGED
@@ -20,7 +20,7 @@ import { RpcNotFound, RpcRedirect } from "./outcomes.js";
20
20
  * ```ts
21
21
  * provideRouter(
22
22
  * routes,
23
- * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFoundRoute, {}) })),
23
+ * withNavigationErrorHandler(rpcNavigationErrors({ notFound: createUrl(notFound, {}) })),
24
24
  * );
25
25
  * ```
26
26
  *
package/node/index.d.ts CHANGED
@@ -34,6 +34,9 @@ export type UpgradeListener = (request: IncomingMessage, socket: Duplex, head: B
34
34
  * unless the client already left. Accepted sockets are pinged every 15 s and terminated when
35
35
  * they miss the answer.
36
36
  *
37
+ * Under `ng serve`, Launch's serve builder forwards `/_rpc/` upgrades to the latest listener
38
+ * created, so attaching it where your built server listens is all the wiring there is.
39
+ *
37
40
  * @example
38
41
  * ```ts
39
42
  * import { createServer } from "node:http";
package/node/index.js CHANGED
@@ -1,9 +1,8 @@
1
1
  /// <reference types="node" preserve="true" />
2
2
  import { STATUS_CODES } from "node:http";
3
3
  import { WebSocketServer } from "ws";
4
+ import { upgradeListenerSlot } from "./upgrade-listener-slot.js";
4
5
  const pingMs = 15_000;
5
- // Where S2's dev-server forwarding finds the app's listener; the latest one created wins.
6
- const listenerSlot = Symbol.for("@loozo/angular-launch/upgrade-listener/v1");
7
6
  // The upgrade request as a web Request. Like Angular's createWebRequestFromNodeRequest by
8
7
  // default, it trusts no proxy headers: the protocol comes from the socket, the host from Host.
9
8
  function webRequest(incoming, signal) {
@@ -80,6 +79,9 @@ function keepAlive(socket) {
80
79
  * unless the client already left. Accepted sockets are pinged every 15 s and terminated when
81
80
  * they miss the answer.
82
81
  *
82
+ * Under `ng serve`, Launch's serve builder forwards `/_rpc/` upgrades to the latest listener
83
+ * created, so attaching it where your built server listens is all the wiring there is.
84
+ *
83
85
  * @example
84
86
  * ```ts
85
87
  * import { createServer } from "node:http";
@@ -170,6 +172,7 @@ export function createUpgradeHandler(handle, { maxPayload = 1024 * 1024 } = {})
170
172
  const listener = (incoming, socket, head) => {
171
173
  void upgrade(incoming, socket, head);
172
174
  };
173
- globalThis[listenerSlot] = listener;
175
+ // Where `ng serve` finds the app's listener; the latest one created wins.
176
+ globalThis[upgradeListenerSlot] = listener;
174
177
  return listener;
175
178
  }
@@ -0,0 +1 @@
1
+ export declare const upgradeListenerSlot: unique symbol;
@@ -0,0 +1,4 @@
1
+ // The process-global slot where createUpgradeHandler stores the listener it creates, latest
2
+ // first, and where the serve builder's dev-server middleware finds it. Its own module so the
3
+ // builder reads it without loading ws.
4
+ export const upgradeListenerSlot = Symbol.for("@loozo/angular-launch/upgrade-listener/v1");
package/outcomes.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type TranslateRedirect } from "./redirect-translation.js";
1
2
  /**
2
3
  * Whether `to` is a root-relative URL that stays on the app's origin.
3
4
  *
@@ -8,15 +9,23 @@
8
9
  */
9
10
  export declare function isRootRelative(to: unknown): to is `/${string}`;
10
11
  /**
11
- * The rejection of a call whose middleware or handler threw `redirect(to)`.
12
+ * The rejection of a call whose stage, middleware or handler threw `redirect()`.
12
13
  *
13
14
  * @remarks
14
15
  * Generated callables reject with it for a response that is exactly a redirect frame, and
15
16
  * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} turns it
16
17
  * into a navigation to {@link RpcRedirect.to}; anywhere else, nothing navigates for you.
18
+ *
19
+ * With `translateSegments` and `provideRedirectTranslation()` installed, `to` is in the
20
+ * page's language, in the browser and while rendering a live request: it equals the page's
21
+ * own `createUrl` for the same destination and values. The wire frame and every
22
+ * `HttpInterceptor` see the canonical URL with its `words`.
17
23
  */
18
24
  export declare class RpcRedirect extends Error {
19
- /** The root-relative URL the server redirected to, such as `/sign-in`. */
25
+ /**
26
+ * The root-relative URL the server redirected to, such as `/sign-in`, in this build's
27
+ * language for a translated app.
28
+ */
20
29
  readonly to: `/${string}`;
21
30
  /**
22
31
  * Creates a redirect rejection.
@@ -24,7 +33,10 @@ export declare class RpcRedirect extends Error {
24
33
  * @param to - The root-relative URL the server redirected to.
25
34
  */
26
35
  constructor(
27
- /** The root-relative URL the server redirected to, such as `/sign-in`. */
36
+ /**
37
+ * The root-relative URL the server redirected to, such as `/sign-in`, in this build's
38
+ * language for a translated app.
39
+ */
28
40
  to: `/${string}`);
29
41
  }
30
42
  /**
@@ -44,12 +56,16 @@ export declare class RpcNotFound extends Error {
44
56
  * Recognizes a response body that is exactly a redirect or not-found frame.
45
57
  *
46
58
  * @remarks
47
- * Internal. A redirect is status 303 with exactly `{ redirect: { to } }`, where `to` is
48
- * root-relative; not-found is status 404 with exactly `{ notFound: null }`. The body must
49
- * be strict JSON.
59
+ * Internal. A redirect is status 303 with exactly `{ redirect: { to } }` or
60
+ * `{ redirect: { to, words } }`, where `to` is root-relative and `words` lists, strictly
61
+ * increasing, the ordinals of its path segments that hold static words, on a path `createUrl`
62
+ * writes (`targetSegments`); not-found is status 404 with exactly
63
+ * `{ notFound: null }`. The body must be strict JSON. A redirect with `words` goes through
64
+ * `translate` when one is given; anything else keeps its `to`.
50
65
  *
51
66
  * @param value - The parsed response body.
52
67
  * @param status - The response's HTTP status.
68
+ * @param translate - Puts a frame's listed words in this build's language.
53
69
  * @returns The rejection to use, or `undefined` when the body doesn't match exactly.
54
70
  */
55
- export declare function recognizedOutcome(value: unknown, status: number): RpcRedirect | RpcNotFound | undefined;
71
+ export declare function recognizedOutcome(value: unknown, status: number, translate?: TranslateRedirect): RpcRedirect | RpcNotFound | undefined;
package/outcomes.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { serializeJson } from "./json.js";
2
+ import { targetSegments } from "./redirect-translation.js";
2
3
  const base = "http://launch.invalid";
3
4
  /**
4
5
  * Whether `to` is a root-relative URL that stays on the app's origin.
@@ -22,12 +23,17 @@ export function isRootRelative(to) {
22
23
  return resolved.origin === base;
23
24
  }
24
25
  /**
25
- * The rejection of a call whose middleware or handler threw `redirect(to)`.
26
+ * The rejection of a call whose stage, middleware or handler threw `redirect()`.
26
27
  *
27
28
  * @remarks
28
29
  * Generated callables reject with it for a response that is exactly a redirect frame, and
29
30
  * stream iteration throws it. In a guard or resolver, {@link rpcNavigationErrors} turns it
30
31
  * into a navigation to {@link RpcRedirect.to}; anywhere else, nothing navigates for you.
32
+ *
33
+ * With `translateSegments` and `provideRedirectTranslation()` installed, `to` is in the
34
+ * page's language, in the browser and while rendering a live request: it equals the page's
35
+ * own `createUrl` for the same destination and values. The wire frame and every
36
+ * `HttpInterceptor` see the canonical URL with its `words`.
31
37
  */
32
38
  export class RpcRedirect extends Error {
33
39
  to;
@@ -37,7 +43,10 @@ export class RpcRedirect extends Error {
37
43
  * @param to - The root-relative URL the server redirected to.
38
44
  */
39
45
  constructor(
40
- /** The root-relative URL the server redirected to, such as `/sign-in`. */
46
+ /**
47
+ * The root-relative URL the server redirected to, such as `/sign-in`, in this build's
48
+ * language for a translated app.
49
+ */
41
50
  to) {
42
51
  super(`RPC redirected to ${to}`);
43
52
  this.to = to;
@@ -60,19 +69,42 @@ export class RpcNotFound extends Error {
60
69
  this.name = "RpcNotFound";
61
70
  }
62
71
  }
72
+ // Valid `words`: a non-empty array of strictly increasing integer ordinals of `to`'s path
73
+ // segments, on a path createUrl writes.
74
+ function validWords(words, to) {
75
+ if (!Array.isArray(words) || words.length === 0) {
76
+ return false;
77
+ }
78
+ const segments = targetSegments(to);
79
+ if (segments === undefined) {
80
+ return false;
81
+ }
82
+ let previous = -1;
83
+ for (const at of words) {
84
+ if (!Number.isInteger(at) || at <= previous || at >= segments.length) {
85
+ return false;
86
+ }
87
+ previous = at;
88
+ }
89
+ return true;
90
+ }
63
91
  /**
64
92
  * Recognizes a response body that is exactly a redirect or not-found frame.
65
93
  *
66
94
  * @remarks
67
- * Internal. A redirect is status 303 with exactly `{ redirect: { to } }`, where `to` is
68
- * root-relative; not-found is status 404 with exactly `{ notFound: null }`. The body must
69
- * be strict JSON.
95
+ * Internal. A redirect is status 303 with exactly `{ redirect: { to } }` or
96
+ * `{ redirect: { to, words } }`, where `to` is root-relative and `words` lists, strictly
97
+ * increasing, the ordinals of its path segments that hold static words, on a path `createUrl`
98
+ * writes (`targetSegments`); not-found is status 404 with exactly
99
+ * `{ notFound: null }`. The body must be strict JSON. A redirect with `words` goes through
100
+ * `translate` when one is given; anything else keeps its `to`.
70
101
  *
71
102
  * @param value - The parsed response body.
72
103
  * @param status - The response's HTTP status.
104
+ * @param translate - Puts a frame's listed words in this build's language.
73
105
  * @returns The rejection to use, or `undefined` when the body doesn't match exactly.
74
106
  */
75
- export function recognizedOutcome(value, status) {
107
+ export function recognizedOutcome(value, status, translate) {
76
108
  try {
77
109
  serializeJson(value);
78
110
  }
@@ -89,12 +121,26 @@ export function recognizedOutcome(value, status) {
89
121
  return undefined;
90
122
  }
91
123
  const redirect = value.redirect;
92
- if (typeof redirect !== "object" ||
93
- redirect === null ||
94
- !("to" in redirect) ||
95
- Object.keys(redirect).length !== 1 ||
96
- !isRootRelative(redirect.to)) {
124
+ if (typeof redirect !== "object" || redirect === null || !("to" in redirect)) {
125
+ return undefined;
126
+ }
127
+ const keys = Object.keys(redirect).length;
128
+ const hasWords = "words" in redirect;
129
+ if (keys !== (hasWords ? 2 : 1) || !isRootRelative(redirect.to)) {
130
+ return undefined;
131
+ }
132
+ if (!hasWords) {
133
+ return new RpcRedirect(redirect.to);
134
+ }
135
+ if (!validWords(redirect.words, redirect.to)) {
136
+ return undefined;
137
+ }
138
+ if (!translate) {
139
+ return new RpcRedirect(redirect.to);
140
+ }
141
+ const translated = translate(redirect.to, redirect.words);
142
+ if (!isRootRelative(translated)) {
97
143
  return undefined;
98
144
  }
99
- return new RpcRedirect(redirect.to);
145
+ return new RpcRedirect(translated);
100
146
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loozo/angular-launch",
3
- "version": "0.0.6",
3
+ "version": "0.1.0",
4
4
  "description": "Typed queries, mutations and declared errors on Angular's native router, HTTP and SSR pipeline.",
5
5
  "bugs": "https://github.com/theo-matzavinos/loozo/issues",
6
6
  "license": "MIT",
@@ -24,14 +24,18 @@
24
24
  "types": "./server/generated.d.ts",
25
25
  "default": "./server/generated.js"
26
26
  },
27
+ "./_source-text": {
28
+ "types": "./source-text.d.ts",
29
+ "default": "./source-text.js"
30
+ },
31
+ "./_redirects": {
32
+ "types": "./redirect-translation.d.ts",
33
+ "default": "./redirect-translation.js"
34
+ },
27
35
  "./node": {
28
36
  "types": "./node/index.d.ts",
29
37
  "default": "./node/index.js"
30
38
  },
31
- "./_generated": {
32
- "types": "./generated.d.ts",
33
- "default": "./generated.js"
34
- },
35
39
  "./generation": {
36
40
  "types": "./generation/index.d.ts",
37
41
  "node": "./generation/index.js"
@@ -40,9 +44,9 @@
40
44
  "types": "./tanstack-query/index.d.ts",
41
45
  "default": "./tanstack-query/index.js"
42
46
  },
43
- "./_tanstack-query": {
44
- "types": "./tanstack-query/generated.d.ts",
45
- "default": "./tanstack-query/generated.js"
47
+ "./testing": {
48
+ "types": "./testing/index.d.ts",
49
+ "default": "./testing/index.js"
46
50
  },
47
51
  "./package.json": "./package.json"
48
52
  },
@@ -51,17 +55,17 @@
51
55
  "registry": "https://registry.npmjs.org/"
52
56
  },
53
57
  "dependencies": {
54
- "@angular-devkit/architect": "0.2202.2",
58
+ "@angular-devkit/architect": "0.2202.6",
55
59
  "chokidar": "5.0.0",
56
60
  "typescript": "6.0.3",
57
61
  "ws": "8.21.3"
58
62
  },
59
63
  "peerDependencies": {
60
- "@angular/build": "~22.2.0",
64
+ "@angular/build": "~22.3.0",
61
65
  "@angular/common": "^22.0.0",
62
66
  "@angular/core": "^22.0.0",
63
67
  "@angular/router": "^22.0.0",
64
- "@loozo/angular-router": "0.0.8",
68
+ "@loozo/angular-router": "0.1.0",
65
69
  "@tanstack/angular-query": "^5.0.0-rc.5",
66
70
  "rxjs": "^7.8.2"
67
71
  },
@@ -0,0 +1,53 @@
1
+ import { InjectionToken, type EnvironmentProviders } from "@angular/core";
2
+ /**
3
+ * Puts the listed static path segments of a canonical redirect target, ordinals of
4
+ * {@link targetSegments}, in this build's language. Internal.
5
+ */
6
+ export type TranslateRedirect = (to: `/${string}`, words: readonly number[]) => `/${string}`;
7
+ /**
8
+ * The installed {@link TranslateRedirect}, which the generated client applies when it
9
+ * recognizes a redirect frame with `words`. Internal.
10
+ */
11
+ export declare const REDIRECT_TRANSLATOR: InjectionToken<TranslateRedirect>;
12
+ /** Every canonical static word of an app and its text in this build, in the same order. */
13
+ export interface RedirectWords {
14
+ readonly words: readonly string[];
15
+ readonly translations: readonly string[];
16
+ }
17
+ /**
18
+ * The path segments of a redirect target, in order, as `[start, end)` offsets into `to`.
19
+ *
20
+ * @remarks
21
+ * Internal. It recognizes only the paths `createUrl` writes: `/` or `/a/b` for a primary
22
+ * destination, and `/(outlet:a/b)` or `/a/(outlet:b)` for one in a named outlet, the anchor's
23
+ * segments before the group's; any `?` or `#` suffix follows. The outlet label is no segment.
24
+ * Matrix parameters, several groups, nested outlets and anything else aren't recognized.
25
+ *
26
+ * @param to - A root-relative redirect target.
27
+ * @returns The segment spans, or `undefined` for any other path.
28
+ */
29
+ export declare function targetSegments(to: string): readonly (readonly [number, number])[] | undefined;
30
+ /**
31
+ * Swaps the path segments at `words` in `to` for their words' translation in `table`.
32
+ *
33
+ * @remarks
34
+ * Internal. `words` are ascending ordinals of {@link targetSegments}. Only those segments
35
+ * change: parameter and catchall values, outlet labels, the search and the fragment stay byte
36
+ * for byte, and a word missing from `table`, or one that doesn't decode, stays canonical.
37
+ *
38
+ * @throws TypeError when `to` isn't a path `createUrl` writes, which recognition already
39
+ * refused.
40
+ */
41
+ export declare function swap(table: ReadonlyMap<string, string>, to: `/${string}`, words: readonly number[]): `/${string}`;
42
+ /**
43
+ * Provides the {@link REDIRECT_TRANSLATOR} of one build's generated word table.
44
+ *
45
+ * @remarks
46
+ * Internal: exported only from `@loozo/angular-launch/_redirects` for a translated app's
47
+ * generated `redirects.generated.ts`. `table` runs once, the first time a client needs it, so
48
+ * its `$localize` tags evaluate inside the localized application.
49
+ *
50
+ * @param table - Returns every canonical word and its translation in this build.
51
+ * @returns The providers.
52
+ */
53
+ export declare function redirectTranslation(table: () => RedirectWords): EnvironmentProviders;
@@ -0,0 +1,141 @@
1
+ import { InjectionToken, makeEnvironmentProviders } from "@angular/core";
2
+ /**
3
+ * The installed {@link TranslateRedirect}, which the generated client applies when it
4
+ * recognizes a redirect frame with `words`. Internal.
5
+ */
6
+ export const REDIRECT_TRANSLATOR = new InjectionToken("Launch redirect translator");
7
+ // createUrl's encoding: component-encoded, with parentheses escaped too.
8
+ function encode(text) {
9
+ return encodeURIComponent(text).replaceAll("(", "%28").replaceAll(")", "%29");
10
+ }
11
+ // One path segment as createUrl encodes it, and an outlet group's label: the router's outlet
12
+ // name grammar, then ":". Sticky, so each match starts exactly at `lastIndex`.
13
+ const segmentText = /(?:[A-Za-z0-9\-_.!~*']|%[0-9A-Fa-f]{2})+/y;
14
+ const outletLabel = /[A-Za-z][A-Za-z0-9_-]*:/y;
15
+ // Reads `segment ("/" segment)*` from `at` into `spans`, stopping before an outlet group's
16
+ // "/(". Returns the offset after the last segment, or undefined when no segment starts there.
17
+ function readSegments(to, at, spans) {
18
+ for (;;) {
19
+ segmentText.lastIndex = at;
20
+ if (!segmentText.test(to)) {
21
+ return undefined;
22
+ }
23
+ const end = segmentText.lastIndex;
24
+ spans.push([at, end]);
25
+ if (to[end] !== "/" || to[end + 1] === "(") {
26
+ return end;
27
+ }
28
+ at = end + 1;
29
+ }
30
+ }
31
+ /**
32
+ * The path segments of a redirect target, in order, as `[start, end)` offsets into `to`.
33
+ *
34
+ * @remarks
35
+ * Internal. It recognizes only the paths `createUrl` writes: `/` or `/a/b` for a primary
36
+ * destination, and `/(outlet:a/b)` or `/a/(outlet:b)` for one in a named outlet, the anchor's
37
+ * segments before the group's; any `?` or `#` suffix follows. The outlet label is no segment.
38
+ * Matrix parameters, several groups, nested outlets and anything else aren't recognized.
39
+ *
40
+ * @param to - A root-relative redirect target.
41
+ * @returns The segment spans, or `undefined` for any other path.
42
+ */
43
+ export function targetSegments(to) {
44
+ // createUrl encodes "?" and "#" inside segments, so the first one ends the path.
45
+ const cut = to.search(/[?#]/);
46
+ const end = cut === -1 ? to.length : cut;
47
+ const spans = [];
48
+ let at = 1;
49
+ if (to[0] !== "/") {
50
+ return undefined;
51
+ }
52
+ if (at < end && to[at] !== "(") {
53
+ const after = readSegments(to, at, spans);
54
+ if (after === undefined) {
55
+ return undefined;
56
+ }
57
+ if (after === end) {
58
+ return spans;
59
+ }
60
+ // Only "/(" ends the anchor early: the group follows.
61
+ if (to[after] !== "/") {
62
+ return undefined;
63
+ }
64
+ at = after + 1;
65
+ }
66
+ if (at === end) {
67
+ return spans;
68
+ }
69
+ outletLabel.lastIndex = at + 1;
70
+ if (to[at] !== "(" || !outletLabel.test(to)) {
71
+ return undefined;
72
+ }
73
+ const close = readSegments(to, outletLabel.lastIndex, spans);
74
+ if (close === undefined || to[close] !== ")" || close + 1 !== end) {
75
+ return undefined;
76
+ }
77
+ return spans;
78
+ }
79
+ /**
80
+ * Swaps the path segments at `words` in `to` for their words' translation in `table`.
81
+ *
82
+ * @remarks
83
+ * Internal. `words` are ascending ordinals of {@link targetSegments}. Only those segments
84
+ * change: parameter and catchall values, outlet labels, the search and the fragment stay byte
85
+ * for byte, and a word missing from `table`, or one that doesn't decode, stays canonical.
86
+ *
87
+ * @throws TypeError when `to` isn't a path `createUrl` writes, which recognition already
88
+ * refused.
89
+ */
90
+ export function swap(table, to, words) {
91
+ const segments = targetSegments(to);
92
+ if (segments === undefined) {
93
+ throw new TypeError(`Not a createUrl path: ${to}`);
94
+ }
95
+ let result = "";
96
+ let copied = 1;
97
+ for (const at of words) {
98
+ const [start, end] = segments[at];
99
+ let canonical;
100
+ try {
101
+ canonical = decodeURIComponent(to.slice(start, end));
102
+ }
103
+ catch {
104
+ continue;
105
+ }
106
+ const word = table.get(canonical);
107
+ if (word !== undefined) {
108
+ result += to.slice(copied, start) + encode(word);
109
+ copied = end;
110
+ }
111
+ }
112
+ return `/${result}${to.slice(copied)}`;
113
+ }
114
+ /**
115
+ * Provides the {@link REDIRECT_TRANSLATOR} of one build's generated word table.
116
+ *
117
+ * @remarks
118
+ * Internal: exported only from `@loozo/angular-launch/_redirects` for a translated app's
119
+ * generated `redirects.generated.ts`. `table` runs once, the first time a client needs it, so
120
+ * its `$localize` tags evaluate inside the localized application.
121
+ *
122
+ * @param table - Returns every canonical word and its translation in this build.
123
+ * @returns The providers.
124
+ */
125
+ export function redirectTranslation(table) {
126
+ return makeEnvironmentProviders([
127
+ {
128
+ provide: REDIRECT_TRANSLATOR,
129
+ useFactory: () => {
130
+ let map;
131
+ return (to, words) => {
132
+ if (!map) {
133
+ const { words: canonical, translations } = table();
134
+ map = new Map(canonical.map((word, index) => [word, translations[index]]));
135
+ }
136
+ return swap(map, to, words);
137
+ };
138
+ },
139
+ },
140
+ ]);
141
+ }
@@ -1,15 +1,16 @@
1
1
  import { isPlatformServer } from "@angular/common";
2
- import { inject, PLATFORM_ID } from "@angular/core";
2
+ import { inject, PLATFORM_ID, REQUEST } from "@angular/core";
3
3
  import { HttpClient, HttpContext, HttpContextToken, HttpErrorResponse } from "@angular/common/http";
4
4
  import { openChannel } from "./channel.js";
5
5
  import { RpcError, recognizedError, } from "./client.js";
6
6
  import { connect } from "./connect.js";
7
7
  import { serializeJson } from "./json.js";
8
8
  import { recognizedOutcome } from "./outcomes.js";
9
+ import { REDIRECT_TRANSLATOR } from "./redirect-translation.js";
9
10
  import { openStream } from "./stream.js";
10
11
  export const RPC_CALL = new HttpContextToken(() => false);
11
12
  const errorOwners = new WeakMap();
12
- function call(http, group, method, input, { signal, transferCache = true } = {}) {
13
+ function call(http, group, method, input, translate, { signal, transferCache = true } = {}) {
13
14
  return new Promise((resolve, reject) => {
14
15
  let subscription;
15
16
  let settled = false;
@@ -56,7 +57,7 @@ function call(http, group, method, input, { signal, transferCache = true } = {})
56
57
  reject(converted);
57
58
  return;
58
59
  }
59
- const outcome = recognizedOutcome(error.error, error.status);
60
+ const outcome = recognizedOutcome(error.error, error.status, translate);
60
61
  if (outcome) {
61
62
  reject(outcome);
62
63
  return;
@@ -80,7 +81,7 @@ function owner(group, method) {
80
81
  return error;
81
82
  };
82
83
  }
83
- function stream(server, group, method, input, options = {}, opened) {
84
+ function stream(server, translate, group, method, input, options = {}, opened) {
84
85
  const own = owner(group, method);
85
86
  // Each iteration is its own request, so iterating again reconnects.
86
87
  return {
@@ -88,12 +89,12 @@ function stream(server, group, method, input, options = {}, opened) {
88
89
  if (server) {
89
90
  return refusedStream(own(new RpcError("FORBIDDEN", 403)));
90
91
  }
91
- return openStream(`/_rpc/${group}/${method.name}`, input, method.errors, own, options, opened);
92
+ return openStream(`/_rpc/${group}/${method.name}`, input, method.errors, own, options, opened, translate);
92
93
  },
93
94
  };
94
95
  }
95
96
  // Channels don't run during server rendering either: they fail at once with FORBIDDEN.
96
- function channel(server, group, method, input, options = {}, opened) {
97
+ function channel(server, translate, group, method, input, options = {}, opened) {
97
98
  const own = owner(group, method);
98
99
  let path = `/_rpc/${group}/${method.name}`;
99
100
  let refused;
@@ -108,17 +109,22 @@ function channel(server, group, method, input, options = {}, opened) {
108
109
  refused = error;
109
110
  }
110
111
  }
111
- return openChannel(path, method.errors, own, options, opened, refused);
112
+ return openChannel(path, method.errors, own, options, opened, refused, translate);
112
113
  }
113
114
  export function injectClient(groups) {
114
115
  const http = inject(HttpClient);
116
+ let translate = inject(REDIRECT_TRANSLATOR, { optional: true }) ?? undefined;
115
117
  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
- }
118
+ // Only a redirect translation, streams and channels depend on the platform.
119
+ if (translate ||
120
+ Object.values(groups).some((group) => group.methods.some((method) => method.kind === "stream" || method.kind === "channel"))) {
121
+ server = isPlatformServer(inject(PLATFORM_ID));
122
+ }
123
+ // On the server, only a live request's rendering translates, as the rendering backend tells
124
+ // live from prerender. A prerendered page's calls run in this localized application, so
125
+ // their redirects are already in its language.
126
+ if (server && !(inject(REQUEST, { optional: true }) instanceof Request)) {
127
+ translate = undefined;
122
128
  }
123
129
  const result = Object.create(null);
124
130
  for (const [namespace, group] of Object.entries(groups)) {
@@ -127,28 +133,28 @@ export function injectClient(groups) {
127
133
  let invoke;
128
134
  let open;
129
135
  if (method.kind === "stream") {
130
- open = (input, signal, opened) => stream(server, namespace, method, input, { signal }, opened);
136
+ open = (input, signal, opened) => stream(server, translate, namespace, method, input, { signal }, opened);
131
137
  if (method.input) {
132
- invoke = (input, options) => stream(server, namespace, method, input, options);
138
+ invoke = (input, options) => stream(server, translate, namespace, method, input, options);
133
139
  }
134
140
  else {
135
- invoke = (options) => stream(server, namespace, method, null, options);
141
+ invoke = (options) => stream(server, translate, namespace, method, null, options);
136
142
  }
137
143
  }
138
144
  else if (method.kind === "channel") {
139
- open = (input, signal, opened) => channel(server, namespace, method, input, { signal }, opened);
145
+ open = (input, signal, opened) => channel(server, translate, namespace, method, input, { signal }, opened);
140
146
  if (method.input) {
141
- invoke = (input, options) => channel(server, namespace, method, input, options);
147
+ invoke = (input, options) => channel(server, translate, namespace, method, input, options);
142
148
  }
143
149
  else {
144
- invoke = (options) => channel(server, namespace, method, null, options);
150
+ invoke = (options) => channel(server, translate, namespace, method, null, options);
145
151
  }
146
152
  }
147
153
  else if (method.input) {
148
- invoke = (input, options) => call(http, namespace, method, input, options);
154
+ invoke = (input, options) => call(http, namespace, method, input, translate, options);
149
155
  }
150
156
  else {
151
- invoke = (options) => call(http, namespace, method, null, options);
157
+ invoke = (options) => call(http, namespace, method, null, translate, options);
152
158
  }
153
159
  if (open) {
154
160
  const opener = open;