@analogjs/router 3.0.0-alpha.9 → 3.0.0-alpha.90

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 (99) hide show
  1. package/content/package.json +4 -0
  2. package/fesm2022/analogjs-router-content.mjs +63 -0
  3. package/fesm2022/analogjs-router-content.mjs.map +1 -0
  4. package/fesm2022/analogjs-router-i18n.mjs +156 -0
  5. package/fesm2022/analogjs-router-i18n.mjs.map +1 -0
  6. package/fesm2022/analogjs-router-server-actions.mjs +2 -27
  7. package/fesm2022/analogjs-router-server.mjs +734 -105
  8. package/fesm2022/analogjs-router-server.mjs.map +1 -0
  9. package/fesm2022/analogjs-router-tanstack-query-server.mjs +71 -0
  10. package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -0
  11. package/fesm2022/analogjs-router-tanstack-query.mjs +39 -0
  12. package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -0
  13. package/fesm2022/analogjs-router-tokens.mjs +7 -2
  14. package/fesm2022/analogjs-router-tokens.mjs.map +1 -0
  15. package/fesm2022/analogjs-router.mjs +827 -179
  16. package/fesm2022/analogjs-router.mjs.map +1 -0
  17. package/fesm2022/debug.page.mjs +53 -31
  18. package/fesm2022/debug.page.mjs.map +1 -0
  19. package/fesm2022/provide-analog-query.mjs +72 -0
  20. package/fesm2022/provide-analog-query.mjs.map +1 -0
  21. package/fesm2022/route-files.mjs +361 -0
  22. package/fesm2022/route-files.mjs.map +1 -0
  23. package/fesm2022/routes.mjs +5 -278
  24. package/fesm2022/routes.mjs.map +1 -0
  25. package/fesm2022/src.mjs +335 -0
  26. package/fesm2022/src.mjs.map +1 -0
  27. package/i18n/package.json +4 -0
  28. package/package.json +51 -6
  29. package/tanstack-query/package.json +4 -0
  30. package/tanstack-query/server/package.json +4 -0
  31. package/types/content/src/index.d.ts +4 -0
  32. package/types/content/src/lib/debug/routes.d.ts +10 -0
  33. package/types/{src → content/src}/lib/markdown-helpers.d.ts +1 -1
  34. package/types/content/src/lib/routes.d.ts +8 -0
  35. package/types/content/src/lib/with-content-routes.d.ts +2 -0
  36. package/types/i18n/src/index.d.ts +1 -0
  37. package/types/i18n/src/provide-i18n.d.ts +92 -0
  38. package/types/server/actions/src/actions.d.ts +1 -1
  39. package/types/server/actions/src/define-action.d.ts +54 -0
  40. package/types/server/actions/src/define-api-route.d.ts +57 -0
  41. package/types/server/actions/src/define-page-load.d.ts +55 -0
  42. package/types/server/actions/src/define-server-route.d.ts +68 -0
  43. package/types/server/actions/src/index.d.ts +9 -1
  44. package/types/server/actions/src/parse-request-data.d.ts +9 -0
  45. package/types/server/actions/src/validate.d.ts +8 -0
  46. package/types/server/src/defer-reconcile-runtime.d.ts +23 -0
  47. package/types/server/src/index.d.ts +9 -2
  48. package/types/server/src/provide-server-context.d.ts +15 -1
  49. package/types/server/src/render-stream.d.ts +40 -0
  50. package/types/server/src/render.d.ts +3 -3
  51. package/types/server/src/server-fn/app-injector.d.ts +30 -0
  52. package/types/server/src/server-fn/dispatch.d.ts +56 -0
  53. package/types/server/src/server-fn/event-handler.d.ts +22 -0
  54. package/types/server/src/server-fn/interceptors.d.ts +30 -0
  55. package/types/server/src/server-fn/node-context.d.ts +14 -0
  56. package/types/server/src/server-fn/registry.d.ts +7 -0
  57. package/types/server/src/server-fn/same-origin.d.ts +46 -0
  58. package/types/server/src/server-fn/server-fn.d.ts +21 -0
  59. package/types/server/src/server-fn/ssr-dispatcher.d.ts +17 -0
  60. package/types/server/src/utils/reset-component-def-tviews.d.ts +14 -0
  61. package/types/server/src/utils/stream-html.d.ts +13 -0
  62. package/types/server/src/utils/stream-request.d.ts +24 -0
  63. package/types/src/index.d.ts +20 -6
  64. package/types/src/lib/cookie-interceptor.d.ts +1 -1
  65. package/types/src/lib/debug/debug.page.d.ts +4 -2
  66. package/types/src/lib/define-route.d.ts +6 -1
  67. package/types/src/lib/endpoints.d.ts +1 -1
  68. package/types/src/lib/experimental.d.ts +140 -0
  69. package/types/src/lib/form-action.directive.d.ts +12 -5
  70. package/types/src/lib/inject-load.d.ts +5 -2
  71. package/types/src/lib/inject-navigate.d.ts +23 -0
  72. package/types/src/lib/inject-route-context.d.ts +32 -0
  73. package/types/src/lib/inject-typed-params.d.ts +63 -0
  74. package/types/src/lib/json-ld.d.ts +32 -0
  75. package/types/src/lib/meta-tags.d.ts +3 -1
  76. package/types/src/lib/models.d.ts +3 -0
  77. package/types/src/lib/provide-file-router-base.d.ts +4 -0
  78. package/types/src/lib/provide-file-router.d.ts +2 -8
  79. package/types/src/lib/route-builder.d.ts +5 -0
  80. package/types/src/lib/route-files.d.ts +18 -0
  81. package/types/src/lib/route-path.d.ts +124 -0
  82. package/types/src/lib/route-types.d.ts +3 -2
  83. package/types/src/lib/routes.d.ts +2 -10
  84. package/types/src/lib/server-fn/dispatcher.d.ts +23 -0
  85. package/types/src/lib/server-fn/inject-server-fn.d.ts +44 -0
  86. package/types/src/lib/server-fn/server-fn-ref.d.ts +24 -0
  87. package/types/src/lib/server-fn/types.d.ts +55 -0
  88. package/types/src/lib/validation-errors.d.ts +7 -0
  89. package/types/tanstack-query/server/src/define-page-load-queries.d.ts +66 -0
  90. package/types/tanstack-query/server/src/index.d.ts +3 -0
  91. package/types/tanstack-query/src/constants.d.ts +9 -0
  92. package/types/tanstack-query/src/index.d.ts +2 -0
  93. package/types/tanstack-query/src/provide-analog-query.d.ts +4 -0
  94. package/types/tanstack-query/src/provide-server-analog-query.d.ts +2 -0
  95. package/types/tanstack-query/src/server-query.d.ts +16 -0
  96. package/types/tokens/src/index.d.ts +3 -1
  97. package/types/server/src/server-component-render.d.ts +0 -4
  98. package/types/server/src/tokens.d.ts +0 -7
  99. package/types/src/lib/server.component.d.ts +0 -33
@@ -1,12 +1,14 @@
1
- import { a as updateMetaTagsOnRouteChange, i as injectRouteEndpointURL, n as createRoutes, r as routes, t as injectDebugRoutes } from "./routes.mjs";
1
+ import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectInternalServerFetch, injectRequest } from "./analogjs-router-tokens.mjs";
2
+ import { a as updateMetaTagsOnRouteChange, i as injectRouteEndpointURL, n as ANALOG_ROUTE_FILES, o as updateJsonLdOnRouteChange, r as createRoutes$1, t as ANALOG_EXTRA_ROUTE_FILE_SOURCES } from "./route-files.mjs";
3
+ import { n as createRoutes, r as routes, t as injectDebugRoutes } from "./routes.mjs";
2
4
  import { ActivatedRoute, ROUTES, Router, provideRouter } from "@angular/router";
3
5
  import * as i0 from "@angular/core";
4
- import { ChangeDetectionStrategy, Component, Directive, ENVIRONMENT_INITIALIZER, Injector, PLATFORM_ID, TransferState, effect, inject, input, makeEnvironmentProviders, makeStateKey, output, signal } from "@angular/core";
5
- import { HttpClient, HttpHeaders, HttpRequest, HttpResponse, ɵHTTP_ROOT_INTERCEPTOR_FNS } from "@angular/common/http";
6
- import { catchError, from, map, of, throwError } from "rxjs";
7
- import { API_PREFIX, injectAPIPrefix, injectBaseURL, injectInternalServerFetch, injectRequest } from "@analogjs/router/tokens";
8
- import { DomSanitizer } from "@angular/platform-browser";
6
+ import { DOCUMENT, Directive, Injectable, InjectionToken, Injector, PLATFORM_ID, TransferState, assertInInjectionContext, inject, input, isDevMode, makeEnvironmentProviders, makeStateKey, output, provideAppInitializer, resource, signal } from "@angular/core";
7
+ import { HttpClient, HttpHeaders, HttpResponse, ɵHTTP_ROOT_INTERCEPTOR_FNS } from "@angular/common/http";
8
+ import { firstValueFrom, from, map, of, take } from "rxjs";
9
+ import { Meta } from "@angular/platform-browser";
9
10
  import { isPlatformServer } from "@angular/common";
11
+ import { toSignal } from "@angular/core/rxjs-interop";
10
12
  //#region packages/router/src/lib/define-route.ts
11
13
  /**
12
14
  * @deprecated Use `RouteMeta` type instead.
@@ -66,26 +68,38 @@ function cookieInterceptor(req, next, location = inject(PLATFORM_ID), serverRequ
66
68
  } else return next(req);
67
69
  }
68
70
  //#endregion
69
- //#region packages/router/src/lib/provide-file-router.ts
70
- /**
71
- * Sets up providers for the Angular router, and registers
72
- * file-based routes. Additional features can be provided
73
- * to further configure the behavior of the router.
74
- *
75
- * @param features
76
- * @returns Providers and features to configure the router with routes
77
- */
78
- function provideFileRouter(...features) {
71
+ //#region packages/router/src/lib/provide-file-router-base.ts
72
+ function provideFileRouterWithRoutes(...features) {
79
73
  const extraRoutesFeature = features.filter((feat) => feat.ɵkind >= 100);
80
74
  const routerFeatures = features.filter((feat) => feat.ɵkind < 100);
81
75
  return makeEnvironmentProviders([
82
76
  extraRoutesFeature.map((erf) => erf.ɵproviders),
83
- provideRouter(routes, ...routerFeatures),
77
+ provideRouter([], ...routerFeatures),
84
78
  {
85
- provide: ENVIRONMENT_INITIALIZER,
79
+ provide: ROUTES,
86
80
  multi: true,
87
- useValue: () => updateMetaTagsOnRouteChange()
81
+ useFactory: () => {
82
+ const extraSources = inject(ANALOG_EXTRA_ROUTE_FILE_SOURCES, { optional: true }) ?? [];
83
+ if (extraSources.length === 0) return createRoutes$1(ANALOG_ROUTE_FILES, (_filename, fileLoader) => fileLoader);
84
+ const allFiles = { ...ANALOG_ROUTE_FILES };
85
+ const resolverMap = /* @__PURE__ */ new Map();
86
+ for (const source of extraSources) for (const [key, loader] of Object.entries(source.files)) {
87
+ allFiles[key] = loader;
88
+ resolverMap.set(key, source.resolveModule);
89
+ }
90
+ return createRoutes$1(allFiles, (filename, fileLoader) => {
91
+ const resolver = resolverMap.get(filename);
92
+ return resolver ? resolver(filename, fileLoader) : fileLoader;
93
+ });
94
+ }
88
95
  },
96
+ provideAppInitializer(() => {
97
+ const router = inject(Router);
98
+ const meta = inject(Meta);
99
+ const document = inject(DOCUMENT, { optional: true });
100
+ updateMetaTagsOnRouteChange(router, meta);
101
+ updateJsonLdOnRouteChange(router, document);
102
+ }),
89
103
  {
90
104
  provide: ɵHTTP_ROOT_INTERCEPTOR_FNS,
91
105
  multi: true,
@@ -99,12 +113,6 @@ function provideFileRouter(...features) {
99
113
  }
100
114
  ]);
101
115
  }
102
- /**
103
- * Provides extra custom routes in addition to the routes
104
- * discovered from the filesystem-based routing. These routes are
105
- * inserted before the filesystem-based routes, and take priority in
106
- * route matching.
107
- */
108
116
  function withExtraRoutes(routes) {
109
117
  return {
110
118
  ɵkind: 100,
@@ -116,10 +124,32 @@ function withExtraRoutes(routes) {
116
124
  };
117
125
  }
118
126
  //#endregion
127
+ //#region packages/router/src/lib/provide-file-router.ts
128
+ /**
129
+ * Sets up providers for the Angular router, and registers
130
+ * file-based routes. Additional features can be provided
131
+ * to further configure the behavior of the router.
132
+ *
133
+ * @param features
134
+ * @returns Providers and features to configure the router with routes
135
+ */
136
+ function provideFileRouter(...features) {
137
+ return provideFileRouterWithRoutes(...features);
138
+ }
139
+ //#endregion
119
140
  //#region packages/router/src/lib/inject-load.ts
141
+ function isResponse(value) {
142
+ return typeof value === "object" && value instanceof Response;
143
+ }
120
144
  function injectLoad(options) {
121
145
  return (options?.injector ?? inject(Injector)).get(ActivatedRoute).data.pipe(map((data) => data["load"]));
122
146
  }
147
+ function injectLoadData(options) {
148
+ return injectLoad(options).pipe(map((result) => {
149
+ if (isResponse(result)) throw new Error("Expected page load data but received a response.");
150
+ return result;
151
+ }));
152
+ }
123
153
  //#endregion
124
154
  //#region packages/router/src/lib/get-load-resolver.ts
125
155
  /**
@@ -133,8 +163,14 @@ async function getLoadResolver(route) {
133
163
  }
134
164
  //#endregion
135
165
  //#region packages/router/src/lib/cache-key.ts
166
+ function encodeAtom(value) {
167
+ return `${value.length}:${value}`;
168
+ }
136
169
  function sortAndConcatParams(params) {
137
- return [...params.keys()].sort().map((k) => `${k}=${params.getAll(k)}`).join("&");
170
+ const keys = [...new Set(params.keys())].sort();
171
+ const atoms = [];
172
+ for (const key of keys) for (const value of params.getAll(key) ?? []) atoms.push(encodeAtom(key), encodeAtom(value));
173
+ return atoms.join("");
138
174
  }
139
175
  function makeCacheKey(request, mappedRequestUrl) {
140
176
  const { params, method, responseType } = request;
@@ -148,19 +184,177 @@ function makeCacheKey(request, mappedRequestUrl) {
148
184
  mappedRequestUrl,
149
185
  serializedBody,
150
186
  encodedParams
151
- ].join("|")));
187
+ ].map(encodeAtom).join("")));
152
188
  }
153
- function generateHash(str) {
154
- let hash = 0;
155
- for (let i = 0, len = str.length; i < len; i++) {
156
- const chr = str.charCodeAt(i);
157
- hash = (hash << 5) - hash + chr;
158
- hash |= 0;
189
+ /**
190
+ * SHA-256 round constants (first 32 bits of the fractional parts of the cube
191
+ * roots of the first 64 primes).
192
+ */
193
+ var SHA256_ROUND_CONSTANTS = /* @__PURE__ */ new Uint32Array([
194
+ 1116352408,
195
+ 1899447441,
196
+ 3049323471,
197
+ 3921009573,
198
+ 961987163,
199
+ 1508970993,
200
+ 2453635748,
201
+ 2870763221,
202
+ 3624381080,
203
+ 310598401,
204
+ 607225278,
205
+ 1426881987,
206
+ 1925078388,
207
+ 2162078206,
208
+ 2614888103,
209
+ 3248222580,
210
+ 3835390401,
211
+ 4022224774,
212
+ 264347078,
213
+ 604807628,
214
+ 770255983,
215
+ 1249150122,
216
+ 1555081692,
217
+ 1996064986,
218
+ 2554220882,
219
+ 2821834349,
220
+ 2952996808,
221
+ 3210313671,
222
+ 3336571891,
223
+ 3584528711,
224
+ 113926993,
225
+ 338241895,
226
+ 666307205,
227
+ 773529912,
228
+ 1294757372,
229
+ 1396182291,
230
+ 1695183700,
231
+ 1986661051,
232
+ 2177026350,
233
+ 2456956037,
234
+ 2730485921,
235
+ 2820302411,
236
+ 3259730800,
237
+ 3345764771,
238
+ 3516065817,
239
+ 3600352804,
240
+ 4094571909,
241
+ 275423344,
242
+ 430227734,
243
+ 506948616,
244
+ 659060556,
245
+ 883997877,
246
+ 958139571,
247
+ 1322822218,
248
+ 1537002063,
249
+ 1747873779,
250
+ 1955562222,
251
+ 2024104815,
252
+ 2227730452,
253
+ 2361852424,
254
+ 2428436474,
255
+ 2756734187,
256
+ 3204031479,
257
+ 3329325298
258
+ ]);
259
+ var textEncoder;
260
+ /**
261
+ * Generates a SHA-256 hash of a string. This mirrors Angular's `HttpTransferCache`
262
+ * key derivation: a synchronous SHA-256 is used because the Web Crypto API is
263
+ * asynchronous, whereas cache-key derivation in the interceptor must stay
264
+ * synchronous. The previous 32-bit DJB2 hash had a keyspace small enough for an
265
+ * attacker to craft colliding requests and poison the transfer cache.
266
+ */
267
+ function generateHash(value) {
268
+ textEncoder ??= new TextEncoder();
269
+ const inputBytes = textEncoder.encode(value);
270
+ let hashState0 = 1779033703;
271
+ let hashState1 = 3144134277;
272
+ let hashState2 = 1013904242;
273
+ let hashState3 = 2773480762;
274
+ let hashState4 = 1359893119;
275
+ let hashState5 = 2600822924;
276
+ let hashState6 = 528734635;
277
+ let hashState7 = 1541459225;
278
+ const messageLengthInBits = inputBytes.length * 8;
279
+ const paddedLengthInBytes = (inputBytes.length + 8 >> 6) + 1 << 6;
280
+ const paddedBytes = new Uint8Array(paddedLengthInBytes);
281
+ paddedBytes.set(inputBytes);
282
+ paddedBytes[inputBytes.length] = 128;
283
+ const paddedBytesView = new DataView(paddedBytes.buffer);
284
+ const lowBits = messageLengthInBits >>> 0;
285
+ const highBits = messageLengthInBits / 4294967296 >>> 0;
286
+ paddedBytesView.setUint32(paddedLengthInBytes - 8, highBits, false);
287
+ paddedBytesView.setUint32(paddedLengthInBytes - 4, lowBits, false);
288
+ const messageSchedule = new Uint32Array(64);
289
+ for (let chunkOffset = 0; chunkOffset < paddedLengthInBytes; chunkOffset += 64) {
290
+ for (let i = 0; i < 16; i++) messageSchedule[i] = paddedBytesView.getUint32(chunkOffset + i * 4, false);
291
+ for (let i = 16; i < 64; i++) {
292
+ const prevWord15 = messageSchedule[i - 15];
293
+ const sigma0 = ((prevWord15 >>> 7 | prevWord15 << 25) ^ (prevWord15 >>> 18 | prevWord15 << 14) ^ prevWord15 >>> 3) >>> 0;
294
+ const prevWord2 = messageSchedule[i - 2];
295
+ const sigma1 = ((prevWord2 >>> 17 | prevWord2 << 15) ^ (prevWord2 >>> 19 | prevWord2 << 13) ^ prevWord2 >>> 10) >>> 0;
296
+ messageSchedule[i] = messageSchedule[i - 16] + sigma0 + messageSchedule[i - 7] + sigma1 >>> 0;
297
+ }
298
+ let workingStateA = hashState0;
299
+ let workingStateB = hashState1;
300
+ let workingStateC = hashState2;
301
+ let workingStateD = hashState3;
302
+ let workingStateE = hashState4;
303
+ let workingStateF = hashState5;
304
+ let workingStateG = hashState6;
305
+ let workingStateH = hashState7;
306
+ for (let i = 0; i < 64; i++) {
307
+ const capitalSigma1 = ((workingStateE >>> 6 | workingStateE << 26) ^ (workingStateE >>> 11 | workingStateE << 21) ^ (workingStateE >>> 25 | workingStateE << 7)) >>> 0;
308
+ const chFunction = (workingStateE & workingStateF ^ ~workingStateE & workingStateG) >>> 0;
309
+ const temp1 = workingStateH + capitalSigma1 + chFunction + SHA256_ROUND_CONSTANTS[i] + messageSchedule[i] >>> 0;
310
+ const temp2 = (((workingStateA >>> 2 | workingStateA << 30) ^ (workingStateA >>> 13 | workingStateA << 19) ^ (workingStateA >>> 22 | workingStateA << 10)) >>> 0) + ((workingStateA & workingStateB ^ workingStateA & workingStateC ^ workingStateB & workingStateC) >>> 0) >>> 0;
311
+ workingStateH = workingStateG;
312
+ workingStateG = workingStateF;
313
+ workingStateF = workingStateE;
314
+ workingStateE = workingStateD + temp1 >>> 0;
315
+ workingStateD = workingStateC;
316
+ workingStateC = workingStateB;
317
+ workingStateB = workingStateA;
318
+ workingStateA = temp1 + temp2 >>> 0;
319
+ }
320
+ hashState0 = hashState0 + workingStateA >>> 0;
321
+ hashState1 = hashState1 + workingStateB >>> 0;
322
+ hashState2 = hashState2 + workingStateC >>> 0;
323
+ hashState3 = hashState3 + workingStateD >>> 0;
324
+ hashState4 = hashState4 + workingStateE >>> 0;
325
+ hashState5 = hashState5 + workingStateF >>> 0;
326
+ hashState6 = hashState6 + workingStateG >>> 0;
327
+ hashState7 = hashState7 + workingStateH >>> 0;
159
328
  }
160
- return `${hash}`;
329
+ return [
330
+ hashState0,
331
+ hashState1,
332
+ hashState2,
333
+ hashState3,
334
+ hashState4,
335
+ hashState5,
336
+ hashState6,
337
+ hashState7
338
+ ].map((x) => x.toString(16).padStart(8, "0")).join("");
161
339
  }
162
340
  //#endregion
163
341
  //#region packages/router/src/lib/request-context.ts
342
+ function mergeFetchParams(requestUrl, request) {
343
+ const merged = /* @__PURE__ */ new Map();
344
+ for (const key of requestUrl.searchParams.keys()) {
345
+ const values = requestUrl.searchParams.getAll(key);
346
+ if (values.length > 0) merged.set(key, values);
347
+ }
348
+ for (const key of request.params.keys()) {
349
+ const values = request.params.getAll(key);
350
+ if (values?.length) merged.set(key, values);
351
+ }
352
+ if (merged.size === 0) return;
353
+ return [...merged.entries()].reduce((params, [key, values]) => {
354
+ params[key] = values.length === 1 ? values[0] : values;
355
+ return params;
356
+ }, {});
357
+ }
164
358
  /**
165
359
  * Interceptor that is server-aware when making HttpClient requests.
166
360
  * Server-side requests use the full URL
@@ -178,20 +372,22 @@ function requestContextInterceptor(req, next) {
178
372
  const nitroGlobal = globalThis;
179
373
  const serverFetch = injectInternalServerFetch() ?? nitroGlobal.$fetch;
180
374
  if (serverFetch && baseUrl && (req.url.startsWith("/") || req.url.startsWith(baseUrl) || req.url.startsWith(`/${apiPrefix}`))) {
181
- const requestUrl = new URL(req.url, baseUrl);
182
- const storeKey = makeStateKey(`analog_${makeCacheKey(req, new URL(requestUrl).pathname)}`);
375
+ const requestUrl = new URL(req.urlWithParams, baseUrl);
376
+ const storeKey = makeStateKey(`analog_${makeCacheKey(req, `${requestUrl.pathname}${requestUrl.search}`)}`);
183
377
  const fetchUrl = requestUrl.pathname;
378
+ const fetchParams = mergeFetchParams(requestUrl, req);
184
379
  const responseType = req.responseType === "arraybuffer" ? "arrayBuffer" : req.responseType;
185
380
  return from(serverFetch.raw(fetchUrl, {
186
381
  method: req.method,
187
382
  body: req.body ? req.body : void 0,
188
- params: requestUrl.searchParams,
383
+ params: fetchParams,
189
384
  responseType,
190
385
  headers: req.headers.keys().reduce((hdrs, current) => {
191
- return {
386
+ const value = req.headers.get(current);
387
+ return value != null ? {
192
388
  ...hdrs,
193
- [current]: req.headers.get(current)
194
- };
389
+ [current]: value
390
+ } : hdrs;
195
391
  }, {})
196
392
  }).then((res) => {
197
393
  const cacheResponse = {
@@ -207,8 +403,10 @@ function requestContextInterceptor(req, next) {
207
403
  }));
208
404
  }
209
405
  if (req.url.startsWith("/") || req.url.includes("/_analog/")) {
210
- const requestUrl = req.url.includes("/_analog/") ? req.url : `${window.location.origin}${req.url}`;
211
- const storeKey = makeStateKey(`analog_${makeCacheKey(req, new URL(requestUrl).pathname)}`);
406
+ const toAbsoluteUrl = (url) => new URL(url, window.location.origin);
407
+ const requestUrl = toAbsoluteUrl(req.url).href;
408
+ const { pathname, search } = toAbsoluteUrl(req.urlWithParams);
409
+ const storeKey = makeStateKey(`analog_${makeCacheKey(req, `${pathname}${search}`)}`);
212
410
  const cacheRestoreResponse = transferState.get(storeKey, null);
213
411
  if (cacheRestoreResponse) {
214
412
  transferState.remove(storeKey);
@@ -232,62 +430,83 @@ var FormAction = class FormAction {
232
430
  this.state = output();
233
431
  this.router = inject(Router);
234
432
  this.route = inject(ActivatedRoute);
235
- this.path = this._getPath();
433
+ this.currentState = signal("idle", ...[]);
434
+ /** Cached during construction (injection context) so inject() works. */
435
+ this._endpointUrl = this.route ? injectRouteEndpointURL(this.route.snapshot) : void 0;
236
436
  }
237
437
  submitted($event) {
238
438
  $event.preventDefault();
239
- this.state.emit("submitting");
240
- const body = new FormData($event.target);
241
- if ($event.target.method.toUpperCase() === "GET") this._handleGet(body, this.router.url);
242
- else this._handlePost(body, this.path, $event);
439
+ const form = $event.target;
440
+ this._emitState("submitting");
441
+ const body = new FormData(form);
442
+ if (form.method.toUpperCase() === "GET") this._handleGet(body, this._getGetPath(form));
443
+ else this._handlePost(body, this._getPostPath(form), form.method);
243
444
  }
244
445
  _handleGet(body, path) {
245
- const params = {};
246
- body.forEach((formVal, formKey) => params[formKey] = formVal);
247
- this.state.emit("navigate");
248
- const url = path.split("?")[0];
249
- this.router.navigate([url], {
250
- queryParams: params,
251
- onSameUrlNavigation: "reload"
446
+ const url = new URL(path, window.location.href);
447
+ const params = new URLSearchParams(url.search);
448
+ body.forEach((value, key) => {
449
+ params.append(key, value instanceof File ? value.name : value);
252
450
  });
451
+ url.search = params.toString();
452
+ this._emitState("navigate");
453
+ this._navigateTo(url);
253
454
  }
254
- _handlePost(body, path, $event) {
455
+ _handlePost(body, path, method) {
255
456
  fetch(path, {
256
- method: $event.target.method,
457
+ method,
257
458
  body
258
459
  }).then((res) => {
259
460
  if (res.ok) if (res.redirected) {
260
- const redirectUrl = new URL(res.url).pathname;
261
- this.state.emit("redirect");
262
- this.router.navigate([redirectUrl]);
461
+ this._emitState("redirect");
462
+ this._navigateTo(new URL(res.url, window.location.href));
263
463
  } else if (this._isJSON(res.headers.get("Content-type"))) res.json().then((result) => {
264
464
  this.onSuccess.emit(result);
265
- this.state.emit("success");
465
+ this._emitState("success");
266
466
  });
267
467
  else res.text().then((result) => {
268
468
  this.onSuccess.emit(result);
269
- this.state.emit("success");
469
+ this._emitState("success");
270
470
  });
271
471
  else if (res.headers.get("X-Analog-Errors")) res.json().then((errors) => {
272
472
  this.onError.emit(errors);
273
- this.state.emit("error");
473
+ this._emitState("error");
274
474
  });
275
- else this.state.emit("error");
475
+ else this._emitState("error");
276
476
  }).catch((_) => {
277
- this.state.emit("error");
477
+ this._emitState("error");
278
478
  });
279
479
  }
280
- _getPath() {
281
- if (this.route) return injectRouteEndpointURL(this.route.snapshot).pathname;
480
+ _getExplicitAction(form) {
481
+ return this.action().trim() || form.getAttribute("action")?.trim() || void 0;
482
+ }
483
+ _getGetPath(form) {
484
+ return this._getExplicitAction(form) ?? this.router.url;
485
+ }
486
+ _getPostPath(form) {
487
+ const explicitAction = this._getExplicitAction(form);
488
+ if (explicitAction) return new URL(explicitAction, window.location.href).toString();
489
+ if (this._endpointUrl) return this._endpointUrl.pathname;
282
490
  return `/api/_analog/pages${window.location.pathname}`;
283
491
  }
492
+ _emitState(state) {
493
+ this.currentState.set(state);
494
+ this.state.emit(state);
495
+ }
496
+ _navigateTo(url) {
497
+ if (url.origin === window.location.origin) {
498
+ this.router.navigateByUrl(`${url.pathname}${url.search}${url.hash}`, { onSameUrlNavigation: "reload" });
499
+ return;
500
+ }
501
+ window.location.assign(url.toString());
502
+ }
284
503
  _isJSON(contentType) {
285
504
  return (contentType ? contentType.split(";") : [])[0] === "application/json";
286
505
  }
287
506
  static {
288
507
  this.ɵfac = i0.ɵɵngDeclareFactory({
289
508
  minVersion: "12.0.0",
290
- version: "21.1.1",
509
+ version: "22.1.5",
291
510
  ngImport: i0,
292
511
  type: FormAction,
293
512
  deps: [],
@@ -297,7 +516,7 @@ var FormAction = class FormAction {
297
516
  static {
298
517
  this.ɵdir = i0.ɵɵngDeclareDirective({
299
518
  minVersion: "17.1.0",
300
- version: "21.1.1",
519
+ version: "22.1.5",
301
520
  type: FormAction,
302
521
  isStandalone: true,
303
522
  selector: "form[action],form[method]",
@@ -313,21 +532,31 @@ var FormAction = class FormAction {
313
532
  onError: "onError",
314
533
  state: "state"
315
534
  },
316
- host: { listeners: { "submit": "submitted($event)" } },
535
+ host: {
536
+ listeners: { "submit": "submitted($event)" },
537
+ properties: {
538
+ "attr.data-state": "currentState()",
539
+ "attr.aria-busy": "currentState() === \"submitting\" ? \"true\" : null"
540
+ }
541
+ },
317
542
  ngImport: i0
318
543
  });
319
544
  }
320
545
  };
321
546
  i0.ɵɵngDeclareClassMetadata({
322
547
  minVersion: "12.0.0",
323
- version: "21.1.1",
548
+ version: "22.1.5",
324
549
  ngImport: i0,
325
550
  type: FormAction,
326
551
  decorators: [{
327
552
  type: Directive,
328
553
  args: [{
329
554
  selector: "form[action],form[method]",
330
- host: { "(submit)": `submitted($event)` },
555
+ host: {
556
+ "(submit)": `submitted($event)`,
557
+ "[attr.data-state]": "currentState()",
558
+ "[attr.aria-busy]": "currentState() === \"submitting\" ? \"true\" : null"
559
+ },
331
560
  standalone: true
332
561
  }]
333
562
  }],
@@ -375,141 +604,560 @@ function withDebugRoutes() {
375
604
  };
376
605
  }
377
606
  //#endregion
378
- //#region packages/router/src/lib/server.component.ts
607
+ //#region packages/router/src/lib/validation-errors.ts
608
+ function getPathSegmentKey(segment) {
609
+ return typeof segment === "object" ? segment.key : segment;
610
+ }
611
+ function issuePathToFieldName(path) {
612
+ return path.map((segment) => String(getPathSegmentKey(segment))).join(".");
613
+ }
614
+ function issuesToFieldErrors(issues) {
615
+ return issues.reduce((errors, issue) => {
616
+ if (!issue.path?.length) return errors;
617
+ const fieldName = issuePathToFieldName(issue.path);
618
+ errors[fieldName] ??= [];
619
+ errors[fieldName].push(issue.message);
620
+ return errors;
621
+ }, {});
622
+ }
623
+ function issuesToFormErrors(issues) {
624
+ return issues.filter((issue) => !issue.path?.length).map((issue) => issue.message);
625
+ }
626
+ //#endregion
627
+ //#region packages/router/src/lib/server-fn/dispatcher.ts
628
+ var SERVER_FN_DISPATCHER = new InjectionToken("@analogjs/router Server Function Dispatcher");
629
+ //#endregion
630
+ //#region packages/router/src/lib/server-fn/inject-server-fn.ts
379
631
  /**
380
- * @description
381
- * Component that defines the bridge between the client and server-only
382
- * components. The component passes the component ID and props to the server
383
- * and retrieves the rendered HTML and outputs from the server-only component.
384
- *
385
- * Status: experimental
632
+ * Client transport for server functions. In the browser it goes through Angular
633
+ * `HttpClient`, so client `HttpInterceptorFn`s apply. During SSR the dispatcher
634
+ * token is provided, and the call short-circuits the HTTP round-trip: the
635
+ * handler runs in-process in the current request injector. Lives in the client
636
+ * entry (client-safe).
386
637
  */
387
- var ServerOnly = class ServerOnly {
638
+ var ServerFnClient = class ServerFnClient {
388
639
  constructor() {
389
- this.component = input.required(...[]);
390
- this.props = input(...[]);
391
- this.outputs = output();
392
640
  this.http = inject(HttpClient);
393
- this.sanitizer = inject(DomSanitizer);
394
- this.content = signal("", ...[]);
395
- this.route = inject(ActivatedRoute, { optional: true });
396
- this.baseURL = injectBaseURL();
397
641
  this.transferState = inject(TransferState);
398
- effect(() => {
399
- const routeComponentId = this.route?.snapshot.data["component"];
400
- const props = this.props() || {};
401
- const componentId = routeComponentId || this.component();
402
- const headers = new HttpHeaders(new Headers({
403
- "Content-type": "application/json",
404
- "X-Analog-Component": componentId
405
- }));
406
- const componentUrl = this.getComponentUrl(componentId);
407
- const httpRequest = new HttpRequest("POST", componentUrl, props, { headers });
408
- const storeKey = makeStateKey(makeCacheKey(httpRequest, new URL(componentUrl).pathname));
409
- const componentState = this.transferState.get(storeKey, null);
410
- if (componentState) {
411
- this.updateContent(componentState);
412
- this.transferState.remove(storeKey);
413
- } else this.http.request(httpRequest).pipe(map((response) => {
414
- if (response instanceof HttpResponse) return response.body;
415
- return throwError(() => ({}));
416
- }), catchError((error) => {
417
- console.log(error);
418
- return of({
419
- html: "",
420
- outputs: {}
421
- });
422
- })).subscribe((content) => this.updateContent(content));
423
- });
642
+ this.injector = inject(Injector);
643
+ this.dispatcher = inject(SERVER_FN_DISPATCHER, { optional: true });
644
+ }
645
+ /** True while rendering on the server (the in-process dispatcher is provided). */
646
+ get isServer() {
647
+ return !!this.dispatcher;
648
+ }
649
+ async call(fn, input) {
650
+ if (this.dispatcher) return this.dispatcher(fn, input, this.injector);
651
+ return firstValueFrom(fn.method === "GET" ? this.http.get(fn.url) : this.http.post(fn.url, input ?? {}));
652
+ }
653
+ /** Key a read's value for TransferState hydration (fn id + input). */
654
+ stateKey(fn, input) {
655
+ return makeStateKey(`__analog_fn_${fn.id}_${stableInput(input)}`);
424
656
  }
425
- updateContent(content) {
426
- this.content.set(this.sanitizer.bypassSecurityTrustHtml(content.html));
427
- this.outputs.emit(content.outputs);
657
+ readSeed(fn, input) {
658
+ const key = this.stateKey(fn, input);
659
+ if (this.transferState.hasKey(key)) {
660
+ const value = this.transferState.get(key, void 0);
661
+ this.transferState.remove(key);
662
+ return value;
663
+ }
428
664
  }
429
- getComponentUrl(componentId) {
430
- let baseURL = this.baseURL;
431
- if (!baseURL && typeof window !== "undefined") baseURL = window.location.origin;
432
- return `${baseURL}/_analog/components/${componentId}`;
665
+ writeSeed(fn, input, value) {
666
+ this.transferState.set(this.stateKey(fn, input), value);
433
667
  }
434
668
  static {
435
669
  this.ɵfac = i0.ɵɵngDeclareFactory({
436
670
  minVersion: "12.0.0",
437
- version: "21.1.1",
671
+ version: "22.1.5",
438
672
  ngImport: i0,
439
- type: ServerOnly,
673
+ type: ServerFnClient,
440
674
  deps: [],
441
- target: i0.ɵɵFactoryTarget.Component
675
+ target: i0.ɵɵFactoryTarget.Injectable
442
676
  });
443
677
  }
444
678
  static {
445
- this.ɵcmp = i0.ɵɵngDeclareComponent({
446
- minVersion: "17.1.0",
447
- version: "21.1.1",
448
- type: ServerOnly,
449
- isStandalone: true,
450
- selector: "server-only,ServerOnly,Server",
451
- inputs: {
452
- component: {
453
- classPropertyName: "component",
454
- publicName: "component",
455
- isSignal: true,
456
- isRequired: true,
457
- transformFunction: null
458
- },
459
- props: {
460
- classPropertyName: "props",
461
- publicName: "props",
462
- isSignal: true,
463
- isRequired: false,
464
- transformFunction: null
465
- }
466
- },
467
- outputs: { outputs: "outputs" },
679
+ this.ɵprov = i0.ɵɵngDeclareInjectable({
680
+ minVersion: "12.0.0",
681
+ version: "22.1.5",
468
682
  ngImport: i0,
469
- template: ` <div [innerHTML]="content()"></div> `,
470
- isInline: true,
471
- changeDetection: i0.ChangeDetectionStrategy.OnPush
683
+ type: ServerFnClient,
684
+ providedIn: "root"
472
685
  });
473
686
  }
474
687
  };
475
688
  i0.ɵɵngDeclareClassMetadata({
476
689
  minVersion: "12.0.0",
477
- version: "21.1.1",
690
+ version: "22.1.5",
478
691
  ngImport: i0,
479
- type: ServerOnly,
692
+ type: ServerFnClient,
480
693
  decorators: [{
481
- type: Component,
482
- args: [{
483
- selector: "server-only,ServerOnly,Server",
484
- changeDetection: ChangeDetectionStrategy.OnPush,
485
- template: ` <div [innerHTML]="content()"></div> `
694
+ type: Injectable,
695
+ args: [{ providedIn: "root" }]
696
+ }]
697
+ });
698
+ /** No-op provider hook; ServerFnClient is `providedIn: 'root'`. */
699
+ function provideServerFnClient() {
700
+ return [];
701
+ }
702
+ var NO_INPUT = Symbol("analog.serverFn.noInput");
703
+ function injectServerFn(fn, args) {
704
+ assertInInjectionContext(injectServerFn);
705
+ const client = inject(ServerFnClient);
706
+ return resource({
707
+ params: () => args ? args() : NO_INPUT,
708
+ loader: async ({ params }) => {
709
+ const input = params === NO_INPUT ? void 0 : params;
710
+ const seeded = client.readSeed(fn, input);
711
+ if (seeded !== void 0) return seeded;
712
+ const value = await client.call(fn, input);
713
+ if (client.isServer) client.writeSeed(fn, input, value);
714
+ return value;
715
+ }
716
+ });
717
+ }
718
+ /**
719
+ * Imperative binding of a server function: returns a callable that dispatches
720
+ * the call through `HttpClient` (so client interceptors apply) and resolves the
721
+ * result. Use for mutations and event-driven calls; use `injectServerFn` for
722
+ * reactive reads.
723
+ */
724
+ function injectServerFnMutation(fn) {
725
+ assertInInjectionContext(injectServerFnMutation);
726
+ const client = inject(ServerFnClient);
727
+ return (input) => client.call(fn, input);
728
+ }
729
+ function stableInput(input) {
730
+ if (input === void 0 || input === null) return "_";
731
+ return JSON.stringify(input);
732
+ }
733
+ //#endregion
734
+ //#region packages/router/src/lib/server-fn/server-fn-ref.ts
735
+ /**
736
+ * Builds a server-function reference: the client-safe `{ __serverFn, id, url,
737
+ * method }` metadata that `injectServerFn`/`ServerFnClient` dispatch through.
738
+ *
739
+ * Shared by both sides so they produce identical refs: the server `serverFn`
740
+ * wraps this with registration + the handler, and the client build's scrub
741
+ * transform emits a call to this factory in place of the server module so the
742
+ * browser bundle carries only the ref, never the handler or its server imports.
743
+ *
744
+ * The returned value is callable-typed but throws if invoked directly — it is
745
+ * always dispatched via `injectServerFn`/`ServerFnClient`, never called.
746
+ */
747
+ function createServerFnRef(config) {
748
+ if (!config.id) throw new Error("[analog] serverFn is missing its build-derived id. Server functions require the Analog build transform (@analogjs/platform / @analogjs/vite-plugin-nitro); a raw import without it is not supported.");
749
+ const method = config.method ?? (config.input ? "POST" : "GET");
750
+ const url = `/_analog/fn/${config.id}`;
751
+ const ref = (() => {
752
+ throw new Error(`serverFn "${config.id}" must be called via injectServerFn/ServerFnClient`);
753
+ });
754
+ return Object.assign(ref, {
755
+ __serverFn: true,
756
+ id: config.id,
757
+ url,
758
+ method
759
+ });
760
+ }
761
+ //#endregion
762
+ //#region packages/router/src/lib/route-path.ts
763
+ /**
764
+ * Typed route path utilities for Analog.
765
+ *
766
+ * This module provides:
767
+ * - The `AnalogRouteTable` base interface (augmented by generated code)
768
+ * - The `AnalogRoutePath` union type
769
+ * - The `routePath()` URL builder function
770
+ *
771
+ * No Angular dependencies — can be used in any context.
772
+ */
773
+ /**
774
+ * Builds a typed route link object from a route path pattern and options.
775
+ *
776
+ * The returned object separates path, query params, and fragment for
777
+ * direct use with Angular's routerLink directive inputs.
778
+ *
779
+ * @example
780
+ * routePath('/about')
781
+ * // → { path: '/about', queryParams: null, fragment: undefined }
782
+ *
783
+ * routePath('/users/[id]', { params: { id: '42' } })
784
+ * // → { path: '/users/42', queryParams: null, fragment: undefined }
785
+ *
786
+ * routePath('/users/[id]', { params: { id: '42' }, query: { tab: 'settings' }, hash: 'bio' })
787
+ * // → { path: '/users/42', queryParams: { tab: 'settings' }, fragment: 'bio' }
788
+ *
789
+ * @example Template usage
790
+ * ```html
791
+ * @let link = routePath('/users/[id]', { params: { id: userId } });
792
+ * <a [routerLink]="link.path" [queryParams]="link.queryParams" [fragment]="link.fragment">
793
+ * ```
794
+ */
795
+ function routePath(path, ...args) {
796
+ const options = args[0];
797
+ return buildRouteLink(path, options);
798
+ }
799
+ /**
800
+ * Internal: builds a `RouteLinkResult` from path and options.
801
+ * Exported for direct use in tests (avoids generic constraints).
802
+ */
803
+ function buildRouteLink(path, options) {
804
+ const resolvedPath = buildPath(path, options?.params);
805
+ let queryParams = null;
806
+ if (options?.query) {
807
+ const filtered = {};
808
+ let hasEntries = false;
809
+ for (const [key, value] of Object.entries(options.query)) if (value !== void 0) {
810
+ filtered[key] = value;
811
+ hasEntries = true;
812
+ }
813
+ if (hasEntries) queryParams = filtered;
814
+ }
815
+ return {
816
+ path: resolvedPath,
817
+ queryParams,
818
+ fragment: options?.hash
819
+ };
820
+ }
821
+ /**
822
+ * Resolves param placeholders and normalises slashes.
823
+ * Returns only the path — no query string or hash.
824
+ */
825
+ function buildPath(path, params) {
826
+ let url = path;
827
+ if (params) {
828
+ url = url.replace(/\[\[\.\.\.([^\]]+)\]\]/g, (_, name) => {
829
+ const value = params[name];
830
+ if (value == null) return "";
831
+ if (Array.isArray(value)) return value.map((v) => encodeURIComponent(v)).join("/");
832
+ return encodeURIComponent(String(value));
833
+ });
834
+ url = url.replace(/\[\.\.\.([^\]]+)\]/g, (_, name) => {
835
+ const value = params[name];
836
+ if (value == null) throw new Error(`Missing required catch-all param "${name}" for path "${path}"`);
837
+ if (Array.isArray(value)) {
838
+ if (value.length === 0) throw new Error(`Missing required catch-all param "${name}" for path "${path}"`);
839
+ return value.map((v) => encodeURIComponent(v)).join("/");
840
+ }
841
+ return encodeURIComponent(String(value));
842
+ });
843
+ url = url.replace(/\[([^\]]+)\]/g, (_, name) => {
844
+ const value = params[name];
845
+ if (value == null) throw new Error(`Missing required param "${name}" for path "${path}"`);
846
+ return encodeURIComponent(String(value));
847
+ });
848
+ } else {
849
+ url = url.replace(/\[\[\.\.\.([^\]]+)\]\]/g, "");
850
+ url = url.replace(/\[\.\.\.([^\]]+)\]/g, "");
851
+ url = url.replace(/\[([^\]]+)\]/g, "");
852
+ }
853
+ url = url.replace(/\/+/g, "/");
854
+ if (url.length > 1 && url.endsWith("/")) url = url.slice(0, -1);
855
+ if (!url.startsWith("/")) url = "/" + url;
856
+ return url;
857
+ }
858
+ /**
859
+ * Internal URL builder. Separated from `routePath` so it can be
860
+ * used without generic constraints (e.g., in `injectNavigate`).
861
+ */
862
+ function buildUrl(path, options) {
863
+ let url = buildPath(path, options?.params);
864
+ if (options?.query) {
865
+ const parts = [];
866
+ for (const [key, value] of Object.entries(options.query)) {
867
+ if (value === void 0) continue;
868
+ if (Array.isArray(value)) for (const v of value) parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(v)}`);
869
+ else parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
870
+ }
871
+ if (parts.length > 0) url += "?" + parts.join("&");
872
+ }
873
+ if (options?.hash) url += "#" + options.hash;
874
+ return url;
875
+ }
876
+ //#endregion
877
+ //#region packages/router/src/lib/inject-navigate.ts
878
+ function isRoutePathOptionsBase(value) {
879
+ return !!value && typeof value === "object" && ("params" in value || "query" in value || "hash" in value);
880
+ }
881
+ /**
882
+ * Injects a typed navigate function.
883
+ *
884
+ * @example
885
+ * ```ts
886
+ * const navigate = injectNavigate();
887
+ *
888
+ * navigate('/users/[id]', { params: { id: '42' } }); // ✅
889
+ * navigate('/users/[id]', { params: { id: 42 } }); // ❌ type error
890
+ *
891
+ * // With navigation extras
892
+ * navigate('/users/[id]', { params: { id: '42' } }, { replaceUrl: true });
893
+ * ```
894
+ */
895
+ function injectNavigate() {
896
+ const router = inject(Router);
897
+ const navigate = ((path, ...args) => {
898
+ let options;
899
+ let extras;
900
+ if (args.length > 1) {
901
+ options = args[0];
902
+ extras = args[1];
903
+ } else if (args.length === 1) if (isRoutePathOptionsBase(args[0])) options = args[0];
904
+ else extras = args[0];
905
+ const url = buildUrl(path, options);
906
+ return router.navigateByUrl(url, extras);
907
+ });
908
+ return navigate;
909
+ }
910
+ //#endregion
911
+ //#region packages/router/src/lib/experimental.ts
912
+ /** @experimental */
913
+ var EXPERIMENTAL_TYPED_ROUTER = new InjectionToken("EXPERIMENTAL_TYPED_ROUTER");
914
+ /** @experimental */
915
+ var EXPERIMENTAL_ROUTE_CONTEXT = new InjectionToken("EXPERIMENTAL_ROUTE_CONTEXT");
916
+ /** @experimental */
917
+ var EXPERIMENTAL_LOADER_CACHE = new InjectionToken("EXPERIMENTAL_LOADER_CACHE");
918
+ /**
919
+ * Enables experimental typed router features.
920
+ *
921
+ * When active, `routePath()`, `injectNavigate()`, `injectParams()`,
922
+ * and `injectQuery()` will enforce route table constraints and
923
+ * optionally log warnings in strict mode.
924
+ *
925
+ * Inspired by TanStack Router's `Register` interface and strict type
926
+ * checking across the entire navigation surface.
927
+ *
928
+ * @example
929
+ * ```ts
930
+ * provideFileRouter(
931
+ * withTypedRouter({ strictRouteParams: true }),
932
+ * )
933
+ * ```
934
+ *
935
+ * @experimental
936
+ */
937
+ function withTypedRouter(options) {
938
+ return {
939
+ ɵkind: 102,
940
+ ɵproviders: [{
941
+ provide: EXPERIMENTAL_TYPED_ROUTER,
942
+ useValue: {
943
+ strictRouteParams: false,
944
+ ...options
945
+ }
486
946
  }]
487
- }],
488
- ctorParameters: () => [],
489
- propDecorators: {
490
- component: [{
491
- type: i0.Input,
492
- args: [{
493
- isSignal: true,
494
- alias: "component",
495
- required: true
496
- }]
497
- }],
498
- props: [{
499
- type: i0.Input,
500
- args: [{
501
- isSignal: true,
502
- alias: "props",
503
- required: false
504
- }]
505
- }],
506
- outputs: [{
507
- type: i0.Output,
508
- args: ["outputs"]
947
+ };
948
+ }
949
+ /**
950
+ * Provides root-level route context available to all route loaders
951
+ * and components via `injectRouteContext()`.
952
+ *
953
+ * Inspired by TanStack Router's `createRootRouteWithContext<T>()` where
954
+ * a typed context object is required at router creation and automatically
955
+ * available in every route's `beforeLoad` and `loader`.
956
+ *
957
+ * In Angular terms, this creates a DI token that server-side load
958
+ * functions and components can inject to access shared services
959
+ * without importing them individually.
960
+ *
961
+ * @example
962
+ * ```ts
963
+ * // app.config.ts
964
+ * provideFileRouter(
965
+ * withRouteContext({
966
+ * auth: inject(AuthService),
967
+ * db: inject(DatabaseService),
968
+ * }),
969
+ * )
970
+ *
971
+ * // In a component
972
+ * const ctx = injectRouteContext<{ auth: AuthService; db: DatabaseService }>();
973
+ * ```
974
+ *
975
+ * @experimental
976
+ */
977
+ function withRouteContext(context) {
978
+ return {
979
+ ɵkind: 103,
980
+ ɵproviders: [{
981
+ provide: EXPERIMENTAL_ROUTE_CONTEXT,
982
+ useValue: context
983
+ }]
984
+ };
985
+ }
986
+ /**
987
+ * Configures experimental loader caching behavior for server-loaded
988
+ * route data.
989
+ *
990
+ * Inspired by TanStack Router's built-in cache where `createRouter()`
991
+ * accepts `defaultStaleTime` and `defaultGcTime` to control when
992
+ * loaders re-execute and when cached data is discarded.
993
+ *
994
+ * @example
995
+ * ```ts
996
+ * provideFileRouter(
997
+ * withLoaderCaching({
998
+ * defaultStaleTime: 30_000, // 30s before re-fetch
999
+ * defaultGcTime: 300_000, // 5min cache retention
1000
+ * defaultPendingMs: 200, // 200ms loading delay
1001
+ * }),
1002
+ * )
1003
+ * ```
1004
+ *
1005
+ * @experimental
1006
+ */
1007
+ function withLoaderCaching(options) {
1008
+ return {
1009
+ ɵkind: 104,
1010
+ ɵproviders: [{
1011
+ provide: EXPERIMENTAL_LOADER_CACHE,
1012
+ useValue: {
1013
+ defaultStaleTime: 0,
1014
+ defaultGcTime: 3e5,
1015
+ defaultPendingMs: 0,
1016
+ ...options
1017
+ }
509
1018
  }]
1019
+ };
1020
+ }
1021
+ //#endregion
1022
+ //#region packages/router/src/lib/inject-typed-params.ts
1023
+ function extractRouteParams(routePath) {
1024
+ const params = [];
1025
+ for (const match of routePath.matchAll(/\[\[\.\.\.([^\]]+)\]\]/g)) params.push({
1026
+ name: match[1],
1027
+ type: "optionalCatchAll"
1028
+ });
1029
+ for (const match of routePath.matchAll(/(?<!\[)\[\.\.\.([^\]]+)\](?!\])/g)) params.push({
1030
+ name: match[1],
1031
+ type: "catchAll"
1032
+ });
1033
+ for (const match of routePath.matchAll(/(?<!\[)\[(?!\.)([^\]]+)\](?!\])/g)) params.push({
1034
+ name: match[1],
1035
+ type: "dynamic"
1036
+ });
1037
+ return params;
1038
+ }
1039
+ /**
1040
+ * When `strictRouteParams` is enabled, warns if expected params from the
1041
+ * `_from` pattern are missing from the active `ActivatedRoute`.
1042
+ */
1043
+ function assertRouteMatch(from, route, kind) {
1044
+ const expectedParams = extractRouteParams(from).filter((param) => param.type === "dynamic" || param.type === "catchAll").map((param) => param.name);
1045
+ if (expectedParams.length === 0) return;
1046
+ route.params.pipe(take(1)).subscribe((params) => {
1047
+ for (const name of expectedParams) if (!(name in params)) {
1048
+ console.warn(`[Analog] ${kind}('${from}'): expected param "${name}" is not present in the active route's params. Ensure this hook is used inside a component rendered by '${from}'.`);
1049
+ break;
1050
+ }
1051
+ });
1052
+ }
1053
+ /**
1054
+ * Injects typed route params as a signal, constrained by the route table.
1055
+ *
1056
+ * Inspired by TanStack Router's `useParams({ from: '/users/$userId' })`
1057
+ * pattern where the `from` parameter narrows the return type to only
1058
+ * the params defined for that route.
1059
+ *
1060
+ * The `from` parameter is used purely for TypeScript type inference —
1061
+ * at runtime, params are read from the current `ActivatedRoute`. This
1062
+ * means it works correctly when used inside a component rendered by
1063
+ * the specified route.
1064
+ *
1065
+ * When `withTypedRouter({ strictRouteParams: true })` is configured,
1066
+ * a dev-mode assertion checks that the expected params from `from`
1067
+ * exist in the active route and warns on mismatch.
1068
+ *
1069
+ * @example
1070
+ * ```ts
1071
+ * // In a component rendered at /users/[id]
1072
+ * const params = injectParams('/users/[id]');
1073
+ * // params() → { id: string }
1074
+ *
1075
+ * // With schema validation output types
1076
+ * const params = injectParams('/products/[slug]');
1077
+ * // params() → validated output type from routeParamsSchema
1078
+ * ```
1079
+ *
1080
+ * @experimental
1081
+ */
1082
+ function injectParams(_from, options) {
1083
+ const injector = options?.injector;
1084
+ const route = injector ? injector.get(ActivatedRoute) : inject(ActivatedRoute);
1085
+ if (isDevMode()) {
1086
+ if ((injector ? injector.get(EXPERIMENTAL_TYPED_ROUTER, null) : inject(EXPERIMENTAL_TYPED_ROUTER, { optional: true }))?.strictRouteParams) assertRouteMatch(_from, route, "injectParams");
510
1087
  }
511
- });
1088
+ return toSignal(route.params.pipe(map((params) => params)), { requireSync: true });
1089
+ }
1090
+ /**
1091
+ * Injects typed route query params as a signal, constrained by the
1092
+ * route table.
1093
+ *
1094
+ * Inspired by TanStack Router's `useSearch({ from: '/issues' })` pattern
1095
+ * where search params are validated and typed per-route via
1096
+ * `validateSearch` schemas.
1097
+ *
1098
+ * In Analog, the typing comes from `routeQuerySchema` exports that are
1099
+ * detected at build time and recorded in the generated route table.
1100
+ *
1101
+ * The `from` parameter is used purely for TypeScript type inference.
1102
+ * When `withTypedRouter({ strictRouteParams: true })` is configured,
1103
+ * a dev-mode assertion checks that the expected params from `from`
1104
+ * exist in the active route and warns on mismatch.
1105
+ *
1106
+ * @example
1107
+ * ```ts
1108
+ * // In a component rendered at /issues
1109
+ * // (where routeQuerySchema validates { page: number, status: string })
1110
+ * const query = injectQuery('/issues');
1111
+ * // query() → { page: number; status: string }
1112
+ * ```
1113
+ *
1114
+ * @experimental
1115
+ */
1116
+ function injectQuery(_from, options) {
1117
+ const injector = options?.injector;
1118
+ const route = injector ? injector.get(ActivatedRoute) : inject(ActivatedRoute);
1119
+ if (isDevMode()) {
1120
+ if ((injector ? injector.get(EXPERIMENTAL_TYPED_ROUTER, null) : inject(EXPERIMENTAL_TYPED_ROUTER, { optional: true }))?.strictRouteParams) assertRouteMatch(_from, route, "injectQuery");
1121
+ }
1122
+ return toSignal(route.queryParams.pipe(map((params) => params)), { requireSync: true });
1123
+ }
1124
+ //#endregion
1125
+ //#region packages/router/src/lib/inject-route-context.ts
1126
+ /**
1127
+ * Injects the root route context provided via `withRouteContext()`.
1128
+ *
1129
+ * Inspired by TanStack Router's context inheritance where
1130
+ * `createRootRouteWithContext<T>()` makes a typed context available
1131
+ * to every route's `beforeLoad` and `loader` callbacks.
1132
+ *
1133
+ * In Angular, this uses DI under the hood — `withRouteContext(ctx)`
1134
+ * provides the value, and `injectRouteContext<T>()` retrieves it
1135
+ * with the expected type.
1136
+ *
1137
+ * @example
1138
+ * ```ts
1139
+ * // app.config.ts
1140
+ * provideFileRouter(
1141
+ * withRouteContext({
1142
+ * auth: inject(AuthService),
1143
+ * analytics: inject(AnalyticsService),
1144
+ * }),
1145
+ * )
1146
+ *
1147
+ * // any-page.page.ts
1148
+ * const ctx = injectRouteContext<{
1149
+ * auth: AuthService;
1150
+ * analytics: AnalyticsService;
1151
+ * }>();
1152
+ * ctx.analytics.trackPageView();
1153
+ * ```
1154
+ *
1155
+ * @experimental
1156
+ */
1157
+ function injectRouteContext() {
1158
+ return inject(EXPERIMENTAL_ROUTE_CONTEXT);
1159
+ }
512
1160
  //#endregion
513
- export { FormAction, ServerOnly, createRoutes, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectRouteEndpointURL, injectRouter, provideFileRouter, requestContextInterceptor, routes, withDebugRoutes, withExtraRoutes };
1161
+ export { EXPERIMENTAL_LOADER_CACHE, EXPERIMENTAL_ROUTE_CONTEXT, EXPERIMENTAL_TYPED_ROUTER, FormAction, SERVER_FN_DISPATCHER, ServerFnClient, createRoutes, createServerFnRef, defineRouteMeta, getLoadResolver, injectActivatedRoute, injectDebugRoutes, injectLoad, injectLoadData, injectNavigate, injectParams, injectQuery, injectRouteContext, injectRouteEndpointURL, injectRouter, injectServerFn, injectServerFnMutation, issuePathToFieldName, issuesToFieldErrors, issuesToFormErrors, provideFileRouter, provideServerFnClient, requestContextInterceptor, routePath, routes, withDebugRoutes, withExtraRoutes, withLoaderCaching, withRouteContext, withTypedRouter };
514
1162
 
515
1163
  //# sourceMappingURL=analogjs-router.mjs.map