@tanstack/start-server-core 1.121.10 → 1.121.14
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/dist/cjs/createStartHandler.cjs +128 -89
- package/dist/cjs/createStartHandler.cjs.map +1 -1
- package/dist/cjs/createStartHandler.d.cts +0 -3
- package/dist/cjs/serverRoute.cjs.map +1 -1
- package/dist/cjs/serverRoute.d.cts +2 -2
- package/dist/esm/createStartHandler.d.ts +0 -3
- package/dist/esm/createStartHandler.js +131 -92
- package/dist/esm/createStartHandler.js.map +1 -1
- package/dist/esm/serverRoute.d.ts +2 -2
- package/dist/esm/serverRoute.js.map +1 -1
- package/package.json +3 -3
- package/src/createStartHandler.ts +188 -128
- package/src/serverRoute.ts +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createMemoryHistory } from "@tanstack/history";
|
|
2
|
-
import { json,
|
|
3
|
-
import { joinPaths, trimPath, isRedirect, isResolvedRedirect,
|
|
2
|
+
import { json, mergeHeaders, flattenMiddlewares } from "@tanstack/start-client-core";
|
|
3
|
+
import { joinPaths, trimPath, processRouteTree, isRedirect, isResolvedRedirect, getMatchedRoutes } from "@tanstack/router-core";
|
|
4
4
|
import { requestHandler, getResponseHeaders } from "./h3.js";
|
|
5
5
|
import { attachRouterServerSsrUtils, dehydrateRouter } from "./ssr-server.js";
|
|
6
6
|
import { getStartManifest } from "./router-manifest.js";
|
|
@@ -8,7 +8,7 @@ import { handleServerAction } from "./server-functions-handler.js";
|
|
|
8
8
|
import { VIRTUAL_MODULES } from "./virtual-modules.js";
|
|
9
9
|
import { loadVirtualModule } from "./loadVirtualModule.js";
|
|
10
10
|
function getStartResponseHeaders(opts) {
|
|
11
|
-
|
|
11
|
+
const headers = mergeHeaders(
|
|
12
12
|
getResponseHeaders(),
|
|
13
13
|
{
|
|
14
14
|
"Content-Type": "text/html; charset=UTF-8"
|
|
@@ -17,16 +17,14 @@ function getStartResponseHeaders(opts) {
|
|
|
17
17
|
return match.headers;
|
|
18
18
|
})
|
|
19
19
|
);
|
|
20
|
-
const { redirect } = opts.router.state;
|
|
21
|
-
if (redirect) {
|
|
22
|
-
headers = mergeHeaders(headers, redirect.headers);
|
|
23
|
-
}
|
|
24
20
|
return headers;
|
|
25
21
|
}
|
|
26
22
|
function createStartHandler({
|
|
27
23
|
createRouter
|
|
28
24
|
}) {
|
|
29
|
-
let
|
|
25
|
+
let routeTreeModule = null;
|
|
26
|
+
let startRoutesManifest = null;
|
|
27
|
+
let processedServerRouteTree = void 0;
|
|
30
28
|
return (cb) => {
|
|
31
29
|
const originalFetch = globalThis.fetch;
|
|
32
30
|
const startRequestResolver = async ({ request }) => {
|
|
@@ -49,13 +47,11 @@ function createStartHandler({
|
|
|
49
47
|
};
|
|
50
48
|
const url = new URL(request.url);
|
|
51
49
|
const href = url.href.replace(url.origin, "");
|
|
50
|
+
const APP_BASE = process.env.TSS_APP_BASE || "/";
|
|
51
|
+
const router = createRouter();
|
|
52
52
|
const history = createMemoryHistory({
|
|
53
53
|
initialEntries: [href]
|
|
54
54
|
});
|
|
55
|
-
const APP_BASE = process.env.TSS_APP_BASE || "/";
|
|
56
|
-
const router = createRouter();
|
|
57
|
-
const startRoutesManifest = await getStartManifest({ basePath: APP_BASE });
|
|
58
|
-
attachRouterServerSsrUtils(router, startRoutesManifest);
|
|
59
55
|
router.update({
|
|
60
56
|
history
|
|
61
57
|
});
|
|
@@ -74,49 +70,75 @@ function createStartHandler({
|
|
|
74
70
|
if (href.startsWith(serverFnBase)) {
|
|
75
71
|
return await handleServerAction({ request });
|
|
76
72
|
}
|
|
77
|
-
if (
|
|
73
|
+
if (routeTreeModule === null) {
|
|
78
74
|
try {
|
|
79
|
-
|
|
75
|
+
routeTreeModule = await loadVirtualModule(
|
|
76
|
+
VIRTUAL_MODULES.routeTree
|
|
77
|
+
);
|
|
78
|
+
if (routeTreeModule.serverRouteTree) {
|
|
79
|
+
processedServerRouteTree = processRouteTree({
|
|
80
|
+
routeTree: routeTreeModule.serverRouteTree,
|
|
81
|
+
initRoute: (route, i) => {
|
|
82
|
+
route.init({
|
|
83
|
+
originalIndex: i
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
80
88
|
} catch (e) {
|
|
81
89
|
console.log(e);
|
|
82
90
|
}
|
|
83
91
|
}
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
|
|
92
|
+
async function executeRouter() {
|
|
93
|
+
const requestAcceptHeader = request.headers.get("Accept") || "*/*";
|
|
94
|
+
const splitRequestAcceptHeader = requestAcceptHeader.split(",");
|
|
95
|
+
const supportedMimeTypes = ["*/*", "text/html"];
|
|
96
|
+
const isRouterAcceptSupported = supportedMimeTypes.some(
|
|
97
|
+
(mimeType) => splitRequestAcceptHeader.some(
|
|
98
|
+
(acceptedMimeType) => acceptedMimeType.trim().startsWith(mimeType)
|
|
99
|
+
)
|
|
100
|
+
);
|
|
101
|
+
if (!isRouterAcceptSupported) {
|
|
102
|
+
return json(
|
|
103
|
+
{
|
|
104
|
+
error: "Only HTML requests are supported here"
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
status: 500
|
|
108
|
+
}
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
if (startRoutesManifest === null) {
|
|
112
|
+
startRoutesManifest = await getStartManifest({
|
|
113
|
+
basePath: APP_BASE
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
attachRouterServerSsrUtils(router, startRoutesManifest);
|
|
117
|
+
await router.load();
|
|
118
|
+
if (router.state.redirect) {
|
|
119
|
+
return router.state.redirect;
|
|
120
|
+
}
|
|
121
|
+
dehydrateRouter(router);
|
|
122
|
+
const responseHeaders = getStartResponseHeaders({ router });
|
|
123
|
+
const response2 = await cb({
|
|
87
124
|
request,
|
|
88
|
-
|
|
125
|
+
router,
|
|
126
|
+
responseHeaders
|
|
89
127
|
});
|
|
90
|
-
|
|
128
|
+
return response2;
|
|
91
129
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
return json(
|
|
102
|
-
{
|
|
103
|
-
error: "Only HTML requests are supported here"
|
|
104
|
-
},
|
|
105
|
-
{
|
|
106
|
-
status: 500
|
|
107
|
-
}
|
|
108
|
-
);
|
|
130
|
+
if (processedServerRouteTree) {
|
|
131
|
+
const [_matchedRoutes, response2] = await handleServerRoutes({
|
|
132
|
+
processedServerRouteTree,
|
|
133
|
+
router,
|
|
134
|
+
request,
|
|
135
|
+
basePath: APP_BASE,
|
|
136
|
+
executeRouter
|
|
137
|
+
});
|
|
138
|
+
if (response2) return response2;
|
|
109
139
|
}
|
|
110
|
-
await
|
|
111
|
-
|
|
112
|
-
dehydrateRouter(router);
|
|
113
|
-
const responseHeaders = getStartResponseHeaders({ router });
|
|
114
|
-
const response2 = await cb({
|
|
115
|
-
request,
|
|
116
|
-
router,
|
|
117
|
-
responseHeaders
|
|
118
|
-
});
|
|
119
|
-
return response2;
|
|
140
|
+
const routerResponse = await executeRouter();
|
|
141
|
+
return routerResponse;
|
|
120
142
|
} catch (err) {
|
|
121
143
|
if (err instanceof Response) {
|
|
122
144
|
return err;
|
|
@@ -172,60 +194,78 @@ function createStartHandler({
|
|
|
172
194
|
return requestHandler(startRequestResolver);
|
|
173
195
|
};
|
|
174
196
|
}
|
|
175
|
-
async function handleServerRoutes({
|
|
176
|
-
|
|
177
|
-
request
|
|
178
|
-
basePath
|
|
179
|
-
}) {
|
|
180
|
-
const { flatRoutes, routesById, routesByPath } = processRouteTree({
|
|
181
|
-
routeTree,
|
|
182
|
-
initRoute: (route, i) => {
|
|
183
|
-
route.init({
|
|
184
|
-
originalIndex: i
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
});
|
|
188
|
-
const url = new URL(request.url);
|
|
197
|
+
async function handleServerRoutes(opts) {
|
|
198
|
+
var _a, _b;
|
|
199
|
+
const url = new URL(opts.request.url);
|
|
189
200
|
const pathname = url.pathname;
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
const { matchedRoutes, foundRoute, routeParams } = getMatchedRoutes({
|
|
194
|
-
pathname: history.location.pathname,
|
|
195
|
-
basepath: basePath,
|
|
201
|
+
const serverTreeResult = getMatchedRoutes({
|
|
202
|
+
pathname,
|
|
203
|
+
basepath: opts.basePath,
|
|
196
204
|
caseSensitive: true,
|
|
197
|
-
routesByPath,
|
|
198
|
-
routesById,
|
|
199
|
-
flatRoutes
|
|
205
|
+
routesByPath: opts.processedServerRouteTree.routesByPath,
|
|
206
|
+
routesById: opts.processedServerRouteTree.routesById,
|
|
207
|
+
flatRoutes: opts.processedServerRouteTree.flatRoutes
|
|
200
208
|
});
|
|
209
|
+
const routeTreeResult = opts.router.getMatchedRoutes(pathname, void 0);
|
|
201
210
|
let response;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
)
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
211
|
+
let matchedRoutes = [];
|
|
212
|
+
matchedRoutes = serverTreeResult.matchedRoutes;
|
|
213
|
+
if (routeTreeResult.foundRoute) {
|
|
214
|
+
if (serverTreeResult.matchedRoutes.length < routeTreeResult.matchedRoutes.length) {
|
|
215
|
+
const closestCommon = [...routeTreeResult.matchedRoutes].reverse().find((r) => {
|
|
216
|
+
return opts.processedServerRouteTree.routesById[r.id] !== void 0;
|
|
217
|
+
});
|
|
218
|
+
if (closestCommon) {
|
|
219
|
+
let routeId = closestCommon.id;
|
|
220
|
+
matchedRoutes = [];
|
|
221
|
+
do {
|
|
222
|
+
const route = opts.processedServerRouteTree.routesById[routeId];
|
|
223
|
+
if (!route) {
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
matchedRoutes.push(route);
|
|
227
|
+
routeId = (_a = route.parentRoute) == null ? void 0 : _a.id;
|
|
228
|
+
} while (routeId);
|
|
229
|
+
matchedRoutes.reverse();
|
|
220
230
|
}
|
|
221
231
|
}
|
|
222
232
|
}
|
|
233
|
+
if (matchedRoutes.length) {
|
|
234
|
+
const middlewares = flattenMiddlewares(
|
|
235
|
+
matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean)
|
|
236
|
+
).map((d) => d.options.server);
|
|
237
|
+
if ((_b = serverTreeResult.foundRoute) == null ? void 0 : _b.options.methods) {
|
|
238
|
+
const method = Object.keys(
|
|
239
|
+
serverTreeResult.foundRoute.options.methods
|
|
240
|
+
).find(
|
|
241
|
+
(method2) => method2.toLowerCase() === opts.request.method.toLowerCase()
|
|
242
|
+
);
|
|
243
|
+
if (method) {
|
|
244
|
+
const handler = serverTreeResult.foundRoute.options.methods[method];
|
|
245
|
+
if (handler) {
|
|
246
|
+
middlewares.push(handlerToMiddleware(handler));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
middlewares.push(handlerToMiddleware(opts.executeRouter));
|
|
251
|
+
const ctx = await executeMiddleware(middlewares, {
|
|
252
|
+
request: opts.request,
|
|
253
|
+
context: {},
|
|
254
|
+
params: serverTreeResult.routeParams,
|
|
255
|
+
pathname
|
|
256
|
+
});
|
|
257
|
+
response = ctx.response;
|
|
258
|
+
}
|
|
223
259
|
return [matchedRoutes, response];
|
|
224
260
|
}
|
|
225
261
|
function handlerToMiddleware(handler) {
|
|
226
|
-
return async ({ next: _next, ...rest }) =>
|
|
227
|
-
response
|
|
228
|
-
|
|
262
|
+
return async ({ next: _next, ...rest }) => {
|
|
263
|
+
const response = await handler(rest);
|
|
264
|
+
if (response) {
|
|
265
|
+
return { response };
|
|
266
|
+
}
|
|
267
|
+
return _next(rest);
|
|
268
|
+
};
|
|
229
269
|
}
|
|
230
270
|
function executeMiddleware(middlewares, ctx) {
|
|
231
271
|
let index = -1;
|
|
@@ -268,7 +308,6 @@ function isResponse(response) {
|
|
|
268
308
|
return response instanceof Response;
|
|
269
309
|
}
|
|
270
310
|
export {
|
|
271
|
-
createStartHandler
|
|
272
|
-
getStartResponseHeaders
|
|
311
|
+
createStartHandler
|
|
273
312
|
};
|
|
274
313
|
//# sourceMappingURL=createStartHandler.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n flattenMiddlewares,\n json,\n mergeHeaders,\n} from '@tanstack/start-client-core'\nimport {\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n rootRouteId,\n trimPath,\n} from '@tanstack/router-core'\nimport { getResponseHeaders, requestHandler } from './h3'\nimport { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\nimport type { AnyServerRoute, AnyServerRouteWithTypes } from './serverRoute'\nimport type { RequestHandler } from './h3'\nimport type { AnyRouter } from '@tanstack/router-core'\nimport type { HandlerCallback } from './handlerCallback'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nexport function getStartResponseHeaders(opts: { router: AnyRouter }) {\n let headers = mergeHeaders(\n getResponseHeaders(),\n {\n 'Content-Type': 'text/html; charset=UTF-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n // Handle Redirects\n const { redirect } = opts.router.state\n\n if (redirect) {\n headers = mergeHeaders(headers, redirect.headers)\n }\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => TRouter\n}): CustomizeStartHandler<TRouter> {\n let serverRouteTree: AnyServerRoute | undefined | null = null\n\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async ({ request }) => {\n // Patching fetch function to use our request resolver\n // if the input starts with `/` which is a common pattern for\n // client-side routing.\n // When we encounter similar requests, we can assume that the\n // user wants to use the same origin as the current request.\n globalThis.fetch = async function (input, init) {\n function resolve(url: URL, requestOptions: RequestInit | undefined) {\n const fetchRequest = new Request(url, requestOptions)\n return startRequestResolver({ request: fetchRequest })\n }\n\n function getOrigin() {\n return (\n request.headers.get('Origin') ||\n request.headers.get('Referer') ||\n 'http://localhost'\n )\n }\n\n if (typeof input === 'string' && input.startsWith('/')) {\n // e.g: fetch('/api/data')\n const url = new URL(input, getOrigin())\n return resolve(url, init)\n } else if (\n typeof input === 'object' &&\n 'url' in input &&\n typeof input.url === 'string' &&\n input.url.startsWith('/')\n ) {\n // e.g: fetch(new Request('/api/data'))\n const url = new URL(input.url, getOrigin())\n return resolve(url, init)\n }\n\n // If not, it should just use the original fetch\n return originalFetch(input, init)\n }\n\n const url = new URL(request.url)\n const href = url.href.replace(url.origin, '')\n\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n const APP_BASE = process.env.TSS_APP_BASE || '/'\n\n // TODO do not create a router instance before we need it\n // Create the client-side router\n const router = createRouter()\n\n // TODO only build startRoutesManifest once, not per request\n // Attach the server-side SSR utils to the client-side router\n const startRoutesManifest = await getStartManifest({ basePath: APP_BASE })\n attachRouterServerSsrUtils(router, startRoutesManifest)\n\n // Update the client-side router with the history and context\n router.update({\n history,\n })\n\n const response = await (async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n APP_BASE,\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n if (serverRouteTree === null) {\n try {\n serverRouteTree = (\n await loadVirtualModule(VIRTUAL_MODULES.routeTree)\n ).serverRouteTree\n } catch (e) {\n console.log(e)\n }\n }\n\n // If we have a server route tree, then we try matching to see if we have a\n // server route that matches the request.\n if (serverRouteTree) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n routeTree: serverRouteTree,\n request,\n basePath: APP_BASE,\n })\n\n if (response) return response\n }\n\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some((mimeType) =>\n splitRequestAcceptHeader.some((acceptedMimeType) =>\n acceptedMimeType.trim().startsWith(mimeType),\n ),\n )\n\n if (!isRouterAcceptSupported) {\n return json(\n {\n error: 'Only HTML requests are supported here',\n },\n {\n status: 500,\n },\n )\n }\n\n // If no Server Routes were found, so fallback to normal SSR matching using\n // the router\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) return router.state.redirect\n\n dehydrateRouter(router)\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n\n throw err\n }\n })()\n\n if (isRedirect(response)) {\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n return response\n }\n if (\n response.options.to &&\n typeof response.options.to === 'string' &&\n !response.options.to.startsWith('/')\n ) {\n throw new Error(\n `Server side redirects must use absolute paths via the 'href' or 'to' options. Received: ${JSON.stringify(response.options)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (response.options as any)[d] === 'function',\n )\n ) {\n throw new Error(\n `Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(\n response.options,\n )\n .filter((d) => typeof (response.options as any)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n\n return redirect\n }\n\n return response\n }\n\n return requestHandler(startRequestResolver)\n }\n}\n\nasync function handleServerRoutes({\n routeTree,\n request,\n basePath,\n}: {\n routeTree: AnyServerRouteWithTypes\n request: Request\n basePath: string\n}) {\n // TODO only process server route tree once, not per request\n const { flatRoutes, routesById, routesByPath } = processRouteTree({\n routeTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n\n const url = new URL(request.url)\n const pathname = url.pathname\n\n // TODO history seems not to be needed, we can just use the pathname\n const history = createMemoryHistory({\n initialEntries: [pathname],\n })\n\n const { matchedRoutes, foundRoute, routeParams } =\n getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname: history.location.pathname,\n basepath: basePath,\n caseSensitive: true,\n routesByPath,\n routesById,\n flatRoutes,\n })\n\n let response: Response | undefined\n\n if (foundRoute && foundRoute.id !== rootRouteId) {\n // We've found a server route that matches the request, so we can call it.\n // TODO: Get the input type-signature correct\n // TODO: Perform the middlewares?\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const method = Object.keys(foundRoute.options.methods).find(\n (method) => method.toLowerCase() === request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = foundRoute.options.methods[method]\n\n if (handler) {\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n middlewares.push(handlerToMiddleware(handler) as TODO)\n\n // TODO: This is starting to feel too much like a server function\n // Do generalize the existing middleware execution? Or do we need to\n // build a new middleware execution system for server routes?\n const ctx = await executeMiddleware(middlewares, {\n request,\n context: {},\n params: routeParams,\n pathname: history.location.pathname,\n })\n\n response = ctx.response\n }\n }\n }\n\n // We return the matched routes too so if\n // the app router happens to match the same path,\n // it can use any request middleware from server routes\n return [matchedRoutes, response] as const\n}\n\nfunction handlerToMiddleware(\n handler: AnyServerRouteWithTypes['options']['methods'][string],\n) {\n return async ({ next: _next, ...rest }: TODO) => ({\n response: await handler(rest),\n })\n}\n\nfunction executeMiddleware(middlewares: TODO, ctx: TODO) {\n let index = -1\n\n const next = async (ctx: TODO) => {\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n const result = await middleware({\n ...ctx,\n // Allow the middleware to call the next middleware in the chain\n next: async (nextCtx: TODO) => {\n // Allow the caller to extend the context for the next middleware\n const nextResult = await next({ ...ctx, ...nextCtx })\n\n // Merge the result into the context\\\n return Object.assign(ctx, handleCtxResult(nextResult))\n },\n // Allow the middleware result to extend the return context\n }).catch((err: TODO) => {\n if (isSpecialResponse(err)) {\n return {\n response: err,\n }\n }\n\n throw err\n })\n\n // Merge the middleware result into the context, just in case it\n // returns a partial context\n return Object.assign(ctx, handleCtxResult(result))\n }\n\n return handleCtxResult(next(ctx))\n}\n\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return {\n response: result,\n }\n }\n\n return result\n}\n\nfunction isSpecialResponse(err: TODO) {\n return isResponse(err) || isRedirect(err)\n}\n\nfunction isResponse(response: Response): response is Response {\n return response instanceof Response\n}\n"],"names":["url","response","method","ctx"],"mappings":";;;;;;;;;AAgCO,SAAS,wBAAwB,MAA6B;AACnE,MAAI,UAAU;AAAA,IACZ,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AAEA,QAAM,EAAE,SAAA,IAAa,KAAK,OAAO;AAEjC,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|
1
|
+
{"version":3,"file":"createStartHandler.js","sources":["../../src/createStartHandler.ts"],"sourcesContent":["import { createMemoryHistory } from '@tanstack/history'\nimport {\n flattenMiddlewares,\n json,\n mergeHeaders,\n} from '@tanstack/start-client-core'\nimport {\n getMatchedRoutes,\n isRedirect,\n isResolvedRedirect,\n joinPaths,\n processRouteTree,\n trimPath,\n} from '@tanstack/router-core'\nimport { getResponseHeaders, requestHandler } from './h3'\nimport { attachRouterServerSsrUtils, dehydrateRouter } from './ssr-server'\nimport { getStartManifest } from './router-manifest'\nimport { handleServerAction } from './server-functions-handler'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\nimport type {\n AnyServerRoute,\n AnyServerRouteWithTypes,\n ServerRouteMethodHandlerFn,\n} from './serverRoute'\nimport type { RequestHandler } from './h3'\nimport type {\n AnyRoute,\n AnyRouter,\n Manifest,\n ProcessRouteTreeResult,\n} from '@tanstack/router-core'\nimport type { HandlerCallback } from './handlerCallback'\n\ntype TODO = any\n\nexport type CustomizeStartHandler<TRouter extends AnyRouter> = (\n cb: HandlerCallback<TRouter>,\n) => RequestHandler\n\nfunction getStartResponseHeaders(opts: { router: AnyRouter }) {\n const headers = mergeHeaders(\n getResponseHeaders(),\n {\n 'Content-Type': 'text/html; charset=UTF-8',\n },\n ...opts.router.state.matches.map((match) => {\n return match.headers\n }),\n )\n return headers\n}\n\nexport function createStartHandler<TRouter extends AnyRouter>({\n createRouter,\n}: {\n createRouter: () => TRouter\n}): CustomizeStartHandler<TRouter> {\n let routeTreeModule: {\n serverRouteTree: AnyServerRoute | undefined\n routeTree: AnyRoute | undefined\n } | null = null\n let startRoutesManifest: Manifest | null = null\n let processedServerRouteTree:\n | ProcessRouteTreeResult<AnyServerRouteWithTypes>\n | undefined = undefined\n\n return (cb) => {\n const originalFetch = globalThis.fetch\n\n const startRequestResolver: RequestHandler = async ({ request }) => {\n // Patching fetch function to use our request resolver\n // if the input starts with `/` which is a common pattern for\n // client-side routing.\n // When we encounter similar requests, we can assume that the\n // user wants to use the same origin as the current request.\n globalThis.fetch = async function (input, init) {\n function resolve(url: URL, requestOptions: RequestInit | undefined) {\n const fetchRequest = new Request(url, requestOptions)\n return startRequestResolver({ request: fetchRequest })\n }\n\n function getOrigin() {\n return (\n request.headers.get('Origin') ||\n request.headers.get('Referer') ||\n 'http://localhost'\n )\n }\n\n if (typeof input === 'string' && input.startsWith('/')) {\n // e.g: fetch('/api/data')\n const url = new URL(input, getOrigin())\n return resolve(url, init)\n } else if (\n typeof input === 'object' &&\n 'url' in input &&\n typeof input.url === 'string' &&\n input.url.startsWith('/')\n ) {\n // e.g: fetch(new Request('/api/data'))\n const url = new URL(input.url, getOrigin())\n return resolve(url, init)\n }\n\n // If not, it should just use the original fetch\n return originalFetch(input, init)\n }\n\n const url = new URL(request.url)\n const href = url.href.replace(url.origin, '')\n\n const APP_BASE = process.env.TSS_APP_BASE || '/'\n\n // TODO how does this work with base path? does the router need to be configured the same as APP_BASE?\n const router = createRouter()\n // Create a history for the client-side router\n const history = createMemoryHistory({\n initialEntries: [href],\n })\n\n // Update the client-side router with the history\n router.update({\n history,\n })\n\n const response = await (async () => {\n try {\n if (!process.env.TSS_SERVER_FN_BASE) {\n throw new Error(\n 'tanstack/start-server-core: TSS_SERVER_FN_BASE must be defined in your environment for createStartHandler()',\n )\n }\n\n // First, let's attempt to handle server functions\n // Add trailing slash to sanitise user defined TSS_SERVER_FN_BASE\n const serverFnBase = joinPaths([\n APP_BASE,\n trimPath(process.env.TSS_SERVER_FN_BASE),\n '/',\n ])\n if (href.startsWith(serverFnBase)) {\n return await handleServerAction({ request })\n }\n\n if (routeTreeModule === null) {\n try {\n routeTreeModule = await loadVirtualModule(\n VIRTUAL_MODULES.routeTree,\n )\n if (routeTreeModule.serverRouteTree) {\n processedServerRouteTree =\n processRouteTree<AnyServerRouteWithTypes>({\n routeTree: routeTreeModule.serverRouteTree,\n initRoute: (route, i) => {\n route.init({\n originalIndex: i,\n })\n },\n })\n }\n } catch (e) {\n console.log(e)\n }\n }\n\n async function executeRouter() {\n const requestAcceptHeader = request.headers.get('Accept') || '*/*'\n const splitRequestAcceptHeader = requestAcceptHeader.split(',')\n\n const supportedMimeTypes = ['*/*', 'text/html']\n const isRouterAcceptSupported = supportedMimeTypes.some(\n (mimeType) =>\n splitRequestAcceptHeader.some((acceptedMimeType) =>\n acceptedMimeType.trim().startsWith(mimeType),\n ),\n )\n\n if (!isRouterAcceptSupported) {\n return json(\n {\n error: 'Only HTML requests are supported here',\n },\n {\n status: 500,\n },\n )\n }\n\n // if the startRoutesManifest is not loaded yet, load it once\n if (startRoutesManifest === null) {\n startRoutesManifest = await getStartManifest({\n basePath: APP_BASE,\n })\n }\n\n // Attach the server-side SSR utils to the client-side router\n attachRouterServerSsrUtils(router, startRoutesManifest)\n\n await router.load()\n\n // If there was a redirect, skip rendering the page at all\n if (router.state.redirect) {\n return router.state.redirect\n }\n\n dehydrateRouter(router)\n\n const responseHeaders = getStartResponseHeaders({ router })\n const response = await cb({\n request,\n router,\n responseHeaders,\n })\n\n return response\n }\n\n // If we have a server route tree, then we try matching to see if we have a\n // server route that matches the request.\n if (processedServerRouteTree) {\n const [_matchedRoutes, response] = await handleServerRoutes({\n processedServerRouteTree,\n router,\n request,\n basePath: APP_BASE,\n executeRouter,\n })\n\n if (response) return response\n }\n\n // Server Routes did not produce a response, so fallback to normal SSR matching using the router\n const routerResponse = await executeRouter()\n return routerResponse\n } catch (err) {\n if (err instanceof Response) {\n return err\n }\n\n throw err\n }\n })()\n\n if (isRedirect(response)) {\n if (isResolvedRedirect(response)) {\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n return response\n }\n if (\n response.options.to &&\n typeof response.options.to === 'string' &&\n !response.options.to.startsWith('/')\n ) {\n throw new Error(\n `Server side redirects must use absolute paths via the 'href' or 'to' options. Received: ${JSON.stringify(response.options)}`,\n )\n }\n\n if (\n ['params', 'search', 'hash'].some(\n (d) => typeof (response.options as any)[d] === 'function',\n )\n ) {\n throw new Error(\n `Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(\n response.options,\n )\n .filter((d) => typeof (response.options as any)[d] === 'function')\n .map((d) => `\"${d}\"`)\n .join(', ')}`,\n )\n }\n\n const redirect = router.resolveRedirect(response)\n\n if (request.headers.get('x-tsr-redirect') === 'manual') {\n return json(\n {\n ...response.options,\n isSerializedRedirect: true,\n },\n {\n headers: response.headers,\n },\n )\n }\n\n return redirect\n }\n\n return response\n }\n\n return requestHandler(startRequestResolver)\n }\n}\n\nasync function handleServerRoutes(opts: {\n router: AnyRouter\n processedServerRouteTree: ProcessRouteTreeResult<AnyServerRouteWithTypes>\n request: Request\n basePath: string\n executeRouter: () => Promise<Response>\n}) {\n const url = new URL(opts.request.url)\n const pathname = url.pathname\n\n const serverTreeResult = getMatchedRoutes<AnyServerRouteWithTypes>({\n pathname,\n basepath: opts.basePath,\n caseSensitive: true,\n routesByPath: opts.processedServerRouteTree.routesByPath,\n routesById: opts.processedServerRouteTree.routesById,\n flatRoutes: opts.processedServerRouteTree.flatRoutes,\n })\n\n const routeTreeResult = opts.router.getMatchedRoutes(pathname, undefined)\n\n let response: Response | undefined\n let matchedRoutes: Array<AnyServerRouteWithTypes> = []\n matchedRoutes = serverTreeResult.matchedRoutes\n // check if the app route tree found a match that is deeper than the server route tree\n if (routeTreeResult.foundRoute) {\n if (\n serverTreeResult.matchedRoutes.length <\n routeTreeResult.matchedRoutes.length\n ) {\n const closestCommon = [...routeTreeResult.matchedRoutes]\n .reverse()\n .find((r) => {\n return opts.processedServerRouteTree.routesById[r.id] !== undefined\n })\n if (closestCommon) {\n // walk up the tree and collect all parents\n let routeId = closestCommon.id\n matchedRoutes = []\n do {\n const route = opts.processedServerRouteTree.routesById[routeId]\n if (!route) {\n break\n }\n matchedRoutes.push(route)\n routeId = route.parentRoute?.id\n } while (routeId)\n\n matchedRoutes.reverse()\n }\n }\n }\n\n if (matchedRoutes.length) {\n // We've found a server route that (partially) matches the request, so we can call it.\n // TODO: Error handling? What happens when its `throw redirect()` vs `throw new Error()`?\n\n const middlewares = flattenMiddlewares(\n matchedRoutes.flatMap((r) => r.options.middleware).filter(Boolean),\n ).map((d) => d.options.server)\n\n if (serverTreeResult.foundRoute?.options.methods) {\n const method = Object.keys(\n serverTreeResult.foundRoute.options.methods,\n ).find(\n (method) => method.toLowerCase() === opts.request.method.toLowerCase(),\n )\n\n if (method) {\n const handler = serverTreeResult.foundRoute.options.methods[method]\n\n if (handler) {\n middlewares.push(handlerToMiddleware(handler) as TODO)\n }\n }\n }\n\n // eventually, execute the router\n middlewares.push(handlerToMiddleware(opts.executeRouter))\n\n // TODO: This is starting to feel too much like a server function\n // Do generalize the existing middleware execution? Or do we need to\n // build a new middleware execution system for server routes?\n const ctx = await executeMiddleware(middlewares, {\n request: opts.request,\n context: {},\n params: serverTreeResult.routeParams,\n pathname,\n })\n\n response = ctx.response\n }\n\n // We return the matched routes too so if\n // the app router happens to match the same path,\n // it can use any request middleware from server routes\n return [matchedRoutes, response] as const\n}\n\nfunction handlerToMiddleware(\n handler: ServerRouteMethodHandlerFn<\n AnyServerRouteWithTypes,\n any,\n any,\n any,\n any\n >,\n) {\n return async ({ next: _next, ...rest }: TODO) => {\n const response = await handler(rest)\n if (response) {\n return { response }\n }\n return _next(rest)\n }\n}\n\nfunction executeMiddleware(middlewares: TODO, ctx: TODO) {\n let index = -1\n\n const next = async (ctx: TODO) => {\n index++\n const middleware = middlewares[index]\n if (!middleware) return ctx\n\n const result = await middleware({\n ...ctx,\n // Allow the middleware to call the next middleware in the chain\n next: async (nextCtx: TODO) => {\n // Allow the caller to extend the context for the next middleware\n const nextResult = await next({ ...ctx, ...nextCtx })\n\n // Merge the result into the context\\\n return Object.assign(ctx, handleCtxResult(nextResult))\n },\n // Allow the middleware result to extend the return context\n }).catch((err: TODO) => {\n if (isSpecialResponse(err)) {\n return {\n response: err,\n }\n }\n\n throw err\n })\n\n // Merge the middleware result into the context, just in case it\n // returns a partial context\n return Object.assign(ctx, handleCtxResult(result))\n }\n\n return handleCtxResult(next(ctx))\n}\n\nfunction handleCtxResult(result: TODO) {\n if (isSpecialResponse(result)) {\n return {\n response: result,\n }\n }\n\n return result\n}\n\nfunction isSpecialResponse(err: TODO) {\n return isResponse(err) || isRedirect(err)\n}\n\nfunction isResponse(response: Response): response is Response {\n return response instanceof Response\n}\n"],"names":["url","response","method","ctx"],"mappings":";;;;;;;;;AAwCA,SAAS,wBAAwB,MAA6B;AAC5D,QAAM,UAAU;AAAA,IACd,mBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IACA,GAAG,KAAK,OAAO,MAAM,QAAQ,IAAI,CAAC,UAAU;AAC1C,aAAO,MAAM;AAAA,IACd,CAAA;AAAA,EACH;AACO,SAAA;AACT;AAEO,SAAS,mBAA8C;AAAA,EAC5D;AACF,GAEmC;AACjC,MAAI,kBAGO;AACX,MAAI,sBAAuC;AAC3C,MAAI,2BAEY;AAEhB,SAAO,CAAC,OAAO;AACb,UAAM,gBAAgB,WAAW;AAEjC,UAAM,uBAAuC,OAAO,EAAE,cAAc;AAMvD,iBAAA,QAAQ,eAAgB,OAAO,MAAM;AACrC,iBAAA,QAAQA,MAAU,gBAAyC;AAClE,gBAAM,eAAe,IAAI,QAAQA,MAAK,cAAc;AACpD,iBAAO,qBAAqB,EAAE,SAAS,cAAc;AAAA,QAAA;AAGvD,iBAAS,YAAY;AAEjB,iBAAA,QAAQ,QAAQ,IAAI,QAAQ,KAC5B,QAAQ,QAAQ,IAAI,SAAS,KAC7B;AAAA,QAAA;AAIJ,YAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,GAAG;AAEtD,gBAAMA,OAAM,IAAI,IAAI,OAAO,WAAW;AAC/B,iBAAA,QAAQA,MAAK,IAAI;AAAA,QAExB,WAAA,OAAO,UAAU,YACjB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AAK,GAAG,CAAC;AAClC;AAEA,SAAS,gBAAgB,QAAc;AACjC,MAAA,kBAAkB,MAAM,GAAG;AACtB,WAAA;AAAA,MACL,UAAU;AAAA,IACZ;AAAA,EAAA;AAGK,SAAA;AACT;AAEA,SAAS,kBAAkB,KAAW;AACpC,SAAO,WAAW,GAAG,KAAK,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;"}
|
|
@@ -9,8 +9,8 @@ export interface ServerRouteOptions<TParentRoute extends AnyServerRouteWithTypes
|
|
|
9
9
|
pathname: TFullPath;
|
|
10
10
|
originalIndex: number;
|
|
11
11
|
getParentRoute?: () => TParentRoute;
|
|
12
|
-
middleware
|
|
13
|
-
methods
|
|
12
|
+
middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>;
|
|
13
|
+
methods?: Record<string, ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>>;
|
|
14
14
|
caseSensitive?: boolean;
|
|
15
15
|
}
|
|
16
16
|
export type ServerRouteManifest = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serverRoute.js","sources":["../../src/serverRoute.ts"],"sourcesContent":["import { joinPaths, rootRouteId, trimPathLeft } from '@tanstack/router-core'\nimport type {\n Assign,\n Constrain,\n Expand,\n ResolveParams,\n RouteConstraints,\n TrimPathRight,\n} from '@tanstack/router-core'\nimport type {\n AnyRequestMiddleware,\n AssignAllServerContext,\n} from '@tanstack/start-client-core'\n\nexport function createServerFileRoute<\n TFilePath extends keyof ServerFileRoutesByPath,\n TParentRoute extends\n AnyServerRouteWithTypes = ServerFileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = ServerFileRoutesByPath[TFilePath]['id'],\n TPath extends\n RouteConstraints['TPath'] = ServerFileRoutesByPath[TFilePath]['path'],\n TFullPath extends\n RouteConstraints['TFullPath'] = ServerFileRoutesByPath[TFilePath]['fullPath'],\n TChildren = ServerFileRoutesByPath[TFilePath]['children'],\n>(_: TFilePath): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n return createServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>(\n undefined,\n )\n}\n\nexport interface ServerFileRoutesByPath {}\n\nexport interface ServerRouteOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n> {\n id: TId\n path: TPath\n pathname: TFullPath\n originalIndex: number\n getParentRoute?: () => TParentRoute\n middleware: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>\n methods: Record<\n string,\n ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>\n >\n caseSensitive?: boolean\n}\n\nexport type ServerRouteManifest = {\n middleware: boolean\n methods: Record<string, { middleware: boolean }>\n}\n\nexport function createServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n>(\n __?: never,\n __opts?: Partial<\n ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>\n >,\n): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n const options = __opts || {}\n\n const route: ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> = {\n path: '' as TPath,\n id: '' as TId,\n fullPath: '' as TFullPath,\n to: '' as TrimPathRight<TFullPath>,\n options: options as ServerRouteOptions<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n any\n >,\n parentRoute: undefined as unknown as TParentRoute,\n _types: {} as ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined\n >,\n // children: undefined as TChildren,\n middleware: (middlewares) =>\n createServerRoute(undefined, {\n ...options,\n middleware: middlewares,\n }) as never,\n methods: (methodsOrGetMethods) => {\n const methods = (() => {\n if (typeof methodsOrGetMethods === 'function') {\n return methodsOrGetMethods(createMethodBuilder())\n }\n\n return methodsOrGetMethods\n })()\n\n return createServerRoute(undefined, {\n ...__opts,\n methods: methods as never,\n }) as never\n },\n update: (opts) =>\n createServerRoute(undefined, {\n ...options,\n ...opts,\n }),\n init: (opts: { originalIndex: number }): void => {\n options.originalIndex = opts.originalIndex\n\n const isRoot = !options.path && !options.id\n\n route.parentRoute = options.getParentRoute?.() as TParentRoute\n\n if (isRoot) {\n route.path = rootRouteId as TPath\n } else if (!(route.parentRoute as any)) {\n throw new Error(\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a ServerRoute instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPathLeft(path)\n }\n\n const customId = options.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n route.parentRoute.id === rootRouteId ? '' : route.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([route.parentRoute.fullPath, path])\n\n route.path = path as TPath\n route.id = id as TId\n route.fullPath = fullPath as TFullPath\n route.to = fullPath as TrimPathRight<TFullPath>\n },\n\n _addFileChildren: (children) => {\n if (Array.isArray(children)) {\n route.children = children as TChildren\n }\n\n if (typeof children === 'object' && children !== null) {\n route.children = Object.values(children) as TChildren\n }\n\n return route\n },\n\n _addFileTypes: <TFileTypes>() => route,\n }\n\n return route\n}\n\n// TODO this needs to be restricted to only allow middleware, no methods\n// TODO we also need to restrict pathless server routes to only allow middleware\nexport const createServerRootRoute = createServerRoute\n\nexport type ServerRouteAddFileChildrenFn<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TId extends RouteConstraints['TId'],\n in out TPath extends RouteConstraints['TPath'],\n in out TFullPath extends RouteConstraints['TFullPath'],\n in out TMiddlewares,\n in out TMethods,\n in out TChildren,\n> = (\n children: TChildren,\n) => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n>\n\nconst createMethodBuilder = <\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n>(\n __opts?: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n unknown,\n unknown\n >,\n): ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares> => {\n return {\n _options: (__opts || {}) as never,\n _types: {} as never,\n middleware: (middlewares) =>\n createMethodBuilder({\n ...__opts,\n middlewares,\n }) as never,\n handler: (handler) =>\n createMethodBuilder({\n ...__opts,\n handler: handler as never,\n }) as never,\n }\n}\n\nexport interface ServerRouteMethodBuilderOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n middlewares?: Constrain<\n TMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >\n}\n\nexport type CreateServerFileRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> = () => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n\nexport type AnyServerRouteWithTypes = ServerRouteWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> {\n _types: ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods\n >\n path: TPath\n id: TId\n fullPath: TFullPath\n to: TrimPathRight<TFullPath>\n parentRoute: TParentRoute\n children?: TChildren\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n update: (\n opts: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>,\n ) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n init: (opts: { originalIndex: number }) => void\n _addFileChildren: ServerRouteAddFileChildrenFn<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n _addFileTypes: () => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport interface ServerRouteTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n> {\n id: TId\n path: TPath\n fullPath: TFullPath\n middlewares: TMiddlewares\n methods: TMethods\n parentRoute: TParentRoute\n allContext: ResolveAllServerContext<TParentRoute, TMiddlewares>\n}\n\nexport type ResolveAllServerContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n> = unknown extends TParentRoute\n ? AssignAllServerContext<TMiddlewares>\n : Assign<\n TParentRoute['_types']['allContext'],\n AssignAllServerContext<TMiddlewares>\n >\n\nexport type AnyServerRoute = AnyServerRouteWithTypes\n\nexport interface ServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined,\n TChildren\n >,\n ServerRouteMiddleware<TParentRoute, TId, TPath, TFullPath, TChildren>,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n TChildren\n > {}\n\nexport interface ServerRouteMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> {\n middleware: <const TNewMiddleware>(\n middleware: Constrain<TNewMiddleware, ReadonlyArray<AnyRequestMiddleware>>,\n ) => ServerRouteAfterMiddleware<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TNewMiddleware,\n TChildren\n >\n}\n\nexport interface ServerRouteAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n undefined,\n TChildren\n >,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TChildren\n > {}\n\nexport interface ServerRouteMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> {\n methods: <const TMethods>(\n methodsOrGetMethods: Constrain<\n TMethods,\n ServerRouteMethodsOptions<TParentRoute, TFullPath, TMiddlewares>\n >,\n ) => ServerRouteAfterMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport type ServerRouteMethodsOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>\n | ((\n api: ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares>,\n ) => ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>)\n\nexport interface ServerRouteMethodsRecord<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n GET?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n POST?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PUT?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PATCH?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n DELETE?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n OPTIONS?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n HEAD?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n}\n\nexport type ServerRouteMethodRecordValue<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n any\n >\n | AnyRouteMethodsBuilder\n\nexport type ServerRouteVerb = (typeof ServerRouteVerbs)[number]\n\nexport const ServerRouteVerbs = [\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n] as const\n\nexport type ServerRouteMethodHandlerFn<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> = (\n ctx: ServerRouteMethodHandlerCtx<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >,\n) => TResponse | Promise<TResponse>\n\nexport interface ServerRouteMethodHandlerCtx<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n> {\n context: Expand<\n AssignAllMethodContext<TParentRoute, TMiddlewares, TMethodMiddlewares>\n >\n request: Request\n params: Expand<ResolveParams<TFullPath>>\n pathname: TFullPath\n}\n\nexport type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> =\n TMiddlewares extends ReadonlyArray<any>\n ? TMethodMiddlewares extends ReadonlyArray<any>\n ? readonly [...TMiddlewares, ...TMethodMiddlewares]\n : TMiddlewares\n : TMethodMiddlewares\n\nexport type AssignAllMethodContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n TMethodMiddlewares,\n> = ResolveAllServerContext<\n TParentRoute,\n MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>\n>\n\nexport type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteMethodBuilder<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n undefined\n >,\n ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined\n > {}\n\nexport interface ServerRouteMethodBuilderWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n _options: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n _types: ServerRouteMethodBuilderTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderTypes<\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n in out TResponse,\n> {\n middlewares: TMiddlewares\n methodMiddleware: TMethodMiddlewares\n fullPath: TFullPath\n response: TResponse\n}\n\nexport interface ServerRouteMethodBuilderMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n middleware: <const TNewMethodMiddlewares>(\n middleware: Constrain<\n TNewMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >,\n ) => ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TNewMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n > {}\n\nexport interface ServerRouteMethodBuilderHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n handler: <TResponse>(\n handler: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >,\n ) => ServerRouteMethodBuilderAfterHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n > {\n opts: ServerRouteMethod<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethod<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n middleware?: Constrain<TMiddlewares, Array<AnyRequestMiddleware>>\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >\n}\n\nexport interface ServerRouteAfterMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n > {\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n}\n"],"names":[],"mappings":";AAcO,SAAS,sBAUd,GAA2E;AACpE,SAAA,kBAEP;AACF;AA6BgB,SAAA,kBAOd,IACA,QAG6D;AACvD,QAAA,UAAU,UAAU,CAAC;AAE3B,QAAM,QAAqE;AAAA,IACzE,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,IAAI;AAAA,IACJ;AAAA,IAOA,aAAa;AAAA,IACb,QAAQ,CAAC;AAAA;AAAA,IAST,YAAY,CAAC,gBACX,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,MACH,YAAY;AAAA,IAAA,CACb;AAAA,IACH,SAAS,CAAC,wBAAwB;AAChC,YAAM,WAAW,MAAM;AACjB,YAAA,OAAO,wBAAwB,YAAY;AACtC,iBAAA,oBAAoB,qBAAqB;AAAA,QAAA;AAG3C,eAAA;AAAA,MAAA,GACN;AAEH,aAAO,kBAAkB,QAAW;AAAA,QAClC,GAAG;AAAA,QACH;AAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,QAAQ,CAAC,SACP,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,MACH,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,MAAM,CAAC,SAA0C;;AAC/C,cAAQ,gBAAgB,KAAK;AAE7B,YAAM,SAAS,CAAC,QAAQ,QAAQ,CAAC,QAAQ;AAEnC,YAAA,eAAc,aAAQ,mBAAR;AAEpB,UAAI,QAAQ;AACV,cAAM,OAAO;AAAA,MAAA,WACJ,CAAE,MAAM,aAAqB;AACtC,cAAM,IAAI;AAA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aths, rootRouteId, trimPathLeft } from '@tanstack/router-core'\nimport type {\n Assign,\n Constrain,\n Expand,\n ResolveParams,\n RouteConstraints,\n TrimPathRight,\n} from '@tanstack/router-core'\nimport type {\n AnyRequestMiddleware,\n AssignAllServerContext,\n} from '@tanstack/start-client-core'\n\nexport function createServerFileRoute<\n TFilePath extends keyof ServerFileRoutesByPath,\n TParentRoute extends\n AnyServerRouteWithTypes = ServerFileRoutesByPath[TFilePath]['parentRoute'],\n TId extends RouteConstraints['TId'] = ServerFileRoutesByPath[TFilePath]['id'],\n TPath extends\n RouteConstraints['TPath'] = ServerFileRoutesByPath[TFilePath]['path'],\n TFullPath extends\n RouteConstraints['TFullPath'] = ServerFileRoutesByPath[TFilePath]['fullPath'],\n TChildren = ServerFileRoutesByPath[TFilePath]['children'],\n>(_: TFilePath): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n return createServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>(\n undefined,\n )\n}\n\nexport interface ServerFileRoutesByPath {}\n\nexport interface ServerRouteOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n> {\n id: TId\n path: TPath\n pathname: TFullPath\n originalIndex: number\n getParentRoute?: () => TParentRoute\n middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>\n methods?: Record<\n string,\n ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any>\n >\n caseSensitive?: boolean\n}\n\nexport type ServerRouteManifest = {\n middleware: boolean\n methods: Record<string, { middleware: boolean }>\n}\n\nexport function createServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n>(\n __?: never,\n __opts?: Partial<\n ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>\n >,\n): ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> {\n const options = __opts || {}\n\n const route: ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren> = {\n path: '' as TPath,\n id: '' as TId,\n fullPath: '' as TFullPath,\n to: '' as TrimPathRight<TFullPath>,\n options: options as ServerRouteOptions<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n any\n >,\n parentRoute: undefined as unknown as TParentRoute,\n _types: {} as ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined\n >,\n // children: undefined as TChildren,\n middleware: (middlewares) =>\n createServerRoute(undefined, {\n ...options,\n middleware: middlewares,\n }) as never,\n methods: (methodsOrGetMethods) => {\n const methods = (() => {\n if (typeof methodsOrGetMethods === 'function') {\n return methodsOrGetMethods(createMethodBuilder())\n }\n\n return methodsOrGetMethods\n })()\n\n return createServerRoute(undefined, {\n ...__opts,\n methods: methods as never,\n }) as never\n },\n update: (opts) =>\n createServerRoute(undefined, {\n ...options,\n ...opts,\n }),\n init: (opts: { originalIndex: number }): void => {\n options.originalIndex = opts.originalIndex\n\n const isRoot = !options.path && !options.id\n\n route.parentRoute = options.getParentRoute?.() as TParentRoute\n\n if (isRoot) {\n route.path = rootRouteId as TPath\n } else if (!(route.parentRoute as any)) {\n throw new Error(\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a ServerRoute instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPathLeft(path)\n }\n\n const customId = options.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n route.parentRoute.id === rootRouteId ? '' : route.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([route.parentRoute.fullPath, path])\n\n route.path = path as TPath\n route.id = id as TId\n route.fullPath = fullPath as TFullPath\n route.to = fullPath as TrimPathRight<TFullPath>\n },\n\n _addFileChildren: (children) => {\n if (Array.isArray(children)) {\n route.children = children as TChildren\n }\n\n if (typeof children === 'object' && children !== null) {\n route.children = Object.values(children) as TChildren\n }\n\n return route\n },\n\n _addFileTypes: <TFileTypes>() => route,\n }\n\n return route\n}\n\n// TODO this needs to be restricted to only allow middleware, no methods\n// TODO we also need to restrict pathless server routes to only allow middleware\nexport const createServerRootRoute = createServerRoute\n\nexport type ServerRouteAddFileChildrenFn<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TId extends RouteConstraints['TId'],\n in out TPath extends RouteConstraints['TPath'],\n in out TFullPath extends RouteConstraints['TFullPath'],\n in out TMiddlewares,\n in out TMethods,\n in out TChildren,\n> = (\n children: TChildren,\n) => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n>\n\nconst createMethodBuilder = <\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n>(\n __opts?: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n unknown,\n unknown\n >,\n): ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares> => {\n return {\n _options: (__opts || {}) as never,\n _types: {} as never,\n middleware: (middlewares) =>\n createMethodBuilder({\n ...__opts,\n middlewares,\n }) as never,\n handler: (handler) =>\n createMethodBuilder({\n ...__opts,\n handler: handler as never,\n }) as never,\n }\n}\n\nexport interface ServerRouteMethodBuilderOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n middlewares?: Constrain<\n TMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >\n}\n\nexport type CreateServerFileRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> = () => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n\nexport type AnyServerRouteWithTypes = ServerRouteWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> {\n _types: ServerRouteTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods\n >\n path: TPath\n id: TId\n fullPath: TFullPath\n to: TrimPathRight<TFullPath>\n parentRoute: TParentRoute\n children?: TChildren\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n update: (\n opts: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, undefined>,\n ) => ServerRoute<TParentRoute, TId, TPath, TFullPath, TChildren>\n init: (opts: { originalIndex: number }) => void\n _addFileChildren: ServerRouteAddFileChildrenFn<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n _addFileTypes: () => ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport interface ServerRouteTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n> {\n id: TId\n path: TPath\n fullPath: TFullPath\n middlewares: TMiddlewares\n methods: TMethods\n parentRoute: TParentRoute\n allContext: ResolveAllServerContext<TParentRoute, TMiddlewares>\n}\n\nexport type ResolveAllServerContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n> = unknown extends TParentRoute\n ? AssignAllServerContext<TMiddlewares>\n : Assign<\n TParentRoute['_types']['allContext'],\n AssignAllServerContext<TMiddlewares>\n >\n\nexport type AnyServerRoute = AnyServerRouteWithTypes\n\nexport interface ServerRoute<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n undefined,\n TChildren\n >,\n ServerRouteMiddleware<TParentRoute, TId, TPath, TFullPath, TChildren>,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n undefined,\n TChildren\n > {}\n\nexport interface ServerRouteMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TChildren,\n> {\n middleware: <const TNewMiddleware>(\n middleware: Constrain<TNewMiddleware, ReadonlyArray<AnyRequestMiddleware>>,\n ) => ServerRouteAfterMiddleware<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TNewMiddleware,\n TChildren\n >\n}\n\nexport interface ServerRouteAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n undefined,\n TChildren\n >,\n ServerRouteMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TChildren\n > {}\n\nexport interface ServerRouteMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TChildren,\n> {\n methods: <const TMethods>(\n methodsOrGetMethods: Constrain<\n TMethods,\n ServerRouteMethodsOptions<TParentRoute, TFullPath, TMiddlewares>\n >,\n ) => ServerRouteAfterMethods<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n >\n}\n\nexport type ServerRouteMethodsOptions<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>\n | ((\n api: ServerRouteMethodBuilder<TParentRoute, TFullPath, TMiddlewares>,\n ) => ServerRouteMethodsRecord<TParentRoute, TFullPath, TMiddlewares>)\n\nexport interface ServerRouteMethodsRecord<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n GET?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n POST?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PUT?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n PATCH?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n DELETE?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n OPTIONS?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n HEAD?: ServerRouteMethodRecordValue<TParentRoute, TFullPath, TMiddlewares>\n}\n\nexport type ServerRouteMethodRecordValue<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> =\n | ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n any\n >\n | AnyRouteMethodsBuilder\n\nexport type ServerRouteVerb = (typeof ServerRouteVerbs)[number]\n\nexport const ServerRouteVerbs = [\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n] as const\n\nexport type ServerRouteMethodHandlerFn<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> = (\n ctx: ServerRouteMethodHandlerCtx<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >,\n) => TResponse | Promise<TResponse>\n\nexport interface ServerRouteMethodHandlerCtx<\n in out TParentRoute extends AnyServerRouteWithTypes,\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n> {\n context: Expand<\n AssignAllMethodContext<TParentRoute, TMiddlewares, TMethodMiddlewares>\n >\n request: Request\n params: Expand<ResolveParams<TFullPath>>\n pathname: TFullPath\n}\n\nexport type MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares> =\n TMiddlewares extends ReadonlyArray<any>\n ? TMethodMiddlewares extends ReadonlyArray<any>\n ? readonly [...TMiddlewares, ...TMethodMiddlewares]\n : TMiddlewares\n : TMethodMiddlewares\n\nexport type AssignAllMethodContext<\n TParentRoute extends AnyServerRouteWithTypes,\n TMiddlewares,\n TMethodMiddlewares,\n> = ResolveAllServerContext<\n TParentRoute,\n MergeMethodMiddlewares<TMiddlewares, TMethodMiddlewares>\n>\n\nexport type AnyRouteMethodsBuilder = ServerRouteMethodBuilderWithTypes<\n any,\n any,\n any,\n any,\n any\n>\n\nexport interface ServerRouteMethodBuilder<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined,\n undefined\n >,\n ServerRouteMethodBuilderMiddleware<TParentRoute, TFullPath, TMiddlewares>,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n undefined\n > {}\n\nexport interface ServerRouteMethodBuilderWithTypes<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> {\n _options: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n _types: ServerRouteMethodBuilderTypes<\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderTypes<\n in out TFullPath extends string,\n in out TMiddlewares,\n in out TMethodMiddlewares,\n in out TResponse,\n> {\n middlewares: TMiddlewares\n methodMiddleware: TMethodMiddlewares\n fullPath: TFullPath\n response: TResponse\n}\n\nexport interface ServerRouteMethodBuilderMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n> {\n middleware: <const TNewMethodMiddlewares>(\n middleware: Constrain<\n TNewMethodMiddlewares,\n ReadonlyArray<AnyRequestMiddleware>\n >,\n ) => ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TNewMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterMiddleware<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >,\n ServerRouteMethodBuilderHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n > {}\n\nexport interface ServerRouteMethodBuilderHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n handler: <TResponse>(\n handler: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >,\n ) => ServerRouteMethodBuilderAfterHandler<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n >\n}\n\nexport interface ServerRouteMethodBuilderAfterHandler<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse,\n> extends ServerRouteMethodBuilderWithTypes<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n TResponse\n > {\n opts: ServerRouteMethod<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares\n >\n}\n\nexport interface ServerRouteMethod<\n TParentRoute extends AnyServerRouteWithTypes,\n TFullPath extends string,\n TMiddlewares,\n TMethodMiddlewares,\n> {\n middleware?: Constrain<TMiddlewares, Array<AnyRequestMiddleware>>\n handler?: ServerRouteMethodHandlerFn<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n TMethodMiddlewares,\n undefined\n >\n}\n\nexport interface ServerRouteAfterMethods<\n TParentRoute extends AnyServerRouteWithTypes,\n TId extends RouteConstraints['TId'],\n TPath extends RouteConstraints['TPath'],\n TFullPath extends RouteConstraints['TFullPath'],\n TMiddlewares,\n TMethods,\n TChildren,\n> extends ServerRouteWithTypes<\n TParentRoute,\n TId,\n TPath,\n TFullPath,\n TMiddlewares,\n TMethods,\n TChildren\n > {\n options: ServerRouteOptions<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n}\n"],"names":[],"mappings":";AAcO,SAAS,sBAUd,GAA2E;AACpE,SAAA,kBAEP;AACF;AA6BgB,SAAA,kBAOd,IACA,QAG6D;AACvD,QAAA,UAAU,UAAU,CAAC;AAE3B,QAAM,QAAqE;AAAA,IACzE,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,UAAU;AAAA,IACV,IAAI;AAAA,IACJ;AAAA,IAOA,aAAa;AAAA,IACb,QAAQ,CAAC;AAAA;AAAA,IAST,YAAY,CAAC,gBACX,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,MACH,YAAY;AAAA,IAAA,CACb;AAAA,IACH,SAAS,CAAC,wBAAwB;AAChC,YAAM,WAAW,MAAM;AACjB,YAAA,OAAO,wBAAwB,YAAY;AACtC,iBAAA,oBAAoB,qBAAqB;AA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AA;AAGlC,aAAA;AAAA,IACT;AAAA,IAEA,eAAe,MAAkB;AAAA,EACnC;AAEO,SAAA;AACT;AAIO,MAAM,wBAAwB;AAsBrC,MAAM,sBAAsB,CAK1B,WAOoE;AAC7D,SAAA;AAAA,IACL,UAAW,UAAU,CAAC;AAAA,IACtB,QAAQ,CAAC;AAAA,IACT,YAAY,CAAC,gBACX,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IAAA,CACD;AAAA,IACH,SAAS,CAAC,YACR,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IACD,CAAA;AAAA,EACL;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/start-server-core",
|
|
3
|
-
"version": "1.121.
|
|
3
|
+
"version": "1.121.14",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"tiny-warning": "^1.0.3",
|
|
55
55
|
"unctx": "^2.4.1",
|
|
56
56
|
"@tanstack/history": "^1.120.17",
|
|
57
|
-
"@tanstack/
|
|
58
|
-
"@tanstack/
|
|
57
|
+
"@tanstack/router-core": "^1.121.14",
|
|
58
|
+
"@tanstack/start-client-core": "^1.121.14"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"@types/jsesc": "^3.0.3",
|