@prantlf/jsonlint 10.1.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,7 +1,7 @@
1
1
  MIT License
2
2
 
3
3
  Copyright (c) 2012-2018 Zachary Carter
4
- Copyright (c) 2019 Ferdinand Prantl
4
+ Copyright (c) 2019-2022 Ferdinand Prantl
5
5
 
6
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
7
7
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,20 +1,18 @@
1
1
  # JSON Lint
2
2
 
3
- [![NPM version](https://badge.fury.io/js/%40prantlf%2Fjsonlint.svg)](https://badge.fury.io/js/%40prantlf%2Fjsonlint)
4
- [![Build Status](https://travis-ci.com/prantlf/jsonlint.svg?branch=master)](https://travis-ci.com/prantlf/jsonlint)
5
- [![codecov](https://codecov.io/gh/prantlf/jsonlint/branch/master/graph/badge.svg)](https://codecov.io/gh/prantlf/jsonlint)
6
- [![Dependency Status](https://david-dm.org/prantlf/jsonlint.svg)](https://david-dm.org/prantlf/jsonlint)
7
- [![devDependency Status](https://david-dm.org/prantlf/jsonlint/dev-status.svg)](https://david-dm.org/prantlf/jsonlint#info=devDependencies)
8
- [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
3
+ [![Latest version](https://img.shields.io/npm/v/@prantlf/jsonlint)
4
+ ![Dependency status](https://img.shields.io/librariesio/release/npm/@prantlf/jsonlint)
5
+ ](https://www.npmjs.com/package/@prantlf/jsonlint)
6
+ [![Code coverage](https://codecov.io/gh/prantlf/jsonlint/branch/master/graph/badge.svg)](https://codecov.io/gh/prantlf/jsonlint)
9
7
 
10
- A [JSON]/[JSON5] parser and validator with a command-line client. A [pure JavaScript version] of the service provided at [jsonlint.com].
8
+ A [JSON]/CJSON/[JSON5] parser, validator and pretty-printer with a command-line client. A [pure JavaScript version] of the service provided at [jsonlint.com].
11
9
 
12
10
  This is a fork of the original package with the following enhancements:
13
11
 
14
12
  * Handles multiple files on the command line (by Greg Inman).
15
13
  * Walks directories recursively (by Paul Vollmer).
16
14
  * Provides 100% compatible interface to the native `JSON.parse` method.
17
- * Optionally recognizes JavaScript-style comments and single quoted strings.
15
+ * Optionally recognizes JavaScript-style comments (CJSON) and single quoted strings (JSON5).
18
16
  * Optionally ignores trailing commas and reports duplicate object keys as an error.
19
17
  * Supports [JSON Schema] drafts 04, 06 and 07.
20
18
  * Offers pretty-printing including comment-stripping and object keys without quotes (JSON5).
@@ -30,6 +28,7 @@ Integration to the favourite task loaders for JSON file validation is provided b
30
28
 
31
29
  * [`Grunt`] - see [`@prantlf/grunt-jsonlint`]
32
30
  * [`Gulp`] - see [`@prantlf/gulp-jsonlint`]
31
+ * [`Rollup`] - see [`rollup-plugin-jsonlint`]
33
32
 
34
33
  ## Synopsis
35
34
 
@@ -103,6 +102,11 @@ By default, `jsonlint` will either report a syntax error with details or pretty-
103
102
  --prune-comments omit comments from the prettified output
104
103
  --strip-object-keys strip quotes from object keys if possible
105
104
  (JSON5)
105
+ --enforce-double-quotes surrounds all strings with double quotes
106
+ --enforce-single-quotes surrounds all strings with single quotes
107
+ (JSON5)
108
+ --trim-trailing-commas omit trailing commas from objects and arrays
109
+ (JSON5)
106
110
  -v, --version output the version number
107
111
  -h, --help output usage information
108
112
 
@@ -184,7 +188,7 @@ const validate = compile('string with JSON schema', {
184
188
 
185
189
  ### Pretty-Printing
186
190
 
187
- You can parse a JSON string to an array of tokens and print it back to a string with some changes applied. It can be unification of whitespace or tripping comments, for example. (Raw token values must be enabled when tokenizing the JSON input.)
191
+ You can parse a JSON string to an array of tokens and print it back to a string with some changes applied. It can be unification of whitespace, reformatting or stripping comments, for example. (Raw token values must be enabled when tokenizing the JSON input.)
188
192
 
189
193
  ```js
190
194
  const { tokenize } = require('@prantlf/jsonlint')
@@ -201,7 +205,10 @@ The [`print`](#pretty-printing) method accepts an object `options` as the second
201
205
  | --------------------------- | ------------------------------------------------------- |
202
206
  | `indent` | count of spaces or the specific characters to be used as an indentation unit |
203
207
  | `pruneComments` | will omit all tokens with comments |
204
- | `stripObjectKeys` | will not print quotes around object keys which are JavaScript identifier names |
208
+ | `stripObjectKeys` | will not print quotes around object keys which are JavaScript identifier names |
209
+ | `enforceDoubleQuotes` | will surround all strings with double quotes |
210
+ | `enforceSingleQuotes` | will surround all strings with single quotes |
211
+ | `trimTrailingCommas` | will omit all trailing commas after the last object entry or array item |
205
212
 
206
213
  ```js
207
214
  // Just concatenate the tokens to produce the same output as was the input.
@@ -220,6 +227,12 @@ print(tokens, { indent: 2 })
220
227
  print(tokens, { indent: ' ', pruneComments: true })
221
228
  // Print to multiple lines with indentation enabled and JSON5 object keys.
222
229
  print(tokens, { indent: '\t', stripObjectKeys: true })
230
+ // Print to multiple lines with indentation enabled, unify JSON5 formatting.
231
+ print(tokens, {
232
+ indent: ' ',
233
+ enforceDoubleQuotes: true,
234
+ trimTrailingCommas: true
235
+ })
223
236
  ```
224
237
 
225
238
  ### Tokenizing
@@ -228,7 +241,10 @@ The method `tokenize` has the same prototype as the method [`parse`](#module-int
228
241
 
229
242
  ```js
230
243
  const { tokenize } = require('@prantlf/jsonlint')
231
- const tokens = tokenize('{"flag":true /* default */}', { ignoreComments: true }))
244
+ const tokens = tokenize('{"flag":true /* default */}', {
245
+ ignoreComments: true,
246
+ rawTokens: true
247
+ }))
232
248
  // Returns the following array:
233
249
  // [
234
250
  // { type: 'symbol', raw: '{', value: '{' },
@@ -253,15 +269,13 @@ If you want to retain comments or whitespace for pretty-printing, for example, s
253
269
 
254
270
  ### Performance
255
271
 
256
- This is a part of an output from the [parser benchmark], when parsing a 4.2 KB formatted string ([package.json](./package.json)) with Node.js 10.15.3:
272
+ This is a part of an output from the [parser benchmark], when parsing a 4.2 KB formatted string ([package.json](./package.json)) with Node.js 12.14.0:
257
273
 
258
- the built-in parser x 68,212 ops/sec ±0.86% (87 runs sampled)
259
- the pure jju parser x 10,234 ops/sec ±1.08% (89 runs sampled)
260
- the extended jju parser x 10,210 ops/sec ±1.26% (88 runs sampled)
261
- the tokenizable jju parser x 8,832 ops/sec ±0.92% (89 runs sampled)
262
- the tokenizing jju parser x 7,911 ops/sec ±1.05% (86 runs sampled)
274
+ jsonlint using native JSON.parse x 97,109 ops/sec ±0.81% (93 runs sampled)
275
+ jsonlint using hand-coded parser x 7,256 ops/sec ±0.54% (90 runs sampled)
276
+ jsonlint using tokenising parser x 6,387 ops/sec ±0.44% (88 runs sampled)
263
277
 
264
- A custom JSON parser is [a lot slower] than the built-in one. However, it is more important to have a [clear error reporting] than the highest speed in scenarios like parsing configuration files. Extending the parser with the support for comments and single-quoted strings does not affect the performance. Making the parser collect tokens and their locations decreases the performance a bit.
278
+ A custom JSON parser is [a lot slower] than the built-in one. However, it is more important to have a [clear error reporting] than the highest speed in scenarios like parsing configuration files. (For better error-reporting, the speed can be preserved by using the native parser initially and re-parsing with another parser only in case of failure.) Features like comments or JSON5 are also helpful in configuration files. Tokens preserve the complete input and can be used for pretty-printing without losing the comments.
265
279
 
266
280
  ### Error Handling
267
281
 
@@ -303,7 +317,7 @@ ${reason}`)
303
317
 
304
318
  ## License
305
319
 
306
- Copyright (C) 2012-2019 Zachary Carter, Ferdinand Prantl
320
+ Copyright (C) 2012-2022 Zachary Carter, Ferdinand Prantl
307
321
 
308
322
  Licensed under the [MIT License].
309
323
 
@@ -316,8 +330,10 @@ Licensed under the [MIT License].
316
330
  [UMD]: https://github.com/umdjs/umd
317
331
  [`Grunt`]: https://gruntjs.com/
318
332
  [`Gulp`]: http://gulpjs.com/
333
+ [`Rollup`]: https://rollupjs.org/
319
334
  [`@prantlf/grunt-jsonlint`]: https://www.npmjs.com/package/@prantlf/grunt-jsonlint
320
335
  [`@prantlf/gulp-jsonlint`]: https://www.npmjs.com/package/@prantlf/gulp-jsonlint
336
+ [`rollup-plugin-jsonlint`]: https://www.npmjs.com/package/rollup-plugin-jsonlint
321
337
  [7x faster than the custom parser]: ./benchmarks/results/performance.md#results
322
338
  [parser benchmark]: ./benchmarks#json-parser-comparison
323
339
  [a lot slower]: ./benchmarks/results/performance.md#results
package/lib/cli.js CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- var fs = require('fs')
4
- var path = require('path')
5
- var parser = require('./jsonlint')
6
- var formatter = require('./formatter')
7
- var printer = require('./printer')
8
- var sorter = require('./sorter')
9
- var validator = require('./validator')
10
- var pkg = require('../package')
3
+ const fs = require('fs')
4
+ const path = require('path')
5
+ const parser = require('./jsonlint')
6
+ const formatter = require('./formatter')
7
+ const printer = require('./printer')
8
+ const sorter = require('./sorter')
9
+ const validator = require('./validator')
10
+ const pkg = require('../package')
11
11
 
12
12
  function collectExtensions (extension) {
13
13
  return extension.split(',')
14
14
  }
15
15
 
16
- var options = require('commander')
16
+ const commander = require('commander')
17
17
  .name('jsonlint')
18
18
  .usage('[options] [<file or directory> ...]')
19
19
  .description(pkg.description)
@@ -34,6 +34,9 @@ var options = require('commander')
34
34
  .option('-P, --pretty-print-invalid', 'force pretty-printing even for invalid input')
35
35
  .option('--prune-comments', 'omit comments from the prettified output')
36
36
  .option('--strip-object-keys', 'strip quotes from object keys if possible (JSON5)')
37
+ .option('--enforce-double-quotes', 'surrounds all strings with double quotes')
38
+ .option('--enforce-single-quotes', 'surrounds all strings with single quotes (JSON5)')
39
+ .option('--trim-trailing-commas', 'omit trailing commas from objects and arrays (JSON5)')
37
40
  .version(pkg.version, '-v, --version')
38
41
  .on('--help', () => {
39
42
  console.log()
@@ -44,6 +47,8 @@ var options = require('commander')
44
47
  })
45
48
  .parse(process.argv)
46
49
 
50
+ const options = commander.opts()
51
+
47
52
  function logNormalError (error, file) {
48
53
  console.log('File:', file)
49
54
  console.error(error.message)
@@ -55,7 +60,7 @@ function logCompactError (error, file) {
55
60
  }
56
61
 
57
62
  function parse (source, file) {
58
- var parserOptions, parsed, formatted
63
+ let parserOptions, parsed, formatted
59
64
  try {
60
65
  parserOptions = {
61
66
  mode: options.mode,
@@ -65,13 +70,13 @@ function parse (source, file) {
65
70
  allowDuplicateObjectKeys: options.duplicateKeys
66
71
  }
67
72
  if (options.validate) {
68
- var validate
73
+ let validate
69
74
  try {
70
- var schema = fs.readFileSync(path.normalize(options.validate), 'utf8')
75
+ const schema = fs.readFileSync(path.normalize(options.validate), 'utf8')
71
76
  parserOptions.environment = options.environment
72
77
  validate = validator.compile(schema, parserOptions)
73
78
  } catch (error) {
74
- var message = 'Loading the JSON schema failed: "' +
79
+ const message = 'Loading the JSON schema failed: "' +
75
80
  options.validate + '".\n' + error.message
76
81
  throw new Error(message)
77
82
  }
@@ -81,12 +86,15 @@ function parse (source, file) {
81
86
  }
82
87
  if (options.prettyPrint) {
83
88
  parserOptions.rawTokens = true
84
- var tokens = parser.tokenize(source, parserOptions)
89
+ const tokens = parser.tokenize(source, parserOptions)
85
90
  // TODO: Support sorting tor the tokenized input too.
86
91
  return printer.print(tokens, {
87
92
  indent: options.indent,
88
93
  pruneComments: options.pruneComments,
89
- stripObjectKeys: options.stripObjectKeys
94
+ stripObjectKeys: options.stripObjectKeys,
95
+ enforceDoubleQuotes: options.enforceDoubleQuotes,
96
+ enforceSingleQuotes: options.enforceSingleQuotes,
97
+ trimTrailingCommas: options.trimTrailingCommas
90
98
  })
91
99
  }
92
100
  if (options.sortKeys) {
@@ -126,7 +134,7 @@ function parse (source, file) {
126
134
 
127
135
  function processFile (file) {
128
136
  file = path.normalize(file)
129
- var source = parse(fs.readFileSync(file, 'utf8'), file)
137
+ const source = parse(fs.readFileSync(file, 'utf8'), file)
130
138
  if (options.inPlace) {
131
139
  fs.writeFileSync(file, source)
132
140
  } else {
@@ -137,23 +145,23 @@ function processFile (file) {
137
145
  }
138
146
 
139
147
  function processSources (src, checkExtension) {
140
- var extensions = options.extensions.map(function (extension) {
148
+ const extensions = options.extensions.map(function (extension) {
141
149
  return '.' + extension
142
150
  })
143
- var srcStat
151
+ let srcStat
144
152
  try {
145
153
  srcStat = fs.statSync(src)
146
154
  if (srcStat.isFile()) {
147
155
  if (checkExtension) {
148
- var ext = path.extname(src)
156
+ const ext = path.extname(src)
149
157
  if (extensions.indexOf(ext) < 0) {
150
158
  return
151
159
  }
152
160
  }
153
161
  processFile(src)
154
162
  } else if (srcStat.isDirectory()) {
155
- var sources = fs.readdirSync(src)
156
- for (var i = 0; i < sources.length; i++) {
163
+ const sources = fs.readdirSync(src)
164
+ for (let i = 0; i < sources.length; i++) {
157
165
  processSources(path.join(src, sources[i]), true)
158
166
  }
159
167
  }
@@ -163,20 +171,20 @@ function processSources (src, checkExtension) {
163
171
  }
164
172
 
165
173
  function main () {
166
- var files = options.args
167
- var source = ''
174
+ const files = commander.args
175
+ let source = ''
168
176
  if (files.length) {
169
- for (var i = 0; i < files.length; i++) {
177
+ for (let i = 0; i < files.length; i++) {
170
178
  processSources(files[i], false)
171
179
  }
172
180
  } else {
173
- var stdin = process.openStdin()
181
+ const stdin = process.openStdin()
174
182
  stdin.setEncoding('utf8')
175
183
  stdin.on('data', function (chunk) {
176
184
  source += chunk.toString('utf8')
177
185
  })
178
186
  stdin.on('end', function () {
179
- var parsed = parse(source, '<stdin>')
187
+ const parsed = parse(source, '<stdin>')
180
188
  if (!options.quiet) {
181
189
  console.log(parsed)
182
190
  }
package/lib/formatter.js CHANGED
@@ -1,7 +1,7 @@
1
1
  (function (global, factory) {
2
- // eslint-disable-next-line no-unused-expressions
2
+ // eslint-disable-next-line no-unused-expressions, multiline-ternary
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports)
4
- // eslint-disable-next-line no-undef
4
+ // eslint-disable-next-line no-undef, multiline-ternary
5
5
  : typeof define === 'function' && define.amd ? define('jsonlint-formatter', ['exports'], factory)
6
6
  // eslint-disable-next-line no-undef
7
7
  : (global = global || self, factory(global.jsonlintFormatter = {}))
@@ -21,15 +21,17 @@
21
21
  }
22
22
 
23
23
  function format (json, indent) {
24
- var i = 0
25
- var length = 0
26
- var indentString = indent !== undefined
24
+ let i = 0
25
+ let length = 0
26
+ const indentString = indent !== undefined
27
27
  ? typeof indent === 'number'
28
- ? ' '.repeat(indent) : indent : ' '
29
- var outputString = ''
30
- var indentLevel = 0
31
- var inString
32
- var currentChar
28
+ ? new Array(indent + 1).join(' ')
29
+ : indent
30
+ : ' '
31
+ let outputString = ''
32
+ let indentLevel = 0
33
+ let inString
34
+ let currentChar
33
35
 
34
36
  for (i = 0, length = json.length; i < length; i += 1) {
35
37
  currentChar = json.charAt(i)
package/lib/jsonlint.d.ts CHANGED
@@ -90,6 +90,9 @@ declare module '@prantlf/jsonlint/lib/printer' {
90
90
  indent?: number | string
91
91
  pruneComments?: boolean
92
92
  stripObjectKeys?: boolean
93
+ enforceDoubleQuotes?: boolean
94
+ enforceSingleQuotes?: boolean
95
+ trimTrailingCommas?: boolean
93
96
  }
94
97
 
95
98
  /**