-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathfile.js
More file actions
467 lines (421 loc) · 14.2 KB
/
file.js
File metadata and controls
467 lines (421 loc) · 14.2 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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
const fs = require('fs');
const bundler = require('api-ref-bundler');
const yaml = require('@stoplight/yaml');
const http = require('http');
const https = require('https');
const {dirname} = require('path');
/**
* Converts a string object to a JSON/YAML object.
* @param {string} str - The input string to be parsed (either JSON or YAML).
* @param {object} options - Options to define the parsing behavior (e.g., keeping comments).
* @returns {Promise<object>} Parsed data object.
*/
async function parseString(str, options = {}) {
// Exit early
if (str.length === 0) {
return str;
}
// Convert large number values safely before parsing
let encodedContent = encodeLargeNumbers(str);
encodedContent = addQuotesToRefInString(encodedContent);
// Default to YAML format unless specified as JSON
const toYaml = options.format !== 'json' && (!options.hasOwnProperty('json') || options.json !== true);
if (toYaml) {
try {
const result = yaml.parseWithPointers(encodedContent, {attachComments: options?.keepComments || false});
options.yamlComments = result.comments;
const obj = normalizeYamlBlockScalarNewlines(result.data);
if (typeof obj === 'object') {
return obj;
} else {
throw new SyntaxError('Invalid YAML');
}
} catch (yamlError) {
return yamlError;
}
} else {
try {
// Try parsing as JSON
return JSON.parse(encodedContent);
} catch (jsonError) {
return jsonError;
}
}
}
/**
* Checks if a given string is valid JSON.
* @param {string} str - The input string to check.
* @returns {Promise<boolean>} True if the string is valid JSON, false otherwise.
*/
async function isJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
/**
* Checks if a given string is valid YAML.
* @param {string} str - The input string to check.
* @returns {Promise<boolean>} True if the string is valid YAML, false otherwise.
*/
async function isYaml(str) {
try {
const rest = yaml.parse(str);
return typeof rest === 'object';
} catch (e) {
return false;
}
}
/**
* Detects the format of a given string (either JSON or YAML).
* @param {string} str - The input string to check.
* @returns {Promise<string>} "json", "yaml", or "unknown" based on the detected format.
*/
async function detectFormat(str) {
if ((await isJSON(str)) !== false) {
return 'json';
} else if ((await isYaml(str)) !== false) {
return 'yaml';
} else {
return 'unknown';
}
}
/**
* Reads a file (local or remote) and returns its content as a string.
* @param {string} filePath - The path to the file (local or URL).
* @param {object} options - Parse file options (e.g., format detection).
* @returns {Promise<string>} The content of the file as a string.
*/
async function readFile(filePath, options) {
try {
const isRemoteFile = filePath.startsWith('http://') || filePath.startsWith('https://');
let fileContent;
if (isRemoteFile) {
fileContent = await getRemoteFile(filePath);
} else {
const isYamlFile = filePath.endsWith('.yaml') || filePath.endsWith('.yml');
isYamlFile ? (options.format = 'yaml') : (options.format = 'json');
fileContent = await getLocalFile(filePath);
}
// Check JSON or YAML
(await isJSON(fileContent)) ? (options.format = 'json') : (options.format = 'yaml');
return fileContent;
} catch (err) {
throw err;
}
}
/**
* Parses a JSON/YAML file and returns the parsed object
* @param {string} filePath - The path to the JSON/YAML file.
* @param {object} options - Parse file options (e.g., reference resolution hooks).
* @returns {Promise<object>} Parsed data object with references resolved, if any.
*/
async function parseFile(filePath, options = {}) {
try {
// Read local or remote file content and get format JSON or YAML
let rawContent = await readFile(filePath, options);
if (rawContent.includes('$ref') && options.bundle === true) {
// Handler to Resolve references
const resolver = async sourcePath => {
let refContent = await readFile(sourcePath, options);
return await parseString(refContent, options);
};
const onErrorHook = msg => {
throw new Error(msg);
};
// Use the bundler to resolve external refs and bundle the document
return bundler.bundle(filePath, resolver, {ignoreSibling: false, hooks: {onError: onErrorHook}});
}
// Parse file content as JSON/YAML
return await parseString(rawContent, options);
} catch (err) {
throw err;
}
}
/**
* Converts a data object to a JSON/YAML string representation.
* @param {object} obj - The data object to stringify.
* @param {object} options - Stringify options (e.g., line width, format).
* @returns {Promise<string>} The object as a string in JSON/YAML format.
*/
async function stringify(obj, options = {}) {
try {
let output;
// Default to YAML format
const toYaml = options.format !== 'json' && (!options.hasOwnProperty('json') || options.json !== true);
if (toYaml) {
// Set YAML options
const yamlOptions = {};
yamlOptions.lineWidth =
(options.lineWidth && options.lineWidth === -1 ? Infinity : options.lineWidth) || Infinity;
if (options?.yamlComments && options?.keepComments === true) {
yamlOptions.comments = options.yamlComments;
}
// Convert object to YAML string
output = yaml.safeStringify(obj, yamlOptions);
output = addQuotesToRefInString(output);
// Decode large number YAML values safely before writing output
output = decodeLargeNumbers(output);
} else {
// Convert object to JSON string
output = JSON.stringify(obj, null, 2);
// Decode large number JSON values safely before writing output
output = decodeLargeNumbers(output, true);
}
// Return the stringify output
return output;
} catch (err) {
// Handle errors or rethrow
throw err;
}
}
/**
* Writes an object to a JSON/YAML file.
* @param {string} filePath - The path to the output file.
* @param {object} data - The data object to write.
* @param {object} options - Write options (e.g., format).
* @returns {Promise<void>} Resolves when the file is written successfully.
*/
async function writeFile(filePath, data, options = {}) {
try {
let output;
const isYamlFile = filePath.endsWith('.yaml') || filePath.endsWith('.yml');
if (isYamlFile) {
// Convert Object to YAML string
options.format = 'yaml';
output = await stringify(data, options);
} else {
// Convert Object to JSON string
options.format = 'json';
output = await stringify(data, options);
}
const dir = dirname(filePath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {recursive: true});
}
// Write the output to the file
fs.writeFileSync(filePath, output, 'utf8');
} catch (err) {
console.error('\x1b[31m', `Error writing file "${filePath}": ${err.message}`);
throw err;
}
}
/**
* Reads a local file and returns the content.
* @param {string} filePath - The path to the local file.
* @returns {Promise<string>} The content of the file as a string.
*/
async function getLocalFile(filePath) {
try {
const inputContent = fs.readFileSync(filePath, 'utf8');
return inputContent;
} catch (err) {
throw err;
// throw new Error(`Input file error - Failed to read file: ${filePath}`);
}
}
/**
* Reads a remote file and returns the content.
* @param {string} filePath - The URL to the remote file.
* @returns {Promise<string>} The content of the remote file as a string.
*/
async function getRemoteFile(filePath) {
const protocol = filePath.startsWith('https://') ? https : http;
const inputContent = await new Promise((resolve, reject) => {
protocol.get(filePath, res => {
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(new Error(`${res.statusCode} ${res.statusMessage}`));
}
const chunks = [];
res.on('data', chunk => {
chunks.push(chunk);
});
res.on('end', () => {
resolve(Buffer.concat(chunks).toString());
});
res.on('error', err => {
reject(new Error(`${err.message}`));
});
});
});
return inputContent;
}
/**
* Convert large number value safely before parsing
* @param inputContent Input content.
* @returns {*} Encoded content.
*/
function encodeLargeNumbers(inputContent) {
// Convert large number value safely before parsing
const regexEncodeLargeNumber = /: ([0-9]+(\.[0-9]+)?)(?!\.[0-9])(,(?!\s*[0-9])|\n)/g; // match > : 123456789.123456789
return inputContent.replace(regexEncodeLargeNumber, rawInput => {
const endChar = rawInput.endsWith(',') ? ',' : '\n';
const rgx = new RegExp(endChar, 'g');
const number = rawInput.replace(/: /g, '').replace(rgx, '');
// Handle large numbers safely in javascript
if (Number(number).toString().includes('e') || number.replace('.', '').length > 15) {
return `: "${number}==="${endChar}`;
} else {
return `: ${number}${endChar}`;
}
});
}
/**
* Decode large number YAML/JSON values safely before writing output
* @param output YAML/JSON Output content.
* @param isJson Indicate if the output is JSON.
* @returns {*} Decoded content.
*/
function decodeLargeNumbers(output, isJson = false) {
if (isJson) {
// Decode large number JSON values safely before writing output
const regexDecodeJsonLargeNumber = /: "([0-9]+(\.[0-9]+)?)\b(?!\.[0-9])==="/g; // match > : "123456789.123456789==="
return output.replace(regexDecodeJsonLargeNumber, strNumber => {
const number = strNumber.replace(/: "|"/g, '');
// Decode large numbers safely in javascript
if (number.endsWith('===') || number.replace('.', '').length > 15) {
return strNumber.replace('===', '').replace(/"/g, '');
} else {
// Keep original number
return strNumber;
}
});
} else {
// Decode large number YAML values safely before writing output
const regexDecodeYamlLargeNumber = /: ([0-9]+(\.[0-9]+)?)\b(?!\.[0-9])===/g; // match > : 123456789.123456789===
return output.replace(regexDecodeYamlLargeNumber, strNumber => {
const number = strNumber.replace(/: '|'/g, '');
// Decode large numbers safely in javascript
if (number.endsWith('===') || number.replace('.', '').length > 15) {
return strNumber.replace('===', '').replace(/'/g, '');
} else {
// Keep original number
return strNumber;
}
});
}
}
/**
* Add quotes to $ref in string
* @param {string} yamlString - The input YAML string.
* @returns {string} YAML string with quotes.
*/
function addQuotesToRefInString(yamlString) {
return yamlString.replace(/(\$ref:\s*)([^"'\s>]+)/g, '$1"$2"');
}
/**
* Normalize a parser artifact where block scalars with indentation indicators
* gain a spurious leading newline during YAML parsing.
* This keeps genuine blank first lines intact by only stripping a single
* leading newline when the string also has a trailing newline.
* @param {*} value - Parsed YAML value.
* @returns {*} Normalized value.
*/
function normalizeYamlBlockScalarNewlines(value) {
if (typeof value === 'string') {
if (value.startsWith('\n') && !value.startsWith('\n\n') && value.endsWith('\n')) {
return value.slice(1);
}
return value;
}
if (Array.isArray(value)) {
return value.map(item => normalizeYamlBlockScalarNewlines(item));
}
if (value && typeof value === 'object') {
for (const key of Object.keys(value)) {
value[key] = normalizeYamlBlockScalarNewlines(value[key]);
}
}
return value;
}
/**
* Analyze the OpenAPI document.
* @param {object} oaObj - The OpenAPI document as a JSON object.
* @returns {{operations: *[], methods: any[], paths: *[], flags: any[], operationIds: *[], flagValues: any[], responseContent: any[], tags: any[]}}
*/
function analyzeOpenApi(oaObj) {
const flags = new Set();
const tags = new Set();
const operationIds = [];
const paths = [];
const methods = new Set();
const operations = [];
const responseContent = new Set();
const requestContent = new Set();
const flagValues = new Set();
if (oaObj && oaObj.paths) {
Object.keys(oaObj.paths).forEach(path => {
paths.push(path);
const pathItem = oaObj.paths[path];
if (pathItem && typeof pathItem === 'object') {
Object.keys(pathItem).forEach(method => {
methods.add(method.toUpperCase());
const operation = pathItem[method];
operations.push(`${method.toUpperCase()}::${path}`);
if (operation && typeof operation === 'object') {
if (operation?.tags && Array.isArray(operation.tags)) {
operation.tags.forEach(tag => {
if (tag.startsWith('x-')) {
flags.add(tag);
} else {
tags.add(tag);
}
});
}
if (operation?.operationId) {
operationIds.push(operation.operationId);
}
if (operation?.requestBody?.content) {
Object.keys(operation.requestBody.content).forEach(contentType => {
requestContent.add(contentType);
});
}
if (operation?.responses) {
Object.values(operation.responses).forEach(response => {
if (response?.content) {
Object.keys(response.content).forEach(contentType => {
responseContent.add(contentType);
});
}
});
}
Object.keys(operation).forEach(key => {
if (key.startsWith('x-')) {
flagValues.add(`${key}: ${operation[key]}`);
}
});
}
});
}
});
}
return {
methods: Array.from(methods),
tags: Array.from(tags),
operationIds,
flags: Array.from(flags),
flagValues: Array.from(flagValues),
paths,
operations,
responseContent: Array.from(responseContent),
requestContent: Array.from(requestContent)
};
}
module.exports = {
readFile,
parseString,
parseFile,
isJSON,
isYaml,
detectFormat,
stringify,
writeFile,
encodeLargeNumbers,
decodeLargeNumbers,
getLocalFile,
getRemoteFile,
analyzeOpenApi,
addQuotesToRefInString
};