UNPKG

1.89 kBJavaScriptView Raw
1/**
2 * Requires quoted keys in objects.
3 *
4 * Type: `Boolean`
5 *
6 * Value: `true`
7 *
8 * #### Example
9 *
10 * ```js
11 * "requireQuotedKeysInObjects": true
12 * ```
13 *
14 * ##### Valid
15 *
16 * ```js
17 * var x = { 'a': { "default": 1 } };
18 * ```
19 *
20 * ##### Invalid
21 *
22 * ```js
23 * var x = { a: 1 };
24 * ```
25 */
26
27var assert = require('assert');
28var cst = require('cst');
29
30module.exports = function() { };
31
32module.exports.prototype = {
33
34 configure: function(options) {
35 assert(
36 options === true,
37 this.getOptionName() + ' option requires a true value or should be removed'
38 );
39 },
40
41 getOptionName: function() {
42 return 'requireQuotedKeysInObjects';
43 },
44
45 check: function(file, errors) {
46 file.iterateNodesByType('ObjectExpression', function(node) {
47 node.properties.forEach(function(property) {
48 if (
49 property.type === 'ObjectMethod' &&
50 (property.kind === 'get' || property.kind === 'set')
51 ) {
52 return;
53 }
54
55 if (property.shorthand || property.method ||
56 node.type === 'SpreadProperty') {
57 return;
58 }
59
60 var key = property.key;
61 if (key && !(typeof key.value === 'string' && key.type.indexOf('Literal') > -1)) {
62 errors.cast({
63 message: 'Object key without surrounding quotes',
64 element: property.firstChild
65 });
66 }
67 });
68 });
69 },
70
71 _fix: function(file, error) {
72 var element = error.element.firstChild;
73 var newElem = new cst.Token(element.type, '"' + element.getSourceCode() + '"');
74
75 element.parentElement.replaceChild(
76 newElem,
77 element
78 );
79 }
80};