/
utils.ts
771 lines (660 loc) · 18.6 KB
/
utils.ts
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
import { Kind, TSchema } from '@sinclair/typebox'
import { Value } from '@sinclair/typebox/value'
import { TypeCheck, TypeCompiler } from '@sinclair/typebox/compiler'
import { t } from '.'
import { isNotEmpty } from './handler'
import type {
LifeCycleStore,
LocalHook,
MaybeArray,
InputSchema,
BaseMacro,
ElysiaFn,
LifeCycleType
} from './types'
import type { CookieOptions } from './cookies'
export const replaceUrlPath = (url: string, pathname: string) => {
const urlObject = new URL(url)
urlObject.pathname = pathname
return urlObject.toString()
}
const isClass = (v: Object) =>
(typeof v === 'function' && /^\s*class\s+/.test(v.toString())) ||
// Handle import * as Sentry from '@sentry/bun'
// This also handle [object Date], [object Array]
// and FFI value like [object Prisma]
v.toString().startsWith('[object ') ||
// If object prototype is not pure, then probably a class-like object
isNotEmpty(Object.getPrototypeOf(v))
const isObject = (item: any): item is Object =>
item && typeof item === 'object' && !Array.isArray(item)
export const mergeDeep = <
A extends Record<string, any>,
B extends Record<string, any>
>(
target: A,
source: B,
{
skipKeys
}: {
skipKeys?: string[]
} = {}
): A & B => {
if (isObject(target) && isObject(source))
for (const [key, value] of Object.entries(source)) {
if (skipKeys?.includes(key)) continue
if (!isObject(value) || !(key in target) || isClass(value)) {
target[key as keyof typeof target] = value
continue
}
target[key as keyof typeof target] = mergeDeep(
(target as any)[key] as any,
value
)
}
return target as A & B
}
export const mergeCookie = <const A extends Object, const B extends Object>(
a: A,
b: B
): A & B => {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { properties: _, ...target } = a ?? {}
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { properties: __, ...source } = b ?? {}
return mergeDeep(target, source) as A & B
}
export const mergeObjectArray = <T extends ElysiaFn>(
a: T | T[] = [],
b: T | T[] = []
): T[] => {
if (!a) return []
// ! Must copy to remove side-effect
const array = <T[]>[]
const checksums = <(number | undefined)[]>[]
if (!Array.isArray(a)) a = [a]
if (!Array.isArray(b)) b = [b]
for (const item of a) {
array.push(item)
if (item.$elysiaChecksum) checksums.push(item.$elysiaChecksum)
}
for (const item of b)
if (!checksums.includes(item?.$elysiaChecksum)) array.push(item)
return array
}
export const primitiveHooks = [
'start',
'request',
'parse',
'transform',
'resolve',
'beforeHandle',
'afterHandle',
'onResponse',
'mapResponse',
'trace',
'error',
'stop',
'body',
'headers',
'params',
'query',
'response',
'type',
'detail'
] as const
const primitiveHookMap = primitiveHooks.reduce(
(acc, x) => ((acc[x] = true), acc),
{} as Record<string, boolean>
)
export const mergeHook = (
a?: LocalHook<any, any, any, any, any, any, any> | LifeCycleStore,
b?: LocalHook<any, any, any, any, any, any, any>
): LifeCycleStore => {
// In case if merging union is need
// const customAStore: Record<string, unknown> = {}
// const customBStore: Record<string, unknown> = {}
// for (const [key, value] of Object.entries(a)) {
// if (primitiveHooks.includes(key as any)) continue
// customAStore[key] = value
// }
// for (const [key, value] of Object.entries(b)) {
// if (primitiveHooks.includes(key as any)) continue
// customBStore[key] = value
// }
// const unioned = Object.keys(customAStore).filter((x) =>
// Object.keys(customBStore).includes(x)
// )
// // Must provide empty object to prevent reference side-effect
// const customStore = Object.assign({}, customAStore, customBStore)
// for (const union of unioned)
// customStore[union] = mergeObjectArray(
// customAStore[union],
// customBStore[union]
// )
return {
...a,
...b,
// Merge local hook first
// @ts-ignore
body: b?.body ?? a?.body,
// @ts-ignore
headers: b?.headers ?? a?.headers,
// @ts-ignore
params: b?.params ?? a?.params,
// @ts-ignore
query: b?.query ?? a?.query,
// @ts-ignore
response: b?.response ?? a?.response,
type: a?.type || b?.type,
detail: mergeDeep(
// @ts-ignore
b?.detail ?? {},
// @ts-ignore
a?.detail ?? {}
),
parse: mergeObjectArray(a?.parse as any, b?.parse),
transform: mergeObjectArray(a?.transform, b?.transform),
beforeHandle: mergeObjectArray(a?.beforeHandle, b?.beforeHandle),
afterHandle: mergeObjectArray(a?.afterHandle, b?.afterHandle),
onResponse: mergeObjectArray(a?.onResponse, b?.onResponse) as any,
mapResponse: mergeObjectArray(a?.mapResponse, b?.mapResponse) as any,
trace: mergeObjectArray(a?.trace, b?.trace) as any,
error: mergeObjectArray(a?.error, b?.error)
}
}
export const getSchemaValidator = (
s: TSchema | string | undefined,
{
models = {},
additionalProperties = false,
dynamic = false
}: {
models?: Record<string, TSchema>
additionalProperties?: boolean
dynamic?: boolean
}
) => {
if (!s) return
if (typeof s === 'string' && !(s in models)) return
const schema: TSchema = typeof s === 'string' ? models[s] : s
// @ts-ignore
if (schema.type === 'object' && 'additionalProperties' in schema === false)
schema.additionalProperties = additionalProperties
if (dynamic)
return {
schema,
references: '',
checkFunc: () => {},
code: '',
Check: (value: unknown) => Value.Check(schema, value),
Errors: (value: unknown) => Value.Errors(schema, value),
Code: () => ''
} as unknown as TypeCheck<TSchema>
return TypeCompiler.Compile(schema, Object.values(models))
}
export const getResponseSchemaValidator = (
s: InputSchema['response'] | undefined,
{
models = {},
additionalProperties = false,
dynamic = false
}: {
models?: Record<string, TSchema>
additionalProperties?: boolean
dynamic?: boolean
}
): Record<number, TypeCheck<any>> | undefined => {
if (!s) return
if (typeof s === 'string' && !(s in models)) return
const maybeSchemaOrRecord = typeof s === 'string' ? models[s] : s
const compile = (schema: TSchema, references?: TSchema[]) => {
if (dynamic)
return {
schema,
references: '',
checkFunc: () => {},
code: '',
Check: (value: unknown) => Value.Check(schema, value),
Errors: (value: unknown) => Value.Errors(schema, value),
Code: () => ''
} as unknown as TypeCheck<TSchema>
return TypeCompiler.Compile(schema, references)
}
if (Kind in maybeSchemaOrRecord) {
if ('additionalProperties' in maybeSchemaOrRecord === false)
maybeSchemaOrRecord.additionalProperties = additionalProperties
return {
200: compile(maybeSchemaOrRecord, Object.values(models))
}
}
const record: Record<number, TypeCheck<any>> = {}
Object.keys(maybeSchemaOrRecord).forEach((status): TSchema | undefined => {
const maybeNameOrSchema = maybeSchemaOrRecord[+status]
if (typeof maybeNameOrSchema === 'string') {
if (maybeNameOrSchema in models) {
const schema = models[maybeNameOrSchema]
schema.type === 'object' &&
'additionalProperties' in schema === false
// Inherits model maybe already compiled
record[+status] =
Kind in schema
? compile(schema, Object.values(models))
: schema
}
return undefined
}
if (
maybeNameOrSchema.type === 'object' &&
'additionalProperties' in maybeNameOrSchema === false
)
maybeNameOrSchema.additionalProperties = additionalProperties
// Inherits model maybe already compiled
record[+status] =
Kind in maybeNameOrSchema
? compile(maybeNameOrSchema, Object.values(models))
: maybeNameOrSchema
})
return record
}
const isBun = typeof Bun !== 'undefined'
const hasHash = isBun && typeof Bun.hash === 'function'
// https://stackoverflow.com/a/52171480
export const checksum = (s: string) => {
if (hasHash) return Bun.hash(s) as number
let h = 9
for (let i = 0; i < s.length; ) h = Math.imul(h ^ s.charCodeAt(i++), 9 ** 9)
return (h = h ^ (h >>> 9))
}
export const getCookieValidator = ({
validator,
defaultConfig = {},
config,
dynamic,
models
}: {
validator: TSchema | string | undefined
defaultConfig: CookieOptions | undefined
config: CookieOptions
dynamic: boolean
models: Record<string, TSchema> | undefined
}) => {
let cookieValidator = getSchemaValidator(validator, {
dynamic,
models,
additionalProperties: true
})
if (isNotEmpty(defaultConfig)) {
if (cookieValidator) {
// @ts-expect-error private
cookieValidator.schema = mergeCookie(
// @ts-expect-error private
cookieValidator.schema,
config
)
} else {
cookieValidator = getSchemaValidator(t.Cookie({}, defaultConfig), {
dynamic,
models,
additionalProperties: true
})
}
}
return cookieValidator
}
export const mergeLifeCycle = (
a: LifeCycleStore,
b: LifeCycleStore | LocalHook<any, any, any, any, any, any, any>,
checksum?: number
): LifeCycleStore => {
const injectChecksum = (x: MaybeArray<ElysiaFn> | undefined) => {
if (!x) return
if (!Array.isArray(x)) {
// ? clone fn is required to prevent side-effect from changing hookType
const fn = x
if (checksum && !fn.$elysiaChecksum) fn.$elysiaChecksum = checksum
if (fn.$elysiaHookType === 'scoped') fn.$elysiaHookType = 'local'
return fn
}
// ? clone fns is required to prevent side-effect from changing hookType
const fns = [...x]
for (const fn of fns) {
if (checksum && !fn.$elysiaChecksum) fn.$elysiaChecksum = checksum
if (fn.$elysiaHookType === 'scoped') fn.$elysiaHookType = 'local'
}
return fns
}
return {
...a,
...b,
start: mergeObjectArray(a.start, injectChecksum(b?.start)),
request: mergeObjectArray(a.request, injectChecksum(b?.request)),
parse: mergeObjectArray(a.parse, injectChecksum(b?.parse)),
transform: mergeObjectArray(a.transform, injectChecksum(b?.transform)),
beforeHandle: mergeObjectArray(
a.beforeHandle,
injectChecksum(b?.beforeHandle)
),
afterHandle: mergeObjectArray(
a.afterHandle,
injectChecksum(b?.afterHandle)
),
mapResponse: mergeObjectArray(
a.mapResponse,
injectChecksum(b?.mapResponse)
),
onResponse: mergeObjectArray(
a.onResponse,
injectChecksum(b?.onResponse)
),
// Already merged on Elysia._use, also logic is more complicated, can't directly merge
trace: a.trace,
error: mergeObjectArray(a.error, injectChecksum(b?.error)),
stop: mergeObjectArray(a.stop, injectChecksum(b?.stop))
}
}
export const asHookType = <T extends MaybeArray<ElysiaFn> | undefined>(
fn: T,
inject: LifeCycleType,
{ skipIfHasType = false }: { skipIfHasType?: boolean } = {}
): T => {
if (!fn) return fn
if (typeof fn === 'function') {
if (skipIfHasType) fn.$elysiaHookType ??= inject
else fn.$elysiaHookType = inject
return fn
}
if (!Array.isArray(fn)) return fn
for (const x of fn)
if (skipIfHasType) x.$elysiaHookType ??= inject
else x.$elysiaHookType = inject
return fn
}
const filterGlobal = <T extends MaybeArray<ElysiaFn> | undefined>(
fn: T
): T | undefined => {
if (!fn) return fn
if (typeof fn === 'function')
switch (fn.$elysiaHookType) {
case 'global':
case 'scoped':
return fn
default:
return undefined
}
if (!Array.isArray(fn)) return <any>[]
const array = <any>[]
for (const x of fn)
switch (x.$elysiaHookType) {
case 'global':
case 'scoped':
array.push(x)
break
}
return array as T
}
export const filterGlobalHook = (
hook: LocalHook<any, any, any, any, any, any, any>
): LocalHook<any, any, any, any, any, any, any> => {
return {
// rest is validator
...hook,
type: hook?.type,
detail: hook?.detail,
parse: filterGlobal(hook?.parse),
transform: filterGlobal(hook?.transform),
beforeHandle: filterGlobal(hook?.beforeHandle),
afterHandle: filterGlobal(hook?.afterHandle),
onResponse: filterGlobal(hook?.onResponse),
error: filterGlobal(hook?.error),
mapResponse: filterGlobal(hook?.mapResponse)
} as LocalHook<any, any, any, any, any, any, any>
}
export const StatusMap = {
Continue: 100,
'Switching Protocols': 101,
Processing: 102,
'Early Hints': 103,
OK: 200,
Created: 201,
Accepted: 202,
'Non-Authoritative Information': 203,
'No Content': 204,
'Reset Content': 205,
'Partial Content': 206,
'Multi-Status': 207,
'Already Reported': 208,
'Multiple Choices': 300,
'Moved Permanently': 301,
Found: 302,
'See Other': 303,
'Not Modified': 304,
'Temporary Redirect': 307,
'Permanent Redirect': 308,
'Bad Request': 400,
Unauthorized: 401,
'Payment Required': 402,
Forbidden: 403,
'Not Found': 404,
'Method Not Allowed': 405,
'Not Acceptable': 406,
'Proxy Authentication Required': 407,
'Request Timeout': 408,
Conflict: 409,
Gone: 410,
'Length Required': 411,
'Precondition Failed': 412,
'Payload Too Large': 413,
'URI Too Long': 414,
'Unsupported Media Type': 415,
'Range Not Satisfiable': 416,
'Expectation Failed': 417,
"I'm a teapot": 418,
'Misdirected Request': 421,
'Unprocessable Content': 422,
Locked: 423,
'Failed Dependency': 424,
'Too Early': 425,
'Upgrade Required': 426,
'Precondition Required': 428,
'Too Many Requests': 429,
'Request Header Fields Too Large': 431,
'Unavailable For Legal Reasons': 451,
'Internal Server Error': 500,
'Not Implemented': 501,
'Bad Gateway': 502,
'Service Unavailable': 503,
'Gateway Timeout': 504,
'HTTP Version Not Supported': 505,
'Variant Also Negotiates': 506,
'Insufficient Storage': 507,
'Loop Detected': 508,
'Not Extended': 510,
'Network Authentication Required': 511
} as const
export const InvertedStatusMap = Object.fromEntries(
Object.entries(StatusMap).map(([k, v]) => [v, k])
) as {
[K in keyof StatusMap as StatusMap[K]]: K
}
export type StatusMap = typeof StatusMap
export type InvertedStatusMap = typeof InvertedStatusMap
function removeTrailingEquals(digest: string): string {
let trimmedDigest = digest
while (trimmedDigest.endsWith('=')) {
trimmedDigest = trimmedDigest.slice(0, -1)
}
return trimmedDigest
}
const encoder = new TextEncoder()
export const signCookie = async (val: string, secret: string | null) => {
if (typeof val !== 'string')
throw new TypeError('Cookie value must be provided as a string.')
if (secret === null) throw new TypeError('Secret key must be provided.')
const secretKey = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const hmacBuffer = await crypto.subtle.sign(
'HMAC',
secretKey,
encoder.encode(val)
)
return (
val +
'.' +
removeTrailingEquals(Buffer.from(hmacBuffer).toString('base64'))
)
}
export const unsignCookie = async (input: string, secret: string | null) => {
if (typeof input !== 'string')
throw new TypeError('Signed cookie string must be provided.')
if (null === secret) throw new TypeError('Secret key must be provided.')
const tentativeValue = input.slice(0, input.lastIndexOf('.'))
const expectedInput = await signCookie(tentativeValue, secret)
return expectedInput === input ? tentativeValue : false
}
export const traceBackMacro = (
extension: unknown,
property: Record<string, unknown>,
hooks = property
) => {
if (!extension || typeof extension !== 'object' || !property) return
for (const [key, value] of Object.entries(property)) {
if (key in primitiveHookMap || !(key in extension)) continue
const v = extension[
key as unknown as keyof typeof extension
] as BaseMacro[string]
if (typeof v === 'function') {
v(value)
} else if (typeof v === 'object')
traceBackMacro(v as BaseMacro, value as any, hooks)
}
}
export const createMacroManager =
({
globalHook,
localHook
}: {
globalHook: LifeCycleStore
localHook: LocalHook<any, any, any, any, any, any, any>
}) =>
(stackName: keyof LifeCycleStore) =>
(
type:
| {
insert?: 'before' | 'after'
stack?: 'global' | 'local'
}
| MaybeArray<Function>,
fn?: MaybeArray<Function>
) => {
if (typeof type === 'function' || Array.isArray(type)) {
if (!localHook[stackName]) localHook[stackName] = []
if (typeof localHook[stackName] === 'function')
localHook[stackName] = [localHook[stackName]]
if (Array.isArray(type))
localHook[stackName] = (
localHook[stackName] as unknown[]
).concat(type) as any
else localHook[stackName].push(type)
return
}
const { insert = 'after', stack = 'local' } = type
if (stack === 'global') {
if (!Array.isArray(fn)) {
if (insert === 'before') {
;(globalHook[stackName] as any[]).unshift(fn)
} else {
;(globalHook[stackName] as any[]).push(fn)
}
} else {
if (insert === 'before') {
globalHook[stackName] = fn.concat(
globalHook[stackName] as any
) as any
} else {
globalHook[stackName] = (
globalHook[stackName] as any[]
).concat(fn)
}
}
} else {
if (!localHook[stackName]) localHook[stackName] = []
if (typeof localHook[stackName] === 'function')
localHook[stackName] = [localHook[stackName]]
if (!Array.isArray(fn)) {
if (insert === 'before') {
;(localHook[stackName] as any[]).unshift(fn)
} else {
;(localHook[stackName] as any[]).push(fn)
}
} else {
if (insert === 'before') {
localHook[stackName] = fn.concat(localHook[stackName])
} else {
localHook[stackName] = localHook[stackName].concat(fn)
}
}
}
}
export const isNumericString = (message: string): boolean => {
if (message.length < 16)
return message.trim().length !== 0 && !Number.isNaN(Number(message))
// if 16 digit but less then 9,007,199,254,740,991 then can be parsed
if (message.length === 16) {
const numVal = Number(message)
if (numVal.toString() === message)
return message.trim().length !== 0 && !Number.isNaN(numVal)
}
return false
}
export class PromiseGroup implements PromiseLike<void> {
private root: Promise<any> | null = null
private promises: Promise<any>[] = []
constructor(public onError: (error: any) => void = console.error) {}
/**
* The number of promises still being awaited.
*/
get size() {
return this.promises.length
}
/**
* Add a promise to the group.
* @returns The promise that was added.
*/
add<T>(promise: Promise<T>) {
this.promises.push(promise)
this.root ||= this.drain()
return promise
}
private async drain() {
while (this.promises.length > 0) {
try {
await this.promises[0]
this.promises.shift()
} catch (error) {
this.onError(error)
}
}
this.root = null
}
// Allow the group to be awaited.
then<TResult1 = void, TResult2 = never>(
onfulfilled?:
| ((value: void) => TResult1 | PromiseLike<TResult1>)
| undefined
| null,
onrejected?:
| ((reason: any) => TResult2 | PromiseLike<TResult2>)
| undefined
| null
): PromiseLike<TResult1 | TResult2> {
return (this.root ?? Promise.resolve()).then(onfulfilled, onrejected)
}
}