@tanstack/start-server-core 1.121.30 → 1.121.33
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 +14 -1
- package/dist/cjs/createStartHandler.cjs.map +1 -1
- package/dist/cjs/serverRoute.cjs.map +1 -1
- package/dist/cjs/serverRoute.d.cts +3 -1
- package/dist/esm/createStartHandler.js +14 -1
- package/dist/esm/createStartHandler.js.map +1 -1
- package/dist/esm/serverRoute.d.ts +3 -1
- package/dist/esm/serverRoute.js.map +1 -1
- package/package.json +4 -4
- package/src/createStartHandler.ts +17 -2
- package/src/serverRoute.ts +16 -1
|
@@ -245,7 +245,20 @@ async function handleServerRoutes(opts) {
|
|
|
245
245
|
if (method) {
|
|
246
246
|
const handler = serverTreeResult.foundRoute.options.methods[method];
|
|
247
247
|
if (handler) {
|
|
248
|
-
|
|
248
|
+
if (typeof handler === "function") {
|
|
249
|
+
middlewares.push(handlerToMiddleware(handler));
|
|
250
|
+
} else {
|
|
251
|
+
if (handler._options.middlewares && handler._options.middlewares.length) {
|
|
252
|
+
middlewares.push(
|
|
253
|
+
...startClientCore.flattenMiddlewares(handler._options.middlewares).map(
|
|
254
|
+
(d) => d.options.server
|
|
255
|
+
)
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
if (handler._options.handler) {
|
|
259
|
+
middlewares.push(handlerToMiddleware(handler._options.handler));
|
|
260
|
+
}
|
|
261
|
+
}
|
|
249
262
|
}
|
|
250
263
|
}
|
|
251
264
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createStartHandler.cjs","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 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: AnyServerRouteWithTypes | 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":["mergeHeaders","getResponseHeaders","url","history","createMemoryHistory","joinPaths","trimPath","handleServerAction","loadVirtualModule","VIRTUAL_MODULES","processRouteTree","json","getStartManifest","attachRouterServerSsrUtils","dehydrateRouter","response","isRedirect","isResolvedRedirect","requestHandler","getMatchedRoutes","flattenMiddlewares","method","ctx"],"mappings":";;;;;;;;;;;AAuCA,SAAS,wBAAwB,MAA6B;AAC5D,QAAM,UAAUA,gBAAA;AAAA,IACdC,sBAAmB;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,QAAQC,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,SAAS,SACT,OAAO,MAAM,QAAQ,YACrB,MAAM,IAAI,WAAW,GA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AA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,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,KAAKN,WAAAA,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;;"}
|
|
1
|
+
{"version":3,"file":"createStartHandler.cjs","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 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: AnyServerRouteWithTypes | 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 if (handler) {\n if (typeof handler === 'function') {\n middlewares.push(handlerToMiddleware(handler) as TODO)\n } else {\n if (\n handler._options.middlewares &&\n handler._options.middlewares.length\n ) {\n middlewares.push(\n ...flattenMiddlewares(handler._options.middlewares as any).map(\n (d) => d.options.server,\n ),\n )\n }\n if (handler._options.handler) {\n middlewares.push(handlerToMiddleware(handler._options.handler))\n }\n }\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":["mergeHeaders","getResponseHeaders","url","history","createMemoryHistory","joinPaths","trimPath","handleServerAction","loadVirtualModule","VIRTUAL_MODULES","processRouteTree","json","getStartManifest","attachRouterServerSsrUtils","dehydrateRouter","response","isRedirect","isResolvedRedirect","requestHandler","getMatchedRoutes","flattenMiddlewares","method","ctx"],"mappings":";;;;;;;;;;;AAuCA,SAAS,wBAAwB,MAA6B;AAC5D,QAAM,UAAUA,gBAAA;AAAA,IACdC,sBAAmB;AAAA,IACnB;AAAA,MACE,gBAAgB;AAAA,IAClB;AAAA,IAC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,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,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,KAAKN,WAAAA,WAAW,GAAG;AAC1C;AAEA,SAAS,WAAW,UAA0C;AAC5D,SAAO,oBAAoB;AAC7B;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serverRoute.cjs","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 isRoot: false as any,\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 route.isRoot = isRoot as any\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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: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AQ,MAAM;AAG3B,UAAA,KAAK,SACLD,WAAA,cACAE,qBAAU;AAAA,QACR,MAAM,YAAY,OAAOF,WAAAA,cAAc,KAAK,MAAM,YAAY;AAAA,QAC9D;AAAA,MAAA,CACD;AAEL,UAAI,SAASA,WAAAA,aAAa;AACjB,eAAA;AAAA,MAAA;AAGT,UAAI,OAAOA,WAAAA,aAAa;AACtB,aAAKE,WAAU,UAAA,CAAC,KAAK,EAAE,CAAC;AAAA,MAAA;AAGpB,YAAA,WACJ,OAAOF,WAAA,cAAc,MAAME,WAAAA,UAAU,CAAC,MAAM,YAAY,UAAU,IAAI,CAAC;AAEzE,YAAM,OAAO;AACb,YAAM,KAAK;AACX,YAAM,WAAW;AACjB,YAAM,KAAK;AACX,YAAM,SAAS;AAAA,IACjB;AAAA,IAEA,kBAAkB,CAAC,aAAa;AAC1B,UAAA,MAAM,QAAQ,QAAQ,GAAG;AAC3B,cAAM,WAAW;AAAA,MAAA;AAGnB,UAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AAC/C,cAAA,WAAW,OAAO,OAAO,QAAQ;AAAA,MAAA;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;;;;"}
|
|
1
|
+
{"version":3,"file":"serverRoute.cjs","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<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n any,\n any\n >\n | {\n _options: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n unknown,\n unknown\n >\n }\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 isRoot: false as any,\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 route.isRoot = isRoot as any\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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":["rootRouteId","trimPathLeft","joinPaths"],"mappings":";;;AAcO,SAAS,sBAUd,GAA2E;AACpE,SAAA,kBAEP;AACF;AA4CgB,SAAA,kBAOd,IACA,QAG6D;AACvD,QAAA,UAAU,UAAU,CAAC;AAE3B,QAAM,QAAqE;AAAA,IACzE,QAAQ;AAAA,IACR,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,QA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M,KAAK;AACX,YAAM,WAAW;AACjB,YAAM,KAAK;AACX,YAAM,SAAS;AAAA,IACjB;AAAA,IAEA,kBAAkB,CAAC,aAAa;AAC1B,UAAA,MAAM,QAAQ,QAAQ,GAAG;AAC3B,cAAM,WAAW;AAAA,MAAA;AAGnB,UAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AAC/C,cAAA,WAAW,OAAO,OAAO,QAAQ;AAAA,MAAA;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;;;;"}
|
|
@@ -10,7 +10,9 @@ export interface ServerRouteOptions<TParentRoute extends AnyServerRouteWithTypes
|
|
|
10
10
|
originalIndex: number;
|
|
11
11
|
getParentRoute?: () => TParentRoute;
|
|
12
12
|
middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>;
|
|
13
|
-
methods?: Record<string, ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any
|
|
13
|
+
methods?: Record<string, ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any> | {
|
|
14
|
+
_options: ServerRouteMethodBuilderOptions<TParentRoute, TFullPath, TMiddlewares, unknown, unknown>;
|
|
15
|
+
}>;
|
|
14
16
|
caseSensitive?: boolean;
|
|
15
17
|
}
|
|
16
18
|
export type ServerRouteManifest = {
|
|
@@ -243,7 +243,20 @@ async function handleServerRoutes(opts) {
|
|
|
243
243
|
if (method) {
|
|
244
244
|
const handler = serverTreeResult.foundRoute.options.methods[method];
|
|
245
245
|
if (handler) {
|
|
246
|
-
|
|
246
|
+
if (typeof handler === "function") {
|
|
247
|
+
middlewares.push(handlerToMiddleware(handler));
|
|
248
|
+
} else {
|
|
249
|
+
if (handler._options.middlewares && handler._options.middlewares.length) {
|
|
250
|
+
middlewares.push(
|
|
251
|
+
...flattenMiddlewares(handler._options.middlewares).map(
|
|
252
|
+
(d) => d.options.server
|
|
253
|
+
)
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
if (handler._options.handler) {
|
|
257
|
+
middlewares.push(handlerToMiddleware(handler._options.handler));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
247
260
|
}
|
|
248
261
|
}
|
|
249
262
|
}
|
|
@@ -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 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 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: AnyServerRouteWithTypes | 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":";;;;;;;;;AAuCA,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,uBA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,WAAmBA,QAAAA;AAElB,UAAA,SAAS,MAAM,WAAW;AAAA,MAC9B,GAAGA;AAAAA;AAAAA,MAEH,MAAM,OAAO,YAAkB;AAEvB,cAAA,aAAa,MAAM,KAAK,EAAE,GAAGA,MAAK,GAAG,SAAS;AAGpD,eAAO,OAAO,OAAOA,MAAK,gBAAgB,UAAU,CAAC;AAAA,MAAA;AAAA;AAAA,IACvD,CAED,EAAE,MAAM,CAAC,QAAc;AAClB,UAAA,kBAAkB,GAAG,GAAG;AACnB,eAAA;AAAA,UACL,UAAU;AAAA,QACZ;AAAA,MAAA;AAGI,YAAA;AAAA,IAAA,CACP;AAID,WAAO,OAAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,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;"}
|
|
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 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: AnyServerRouteWithTypes | 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 if (handler) {\n if (typeof handler === 'function') {\n middlewares.push(handlerToMiddleware(handler) as TODO)\n } else {\n if (\n handler._options.middlewares &&\n handler._options.middlewares.length\n ) {\n middlewares.push(\n ...flattenMiddlewares(handler._options.middlewares as any).map(\n (d) => d.options.server,\n ),\n )\n }\n if (handler._options.handler) {\n middlewares.push(handlerToMiddleware(handler._options.handler))\n }\n }\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: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AAO,OAAOA,MAAK,gBAAgB,MAAM,CAAC;AAAA,EACnD;AAEO,SAAA,gBAAgB,KAAK,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;"}
|
|
@@ -10,7 +10,9 @@ export interface ServerRouteOptions<TParentRoute extends AnyServerRouteWithTypes
|
|
|
10
10
|
originalIndex: number;
|
|
11
11
|
getParentRoute?: () => TParentRoute;
|
|
12
12
|
middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>;
|
|
13
|
-
methods?: Record<string, ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any
|
|
13
|
+
methods?: Record<string, ServerRouteMethodHandlerFn<TParentRoute, TFullPath, TMiddlewares, any, any> | {
|
|
14
|
+
_options: ServerRouteMethodBuilderOptions<TParentRoute, TFullPath, TMiddlewares, unknown, unknown>;
|
|
15
|
+
}>;
|
|
14
16
|
caseSensitive?: boolean;
|
|
15
17
|
}
|
|
16
18
|
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 isRoot: false as any,\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 route.isRoot = isRoot as any\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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,QAAQ;AAAA,IACR,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,kBA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E;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;"}
|
|
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<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n any,\n any\n >\n | {\n _options: ServerRouteMethodBuilderOptions<\n TParentRoute,\n TFullPath,\n TMiddlewares,\n unknown,\n unknown\n >\n }\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 isRoot: false as any,\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 route.isRoot = isRoot as any\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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 isRoot: TParentRoute extends AnyServerRouteWithTypes ? true : false\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<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,MAAM,YAAY,OAAO,cAAc,KAAK,MAAM,YAAY;AAAA,QAC9D;AAAA,MAAA,CACD;AAEL,UAAI,SAAS,aAAa;AACjB,eAAA;AAAA,MAAA;AAGT,UAAI,OAAO,aAAa;AACtB,aAAK,UAAU,CAAC,KAAK,EAAE,CAAC;AAAA,MAAA;AAGpB,YAAA,WACJ,OAAO,cAAc,MAAM,UAAU,CAAC,MAAM,YAAY,UAAU,IAAI,CAAC;AAEzE,YAAM,OAAO;AACb,YAAM,KAAK;AACX,YAAM,WAAW;AACjB,YAAM,KAAK;AACX,YAAM,SAAS;AAAA,IACjB;AAAA,IAEA,kBAAkB,CAAC,aAAa;AAC1B,UAAA,MAAM,QAAQ,QAAQ,GAAG;AAC3B,cAAM,WAAW;AAAA,MAAA;AAGnB,UAAI,OAAO,aAAa,YAAY,aAAa,MAAM;AAC/C,cAAA,WAAW,OAAO,OAAO,QAAQ;AAAA,MAAA;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.33",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -54,15 +54,15 @@
|
|
|
54
54
|
"tiny-warning": "^1.0.3",
|
|
55
55
|
"unctx": "^2.4.1",
|
|
56
56
|
"@tanstack/history": "1.121.21",
|
|
57
|
-
"@tanstack/start-client-core": "1.121.
|
|
58
|
-
"@tanstack/router-core": "1.121.
|
|
57
|
+
"@tanstack/start-client-core": "1.121.33",
|
|
58
|
+
"@tanstack/router-core": "1.121.33"
|
|
59
59
|
},
|
|
60
60
|
"devDependencies": {
|
|
61
61
|
"@types/jsesc": "^3.0.3",
|
|
62
62
|
"esbuild": "^0.25.0",
|
|
63
63
|
"typescript": "^5.7.2",
|
|
64
64
|
"vite": "^6.3.5",
|
|
65
|
-
"@tanstack/directive-functions-plugin": "1.121.
|
|
65
|
+
"@tanstack/directive-functions-plugin": "1.121.31"
|
|
66
66
|
},
|
|
67
67
|
"scripts": {}
|
|
68
68
|
}
|
|
@@ -375,9 +375,24 @@ async function handleServerRoutes(opts: {
|
|
|
375
375
|
|
|
376
376
|
if (method) {
|
|
377
377
|
const handler = serverTreeResult.foundRoute.options.methods[method]
|
|
378
|
-
|
|
379
378
|
if (handler) {
|
|
380
|
-
|
|
379
|
+
if (typeof handler === 'function') {
|
|
380
|
+
middlewares.push(handlerToMiddleware(handler) as TODO)
|
|
381
|
+
} else {
|
|
382
|
+
if (
|
|
383
|
+
handler._options.middlewares &&
|
|
384
|
+
handler._options.middlewares.length
|
|
385
|
+
) {
|
|
386
|
+
middlewares.push(
|
|
387
|
+
...flattenMiddlewares(handler._options.middlewares as any).map(
|
|
388
|
+
(d) => d.options.server,
|
|
389
|
+
),
|
|
390
|
+
)
|
|
391
|
+
}
|
|
392
|
+
if (handler._options.handler) {
|
|
393
|
+
middlewares.push(handlerToMiddleware(handler._options.handler))
|
|
394
|
+
}
|
|
395
|
+
}
|
|
381
396
|
}
|
|
382
397
|
}
|
|
383
398
|
}
|
package/src/serverRoute.ts
CHANGED
|
@@ -45,7 +45,22 @@ export interface ServerRouteOptions<
|
|
|
45
45
|
middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>
|
|
46
46
|
methods?: Record<
|
|
47
47
|
string,
|
|
48
|
-
ServerRouteMethodHandlerFn<
|
|
48
|
+
| ServerRouteMethodHandlerFn<
|
|
49
|
+
TParentRoute,
|
|
50
|
+
TFullPath,
|
|
51
|
+
TMiddlewares,
|
|
52
|
+
any,
|
|
53
|
+
any
|
|
54
|
+
>
|
|
55
|
+
| {
|
|
56
|
+
_options: ServerRouteMethodBuilderOptions<
|
|
57
|
+
TParentRoute,
|
|
58
|
+
TFullPath,
|
|
59
|
+
TMiddlewares,
|
|
60
|
+
unknown,
|
|
61
|
+
unknown
|
|
62
|
+
>
|
|
63
|
+
}
|
|
49
64
|
>
|
|
50
65
|
caseSensitive?: boolean
|
|
51
66
|
}
|