-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (53 loc) · 1.92 KB
/
Copy pathindex.js
File metadata and controls
55 lines (53 loc) · 1.92 KB
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
#! node
import '@dfoverdx/tocamelcase';
import fs from 'fs';
import path from 'path';
import { isBinaryFileSync } from 'isbinaryfile';
import json5 from 'json5';
import stringifyObject from 'stringify-object';
const files = process.argv.slice(2);
for (const file of files) {
if (!fs.existsSync(file)) {
console.error(`File '${file}' does not exist.`);
process.exit(1);
}
if (!fs.statSync(file).isFile()) {
console.error(`File '${file}' is not a file. It is likely a directory.`);
process.exit(1);
}
const buffer = fs.readFileSync(file);
if (isBinaryFileSync(buffer)) {
console.error(`File '${file}' is not a text file.`);
}
const text = buffer.toString();
let json;
let jsonText;
try {
json = json5.parse(text);
jsonText = stringifyObject(json, {
indent: ' ',
inlineCharacterLimit: 80,
});
}
catch {
console.error(`File '${file}' is not a valid json file.`);
process.exit(1);
}
// if (json == null) {
// console.error(`File '${file}' is a valid json file, but parses as 'null', which cannot be set to a const`)
// }
const [declarationType, equals, terminator] = typeof json === 'object'
? json && !Array.isArray(json)
? ['interface', '', '']
: ['type', ' =', ';']
: ['const', ' =', ';'];
const name = path.basename(file);
const typeName = (name.includes('.') ? name.slice(0, name.indexOf('.')) : name).toCamelCase(true);
const output = `${declarationType !== 'const'
? `${declarationType} ${typeName}${equals} ${jsonText}${terminator}
declare const ${typeName}: ${typeName};`
: `declare ${declarationType} ${typeName}${equals} ${jsonText}${terminator}`}
export = ${typeName};`;
console.log(`Writing ${file}.d.ts`);
fs.writeFileSync(`${file}.d.ts`, output);
}