@analogjs/router 2.8.0-beta.9 → 2.8.1-beta.1

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 (28) hide show
  1. package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs +119 -0
  2. package/fesm2022/analogjs-router-debug.page-MFY2u07E.mjs.map +1 -0
  3. package/fesm2022/analogjs-router-i18n.mjs +82 -219
  4. package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
  5. package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs +263 -0
  6. package/fesm2022/analogjs-router-routes-L2tt-0ms.mjs.map +1 -0
  7. package/fesm2022/analogjs-router-server-actions.mjs +228 -463
  8. package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
  9. package/fesm2022/analogjs-router-server.mjs +608 -838
  10. package/fesm2022/analogjs-router-server.mjs.map +1 -1
  11. package/fesm2022/analogjs-router-tanstack-query-server.mjs +35 -85
  12. package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
  13. package/fesm2022/analogjs-router-tanstack-query.mjs +79 -127
  14. package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
  15. package/fesm2022/analogjs-router-tokens.mjs +14 -19
  16. package/fesm2022/analogjs-router-tokens.mjs.map +1 -1
  17. package/fesm2022/analogjs-router.mjs +882 -1324
  18. package/fesm2022/analogjs-router.mjs.map +1 -1
  19. package/package.json +2 -2
  20. package/types/analogjs-router-i18n.d.ts +55 -24
  21. package/types/analogjs-router-server-actions.d.ts +98 -107
  22. package/types/analogjs-router-server.d.ts +76 -116
  23. package/types/analogjs-router-tanstack-query-server.d.ts +33 -37
  24. package/types/analogjs-router-tanstack-query.d.ts +19 -24
  25. package/types/analogjs-router-tokens.d.ts +26 -22
  26. package/types/analogjs-router.d.ts +528 -348
  27. package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs +0 -91
  28. package/fesm2022/analogjs-router-debug.page-COcFkgRu.mjs.map +0 -1
@@ -0,0 +1,119 @@
1
+ import { t as injectDebugRoutes } from "./analogjs-router-routes-L2tt-0ms.mjs";
2
+ import * as i0 from "@angular/core";
3
+ import { Component } from "@angular/core";
4
+ var DebugRoutesComponent = class DebugRoutesComponent {
5
+ constructor() {
6
+ this.collectedRoutes = [];
7
+ this.debugRoutes = injectDebugRoutes();
8
+ }
9
+ ngOnInit() {
10
+ this.traverseRoutes(this.debugRoutes);
11
+ }
12
+ traverseRoutes(routes, parent) {
13
+ routes.forEach((route) => {
14
+ this.collectedRoutes.push({
15
+ path: route.isLayout ? `${parent ? `/${parent}` : ""}${route.path ? `/${route.path}` : ""}` : `${parent ? `/${parent}` : ""}${route.path ? `/${route.path}` : "/"}`,
16
+ filename: route.filename,
17
+ file: route.filename?.replace(/(^.*)pages\//, "") || "",
18
+ isLayout: route.isLayout
19
+ });
20
+ if (route.children) {
21
+ const fullParentPath = [parent, route.path].filter((s) => !!s).join("/");
22
+ this.traverseRoutes(route.children, fullParentPath);
23
+ }
24
+ });
25
+ }
26
+ static {
27
+ this.ɵfac = i0.ɵɵngDeclareFactory({
28
+ minVersion: "12.0.0",
29
+ version: "22.2.0",
30
+ ngImport: i0,
31
+ type: DebugRoutesComponent,
32
+ deps: [],
33
+ target: i0.ɵɵFactoryTarget.Component
34
+ });
35
+ }
36
+ static {
37
+ this.ɵcmp = i0.ɵɵngDeclareComponent({
38
+ minVersion: "17.0.0",
39
+ version: "22.2.0",
40
+ type: DebugRoutesComponent,
41
+ isStandalone: true,
42
+ selector: "analogjs-debug-routes-page",
43
+ ngImport: i0,
44
+ template: `
45
+ <h2>Routes</h2>
46
+
47
+ <div class="table-container">
48
+ <div class="table-header">
49
+ <div class="header-cell">Route Path</div>
50
+ <div class="header-cell">File</div>
51
+ <div class="header-cell">Type</div>
52
+ </div>
53
+ <div class="table-body">
54
+ @for (
55
+ collectedRoute of collectedRoutes;
56
+ track collectedRoute.filename
57
+ ) {
58
+ <div class="table-row">
59
+ <div class="table-cell">{{ collectedRoute.path }}</div>
60
+ <div class="table-cell" [title]="collectedRoute.filename">
61
+ {{ collectedRoute.file }}
62
+ </div>
63
+ <div class="table-cell">
64
+ {{ collectedRoute.isLayout ? 'Layout' : 'Page' }}
65
+ </div>
66
+ </div>
67
+ }
68
+ </div>
69
+ </div>
70
+ `,
71
+ isInline: true,
72
+ styles: [":host{width:100%}.table-container{width:100%;max-width:900px;margin:0 auto;background:#fff;border-radius:8px;box-shadow:0 2px 4px #0000001a;overflow:hidden}.table-header{display:grid;grid-template-columns:repeat(3,1fr);background:gray;border-bottom:2px solid #e5e7eb}.header-cell{padding:16px 24px;font-weight:600;text-transform:uppercase;font-size:14px;letter-spacing:.05em;color:#fff}.table-body{display:flex;flex-direction:column}.table-row{display:grid;grid-template-columns:repeat(3,1fr);border-bottom:1px solid #e5e7eb;transition:background-color .2s ease}.table-row:last-child{border-bottom:none}.table-row:hover{background-color:#f9fafb}.table-cell{padding:16px 24px;font-size:16px;color:#4b5563}@media(max-width:640px){.table-container{border-radius:0;margin:0}.header-cell,.table-cell{padding:12px 16px}}\n"]
73
+ });
74
+ }
75
+ };
76
+ i0.ɵɵngDeclareClassMetadata({
77
+ minVersion: "12.0.0",
78
+ version: "22.2.0",
79
+ ngImport: i0,
80
+ type: DebugRoutesComponent,
81
+ decorators: [{
82
+ type: Component,
83
+ args: [{
84
+ selector: "analogjs-debug-routes-page",
85
+ standalone: true,
86
+ template: `
87
+ <h2>Routes</h2>
88
+
89
+ <div class="table-container">
90
+ <div class="table-header">
91
+ <div class="header-cell">Route Path</div>
92
+ <div class="header-cell">File</div>
93
+ <div class="header-cell">Type</div>
94
+ </div>
95
+ <div class="table-body">
96
+ @for (
97
+ collectedRoute of collectedRoutes;
98
+ track collectedRoute.filename
99
+ ) {
100
+ <div class="table-row">
101
+ <div class="table-cell">{{ collectedRoute.path }}</div>
102
+ <div class="table-cell" [title]="collectedRoute.filename">
103
+ {{ collectedRoute.file }}
104
+ </div>
105
+ <div class="table-cell">
106
+ {{ collectedRoute.isLayout ? 'Layout' : 'Page' }}
107
+ </div>
108
+ </div>
109
+ }
110
+ </div>
111
+ </div>
112
+ `,
113
+ styles: [":host{width:100%}.table-container{width:100%;max-width:900px;margin:0 auto;background:#fff;border-radius:8px;box-shadow:0 2px 4px #0000001a;overflow:hidden}.table-header{display:grid;grid-template-columns:repeat(3,1fr);background:gray;border-bottom:2px solid #e5e7eb}.header-cell{padding:16px 24px;font-weight:600;text-transform:uppercase;font-size:14px;letter-spacing:.05em;color:#fff}.table-body{display:flex;flex-direction:column}.table-row{display:grid;grid-template-columns:repeat(3,1fr);border-bottom:1px solid #e5e7eb;transition:background-color .2s ease}.table-row:last-child{border-bottom:none}.table-row:hover{background-color:#f9fafb}.table-cell{padding:16px 24px;font-size:16px;color:#4b5563}@media(max-width:640px){.table-container{border-radius:0;margin:0}.header-cell,.table-cell{padding:12px 16px}}\n"]
114
+ }]
115
+ }]
116
+ });
117
+ export { DebugRoutesComponent as default };
118
+
119
+ //# sourceMappingURL=analogjs-router-debug.page-MFY2u07E.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analogjs-router-debug.page-MFY2u07E.mjs","names":[],"sources":["../../../../packages/router/src/lib/debug/debug.page.ts"],"sourcesContent":["import { Component } from '@angular/core';\n\nimport { injectDebugRoutes, DebugRoute } from './routes';\n\ntype CollectedRoute = {\n path: string;\n filename: string;\n file: string;\n isLayout: boolean;\n};\n\n@Component({\n selector: 'analogjs-debug-routes-page',\n standalone: true,\n template: `\n <h2>Routes</h2>\n\n <div class=\"table-container\">\n <div class=\"table-header\">\n <div class=\"header-cell\">Route Path</div>\n <div class=\"header-cell\">File</div>\n <div class=\"header-cell\">Type</div>\n </div>\n <div class=\"table-body\">\n @for (\n collectedRoute of collectedRoutes;\n track collectedRoute.filename\n ) {\n <div class=\"table-row\">\n <div class=\"table-cell\">{{ collectedRoute.path }}</div>\n <div class=\"table-cell\" [title]=\"collectedRoute.filename\">\n {{ collectedRoute.file }}\n </div>\n <div class=\"table-cell\">\n {{ collectedRoute.isLayout ? 'Layout' : 'Page' }}\n </div>\n </div>\n }\n </div>\n </div>\n `,\n styles: `\n :host {\n width: 100%;\n }\n\n .table-container {\n width: 100%;\n max-width: 900px;\n margin: 0 auto;\n background: white;\n border-radius: 8px;\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\n overflow: hidden;\n }\n\n .table-header {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n background: gray;\n border-bottom: 2px solid #e5e7eb;\n }\n\n .header-cell {\n padding: 16px 24px;\n font-weight: 600;\n text-transform: uppercase;\n font-size: 14px;\n letter-spacing: 0.05em;\n color: white;\n }\n\n .table-body {\n display: flex;\n flex-direction: column;\n }\n\n .table-row {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n border-bottom: 1px solid #e5e7eb;\n transition: background-color 0.2s ease;\n }\n\n .table-row:last-child {\n border-bottom: none;\n }\n\n .table-row:hover {\n background-color: #f9fafb;\n }\n\n .table-cell {\n padding: 16px 24px;\n font-size: 16px;\n color: #4b5563;\n }\n\n @media (max-width: 640px) {\n .table-container {\n border-radius: 0;\n margin: 0;\n }\n\n .header-cell,\n .table-cell {\n padding: 12px 16px;\n }\n }\n `,\n})\nexport default class DebugRoutesComponent {\n collectedRoutes: CollectedRoute[] = [];\n debugRoutes = injectDebugRoutes();\n\n ngOnInit() {\n this.traverseRoutes(this.debugRoutes);\n }\n\n traverseRoutes(routes: DebugRoute[], parent?: string) {\n routes.forEach((route) => {\n this.collectedRoutes.push({\n path: route.isLayout\n ? `${parent ? `/${parent}` : ''}${route.path ? `/${route.path}` : ''}`\n : `${parent ? `/${parent}` : ''}${\n route.path ? `/${route.path}` : '/'\n }`,\n filename: route.filename,\n file: route.filename?.replace(/(^.*)pages\\//, '') || '',\n isLayout: route.isLayout,\n });\n\n if (route.children) {\n const parentSegments = [parent, route.path];\n\n const fullParentPath = parentSegments.filter((s) => !!s).join('/');\n this.traverseRoutes(route.children, fullParentPath);\n }\n });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;;;;;;;;;;;;;;;;;;;;;;GA0BT,QAAA,CAAA,kzBAAA;EAAA,CAAA"}
@@ -1,238 +1,101 @@
1
- import { InjectionToken, makeEnvironmentProviders, provideAppInitializer, inject, assertInInjectionContext } from '@angular/core';
2
- import { LOCALE, REQUEST } from '@analogjs/router/tokens';
3
-
4
- /**
5
- * Injection token for the resolved i18n configuration.
6
- * Provided by `provideI18n()` and consumed by `injectSwitchLocale()`.
7
- * @internal
8
- */
9
- const I18N_CONFIG = new InjectionToken('@analogjs/router I18n Config');
10
- /**
11
- * Resolves the full i18n config by merging explicit values with
12
- * build-time globals injected by the platform plugin.
13
- */
1
+ import { InjectionToken, assertInInjectionContext, inject, makeEnvironmentProviders, provideAppInitializer } from "@angular/core";
2
+ import { LOCALE, REQUEST } from "@analogjs/router/tokens";
3
+ const I18N_CONFIG = new InjectionToken("@analogjs/router I18n Config");
14
4
  function resolveI18nConfig(config) {
15
- const defaultLocale = config.defaultLocale ??
16
- (typeof ANALOG_I18N_DEFAULT_LOCALE !== 'undefined'
17
- ? ANALOG_I18N_DEFAULT_LOCALE
18
- : undefined);
19
- const locales = config.locales ??
20
- (typeof ANALOG_I18N_LOCALES !== 'undefined'
21
- ? ANALOG_I18N_LOCALES
22
- : undefined);
23
- if (!defaultLocale || !locales) {
24
- throw new Error('[@analogjs/router] provideI18n() requires defaultLocale and locales. ' +
25
- 'Either pass them explicitly or configure i18n in the analog() plugin in vite.config.ts.');
26
- }
27
- return { defaultLocale, locales, loader: config.loader };
5
+ const defaultLocale = config.defaultLocale ?? (typeof ANALOG_I18N_DEFAULT_LOCALE !== "undefined" ? ANALOG_I18N_DEFAULT_LOCALE : void 0);
6
+ const locales = config.locales ?? (typeof ANALOG_I18N_LOCALES !== "undefined" ? ANALOG_I18N_LOCALES : void 0);
7
+ if (!defaultLocale || !locales) throw new Error("[@analogjs/router] provideI18n() requires defaultLocale and locales. Either pass them explicitly or configure i18n in the analog() plugin in vite.config.ts.");
8
+ return {
9
+ defaultLocale,
10
+ locales,
11
+ loader: config.loader
12
+ };
28
13
  }
29
- /**
30
- * Provides runtime i18n support using Angular's $localize.
31
- *
32
- * This provider:
33
- * 1. Detects the active locale from the URL or falls back to the default.
34
- * 2. Makes the current locale available via the LOCALE injection token.
35
- * 3. Loads translations for the active locale at startup using $localize.
36
- *
37
- * Works in both SSR and client-only modes. On the client, locale is detected
38
- * from `window.location.pathname`. On the server, locale is detected from
39
- * the request in `provideServerContext()` and provided at the platform level;
40
- * this function does not shadow it.
41
- *
42
- * When the platform plugin is configured with `i18n` in `vite.config.ts`,
43
- * `defaultLocale` and `locales` are injected automatically — only
44
- * `loader` is required:
45
- *
46
- * ```typescript
47
- * provideI18n({
48
- * loader: (locale) => import(`./i18n/${locale}.json`),
49
- * })
50
- * ```
51
- */
52
14
  function provideI18n(config) {
53
- const resolved = resolveI18nConfig(config);
54
- // Only provide LOCALE at the environment level on the client. On the
55
- // server, the platform-level LOCALE set by `provideServerContext()` is
56
- // authoritative and must not be shadowed by an environment-level provider.
57
- const localeProviders = typeof window !== 'undefined'
58
- ? [{ provide: LOCALE, useValue: detectClientLocale(resolved) }]
59
- : [];
60
- return makeEnvironmentProviders([
61
- { provide: I18N_CONFIG, useValue: resolved },
62
- ...localeProviders,
63
- provideAppInitializer(async () => {
64
- if (typeof window === 'undefined' &&
65
- typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&
66
- ANALOG_I18N_FIXED_LOCALE) {
67
- // The worker entry loads translations before importing the application.
68
- if (!resolved.locales.includes(ANALOG_I18N_FIXED_LOCALE)) {
69
- throw new Error('The i18n worker locale must be included in provideI18n().');
70
- }
71
- return;
72
- }
73
- const locale = resolveActiveLocale(resolved);
74
- await initI18n(resolved, locale);
75
- }),
76
- ]);
15
+ const resolved = resolveI18nConfig(config);
16
+ const localeProviders = typeof window !== "undefined" ? [{
17
+ provide: LOCALE,
18
+ useValue: detectClientLocale(resolved)
19
+ }] : [];
20
+ return makeEnvironmentProviders([
21
+ {
22
+ provide: I18N_CONFIG,
23
+ useValue: resolved
24
+ },
25
+ ...localeProviders,
26
+ provideAppInitializer(async () => {
27
+ if (typeof window === "undefined" && typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE) {
28
+ if (!resolved.locales.includes(ANALOG_I18N_FIXED_LOCALE)) throw new Error("The i18n worker locale must be included in provideI18n().");
29
+ return;
30
+ }
31
+ const locale = resolveActiveLocale(resolved);
32
+ await initI18n(resolved, locale);
33
+ })
34
+ ]);
77
35
  }
78
- /**
79
- * Resolves the active locale, preferring the injected `LOCALE` token
80
- * (which on the server reads from the platform-level provider set by
81
- * `provideServerContext()`) and falling back to the request URL,
82
- * `window.location.pathname`, or `defaultLocale`.
83
- */
84
36
  function resolveActiveLocale(config) {
85
- const injected = inject(LOCALE, { optional: true });
86
- if (injected && config.locales.includes(injected)) {
87
- return injected;
88
- }
89
- // Fallback: read the path directly from the request on the server or
90
- // from the browser URL on the client. This covers cases where a locale
91
- // prefix is present in the URL but no token provider set it explicitly.
92
- const req = inject(REQUEST, { optional: true });
93
- const pathname = req?.originalUrl ??
94
- req?.url ??
95
- (typeof window !== 'undefined' ? window.location.pathname : '/');
96
- const first = pathname.split('?')[0].split('/').filter(Boolean)[0];
97
- if (first && config.locales.includes(first)) {
98
- return first;
99
- }
100
- return config.defaultLocale;
37
+ const injected = inject(LOCALE, { optional: true });
38
+ if (injected && config.locales.includes(injected)) return injected;
39
+ const req = inject(REQUEST, { optional: true });
40
+ const first = (req?.originalUrl ?? req?.url ?? (typeof window !== "undefined" ? window.location.pathname : "/")).split("?")[0].split("/").filter(Boolean)[0];
41
+ if (first && config.locales.includes(first)) return first;
42
+ return config.defaultLocale;
101
43
  }
102
- /**
103
- * Detects the locale on the client from the URL path prefix.
104
- * Returns the default locale on the server or when no match is found.
105
- */
106
44
  function detectClientLocale(config) {
107
- if (typeof window === 'undefined') {
108
- return config.defaultLocale;
109
- }
110
- const pathname = window.location.pathname;
111
- const segments = pathname.split('/').filter(Boolean);
112
- const firstSegment = segments[0];
113
- if (firstSegment && config.locales.includes(firstSegment)) {
114
- return firstSegment;
115
- }
116
- return config.defaultLocale;
45
+ if (typeof window === "undefined") return config.defaultLocale;
46
+ const firstSegment = window.location.pathname.split("/").filter(Boolean)[0];
47
+ if (firstSegment && config.locales.includes(firstSegment)) return firstSegment;
48
+ return config.defaultLocale;
117
49
  }
118
- /**
119
- * Loads translations for the given locale and registers them with $localize.
120
- *
121
- * Always clears any previously loaded translations first so that switching
122
- * between locales in a single SSR process does not mix translation maps.
123
- */
124
50
  async function initI18n(config, locale) {
125
- const activeLocale = locale ?? config.defaultLocale;
126
- await clearTranslationsRuntime();
127
- // The source locale (first entry in `locales`) has its messages baked
128
- // directly into the template source, so there is nothing to load.
129
- if (activeLocale === config.locales[0]) {
130
- return;
131
- }
132
- const translations = await config.loader(activeLocale);
133
- if (translations && Object.keys(translations).length > 0) {
134
- await loadTranslationsRuntime(translations);
135
- }
51
+ const activeLocale = locale ?? config.defaultLocale;
52
+ await clearTranslationsRuntime();
53
+ if (activeLocale === config.locales[0]) return;
54
+ const translations = await config.loader(activeLocale);
55
+ if (translations && Object.keys(translations).length > 0) await loadTranslationsRuntime(translations);
136
56
  }
137
- /**
138
- * Loads translations into the global $localize translation map.
139
- *
140
- * Uses `@angular/localize`'s `loadTranslations` when available so that
141
- * each translation string is parsed into the `{text, messageParts,
142
- * placeholderNames}` shape that `$localize.translate` expects. Falls back
143
- * to writing raw strings only as a last resort (in which case lookups
144
- * will not succeed — the fallback exists to keep error messages useful
145
- * for users who have not installed `@angular/localize`).
146
- *
147
- * Requires `@angular/localize/init` to be imported in the application
148
- * entry point so that `globalThis.$localize` is defined.
149
- */
150
57
  async function loadTranslationsRuntime(translations) {
151
- const $localize = globalThis.$localize;
152
- if (!$localize) {
153
- console.warn('[@analogjs/router] $localize is not available. ' +
154
- 'Make sure to import @angular/localize/init in your application entry point.');
155
- return;
156
- }
157
- try {
158
- const { loadTranslations } = (await import('@angular/localize'));
159
- loadTranslations(translations);
160
- }
161
- catch {
162
- console.warn('[@analogjs/router] Unable to import @angular/localize. ' +
163
- 'Install it as a dependency to enable runtime translation loading.');
164
- $localize.TRANSLATIONS ??= {};
165
- for (const [id, message] of Object.entries(translations)) {
166
- $localize.TRANSLATIONS[id] = message;
167
- }
168
- }
58
+ const $localize = globalThis.$localize;
59
+ if (!$localize) {
60
+ console.warn("[@analogjs/router] $localize is not available. Make sure to import @angular/localize/init in your application entry point.");
61
+ return;
62
+ }
63
+ try {
64
+ const { loadTranslations } = await import("@angular/localize");
65
+ loadTranslations(translations);
66
+ } catch {
67
+ console.warn("[@analogjs/router] Unable to import @angular/localize. Install it as a dependency to enable runtime translation loading.");
68
+ $localize.TRANSLATIONS ??= {};
69
+ for (const [id, message] of Object.entries(translations)) $localize.TRANSLATIONS[id] = message;
70
+ }
169
71
  }
170
- /**
171
- * Clears any previously loaded translations from `$localize` so that the
172
- * next render falls through to the source messages until new translations
173
- * are loaded. Uses `@angular/localize`'s `clearTranslations` when present.
174
- */
175
- /** @internal — exported for tests; not re-exported from the package entry. */
176
72
  async function clearTranslationsRuntime() {
177
- const $localize = globalThis.$localize;
178
- if (!$localize) {
179
- return;
180
- }
181
- try {
182
- const { clearTranslations } = (await import('@angular/localize'));
183
- clearTranslations();
184
- }
185
- catch {
186
- $localize.translate = undefined;
187
- $localize.TRANSLATIONS = {};
188
- }
73
+ const $localize = globalThis.$localize;
74
+ if (!$localize) return;
75
+ try {
76
+ const { clearTranslations } = await import("@angular/localize");
77
+ clearTranslations();
78
+ } catch {
79
+ $localize.translate = void 0;
80
+ $localize.TRANSLATIONS = {};
81
+ }
189
82
  }
190
- /**
191
- * Returns an injectable function that switches the application locale.
192
- * Reads the configured locales from the I18N_CONFIG token provided
193
- * by `provideI18n()`.
194
- *
195
- * Triggers a full page navigation to the new locale URL so that
196
- * all $localize templates re-evaluate with the correct translations.
197
- *
198
- * Usage:
199
- * ```typescript
200
- * const switchLang = injectSwitchLocale();
201
- * switchLang('fr'); // navigates to /fr/current-path
202
- * ```
203
- */
204
83
  function injectSwitchLocale() {
205
- assertInInjectionContext(injectSwitchLocale);
206
- const config = inject(I18N_CONFIG);
207
- return (targetLocale) => {
208
- if (typeof window === 'undefined') {
209
- return;
210
- }
211
- const { pathname, search, hash } = window.location;
212
- const newPath = replaceLocaleInPath(pathname, targetLocale, config.locales);
213
- window.location.href = `${newPath}${search}${hash}`;
214
- };
84
+ assertInInjectionContext(injectSwitchLocale);
85
+ const config = inject(I18N_CONFIG);
86
+ return (targetLocale) => {
87
+ if (typeof window === "undefined") return;
88
+ const { pathname, search, hash } = window.location;
89
+ const newPath = replaceLocaleInPath(pathname, targetLocale, config.locales);
90
+ window.location.href = `${newPath}${search}${hash}`;
91
+ };
215
92
  }
216
- /**
217
- * Replaces or inserts the locale prefix in a URL path.
218
- *
219
- * - If the path starts with a known locale, it is swapped.
220
- * - If no locale prefix exists, the target locale is prepended.
221
- */
222
93
  function replaceLocaleInPath(pathname, targetLocale, locales) {
223
- const segments = pathname.split('/').filter(Boolean);
224
- if (segments.length > 0 && locales.includes(segments[0])) {
225
- segments[0] = targetLocale;
226
- }
227
- else {
228
- segments.unshift(targetLocale);
229
- }
230
- return '/' + segments.join('/');
94
+ const segments = pathname.split("/").filter(Boolean);
95
+ if (segments.length > 0 && locales.includes(segments[0])) segments[0] = targetLocale;
96
+ else segments.unshift(targetLocale);
97
+ return "/" + segments.join("/");
231
98
  }
232
-
233
- /**
234
- * Generated bundle index. Do not edit.
235
- */
236
-
237
99
  export { injectSwitchLocale, loadTranslationsRuntime, provideI18n };
238
- //# sourceMappingURL=analogjs-router-i18n.mjs.map
100
+
101
+ //# sourceMappingURL=analogjs-router-i18n.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"analogjs-router-i18n.mjs","sources":["../../../../packages/router/i18n/src/provide-i18n.ts","../../../../packages/router/i18n/src/analogjs-router-i18n.ts"],"sourcesContent":["import {\n EnvironmentProviders,\n InjectionToken,\n assertInInjectionContext,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { LOCALE, REQUEST, ServerRequest } from '@analogjs/router/tokens';\n\ndeclare const ANALOG_I18N_DEFAULT_LOCALE: string;\ndeclare const ANALOG_I18N_LOCALES: string[];\ndeclare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\n/**\n * Configuration for runtime i18n support.\n *\n * `defaultLocale` and `locales` are optional when the platform plugin\n * is configured with `i18n` in `vite.config.ts` — the values are\n * injected as build-time globals automatically.\n */\nexport interface I18nConfig {\n /**\n * The default locale to use when no locale is detected.\n * If omitted, reads from the platform plugin's `i18n.defaultLocale`.\n */\n defaultLocale?: string;\n\n /**\n * List of supported locale identifiers.\n * If omitted, reads from the platform plugin's `i18n.locales`.\n */\n locales?: string[];\n\n /**\n * A function that returns translations for a given locale.\n * The returned record maps message IDs to translated strings.\n */\n loader: (\n locale: string,\n ) => Promise<Record<string, string>> | Record<string, string>;\n}\n\n/**\n * Fully resolved i18n config with all required fields.\n */\nexport type ResolvedI18nConfig = Required<I18nConfig>;\n\n/**\n * Injection token for the resolved i18n configuration.\n * Provided by `provideI18n()` and consumed by `injectSwitchLocale()`.\n * @internal\n */\nconst I18N_CONFIG = new InjectionToken<ResolvedI18nConfig>(\n '@analogjs/router I18n Config',\n);\n\n/**\n * Resolves the full i18n config by merging explicit values with\n * build-time globals injected by the platform plugin.\n */\nexport function resolveI18nConfig(config: I18nConfig): Required<I18nConfig> {\n const defaultLocale =\n config.defaultLocale ??\n (typeof ANALOG_I18N_DEFAULT_LOCALE !== 'undefined'\n ? ANALOG_I18N_DEFAULT_LOCALE\n : undefined);\n\n const locales =\n config.locales ??\n (typeof ANALOG_I18N_LOCALES !== 'undefined'\n ? ANALOG_I18N_LOCALES\n : undefined);\n\n if (!defaultLocale || !locales) {\n throw new Error(\n '[@analogjs/router] provideI18n() requires defaultLocale and locales. ' +\n 'Either pass them explicitly or configure i18n in the analog() plugin in vite.config.ts.',\n );\n }\n\n return { defaultLocale, locales, loader: config.loader };\n}\n\n/**\n * Provides runtime i18n support using Angular's $localize.\n *\n * This provider:\n * 1. Detects the active locale from the URL or falls back to the default.\n * 2. Makes the current locale available via the LOCALE injection token.\n * 3. Loads translations for the active locale at startup using $localize.\n *\n * Works in both SSR and client-only modes. On the client, locale is detected\n * from `window.location.pathname`. On the server, locale is detected from\n * the request in `provideServerContext()` and provided at the platform level;\n * this function does not shadow it.\n *\n * When the platform plugin is configured with `i18n` in `vite.config.ts`,\n * `defaultLocale` and `locales` are injected automatically — only\n * `loader` is required:\n *\n * ```typescript\n * provideI18n({\n * loader: (locale) => import(`./i18n/${locale}.json`),\n * })\n * ```\n */\nexport function provideI18n(config: I18nConfig): EnvironmentProviders {\n const resolved = resolveI18nConfig(config);\n\n // Only provide LOCALE at the environment level on the client. On the\n // server, the platform-level LOCALE set by `provideServerContext()` is\n // authoritative and must not be shadowed by an environment-level provider.\n const localeProviders =\n typeof window !== 'undefined'\n ? [{ provide: LOCALE, useValue: detectClientLocale(resolved) }]\n : [];\n\n return makeEnvironmentProviders([\n { provide: I18N_CONFIG, useValue: resolved },\n ...localeProviders,\n provideAppInitializer(async () => {\n if (\n typeof window === 'undefined' &&\n typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE\n ) {\n // The worker entry loads translations before importing the application.\n if (!resolved.locales.includes(ANALOG_I18N_FIXED_LOCALE)) {\n throw new Error(\n 'The i18n worker locale must be included in provideI18n().',\n );\n }\n return;\n }\n const locale = resolveActiveLocale(resolved);\n await initI18n(resolved, locale);\n }),\n ]);\n}\n\n/**\n * Resolves the active locale, preferring the injected `LOCALE` token\n * (which on the server reads from the platform-level provider set by\n * `provideServerContext()`) and falling back to the request URL,\n * `window.location.pathname`, or `defaultLocale`.\n */\nfunction resolveActiveLocale(config: ResolvedI18nConfig): string {\n const injected = inject(LOCALE, { optional: true });\n if (injected && config.locales.includes(injected)) {\n return injected;\n }\n\n // Fallback: read the path directly from the request on the server or\n // from the browser URL on the client. This covers cases where a locale\n // prefix is present in the URL but no token provider set it explicitly.\n const req = inject(REQUEST, { optional: true }) as ServerRequest | null;\n const pathname =\n req?.originalUrl ??\n req?.url ??\n (typeof window !== 'undefined' ? window.location.pathname : '/');\n const first = pathname.split('?')[0].split('/').filter(Boolean)[0];\n if (first && config.locales.includes(first)) {\n return first;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Detects the locale on the client from the URL path prefix.\n * Returns the default locale on the server or when no match is found.\n */\nexport function detectClientLocale(config: ResolvedI18nConfig): string {\n if (typeof window === 'undefined') {\n return config.defaultLocale;\n }\n\n const pathname = window.location.pathname;\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && config.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Loads translations for the given locale and registers them with $localize.\n *\n * Always clears any previously loaded translations first so that switching\n * between locales in a single SSR process does not mix translation maps.\n */\nexport async function initI18n(\n config: ResolvedI18nConfig,\n locale?: string,\n): Promise<void> {\n const activeLocale = locale ?? config.defaultLocale;\n await clearTranslationsRuntime();\n\n // The source locale (first entry in `locales`) has its messages baked\n // directly into the template source, so there is nothing to load.\n if (activeLocale === config.locales[0]) {\n return;\n }\n\n const translations = await config.loader(activeLocale);\n if (translations && Object.keys(translations).length > 0) {\n await loadTranslationsRuntime(translations);\n }\n}\n\n/**\n * Loads translations into the global $localize translation map.\n *\n * Uses `@angular/localize`'s `loadTranslations` when available so that\n * each translation string is parsed into the `{text, messageParts,\n * placeholderNames}` shape that `$localize.translate` expects. Falls back\n * to writing raw strings only as a last resort (in which case lookups\n * will not succeed — the fallback exists to keep error messages useful\n * for users who have not installed `@angular/localize`).\n *\n * Requires `@angular/localize/init` to be imported in the application\n * entry point so that `globalThis.$localize` is defined.\n */\nexport async function loadTranslationsRuntime(\n translations: Record<string, string>,\n): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n console.warn(\n '[@analogjs/router] $localize is not available. ' +\n 'Make sure to import @angular/localize/init in your application entry point.',\n );\n return;\n }\n\n try {\n const { loadTranslations } = (await import('@angular/localize')) as {\n loadTranslations: (t: Record<string, string>) => void;\n };\n loadTranslations(translations);\n } catch {\n console.warn(\n '[@analogjs/router] Unable to import @angular/localize. ' +\n 'Install it as a dependency to enable runtime translation loading.',\n );\n $localize.TRANSLATIONS ??= {};\n for (const [id, message] of Object.entries(translations)) {\n $localize.TRANSLATIONS[id] = message;\n }\n }\n}\n\n/**\n * Clears any previously loaded translations from `$localize` so that the\n * next render falls through to the source messages until new translations\n * are loaded. Uses `@angular/localize`'s `clearTranslations` when present.\n */\n/** @internal — exported for tests; not re-exported from the package entry. */\nexport async function clearTranslationsRuntime(): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n return;\n }\n try {\n const { clearTranslations } = (await import('@angular/localize')) as {\n clearTranslations: () => void;\n };\n clearTranslations();\n } catch {\n $localize.translate = undefined;\n $localize.TRANSLATIONS = {};\n }\n}\n\n/**\n * Returns an injectable function that switches the application locale.\n * Reads the configured locales from the I18N_CONFIG token provided\n * by `provideI18n()`.\n *\n * Triggers a full page navigation to the new locale URL so that\n * all $localize templates re-evaluate with the correct translations.\n *\n * Usage:\n * ```typescript\n * const switchLang = injectSwitchLocale();\n * switchLang('fr'); // navigates to /fr/current-path\n * ```\n */\nexport function injectSwitchLocale(): (targetLocale: string) => void {\n assertInInjectionContext(injectSwitchLocale);\n const config = inject(I18N_CONFIG);\n\n return (targetLocale: string) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const { pathname, search, hash } = window.location;\n const newPath = replaceLocaleInPath(pathname, targetLocale, config.locales);\n window.location.href = `${newPath}${search}${hash}`;\n };\n}\n\n/**\n * Replaces or inserts the locale prefix in a URL path.\n *\n * - If the path starts with a known locale, it is swapped.\n * - If no locale prefix exists, the target locale is prepended.\n */\nexport function replaceLocaleInPath(\n pathname: string,\n targetLocale: string,\n locales: string[],\n): string {\n const segments = pathname.split('/').filter(Boolean);\n\n if (segments.length > 0 && locales.includes(segments[0])) {\n segments[0] = targetLocale;\n } else {\n segments.unshift(targetLocale);\n }\n\n return '/' + segments.join('/');\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;AAgDA;;;;AAIG;AACH,MAAM,WAAW,GAAG,IAAI,cAAc,CACpC,8BAA8B,CAC/B;AAED;;;AAGG;AACG,SAAU,iBAAiB,CAAC,MAAkB,EAAA;AAClD,IAAA,MAAM,aAAa,GACjB,MAAM,CAAC,aAAa;SACnB,OAAO,0BAA0B,KAAK;AACrC,cAAE;cACA,SAAS,CAAC;AAEhB,IAAA,MAAM,OAAO,GACX,MAAM,CAAC,OAAO;SACb,OAAO,mBAAmB,KAAK;AAC9B,cAAE;cACA,SAAS,CAAC;AAEhB,IAAA,IAAI,CAAC,aAAa,IAAI,CAAC,OAAO,EAAE;QAC9B,MAAM,IAAI,KAAK,CACb,uEAAuE;AACrE,YAAA,yFAAyF,CAC5F;IACH;IAEA,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE;AAC1D;AAEA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AACG,SAAU,WAAW,CAAC,MAAkB,EAAA;AAC5C,IAAA,MAAM,QAAQ,GAAG,iBAAiB,CAAC,MAAM,CAAC;;;;AAK1C,IAAA,MAAM,eAAe,GACnB,OAAO,MAAM,KAAK;AAChB,UAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE;UAC5D,EAAE;AAER,IAAA,OAAO,wBAAwB,CAAC;AAC9B,QAAA,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE;AAC5C,QAAA,GAAG,eAAe;QAClB,qBAAqB,CAAC,YAAW;YAC/B,IACE,OAA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A,EAAG,IAAI,CAAA,CAAE;AACrD,IAAA,CAAC;AACH;AAEA;;;;;AAKG;SACa,mBAAmB,CACjC,QAAgB,EAChB,YAAoB,EACpB,OAAiB,EAAA;AAEjB,IAAA,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC;AAEpD,IAAA,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;AACxD,QAAA,QAAQ,CAAC,CAAC,CAAC,GAAG,YAAY;IAC5B;SAAO;AACL,QAAA,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC;IAChC;IAEA,OAAO,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC;AACjC;;ACvUA;;AAEG;;;;"}
1
+ {"version":3,"file":"analogjs-router-i18n.mjs","names":[],"sources":["../../../../packages/router/i18n/src/provide-i18n.ts"],"sourcesContent":["import {\n EnvironmentProviders,\n InjectionToken,\n assertInInjectionContext,\n inject,\n makeEnvironmentProviders,\n provideAppInitializer,\n} from '@angular/core';\nimport { LOCALE, REQUEST, ServerRequest } from '@analogjs/router/tokens';\n\ndeclare const ANALOG_I18N_DEFAULT_LOCALE: string;\ndeclare const ANALOG_I18N_LOCALES: string[];\ndeclare const ANALOG_I18N_FIXED_LOCALE: string | undefined;\n\n/**\n * Configuration for runtime i18n support.\n *\n * `defaultLocale` and `locales` are optional when the platform plugin\n * is configured with `i18n` in `vite.config.ts` — the values are\n * injected as build-time globals automatically.\n */\nexport interface I18nConfig {\n /**\n * The default locale to use when no locale is detected.\n * If omitted, reads from the platform plugin's `i18n.defaultLocale`.\n */\n defaultLocale?: string;\n\n /**\n * List of supported locale identifiers.\n * If omitted, reads from the platform plugin's `i18n.locales`.\n */\n locales?: string[];\n\n /**\n * A function that returns translations for a given locale.\n * The returned record maps message IDs to translated strings.\n */\n loader: (\n locale: string,\n ) => Promise<Record<string, string>> | Record<string, string>;\n}\n\n/**\n * Fully resolved i18n config with all required fields.\n */\nexport type ResolvedI18nConfig = Required<I18nConfig>;\n\n/**\n * Injection token for the resolved i18n configuration.\n * Provided by `provideI18n()` and consumed by `injectSwitchLocale()`.\n * @internal\n */\nconst I18N_CONFIG = new InjectionToken<ResolvedI18nConfig>(\n '@analogjs/router I18n Config',\n);\n\n/**\n * Resolves the full i18n config by merging explicit values with\n * build-time globals injected by the platform plugin.\n */\nexport function resolveI18nConfig(config: I18nConfig): Required<I18nConfig> {\n const defaultLocale =\n config.defaultLocale ??\n (typeof ANALOG_I18N_DEFAULT_LOCALE !== 'undefined'\n ? ANALOG_I18N_DEFAULT_LOCALE\n : undefined);\n\n const locales =\n config.locales ??\n (typeof ANALOG_I18N_LOCALES !== 'undefined'\n ? ANALOG_I18N_LOCALES\n : undefined);\n\n if (!defaultLocale || !locales) {\n throw new Error(\n '[@analogjs/router] provideI18n() requires defaultLocale and locales. ' +\n 'Either pass them explicitly or configure i18n in the analog() plugin in vite.config.ts.',\n );\n }\n\n return { defaultLocale, locales, loader: config.loader };\n}\n\n/**\n * Provides runtime i18n support using Angular's $localize.\n *\n * This provider:\n * 1. Detects the active locale from the URL or falls back to the default.\n * 2. Makes the current locale available via the LOCALE injection token.\n * 3. Loads translations for the active locale at startup using $localize.\n *\n * Works in both SSR and client-only modes. On the client, locale is detected\n * from `window.location.pathname`. On the server, locale is detected from\n * the request in `provideServerContext()` and provided at the platform level;\n * this function does not shadow it.\n *\n * When the platform plugin is configured with `i18n` in `vite.config.ts`,\n * `defaultLocale` and `locales` are injected automatically — only\n * `loader` is required:\n *\n * ```typescript\n * provideI18n({\n * loader: (locale) => import(`./i18n/${locale}.json`),\n * })\n * ```\n */\nexport function provideI18n(config: I18nConfig): EnvironmentProviders {\n const resolved = resolveI18nConfig(config);\n\n // Only provide LOCALE at the environment level on the client. On the\n // server, the platform-level LOCALE set by `provideServerContext()` is\n // authoritative and must not be shadowed by an environment-level provider.\n const localeProviders =\n typeof window !== 'undefined'\n ? [{ provide: LOCALE, useValue: detectClientLocale(resolved) }]\n : [];\n\n return makeEnvironmentProviders([\n { provide: I18N_CONFIG, useValue: resolved },\n ...localeProviders,\n provideAppInitializer(async () => {\n if (\n typeof window === 'undefined' &&\n typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&\n ANALOG_I18N_FIXED_LOCALE\n ) {\n // The worker entry loads translations before importing the application.\n if (!resolved.locales.includes(ANALOG_I18N_FIXED_LOCALE)) {\n throw new Error(\n 'The i18n worker locale must be included in provideI18n().',\n );\n }\n return;\n }\n const locale = resolveActiveLocale(resolved);\n await initI18n(resolved, locale);\n }),\n ]);\n}\n\n/**\n * Resolves the active locale, preferring the injected `LOCALE` token\n * (which on the server reads from the platform-level provider set by\n * `provideServerContext()`) and falling back to the request URL,\n * `window.location.pathname`, or `defaultLocale`.\n */\nfunction resolveActiveLocale(config: ResolvedI18nConfig): string {\n const injected = inject(LOCALE, { optional: true });\n if (injected && config.locales.includes(injected)) {\n return injected;\n }\n\n // Fallback: read the path directly from the request on the server or\n // from the browser URL on the client. This covers cases where a locale\n // prefix is present in the URL but no token provider set it explicitly.\n const req = inject(REQUEST, { optional: true }) as ServerRequest | null;\n const pathname =\n req?.originalUrl ??\n req?.url ??\n (typeof window !== 'undefined' ? window.location.pathname : '/');\n const first = pathname.split('?')[0].split('/').filter(Boolean)[0];\n if (first && config.locales.includes(first)) {\n return first;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Detects the locale on the client from the URL path prefix.\n * Returns the default locale on the server or when no match is found.\n */\nexport function detectClientLocale(config: ResolvedI18nConfig): string {\n if (typeof window === 'undefined') {\n return config.defaultLocale;\n }\n\n const pathname = window.location.pathname;\n const segments = pathname.split('/').filter(Boolean);\n const firstSegment = segments[0];\n\n if (firstSegment && config.locales.includes(firstSegment)) {\n return firstSegment;\n }\n\n return config.defaultLocale;\n}\n\n/**\n * Loads translations for the given locale and registers them with $localize.\n *\n * Always clears any previously loaded translations first so that switching\n * between locales in a single SSR process does not mix translation maps.\n */\nexport async function initI18n(\n config: ResolvedI18nConfig,\n locale?: string,\n): Promise<void> {\n const activeLocale = locale ?? config.defaultLocale;\n await clearTranslationsRuntime();\n\n // The source locale (first entry in `locales`) has its messages baked\n // directly into the template source, so there is nothing to load.\n if (activeLocale === config.locales[0]) {\n return;\n }\n\n const translations = await config.loader(activeLocale);\n if (translations && Object.keys(translations).length > 0) {\n await loadTranslationsRuntime(translations);\n }\n}\n\n/**\n * Loads translations into the global $localize translation map.\n *\n * Uses `@angular/localize`'s `loadTranslations` when available so that\n * each translation string is parsed into the `{text, messageParts,\n * placeholderNames}` shape that `$localize.translate` expects. Falls back\n * to writing raw strings only as a last resort (in which case lookups\n * will not succeed — the fallback exists to keep error messages useful\n * for users who have not installed `@angular/localize`).\n *\n * Requires `@angular/localize/init` to be imported in the application\n * entry point so that `globalThis.$localize` is defined.\n */\nexport async function loadTranslationsRuntime(\n translations: Record<string, string>,\n): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n console.warn(\n '[@analogjs/router] $localize is not available. ' +\n 'Make sure to import @angular/localize/init in your application entry point.',\n );\n return;\n }\n\n try {\n const { loadTranslations } = (await import('@angular/localize')) as {\n loadTranslations: (t: Record<string, string>) => void;\n };\n loadTranslations(translations);\n } catch {\n console.warn(\n '[@analogjs/router] Unable to import @angular/localize. ' +\n 'Install it as a dependency to enable runtime translation loading.',\n );\n $localize.TRANSLATIONS ??= {};\n for (const [id, message] of Object.entries(translations)) {\n $localize.TRANSLATIONS[id] = message;\n }\n }\n}\n\n/**\n * Clears any previously loaded translations from `$localize` so that the\n * next render falls through to the source messages until new translations\n * are loaded. Uses `@angular/localize`'s `clearTranslations` when present.\n */\n/** @internal — exported for tests; not re-exported from the package entry. */\nexport async function clearTranslationsRuntime(): Promise<void> {\n const $localize = (globalThis as any).$localize;\n if (!$localize) {\n return;\n }\n try {\n const { clearTranslations } = (await import('@angular/localize')) as {\n clearTranslations: () => void;\n };\n clearTranslations();\n } catch {\n $localize.translate = undefined;\n $localize.TRANSLATIONS = {};\n }\n}\n\n/**\n * Returns an injectable function that switches the application locale.\n * Reads the configured locales from the I18N_CONFIG token provided\n * by `provideI18n()`.\n *\n * Triggers a full page navigation to the new locale URL so that\n * all $localize templates re-evaluate with the correct translations.\n *\n * Usage:\n * ```typescript\n * const switchLang = injectSwitchLocale();\n * switchLang('fr'); // navigates to /fr/current-path\n * ```\n */\nexport function injectSwitchLocale(): (targetLocale: string) => void {\n assertInInjectionContext(injectSwitchLocale);\n const config = inject(I18N_CONFIG);\n\n return (targetLocale: string) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const { pathname, search, hash } = window.location;\n const newPath = replaceLocaleInPath(pathname, targetLocale, config.locales);\n window.location.href = `${newPath}${search}${hash}`;\n };\n}\n\n/**\n * Replaces or inserts the locale prefix in a URL path.\n *\n * - If the path starts with a known locale, it is swapped.\n * - If no locale prefix exists, the target locale is prepended.\n */\nexport function replaceLocaleInPath(\n pathname: string,\n targetLocale: string,\n locales: string[],\n): string {\n const segments = pathname.split('/').filter(Boolean);\n\n if (segments.length > 0 && locales.includes(segments[0])) {\n segments[0] = targetLocale;\n } else {\n segments.unshift(targetLocale);\n }\n\n return '/' + segments.join('/');\n}\n"],"mappings":";;AAqDA,MAAM,cAAc,IAAI,eACtB,8BAA8B;AAOhC,SAAgB,kBAAkB,QAAkB;CAClD,MAAM,gBACJ,OAAO,kBACN,OAAO,+BAA+B,cACnC,6BACA;CAEN,MAAM,UACJ,OAAO,YACN,OAAO,wBAAwB,cAC5B,sBACA;CAEN,IAAI,CAAC,iBAAiB,CAAC,SACrB,MAAM,IAAI,MACR,8JAC2F;CAI/F,OAAO;EAAE;EAAe;EAAS,QAAQ,OAAO;CAAM;AACxD;AAyBA,SAAgB,YAAY,QAAkB;CAC5C,MAAM,WAAW,kBAAkB,MAAM;CAKzC,MAAM,kBACJ,OAAO,WAAW,c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