-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathrequest-response.ts
More file actions
419 lines (371 loc) · 11.1 KB
/
request-response.ts
File metadata and controls
419 lines (371 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import { AsyncLocalStorage } from 'node:async_hooks'
import {
H3Event,
clearSession as h3_clearSession,
deleteCookie as h3_deleteCookie,
getRequestHost as h3_getRequestHost,
getRequestIP as h3_getRequestIP,
getRequestProtocol as h3_getRequestProtocol,
getRequestURL as h3_getRequestURL,
getSession as h3_getSession,
getValidatedQuery as h3_getValidatedQuery,
parseCookies as h3_parseCookies,
sanitizeStatusCode as h3_sanitizeStatusCode,
sanitizeStatusMessage as h3_sanitizeStatusMessage,
sealSession as h3_sealSession,
setCookie as h3_setCookie,
toResponse as h3_toResponse,
unsealSession as h3_unsealSession,
updateSession as h3_updateSession,
useSession as h3_useSession,
} from 'h3'
import type {
RequestHeaderMap,
RequestHeaderName,
ResponseHeaderMap,
ResponseHeaderName,
TypedHeaders,
} from 'fetchdts'
import type { CookieSerializeOptions } from 'cookie-es'
import type {
Session,
SessionConfig,
SessionData,
SessionManager,
SessionUpdate,
} from './session'
import type { StandardSchemaV1 } from '@standard-schema/spec'
import type { RequestHandler } from './request-handler'
interface StartEvent {
h3Event: H3Event
}
// Use a global symbol to ensure the same AsyncLocalStorage instance is shared
// across different bundles that may each bundle this module.
const GLOBAL_EVENT_STORAGE_KEY = Symbol.for('tanstack-start:event-storage')
const globalObj = globalThis as typeof globalThis & {
[GLOBAL_EVENT_STORAGE_KEY]?: AsyncLocalStorage<StartEvent>
}
if (!globalObj[GLOBAL_EVENT_STORAGE_KEY]) {
globalObj[GLOBAL_EVENT_STORAGE_KEY] = new AsyncLocalStorage<StartEvent>()
}
const eventStorage = globalObj[GLOBAL_EVENT_STORAGE_KEY]
export type { ResponseHeaderName, RequestHeaderName }
type HeadersWithGetSetCookie = Headers & {
getSetCookie?: () => Array<string>
}
type MaybePromise<T> = T | Promise<T>
function isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {
return typeof (value as Promise<T>).then === 'function'
}
function getSetCookieValues(headers: Headers): Array<string> {
const headersWithSetCookie = headers as HeadersWithGetSetCookie
if (typeof headersWithSetCookie.getSetCookie === 'function') {
return headersWithSetCookie.getSetCookie()
}
const value = headers.get('set-cookie')
return value ? [value] : []
}
function mergeEventResponseHeaders(response: Response, event: H3Event): void {
if (response.ok) {
return
}
const eventSetCookies = getSetCookieValues(event.res.headers)
if (eventSetCookies.length === 0) {
return
}
const responseSetCookies = getSetCookieValues(response.headers)
response.headers.delete('set-cookie')
for (const cookie of responseSetCookies) {
response.headers.append('set-cookie', cookie)
}
for (const cookie of eventSetCookies) {
response.headers.append('set-cookie', cookie)
}
}
function attachResponseHeaders<T>(
value: MaybePromise<T>,
event: H3Event,
): MaybePromise<T> {
if (isPromiseLike(value)) {
return value.then((resolved) => {
if (resolved instanceof Response) {
mergeEventResponseHeaders(resolved, event)
}
return resolved
})
}
if (value instanceof Response) {
mergeEventResponseHeaders(value, event)
}
return value
}
export function requestHandler<TRegister = unknown>(
handler: RequestHandler<TRegister>,
) {
return (request: Request, requestOpts: any): Promise<Response> | Response => {
const h3Event = new H3Event(request)
const response = eventStorage.run({ h3Event }, () =>
handler(request, requestOpts),
)
return h3_toResponse(attachResponseHeaders(response, h3Event), h3Event)
}
}
function getH3Event() {
const event = eventStorage.getStore()
if (!event) {
throw new Error(
`No StartEvent found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`,
)
}
return event.h3Event
}
export function getRequest(): Request {
const event = getH3Event()
return event.req
}
export function getRequestHeaders(): TypedHeaders<RequestHeaderMap> {
return getH3Event().req.headers
}
export function getRequestHeader(name: RequestHeaderName): string | undefined {
return getRequestHeaders().get(name) || undefined
}
export function getRequestIP(opts?: {
/**
* Use the X-Forwarded-For HTTP header set by proxies.
*
* Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.
*/
xForwardedFor?: boolean
}) {
return h3_getRequestIP(getH3Event(), opts)
}
/**
* Get the request hostname.
*
* If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
*
* If no host header is found, it will default to "localhost".
*/
export function getRequestHost(opts?: { xForwardedHost?: boolean }) {
return h3_getRequestHost(getH3Event(), opts)
}
/**
* Get the full incoming request URL.
*
* If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
*
* If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.
*/
export function getRequestUrl(opts?: {
xForwardedHost?: boolean
xForwardedProto?: boolean
}) {
return h3_getRequestURL(getH3Event(), opts)
}
/**
* Get the request protocol.
*
* If `x-forwarded-proto` header is set to "https", it will return "https". You can disable this behavior by setting `xForwardedProto` to `false`.
*
* If protocol cannot be determined, it will default to "http".
*/
export function getRequestProtocol(opts?: {
xForwardedProto?: boolean
}): 'http' | 'https' | (string & {}) {
return h3_getRequestProtocol(getH3Event(), opts)
}
export function setResponseHeaders(
headers: TypedHeaders<ResponseHeaderMap>,
): void {
const event = getH3Event()
for (const [name, value] of Object.entries(headers)) {
event.res.headers.set(name, value)
}
}
export function getResponseHeaders(): TypedHeaders<ResponseHeaderMap> {
const event = getH3Event()
return event.res.headers
}
export function getResponseHeader(
name: ResponseHeaderName,
): string | undefined {
const event = getH3Event()
return event.res.headers.get(name) || undefined
}
export function setResponseHeader(
name: ResponseHeaderName,
value: string | Array<string>,
): void {
const event = getH3Event()
if (Array.isArray(value)) {
event.res.headers.delete(name)
for (const valueItem of value) {
event.res.headers.append(name, valueItem)
}
} else {
event.res.headers.set(name, value)
}
}
export function removeResponseHeader(name: ResponseHeaderName): void {
const event = getH3Event()
event.res.headers.delete(name)
}
export function clearResponseHeaders(
headerNames?: Array<ResponseHeaderName>,
): void {
const event = getH3Event()
// If headerNames is provided, clear only those headers
if (headerNames && headerNames.length > 0) {
for (const name of headerNames) {
event.res.headers.delete(name)
}
// Otherwise, clear all headers
} else {
for (const name of event.res.headers.keys()) {
event.res.headers.delete(name)
}
}
}
export function getResponseStatus(): number {
return getH3Event().res.status || 200
}
export function setResponseStatus(code?: number, text?: string): void {
const event = getH3Event()
if (code) {
event.res.status = h3_sanitizeStatusCode(code, event.res.status)
}
if (text) {
event.res.statusText = h3_sanitizeStatusMessage(text)
}
}
/**
* Parse the request to get HTTP Cookie header string and return an object of all cookie name-value pairs.
* @returns Object of cookie name-value pairs
* ```ts
* const cookies = getCookies()
* ```
*/
export function getCookies(): Record<string, string> {
const event = getH3Event()
const cookies = h3_parseCookies(event)
const normalizedCookies: Record<string, string> = Object.create(null)
for (const [name, value] of Object.entries(cookies)) {
if (value !== undefined) {
normalizedCookies[name] = value
}
}
return normalizedCookies
}
/**
* Get a cookie value by name.
* @param name Name of the cookie to get
* @returns {*} Value of the cookie (String or undefined)
* ```ts
* const authorization = getCookie('Authorization')
* ```
*/
export function getCookie(name: string): string | undefined {
const event = getH3Event()
const cookies = h3_parseCookies(event)
return cookies[name] || undefined
}
/**
* Set a cookie value by name.
* @param name Name of the cookie to set
* @param value Value of the cookie to set
* @param options {CookieSerializeOptions} Options for serializing the cookie
* ```ts
* setCookie('Authorization', '1234567')
* ```
*/
export function setCookie(
name: string,
value: string,
options?: CookieSerializeOptions,
): void {
const event = getH3Event()
h3_setCookie(event, name, value, options)
}
/**
* Remove a cookie by name.
* @param name Name of the cookie to delete
* @param serializeOptions {CookieSerializeOptions} Cookie options
* ```ts
* deleteCookie('SessionId')
* ```
*/
export function deleteCookie(
name: string,
options?: CookieSerializeOptions,
): void {
const event = getH3Event()
h3_deleteCookie(event, name, options)
}
function getDefaultSessionConfig(config: SessionConfig): SessionConfig {
return {
name: 'start',
...config,
}
}
/**
* Create a session manager for the current request.
*/
export function useSession<TSessionData extends SessionData = SessionData>(
config: SessionConfig,
): Promise<SessionManager<TSessionData>> {
const event = getH3Event()
return h3_useSession(event, getDefaultSessionConfig(config))
}
/**
* Get the session for the current request
*/
export function getSession<TSessionData extends SessionData = SessionData>(
config: SessionConfig,
): Promise<Session<TSessionData>> {
const event = getH3Event()
return h3_getSession(event, getDefaultSessionConfig(config))
}
/**
* Update the session data for the current request.
*/
export function updateSession<TSessionData extends SessionData = SessionData>(
config: SessionConfig,
update?: SessionUpdate<TSessionData>,
): Promise<Session<TSessionData>> {
const event = getH3Event()
return h3_updateSession(event, getDefaultSessionConfig(config), update)
}
/**
* Encrypt and sign the session data for the current request.
*/
export function sealSession(config: SessionConfig): Promise<string> {
const event = getH3Event()
return h3_sealSession(event, getDefaultSessionConfig(config))
}
/**
* Decrypt and verify the session data for the current request.
*/
export function unsealSession(
config: SessionConfig,
sealed: string,
): Promise<Partial<Session>> {
const event = getH3Event()
return h3_unsealSession(event, getDefaultSessionConfig(config), sealed)
}
/**
* Clear the session data for the current request.
*/
export function clearSession(config: Partial<SessionConfig>): Promise<void> {
const event = getH3Event()
return h3_clearSession(event, { name: 'start', ...config })
}
export function getResponse() {
const event = getH3Event()
return event.res
}
// not public API (yet)
export function getValidatedQuery<TSchema extends StandardSchemaV1>(
schema: StandardSchemaV1,
): Promise<StandardSchemaV1.InferOutput<TSchema>> {
return h3_getValidatedQuery(getH3Event(), schema)
}