@analogjs/router 2.8.0-beta.8 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -1,541 +1,358 @@
1
- import { InjectionToken, Injector, runInInjectionContext, ɵresetCompiledComponents as _resetCompiledComponents, enableProdMode } from '@angular/core';
2
- import { ɵSERVER_CONTEXT as _SERVER_CONTEXT, renderApplication, platformServer, INITIAL_CONFIG, ɵrenderInternal as _renderInternal, provideServerRendering } from '@angular/platform-server';
3
- import { REQUEST, RESPONSE, BASE_URL, LOCALE } from '@analogjs/router/tokens';
4
- import { SERVER_FN_DISPATCHER, createServerFnRef } from '@analogjs/router';
5
- import { HttpErrorResponse } from '@angular/common/http';
6
- import { bootstrapApplication, createApplication } from '@angular/platform-browser';
7
- import { AsyncLocalStorage } from 'node:async_hooks';
8
- import { eventHandler, getRouterParam, readBody } from 'h3';
9
-
10
- /**
11
- * Server-side registry of server functions, keyed by id. A `.server.ts` module
12
- * populates it as a side effect of `serverFn(...)` running at import time; the
13
- * Nitro dispatch route imports those modules to fill it, then looks up by id.
14
- */
15
- const serverFnRegistry = new Map();
16
-
17
- const SERVER_FN_INTERCEPTORS = new InjectionToken('SERVER_FN_INTERCEPTORS');
18
- /** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */
1
+ import { DestroyRef, ENVIRONMENT_INITIALIZER, InjectionToken, Injector, enableProdMode, inject, makeEnvironmentProviders, runInInjectionContext, ɵresetCompiledComponents } from "@angular/core";
2
+ import { INITIAL_CONFIG, PlatformState, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
3
+ import { BASE_URL, LOCALE, REQUEST, RESPONSE } from "@analogjs/router/tokens";
4
+ import { SERVER_FN_DISPATCHER, createServerFnRef } from "@analogjs/router";
5
+ import { HttpErrorResponse } from "@angular/common/http";
6
+ import { bootstrapApplication, createApplication } from "@angular/platform-browser";
7
+ import { AsyncLocalStorage } from "node:async_hooks";
8
+ import { NavigationEnd, NavigationError, Router } from "@angular/router";
9
+ import { eventHandler, getRouterParam, readBody } from "h3";
10
+ const serverFnRegistry = /* @__PURE__ */ new Map();
11
+ const SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
19
12
  function withServerFnInterceptors(interceptors) {
20
- return {
21
- providers: interceptors.map((fn) => ({
22
- provide: SERVER_FN_INTERCEPTORS,
23
- useValue: fn,
24
- multi: true,
25
- })),
26
- };
27
- }
28
- /** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */
13
+ return { providers: interceptors.map((fn) => ({
14
+ provide: SERVER_FN_INTERCEPTORS,
15
+ useValue: fn,
16
+ multi: true
17
+ })) };
18
+ }
29
19
  function provideServerFns(...features) {
30
- return features.flatMap((f) => f.providers);
20
+ return features.flatMap((f) => f.providers);
31
21
  }
32
22
  function makeCtx(input, context) {
33
- return {
34
- input,
35
- context,
36
- with(patch) {
37
- return makeCtx(input, { ...context, ...patch });
38
- },
39
- };
40
- }
41
- /**
42
- * Run the interceptor chain, then the handler, threading the context.
43
- *
44
- * `runInCtx` re-establishes the DI injection context around each interceptor
45
- * and the handler individually. This is what keeps `inject()` working in a
46
- * handler even when an upstream interceptor `await`s before calling `next`
47
- * (which would otherwise resume outside Angular's synchronous injection
48
- * context). It defaults to a pass-through for non-DI callers/tests.
49
- */
50
- async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
51
- let i = -1;
52
- const dispatch = async (ctx) => {
53
- i += 1;
54
- if (i < interceptors.length) {
55
- return runInCtx(() => interceptors[i](ctx, dispatch));
56
- }
57
- return runInCtx(() => handler(ctx.input, ctx.context));
58
- };
59
- return dispatch(makeCtx(input, {}));
23
+ return {
24
+ input,
25
+ context,
26
+ with(patch) {
27
+ return makeCtx(input, {
28
+ ...context,
29
+ ...patch
30
+ });
31
+ }
32
+ };
60
33
  }
61
-
62
- /**
63
- * Same-origin enforcement for the server-function HTTP transport.
64
- *
65
- * Server functions are same-origin RPC: a client proxy only ever calls the
66
- * relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be
67
- * able to invoke them against a logged-in user (a CSRF-shaped attack), so the
68
- * transport rejects browser requests whose origin is not the app's own — out of
69
- * the box, with no per-app configuration.
70
- *
71
- * The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and
72
- * cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,
73
- * server-to-server, SSR in-process) send neither, so they are unaffected: the
74
- * guard blocks the cross-origin browser attack it is meant to, and nothing else.
75
- */
76
- /**
77
- * Origins permitted beyond the app's own, registered through DI:
78
- * `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the
79
- * transport is same-origin unless an app opts out explicitly.
80
- */
81
- const SERVER_FN_ALLOWED_ORIGINS = new InjectionToken('SERVER_FN_ALLOWED_ORIGINS');
82
- /**
83
- * `withAllowedOrigins([...])` — permit cross-origin browser calls from the
84
- * listed origins, or pass `'*'` to disable the same-origin guard entirely.
85
- * Server functions are frequently cookie-authenticated, so this is an explicit
86
- * opt-out of CSRF protection: allow-list the exact origins you control.
87
- */
34
+ async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
35
+ let i = -1;
36
+ const dispatch = async (ctx) => {
37
+ i += 1;
38
+ if (i < interceptors.length) return runInCtx(() => interceptors[i](ctx, dispatch));
39
+ return runInCtx(() => handler(ctx.input, ctx.context));
40
+ };
41
+ return dispatch(makeCtx(input, {}));
42
+ }
43
+ const SERVER_FN_ALLOWED_ORIGINS = new InjectionToken("SERVER_FN_ALLOWED_ORIGINS");
88
44
  function withAllowedOrigins(origins) {
89
- return {
90
- providers: origins.map((origin) => ({
91
- provide: SERVER_FN_ALLOWED_ORIGINS,
92
- useValue: origin,
93
- multi: true,
94
- })),
95
- };
45
+ return { providers: origins.map((origin) => ({
46
+ provide: SERVER_FN_ALLOWED_ORIGINS,
47
+ useValue: origin,
48
+ multi: true
49
+ })) };
96
50
  }
97
51
  function firstHeader(value) {
98
- return Array.isArray(value) ? value[0] : value;
99
- }
100
- /**
101
- * Whether an HTTP request to a server function may proceed.
102
- *
103
- * Allowed when the request is same-origin, carries no browser-origin signal at
104
- * all (a non-browser client, or a same-origin GET that omits `Origin`), or its
105
- * `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`
106
- * disables the check — the explicit opt-in to cross-origin access.
107
- *
108
- * `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and
109
- * `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and
110
- * `cross-site` require an explicit `allowedOrigins` entry. When the header is
111
- * absent (older browsers, some proxies) the `Origin` host is compared to the
112
- * request host as a fallback.
113
- */
52
+ return Array.isArray(value) ? value[0] : value;
53
+ }
114
54
  function isServerFnOriginAllowed(headers, allowedOrigins = []) {
115
- if (allowedOrigins.includes('*')) {
116
- return true;
117
- }
118
- const origin = firstHeader(headers['origin']);
119
- const originAllowlisted = origin !== undefined && allowedOrigins.includes(origin);
120
- const site = firstHeader(headers['sec-fetch-site']);
121
- if (site) {
122
- if (site === 'same-origin' || site === 'none') {
123
- return true;
124
- }
125
- // same-site / cross-site: only when the origin is explicitly permitted.
126
- return originAllowlisted;
127
- }
128
- // No `Sec-Fetch-Site`: fall back to comparing the `Origin` host to the host.
129
- if (!origin) {
130
- // Non-browser client, or a same-origin GET with no `Origin` — not the
131
- // cross-origin browser request this guard exists to reject.
132
- return true;
133
- }
134
- if (originAllowlisted) {
135
- return true;
136
- }
137
- const host = firstHeader(headers['x-forwarded-host']) ?? firstHeader(headers['host']);
138
- if (!host) {
139
- return false;
140
- }
141
- try {
142
- return new URL(origin).host === host;
143
- }
144
- catch {
145
- return false;
146
- }
55
+ if (allowedOrigins.includes("*")) return true;
56
+ const origin = firstHeader(headers["origin"]);
57
+ const originAllowlisted = origin !== void 0 && allowedOrigins.includes(origin);
58
+ const site = firstHeader(headers["sec-fetch-site"]);
59
+ if (site) {
60
+ if (site === "same-origin" || site === "none") return true;
61
+ return originAllowlisted;
62
+ }
63
+ if (!origin) return true;
64
+ if (originAllowlisted) return true;
65
+ const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers["host"]);
66
+ if (!host) return false;
67
+ try {
68
+ return new URL(origin).host === host;
69
+ } catch {
70
+ return false;
71
+ }
147
72
  }
148
-
149
- /**
150
- * Server-side dispatch for a server function call.
151
- *
152
- * 1. reject cross-origin browser calls (403), unless allow-listed — HTTP
153
- * transport only (in-process callers omit `method` and are exempt)
154
- * 2. look up the function by id
155
- * 3. enforce the configured HTTP method (405 on mismatch)
156
- * 4. require a JSON body on input-bearing calls (415 otherwise)
157
- * 5. validate `input` against the Standard-Schema (4xx on failure)
158
- * 6. build a per-request injector (REQUEST/RESPONSE + app providers)
159
- * 7. run the interceptor chain, then the handler, re-entering
160
- * `runInInjectionContext` at every hop so `inject()` works even after an
161
- * interceptor `await`s before calling `next`
162
- * 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)
163
- * short-circuits with its status AND headers
164
- *
165
- * `options.method` is the request's HTTP method; when provided it is enforced
166
- * against the function's configured method AND it turns on the same-origin
167
- * guard. Transports (the generated Nitro handler) always pass it; trusted
168
- * in-process callers may omit it, which also exempts them from the origin guard.
169
- */
170
73
  async function dispatchServerFn(id, rawInput, event, options = {}) {
171
- const { parent, providers = [], method, allowedOrigins = [] } = options;
172
- const headers = (event.node.req.headers ?? {});
173
- // Same-origin guard runs first — before we even confirm the function exists —
174
- // so a cross-origin page cannot probe which ids are registered. Gated on
175
- // `method` so only HTTP-transport calls are checked; in-process callers omit
176
- // it. The signals (`Origin`/`Sec-Fetch-Site`) are browser-set and unforgeable.
177
- if (method) {
178
- const allowed = [
179
- ...allowedOrigins,
180
- ...(parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []),
181
- ];
182
- if (!isServerFnOriginAllowed(headers, allowed)) {
183
- return {
184
- status: 403,
185
- body: { message: 'Cross-origin server function call rejected' },
186
- };
187
- }
188
- }
189
- const def = serverFnRegistry.get(id);
190
- if (!def) {
191
- return { status: 404, body: { message: `Unknown server function: ${id}` } };
192
- }
193
- // Enforce the transport method: a GET-only read must not be POSTable, and an
194
- // input-bearing POST must not be reachable via GET.
195
- if (method && method.toUpperCase() !== def.method) {
196
- return {
197
- status: 405,
198
- body: { message: `Method ${method} not allowed for ${id}` },
199
- headers: { Allow: def.method },
200
- };
201
- }
202
- // Input travels as a JSON body. Reject anything else before decoding, so a
203
- // form post from a cross-origin page (which cannot set a JSON content type
204
- // without a CORS preflight) never reaches a handler. HTTP transport only.
205
- if (method && def.method === 'POST' && !isJsonContentType(headers)) {
206
- return {
207
- status: 415,
208
- body: { message: 'Server functions accept an application/json body' },
209
- };
210
- }
211
- let input = rawInput;
212
- if (def.config.input) {
213
- const result = await def.config.input['~standard'].validate(rawInput);
214
- if ('issues' in result && result.issues) {
215
- return { status: 400, body: { errors: result.issues } };
216
- }
217
- input = result.value;
218
- }
219
- // Child of the app injector: only the request tokens are per-request; app
220
- // services + interceptors resolve up the parent chain. All four are provided
221
- // here so a handler resolves them the same way it would inside a component
222
- // during SSR, whether it was reached over HTTP or in-process.
223
- const req = event.node.req;
224
- const locale = detectLocale(req);
225
- const injector = Injector.create({
226
- parent,
227
- providers: [
228
- { provide: REQUEST, useValue: event.node.req },
229
- { provide: RESPONSE, useValue: event.node.res },
230
- { provide: BASE_URL, useValue: getBaseUrl(req) },
231
- ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),
232
- ...providers,
233
- ],
234
- });
235
- // Re-enter the injection context at each hop rather than wrapping the whole
236
- // chain once: an interceptor that awaits before `next` would otherwise run the
237
- // handler outside the context and break `inject()`.
238
- const runInCtx = (fn) => runInInjectionContext(injector, fn);
239
- const interceptors = injector.get(SERVER_FN_INTERCEPTORS, []);
240
- const outcome = await runInterceptors(interceptors, input, def.handler, runInCtx);
241
- if (outcome instanceof Response) {
242
- const text = await outcome.text();
243
- const body = text ? safeJson(text) : null;
244
- const headers = {};
245
- outcome.headers.forEach((value, key) => {
246
- if (key.toLowerCase() !== 'set-cookie') {
247
- headers[key] = value;
248
- }
249
- });
250
- // `Headers.forEach` yields cookies comma-joined into a single value, which
251
- // is not a valid way to send more than one; `getSetCookie` keeps them apart.
252
- const setCookie = outcome.headers.getSetCookie?.() ?? [];
253
- if (setCookie.length) {
254
- headers['set-cookie'] = setCookie;
255
- }
256
- return {
257
- status: outcome.status,
258
- body,
259
- headers: Object.keys(headers).length ? headers : undefined,
260
- };
261
- }
262
- return { status: 200, body: outcome };
74
+ const { parent, providers = [], method, allowedOrigins = [] } = options;
75
+ const headers = event.node.req.headers ?? {};
76
+ if (method) {
77
+ if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
78
+ status: 403,
79
+ body: { message: "Cross-origin server function call rejected" }
80
+ };
81
+ }
82
+ const def = serverFnRegistry.get(id);
83
+ if (!def) return {
84
+ status: 404,
85
+ body: { message: `Unknown server function: ${id}` }
86
+ };
87
+ if (method && method.toUpperCase() !== def.method) return {
88
+ status: 405,
89
+ body: { message: `Method ${method} not allowed for ${id}` },
90
+ headers: { Allow: def.method }
91
+ };
92
+ if (method && def.method === "POST" && !isJsonContentType(headers)) return {
93
+ status: 415,
94
+ body: { message: "Server functions accept an application/json body" }
95
+ };
96
+ let input = rawInput;
97
+ if (def.config.input) {
98
+ const result = await def.config.input["~standard"].validate(rawInput);
99
+ if ("issues" in result && result.issues) return {
100
+ status: 400,
101
+ body: { errors: result.issues }
102
+ };
103
+ input = result.value;
104
+ }
105
+ const req = event.node.req;
106
+ const locale = detectLocale(req);
107
+ const injector = Injector.create({
108
+ parent,
109
+ providers: [
110
+ {
111
+ provide: REQUEST,
112
+ useValue: event.node.req
113
+ },
114
+ {
115
+ provide: RESPONSE,
116
+ useValue: event.node.res
117
+ },
118
+ {
119
+ provide: BASE_URL,
120
+ useValue: getBaseUrl(req)
121
+ },
122
+ ...locale ? [{
123
+ provide: LOCALE,
124
+ useValue: locale
125
+ }] : [],
126
+ ...providers
127
+ ]
128
+ });
129
+ const runInCtx = (fn) => runInInjectionContext(injector, fn);
130
+ const outcome = await runInterceptors(injector.get(SERVER_FN_INTERCEPTORS, []), input, def.handler, runInCtx);
131
+ if (outcome instanceof Response) {
132
+ const text = await outcome.text();
133
+ const body = text ? safeJson(text) : null;
134
+ const headers = {};
135
+ outcome.headers.forEach((value, key) => {
136
+ if (key.toLowerCase() !== "set-cookie") headers[key] = value;
137
+ });
138
+ const setCookie = outcome.headers.getSetCookie?.() ?? [];
139
+ if (setCookie.length) headers["set-cookie"] = setCookie;
140
+ return {
141
+ status: outcome.status,
142
+ body,
143
+ headers: Object.keys(headers).length ? headers : void 0
144
+ };
145
+ }
146
+ return {
147
+ status: 200,
148
+ body: outcome
149
+ };
263
150
  }
264
151
  function isJsonContentType(headers) {
265
- const contentType = headers['content-type'];
266
- const value = Array.isArray(contentType) ? contentType[0] : contentType;
267
- if (!value) {
268
- return false;
269
- }
270
- const mediaType = value.split(';')[0].trim().toLowerCase();
271
- return mediaType === 'application/json' || mediaType.endsWith('+json');
152
+ const contentType = headers["content-type"];
153
+ const value = Array.isArray(contentType) ? contentType[0] : contentType;
154
+ if (!value) return false;
155
+ const mediaType = value.split(";")[0].trim().toLowerCase();
156
+ return mediaType === "application/json" || mediaType.endsWith("+json");
272
157
  }
273
158
  function safeJson(text) {
274
- try {
275
- return JSON.parse(text);
276
- }
277
- catch {
278
- return text;
279
- }
159
+ try {
160
+ return JSON.parse(text);
161
+ } catch {
162
+ return text;
163
+ }
280
164
  }
281
-
282
- /**
283
- * The in-process transport used during SSR. `ServerFnClient` picks this up from
284
- * DI and calls the handler directly instead of issuing an HTTP request back
285
- * into the app — the render and the handler already share a process and a
286
- * request, so the round-trip only adds latency (and would need an absolute URL).
287
- *
288
- * `method` is deliberately not passed to `dispatchServerFn`: this is a trusted
289
- * in-process caller, so the HTTP-transport-only checks (same-origin, method
290
- * enforcement, content type) do not apply. Validation and the interceptor chain
291
- * still run, so an SSR call behaves like a browser call in every other respect.
292
- *
293
- * A non-2xx result is thrown as an `HttpErrorResponse` so the failure surfaces
294
- * on `resource.error()` exactly as it does in the browser.
295
- */
296
165
  function createServerFnDispatcher(req, res) {
297
- const event = { node: { req, res } };
298
- return async (fn, input, injector) => {
299
- const { status, body } = await dispatchServerFn(fn.id, input, event, {
300
- parent: injector,
301
- });
302
- if (status < 200 || status > 299) {
303
- throw new HttpErrorResponse({ status, error: body, url: fn.url });
304
- }
305
- return body;
306
- };
166
+ const event = { node: {
167
+ req,
168
+ res
169
+ } };
170
+ return async (fn, input, injector) => {
171
+ const { status, body } = await dispatchServerFn(fn.id, input, event, { parent: injector });
172
+ if (status < 200 || status > 299) throw new HttpErrorResponse({
173
+ status,
174
+ error: body,
175
+ url: fn.url
176
+ });
177
+ return body;
178
+ };
179
+ }
180
+ function provideServerContext({ req, res }) {
181
+ const baseUrl = getBaseUrl(req);
182
+ const locale = typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE || detectLocale(req);
183
+ if (import.meta.env?.DEV) ɵresetCompiledComponents();
184
+ return [
185
+ {
186
+ provide: ɵSERVER_CONTEXT,
187
+ useValue: "ssr-analog"
188
+ },
189
+ {
190
+ provide: REQUEST,
191
+ useValue: req
192
+ },
193
+ {
194
+ provide: RESPONSE,
195
+ useValue: res
196
+ },
197
+ {
198
+ provide: BASE_URL,
199
+ useValue: baseUrl
200
+ },
201
+ {
202
+ provide: SERVER_FN_DISPATCHER,
203
+ useValue: createServerFnDispatcher(req, res)
204
+ },
205
+ ...locale ? [{
206
+ provide: LOCALE,
207
+ useValue: locale
208
+ }] : []
209
+ ];
307
210
  }
308
-
309
- function provideServerContext({ req, res, }) {
310
- const baseUrl = getBaseUrl(req);
311
- const locale = (typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&
312
- ANALOG_I18N_FIXED_LOCALE) ||
313
- detectLocale(req);
314
- // Optional chaining: a Nitro-bundled caller has no `import.meta.env` at all.
315
- if (import.meta.env?.DEV) {
316
- _resetCompiledComponents();
317
- }
318
- return [
319
- { provide: _SERVER_CONTEXT, useValue: 'ssr-analog' },
320
- { provide: REQUEST, useValue: req },
321
- { provide: RESPONSE, useValue: res },
322
- { provide: BASE_URL, useValue: baseUrl },
323
- // Server functions called while rendering run in-process, in this injector.
324
- {
325
- provide: SERVER_FN_DISPATCHER,
326
- useValue: createServerFnDispatcher(req, res),
327
- },
328
- ...(locale ? [{ provide: LOCALE, useValue: locale }] : []),
329
- ];
330
- }
331
- /**
332
- * Detects the locale from the request URL path prefix or Accept-Language header.
333
- * URL prefix takes priority (e.g. /fr/about -> 'fr').
334
- */
335
211
  function detectLocale(req) {
336
- const url = req.originalUrl || req.url || '';
337
- const localeFromUrl = extractLocaleFromUrl(url);
338
- if (localeFromUrl) {
339
- return localeFromUrl;
340
- }
341
- return parseAcceptLanguage(req.headers['accept-language']);
212
+ const localeFromUrl = extractLocaleFromUrl(req.originalUrl || req.url || "");
213
+ if (localeFromUrl) return localeFromUrl;
214
+ return parseAcceptLanguage(req.headers["accept-language"]);
342
215
  }
343
- /**
344
- * Extracts a locale from the first URL path segment if it matches
345
- * a BCP 47-like pattern (e.g. 'en', 'en-US', 'zh-Hans-CN').
346
- */
347
216
  function extractLocaleFromUrl(url) {
348
- const pathname = url.split('?')[0];
349
- const segments = pathname.split('/').filter(Boolean);
350
- if (segments.length === 0) {
351
- return undefined;
352
- }
353
- const firstSegment = segments[0];
354
- // Match BCP 47 language tags: 2-letter language code with optional region/script
355
- // e.g. 'en', 'en-US', 'zh-Hans', 'zh-Hans-CN'
356
- if (/^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\d{3})?$/.test(firstSegment)) {
357
- return firstSegment;
358
- }
359
- return undefined;
217
+ const segments = url.split("?")[0].split("/").filter(Boolean);
218
+ if (segments.length === 0) return;
219
+ const firstSegment = segments[0];
220
+ if (/^[a-z]{2}(-[a-zA-Z]{2,4})?(-[a-zA-Z]{2}|\d{3})?$/.test(firstSegment)) return firstSegment;
360
221
  }
361
- /**
362
- * Parses the Accept-Language header and returns the most preferred language.
363
- */
364
222
  function parseAcceptLanguage(header) {
365
- if (!header) {
366
- return undefined;
367
- }
368
- const locales = header
369
- .split(',')
370
- .map((part) => {
371
- const [locale, qPart] = part.trim().split(';');
372
- const q = qPart ? parseFloat(qPart.replace('q=', '')) : 1;
373
- return { locale: locale.trim(), q };
374
- })
375
- .sort((a, b) => b.q - a.q);
376
- return locales[0]?.locale || undefined;
223
+ if (!header) return;
224
+ return header.split(",").map((part) => {
225
+ const [locale, qPart] = part.trim().split(";");
226
+ const q = qPart ? parseFloat(qPart.replace("q=", "")) : 1;
227
+ return {
228
+ locale: locale.trim(),
229
+ q
230
+ };
231
+ }).sort((a, b) => b.q - a.q)[0]?.locale || void 0;
377
232
  }
378
233
  function getBaseUrl(req) {
379
- const protocol = getRequestProtocol(req);
380
- const { headers } = req;
381
- // Node's `IncomingMessage` has no `originalUrl`, and a server function
382
- // endpoint is reached with a plain request, so fall back before dereferencing.
383
- const originalUrl = req.originalUrl || req.url || '/';
384
- const parsedUrl = new URL('', `${protocol}://${headers.host}${originalUrl.endsWith('/')
385
- ? originalUrl.substring(0, originalUrl.length - 1)
386
- : originalUrl}`);
387
- const baseUrl = parsedUrl.origin;
388
- return baseUrl;
234
+ const protocol = getRequestProtocol(req);
235
+ const { headers } = req;
236
+ const originalUrl = req.originalUrl || req.url || "/";
237
+ return new URL("", `${protocol}://${headers.host}${originalUrl.endsWith("/") ? originalUrl.substring(0, originalUrl.length - 1) : originalUrl}`).origin;
389
238
  }
390
239
  function getRequestProtocol(req, opts = {}) {
391
- if (opts.xForwardedProto !== false &&
392
- req.headers['x-forwarded-proto'] === 'https') {
393
- return 'https';
394
- }
395
- return req.connection?.encrypted ? 'https' : 'http';
240
+ if (opts.xForwardedProto !== false && req.headers["x-forwarded-proto"] === "https") return "https";
241
+ return req.connection?.encrypted ? "https" : "http";
396
242
  }
397
-
398
- /**
399
- * Nulls `def.tView` on every component definition that Angular has
400
- * compiled in this process. Angular caches the result of `consts()` on
401
- * `def.tView` — that factory is where `$localize` tagged templates are
402
- * evaluated — so without this reset the first rendered locale would be
403
- * frozen into the cache for the process lifetime.
404
- *
405
- * The set on `globalThis.__ngComponentDefs` is populated by a Vite
406
- * transform in `@analogjs/platform` that patches `@angular/core`'s
407
- * `getComponentId()` to mirror every compiled component definition to
408
- * a global Set, bypassing the `ngServerMode` guard that normally
409
- * prevents registration on the server.
410
- */
411
243
  function resetComponentDefTViews() {
412
- if (typeof ANALOG_I18N_FIXED_LOCALE !== 'undefined' &&
413
- ANALOG_I18N_FIXED_LOCALE)
414
- return;
415
- const defs = globalThis.__ngComponentDefs;
416
- if (!defs)
417
- return;
418
- for (const def of defs) {
419
- def.tView = null;
420
- }
244
+ if (typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE) return;
245
+ const defs = globalThis.__ngComponentDefs;
246
+ if (!defs) return;
247
+ for (const def of defs) def.tView = null;
421
248
  }
422
-
423
- // Optional chaining: the server-function dispatch endpoint imports this entry
424
- // from a Nitro bundle, where `import.meta.env` is not defined at all.
425
- if (import.meta.env?.PROD) {
426
- enableProdMode();
427
- }
428
- /**
429
- * Returns a function that accepts the navigation URL,
430
- * the root HTML, and server context.
431
- *
432
- * @param rootComponent
433
- * @param config
434
- * @param platformProviders
435
- * @returns Promise<string | Reponse>
436
- */
249
+ if (import.meta.env?.PROD) enableProdMode();
437
250
  function render(rootComponent, config, platformProviders = []) {
438
- function bootstrap(context) {
439
- return bootstrapApplication(rootComponent, config, context);
440
- }
441
- return async function render(url, document, serverContext) {
442
- resetComponentDefTViews();
443
- const html = await renderApplication(bootstrap, {
444
- document,
445
- url,
446
- platformProviders: [
447
- provideServerContext(serverContext),
448
- platformProviders,
449
- ],
450
- });
451
- return html;
452
- };
251
+ function bootstrap(context) {
252
+ return bootstrapApplication(rootComponent, config, context);
253
+ }
254
+ return async function render(url, document, serverContext) {
255
+ resetComponentDefTViews();
256
+ return await renderApplication(bootstrap, {
257
+ document,
258
+ url,
259
+ platformProviders: [provideServerContext(serverContext), platformProviders]
260
+ });
261
+ };
453
262
  }
454
-
455
- /**
456
- * Pure string helpers for slicing a fully rendered SSR document into the parts
457
- * the streaming renderer flushes: the shell up to `<body>`, the authoritative
458
- * `<body>` inner HTML for the tail, and the authoritative `<head>` inner HTML
459
- * for the finalize-time head reconcile. Extracted from `render-stream` so they
460
- * can be unit tested without driving the platform.
461
- */
462
- /** Byte offset just after the opening `<body>` tag, or 0 if none. */
463
263
  function afterBodyOpen(html) {
464
- const m = /<body[^>]*>/i.exec(html);
465
- return m ? m.index + m[0].length : 0;
264
+ const m = /<body[^>]*>/i.exec(html);
265
+ return m ? m.index + m[0].length : 0;
466
266
  }
467
- /** Inner HTML of `<body>` from a fully rendered document string. */
468
267
  function bodyInner(html) {
469
- const start = afterBodyOpen(html);
470
- const end = html.lastIndexOf('</body>');
471
- return html.slice(start, end > -1 ? end : html.length);
268
+ const start = afterBodyOpen(html);
269
+ const end = html.lastIndexOf("</body>");
270
+ return html.slice(start, end > -1 ? end : html.length);
472
271
  }
473
- /** Inner HTML of `<head>` from a fully rendered document string. */
474
272
  function headInner(html) {
475
- const open = /<head[^>]*>/i.exec(html);
476
- if (!open)
477
- return '';
478
- const start = open.index + open[0].length;
479
- const end = html.indexOf('</head>', start);
480
- return html.slice(start, end > -1 ? end : start);
273
+ const open = /<head[^>]*>/i.exec(html);
274
+ if (!open) return "";
275
+ const start = open.index + open[0].length;
276
+ const end = html.indexOf("</head>", start);
277
+ return html.slice(start, end > -1 ? end : start);
278
+ }
279
+ function createStreamShell(platform) {
280
+ const document = platform.injector.get(PlatformState).getDocument().cloneNode(true);
281
+ for (const script of Array.from(document.head.querySelectorAll("script[type=\"module\"]"))) {
282
+ const src = script.getAttribute("src");
283
+ if (src) {
284
+ const preload = document.createElement("link");
285
+ preload.setAttribute("rel", "modulepreload");
286
+ preload.setAttribute("href", src);
287
+ for (const name of [
288
+ "crossorigin",
289
+ "integrity",
290
+ "referrerpolicy",
291
+ "nonce",
292
+ "fetchpriority"
293
+ ]) {
294
+ const value = script.getAttribute(name);
295
+ if (value !== null) preload.setAttribute(name, value);
296
+ }
297
+ script.parentNode.replaceChild(preload, script);
298
+ } else script.parentNode.removeChild(script);
299
+ }
300
+ while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
301
+ const html = runInInjectionContext(platform.injector, () => new PlatformState(document).renderToString());
302
+ return html.slice(0, html.lastIndexOf("</body>"));
481
303
  }
482
-
483
- /**
484
- * Per-request decisions about whether the streaming renderer should fall back
485
- * to a buffered render. Extracted from `render-stream` so they can be unit
486
- * tested without driving the platform.
487
- */
488
- /**
489
- * User agents that receive a fully buffered render (with a resolved `<head>`)
490
- * instead of the streamed shell. Streaming flushes the head before the app has
491
- * set a dynamic title/meta and reconciles it via a finalize script; a crawler
492
- * that does not run that script would index the shell's static head. Mirrors
493
- * Nuxt's bot bypass — streaming targets interactive clients, bots get the
494
- * buffered path whose head is byte-identical to the classic `render()`.
495
- */
496
304
  const SSR_BOT_RE = /bot|crawl|spider|slurp|mediapartners|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|telegrambot|lighthouse|google-inspectiontool|headlesschrome|bingpreview/i;
497
305
  function isLikelyBot(serverContext) {
498
- const ua = serverContext?.req?.headers?.['user-agent'];
499
- return typeof ua === 'string' && SSR_BOT_RE.test(ua);
500
- }
501
- /**
502
- * Whether streaming is disabled for this request by a `streaming: false` route
503
- * rule. The platform plugin translates that rule into an `x-analog-no-streaming`
504
- * response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when
505
- * present, `renderStream` produces the buffered `render()` output for this
506
- * route instead of streaming.
507
- */
306
+ const ua = serverContext?.req?.headers?.["user-agent"];
307
+ return typeof ua === "string" && SSR_BOT_RE.test(ua);
308
+ }
508
309
  function streamingDisabledByRoute(serverContext) {
509
- return serverContext?.res?.getHeader?.('x-analog-no-streaming') === 'true';
310
+ return serverContext.streaming === void 0 ? serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true" : !serverContext.streaming;
510
311
  }
511
-
512
- /**
513
- * Tiny client runtime for progressive streaming SSR — EXPERIMENTAL.
514
- *
515
- * `renderStream` streams the document in three parts:
516
- * 1. the head + this runtime + an empty `<div data-analog-stream>` region;
517
- * 2. each `@defer` block, as it resolves on the server, as a
518
- * `<template data-analog-defer="ID">…</template>` followed by a call to
519
- * `window.__analogPaint("ID")` — this runtime paints the block into the
520
- * streaming region immediately, so content appears progressively and out
521
- * of document order;
522
- * 3. the authoritative document tail: the app's resolved `<head>` in a
523
- * `<template data-analog-head>` and the hydration-annotated body in a
524
- * `<template data-analog-authoritative>`, followed by
525
- * `window.__analogReconcileHead()` + `window.__analogFinalize()`. The head
526
- * is reconciled first (a dynamically-set `<title>`/meta is applied to the
527
- * live document, since the streamed shell head was flushed before the app
528
- * ran), then the body is swapped to the exact document Angular's
529
- * incremental hydration expects.
530
- *
531
- * Emitted into the document by `renderStream`. Exported as a string so it can
532
- * be injected verbatim and unit-tested against a DOM.
533
- */
534
- const DEFER_RECONCILE_RUNTIME = /* js */ `
312
+ const DEFER_RECONCILE_RUNTIME = `
535
313
  (function () {
314
+ var completed = false;
315
+ var headModules = [];
316
+ function activateModule(source) {
317
+ var script = document.createElement('script');
318
+ Array.from(source.attributes).forEach(function (attr) {
319
+ script.setAttribute(attr.name, attr.value);
320
+ });
321
+ if (source.hasAttribute('nonce')) script.nonce = source.nonce;
322
+ if (!source.hasAttribute('async')) script.async = false;
323
+ script.textContent = source.textContent;
324
+ return script;
325
+ }
536
326
  function region() {
537
327
  return document.querySelector('[data-analog-stream]');
538
328
  }
329
+ function showError() {
330
+ document.title = 'Unable to load this page';
331
+ var robots = document.head.querySelector('meta[name="robots"]');
332
+ if (!robots) {
333
+ robots = document.createElement('meta');
334
+ robots.setAttribute('name', 'robots');
335
+ document.head.appendChild(robots);
336
+ }
337
+ robots.setAttribute('content', 'noindex');
338
+ var error = document.createElement('main');
339
+ error.setAttribute('data-analog-render-error', '');
340
+ error.setAttribute('role', 'alert');
341
+ var heading = document.createElement('h1');
342
+ heading.textContent = 'Unable to load this page';
343
+ var message = document.createElement('p');
344
+ message.textContent = 'The page could not finish loading.';
345
+ error.appendChild(heading);
346
+ error.appendChild(message);
347
+ document.body.replaceChildren(error);
348
+ }
349
+ function checkCompletion() {
350
+ if (!completed && region()) showError();
351
+ }
352
+ window.__analogFail = showError;
353
+ // A Worker HTTP adapter can turn a stream error into ordinary EOF. The
354
+ // authoritative tail, rather than transport completion, proves SSR success.
355
+ document.addEventListener('DOMContentLoaded', checkCompletion, { once: true });
539
356
  window.__analogPaint = function (id) {
540
357
  var tpl = document.querySelector('template[data-analog-defer="' + id + '"]');
541
358
  var r = region();
@@ -554,6 +371,9 @@ const DEFER_RECONCILE_RUNTIME = /* js */ `
554
371
  if (!tpl) return;
555
372
  var frag = tpl.content;
556
373
  var head = document.head;
374
+ frag.querySelectorAll('script[type="module"]').forEach(function (script) {
375
+ headModules.push(script.cloneNode(true));
376
+ });
557
377
  var title = frag.querySelector('title');
558
378
  if (title) document.title = title.textContent || '';
559
379
  function metaKey(m) {
@@ -592,379 +412,329 @@ const DEFER_RECONCILE_RUNTIME = /* js */ `
592
412
  window.__analogFinalize = function () {
593
413
  var auth = document.querySelector('template[data-analog-authoritative]');
594
414
  if (!auth) return;
415
+ completed = true;
416
+ document.removeEventListener('DOMContentLoaded', checkCompletion);
595
417
  // Replace the entire body — preview region, block templates and runtime
596
418
  // scripts — with just the authoritative body, so the reconciled DOM matches
597
419
  // a buffered render byte-for-byte before hydration boots.
598
- document.body.replaceChildren(auth.content.cloneNode(true));
420
+ var body = auth.content.cloneNode(true);
421
+ var bodyModules = Array.from(body.querySelectorAll('script[type="module"]'));
422
+ document.body.replaceChildren(body);
423
+ headModules.forEach(function (script) {
424
+ document.head.appendChild(activateModule(script));
425
+ });
426
+ headModules = [];
427
+ bodyModules.forEach(function (script) {
428
+ script.replaceWith(activateModule(script));
429
+ });
599
430
  };
600
431
  })();
601
432
  `;
602
-
603
- /**
604
- * Progressive streaming SSR renderer — EXPERIMENTAL.
605
- *
606
- * Returns a `ReadableStream<Uint8Array>` that flushes bytes DURING the render,
607
- * not after it:
608
- * 1. the document head + a client reconcile runtime are flushed immediately,
609
- * before the app has finished rendering, so the browser starts fetching
610
- * assets right away;
611
- * 2. each `@defer (hydrate …)` block's content is flushed the moment it
612
- * resolves on the server — out of document order — while later blocks are
613
- * still pending (proven: a slow block does not hold back an early one);
614
- * 3. once the app is stable, the authoritative, fully hydration-annotated
615
- * document is flushed as the tail. This is byte-identical to a buffered
616
- * `renderApplication`, and is what Angular's incremental hydration runs
617
- * against on the client.
618
- *
619
- * Unlike a buffered renderer, this drives the platform directly
620
- * (`platformServer` + `bootstrapApplication` + `ɵrenderInternal`) so it can
621
- * interleave flushes with rendering. Angular's hydration annotation is
622
- * whole-document (the root's `ngh` index references every `@defer` container),
623
- * so the authoritative hydration payload is necessarily the tail: RENDERING
624
- * streams progressively, and hydration begins once the tail arrives.
625
- *
626
- * Depends on an upstream Angular per-block resolution hook exposed on two
627
- * globals (see {@link SsrStreamingGlobals}). When the primitive is absent,
628
- * `renderStream` degrades to a single buffered chunk so behaviour matches the
629
- * classic `render()` path, which is unchanged and remains the default.
630
- */
631
- // Optional chaining: the server-function dispatch endpoint imports this entry
632
- // from a Nitro bundle, where `import.meta.env` is not defined at all.
633
- if (import.meta.env?.PROD) {
634
- enableProdMode();
635
- }
433
+ function createSsrStream(options) {
434
+ const encoder = new TextEncoder();
435
+ const pending = /* @__PURE__ */ new Map();
436
+ let state = "rendering";
437
+ let capturing = true;
438
+ let cleanup;
439
+ let controller;
440
+ let keepAlive;
441
+ let complete;
442
+ const completed = new Promise((resolve) => {
443
+ complete = resolve;
444
+ });
445
+ function destroy() {
446
+ capturing = false;
447
+ clearInterval(keepAlive);
448
+ options.signal?.removeEventListener("abort", abort);
449
+ for (const [timer, task] of pending) {
450
+ clearTimeout(timer);
451
+ task.resolve();
452
+ }
453
+ pending.clear();
454
+ return cleanup ??= Promise.resolve().then(options.destroy).finally(complete);
455
+ }
456
+ function fail(error, aborted = false) {
457
+ if (state !== "rendering" && state !== "closing") return;
458
+ const documentComplete = state === "closing";
459
+ state = "failed";
460
+ if (options.errorHtml && !aborted) {
461
+ console.error("[analog ssr]", error);
462
+ if (!documentComplete) controller.enqueue(encoder.encode(options.errorHtml));
463
+ controller.close();
464
+ } else controller.error(error);
465
+ destroy().catch(() => void 0);
466
+ }
467
+ function abort() {
468
+ fail(options.signal?.reason ?? new DOMException("The render was aborted.", "AbortError"), true);
469
+ }
470
+ const writer = {
471
+ get active() {
472
+ return state === "rendering";
473
+ },
474
+ enqueue(html) {
475
+ if (state === "rendering") controller.enqueue(encoder.encode(html));
476
+ },
477
+ scheduleBlock(serialize) {
478
+ if (state !== "rendering" || !capturing) return;
479
+ let resolve;
480
+ const promise = new Promise((finish) => {
481
+ resolve = finish;
482
+ });
483
+ const timer = setTimeout(() => {
484
+ try {
485
+ if (state === "rendering") writer.enqueue(serialize());
486
+ } catch (error) {
487
+ fail(error);
488
+ } finally {
489
+ pending.delete(timer);
490
+ resolve();
491
+ }
492
+ }, 0);
493
+ pending.set(timer, {
494
+ promise,
495
+ resolve
496
+ });
497
+ },
498
+ async finishBlocks() {
499
+ capturing = false;
500
+ await Promise.all([...pending.values()].map((task) => task.promise));
501
+ }
502
+ };
503
+ return new ReadableStream({
504
+ start(streamController) {
505
+ controller = streamController;
506
+ if (options.waitUntil) {
507
+ options.waitUntil(completed);
508
+ keepAlive = setInterval(() => writer.enqueue("<!--analog-render-pending-->"), 1e3);
509
+ }
510
+ options.signal?.addEventListener("abort", abort, { once: true });
511
+ if (options.signal?.aborted) abort();
512
+ (async () => {
513
+ try {
514
+ if (state === "rendering") await options.render(writer);
515
+ if (state === "rendering") {
516
+ state = "closing";
517
+ await destroy();
518
+ if (state === "closing") {
519
+ state = "closed";
520
+ controller.close();
521
+ }
522
+ }
523
+ } catch (error) {
524
+ fail(error);
525
+ } finally {
526
+ await destroy();
527
+ }
528
+ })().catch(fail);
529
+ },
530
+ cancel() {
531
+ state = "cancelled";
532
+ return destroy();
533
+ }
534
+ });
535
+ }
536
+ function createSsrNavigationTracker() {
537
+ let failure;
538
+ return {
539
+ provider: makeEnvironmentProviders([{
540
+ provide: ENVIRONMENT_INITIALIZER,
541
+ multi: true,
542
+ useValue() {
543
+ const router = inject(Router, { optional: true });
544
+ if (!router) return;
545
+ const subscription = router.events.subscribe((event) => {
546
+ if (event instanceof NavigationError) failure = event;
547
+ else if (event instanceof NavigationEnd) failure = void 0;
548
+ });
549
+ inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
550
+ }
551
+ }]),
552
+ throwIfFailed() {
553
+ if (failure) throw failure.error;
554
+ }
555
+ };
556
+ }
557
+ if (import.meta.env?.PROD) enableProdMode();
636
558
  function streamingPrimitiveAvailable() {
637
- const g = globalThis;
638
- return (typeof g.__analogSsrInternals?.collectNativeNodesInLContainer === 'function');
639
- }
640
- /**
641
- * Per-render capture handlers live in async-local storage, not a single shared
642
- * global slot, so concurrent renders in one process do not clobber each other.
643
- * `globalThis.__analogSsrDeferCapture` is a stable dispatcher installed once; it
644
- * routes each resolved `@defer` block to the handler of the render whose async
645
- * context it fired in. A block that resolves outside any render (no store) is a
646
- * no-op.
647
- */
559
+ return typeof globalThis.__analogSsrInternals?.collectNativeNodesInLContainer === "function";
560
+ }
648
561
  const captureStore = new AsyncLocalStorage();
562
+ const CAPTURE_ZONE_KEY = "analogSsrDeferCapture";
563
+ function currentCaptureZone() {
564
+ return globalThis.Zone?.current;
565
+ }
566
+ function runWithCapture(handler, render) {
567
+ const zone = currentCaptureZone();
568
+ return captureStore.run(handler, () => zone === void 0 ? render() : zone.fork({
569
+ name: "analog-ssr-capture",
570
+ properties: { [CAPTURE_ZONE_KEY]: handler }
571
+ }).run(render));
572
+ }
649
573
  function installCaptureDispatcher() {
650
- const g = globalThis;
651
- if (g.__analogSsrDeferCapture?.__analogDispatcher)
652
- return;
653
- const dispatch = ((ev) => {
654
- captureStore.getStore()?.(ev);
655
- });
656
- dispatch.__analogDispatcher = true;
657
- g.__analogSsrDeferCapture = dispatch;
574
+ const g = globalThis;
575
+ if (g.__analogSsrDeferCapture?.__analogDispatcher) return;
576
+ const dispatch = (ev) => {
577
+ (currentCaptureZone()?.get(CAPTURE_ZONE_KEY) ?? captureStore.getStore())?.(ev);
578
+ };
579
+ dispatch.__analogDispatcher = true;
580
+ g.__analogSsrDeferCapture = dispatch;
658
581
  }
659
582
  let warnedMissingPrimitive = false;
660
583
  function warnMissingPrimitiveOnce() {
661
- if (warnedMissingPrimitive || !import.meta.env?.DEV)
662
- return;
663
- warnedMissingPrimitive = true;
664
- console.warn('[@analogjs/router] renderStream: the streaming hook was not found on ' +
665
- '@angular/core, so rendering falls back to buffered. Enable ' +
666
- '`experimental.streaming` in your Analog config; if it already is, your ' +
667
- 'installed Angular version may be incompatible with the streaming patch.');
668
- }
669
- /**
670
- * Serialize a `@defer` block's live domino subtree to HTML. Called a macrotask
671
- * after the block resolves, by which point change detection has filled in the
672
- * block's interpolations.
673
- */
584
+ if (warnedMissingPrimitive || !import.meta.env?.DEV) return;
585
+ warnedMissingPrimitive = true;
586
+ console.warn("[@analogjs/router] renderStream: the streaming hook was not found on @angular/core, so rendering falls back to buffered. Enable `experimental.streaming` in your Analog config; if it already is, your installed Angular version may be incompatible with the streaming patch.");
587
+ }
674
588
  function serializeLContainerHtml(lContainer) {
675
- const g = globalThis;
676
- const collect = g.__analogSsrInternals?.collectNativeNodesInLContainer;
677
- if (!collect)
678
- return '';
679
- const nodes = [];
680
- collect(lContainer, nodes);
681
- let html = '';
682
- for (const n of nodes)
683
- html += n?.outerHTML ?? n?.data ?? n?.nodeValue ?? '';
684
- return html;
685
- }
686
- /** Destroy the platform on a macrotask, matching `renderApplication`. */
589
+ const collect = globalThis.__analogSsrInternals?.collectNativeNodesInLContainer;
590
+ if (!collect) return "";
591
+ const nodes = [];
592
+ collect(lContainer, nodes);
593
+ let html = "";
594
+ for (const node of nodes) if (node.nodeType === 1) html += node.outerHTML ?? "";
595
+ else if (node.nodeType === 3) html += (node.data ?? node.nodeValue ?? "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
596
+ return html;
597
+ }
687
598
  function asyncDestroyPlatform(platformRef) {
688
- return new Promise((resolve) => {
689
- setTimeout(() => {
690
- platformRef.destroy();
691
- resolve();
692
- }, 0);
693
- });
599
+ return new Promise((resolve, reject) => {
600
+ setTimeout(() => {
601
+ try {
602
+ platformRef.destroy();
603
+ resolve();
604
+ } catch (error) {
605
+ reject(error);
606
+ }
607
+ }, 0);
608
+ });
694
609
  }
695
- /**
696
- * Returns a function that renders a URL to a `ReadableStream<Uint8Array>`.
697
- *
698
- * Usage in main.server.ts:
699
- * ```ts
700
- * import { renderStream } from '@analogjs/router/server';
701
- * export default renderStream(App, config);
702
- * ```
703
- */
704
610
  function renderStream(rootComponent, config, platformProviders = []) {
705
- function bootstrap(context) {
706
- return bootstrapApplication(rootComponent, config, context);
707
- }
708
- return async function renderStream(url, document, serverContext) {
709
- // Reset before every render — both the buffered fallback below and the
710
- // streaming path — so a prior render's locale/consts are not frozen for the
711
- // process lifetime (parity with render.ts).
712
- resetComponentDefTViews();
713
- // Fall back to a single buffered chunk so output matches the classic path
714
- // for:
715
- // - crawlers, which may not run the finalize script that reconciles a
716
- // dynamic <head>, so they get a buffered render with a resolved head;
717
- // - routes with a `streaming: false` rule (opt out per route);
718
- // - a missing streaming primitive.
719
- const primitiveAvailable = streamingPrimitiveAvailable();
720
- const bot = isLikelyBot(serverContext);
721
- const routeDisabled = streamingDisabledByRoute(serverContext);
722
- if (bot || routeDisabled || !primitiveAvailable) {
723
- // Warn only when the primitive is genuinely absent — the bot and
724
- // route-opt-out paths fall back to buffered by design, not by degradation.
725
- if (!bot && !routeDisabled && !primitiveAvailable) {
726
- warnMissingPrimitiveOnce();
727
- }
728
- const html = await renderApplication((context) => bootstrapApplication(rootComponent, config, context), {
729
- document,
730
- url,
731
- platformProviders: [
732
- provideServerContext(serverContext),
733
- platformProviders,
734
- ],
735
- });
736
- return new ReadableStream({
737
- start(controller) {
738
- controller.enqueue(new TextEncoder().encode(html));
739
- controller.close();
740
- },
741
- });
742
- }
743
- installCaptureDispatcher();
744
- const encoder = new TextEncoder();
745
- // The stream is returned immediately; `start` fills it as the render
746
- // progresses, so the consumer receives the head, then each @defer block the
747
- // moment it resolves, then the authoritative tail — true streaming.
748
- return new ReadableStream({
749
- async start(controller) {
750
- const enqueue = (s) => controller.enqueue(encoder.encode(s));
751
- // The capture handler fires once per @defer block as it resolves. The
752
- // block's DOM is not filled until the next change-detection tick, so we
753
- // serialize + flush it a macrotask later — flushing DURING the render.
754
- // It is scoped to this render via async-local storage (see
755
- // installCaptureDispatcher) so concurrent renders never cross-talk.
756
- let blockIndex = 0;
757
- let capturing = true;
758
- const seen = new Set();
759
- const pendingFlushes = [];
760
- const onBlockResolved = (ev) => {
761
- // A block can reach `Complete` more than once during a render; only
762
- // stream each container once. Also ignore any resolution that fires
763
- // after the render has moved on to serializing the authoritative tail.
764
- if (!capturing || seen.has(ev.lContainer))
765
- return;
766
- seen.add(ev.lContainer);
767
- const id = `s${blockIndex++}`;
768
- pendingFlushes.push(new Promise((resolve) => {
769
- setTimeout(() => {
770
- const html = serializeLContainerHtml(ev.lContainer);
771
- enqueue(`<template data-analog-defer="${id}">${html}</template>` +
772
- `<script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})</script>`);
773
- resolve();
774
- }, 0);
775
- }));
776
- };
777
- // Run the whole render inside the async-local context so every
778
- // change-detection tick and @defer resolution it schedules routes back
779
- // to THIS render's handler.
780
- await captureStore.run(onBlockResolved, async () => {
781
- const platformRef = platformServer([
782
- { provide: INITIAL_CONFIG, useValue: { document, url } },
783
- provideServerContext(serverContext),
784
- platformProviders,
785
- ]);
786
- // 1. Flush the head + reconcile runtime immediately (before the app is
787
- // rendered), then open the live streaming region.
788
- enqueue(document.slice(0, afterBodyOpen(document)) +
789
- `<script>${DEFER_RECONCILE_RUNTIME}</script>` +
790
- `<div data-analog-stream></div>`);
791
- let appRef;
792
- let errored = false;
793
- try {
794
- // 2. Bootstrap + render. Blocks resolve out of order during this
795
- // phase and flush via the capture handler above.
796
- appRef = await bootstrap({ platformRef });
797
- await appRef.whenStable();
798
- await Promise.all(pendingFlushes);
799
- // Stop capturing before serializing the tail so late resolutions
800
- // triggered by the hydration pass are not streamed as extra blocks.
801
- capturing = false;
802
- // 3. Flush the authoritative, fully hydration-annotated document as
803
- // the tail. Carried in <template>s (their inert `ng-state`
804
- // script survives). The app's resolved <head> ships alongside so
805
- // a dynamically-set title/meta — set during render, after the
806
- // shell head was already flushed — is reconciled onto the live
807
- // document before the runtime swaps in the body and hydration
808
- // boots.
809
- const authoritative = await _renderInternal(platformRef, appRef);
810
- enqueue(`<template data-analog-head>${headInner(authoritative)}</template>` +
811
- `<template data-analog-authoritative>${bodyInner(authoritative)}</template>` +
812
- `<script>window.__analogReconcileHead&&window.__analogReconcileHead();` +
813
- `window.__analogFinalize&&window.__analogFinalize()</script>` +
814
- `</body></html>`);
815
- }
816
- catch (err) {
817
- // The head + runtime were already flushed, so the status/headers are
818
- // committed; error the stream (a no-op silent close would hand the
819
- // client a truncated, non-hydratable 200) and log with block context.
820
- errored = true;
821
- console.error(`[@analogjs/router] renderStream failed for ${url} after ` +
822
- `${blockIndex} block(s); response truncated.`, err);
823
- controller.error(err);
824
- }
825
- finally {
826
- await asyncDestroyPlatform(platformRef);
827
- if (!errored)
828
- controller.close();
829
- }
830
- });
831
- },
832
- });
833
- };
611
+ return async function renderStream(url, document, serverContext) {
612
+ serverContext.signal?.throwIfAborted();
613
+ const navigation = createSsrNavigationTracker();
614
+ const applicationConfig = {
615
+ ...config,
616
+ providers: [...config.providers, navigation.provider]
617
+ };
618
+ const bootstrap = (context) => bootstrapApplication(rootComponent, applicationConfig, context);
619
+ resetComponentDefTViews();
620
+ const primitiveAvailable = streamingPrimitiveAvailable();
621
+ const bot = isLikelyBot(serverContext);
622
+ const routeDisabled = streamingDisabledByRoute(serverContext);
623
+ if (bot || routeDisabled || !primitiveAvailable) {
624
+ if (!bot && !routeDisabled && !primitiveAvailable) warnMissingPrimitiveOnce();
625
+ const html = await renderApplication(bootstrap, {
626
+ document,
627
+ url,
628
+ platformProviders: [provideServerContext(serverContext), platformProviders]
629
+ });
630
+ navigation.throwIfFailed();
631
+ return new ReadableStream({ start(controller) {
632
+ controller.enqueue(new TextEncoder().encode(html));
633
+ controller.close();
634
+ } });
635
+ }
636
+ installCaptureDispatcher();
637
+ const platformRef = platformServer([
638
+ {
639
+ provide: INITIAL_CONFIG,
640
+ useValue: {
641
+ document,
642
+ url
643
+ }
644
+ },
645
+ provideServerContext(serverContext),
646
+ platformProviders
647
+ ]);
648
+ let shell;
649
+ try {
650
+ shell = createStreamShell(platformRef);
651
+ } catch (error) {
652
+ await asyncDestroyPlatform(platformRef);
653
+ throw error;
654
+ }
655
+ return createSsrStream({
656
+ signal: serverContext.signal,
657
+ waitUntil: serverContext.waitUntil,
658
+ errorHtml: serverContext.renderErrorsAsHtml ? "<script data-analog-error>window.__analogFail&&window.__analogFail();<\/script></body></html>" : void 0,
659
+ destroy: () => asyncDestroyPlatform(platformRef),
660
+ async render(writer) {
661
+ let blockIndex = 0;
662
+ const seen = /* @__PURE__ */ new Set();
663
+ const onBlockResolved = (event) => {
664
+ if (!writer.active || seen.has(event.lContainer)) return;
665
+ seen.add(event.lContainer);
666
+ const id = `s${blockIndex++}`;
667
+ writer.scheduleBlock(() => `<template data-analog-defer="${id}">${serializeLContainerHtml(event.lContainer)}</template><script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})<\/script>`);
668
+ };
669
+ await runWithCapture(onBlockResolved, async () => {
670
+ writer.enqueue(shell + `<script>${DEFER_RECONCILE_RUNTIME}<\/script><div data-analog-stream></div>`);
671
+ const appRef = await bootstrap({ platformRef });
672
+ if (!writer.active) return;
673
+ await appRef.whenStable();
674
+ if (!writer.active) return;
675
+ navigation.throwIfFailed();
676
+ await writer.finishBlocks();
677
+ if (!writer.active) return;
678
+ const authoritative = await ɵrenderInternal(platformRef, appRef);
679
+ navigation.throwIfFailed();
680
+ writer.enqueue(`<template data-analog-head>${headInner(authoritative)}</template><template data-analog-authoritative>${bodyInner(authoritative)}</template><script>window.__analogReconcileHead&&window.__analogReconcileHead();window.__analogFinalize&&window.__analogFinalize()<\/script></body></html>`);
681
+ });
682
+ }
683
+ });
684
+ };
834
685
  }
835
-
836
686
  function serverFn(arg1, arg2) {
837
- const { config, handler } = normalizeArgs(arg1, arg2);
838
- // GET is reserved for input-less reads; an input schema requires POST (the
839
- // input travels in the body, not the query). Build transforms reject this too.
840
- if (config.method === 'GET' && config.input) {
841
- throw new Error('[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.');
842
- }
843
- // `createServerFnRef` throws if the build-derived id is missing, so `ref.id`
844
- // is the authoritative route key here.
845
- const ref = createServerFnRef(config);
846
- serverFnRegistry.set(ref.id, {
847
- id: ref.id,
848
- method: ref.method,
849
- config,
850
- handler,
851
- });
852
- return ref;
687
+ const { config, handler } = normalizeArgs(arg1, arg2);
688
+ if (config.method === "GET" && config.input) throw new Error("[analog] a serverFn with `input` must use POST; GET is reserved for input-less reads.");
689
+ const ref = createServerFnRef(config);
690
+ serverFnRegistry.set(ref.id, {
691
+ id: ref.id,
692
+ method: ref.method,
693
+ config,
694
+ handler
695
+ });
696
+ return ref;
853
697
  }
854
698
  function normalizeArgs(arg1, arg2) {
855
- // serverFn(handler) — input-less GET.
856
- if (typeof arg1 === 'function') {
857
- return {
858
- config: {},
859
- handler: arg1,
860
- };
861
- }
862
- // serverFn(schema, handler) — a Standard Schema ⇒ POST + input.
863
- if (isStandardSchema(arg1)) {
864
- return {
865
- config: { input: arg1 },
866
- handler: arg2,
867
- };
868
- }
869
- // serverFn(config, handler) — explicit config object.
870
- return {
871
- config: arg1 ?? {},
872
- handler: arg2,
873
- };
699
+ if (typeof arg1 === "function") return {
700
+ config: {},
701
+ handler: arg1
702
+ };
703
+ if (isStandardSchema(arg1)) return {
704
+ config: { input: arg1 },
705
+ handler: arg2
706
+ };
707
+ return {
708
+ config: arg1 ?? {},
709
+ handler: arg2
710
+ };
874
711
  }
875
712
  function isStandardSchema(value) {
876
- return typeof value === 'object' && value !== null && '~standard' in value;
713
+ return typeof value === "object" && value !== null && "~standard" in value;
877
714
  }
878
-
879
- /**
880
- * Builds the parent injector the server-function dispatch endpoint runs handlers
881
- * against, over HTTP.
882
- *
883
- * A plain `Injector.create({ providers })` resolves explicitly-listed providers
884
- * but not tree-shakeable `providedIn: 'root'` services — those attach to a
885
- * *bootstrapped* application's root injector, which `Injector.create` is not.
886
- * So the in-process SSR leg (whose parent is the app's own bootstrapped
887
- * injector) resolved `root` services while the HTTP leg did not — the same
888
- * handler could work while rendering and fail when called from the browser.
889
- *
890
- * Bootstrapping a real application on the server platform closes that gap: the
891
- * returned `appRef.injector` is a root environment injector, so both listed
892
- * providers and `providedIn: 'root'` services resolve, matching SSR.
893
- *
894
- * The generated endpoint passes the app's own server `ApplicationConfig` (the
895
- * one `main.server.ts` renders with), so a handler sees exactly the DI the app
896
- * configured — services, tokens, and interceptors alike — with no second
897
- * provider list to keep in sync. No root component is bootstrapped
898
- * (`createApplication`, not `bootstrapApplication`), so nothing renders, no
899
- * change detection runs, and the router registers but never navigates. It is a
900
- * DI container with the app's providers, built once and reused for the process,
901
- * with only `REQUEST`/`RESPONSE` rebuilt per call in the child.
902
- *
903
- * A bare provider array is also accepted (direct callers and tests without an
904
- * app config); it is wrapped with `provideServerRendering` so the server tokens
905
- * resolve the same way.
906
- */
907
715
  async function createServerFnAppInjector(configOrProviders = []) {
908
- const config = Array.isArray(configOrProviders)
909
- ? { providers: [provideServerRendering(), ...configOrProviders] }
910
- : configOrProviders;
911
- const appRef = await createApplication(config, {
912
- platformRef: platformServer(),
913
- });
914
- return appRef.injector;
716
+ return (await createApplication(Array.isArray(configOrProviders) ? { providers: [provideServerRendering(), ...configOrProviders] } : configOrProviders, { platformRef: platformServer() })).injector;
915
717
  }
916
-
917
- /**
918
- * The h3 request/response layer for the server-function dispatch route.
919
- *
920
- * `createServerFnAppInjector` bootstraps the parent injector once; this wraps
921
- * that in the `/_analog/fn/:id` handler the Nitro build registers. Kept as a
922
- * runtime function (rather than inlined into the generated module) so the
923
- * transport behaviour — body decoding, the malformed-body contract, and header
924
- * propagation — is unit-tested directly instead of by matching generated source.
925
- *
926
- * `appInjector` may be a promise: the generated module bootstraps the app at
927
- * import time and passes the pending injector, which is awaited on first request
928
- * and resolved instantly thereafter.
929
- */
930
718
  function createServerFnEventHandler(appInjector) {
931
- return eventHandler((event) => handleServerFnRequest(event, appInjector));
719
+ return eventHandler((event) => handleServerFnRequest(event, appInjector));
932
720
  }
933
- /**
934
- * Decode a server-function request, dispatch it, and write the result to the
935
- * h3 response. Same-origin, method, content-type, validation, and interceptors
936
- * are enforced inside `dispatchServerFn`; this owns only the h3 I/O around it.
937
- */
938
721
  async function handleServerFnRequest(event, appInjector) {
939
- const id = getRouterParam(event, 'id') ?? '';
940
- // h3 parses the body before dispatch gets a say, and its parse error is an
941
- // HTML/500-shaped response rather than the JSON contract callers expect.
942
- let input;
943
- if (event.method !== 'GET') {
944
- try {
945
- input = await readBody(event);
946
- }
947
- catch {
948
- event.node.res.statusCode = 400;
949
- return { message: 'Malformed request body' };
950
- }
951
- }
952
- const { status, body, headers } = await dispatchServerFn(id, input, event, {
953
- parent: await appInjector,
954
- method: event.method,
955
- });
956
- event.node.res.statusCode = status;
957
- if (headers) {
958
- for (const [key, value] of Object.entries(headers)) {
959
- event.node.res.setHeader(key, value);
960
- }
961
- }
962
- return body;
722
+ const id = getRouterParam(event, "id") ?? "";
723
+ let input;
724
+ if (event.method !== "GET") try {
725
+ input = await readBody(event);
726
+ } catch {
727
+ event.node.res.statusCode = 400;
728
+ return { message: "Malformed request body" };
729
+ }
730
+ const { status, body, headers } = await dispatchServerFn(id, input, event, {
731
+ parent: await appInjector,
732
+ method: event.method
733
+ });
734
+ event.node.res.statusCode = status;
735
+ if (headers) for (const [key, value] of Object.entries(headers)) event.node.res.setHeader(key, value);
736
+ return body;
963
737
  }
964
-
965
- /**
966
- * Generated bundle index. Do not edit.
967
- */
968
-
969
738
  export { SERVER_FN_ALLOWED_ORIGINS, SERVER_FN_INTERCEPTORS, createServerFnAppInjector, createServerFnEventHandler, dispatchServerFn, handleServerFnRequest, isServerFnOriginAllowed, provideServerContext, provideServerFns, render, renderStream, runInterceptors, serverFn, serverFnRegistry, withAllowedOrigins, withServerFnInterceptors };
970
- //# sourceMappingURL=analogjs-router-server.mjs.map
739
+
740
+ //# sourceMappingURL=analogjs-router-server.mjs.map