-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
48 lines (44 loc) · 2.14 KB
/
index.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
/**
* @public
*/
export declare namespace ParseUrlParams {
export type ParserError<T extends string> = { error: true } & T
// remove matcher groups
export type CleanKey<State extends string> = string extends State
? ParserError<"CleanKey got generic string type">
: State extends `${infer Key}(${infer _})${infer Rest}`
? `${Key}${Rest}`
: State
export type AddUrlSection<State extends string, Memo extends Record<string, any> = {}> = string extends State
? ParserError<"AddUrlSection got generic string type">
: CleanKey<State> extends `${infer Key}/`
? AddKeyValue<Memo, Key, string>
: CleanKey<State> extends `${infer Key}*${infer Rest}`
? ParseUrlParams<Rest, AddOptionalKeyValue<Memo, Key, string[]>>
: CleanKey<State> extends `${infer Key}/${infer Rest}`
? ParseUrlParams<Rest, AddKeyValue<Memo, Key, string>>
: CleanKey<State> extends `${infer Key}+${infer Rest}`
? ParseUrlParams<Rest, AddKeyValue<Memo, Key, string[]>>
: CleanKey<State> extends `${infer Key}?${infer Rest}`
? ParseUrlParams<Rest, AddOptionalKeyValue<Memo, Key, string>>
: CleanKey<State> extends `${infer Key}.${infer Rest}`
? ParseUrlParams<Rest, AddKeyValue<Memo, Key, string>>
: CleanKey<State> extends `${infer Key}-${infer Rest}`
? ParseUrlParams<Rest, AddKeyValue<Memo, Key, string>>
: CleanKey<State> extends `${infer Key}`
? AddKeyValue<Memo, Key, string>
: ParseUrlParams<`AddUrlSection returned unexpected value for: ${State}`>
export type AddKeyValue<Memo extends Record<string, any>, Key extends string, Value extends any> = Memo &
{ [K in Key]: Value }
export type AddOptionalKeyValue<Memo extends Record<string, any>, Key extends string, Value extends any> = Memo &
{ [K in Key]?: Value }
}
/**
* Creates object types compliant with https://github.com/pillarjs/path-to-regexp and Express.js
* @public
*/
export type ParseUrlParams<State extends string, Memo extends Record<string, any> = {}> = string extends State
? ParseUrlParams.ParserError<"ParseUrlParams got generic string type">
: State extends `${infer _}:${infer Rest}`
? ParseUrlParams.AddUrlSection<Rest, Memo>
: Memo