-
Notifications
You must be signed in to change notification settings - Fork 13
/
protobuf.ts
189 lines (163 loc) · 4.7 KB
/
protobuf.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
import * as fs from 'fs';
import {GrpcObject, loadPackageDefinition} from 'grpc';
import get = require('lodash/get');
import * as path from 'path';
import {
Enum,
Field,
MapField, Method,
Namespace,
OneOf,
ReflectionObject,
Root,
Service,
Service as ProtoService,
Type,
} from 'protobufjs';
import {load as grpcDef} from '@grpc/proto-loader';
export interface Proto {
fileName: string;
filePath: string;
protoText: string;
ast: GrpcObject;
root: Root;
}
/**
* Proto ast from filename
*/
export async function fromFileName(protoPath: string, includeDirs?: string[]): Promise<Proto> {
includeDirs = includeDirs ? [...includeDirs] : [];
if (path.isAbsolute(protoPath)) {
includeDirs.push(
path.dirname(protoPath)
);
} else {
includeDirs.push(
path.dirname(path.join(process.cwd(), protoPath))
);
}
const packageDefinition = await grpcDef(path.basename(protoPath), {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs,
});
const protoAST = loadPackageDefinition(packageDefinition);
const protoRoot = new Root();
if (includeDirs) {
addIncludePathToRoot(protoRoot, includeDirs);
}
const root = await protoRoot.load(
protoPath,
{
keepCase: true,
}
);
const protoText = await promisifyRead(protoPath);
return {
fileName: protoPath.split(path.sep).pop() || '',
filePath: protoPath,
protoText,
ast: protoAST,
root,
};
}
/**
* Walk through services
*/
export function walkServices(proto: Proto, onService: (service: Service, def: any, serviceName: string) => void) {
const {ast, root} = proto;
walkNamespace(root, namespace => {
const nestedNamespaceTypes = namespace.nested;
if (nestedNamespaceTypes) {
Object.keys(nestedNamespaceTypes).forEach(nestedTypeName => {
const fullNamespaceName = (namespace.fullName.startsWith('.'))
? namespace.fullName.replace('.', '')
: namespace.fullName;
const nestedType = root.lookup(`${fullNamespaceName}.${nestedTypeName}`);
if (nestedType instanceof Service) {
const serviceName = [
...fullNamespaceName.split('.'),
nestedType.name
];
const fullyQualifiedServiceName = serviceName.join('.');
onService(nestedType as Service, get(ast, serviceName), fullyQualifiedServiceName);
}
});
}
});
Object.keys(ast)
.forEach(serviceName => {
const lookupType = root.lookup(serviceName);
if (lookupType instanceof Service) {
// No namespace, root services
onService(serviceByName(root, serviceName), ast[serviceName], serviceName);
}
});
}
export function walkNamespace(root: Root, onNamespace: (namespace: Namespace) => void, parentNamespace?: Namespace) {
const namespace = parentNamespace ? parentNamespace : root;
const nestedType = namespace.nested;
if (nestedType) {
Object.keys(nestedType).forEach((typeName: string) => {
const nestedNamespace = root.lookup(`${namespace.fullName}.${typeName}`);
if (nestedNamespace && isNamespace(nestedNamespace)) {
onNamespace(nestedNamespace as Namespace);
walkNamespace(root, onNamespace, nestedNamespace as Namespace);
}
});
}
}
export function serviceByName(root: Root, serviceName: string): ProtoService {
if (!root.nested) {
throw new Error('Empty PROTO!');
}
const serviceLeaf = root.nested[serviceName];
return root.lookupService(serviceLeaf.fullName);
}
function promisifyRead(fileName: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8', function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
function addIncludePathToRoot(root: Root, includePaths: string[]) {
const originalResolvePath = root.resolvePath;
root.resolvePath = (origin: string, target: string) => {
if (path.isAbsolute(target)) {
return target;
}
for (const directory of includePaths) {
const fullPath: string = path.join(directory, target);
try {
fs.accessSync(fullPath, fs.constants.R_OK);
return fullPath;
} catch (err) {
continue;
}
}
return originalResolvePath(origin, target);
};
}
function isNamespace(lookupType: ReflectionObject) {
if (
(lookupType instanceof Namespace) &&
!(lookupType instanceof Service) &&
!(lookupType instanceof Type) &&
!(lookupType instanceof Enum) &&
!(lookupType instanceof Field) &&
!(lookupType instanceof MapField) &&
!(lookupType instanceof OneOf) &&
!(lookupType instanceof Method)
) {
return true;
}
return false;
}