@analogjs/router 3.0.0-alpha.91 → 3.0.0-alpha.93
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.
- package/fesm2022/analogjs-router-i18n.mjs +4 -0
- package/fesm2022/analogjs-router-i18n.mjs.map +1 -1
- package/fesm2022/analogjs-router-server-actions.mjs +416 -2
- package/fesm2022/analogjs-router-server-actions.mjs.map +1 -0
- package/fesm2022/analogjs-router-server.mjs +588 -319
- package/fesm2022/analogjs-router-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query-server.mjs +4 -4
- package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query.mjs +70 -2
- package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -1
- package/fesm2022/analogjs-router-tokens.mjs.map +1 -1
- package/fesm2022/analogjs-router.mjs +147 -80
- package/fesm2022/analogjs-router.mjs.map +1 -1
- package/fesm2022/debug.page.mjs +3 -3
- package/fesm2022/route-files.mjs +1 -1
- package/package.json +11 -7
- package/types/server/actions/src/actions.d.ts +1 -1
- package/types/server/actions/src/define-action.d.ts +8 -15
- package/types/server/actions/src/define-api-route.d.ts +3 -4
- package/types/server/actions/src/define-page-load.d.ts +9 -10
- package/types/server/actions/src/define-server-route.d.ts +2 -2
- package/types/server/actions/src/index.d.ts +3 -2
- package/types/server/actions/src/parse-request-data.d.ts +3 -4
- package/types/server/actions/src/standard-schema.d.ts +39 -0
- package/types/server/actions/src/validate.d.ts +1 -1
- package/types/server/src/defer-reconcile-runtime.d.ts +1 -1
- package/types/server/src/server-fn/dispatch.d.ts +1 -1
- package/types/server/src/server-fn/event-handler.d.ts +1 -1
- package/types/server/src/server-fn/node-context.d.ts +3 -2
- package/types/server/src/ssr-navigation.d.ts +6 -0
- package/types/server/src/utils/ssr-stream-lifecycle.d.ts +14 -0
- package/types/server/src/utils/stream-request.d.ts +2 -1
- package/types/server/src/utils/stream-shell.d.ts +3 -0
- package/types/src/index.d.ts +2 -4
- package/types/src/lib/form-action.directive.d.ts +11 -9
- package/types/src/lib/route-types.d.ts +1 -1
- package/types/src/lib/server-fn/inject-server-fn.d.ts +1 -1
- package/types/tanstack-query/server/src/define-page-load-queries.d.ts +5 -7
- package/types/tanstack-query/server/src/index.d.ts +1 -1
- package/types/tanstack-query/server/src/provide-server-analog-query.d.ts +2 -0
- package/types/tanstack-query/src/index.d.ts +3 -2
- package/types/tanstack-query/src/server-query.d.ts +1 -1
- package/types/tokens/src/index.d.ts +8 -0
- package/fesm2022/provide-analog-query.mjs +0 -72
- package/fesm2022/provide-analog-query.mjs.map +0 -1
- package/fesm2022/src.mjs +0 -335
- package/fesm2022/src.mjs.map +0 -1
|
@@ -1,11 +1,297 @@
|
|
|
1
1
|
import { BASE_URL as BASE_URL$1, INTERNAL_FETCH, LOCALE as LOCALE$1, REQUEST as REQUEST$1, RESPONSE as RESPONSE$1 } from "./analogjs-router-tokens.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { NavigationEnd, NavigationError, Router } from "@angular/router";
|
|
3
|
+
import { DestroyRef, ENVIRONMENT_INITIALIZER, InjectionToken, Injector, enableProdMode, inject, makeEnvironmentProviders, runInInjectionContext } from "@angular/core";
|
|
4
|
+
import { HttpErrorResponse } from "@angular/common/http";
|
|
3
5
|
import { bootstrapApplication, createApplication } from "@angular/platform-browser";
|
|
4
6
|
import { BASE_URL, LOCALE, REQUEST, RESPONSE } from "@analogjs/router/tokens";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
+
import { INITIAL_CONFIG, PlatformState, platformServer, provideServerRendering, renderApplication, ɵSERVER_CONTEXT, ɵrenderInternal } from "@angular/platform-server";
|
|
8
|
+
import { SERVER_FN_DISPATCHER, createServerFnRef } from "@analogjs/router";
|
|
7
9
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
|
-
import {
|
|
10
|
+
import { eventHandler, getRouterParam, readBody } from "h3";
|
|
11
|
+
//#region packages/router/server/src/server-fn/registry.ts
|
|
12
|
+
/**
|
|
13
|
+
* Server-side registry of server functions, keyed by id. A `.server.ts` module
|
|
14
|
+
* populates it as a side effect of `serverFn(...)` running at import time; the
|
|
15
|
+
* Nitro dispatch route imports those modules to fill it, then looks up by id.
|
|
16
|
+
*/
|
|
17
|
+
var serverFnRegistry = /* @__PURE__ */ new Map();
|
|
18
|
+
//#endregion
|
|
19
|
+
//#region packages/router/server/src/server-fn/node-context.ts
|
|
20
|
+
/**
|
|
21
|
+
* Dispatch provides the Node request and response through `REQUEST` and
|
|
22
|
+
* `RESPONSE`, which are typed as Node primitives, so server functions only run
|
|
23
|
+
* on a Node runtime. h3 leaves `node` undefined on other runtimes. Calls made
|
|
24
|
+
* in-process while rendering may have no response.
|
|
25
|
+
*/
|
|
26
|
+
function assertNodeContext(event) {
|
|
27
|
+
const node = event.node;
|
|
28
|
+
if (!node?.req) throw new Error("@analogjs/router: server functions require a Node runtime.");
|
|
29
|
+
return node;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region packages/router/server/src/server-fn/interceptors.ts
|
|
33
|
+
var SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
|
|
34
|
+
/** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */
|
|
35
|
+
function withServerFnInterceptors(interceptors) {
|
|
36
|
+
return { providers: interceptors.map((fn) => ({
|
|
37
|
+
provide: SERVER_FN_INTERCEPTORS,
|
|
38
|
+
useValue: fn,
|
|
39
|
+
multi: true
|
|
40
|
+
})) };
|
|
41
|
+
}
|
|
42
|
+
/** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */
|
|
43
|
+
function provideServerFns(...features) {
|
|
44
|
+
return features.flatMap((f) => f.providers);
|
|
45
|
+
}
|
|
46
|
+
function makeCtx(input, context) {
|
|
47
|
+
return {
|
|
48
|
+
input,
|
|
49
|
+
context,
|
|
50
|
+
with(patch) {
|
|
51
|
+
return makeCtx(input, {
|
|
52
|
+
...context,
|
|
53
|
+
...patch
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Run the interceptor chain, then the handler, threading the context.
|
|
60
|
+
*
|
|
61
|
+
* `runInCtx` re-establishes the DI injection context around each interceptor
|
|
62
|
+
* and the handler individually. This is what keeps `inject()` working in a
|
|
63
|
+
* handler even when an upstream interceptor `await`s before calling `next`
|
|
64
|
+
* (which would otherwise resume outside Angular's synchronous injection
|
|
65
|
+
* context). It defaults to a pass-through for non-DI callers/tests.
|
|
66
|
+
*/
|
|
67
|
+
async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
|
|
68
|
+
let i = -1;
|
|
69
|
+
const dispatch = async (ctx) => {
|
|
70
|
+
i += 1;
|
|
71
|
+
if (i < interceptors.length) return runInCtx(() => interceptors[i](ctx, dispatch));
|
|
72
|
+
return runInCtx(() => handler(ctx.input, ctx.context));
|
|
73
|
+
};
|
|
74
|
+
return dispatch(makeCtx(input, {}));
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region packages/router/server/src/server-fn/same-origin.ts
|
|
78
|
+
/**
|
|
79
|
+
* Same-origin enforcement for the server-function HTTP transport.
|
|
80
|
+
*
|
|
81
|
+
* Server functions are same-origin RPC: a client proxy only ever calls the
|
|
82
|
+
* relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be
|
|
83
|
+
* able to invoke them against a logged-in user (a CSRF-shaped attack), so the
|
|
84
|
+
* transport rejects browser requests whose origin is not the app's own — out of
|
|
85
|
+
* the box, with no per-app configuration.
|
|
86
|
+
*
|
|
87
|
+
* The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and
|
|
88
|
+
* cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,
|
|
89
|
+
* server-to-server, SSR in-process) send neither, so they are unaffected: the
|
|
90
|
+
* guard blocks the cross-origin browser attack it is meant to, and nothing else.
|
|
91
|
+
*/
|
|
92
|
+
/**
|
|
93
|
+
* Origins permitted beyond the app's own, registered through DI:
|
|
94
|
+
* `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the
|
|
95
|
+
* transport is same-origin unless an app opts out explicitly.
|
|
96
|
+
*/
|
|
97
|
+
var SERVER_FN_ALLOWED_ORIGINS = new InjectionToken("SERVER_FN_ALLOWED_ORIGINS");
|
|
98
|
+
/**
|
|
99
|
+
* `withAllowedOrigins([...])` — permit cross-origin browser calls from the
|
|
100
|
+
* listed origins, or pass `'*'` to disable the same-origin guard entirely.
|
|
101
|
+
* Server functions are frequently cookie-authenticated, so this is an explicit
|
|
102
|
+
* opt-out of CSRF protection: allow-list the exact origins you control.
|
|
103
|
+
*/
|
|
104
|
+
function withAllowedOrigins(origins) {
|
|
105
|
+
return { providers: origins.map((origin) => ({
|
|
106
|
+
provide: SERVER_FN_ALLOWED_ORIGINS,
|
|
107
|
+
useValue: origin,
|
|
108
|
+
multi: true
|
|
109
|
+
})) };
|
|
110
|
+
}
|
|
111
|
+
function firstHeader(value) {
|
|
112
|
+
return Array.isArray(value) ? value[0] : value;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Whether an HTTP request to a server function may proceed.
|
|
116
|
+
*
|
|
117
|
+
* Allowed when the request is same-origin, carries no browser-origin signal at
|
|
118
|
+
* all (a non-browser client, or a same-origin GET that omits `Origin`), or its
|
|
119
|
+
* `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`
|
|
120
|
+
* disables the check — the explicit opt-in to cross-origin access.
|
|
121
|
+
*
|
|
122
|
+
* `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and
|
|
123
|
+
* `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and
|
|
124
|
+
* `cross-site` require an explicit `allowedOrigins` entry. When the header is
|
|
125
|
+
* absent (older browsers, some proxies) the `Origin` host is compared to the
|
|
126
|
+
* request host as a fallback.
|
|
127
|
+
*/
|
|
128
|
+
function isServerFnOriginAllowed(headers, allowedOrigins = []) {
|
|
129
|
+
if (allowedOrigins.includes("*")) return true;
|
|
130
|
+
const origin = firstHeader(headers["origin"]);
|
|
131
|
+
const originAllowlisted = origin !== void 0 && allowedOrigins.includes(origin);
|
|
132
|
+
const site = firstHeader(headers["sec-fetch-site"]);
|
|
133
|
+
if (site) {
|
|
134
|
+
if (site === "same-origin" || site === "none") return true;
|
|
135
|
+
return originAllowlisted;
|
|
136
|
+
}
|
|
137
|
+
if (!origin) return true;
|
|
138
|
+
if (originAllowlisted) return true;
|
|
139
|
+
const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers["host"]);
|
|
140
|
+
if (!host) return false;
|
|
141
|
+
try {
|
|
142
|
+
return new URL(origin).host === host;
|
|
143
|
+
} catch {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
//#region packages/router/server/src/server-fn/dispatch.ts
|
|
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
|
+
async function dispatchServerFn(id, rawInput, event, options = {}) {
|
|
171
|
+
const { parent, providers = [], method, allowedOrigins = [] } = options;
|
|
172
|
+
const node = assertNodeContext(event);
|
|
173
|
+
const headers = node.req.headers ?? {};
|
|
174
|
+
if (method) {
|
|
175
|
+
if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
|
|
176
|
+
status: 403,
|
|
177
|
+
body: { message: "Cross-origin server function call rejected" }
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const def = serverFnRegistry.get(id);
|
|
181
|
+
if (!def) return {
|
|
182
|
+
status: 404,
|
|
183
|
+
body: { message: `Unknown server function: ${id}` }
|
|
184
|
+
};
|
|
185
|
+
if (method && method.toUpperCase() !== def.method) return {
|
|
186
|
+
status: 405,
|
|
187
|
+
body: { message: `Method ${method} not allowed for ${id}` },
|
|
188
|
+
headers: { Allow: def.method }
|
|
189
|
+
};
|
|
190
|
+
if (method && def.method === "POST" && !isJsonContentType(headers)) return {
|
|
191
|
+
status: 415,
|
|
192
|
+
body: { message: "Server functions accept an application/json body" }
|
|
193
|
+
};
|
|
194
|
+
let input = rawInput;
|
|
195
|
+
if (def.config.input) {
|
|
196
|
+
const result = await def.config.input["~standard"].validate(rawInput);
|
|
197
|
+
if ("issues" in result && result.issues) return {
|
|
198
|
+
status: 400,
|
|
199
|
+
body: { errors: result.issues }
|
|
200
|
+
};
|
|
201
|
+
input = result.value;
|
|
202
|
+
}
|
|
203
|
+
const req = node.req;
|
|
204
|
+
const locale = detectLocale(req);
|
|
205
|
+
const injector = Injector.create({
|
|
206
|
+
parent,
|
|
207
|
+
providers: [
|
|
208
|
+
{
|
|
209
|
+
provide: REQUEST,
|
|
210
|
+
useValue: node.req
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
provide: RESPONSE,
|
|
214
|
+
useValue: node.res
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
provide: BASE_URL,
|
|
218
|
+
useValue: getBaseUrl(req)
|
|
219
|
+
},
|
|
220
|
+
...locale ? [{
|
|
221
|
+
provide: LOCALE,
|
|
222
|
+
useValue: locale
|
|
223
|
+
}] : [],
|
|
224
|
+
...providers
|
|
225
|
+
]
|
|
226
|
+
});
|
|
227
|
+
const runInCtx = (fn) => runInInjectionContext(injector, fn);
|
|
228
|
+
const outcome = await runInterceptors(injector.get(SERVER_FN_INTERCEPTORS, []), input, def.handler, runInCtx);
|
|
229
|
+
if (outcome instanceof Response) {
|
|
230
|
+
const text = await outcome.text();
|
|
231
|
+
const body = text ? safeJson(text) : null;
|
|
232
|
+
const headers = {};
|
|
233
|
+
outcome.headers.forEach((value, key) => {
|
|
234
|
+
if (key.toLowerCase() !== "set-cookie") headers[key] = value;
|
|
235
|
+
});
|
|
236
|
+
const setCookie = outcome.headers.getSetCookie?.() ?? [];
|
|
237
|
+
if (setCookie.length) headers["set-cookie"] = setCookie;
|
|
238
|
+
return {
|
|
239
|
+
status: outcome.status,
|
|
240
|
+
body,
|
|
241
|
+
headers: Object.keys(headers).length ? headers : void 0
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
return {
|
|
245
|
+
status: 200,
|
|
246
|
+
body: outcome
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
function isJsonContentType(headers) {
|
|
250
|
+
const contentType = headers["content-type"];
|
|
251
|
+
const value = Array.isArray(contentType) ? contentType[0] : contentType;
|
|
252
|
+
if (!value) return false;
|
|
253
|
+
const mediaType = value.split(";")[0].trim().toLowerCase();
|
|
254
|
+
return mediaType === "application/json" || mediaType.endsWith("+json");
|
|
255
|
+
}
|
|
256
|
+
function safeJson(text) {
|
|
257
|
+
try {
|
|
258
|
+
return JSON.parse(text);
|
|
259
|
+
} catch {
|
|
260
|
+
return text;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
//#endregion
|
|
264
|
+
//#region packages/router/server/src/server-fn/ssr-dispatcher.ts
|
|
265
|
+
/**
|
|
266
|
+
* The in-process transport used during SSR. `ServerFnClient` picks this up from
|
|
267
|
+
* DI and calls the handler directly instead of issuing an HTTP request back
|
|
268
|
+
* into the app — the render and the handler already share a process and a
|
|
269
|
+
* request, so the round-trip only adds latency (and would need an absolute URL).
|
|
270
|
+
*
|
|
271
|
+
* `method` is deliberately not passed to `dispatchServerFn`: this is a trusted
|
|
272
|
+
* in-process caller, so the HTTP-transport-only checks (same-origin, method
|
|
273
|
+
* enforcement, content type) do not apply. Validation and the interceptor chain
|
|
274
|
+
* still run, so an SSR call behaves like a browser call in every other respect.
|
|
275
|
+
*
|
|
276
|
+
* A non-2xx result is thrown as an `HttpErrorResponse` so the failure surfaces
|
|
277
|
+
* on `resource.error()` exactly as it does in the browser.
|
|
278
|
+
*/
|
|
279
|
+
function createServerFnDispatcher(req, res) {
|
|
280
|
+
const event = { node: {
|
|
281
|
+
req,
|
|
282
|
+
res
|
|
283
|
+
} };
|
|
284
|
+
return async (fn, input, injector) => {
|
|
285
|
+
const { status, body } = await dispatchServerFn(fn.id, input, event, { parent: injector });
|
|
286
|
+
if (status < 200 || status > 299) throw new HttpErrorResponse({
|
|
287
|
+
status,
|
|
288
|
+
error: body,
|
|
289
|
+
url: fn.url
|
|
290
|
+
});
|
|
291
|
+
return body;
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
//#endregion
|
|
9
295
|
//#region packages/router/server/src/provide-server-context.ts
|
|
10
296
|
function getHeaderValue(value) {
|
|
11
297
|
return Array.isArray(value) ? value[0] : value;
|
|
@@ -18,7 +304,7 @@ function getRequestHeader(req, name) {
|
|
|
18
304
|
}
|
|
19
305
|
function provideServerContext({ req, res, fetch }) {
|
|
20
306
|
const baseUrl = getBaseUrl(req);
|
|
21
|
-
const locale = detectLocale(req);
|
|
307
|
+
const locale = typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE || detectLocale(req);
|
|
22
308
|
return [
|
|
23
309
|
{
|
|
24
310
|
provide: ɵSERVER_CONTEXT,
|
|
@@ -40,6 +326,10 @@ function provideServerContext({ req, res, fetch }) {
|
|
|
40
326
|
provide: INTERNAL_FETCH,
|
|
41
327
|
useValue: fetch
|
|
42
328
|
},
|
|
329
|
+
{
|
|
330
|
+
provide: SERVER_FN_DISPATCHER,
|
|
331
|
+
useValue: createServerFnDispatcher(req, res)
|
|
332
|
+
},
|
|
43
333
|
...locale ? [{
|
|
44
334
|
provide: LOCALE$1,
|
|
45
335
|
useValue: locale
|
|
@@ -106,6 +396,7 @@ function parseAcceptLanguage(header) {
|
|
|
106
396
|
* prevents registration on the server.
|
|
107
397
|
*/
|
|
108
398
|
function resetComponentDefTViews() {
|
|
399
|
+
if (typeof ANALOG_I18N_FIXED_LOCALE !== "undefined" && ANALOG_I18N_FIXED_LOCALE) return;
|
|
109
400
|
const defs = globalThis.__ngComponentDefs;
|
|
110
401
|
if (!defs) return;
|
|
111
402
|
for (const def of defs) def.tView = null;
|
|
@@ -164,6 +455,34 @@ function headInner(html) {
|
|
|
164
455
|
return html.slice(start, end > -1 ? end : start);
|
|
165
456
|
}
|
|
166
457
|
//#endregion
|
|
458
|
+
//#region packages/router/server/src/utils/stream-shell.ts
|
|
459
|
+
/** Preload bootstrap modules, but leave execution to the authoritative tail. */
|
|
460
|
+
function createStreamShell(platform) {
|
|
461
|
+
const document = platform.injector.get(PlatformState).getDocument().cloneNode(true);
|
|
462
|
+
for (const script of Array.from(document.head.querySelectorAll("script[type=\"module\"]"))) {
|
|
463
|
+
const src = script.getAttribute("src");
|
|
464
|
+
if (src) {
|
|
465
|
+
const preload = document.createElement("link");
|
|
466
|
+
preload.setAttribute("rel", "modulepreload");
|
|
467
|
+
preload.setAttribute("href", src);
|
|
468
|
+
for (const name of [
|
|
469
|
+
"crossorigin",
|
|
470
|
+
"integrity",
|
|
471
|
+
"referrerpolicy",
|
|
472
|
+
"nonce",
|
|
473
|
+
"fetchpriority"
|
|
474
|
+
]) {
|
|
475
|
+
const value = script.getAttribute(name);
|
|
476
|
+
if (value !== null) preload.setAttribute(name, value);
|
|
477
|
+
}
|
|
478
|
+
script.parentNode.replaceChild(preload, script);
|
|
479
|
+
} else script.parentNode.removeChild(script);
|
|
480
|
+
}
|
|
481
|
+
while (document.body.firstChild) document.body.removeChild(document.body.firstChild);
|
|
482
|
+
const html = runInInjectionContext(platform.injector, () => new PlatformState(document).renderToString());
|
|
483
|
+
return html.slice(0, html.lastIndexOf("</body>"));
|
|
484
|
+
}
|
|
485
|
+
//#endregion
|
|
167
486
|
//#region packages/router/server/src/utils/stream-request.ts
|
|
168
487
|
/**
|
|
169
488
|
* Per-request decisions about whether the streaming renderer should fall back
|
|
@@ -188,10 +507,12 @@ function isLikelyBot(serverContext) {
|
|
|
188
507
|
* rule. The platform plugin translates that rule into an `x-analog-no-streaming`
|
|
189
508
|
* response header (mirroring how `ssr: false` becomes `x-analog-no-ssr`); when
|
|
190
509
|
* present, `renderStream` produces the buffered `render()` output for this
|
|
191
|
-
* route instead of streaming.
|
|
510
|
+
* route instead of streaming. On Nitro v3, which renders without a Node
|
|
511
|
+
* response, the header is forwarded on the request instead.
|
|
192
512
|
*/
|
|
193
513
|
function streamingDisabledByRoute(serverContext) {
|
|
194
|
-
|
|
514
|
+
if (serverContext?.streaming !== void 0) return !serverContext.streaming;
|
|
515
|
+
return serverContext?.res?.getHeader?.("x-analog-no-streaming") === "true" || serverContext?.req?.headers?.["x-analog-no-streaming"] === "true";
|
|
195
516
|
}
|
|
196
517
|
//#endregion
|
|
197
518
|
//#region packages/router/server/src/defer-reconcile-runtime.ts
|
|
@@ -219,9 +540,48 @@ function streamingDisabledByRoute(serverContext) {
|
|
|
219
540
|
*/
|
|
220
541
|
var DEFER_RECONCILE_RUNTIME = `
|
|
221
542
|
(function () {
|
|
543
|
+
var completed = false;
|
|
544
|
+
var headModules = [];
|
|
545
|
+
function activateModule(source) {
|
|
546
|
+
var script = document.createElement('script');
|
|
547
|
+
Array.from(source.attributes).forEach(function (attr) {
|
|
548
|
+
script.setAttribute(attr.name, attr.value);
|
|
549
|
+
});
|
|
550
|
+
if (source.hasAttribute('nonce')) script.nonce = source.nonce;
|
|
551
|
+
if (!source.hasAttribute('async')) script.async = false;
|
|
552
|
+
script.textContent = source.textContent;
|
|
553
|
+
return script;
|
|
554
|
+
}
|
|
222
555
|
function region() {
|
|
223
556
|
return document.querySelector('[data-analog-stream]');
|
|
224
557
|
}
|
|
558
|
+
function showError() {
|
|
559
|
+
document.title = 'Unable to load this page';
|
|
560
|
+
var robots = document.head.querySelector('meta[name="robots"]');
|
|
561
|
+
if (!robots) {
|
|
562
|
+
robots = document.createElement('meta');
|
|
563
|
+
robots.setAttribute('name', 'robots');
|
|
564
|
+
document.head.appendChild(robots);
|
|
565
|
+
}
|
|
566
|
+
robots.setAttribute('content', 'noindex');
|
|
567
|
+
var error = document.createElement('main');
|
|
568
|
+
error.setAttribute('data-analog-render-error', '');
|
|
569
|
+
error.setAttribute('role', 'alert');
|
|
570
|
+
var heading = document.createElement('h1');
|
|
571
|
+
heading.textContent = 'Unable to load this page';
|
|
572
|
+
var message = document.createElement('p');
|
|
573
|
+
message.textContent = 'The page could not finish loading.';
|
|
574
|
+
error.appendChild(heading);
|
|
575
|
+
error.appendChild(message);
|
|
576
|
+
document.body.replaceChildren(error);
|
|
577
|
+
}
|
|
578
|
+
function checkCompletion() {
|
|
579
|
+
if (!completed && region()) showError();
|
|
580
|
+
}
|
|
581
|
+
window.__analogFail = showError;
|
|
582
|
+
// A Worker HTTP adapter can turn a stream error into ordinary EOF. The
|
|
583
|
+
// authoritative tail, rather than transport completion, proves SSR success.
|
|
584
|
+
document.addEventListener('DOMContentLoaded', checkCompletion, { once: true });
|
|
225
585
|
window.__analogPaint = function (id) {
|
|
226
586
|
var tpl = document.querySelector('template[data-analog-defer="' + id + '"]');
|
|
227
587
|
var r = region();
|
|
@@ -240,6 +600,9 @@ var DEFER_RECONCILE_RUNTIME = `
|
|
|
240
600
|
if (!tpl) return;
|
|
241
601
|
var frag = tpl.content;
|
|
242
602
|
var head = document.head;
|
|
603
|
+
frag.querySelectorAll('script[type="module"]').forEach(function (script) {
|
|
604
|
+
headModules.push(script.cloneNode(true));
|
|
605
|
+
});
|
|
243
606
|
var title = frag.querySelector('title');
|
|
244
607
|
if (title) document.title = title.textContent || '';
|
|
245
608
|
function metaKey(m) {
|
|
@@ -278,14 +641,154 @@ var DEFER_RECONCILE_RUNTIME = `
|
|
|
278
641
|
window.__analogFinalize = function () {
|
|
279
642
|
var auth = document.querySelector('template[data-analog-authoritative]');
|
|
280
643
|
if (!auth) return;
|
|
644
|
+
completed = true;
|
|
645
|
+
document.removeEventListener('DOMContentLoaded', checkCompletion);
|
|
281
646
|
// Replace the entire body — preview region, block templates and runtime
|
|
282
647
|
// scripts — with just the authoritative body, so the reconciled DOM matches
|
|
283
648
|
// a buffered render byte-for-byte before hydration boots.
|
|
284
|
-
|
|
649
|
+
var body = auth.content.cloneNode(true);
|
|
650
|
+
var bodyModules = Array.from(body.querySelectorAll('script[type="module"]'));
|
|
651
|
+
document.body.replaceChildren(body);
|
|
652
|
+
headModules.forEach(function (script) {
|
|
653
|
+
document.head.appendChild(activateModule(script));
|
|
654
|
+
});
|
|
655
|
+
headModules = [];
|
|
656
|
+
bodyModules.forEach(function (script) {
|
|
657
|
+
script.replaceWith(activateModule(script));
|
|
658
|
+
});
|
|
285
659
|
};
|
|
286
660
|
})();
|
|
287
661
|
`;
|
|
288
662
|
//#endregion
|
|
663
|
+
//#region packages/router/server/src/utils/ssr-stream-lifecycle.ts
|
|
664
|
+
function createSsrStream(options) {
|
|
665
|
+
const encoder = new TextEncoder();
|
|
666
|
+
const pending = /* @__PURE__ */ new Map();
|
|
667
|
+
let state = "rendering";
|
|
668
|
+
let capturing = true;
|
|
669
|
+
let cleanup;
|
|
670
|
+
let controller;
|
|
671
|
+
let keepAlive;
|
|
672
|
+
let complete;
|
|
673
|
+
const completed = new Promise((resolve) => {
|
|
674
|
+
complete = resolve;
|
|
675
|
+
});
|
|
676
|
+
function destroy() {
|
|
677
|
+
capturing = false;
|
|
678
|
+
clearInterval(keepAlive);
|
|
679
|
+
options.signal?.removeEventListener("abort", abort);
|
|
680
|
+
for (const [timer, task] of pending) {
|
|
681
|
+
clearTimeout(timer);
|
|
682
|
+
task.resolve();
|
|
683
|
+
}
|
|
684
|
+
pending.clear();
|
|
685
|
+
return cleanup ??= Promise.resolve().then(options.destroy).finally(complete);
|
|
686
|
+
}
|
|
687
|
+
function fail(error, aborted = false) {
|
|
688
|
+
if (state !== "rendering" && state !== "closing") return;
|
|
689
|
+
const documentComplete = state === "closing";
|
|
690
|
+
state = "failed";
|
|
691
|
+
if (options.errorHtml && !aborted) {
|
|
692
|
+
console.error("[analog ssr]", error);
|
|
693
|
+
if (!documentComplete) controller.enqueue(encoder.encode(options.errorHtml));
|
|
694
|
+
controller.close();
|
|
695
|
+
} else controller.error(error);
|
|
696
|
+
destroy().catch(() => void 0);
|
|
697
|
+
}
|
|
698
|
+
function abort() {
|
|
699
|
+
fail(options.signal?.reason ?? new DOMException("The render was aborted.", "AbortError"), true);
|
|
700
|
+
}
|
|
701
|
+
const writer = {
|
|
702
|
+
get active() {
|
|
703
|
+
return state === "rendering";
|
|
704
|
+
},
|
|
705
|
+
enqueue(html) {
|
|
706
|
+
if (state === "rendering") controller.enqueue(encoder.encode(html));
|
|
707
|
+
},
|
|
708
|
+
scheduleBlock(serialize) {
|
|
709
|
+
if (state !== "rendering" || !capturing) return;
|
|
710
|
+
let resolve;
|
|
711
|
+
const promise = new Promise((finish) => {
|
|
712
|
+
resolve = finish;
|
|
713
|
+
});
|
|
714
|
+
const timer = setTimeout(() => {
|
|
715
|
+
try {
|
|
716
|
+
if (state === "rendering") writer.enqueue(serialize());
|
|
717
|
+
} catch (error) {
|
|
718
|
+
fail(error);
|
|
719
|
+
} finally {
|
|
720
|
+
pending.delete(timer);
|
|
721
|
+
resolve();
|
|
722
|
+
}
|
|
723
|
+
}, 0);
|
|
724
|
+
pending.set(timer, {
|
|
725
|
+
promise,
|
|
726
|
+
resolve
|
|
727
|
+
});
|
|
728
|
+
},
|
|
729
|
+
async finishBlocks() {
|
|
730
|
+
capturing = false;
|
|
731
|
+
await Promise.all([...pending.values()].map((task) => task.promise));
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
return new ReadableStream({
|
|
735
|
+
start(streamController) {
|
|
736
|
+
controller = streamController;
|
|
737
|
+
if (options.waitUntil) {
|
|
738
|
+
options.waitUntil(completed);
|
|
739
|
+
keepAlive = setInterval(() => writer.enqueue("<!--analog-render-pending-->"), 1e3);
|
|
740
|
+
}
|
|
741
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
742
|
+
if (options.signal?.aborted) abort();
|
|
743
|
+
(async () => {
|
|
744
|
+
try {
|
|
745
|
+
if (state === "rendering") await options.render(writer);
|
|
746
|
+
if (state === "rendering") {
|
|
747
|
+
state = "closing";
|
|
748
|
+
await destroy();
|
|
749
|
+
if (state === "closing") {
|
|
750
|
+
state = "closed";
|
|
751
|
+
controller.close();
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
} catch (error) {
|
|
755
|
+
fail(error);
|
|
756
|
+
} finally {
|
|
757
|
+
await destroy();
|
|
758
|
+
}
|
|
759
|
+
})().catch(fail);
|
|
760
|
+
},
|
|
761
|
+
cancel() {
|
|
762
|
+
state = "cancelled";
|
|
763
|
+
return destroy();
|
|
764
|
+
}
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
//#endregion
|
|
768
|
+
//#region packages/router/server/src/ssr-navigation.ts
|
|
769
|
+
/** Angular can settle initial navigation after an error without rejecting renderApplication. */
|
|
770
|
+
function createSsrNavigationTracker() {
|
|
771
|
+
let failure;
|
|
772
|
+
return {
|
|
773
|
+
provider: makeEnvironmentProviders([{
|
|
774
|
+
provide: ENVIRONMENT_INITIALIZER,
|
|
775
|
+
multi: true,
|
|
776
|
+
useValue() {
|
|
777
|
+
const router = inject(Router, { optional: true });
|
|
778
|
+
if (!router) return;
|
|
779
|
+
const subscription = router.events.subscribe((event) => {
|
|
780
|
+
if (event instanceof NavigationError) failure = event;
|
|
781
|
+
else if (event instanceof NavigationEnd) failure = void 0;
|
|
782
|
+
});
|
|
783
|
+
inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
|
|
784
|
+
}
|
|
785
|
+
}]),
|
|
786
|
+
throwIfFailed() {
|
|
787
|
+
if (failure) throw failure.error;
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
}
|
|
791
|
+
//#endregion
|
|
289
792
|
//#region packages/router/server/src/render-stream.ts
|
|
290
793
|
/**
|
|
291
794
|
* Progressive streaming SSR renderer — EXPERIMENTAL.
|
|
@@ -328,12 +831,23 @@ function streamingPrimitiveAvailable() {
|
|
|
328
831
|
* no-op.
|
|
329
832
|
*/
|
|
330
833
|
var captureStore = new AsyncLocalStorage();
|
|
834
|
+
var CAPTURE_ZONE_KEY = "analogSsrDeferCapture";
|
|
835
|
+
function currentCaptureZone() {
|
|
836
|
+
return globalThis.Zone?.current;
|
|
837
|
+
}
|
|
838
|
+
function runWithCapture(handler, render) {
|
|
839
|
+
const zone = currentCaptureZone();
|
|
840
|
+
return captureStore.run(handler, () => zone === void 0 ? render() : zone.fork({
|
|
841
|
+
name: "analog-ssr-capture",
|
|
842
|
+
properties: { [CAPTURE_ZONE_KEY]: handler }
|
|
843
|
+
}).run(render));
|
|
844
|
+
}
|
|
331
845
|
function installCaptureDispatcher() {
|
|
332
846
|
const g = globalThis;
|
|
333
847
|
if (g.__analogSsrDeferCapture?.__analogDispatcher) return;
|
|
334
|
-
const dispatch = (
|
|
335
|
-
captureStore.getStore()?.(ev);
|
|
336
|
-
}
|
|
848
|
+
const dispatch = (ev) => {
|
|
849
|
+
(currentCaptureZone()?.get(CAPTURE_ZONE_KEY) ?? captureStore.getStore())?.(ev);
|
|
850
|
+
};
|
|
337
851
|
dispatch.__analogDispatcher = true;
|
|
338
852
|
g.__analogSsrDeferCapture = dispatch;
|
|
339
853
|
}
|
|
@@ -349,15 +863,20 @@ function serializeLContainerHtml(lContainer) {
|
|
|
349
863
|
const nodes = [];
|
|
350
864
|
collect(lContainer, nodes);
|
|
351
865
|
let html = "";
|
|
352
|
-
for (const
|
|
866
|
+
for (const node of nodes) if (node.nodeType === 1) html += node.outerHTML ?? "";
|
|
867
|
+
else if (node.nodeType === 3) html += (node.data ?? node.nodeValue ?? "").replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
353
868
|
return html;
|
|
354
869
|
}
|
|
355
870
|
/** Destroy the platform on a macrotask, matching `renderApplication`. */
|
|
356
871
|
function asyncDestroyPlatform(platformRef) {
|
|
357
|
-
return new Promise((resolve) => {
|
|
872
|
+
return new Promise((resolve, reject) => {
|
|
358
873
|
setTimeout(() => {
|
|
359
|
-
|
|
360
|
-
|
|
874
|
+
try {
|
|
875
|
+
platformRef.destroy();
|
|
876
|
+
resolve();
|
|
877
|
+
} catch (error) {
|
|
878
|
+
reject(error);
|
|
879
|
+
}
|
|
361
880
|
}, 0);
|
|
362
881
|
});
|
|
363
882
|
}
|
|
@@ -371,88 +890,82 @@ function asyncDestroyPlatform(platformRef) {
|
|
|
371
890
|
* ```
|
|
372
891
|
*/
|
|
373
892
|
function renderStream(rootComponent, config, platformProviders = []) {
|
|
374
|
-
function bootstrap(context) {
|
|
375
|
-
return bootstrapApplication(rootComponent, config, context);
|
|
376
|
-
}
|
|
377
893
|
return async function renderStream(url, document, serverContext) {
|
|
894
|
+
serverContext.signal?.throwIfAborted();
|
|
895
|
+
const navigation = createSsrNavigationTracker();
|
|
896
|
+
const applicationConfig = {
|
|
897
|
+
...config,
|
|
898
|
+
providers: [...config.providers, navigation.provider]
|
|
899
|
+
};
|
|
900
|
+
const bootstrap = (context) => bootstrapApplication(rootComponent, applicationConfig, context);
|
|
378
901
|
resetComponentDefTViews();
|
|
379
902
|
const primitiveAvailable = streamingPrimitiveAvailable();
|
|
380
903
|
const bot = isLikelyBot(serverContext);
|
|
381
904
|
const routeDisabled = streamingDisabledByRoute(serverContext);
|
|
382
905
|
if (bot || routeDisabled || !primitiveAvailable) {
|
|
383
906
|
if (!bot && !routeDisabled && !primitiveAvailable) warnMissingPrimitiveOnce();
|
|
384
|
-
const html = await renderApplication(
|
|
907
|
+
const html = await renderApplication(bootstrap, {
|
|
385
908
|
document,
|
|
386
909
|
url,
|
|
387
910
|
platformProviders: [provideServerContext(serverContext), platformProviders]
|
|
388
911
|
});
|
|
912
|
+
navigation.throwIfFailed();
|
|
389
913
|
return new ReadableStream({ start(controller) {
|
|
390
914
|
controller.enqueue(new TextEncoder().encode(html));
|
|
391
915
|
controller.close();
|
|
392
916
|
} });
|
|
393
917
|
}
|
|
394
918
|
installCaptureDispatcher();
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
appRef = await bootstrap({ platformRef });
|
|
919
|
+
const platformRef = platformServer([
|
|
920
|
+
{
|
|
921
|
+
provide: INITIAL_CONFIG,
|
|
922
|
+
useValue: {
|
|
923
|
+
document,
|
|
924
|
+
url
|
|
925
|
+
}
|
|
926
|
+
},
|
|
927
|
+
provideServerContext(serverContext),
|
|
928
|
+
platformProviders
|
|
929
|
+
]);
|
|
930
|
+
let shell;
|
|
931
|
+
try {
|
|
932
|
+
shell = createStreamShell(platformRef);
|
|
933
|
+
} catch (error) {
|
|
934
|
+
await asyncDestroyPlatform(platformRef);
|
|
935
|
+
throw error;
|
|
936
|
+
}
|
|
937
|
+
return createSsrStream({
|
|
938
|
+
signal: serverContext.signal,
|
|
939
|
+
waitUntil: serverContext.waitUntil,
|
|
940
|
+
errorHtml: serverContext.renderErrorsAsHtml ? "<script data-analog-error>window.__analogFail&&window.__analogFail();<\/script></body></html>" : void 0,
|
|
941
|
+
destroy: () => asyncDestroyPlatform(platformRef),
|
|
942
|
+
async render(writer) {
|
|
943
|
+
let blockIndex = 0;
|
|
944
|
+
const seen = /* @__PURE__ */ new Set();
|
|
945
|
+
const onBlockResolved = (event) => {
|
|
946
|
+
if (!writer.active || seen.has(event.lContainer)) return;
|
|
947
|
+
seen.add(event.lContainer);
|
|
948
|
+
const id = `s${blockIndex++}`;
|
|
949
|
+
writer.scheduleBlock(() => `<template data-analog-defer="${id}">${serializeLContainerHtml(event.lContainer)}</template><script>window.__analogPaint&&window.__analogPaint(${JSON.stringify(id)})<\/script>`);
|
|
950
|
+
};
|
|
951
|
+
await runWithCapture(onBlockResolved, async () => {
|
|
952
|
+
writer.enqueue(shell + `<script>${DEFER_RECONCILE_RUNTIME}<\/script><div data-analog-stream></div>`);
|
|
953
|
+
const appRef = await bootstrap({ platformRef });
|
|
954
|
+
if (!writer.active) return;
|
|
430
955
|
await appRef.whenStable();
|
|
431
|
-
|
|
432
|
-
|
|
956
|
+
if (!writer.active) return;
|
|
957
|
+
navigation.throwIfFailed();
|
|
958
|
+
await writer.finishBlocks();
|
|
959
|
+
if (!writer.active) return;
|
|
433
960
|
const authoritative = await ɵrenderInternal(platformRef, appRef);
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
} finally {
|
|
440
|
-
await asyncDestroyPlatform(platformRef);
|
|
441
|
-
if (!errored) controller.close();
|
|
442
|
-
}
|
|
443
|
-
});
|
|
444
|
-
} });
|
|
961
|
+
navigation.throwIfFailed();
|
|
962
|
+
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>`);
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
});
|
|
445
966
|
};
|
|
446
967
|
}
|
|
447
968
|
//#endregion
|
|
448
|
-
//#region packages/router/server/src/server-fn/registry.ts
|
|
449
|
-
/**
|
|
450
|
-
* Server-side registry of server functions, keyed by id. A `.server.ts` module
|
|
451
|
-
* populates it as a side effect of `serverFn(...)` running at import time; the
|
|
452
|
-
* Nitro dispatch route imports those modules to fill it, then looks up by id.
|
|
453
|
-
*/
|
|
454
|
-
var serverFnRegistry = /* @__PURE__ */ new Map();
|
|
455
|
-
//#endregion
|
|
456
969
|
//#region packages/router/server/src/server-fn/server-fn.ts
|
|
457
970
|
function serverFn(arg1, arg2) {
|
|
458
971
|
const { config, handler } = normalizeArgs(arg1, arg2);
|
|
@@ -517,250 +1030,6 @@ async function createServerFnAppInjector(configOrProviders = []) {
|
|
|
517
1030
|
return (await createApplication(Array.isArray(configOrProviders) ? { providers: [provideServerRendering(), ...configOrProviders] } : configOrProviders, { platformRef: platformServer() })).injector;
|
|
518
1031
|
}
|
|
519
1032
|
//#endregion
|
|
520
|
-
//#region packages/router/server/src/server-fn/node-context.ts
|
|
521
|
-
/**
|
|
522
|
-
* Dispatch provides the Node request and response through `REQUEST` and
|
|
523
|
-
* `RESPONSE`, which are typed as Node primitives, so server functions only run
|
|
524
|
-
* on a Node runtime. h3 leaves `node` undefined on other runtimes.
|
|
525
|
-
*/
|
|
526
|
-
function assertNodeContext(event) {
|
|
527
|
-
const node = event.node;
|
|
528
|
-
if (!node?.req || !node.res) throw new Error("@analogjs/router: server functions require a Node runtime.");
|
|
529
|
-
return node;
|
|
530
|
-
}
|
|
531
|
-
//#endregion
|
|
532
|
-
//#region packages/router/server/src/server-fn/interceptors.ts
|
|
533
|
-
var SERVER_FN_INTERCEPTORS = new InjectionToken("SERVER_FN_INTERCEPTORS");
|
|
534
|
-
/** `withServerFnInterceptors([...])` — registers the chain (DI, ordered). */
|
|
535
|
-
function withServerFnInterceptors(interceptors) {
|
|
536
|
-
return { providers: interceptors.map((fn) => ({
|
|
537
|
-
provide: SERVER_FN_INTERCEPTORS,
|
|
538
|
-
useValue: fn,
|
|
539
|
-
multi: true
|
|
540
|
-
})) };
|
|
541
|
-
}
|
|
542
|
-
/** `provideServerFns(withServerFnInterceptors(...))` — mirrors provideHttpClient. */
|
|
543
|
-
function provideServerFns(...features) {
|
|
544
|
-
return features.flatMap((f) => f.providers);
|
|
545
|
-
}
|
|
546
|
-
function makeCtx(input, context) {
|
|
547
|
-
return {
|
|
548
|
-
input,
|
|
549
|
-
context,
|
|
550
|
-
with(patch) {
|
|
551
|
-
return makeCtx(input, {
|
|
552
|
-
...context,
|
|
553
|
-
...patch
|
|
554
|
-
});
|
|
555
|
-
}
|
|
556
|
-
};
|
|
557
|
-
}
|
|
558
|
-
/**
|
|
559
|
-
* Run the interceptor chain, then the handler, threading the context.
|
|
560
|
-
*
|
|
561
|
-
* `runInCtx` re-establishes the DI injection context around each interceptor
|
|
562
|
-
* and the handler individually. This is what keeps `inject()` working in a
|
|
563
|
-
* handler even when an upstream interceptor `await`s before calling `next`
|
|
564
|
-
* (which would otherwise resume outside Angular's synchronous injection
|
|
565
|
-
* context). It defaults to a pass-through for non-DI callers/tests.
|
|
566
|
-
*/
|
|
567
|
-
async function runInterceptors(interceptors, input, handler, runInCtx = (fn) => fn()) {
|
|
568
|
-
let i = -1;
|
|
569
|
-
const dispatch = async (ctx) => {
|
|
570
|
-
i += 1;
|
|
571
|
-
if (i < interceptors.length) return runInCtx(() => interceptors[i](ctx, dispatch));
|
|
572
|
-
return runInCtx(() => handler(ctx.input, ctx.context));
|
|
573
|
-
};
|
|
574
|
-
return dispatch(makeCtx(input, {}));
|
|
575
|
-
}
|
|
576
|
-
//#endregion
|
|
577
|
-
//#region packages/router/server/src/server-fn/same-origin.ts
|
|
578
|
-
/**
|
|
579
|
-
* Same-origin enforcement for the server-function HTTP transport.
|
|
580
|
-
*
|
|
581
|
-
* Server functions are same-origin RPC: a client proxy only ever calls the
|
|
582
|
-
* relative `/_analog/fn/:id` URL of its own app. A cross-origin page must not be
|
|
583
|
-
* able to invoke them against a logged-in user (a CSRF-shaped attack), so the
|
|
584
|
-
* transport rejects browser requests whose origin is not the app's own — out of
|
|
585
|
-
* the box, with no per-app configuration.
|
|
586
|
-
*
|
|
587
|
-
* The signals used (`Sec-Fetch-Site`, `Origin`) are added by the browser and
|
|
588
|
-
* cannot be forged by a cross-origin page's `fetch`. Non-browser callers (curl,
|
|
589
|
-
* server-to-server, SSR in-process) send neither, so they are unaffected: the
|
|
590
|
-
* guard blocks the cross-origin browser attack it is meant to, and nothing else.
|
|
591
|
-
*/
|
|
592
|
-
/**
|
|
593
|
-
* Origins permitted beyond the app's own, registered through DI:
|
|
594
|
-
* `provideServerFns(withAllowedOrigins([...]))`. Empty by default — the
|
|
595
|
-
* transport is same-origin unless an app opts out explicitly.
|
|
596
|
-
*/
|
|
597
|
-
var SERVER_FN_ALLOWED_ORIGINS = new InjectionToken("SERVER_FN_ALLOWED_ORIGINS");
|
|
598
|
-
/**
|
|
599
|
-
* `withAllowedOrigins([...])` — permit cross-origin browser calls from the
|
|
600
|
-
* listed origins, or pass `'*'` to disable the same-origin guard entirely.
|
|
601
|
-
* Server functions are frequently cookie-authenticated, so this is an explicit
|
|
602
|
-
* opt-out of CSRF protection: allow-list the exact origins you control.
|
|
603
|
-
*/
|
|
604
|
-
function withAllowedOrigins(origins) {
|
|
605
|
-
return { providers: origins.map((origin) => ({
|
|
606
|
-
provide: SERVER_FN_ALLOWED_ORIGINS,
|
|
607
|
-
useValue: origin,
|
|
608
|
-
multi: true
|
|
609
|
-
})) };
|
|
610
|
-
}
|
|
611
|
-
function firstHeader(value) {
|
|
612
|
-
return Array.isArray(value) ? value[0] : value;
|
|
613
|
-
}
|
|
614
|
-
/**
|
|
615
|
-
* Whether an HTTP request to a server function may proceed.
|
|
616
|
-
*
|
|
617
|
-
* Allowed when the request is same-origin, carries no browser-origin signal at
|
|
618
|
-
* all (a non-browser client, or a same-origin GET that omits `Origin`), or its
|
|
619
|
-
* `Origin` is listed in `allowedOrigins`. Passing `'*'` in `allowedOrigins`
|
|
620
|
-
* disables the check — the explicit opt-in to cross-origin access.
|
|
621
|
-
*
|
|
622
|
-
* `Sec-Fetch-Site` is the authoritative signal when present: `same-origin` and
|
|
623
|
-
* `none` (a direct navigation, not a cross-site fetch) pass; `same-site` and
|
|
624
|
-
* `cross-site` require an explicit `allowedOrigins` entry. When the header is
|
|
625
|
-
* absent (older browsers, some proxies) the `Origin` host is compared to the
|
|
626
|
-
* request host as a fallback.
|
|
627
|
-
*/
|
|
628
|
-
function isServerFnOriginAllowed(headers, allowedOrigins = []) {
|
|
629
|
-
if (allowedOrigins.includes("*")) return true;
|
|
630
|
-
const origin = firstHeader(headers["origin"]);
|
|
631
|
-
const originAllowlisted = origin !== void 0 && allowedOrigins.includes(origin);
|
|
632
|
-
const site = firstHeader(headers["sec-fetch-site"]);
|
|
633
|
-
if (site) {
|
|
634
|
-
if (site === "same-origin" || site === "none") return true;
|
|
635
|
-
return originAllowlisted;
|
|
636
|
-
}
|
|
637
|
-
if (!origin) return true;
|
|
638
|
-
if (originAllowlisted) return true;
|
|
639
|
-
const host = firstHeader(headers["x-forwarded-host"]) ?? firstHeader(headers["host"]);
|
|
640
|
-
if (!host) return false;
|
|
641
|
-
try {
|
|
642
|
-
return new URL(origin).host === host;
|
|
643
|
-
} catch {
|
|
644
|
-
return false;
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
//#endregion
|
|
648
|
-
//#region packages/router/server/src/server-fn/dispatch.ts
|
|
649
|
-
/**
|
|
650
|
-
* Server-side dispatch for a server function call.
|
|
651
|
-
*
|
|
652
|
-
* 1. reject cross-origin browser calls (403), unless allow-listed — HTTP
|
|
653
|
-
* transport only (in-process callers omit `method` and are exempt)
|
|
654
|
-
* 2. look up the function by id
|
|
655
|
-
* 3. enforce the configured HTTP method (405 on mismatch)
|
|
656
|
-
* 4. require a JSON body on input-bearing calls (415 otherwise)
|
|
657
|
-
* 5. validate `input` against the Standard-Schema (4xx on failure)
|
|
658
|
-
* 6. build a per-request injector (REQUEST/RESPONSE + app providers)
|
|
659
|
-
* 7. run the interceptor chain, then the handler, re-entering
|
|
660
|
-
* `runInInjectionContext` at every hop so `inject()` works even after an
|
|
661
|
-
* interceptor `await`s before calling `next`
|
|
662
|
-
* 8. a `Response` returned by an interceptor/handler (`fail`/`redirect`)
|
|
663
|
-
* short-circuits with its status AND headers
|
|
664
|
-
*
|
|
665
|
-
* `options.method` is the request's HTTP method; when provided it is enforced
|
|
666
|
-
* against the function's configured method AND it turns on the same-origin
|
|
667
|
-
* guard. Transports (the generated Nitro handler) always pass it; trusted
|
|
668
|
-
* in-process callers may omit it, which also exempts them from the origin guard.
|
|
669
|
-
*/
|
|
670
|
-
async function dispatchServerFn(id, rawInput, event, options = {}) {
|
|
671
|
-
const { parent, providers = [], method, allowedOrigins = [] } = options;
|
|
672
|
-
const node = assertNodeContext(event);
|
|
673
|
-
const headers = node.req.headers ?? {};
|
|
674
|
-
if (method) {
|
|
675
|
-
if (!isServerFnOriginAllowed(headers, [...allowedOrigins, ...parent?.get(SERVER_FN_ALLOWED_ORIGINS, []) ?? []])) return {
|
|
676
|
-
status: 403,
|
|
677
|
-
body: { message: "Cross-origin server function call rejected" }
|
|
678
|
-
};
|
|
679
|
-
}
|
|
680
|
-
const def = serverFnRegistry.get(id);
|
|
681
|
-
if (!def) return {
|
|
682
|
-
status: 404,
|
|
683
|
-
body: { message: `Unknown server function: ${id}` }
|
|
684
|
-
};
|
|
685
|
-
if (method && method.toUpperCase() !== def.method) return {
|
|
686
|
-
status: 405,
|
|
687
|
-
body: { message: `Method ${method} not allowed for ${id}` },
|
|
688
|
-
headers: { Allow: def.method }
|
|
689
|
-
};
|
|
690
|
-
if (method && def.method === "POST" && !isJsonContentType(headers)) return {
|
|
691
|
-
status: 415,
|
|
692
|
-
body: { message: "Server functions accept an application/json body" }
|
|
693
|
-
};
|
|
694
|
-
let input = rawInput;
|
|
695
|
-
if (def.config.input) {
|
|
696
|
-
const result = await def.config.input["~standard"].validate(rawInput);
|
|
697
|
-
if ("issues" in result && result.issues) return {
|
|
698
|
-
status: 400,
|
|
699
|
-
body: { errors: result.issues }
|
|
700
|
-
};
|
|
701
|
-
input = result.value;
|
|
702
|
-
}
|
|
703
|
-
const req = node.req;
|
|
704
|
-
const locale = detectLocale(req);
|
|
705
|
-
const injector = Injector.create({
|
|
706
|
-
parent,
|
|
707
|
-
providers: [
|
|
708
|
-
{
|
|
709
|
-
provide: REQUEST,
|
|
710
|
-
useValue: node.req
|
|
711
|
-
},
|
|
712
|
-
{
|
|
713
|
-
provide: RESPONSE,
|
|
714
|
-
useValue: node.res
|
|
715
|
-
},
|
|
716
|
-
{
|
|
717
|
-
provide: BASE_URL,
|
|
718
|
-
useValue: getBaseUrl(req)
|
|
719
|
-
},
|
|
720
|
-
...locale ? [{
|
|
721
|
-
provide: LOCALE,
|
|
722
|
-
useValue: locale
|
|
723
|
-
}] : [],
|
|
724
|
-
...providers
|
|
725
|
-
]
|
|
726
|
-
});
|
|
727
|
-
const runInCtx = (fn) => runInInjectionContext(injector, fn);
|
|
728
|
-
const outcome = await runInterceptors(injector.get(SERVER_FN_INTERCEPTORS, []), input, def.handler, runInCtx);
|
|
729
|
-
if (outcome instanceof Response) {
|
|
730
|
-
const text = await outcome.text();
|
|
731
|
-
const body = text ? safeJson(text) : null;
|
|
732
|
-
const headers = {};
|
|
733
|
-
outcome.headers.forEach((value, key) => {
|
|
734
|
-
if (key.toLowerCase() !== "set-cookie") headers[key] = value;
|
|
735
|
-
});
|
|
736
|
-
const setCookie = outcome.headers.getSetCookie?.() ?? [];
|
|
737
|
-
if (setCookie.length) headers["set-cookie"] = setCookie;
|
|
738
|
-
return {
|
|
739
|
-
status: outcome.status,
|
|
740
|
-
body,
|
|
741
|
-
headers: Object.keys(headers).length ? headers : void 0
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
return {
|
|
745
|
-
status: 200,
|
|
746
|
-
body: outcome
|
|
747
|
-
};
|
|
748
|
-
}
|
|
749
|
-
function isJsonContentType(headers) {
|
|
750
|
-
const contentType = headers["content-type"];
|
|
751
|
-
const value = Array.isArray(contentType) ? contentType[0] : contentType;
|
|
752
|
-
if (!value) return false;
|
|
753
|
-
const mediaType = value.split(";")[0].trim().toLowerCase();
|
|
754
|
-
return mediaType === "application/json" || mediaType.endsWith("+json");
|
|
755
|
-
}
|
|
756
|
-
function safeJson(text) {
|
|
757
|
-
try {
|
|
758
|
-
return JSON.parse(text);
|
|
759
|
-
} catch {
|
|
760
|
-
return text;
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
//#endregion
|
|
764
1033
|
//#region packages/router/server/src/server-fn/event-handler.ts
|
|
765
1034
|
/**
|
|
766
1035
|
* The h3 request/response layer for the server-function dispatch route.
|