1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | export interface GrpcUri {
|
19 | scheme?: string;
|
20 | authority?: string;
|
21 | path: string;
|
22 | }
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/;
|
31 |
|
32 | export function parseUri(uriString: string): GrpcUri | null {
|
33 | const parsedUri = URI_REGEX.exec(uriString);
|
34 | if (parsedUri === null) {
|
35 | return null;
|
36 | }
|
37 | return {
|
38 | scheme: parsedUri[1],
|
39 | authority: parsedUri[2],
|
40 | path: parsedUri[3],
|
41 | };
|
42 | }
|
43 |
|
44 | export interface HostPort {
|
45 | host: string;
|
46 | port?: number;
|
47 | }
|
48 |
|
49 | const NUMBER_REGEX = /^\d+$/;
|
50 |
|
51 | export function splitHostPort(path: string): HostPort | null {
|
52 | if (path.startsWith('[')) {
|
53 | const hostEnd = path.indexOf(']');
|
54 | if (hostEnd === -1) {
|
55 | return null;
|
56 | }
|
57 | const host = path.substring(1, hostEnd);
|
58 | |
59 |
|
60 | if (host.indexOf(':') === -1) {
|
61 | return null;
|
62 | }
|
63 | if (path.length > hostEnd + 1) {
|
64 | if (path[hostEnd + 1] === ':') {
|
65 | const portString = path.substring(hostEnd + 2);
|
66 | if (NUMBER_REGEX.test(portString)) {
|
67 | return {
|
68 | host: host,
|
69 | port: +portString,
|
70 | };
|
71 | } else {
|
72 | return null;
|
73 | }
|
74 | } else {
|
75 | return null;
|
76 | }
|
77 | } else {
|
78 | return {
|
79 | host,
|
80 | };
|
81 | }
|
82 | } else {
|
83 | const splitPath = path.split(':');
|
84 | |
85 |
|
86 |
|
87 | if (splitPath.length === 2) {
|
88 | if (NUMBER_REGEX.test(splitPath[1])) {
|
89 | return {
|
90 | host: splitPath[0],
|
91 | port: +splitPath[1],
|
92 | };
|
93 | } else {
|
94 | return null;
|
95 | }
|
96 | } else {
|
97 | return {
|
98 | host: path,
|
99 | };
|
100 | }
|
101 | }
|
102 | }
|
103 |
|
104 | export function uriToString(uri: GrpcUri): string {
|
105 | let result = '';
|
106 | if (uri.scheme !== undefined) {
|
107 | result += uri.scheme + ':';
|
108 | }
|
109 | if (uri.authority !== undefined) {
|
110 | result += '//' + uri.authority + '/';
|
111 | }
|
112 | result += uri.path;
|
113 | return result;
|
114 | }
|