forked from ChromeDevTools/devtools-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotocol-dts-generator.ts
391 lines (328 loc) · 12.6 KB
/
protocol-dts-generator.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
import * as fs from 'fs'
import * as path from 'path'
import {IProtocol, Protocol as P} from './protocol-schema'
// TODO: @noj validate this via https://github.com/andischerer/typescript-json-typesafe against protocol-schema.d.ts
const jsProtocol: IProtocol = require('../json/js_protocol.json')
const browserProtocol: IProtocol = require('../json/browser_protocol.json')
const protocolDomains: P.Domain[] = jsProtocol.domains.concat(browserProtocol.domains)
let numIndents = 0
let emitStr = ''
const emit = (str: string) => {
emitStr += str
}
const getIndent = () => ' '.repeat(numIndents) // 4 spaced indents
const emitIndent = () => {
emitStr += getIndent()
}
const emitLine = (str?: string) => {
if (str) {
emitIndent()
emit(`${str}\n`)
} else {
emit('\n')
}
}
const emitOpenBlock = (str: string, openChar = ' {') => {
emitLine(`${str}${openChar}`)
numIndents++
}
const emitCloseBlock = (closeChar = '}') => {
numIndents--
emitLine(closeChar)
}
const emitHeaderComments = () => {
emitLine('/**********************************************************************')
emitLine(' * Auto-generated by protocol-dts-generator.ts, do not edit manually. *')
emitLine(' **********************************************************************/')
emitLine()
}
const fixCamelCase = (name: string): string => {
let prefix = '';
let result = name;
if (name[0] === '-') {
prefix = 'Negative';
result = name.substring(1);
}
const refined = result.split('-').map(toTitleCase).join('');
return prefix + refined.replace(/HTML|XML|WML|API/i, match => match.toUpperCase());
};
const emitEnum = (enumName: string, enumValues: string[]) => {
emitOpenBlock(`export const enum ${enumName}`);
enumValues.forEach(value => {
emitLine(`${fixCamelCase(value)} = '${value}',`);
});
emitCloseBlock();
};
const emitPublicDocDeclaration = () => {
emitLine('/**');
emitLine(' * The Chrome DevTools Protocol.');
emitLine(' * @public')
emitLine(' */')
}
const emitModule = (moduleName: string, domains: P.Domain[]) => {
moduleName = toTitleCase(moduleName)
emitHeaderComments()
emitPublicDocDeclaration()
emitOpenBlock(`export namespace ${moduleName}`)
emitGlobalTypeDefs()
domains.forEach(emitDomain)
emitCloseBlock()
emitLine()
emitLine(`export default ${moduleName};`)
}
const emitGlobalTypeDefs = () => {
emitLine()
emitLine(`export type integer = number`)
}
const emitDomain = (domain: P.Domain) => {
const domainName = toTitleCase(domain.domain)
emitLine()
emitDescription(domain.description)
emitOpenBlock(`export namespace ${domainName}`)
if (domain.types) domain.types.forEach(emitDomainType)
if (domain.commands) domain.commands.forEach(emitCommand)
if (domain.events) domain.events.forEach(emitEvent)
emitCloseBlock()
}
const getCommentLines = (description: string) => {
const lines = description
.split(/\r?\n/g)
.map(line => ` * ${line}`)
return [`/**`, ...lines, ` */`]
}
const emitDescription = (description?: string) => {
if (description) getCommentLines(description).map(l => emitLine(l))
}
const isPropertyInlineEnum = (prop: P.ProtocolType): boolean => {
if ('$ref' in prop) {
return false;
}
return prop.type === 'string' && prop.enum !== null && prop.enum !== undefined;
};
const getPropertyDef = (interfaceName: string, prop: P.PropertyType): string => {
// Quote key if it has a . in it.
const propName = prop.name.includes('.') ? `'${prop.name}'` : prop.name
const type = getPropertyType(interfaceName, prop);
return `${propName}${prop.optional ? '?' : ''}: ${type}`;
};
const getPropertyType = (interfaceName: string, prop: P.ProtocolType): string => {
if ('$ref' in prop)
return prop.$ref
else if (prop.type === 'array')
return `${getPropertyType(interfaceName, prop.items)}[]`
else if (prop.type === 'object')
if (!prop.properties) {
// TODO: actually 'any'? or can use generic '[key: string]: string'?
return `any`
} else {
// hack: access indent, \n directly
let objStr = '{\n'
numIndents++
objStr += prop.properties
.map(p => `${getIndent()}${getPropertyDef(interfaceName, p)};\n`)
.join('')
numIndents--
objStr += `${getIndent()}}`
return objStr
}
else if (prop.type === 'string' && prop.enum)
return '(' + prop.enum.map((v: string) => `'${v}'`).join(' | ') + ')'
return prop.type
}
const emitProperty = (interfaceName: string, prop: P.PropertyType) => {
let description = prop.description;
if (isPropertyInlineEnum(prop)) {
const enumName = interfaceName + toTitleCase(prop.name);
description = `${description || ''} (${enumName} enum)`;
}
emitDescription(description)
emitLine(`${getPropertyDef(interfaceName, prop)};`)
}
const emitInlineEnumForDomainType = (type: P.DomainType) => {
if (type.type === 'object') {
emitInlineEnums(type.id, type.properties);
}
};
const emitInlineEnumsForCommands = (command: P.Command) => {
emitInlineEnums(toCmdRequestName(command.name), command.parameters);
emitInlineEnums(toCmdResponseName(command.name), command.returns);
};
const emitInlineEnumsForEvents = (event: P.Event) => {
emitInlineEnums(toEventPayloadName(event.name), event.parameters);
};
const emitInlineEnums = (prefix: string, propertyTypes?: P.PropertyType[]) => {
if (!propertyTypes) {
return;
}
for (const type of propertyTypes) {
if (isPropertyInlineEnum(type)) {
emitLine();
const enumName = prefix + toTitleCase(type.name);
emitEnum(enumName, (type as P.StringType).enum || []);
}
}
};
const emitInterface = (interfaceName: string, props?: P.PropertyType[]) => {
emitOpenBlock(`export interface ${interfaceName}`)
props ? props.forEach(prop => emitProperty(interfaceName, prop)) : emitLine('[key: string]: string;')
emitCloseBlock()
}
const emitDomainType = (type: P.DomainType) => {
emitInlineEnumForDomainType(type);
emitLine()
emitDescription(type.description)
if (type.type === 'object') {
emitInterface(type.id, type.properties)
} else {
emitLine(`export type ${type.id} = ${getPropertyType(type.id, type)};`)
}
}
const toTitleCase = (str: string) => str[0].toUpperCase() + str.substr(1)
const toCmdRequestName = (commandName: string) => `${toTitleCase(commandName)}Request`
const toCmdResponseName = (commandName: string) => `${toTitleCase(commandName)}Response`
const emitCommand = (command: P.Command) => {
emitInlineEnumsForCommands(command);
// TODO(bckenny): should description be emitted for params and return types?
if (command.parameters) {
emitLine()
emitInterface(toCmdRequestName(command.name), command.parameters)
}
if (command.returns) {
emitLine()
emitInterface(toCmdResponseName(command.name), command.returns)
}
}
const toEventPayloadName = (eventName: string) => `${toTitleCase(eventName)}Event`
const emitEvent = (event: P.Event) => {
if (!event.parameters) {
return
}
emitInlineEnumsForEvents(event);
emitLine()
emitDescription(event.description)
emitInterface(toEventPayloadName(event.name), event.parameters)
}
const getEventMapping = (event: P.Event, domainName: string, modulePrefix: string): P.RefType & P.PropertyBaseType => {
// Use TS3.0+ tuples
const payloadType = event.parameters ?
`[${modulePrefix}.${domainName}.${toEventPayloadName(event.name)}]` :
'[]'
return {
// domain-prefixed name since it will be used outside of the module.
name: `${domainName}.${event.name}`,
description: event.description,
$ref: payloadType
}
}
const isWeakInterface = (params: P.PropertyType[]): boolean => {
return params.every(p => !!p.optional)
}
const getCommandMapping = (command: P.Command, domainName: string, modulePrefix: string): P.ObjectType & P.PropertyBaseType => {
const prefix = `${modulePrefix}.${domainName}.`
// Use TS3.0+ tuples for paramsType
let requestType = '[]'
if (command.parameters) {
const optional = isWeakInterface(command.parameters) ? '?' : ''
requestType = '[' + prefix + toCmdRequestName(command.name) + optional + ']'
}
const responseType = command.returns ? prefix + toCmdResponseName(command.name) : 'void'
return {
type: 'object',
name: `${domainName}.${command.name}`,
description: command.description,
properties: [{
name: 'paramsType',
$ref: requestType,
}, {
name: 'returnType',
$ref: responseType,
}]
}
}
const flatten = <T>(arr: T[][]) => ([] as T[]).concat(...arr)
const emitMapping = (moduleName: string, protocolModuleName: string, domains: P.Domain[]) => {
moduleName = toTitleCase(moduleName)
emitHeaderComments()
emitLine(`import Protocol from './${protocolModuleName}'`)
emitLine()
emitDescription('Mappings from protocol event and command names to the types required for them.')
emitOpenBlock(`export namespace ${moduleName}`)
const protocolModulePrefix = toTitleCase(protocolModuleName)
const eventDefs = flatten(domains.map(d => {
const domainName = toTitleCase(d.domain)
return (d.events || []).map(e => getEventMapping(e, domainName, protocolModulePrefix))
}))
emitInterface('Events', eventDefs)
emitLine()
const commandDefs = flatten(domains.map(d => {
const domainName = toTitleCase(d.domain)
return (d.commands || []).map(c => getCommandMapping(c, domainName, protocolModulePrefix))
}))
emitInterface('Commands', commandDefs)
emitCloseBlock()
emitLine()
emitLine(`export default ${moduleName};`)
}
const emitApiCommand = (command: P.Command, domainName: string, modulePrefix: string) => {
const prefix = `${modulePrefix}.${domainName}.`
emitDescription(command.description)
const params = command.parameters ? `params: ${prefix}${toCmdRequestName(command.name)}` : ''
const response = command.returns ? `${prefix}${toCmdResponseName(command.name)}` : 'void'
emitLine(`${command.name}(${params}): Promise<${response}>;`)
emitLine()
}
const emitApiEvent = (event: P.Event, domainName: string, modulePrefix: string) => {
const prefix = `${modulePrefix}.${domainName}.`
emitDescription(event.description)
const params = event.parameters ? `params: ${prefix}${toEventPayloadName(event.name)}` : ''
emitLine(`on(event: '${event.name}', listener: (${params}) => void): void;`)
emitLine()
}
const emitDomainApi = (domain: P.Domain, modulePrefix: string) => {
emitLine()
const domainName = toTitleCase(domain.domain)
emitOpenBlock(`export interface ${domainName}Api`)
if (domain.commands) domain.commands.forEach(c => emitApiCommand(c, domainName, modulePrefix))
if (domain.events) domain.events.forEach(e => emitApiEvent(e, domainName, modulePrefix))
emitCloseBlock()
}
const emitApi = (moduleName: string, protocolModuleName: string, domains: P.Domain[]) => {
moduleName = toTitleCase(moduleName)
emitHeaderComments()
emitLine(`import Protocol from './${protocolModuleName}'`)
emitLine()
emitDescription('API generated from Protocol commands and events.')
emitOpenBlock(`export namespace ${moduleName}`)
emitLine()
emitOpenBlock(`export interface ProtocolApi`)
domains.forEach(d => {
emitLine(`${d.domain}: ${d.domain}Api;`)
emitLine()
});
emitCloseBlock()
emitLine()
const protocolModulePrefix = toTitleCase(protocolModuleName)
domains.forEach(d => emitDomainApi(d, protocolModulePrefix))
emitCloseBlock()
emitLine()
emitLine(`export default ${moduleName};`)
}
const flushEmitToFile = (path: string) => {
console.log(`Writing to ${path}`)
fs.writeFileSync(path, emitStr, {encoding: 'utf-8'})
numIndents = 0
emitStr = ''
}
// Main
const destProtocolFilePath = `${__dirname}/../types/protocol.d.ts`
const protocolModuleName = path.basename(destProtocolFilePath, '.d.ts')
emitModule(protocolModuleName, protocolDomains)
flushEmitToFile(destProtocolFilePath)
const destMappingFilePath = `${__dirname}/../types/protocol-mapping.d.ts`
const mappingModuleName = 'ProtocolMapping'
emitMapping(mappingModuleName, protocolModuleName, protocolDomains)
flushEmitToFile(destMappingFilePath)
const destApiFilePath = `${__dirname}/../types/protocol-proxy-api.d.ts`
const apiModuleName = 'ProtocolProxyApi'
emitApi(apiModuleName, protocolModuleName, protocolDomains)
flushEmitToFile(destApiFilePath)