@tanstack/start-server-core 1.131.6 → 1.132.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/createStartHandler.d.ts +1 -1
- package/dist/esm/createStartHandler.js +8 -9
- package/dist/esm/createStartHandler.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +6 -90
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/loadVirtualModule.js +2 -0
- package/dist/esm/loadVirtualModule.js.map +1 -1
- package/dist/esm/request-response.d.ts +124 -0
- package/dist/esm/request-response.js +177 -0
- package/dist/esm/request-response.js.map +1 -0
- package/dist/esm/router-manifest.js +6 -3
- package/dist/esm/router-manifest.js.map +1 -1
- package/dist/esm/server-functions-handler.js +25 -59
- package/dist/esm/server-functions-handler.js.map +1 -1
- package/dist/esm/serverRoute.js +1 -2
- package/dist/esm/serverRoute.js.map +1 -1
- package/dist/esm/session.d.ts +66 -0
- package/dist/esm/virtual-modules.d.ts +2 -0
- package/dist/esm/virtual-modules.js +2 -1
- package/dist/esm/virtual-modules.js.map +1 -1
- package/package.json +9 -19
- package/src/createStartHandler.ts +7 -7
- package/src/global.d.ts +1 -3
- package/src/index.tsx +1 -1
- package/src/loadVirtualModule.ts +2 -0
- package/src/request-response.ts +335 -0
- package/src/router-manifest.ts +6 -3
- package/src/server-functions-handler.ts +29 -67
- package/src/session.ts +75 -0
- package/src/tanstack-start.d.ts +4 -0
- package/src/virtual-modules.ts +2 -0
- package/dist/cjs/constants.cjs +0 -7
- package/dist/cjs/constants.cjs.map +0 -1
- package/dist/cjs/constants.d.cts +0 -3
- package/dist/cjs/createStartHandler.cjs +0 -342
- package/dist/cjs/createStartHandler.cjs.map +0 -1
- package/dist/cjs/createStartHandler.d.cts +0 -7
- package/dist/cjs/h3.cjs +0 -355
- package/dist/cjs/h3.cjs.map +0 -1
- package/dist/cjs/h3.d.cts +0 -109
- package/dist/cjs/index.cjs +0 -257
- package/dist/cjs/index.cjs.map +0 -1
- package/dist/cjs/index.d.cts +0 -10
- package/dist/cjs/loadVirtualModule.cjs +0 -39
- package/dist/cjs/loadVirtualModule.cjs.map +0 -1
- package/dist/cjs/loadVirtualModule.d.cts +0 -6
- package/dist/cjs/router-manifest.cjs +0 -46
- package/dist/cjs/router-manifest.cjs.map +0 -1
- package/dist/cjs/router-manifest.d.cts +0 -17
- package/dist/cjs/server-functions-handler.cjs +0 -181
- package/dist/cjs/server-functions-handler.cjs.map +0 -1
- package/dist/cjs/server-functions-handler.d.cts +0 -3
- package/dist/cjs/serverRoute.cjs +0 -104
- package/dist/cjs/serverRoute.cjs.map +0 -1
- package/dist/cjs/serverRoute.d.cts +0 -124
- package/dist/cjs/virtual-modules.cjs +0 -9
- package/dist/cjs/virtual-modules.cjs.map +0 -1
- package/dist/cjs/virtual-modules.d.cts +0 -10
- package/dist/esm/h3.d.ts +0 -109
- package/dist/esm/h3.js +0 -248
- package/dist/esm/h3.js.map +0 -1
- package/src/h3.ts +0 -492
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { H3Event, toResponse, getRequestIP as getRequestIP$1, getRequestHost as getRequestHost$1, getRequestURL, getRequestProtocol as getRequestProtocol$1, sanitizeStatusCode, sanitizeStatusMessage, parseCookies, setCookie as setCookie$1, deleteCookie as deleteCookie$1, useSession as useSession$1, getSession as getSession$1, updateSession as updateSession$1, sealSession as sealSession$1, unsealSession as unsealSession$1, clearSession as clearSession$1, getValidatedQuery as getValidatedQuery$1 } from "h3";
|
|
3
|
+
const eventStorage = new AsyncLocalStorage();
|
|
4
|
+
function requestHandler(handler) {
|
|
5
|
+
return (request) => {
|
|
6
|
+
const h3Event = new H3Event(request);
|
|
7
|
+
const response = eventStorage.run({ h3Event }, () => handler(request));
|
|
8
|
+
return toResponse(response, h3Event);
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function getH3Event() {
|
|
12
|
+
const event = eventStorage.getStore();
|
|
13
|
+
if (!event) {
|
|
14
|
+
throw new Error(
|
|
15
|
+
`No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
return event.h3Event;
|
|
19
|
+
}
|
|
20
|
+
function getRequest() {
|
|
21
|
+
const event = getH3Event();
|
|
22
|
+
return event.req;
|
|
23
|
+
}
|
|
24
|
+
function getRequestHeaders() {
|
|
25
|
+
return getH3Event().req.headers;
|
|
26
|
+
}
|
|
27
|
+
function getRequestHeader(name) {
|
|
28
|
+
return getRequestHeaders().get(name) || void 0;
|
|
29
|
+
}
|
|
30
|
+
function getRequestIP(opts) {
|
|
31
|
+
return getRequestIP$1(getH3Event(), opts);
|
|
32
|
+
}
|
|
33
|
+
function getRequestHost(opts) {
|
|
34
|
+
return getRequestHost$1(getH3Event(), opts);
|
|
35
|
+
}
|
|
36
|
+
function getRequestUrl(opts) {
|
|
37
|
+
return getRequestURL(getH3Event(), opts);
|
|
38
|
+
}
|
|
39
|
+
function getRequestProtocol(opts) {
|
|
40
|
+
return getRequestProtocol$1(getH3Event(), opts);
|
|
41
|
+
}
|
|
42
|
+
function setResponseHeaders(headers) {
|
|
43
|
+
const event = getH3Event();
|
|
44
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
45
|
+
event.res.headers.set(name, value);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function getResponseHeaders() {
|
|
49
|
+
const event = getH3Event();
|
|
50
|
+
return Object.fromEntries(event.res.headers.entries());
|
|
51
|
+
}
|
|
52
|
+
function getResponseHeader(name) {
|
|
53
|
+
const event = getH3Event();
|
|
54
|
+
return event.res.headers.get(name) || void 0;
|
|
55
|
+
}
|
|
56
|
+
function setResponseHeader(name, value) {
|
|
57
|
+
const event = getH3Event();
|
|
58
|
+
if (Array.isArray(value)) {
|
|
59
|
+
event.res.headers.delete(name);
|
|
60
|
+
for (const valueItem of value) {
|
|
61
|
+
event.res.headers.append(name, valueItem);
|
|
62
|
+
}
|
|
63
|
+
} else {
|
|
64
|
+
event.res.headers.set(name, value);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function removeResponseHeader(name) {
|
|
68
|
+
const event = getH3Event();
|
|
69
|
+
event.res.headers.delete(name);
|
|
70
|
+
}
|
|
71
|
+
function clearResponseHeaders(headerNames) {
|
|
72
|
+
const event = getH3Event();
|
|
73
|
+
if (headerNames && headerNames.length > 0) {
|
|
74
|
+
for (const name of headerNames) {
|
|
75
|
+
event.res.headers.delete(name);
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
for (const name of event.res.headers.keys()) {
|
|
79
|
+
event.res.headers.delete(name);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function getResponseStatus() {
|
|
84
|
+
return getH3Event().res.status || 200;
|
|
85
|
+
}
|
|
86
|
+
function setResponseStatus(code, text) {
|
|
87
|
+
const event = getH3Event();
|
|
88
|
+
if (code) {
|
|
89
|
+
event.res.status = sanitizeStatusCode(code, event.res.status);
|
|
90
|
+
}
|
|
91
|
+
if (text) {
|
|
92
|
+
event.res.statusText = sanitizeStatusMessage(text);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function getCookies() {
|
|
96
|
+
const event = getH3Event();
|
|
97
|
+
return parseCookies(event);
|
|
98
|
+
}
|
|
99
|
+
function getCookie(name) {
|
|
100
|
+
return getCookies()[name] || void 0;
|
|
101
|
+
}
|
|
102
|
+
function setCookie(name, value, options) {
|
|
103
|
+
const event = getH3Event();
|
|
104
|
+
setCookie$1(event, name, value, options);
|
|
105
|
+
}
|
|
106
|
+
function deleteCookie(name, options) {
|
|
107
|
+
const event = getH3Event();
|
|
108
|
+
deleteCookie$1(event, name, options);
|
|
109
|
+
}
|
|
110
|
+
function getDefaultSessionConfig(config) {
|
|
111
|
+
return {
|
|
112
|
+
name: "start",
|
|
113
|
+
...config
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function useSession(config) {
|
|
117
|
+
const event = getH3Event();
|
|
118
|
+
return useSession$1(event, getDefaultSessionConfig(config));
|
|
119
|
+
}
|
|
120
|
+
function getSession(config) {
|
|
121
|
+
const event = getH3Event();
|
|
122
|
+
return getSession$1(event, getDefaultSessionConfig(config));
|
|
123
|
+
}
|
|
124
|
+
function updateSession(config, update) {
|
|
125
|
+
const event = getH3Event();
|
|
126
|
+
return updateSession$1(event, getDefaultSessionConfig(config), update);
|
|
127
|
+
}
|
|
128
|
+
function sealSession(config) {
|
|
129
|
+
const event = getH3Event();
|
|
130
|
+
return sealSession$1(event, getDefaultSessionConfig(config));
|
|
131
|
+
}
|
|
132
|
+
function unsealSession(config, sealed) {
|
|
133
|
+
const event = getH3Event();
|
|
134
|
+
return unsealSession$1(event, getDefaultSessionConfig(config), sealed);
|
|
135
|
+
}
|
|
136
|
+
function clearSession(config) {
|
|
137
|
+
const event = getH3Event();
|
|
138
|
+
return clearSession$1(event, { name: "start", ...config });
|
|
139
|
+
}
|
|
140
|
+
function getResponse() {
|
|
141
|
+
const event = getH3Event();
|
|
142
|
+
return event._res;
|
|
143
|
+
}
|
|
144
|
+
function getValidatedQuery(schema) {
|
|
145
|
+
return getValidatedQuery$1(getH3Event(), schema);
|
|
146
|
+
}
|
|
147
|
+
export {
|
|
148
|
+
clearResponseHeaders,
|
|
149
|
+
clearSession,
|
|
150
|
+
deleteCookie,
|
|
151
|
+
getCookie,
|
|
152
|
+
getCookies,
|
|
153
|
+
getRequest,
|
|
154
|
+
getRequestHeader,
|
|
155
|
+
getRequestHeaders,
|
|
156
|
+
getRequestHost,
|
|
157
|
+
getRequestIP,
|
|
158
|
+
getRequestProtocol,
|
|
159
|
+
getRequestUrl,
|
|
160
|
+
getResponse,
|
|
161
|
+
getResponseHeader,
|
|
162
|
+
getResponseHeaders,
|
|
163
|
+
getResponseStatus,
|
|
164
|
+
getSession,
|
|
165
|
+
getValidatedQuery,
|
|
166
|
+
removeResponseHeader,
|
|
167
|
+
requestHandler,
|
|
168
|
+
sealSession,
|
|
169
|
+
setCookie,
|
|
170
|
+
setResponseHeader,
|
|
171
|
+
setResponseHeaders,
|
|
172
|
+
setResponseStatus,
|
|
173
|
+
unsealSession,
|
|
174
|
+
updateSession,
|
|
175
|
+
useSession
|
|
176
|
+
};
|
|
177
|
+
//# sourceMappingURL=request-response.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-response.js","sources":["../../src/request-response.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport {\n H3Event,\n clearSession as h3_clearSession,\n deleteCookie as h3_deleteCookie,\n getRequestHost as h3_getRequestHost,\n getRequestIP as h3_getRequestIP,\n getRequestProtocol as h3_getRequestProtocol,\n getRequestURL as h3_getRequestURL,\n getSession as h3_getSession,\n getValidatedQuery as h3_getValidatedQuery,\n parseCookies as h3_parseCookies,\n sanitizeStatusCode as h3_sanitizeStatusCode,\n sanitizeStatusMessage as h3_sanitizeStatusMessage,\n sealSession as h3_sealSession,\n setCookie as h3_setCookie,\n toResponse as h3_toResponse,\n unsealSession as h3_unsealSession,\n updateSession as h3_updateSession,\n useSession as h3_useSession,\n} from 'h3'\nimport type {\n RequestHeaderMap,\n RequestHeaderName,\n ResponseHeaderMap,\n ResponseHeaderName,\n TypedHeaders,\n} from 'fetchdts'\n\nimport type { CookieSerializeOptions } from 'cookie-es'\nimport type {\n Session,\n SessionConfig,\n SessionData,\n SessionManager,\n SessionUpdate,\n} from './session'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\n\ninterface StartEvent {\n h3Event: H3Event\n}\nconst eventStorage = new AsyncLocalStorage<StartEvent>()\n\nexport type RequestHandler = (request: Request) => Promise<Response> | Response\n\nexport type { ResponseHeaderName, RequestHeaderName }\n\nexport function requestHandler(handler: RequestHandler) {\n return (request: Request): Promise<Response> | Response => {\n const h3Event = new H3Event(request)\n\n const response = eventStorage.run({ h3Event }, () => handler(request))\n return h3_toResponse(response, h3Event)\n }\n}\n\nfunction getH3Event() {\n const event = eventStorage.getStore()\n if (!event) {\n throw new Error(\n `No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,\n )\n }\n return event.h3Event\n}\n\nexport function getRequest(): Request {\n const event = getH3Event()\n return event.req\n}\n\nexport function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {\n // TODO `as any` not needed when fetchdts is updated\n return getH3Event().req.headers as any\n}\n\nexport function getRequestHeader(name: RequestHeaderName): string | undefined {\n return getRequestHeaders().get(name) || undefined\n}\n\nexport function getRequestIP(opts?: {\n /**\n * Use the X-Forwarded-For HTTP header set by proxies.\n *\n * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.\n */\n xForwardedFor?: boolean\n}) {\n return h3_getRequestIP(getH3Event(), opts)\n}\n\n/**\n * Get the request hostname.\n *\n * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.\n *\n * If no host header is found, it will default to \"localhost\".\n */\nexport function getRequestHost(opts?: { xForwardedHost?: boolean }) {\n return h3_getRequestHost(getH3Event(), opts)\n}\n\n/**\n * Get the full incoming request URL.\n *\n * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.\n *\n * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.\n */\nexport function getRequestUrl(opts?: {\n xForwardedHost?: boolean\n xForwardedProto?: boolean\n}) {\n return h3_getRequestURL(getH3Event(), opts)\n}\n\n/**\n * Get the request protocol.\n *\n * If `x-forwarded-proto` header is set to \"https\", it will return \"https\". You can disable this behavior by setting `xForwardedProto` to `false`.\n *\n * If protocol cannot be determined, it will default to \"http\".\n */\nexport function getRequestProtocol(opts?: {\n xForwardedProto?: boolean\n}): 'http' | 'https' | (string & {}) {\n return h3_getRequestProtocol(getH3Event(), opts)\n}\n\nexport function setResponseHeaders(\n headers: TypedHeaders<ResponseHeaderMap>,\n): void {\n const event = getH3Event()\n for (const [name, value] of Object.entries(headers)) {\n event.res.headers.set(name, value)\n }\n}\n\nexport function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {\n const event = getH3Event()\n return Object.fromEntries(event.res.headers.entries()) as any\n}\n\nexport function getResponseHeader(\n name: ResponseHeaderName,\n): string | undefined {\n const event = getH3Event()\n return event.res.headers.get(name) || undefined\n}\n\nexport function setResponseHeader(\n name: ResponseHeaderName,\n value: string | Array<string>,\n): void {\n const event = getH3Event()\n if (Array.isArray(value)) {\n event.res.headers.delete(name)\n for (const valueItem of value) {\n event.res.headers.append(name, valueItem)\n }\n } else {\n event.res.headers.set(name, value)\n }\n}\nexport function removeResponseHeader(name: ResponseHeaderName): void {\n const event = getH3Event()\n event.res.headers.delete(name)\n}\n\nexport function clearResponseHeaders(\n headerNames?: Array<ResponseHeaderName>,\n): void {\n const event = getH3Event()\n // If headerNames is provided, clear only those headers\n if (headerNames && headerNames.length > 0) {\n for (const name of headerNames) {\n event.res.headers.delete(name)\n }\n // Otherwise, clear all headers\n } else {\n for (const name of event.res.headers.keys()) {\n event.res.headers.delete(name)\n }\n }\n}\n\nexport function getResponseStatus(): number {\n return getH3Event().res.status || 200\n}\n\nexport function setResponseStatus(code?: number, text?: string): void {\n const event = getH3Event()\n if (code) {\n event.res.status = h3_sanitizeStatusCode(code, event.res.status)\n }\n if (text) {\n event.res.statusText = h3_sanitizeStatusMessage(text)\n }\n}\n\n/**\n * Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.\n * @returns Object of cookie name-value pairs\n * ```ts\n * const cookies = getCookies()\n * ```\n */\nexport function getCookies(): Record<string, string> {\n const event = getH3Event()\n return h3_parseCookies(event)\n}\n\n/**\n * Get a cookie value by name.\n * @param name Name of the cookie to get\n * @returns {*} Value of the cookie (String or undefined)\n * ```ts\n * const authorization = getCookie('Authorization')\n * ```\n */\nexport function getCookie(name: string): string | undefined {\n return getCookies()[name] || undefined\n}\n\n/**\n * Set a cookie value by name.\n * @param name Name of the cookie to set\n * @param value Value of the cookie to set\n * @param options {CookieSerializeOptions} Options for serializing the cookie\n * ```ts\n * setCookie('Authorization', '1234567')\n * ```\n */\nexport function setCookie(\n name: string,\n value: string,\n options?: CookieSerializeOptions,\n): void {\n const event = getH3Event()\n h3_setCookie(event, name, value, options)\n}\n\n/**\n * Remove a cookie by name.\n * @param name Name of the cookie to delete\n * @param serializeOptions {CookieSerializeOptions} Cookie options\n * ```ts\n * deleteCookie('SessionId')\n * ```\n */\nexport function deleteCookie(\n name: string,\n options?: CookieSerializeOptions,\n): void {\n const event = getH3Event()\n h3_deleteCookie(event, name, options)\n}\n\nfunction getDefaultSessionConfig(config: SessionConfig): SessionConfig {\n return {\n name: 'start',\n ...config,\n }\n}\n\n/**\n * Create a session manager for the current request.\n */\nexport function useSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<SessionManager<TSessionData>> {\n const event = getH3Event()\n return h3_useSession(event, getDefaultSessionConfig(config))\n}\n/**\n * Get the session for the current request\n */\nexport function getSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n): Promise<Session<TSessionData>> {\n const event = getH3Event()\n return h3_getSession(event, getDefaultSessionConfig(config))\n}\n\n/**\n * Update the session data for the current request.\n */\nexport function updateSession<TSessionData extends SessionData = SessionData>(\n config: SessionConfig,\n update?: SessionUpdate<TSessionData>,\n): Promise<Session<TSessionData>> {\n const event = getH3Event()\n return h3_updateSession(event, getDefaultSessionConfig(config), update)\n}\n\n/**\n * Encrypt and sign the session data for the current request.\n */\nexport function sealSession(config: SessionConfig): Promise<string> {\n const event = getH3Event()\n return h3_sealSession(event, getDefaultSessionConfig(config))\n}\n/**\n * Decrypt and verify the session data for the current request.\n */\nexport function unsealSession(\n config: SessionConfig,\n sealed: string,\n): Promise<Partial<Session>> {\n const event = getH3Event()\n return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)\n}\n\n/**\n * Clear the session data for the current request.\n */\nexport function clearSession(config: Partial<SessionConfig>): Promise<void> {\n const event = getH3Event()\n return h3_clearSession(event, { name: 'start', ...config })\n}\n\n// not public API\nexport function getResponse() {\n const event = getH3Event()\n return event._res\n}\n\n// not public API (yet)\nexport function getValidatedQuery<TSchema extends StandardSchemaV1>(\n schema: StandardSchemaV1,\n): Promise<StandardSchemaV1.InferOutput<TSchema>> {\n return h3_getValidatedQuery(getH3Event(), schema)\n}\n"],"names":["h3_toResponse","h3_getRequestIP","h3_getRequestHost","h3_getRequestURL","h3_getRequestProtocol","h3_sanitizeStatusCode","h3_sanitizeStatusMessage","h3_parseCookies","h3_setCookie","h3_deleteCookie","h3_useSession","h3_getSession","h3_updateSession","h3_sealSession","h3_unsealSession","h3_clearSession","h3_getValidatedQuery"],"mappings":";;AA2CA,MAAM,eAAe,IAAI,kBAAA;AAMlB,SAAS,eAAe,SAAyB;AACtD,SAAO,CAAC,YAAmD;AACzD,UAAM,UAAU,IAAI,QAAQ,OAAO;AAEnC,UAAM,WAAW,aAAa,IAAI,EAAE,WAAW,MAAM,QAAQ,OAAO,CAAC;AACrE,WAAOA,WAAc,UAAU,OAAO;AAAA,EACxC;AACF;AAEA,SAAS,aAAa;AACpB,QAAM,QAAQ,aAAa,SAAA;AAC3B,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACA,SAAO,MAAM;AACf;AAEO,SAAS,aAAsB;AACpC,QAAM,QAAQ,WAAA;AACd,SAAO,MAAM;AACf;AAEO,SAAS,oBAAoD;AAElE,SAAO,WAAA,EAAa,IAAI;AAC1B;AAEO,SAAS,iBAAiB,MAA6C;AAC5E,SAAO,kBAAA,EAAoB,IAAI,IAAI,KAAK;AAC1C;AAEO,SAAS,aAAa,MAO1B;AACD,SAAOC,eAAgB,WAAA,GAAc,IAAI;AAC3C;AASO,SAAS,eAAe,MAAqC;AAClE,SAAOC,iBAAkB,WAAA,GAAc,IAAI;AAC7C;AASO,SAAS,cAAc,MAG3B;AACD,SAAOC,cAAiB,WAAA,GAAc,IAAI;AAC5C;AASO,SAA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Ac;AAC5B,QAAM,QAAQ,WAAA;AACd,SAAO,MAAM;AACf;AAGO,SAAS,kBACd,QACgD;AAChD,SAAOC,oBAAqB,WAAA,GAAc,MAAM;AAClD;"}
|
|
@@ -9,9 +9,12 @@ async function getStartManifest(opts) {
|
|
|
9
9
|
const rootRoute = startManifest.routes[rootRouteId] = startManifest.routes[rootRouteId] || {};
|
|
10
10
|
rootRoute.assets = rootRoute.assets || [];
|
|
11
11
|
let script = `import('${startManifest.clientEntry}')`;
|
|
12
|
-
if (process.env.
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
if (process.env.TSS_DEV_SERVER === "true") {
|
|
13
|
+
const { injectedHeadScripts } = await loadVirtualModule(
|
|
14
|
+
VIRTUAL_MODULES.injectedHeadScripts
|
|
15
|
+
);
|
|
16
|
+
if (injectedHeadScripts) {
|
|
17
|
+
script = `${injectedHeadScripts + ";"}${script}`;
|
|
15
18
|
}
|
|
16
19
|
}
|
|
17
20
|
rootRoute.assets.push({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { rootRouteId } from '@tanstack/router-core'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\n/**\n * @description Returns the router manifest that should be sent to the client.\n * This includes only the assets and preloads for the current route and any\n * special assets that are needed for the client. It does not include relationships\n * between routes or any other data that is not needed for the client.\n */\nexport async function getStartManifest(opts: { basePath: string }) {\n const { tsrStartManifest } = await loadVirtualModule(\n VIRTUAL_MODULES.startManifest,\n )\n const startManifest = tsrStartManifest()\n\n const rootRoute = (startManifest.routes[rootRouteId] =\n startManifest.routes[rootRouteId] || {})\n\n rootRoute.assets = rootRoute.assets || []\n\n let script = `import('${startManifest.clientEntry}')`\n if (process.env.
|
|
1
|
+
{"version":3,"file":"router-manifest.js","sources":["../../src/router-manifest.ts"],"sourcesContent":["import { rootRouteId } from '@tanstack/router-core'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\n/**\n * @description Returns the router manifest that should be sent to the client.\n * This includes only the assets and preloads for the current route and any\n * special assets that are needed for the client. It does not include relationships\n * between routes or any other data that is not needed for the client.\n */\nexport async function getStartManifest(opts: { basePath: string }) {\n const { tsrStartManifest } = await loadVirtualModule(\n VIRTUAL_MODULES.startManifest,\n )\n const startManifest = tsrStartManifest()\n\n const rootRoute = (startManifest.routes[rootRouteId] =\n startManifest.routes[rootRouteId] || {})\n\n rootRoute.assets = rootRoute.assets || []\n\n let script = `import('${startManifest.clientEntry}')`\n if (process.env.TSS_DEV_SERVER === 'true') {\n const { injectedHeadScripts } = await loadVirtualModule(\n VIRTUAL_MODULES.injectedHeadScripts,\n )\n if (injectedHeadScripts) {\n script = `${injectedHeadScripts + ';'}${script}`\n }\n }\n rootRoute.assets.push({\n tag: 'script',\n attrs: {\n type: 'module',\n suppressHydrationWarning: true,\n async: true,\n },\n children: script,\n })\n\n const manifest = {\n ...startManifest,\n routes: Object.fromEntries(\n Object.entries(startManifest.routes).map(([k, v]) => {\n const { preloads, assets } = v\n return [\n k,\n {\n preloads,\n assets,\n },\n ]\n }),\n ),\n }\n\n // Strip out anything that isn't needed for the client\n return manifest\n}\n"],"names":[],"mappings":";;;AAUA,eAAsB,iBAAiB,MAA4B;AACjE,QAAM,EAAE,iBAAA,IAAqB,MAAM;AAAA,IACjC,gBAAgB;AAAA,EAAA;AAElB,QAAM,gBAAgB,iBAAA;AAEtB,QAAM,YAAa,cAAc,OAAO,WAAW,IACjD,cAAc,OAAO,WAAW,KAAK,CAAA;AAEvC,YAAU,SAAS,UAAU,UAAU,CAAA;AAEvC,MAAI,SAAS,WAAW,cAAc,WAAW;AACjD,MAAI,QAAQ,IAAI,mBAAmB,QAAQ;AACzC,UAAM,EAAE,oBAAA,IAAwB,MAAM;AAAA,MACpC,gBAAgB;AAAA,IAAA;AAElB,QAAI,qBAAqB;AACvB,eAAS,GAAG,sBAAsB,GAAG,GAAG,MAAM;AAAA,IAChD;AAAA,EACF;AACA,YAAU,OAAO,KAAK;AAAA,IACpB,KAAK;AAAA,IACL,OAAO;AAAA,MACL,MAAM;AAAA,MACN,0BAA0B;AAAA,MAC1B,OAAO;AAAA,IAAA;AAAA,IAET,UAAU;AAAA,EAAA,CACX;AAED,QAAM,WAAW;AAAA,IACf,GAAG;AAAA,IACH,QAAQ,OAAO;AAAA,MACb,OAAO,QAAQ,cAAc,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AACnD,cAAM,EAAE,UAAU,OAAA,IAAW;AAC7B,eAAO;AAAA,UACL;AAAA,UACA;AAAA,YACE;AAAA,YACA;AAAA,UAAA;AAAA,QACF;AAAA,MAEJ,CAAC;AAAA,IAAA;AAAA,EACH;AAIF,SAAO;AACT;"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { isNotFound } from "@tanstack/router-core";
|
|
2
2
|
import invariant from "tiny-invariant";
|
|
3
3
|
import { startSerializer } from "@tanstack/start-client-core";
|
|
4
|
-
import { getResponseStatus, getEvent } from "./h3.js";
|
|
5
4
|
import { VIRTUAL_MODULES } from "./virtual-modules.js";
|
|
6
5
|
import { loadVirtualModule } from "./loadVirtualModule.js";
|
|
6
|
+
import { getResponse } from "./request-response.js";
|
|
7
7
|
function sanitizeBase(base) {
|
|
8
8
|
if (!base) {
|
|
9
9
|
throw new Error(
|
|
@@ -12,31 +12,24 @@ function sanitizeBase(base) {
|
|
|
12
12
|
}
|
|
13
13
|
return base.replace(/^\/|\/$/g, "");
|
|
14
14
|
}
|
|
15
|
-
async
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
return async (opts, signal) => {
|
|
33
|
-
const result = await serverFn(opts ?? {}, signal);
|
|
34
|
-
return result.result;
|
|
35
|
-
};
|
|
15
|
+
const handleServerAction = async ({ request }) => {
|
|
16
|
+
const controller = new AbortController();
|
|
17
|
+
const signal = controller.signal;
|
|
18
|
+
const abort = () => controller.abort();
|
|
19
|
+
request.signal.addEventListener("abort", abort);
|
|
20
|
+
const method = request.method;
|
|
21
|
+
const url = new URL(request.url, "http://localhost:3000");
|
|
22
|
+
const regex = new RegExp(
|
|
23
|
+
`${sanitizeBase(process.env.TSS_SERVER_FN_BASE)}/([^/?#]+)`
|
|
24
|
+
);
|
|
25
|
+
const match = url.pathname.match(regex);
|
|
26
|
+
const serverFnId = match ? match[1] : null;
|
|
27
|
+
const search = Object.fromEntries(url.searchParams.entries());
|
|
28
|
+
const isCreateServerFn = "createServerFn" in search;
|
|
29
|
+
const isRaw = "raw" in search;
|
|
30
|
+
if (typeof serverFnId !== "string") {
|
|
31
|
+
throw new Error("Invalid server action param for serverFnId: " + serverFnId);
|
|
36
32
|
}
|
|
37
|
-
return value;
|
|
38
|
-
}
|
|
39
|
-
async function getServerFnById(serverFnId) {
|
|
40
33
|
const { default: serverFnManifest } = await loadVirtualModule(
|
|
41
34
|
VIRTUAL_MODULES.serverFnManifest
|
|
42
35
|
);
|
|
@@ -58,32 +51,6 @@ async function getServerFnById(serverFnId) {
|
|
|
58
51
|
`Server function module export not resolved for serverFn ID: ${serverFnId}`
|
|
59
52
|
);
|
|
60
53
|
}
|
|
61
|
-
return action;
|
|
62
|
-
}
|
|
63
|
-
async function parsePayload(payload) {
|
|
64
|
-
const parsedPayload = startSerializer.parse(payload);
|
|
65
|
-
await revive(parsedPayload, reviveServerFns);
|
|
66
|
-
return parsedPayload;
|
|
67
|
-
}
|
|
68
|
-
const handleServerAction = async ({ request }) => {
|
|
69
|
-
const controller = new AbortController();
|
|
70
|
-
const signal = controller.signal;
|
|
71
|
-
const abort = () => controller.abort();
|
|
72
|
-
request.signal.addEventListener("abort", abort);
|
|
73
|
-
const method = request.method;
|
|
74
|
-
const url = new URL(request.url, "http://localhost:3000");
|
|
75
|
-
const regex = new RegExp(
|
|
76
|
-
`${sanitizeBase(process.env.TSS_SERVER_FN_BASE)}/([^/?#]+)`
|
|
77
|
-
);
|
|
78
|
-
const match = url.pathname.match(regex);
|
|
79
|
-
const serverFnId = match ? match[1] : null;
|
|
80
|
-
const search = Object.fromEntries(url.searchParams.entries());
|
|
81
|
-
const isCreateServerFn = "createServerFn" in search;
|
|
82
|
-
const isRaw = "raw" in search;
|
|
83
|
-
if (typeof serverFnId !== "string") {
|
|
84
|
-
throw new Error("Invalid server action param for serverFnId: " + serverFnId);
|
|
85
|
-
}
|
|
86
|
-
const action = await getServerFnById(serverFnId);
|
|
87
54
|
const formDataContentTypes = [
|
|
88
55
|
"multipart/form-data",
|
|
89
56
|
"application/x-www-form-urlencoded"
|
|
@@ -92,10 +59,7 @@ const handleServerAction = async ({ request }) => {
|
|
|
92
59
|
try {
|
|
93
60
|
let result = await (async () => {
|
|
94
61
|
if (request.headers.get("Content-Type") && formDataContentTypes.some(
|
|
95
|
-
(type) =>
|
|
96
|
-
var _a;
|
|
97
|
-
return (_a = request.headers.get("Content-Type")) == null ? void 0 : _a.includes(type);
|
|
98
|
-
}
|
|
62
|
+
(type) => request.headers.get("Content-Type")?.includes(type)
|
|
99
63
|
)) {
|
|
100
64
|
invariant(
|
|
101
65
|
method.toLowerCase() !== "get",
|
|
@@ -108,11 +72,11 @@ const handleServerAction = async ({ request }) => {
|
|
|
108
72
|
if (isCreateServerFn) {
|
|
109
73
|
payload2 = search.payload;
|
|
110
74
|
}
|
|
111
|
-
payload2 = payload2 ?
|
|
75
|
+
payload2 = payload2 ? startSerializer.parse(payload2) : payload2;
|
|
112
76
|
return await action(payload2, signal);
|
|
113
77
|
}
|
|
114
78
|
const jsonPayloadAsString = await request.text();
|
|
115
|
-
const payload =
|
|
79
|
+
const payload = startSerializer.parse(jsonPayloadAsString);
|
|
116
80
|
if (isCreateServerFn) {
|
|
117
81
|
return await action(payload, signal);
|
|
118
82
|
}
|
|
@@ -130,10 +94,12 @@ const handleServerAction = async ({ request }) => {
|
|
|
130
94
|
if (isNotFound(result)) {
|
|
131
95
|
return isNotFoundResponse(result);
|
|
132
96
|
}
|
|
97
|
+
const response2 = getResponse();
|
|
133
98
|
return new Response(
|
|
134
99
|
result !== void 0 ? startSerializer.stringify(result) : void 0,
|
|
135
100
|
{
|
|
136
|
-
status:
|
|
101
|
+
status: response2?.status,
|
|
102
|
+
statusText: response2?.statusText,
|
|
137
103
|
headers: {
|
|
138
104
|
"Content-Type": "application/json"
|
|
139
105
|
}
|
|
@@ -168,7 +134,7 @@ const handleServerAction = async ({ request }) => {
|
|
|
168
134
|
function isNotFoundResponse(error) {
|
|
169
135
|
const { headers, ...rest } = error;
|
|
170
136
|
return new Response(JSON.stringify(rest), {
|
|
171
|
-
status:
|
|
137
|
+
status: 404,
|
|
172
138
|
headers: {
|
|
173
139
|
"Content-Type": "application/json",
|
|
174
140
|
...headers || {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-functions-handler.js","sources":["../../src/server-functions-handler.ts"],"sourcesContent":["import { isNotFound } from '@tanstack/router-core'\nimport invariant from 'tiny-invariant'\nimport { startSerializer } from '@tanstack/start-client-core'\nimport { getEvent, getResponseStatus } from './h3'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\n\nfunction sanitizeBase(base: string | undefined) {\n if (!base) {\n throw new Error(\n '🚨 process.env.TSS_SERVER_FN_BASE is required in start/server-handler/index',\n )\n }\n\n return base.replace(/^\\/|\\/$/g, '')\n}\n\nasync function revive(root: any, reviver?: (key: string, value: any) => any) {\n async function reviveNode(holder: any, key: string) {\n const value = holder[key]\n\n if (value && typeof value === 'object') {\n await Promise.all(Object.keys(value).map((k) => reviveNode(value, k)))\n }\n\n if (reviver) {\n holder[key] = await reviver(key, holder[key])\n }\n }\n\n const holder = { '': root }\n await reviveNode(holder, '')\n return holder['']\n}\n\nasync function reviveServerFns(key: string, value: any) {\n if (value && value.__serverFn === true && value.functionId) {\n const serverFn = await getServerFnById(value.functionId)\n return async (opts: any, signal: any): Promise<any> => {\n const result = await serverFn(opts ?? {}, signal)\n return result.result\n }\n }\n return value\n}\n\nasync function getServerFnById(serverFnId: string) {\n const { default: serverFnManifest } = await loadVirtualModule(\n VIRTUAL_MODULES.serverFnManifest,\n )\n\n const serverFnInfo = serverFnManifest[serverFnId]\n\n if (!serverFnInfo) {\n console.info('serverFnManifest', serverFnManifest)\n throw new Error('Server function info not found for ' + serverFnId)\n }\n\n const fnModule = await serverFnInfo.importer()\n\n if (!fnModule) {\n console.info('serverFnInfo', serverFnInfo)\n throw new Error('Server function module not resolved for ' + serverFnId)\n }\n\n const action = fnModule[serverFnInfo.functionName]\n\n if (!action) {\n console.info('serverFnInfo', serverFnInfo)\n console.info('fnModule', fnModule)\n throw new Error(\n `Server function module export not resolved for serverFn ID: ${serverFnId}`,\n )\n }\n return action\n}\n\nasync function parsePayload(payload: any) {\n const parsedPayload = startSerializer.parse(payload)\n await revive(parsedPayload, reviveServerFns)\n return parsedPayload\n}\n\nexport const handleServerAction = async ({ request }: { request: Request }) => {\n const controller = new AbortController()\n const signal = controller.signal\n const abort = () => controller.abort()\n request.signal.addEventListener('abort', abort)\n\n const method = request.method\n const url = new URL(request.url, 'http://localhost:3000')\n // extract the serverFnId from the url as host/_serverFn/:serverFnId\n // Define a regex to match the path and extract the :thing part\n const regex = new RegExp(\n `${sanitizeBase(process.env.TSS_SERVER_FN_BASE)}/([^/?#]+)`,\n )\n\n // Execute the regex\n const match = url.pathname.match(regex)\n const serverFnId = match ? match[1] : null\n const search = Object.fromEntries(url.searchParams.entries()) as {\n payload?: any\n createServerFn?: boolean\n }\n\n const isCreateServerFn = 'createServerFn' in search\n const isRaw = 'raw' in search\n\n if (typeof serverFnId !== 'string') {\n throw new Error('Invalid server action param for serverFnId: ' + serverFnId)\n }\n\n const action = await getServerFnById(serverFnId)\n\n // Known FormData 'Content-Type' header values\n const formDataContentTypes = [\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ]\n\n const response = await (async () => {\n try {\n let result = await (async () => {\n // FormData\n if (\n request.headers.get('Content-Type') &&\n formDataContentTypes.some((type) =>\n request.headers.get('Content-Type')?.includes(type),\n )\n ) {\n // We don't support GET requests with FormData payloads... that seems impossible\n invariant(\n method.toLowerCase() !== 'get',\n 'GET requests with FormData payloads are not supported',\n )\n\n return await action(await request.formData(), signal)\n }\n\n // Get requests use the query string\n if (method.toLowerCase() === 'get') {\n // By default the payload is the search params\n let payload: any = search\n\n // If this GET request was created by createServerFn,\n // then the payload will be on the payload param\n if (isCreateServerFn) {\n payload = search.payload\n }\n\n // If there's a payload, we should try to parse it\n payload = payload ? await parsePayload(payload) : payload\n\n // Send it through!\n return await action(payload, signal)\n }\n\n // This must be a POST request, likely JSON???\n const jsonPayloadAsString = await request.text()\n\n // We should probably try to deserialize the payload\n // as JSON, but we'll just pass it through for now.\n const payload = await parsePayload(jsonPayloadAsString)\n\n // If this POST request was created by createServerFn,\n // it's payload will be the only argument\n if (isCreateServerFn) {\n return await action(payload, signal)\n }\n\n // Otherwise, we'll spread the payload. Need to\n // support `use server` functions that take multiple\n // arguments.\n return await action(...(payload as any), signal)\n })()\n\n // Any time we get a Response back, we should just\n // return it immediately.\n if (result.result instanceof Response) {\n return result.result\n }\n\n // If this is a non createServerFn request, we need to\n // pull out the result from the result object\n if (!isCreateServerFn) {\n result = result.result\n\n // The result might again be a response,\n // and if it is, return it.\n if (result instanceof Response) {\n return result\n }\n }\n\n // if (!search.createServerFn) {\n // result = result.result\n // }\n\n // else if (\n // isPlainObject(result) &&\n // 'result' in result &&\n // result.result instanceof Response\n // ) {\n // return result.result\n // }\n\n // TODO: RSCs Where are we getting this package?\n // if (isValidElement(result)) {\n // const { renderToPipeableStream } = await import(\n // // @ts-expect-error\n // 'react-server-dom/server'\n // )\n\n // const pipeableStream = renderToPipeableStream(result)\n\n // setHeaders(event, {\n // 'Content-Type': 'text/x-component',\n // } as any)\n\n // sendStream(event, response)\n // event._handled = true\n\n // return new Response(null, { status: 200 })\n // }\n\n if (isNotFound(result)) {\n return isNotFoundResponse(result)\n }\n\n return new Response(\n result !== undefined ? startSerializer.stringify(result) : undefined,\n {\n status: getResponseStatus(getEvent()),\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n )\n } catch (error: any) {\n if (error instanceof Response) {\n return error\n }\n // else if (\n // isPlainObject(error) &&\n // 'result' in error &&\n // error.result instanceof Response\n // ) {\n // return error.result\n // }\n\n // Currently this server-side context has no idea how to\n // build final URLs, so we need to defer that to the client.\n // The client will check for __redirect and __notFound keys,\n // and if they exist, it will handle them appropriately.\n\n if (isNotFound(error)) {\n return isNotFoundResponse(error)\n }\n\n console.info()\n console.info('Server Fn Error!')\n console.info()\n console.error(error)\n console.info()\n\n return new Response(startSerializer.stringify(error), {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n })()\n\n request.signal.removeEventListener('abort', abort)\n\n if (isRaw) {\n return response\n }\n\n return response\n}\n\nfunction isNotFoundResponse(error: any) {\n const { headers, ...rest } = error\n\n return new Response(JSON.stringify(rest), {\n status: 200,\n headers: {\n 'Content-Type': 'application/json',\n ...(headers || {}),\n },\n })\n}\n"],"names":["holder","payload"],"mappings":";;;;;;AAOA,SAAS,aAAa,MAA0B;AAC9C,MAAI,CAAC,MAAM;AACT,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EAAA;AAGK,SAAA,KAAK,QAAQ,YAAY,EAAE;AACpC;AAEA,eAAe,OAAO,MAAW,SAA4C;AAC5D,iBAAA,WAAWA,SAAa,KAAa;AAC5C,UAAA,QAAQA,QAAO,GAAG;AAEpB,QAAA,SAAS,OAAO,UAAU,UAAU;AACtC,YAAM,QAAQ,IAAI,OAAO,KAAK,KAAK,EAAE,IAAI,CAAC,MAAM,WAAW,OAAO,CAAC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AS,GAAG,KAAA,IAAS;AAE7B,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"server-functions-handler.js","sources":["../../src/server-functions-handler.ts"],"sourcesContent":["import { isNotFound } from '@tanstack/router-core'\nimport invariant from 'tiny-invariant'\nimport { startSerializer } from '@tanstack/start-client-core'\nimport { VIRTUAL_MODULES } from './virtual-modules'\nimport { loadVirtualModule } from './loadVirtualModule'\nimport { getResponse } from './request-response'\n\nfunction sanitizeBase(base: string | undefined) {\n if (!base) {\n throw new Error(\n '🚨 process.env.TSS_SERVER_FN_BASE is required in start/server-handler/index',\n )\n }\n\n return base.replace(/^\\/|\\/$/g, '')\n}\n\nexport const handleServerAction = async ({ request }: { request: Request }) => {\n const controller = new AbortController()\n const signal = controller.signal\n const abort = () => controller.abort()\n request.signal.addEventListener('abort', abort)\n\n const method = request.method\n const url = new URL(request.url, 'http://localhost:3000')\n // extract the serverFnId from the url as host/_serverFn/:serverFnId\n // Define a regex to match the path and extract the :thing part\n const regex = new RegExp(\n `${sanitizeBase(process.env.TSS_SERVER_FN_BASE)}/([^/?#]+)`,\n )\n\n // Execute the regex\n const match = url.pathname.match(regex)\n const serverFnId = match ? match[1] : null\n const search = Object.fromEntries(url.searchParams.entries()) as {\n payload?: any\n createServerFn?: boolean\n }\n\n const isCreateServerFn = 'createServerFn' in search\n const isRaw = 'raw' in search\n\n if (typeof serverFnId !== 'string') {\n throw new Error('Invalid server action param for serverFnId: ' + serverFnId)\n }\n\n const { default: serverFnManifest } = await loadVirtualModule(\n VIRTUAL_MODULES.serverFnManifest,\n )\n\n const serverFnInfo = serverFnManifest[serverFnId]\n\n if (!serverFnInfo) {\n console.info('serverFnManifest', serverFnManifest)\n throw new Error('Server function info not found for ' + serverFnId)\n }\n\n const fnModule = await serverFnInfo.importer()\n\n if (!fnModule) {\n console.info('serverFnInfo', serverFnInfo)\n throw new Error('Server function module not resolved for ' + serverFnId)\n }\n\n const action = fnModule[serverFnInfo.functionName]\n\n if (!action) {\n console.info('serverFnInfo', serverFnInfo)\n console.info('fnModule', fnModule)\n throw new Error(\n `Server function module export not resolved for serverFn ID: ${serverFnId}`,\n )\n }\n\n // Known FormData 'Content-Type' header values\n const formDataContentTypes = [\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n ]\n\n const response = await (async () => {\n try {\n let result = await (async () => {\n // FormData\n if (\n request.headers.get('Content-Type') &&\n formDataContentTypes.some((type) =>\n request.headers.get('Content-Type')?.includes(type),\n )\n ) {\n // We don't support GET requests with FormData payloads... that seems impossible\n invariant(\n method.toLowerCase() !== 'get',\n 'GET requests with FormData payloads are not supported',\n )\n\n return await action(await request.formData(), signal)\n }\n\n // Get requests use the query string\n if (method.toLowerCase() === 'get') {\n // By default the payload is the search params\n let payload: any = search\n\n // If this GET request was created by createServerFn,\n // then the payload will be on the payload param\n if (isCreateServerFn) {\n payload = search.payload\n }\n\n // If there's a payload, we should try to parse it\n payload = payload ? startSerializer.parse(payload) : payload\n\n // Send it through!\n return await action(payload, signal)\n }\n\n // This must be a POST request, likely JSON???\n const jsonPayloadAsString = await request.text()\n\n // We should probably try to deserialize the payload\n // as JSON, but we'll just pass it through for now.\n const payload = startSerializer.parse(jsonPayloadAsString)\n\n // If this POST request was created by createServerFn,\n // it's payload will be the only argument\n if (isCreateServerFn) {\n return await action(payload, signal)\n }\n\n // Otherwise, we'll spread the payload. Need to\n // support `use server` functions that take multiple\n // arguments.\n return await action(...(payload as any), signal)\n })()\n\n // Any time we get a Response back, we should just\n // return it immediately.\n if (result.result instanceof Response) {\n return result.result\n }\n\n // If this is a non createServerFn request, we need to\n // pull out the result from the result object\n if (!isCreateServerFn) {\n result = result.result\n\n // The result might again be a response,\n // and if it is, return it.\n if (result instanceof Response) {\n return result\n }\n }\n\n // if (!search.createServerFn) {\n // result = result.result\n // }\n\n // else if (\n // isPlainObject(result) &&\n // 'result' in result &&\n // result.result instanceof Response\n // ) {\n // return result.result\n // }\n\n // TODO: RSCs Where are we getting this package?\n // if (isValidElement(result)) {\n // const { renderToPipeableStream } = await import(\n // // @ts-expect-error\n // 'react-server-dom/server'\n // )\n\n // const pipeableStream = renderToPipeableStream(result)\n\n // setHeaders(event, {\n // 'Content-Type': 'text/x-component',\n // } as any)\n\n // sendStream(event, response)\n // event._handled = true\n\n // return new Response(null, { status: 200 })\n // }\n\n if (isNotFound(result)) {\n return isNotFoundResponse(result)\n }\n\n const response = getResponse()\n return new Response(\n result !== undefined ? startSerializer.stringify(result) : undefined,\n {\n status: response?.status,\n statusText: response?.statusText,\n headers: {\n 'Content-Type': 'application/json',\n },\n },\n )\n } catch (error: any) {\n if (error instanceof Response) {\n return error\n }\n // else if (\n // isPlainObject(error) &&\n // 'result' in error &&\n // error.result instanceof Response\n // ) {\n // return error.result\n // }\n\n // Currently this server-side context has no idea how to\n // build final URLs, so we need to defer that to the client.\n // The client will check for __redirect and __notFound keys,\n // and if they exist, it will handle them appropriately.\n\n if (isNotFound(error)) {\n return isNotFoundResponse(error)\n }\n\n console.info()\n console.info('Server Fn Error!')\n console.info()\n console.error(error)\n console.info()\n\n return new Response(startSerializer.stringify(error), {\n status: 500,\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n }\n })()\n\n request.signal.removeEventListener('abort', abort)\n\n if (isRaw) {\n return response\n }\n\n return response\n}\n\nfunction isNotFoundResponse(error: any) {\n const { headers, ...rest } = error\n\n return new Response(JSON.stringify(rest), {\n status: 404,\n headers: {\n 'Content-Type': 'application/json',\n ...(headers || {}),\n },\n })\n}\n"],"names":["payload","response"],"mappings":";;;;;;AAOA,SAAS,aAAa,MAA0B;AAC9C,MAAI,CAAC,MAAM;AACT,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO,KAAK,QAAQ,YAA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AAA,QAClB;AAAA,MACF;AAAA,IAEJ,SAAS,OAAY;AACnB,UAAI,iBAAiB,UAAU;AAC7B,eAAO;AAAA,MACT;AAcA,UAAI,WAAW,KAAK,GAAG;AACrB,eAAO,mBAAmB,KAAK;AAAA,MACjC;AAEA,cAAQ,KAAA;AACR,cAAQ,KAAK,kBAAkB;AAC/B,cAAQ,KAAA;AACR,cAAQ,MAAM,KAAK;AACnB,cAAQ,KAAA;AAER,aAAO,IAAI,SAAS,gBAAgB,UAAU,KAAK,GAAG;AAAA,QACpD,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,QAAA;AAAA,MAClB,CACD;AAAA,IACH;AAAA,EACF,GAAA;AAEA,UAAQ,OAAO,oBAAoB,SAAS,KAAK;AAEjD,MAAI,OAAO;AACT,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEA,SAAS,mBAAmB,OAAY;AACtC,QAAM,EAAE,SAAS,GAAG,KAAA,IAAS;AAE7B,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,GAAI,WAAW,CAAA;AAAA,IAAC;AAAA,EAClB,CACD;AACH;"}
|
package/dist/esm/serverRoute.js
CHANGED
|
@@ -35,10 +35,9 @@ function createServerRoute(__, __opts) {
|
|
|
35
35
|
...opts
|
|
36
36
|
}),
|
|
37
37
|
init: (opts) => {
|
|
38
|
-
var _a;
|
|
39
38
|
options.originalIndex = opts.originalIndex;
|
|
40
39
|
const isRoot = !options.path && !options.id;
|
|
41
|
-
route.parentRoute =
|
|
40
|
+
route.parentRoute = options.getParentRoute?.();
|
|
42
41
|
if (isRoot) {
|
|
43
42
|
route.path = rootRouteId;
|
|
44
43
|
} else if (!route.parentRoute) {
|
|
@@ -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<\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":[],"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;A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AAM,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.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<TParentRoute, TId, TPath, TFullPath, TMiddlewares>\n}\n"],"names":[],"mappings":";AAcO,SAAS,sBAUd,GAA2E;AAC3E,SAAO,kBAEP;AACF;AA4CO,SAAS,kBAOd,IACA,QAG6D;AAC7D,QAAM,UAAU,UAAU,CAAA;AAE1B,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,CAAA;AAAA;AAAA,IASR,YAAY,CAAC,gBACX,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,MACH,YAAY;AAAA,IAAA,CACb;AAAA,IACH,SAAS,CAAC,wBAAwB;AAChC,YAAM,WAAW,MAAM;AACrB,YAAI,OAAO,wBAAwB,YAAY;AAC7C,iBAAO,oBAAoB,qBAAqB;AAAA,QAClD;AAEA,eAAO;AAAA,MACT,GAAA;AAEA,aAAO,kBAAkB,QAAW;AAAA,QAClC,GAAG;AAAA,QACH;AAAA,MAAA,CACD;AAAA,IACH;AAAA,IACA,QAAQ,CAAC,SACP,kBAAkB,QAAW;AAAA,MAC3B,GAAG;AAAA,MACH,GAAG;AAAA,IAAA,CACJ;AAAA,IACH,MAAM,CAAC,SAA0C;AAC/C,cAAQ,gBAAgB,KAAK;AAE7B,YAAM,SAAS,CAAC,Q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AA,IACH,SAAS,CAAC,YACR,oBAAoB;AAAA,MAClB,GAAG;AAAA,MACH;AAAA,IAAA,CACD;AAAA,EAAA;AAEP;"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { CookieSerializeOptions } from 'cookie-es';
|
|
2
|
+
/** Algorithm used for encryption and decryption. */
|
|
3
|
+
type EncryptionAlgorithm = 'aes-128-ctr' | 'aes-256-cbc';
|
|
4
|
+
/** Algorithm used for integrity verification. */
|
|
5
|
+
type IntegrityAlgorithm = 'sha256';
|
|
6
|
+
/** @internal */
|
|
7
|
+
type _Algorithm = EncryptionAlgorithm | IntegrityAlgorithm;
|
|
8
|
+
/**
|
|
9
|
+
* Options for customizing the key derivation algorithm used to generate encryption and integrity verification keys as well as the algorithms and salt sizes used.
|
|
10
|
+
*/
|
|
11
|
+
type SealOptions = Readonly<{
|
|
12
|
+
/** Encryption step options. */
|
|
13
|
+
encryption: SealOptionsSub<EncryptionAlgorithm>;
|
|
14
|
+
/** Integrity step options. */
|
|
15
|
+
integrity: SealOptionsSub<IntegrityAlgorithm>;
|
|
16
|
+
ttl: number;
|
|
17
|
+
/** Number of seconds of permitted clock skew for incoming expirations. Defaults to 60 seconds. */
|
|
18
|
+
timestampSkewSec: number;
|
|
19
|
+
/**
|
|
20
|
+
* Local clock time offset, expressed in number of milliseconds (positive or negative). Defaults to 0.
|
|
21
|
+
*/
|
|
22
|
+
localtimeOffsetMsec: number;
|
|
23
|
+
}>;
|
|
24
|
+
/** `seal()` method options. */
|
|
25
|
+
type SealOptionsSub<TAlgorithm extends _Algorithm = _Algorithm> = Readonly<{
|
|
26
|
+
/** The length of the salt (random buffer used to ensure that two identical objects will generate a different encrypted result). Defaults to 256. */
|
|
27
|
+
saltBits: number;
|
|
28
|
+
/** The algorithm used. Defaults to 'aes-256-cbc' for encryption and 'sha256' for integrity. */
|
|
29
|
+
algorithm: TAlgorithm;
|
|
30
|
+
/** The number of iterations used to derive a key from the password. Defaults to 1. */
|
|
31
|
+
iterations: number;
|
|
32
|
+
/** Minimum password size. Defaults to 32. */
|
|
33
|
+
minPasswordlength: number;
|
|
34
|
+
}>;
|
|
35
|
+
/** Password secret string or buffer.*/
|
|
36
|
+
type SessionDataT = Record<string, any>;
|
|
37
|
+
export type SessionData<T extends SessionDataT = SessionDataT> = Partial<T>;
|
|
38
|
+
export interface Session<T extends SessionDataT = SessionDataT> {
|
|
39
|
+
id: string;
|
|
40
|
+
createdAt: number;
|
|
41
|
+
data: SessionData<T>;
|
|
42
|
+
}
|
|
43
|
+
export type SessionUpdate<T extends SessionData = SessionData> = Partial<SessionData<T>> | ((oldData: SessionData<T>) => Partial<SessionData<T>> | undefined);
|
|
44
|
+
export interface SessionManager<T extends SessionDataT = SessionDataT> {
|
|
45
|
+
readonly id: string | undefined;
|
|
46
|
+
readonly data: SessionData<T>;
|
|
47
|
+
update: (update: SessionUpdate<T>) => Promise<SessionManager<T>>;
|
|
48
|
+
clear: () => Promise<SessionManager<T>>;
|
|
49
|
+
}
|
|
50
|
+
export interface SessionConfig {
|
|
51
|
+
/** Private key used to encrypt session tokens */
|
|
52
|
+
password: string;
|
|
53
|
+
/** Session expiration time in seconds */
|
|
54
|
+
maxAge?: number;
|
|
55
|
+
/** default is 'start' */
|
|
56
|
+
name?: string;
|
|
57
|
+
/** Default is secure, httpOnly, / */
|
|
58
|
+
cookie?: false | CookieSerializeOptions;
|
|
59
|
+
/** Default is x-start-session / x-{name}-session */
|
|
60
|
+
sessionHeader?: false | string;
|
|
61
|
+
seal?: SealOptions;
|
|
62
|
+
crypto?: Crypto;
|
|
63
|
+
/** Default is Crypto.randomUUID */
|
|
64
|
+
generateId?: () => string;
|
|
65
|
+
}
|
|
66
|
+
export {};
|
|
@@ -2,9 +2,11 @@ export declare const VIRTUAL_MODULES: {
|
|
|
2
2
|
readonly routeTree: "tanstack-start-route-tree:v";
|
|
3
3
|
readonly startManifest: "tanstack-start-manifest:v";
|
|
4
4
|
readonly serverFnManifest: "tanstack-start-server-fn-manifest:v";
|
|
5
|
+
readonly injectedHeadScripts: "tanstack-start-injected-head-scripts:v";
|
|
5
6
|
};
|
|
6
7
|
export type VirtualModules = {
|
|
7
8
|
[VIRTUAL_MODULES.routeTree]: typeof import('tanstack-start-route-tree:v');
|
|
8
9
|
[VIRTUAL_MODULES.startManifest]: typeof import('tanstack-start-manifest:v');
|
|
9
10
|
[VIRTUAL_MODULES.serverFnManifest]: typeof import('tanstack-start-server-fn-manifest:v');
|
|
11
|
+
[VIRTUAL_MODULES.injectedHeadScripts]: typeof import('tanstack-start-injected-head-scripts:v');
|
|
10
12
|
};
|