diff --git a/.eslintrc.json b/.eslintrc.json index 2270877fc..d1b9a0af6 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -7,10 +7,23 @@ "Buffer": true, "escape": true }, - "extends": ["eslint:recommended", "prettier"], + "extends": ["airbnb-base", "prettier"], "plugins": ["prettier"], "rules": { - "no-console": 0, - "no-unused-vars": 1 - } + "no-console": 0 + }, + "overrides": [ + { + "files": ["__tests__/**//*.js"], + "globals": { + "expect": true, + "beforeAll": true, + "afterAll": true + }, + "rules": { + "global-require": "off", + "import/no-unresolved": "off" + } + } + ] } diff --git a/__tests__/__helpers.js b/__tests__/__helpers.js index 8b3f6a12f..67fd20f9f 100644 --- a/__tests__/__helpers.js +++ b/__tests__/__helpers.js @@ -11,18 +11,14 @@ * and limitations under the License. */ -var fs = require('fs-extra'); +const fs = require('fs-extra'); module.exports = { - clearOutput: function() { - fs.emptyDirSync('__tests__/__output'); - }, + clearOutput: () => fs.emptyDirSync('__tests__/__output'), - fileToJSON: function(path) { - return fs.readJsonSync(path); - }, + fileToJSON: path => fs.readJsonSync(path), - fileExists: function(filePath) { + fileExists(filePath) { try { return fs.statSync(filePath).isFile(); } catch (err) { @@ -30,7 +26,7 @@ module.exports = { } }, - pathDoesNotExist: function(path) { + pathDoesNotExist(path) { try { return !fs.existsSync(path); } catch (err) { @@ -38,12 +34,11 @@ module.exports = { } }, - dirDoesNotExist: function(dirPath) { + dirDoesNotExist(dirPath) { return this.pathDoesNotExist(dirPath); }, - fileDoesNotExist: function(filePath) { + fileDoesNotExist(filePath) { return this.pathDoesNotExist(filePath); - - } + }, }; diff --git a/__tests__/buildAllPlatforms.test.js b/__tests__/buildAllPlatforms.test.js index 81f53d7c3..28cdd4067 100644 --- a/__tests__/buildAllPlatforms.test.js +++ b/__tests__/buildAllPlatforms.test.js @@ -11,8 +11,8 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var StyleDictionary = require('../index'); +const helpers = require('./__helpers'); +const StyleDictionary = require('../index'); describe('buildAllPlatforms', () => { @@ -25,14 +25,14 @@ describe('buildAllPlatforms', () => { }); it('should work with json config', () => { - var StyleDictionaryExtended = StyleDictionary.extend(__dirname + '/__configs/test.json'); + const StyleDictionaryExtended = StyleDictionary.extend(`${__dirname}/__configs/test.json`); StyleDictionaryExtended.buildAllPlatforms(); expect(helpers.fileExists('./__tests__/__output/web/_icons.css')).toBeTruthy(); expect(helpers.fileExists('./__tests__/__output/android/colors.xml')).toBeTruthy(); }); it('should work with js config', () => { - var StyleDictionaryExtended = StyleDictionary.extend(__dirname + '/__configs/test.js'); + const StyleDictionaryExtended = StyleDictionary.extend(`${__dirname}/__configs/test.js`); StyleDictionaryExtended.buildAllPlatforms(); expect(helpers.fileExists('./__tests__/__output/web/_icons.css')).toBeTruthy(); expect(helpers.fileExists('./__tests__/__output/android/colors.xml')).toBeTruthy(); diff --git a/__tests__/buildFile.test.js b/__tests__/buildFile.test.js index 8e742d222..28de066a2 100644 --- a/__tests__/buildFile.test.js +++ b/__tests__/buildFile.test.js @@ -11,8 +11,8 @@ * and limitations under the License. */ -var buildFile = require('../lib/buildFile'); -var helpers = require('./__helpers'); +const buildFile = require('../lib/buildFile'); +const helpers = require('./__helpers'); function format() { return "hi"; diff --git a/__tests__/buildFiles.test.js b/__tests__/buildFiles.test.js index 2e4e972d4..c843955e4 100644 --- a/__tests__/buildFiles.test.js +++ b/__tests__/buildFiles.test.js @@ -11,117 +11,101 @@ * and limitations under the License. */ -var buildFiles = require('../lib/buildFiles'); -var helpers = require('./__helpers'); -var _ = require('lodash'); +const _ = require('lodash'); +const buildFiles = require('../lib/buildFiles'); +const helpers = require('./__helpers'); -var dictionary = { +const dictionary = { properties: { foo: { value: 'bar' }, - bingo: { value: 'bango' } - } + bingo: { value: 'bango' }, + }, }; -var platform = { +const platform = { files: [ { destination: '__tests__/__output/test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; -var platformWithBuildPath = { +const platformWithBuildPath = { buildPath: '__tests__/__output/', files: [ { destination: 'test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; -var platformWithFilter = { +const platformWithFilter = { buildPath: '__tests__/__output/', files: [ { destination: 'test.json', - filter: function(property) { - return property.value === "bango" + filter({ value }) { + return value === 'bango'; }, - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - }, - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; -var platformWithoutFormatter = { +const platformWithoutFormatter = { buildPath: '__tests__/__output/', files: [ { destination: 'test.json', - } - ] + }, + ], }; -var platformWithBadBuildPath = { +const platformWithBadBuildPath = { buildPath: '__tests__/__output', files: [ { destination: 'test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; describe('buildFiles', () => { + beforeEach(() => helpers.clearOutput()); - beforeEach(() => { - helpers.clearOutput(); - }); + afterEach(() => helpers.clearOutput()); - afterEach(() => { - helpers.clearOutput(); - }); - - it('should throw if build path doesn\'t have a trailing slash', () => { - expect( - buildFiles.bind(null, dictionary, platformWithBadBuildPath), - ).toThrow('Build path must end in a trailing slash or you will get weird file names.'); + it("should throw if build path doesn't have a trailing slash", () => { + expect(buildFiles.bind(null, dictionary, platformWithBadBuildPath)).toThrow( + 'Build path must end in a trailing slash or you will get weird file names.' + ); }); it('should throw if template or formatter missing', () => { - expect( - buildFiles.bind(null, dictionary, platformWithoutFormatter), - ).toThrow('Please supply a template or formatter'); + expect(buildFiles.bind(null, dictionary, platformWithoutFormatter)).toThrow( + 'Please supply a template or formatter' + ); }); it('should work without buildPath', () => { - buildFiles( dictionary, platform ); + buildFiles(dictionary, platform); expect(helpers.fileExists('./__tests__/__output/test.json')).toBeTruthy(); }); it('should work with buildPath', () => { - buildFiles( dictionary, platformWithBuildPath ); + buildFiles(dictionary, platformWithBuildPath); expect(helpers.fileExists('./__tests__/__output/test.json')).toBeTruthy(); }); it('should work with a filter', () => { buildFiles(dictionary, platformWithFilter); expect(helpers.fileExists('./__tests__/__output/test.json')).toBeTruthy(); - var output = require("./__output/test.json") + const output = require('./__output/test.json'); expect(output).toHaveProperty('bingo'); expect(output).not.toHaveProperty('foo'); - _.each(output, function(property) { - expect(property.value).toBe('bango'); - }); + _.each(output, ({ value }) => expect(value).toBe('bango')); }); - }); diff --git a/__tests__/buildPlatform.test.js b/__tests__/buildPlatform.test.js index 1f9d2a472..6329f03f8 100644 --- a/__tests__/buildPlatform.test.js +++ b/__tests__/buildPlatform.test.js @@ -11,10 +11,10 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var config = helpers.fileToJSON(__dirname + '/__configs/test.json'); -var StyleDictionary = require('../index'); -var StyleDictionaryExtended = StyleDictionary.extend(config); +const helpers = require('./__helpers'); +const config = helpers.fileToJSON(`${__dirname}/__configs/test.json`); +const StyleDictionary = require('../index'); +const StyleDictionaryExtended = StyleDictionary.extend(config); describe('buildPlatform', () => { @@ -28,7 +28,7 @@ describe('buildPlatform', () => { ).toThrow('Platform foobar doesn\'t exist'); expect( - function() { + () => { StyleDictionaryExtended.buildPlatform('web'); } ).not.toThrow(); @@ -69,7 +69,7 @@ describe('buildPlatform', () => { }); it('should handle non-string values in properties', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ source: ['__tests__/__properties/nonString.json'], platforms: { test: { @@ -87,7 +87,7 @@ describe('buildPlatform', () => { StyleDictionaryExtended.buildPlatform('test'); expect(helpers.fileExists('./__tests__/__output/output.json')).toBeTruthy(); // var input = helpers.fileToJSON('./__tests__/__properties/nonString.json'); - var output = helpers.fileToJSON('./__tests__/__output/output.json'); + const output = helpers.fileToJSON('./__tests__/__output/output.json'); // Make sure transforms run on non-string values as they normally would expect(output).toHaveProperty('color.red.value', output.color.otherRed.value); @@ -104,7 +104,7 @@ describe('buildPlatform', () => { }); it('should handle non-property nodes', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ source: ['__tests__/__properties/nonPropertyNode.json'], platforms: { test: { @@ -121,15 +121,15 @@ describe('buildPlatform', () => { }); StyleDictionaryExtended.buildPlatform('test'); expect(helpers.fileExists('./__tests__/__output/output.json')).toBeTruthy(); - var input = helpers.fileToJSON('./__tests__/__properties/nonPropertyNode.json'); - var output = helpers.fileToJSON('./__tests__/__output/output.json'); + const input = helpers.fileToJSON('./__tests__/__properties/nonPropertyNode.json'); + const output = helpers.fileToJSON('./__tests__/__output/output.json'); expect(output.color.key1).toEqual(input.color.key1); expect(output.color.base.red.key2).toEqual(input.color.base.red.key2); expect(output.color.base.attributes.key3).toEqual(input.color.base.attributes.key3); }); it('should handle comments', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ source: ['__tests__/__properties/comment.json'], platforms: { test: { @@ -146,13 +146,13 @@ describe('buildPlatform', () => { }); StyleDictionaryExtended.buildPlatform('test'); expect(helpers.fileExists('./__tests__/__output/output.json')).toBeTruthy(); - var input = helpers.fileToJSON('./__tests__/__properties/comment.json'); - var output = helpers.fileToJSON('./__tests__/__output/output.json'); + const input = helpers.fileToJSON('./__tests__/__properties/comment.json'); + const output = helpers.fileToJSON('./__tests__/__output/output.json'); expect(output.size.large.comment).toEqual(input.size.large.comment); }); it('should throw an error if given a transformGroup that doesn\'t exist', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ source: ['__properties/**/*.json'], platforms: { foo: { diff --git a/__tests__/cleanAction.test.js b/__tests__/cleanAction.test.js index b6eea86c4..fc109fd26 100644 --- a/__tests__/cleanAction.test.js +++ b/__tests__/cleanAction.test.js @@ -11,31 +11,26 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var fs = require('fs-extra'); -var StyleDictionary = require('../index'); -var StyleDictionaryExtended = StyleDictionary.extend({ - "platforms": { - "android": { - "actions": ["test"] - } - } +const fs = require('fs-extra'); +const helpers = require('./__helpers'); +const StyleDictionary = require('../index'); + +const StyleDictionaryExtended = StyleDictionary.extend({ + platforms: { + android: { + actions: ['test'], + }, + }, }); StyleDictionaryExtended.registerAction({ name: 'test', - do: function() { - fs.writeFileSync('./__tests__/__output/action.txt', 'hi') - }, - undo: function() { - fs.removeSync('./__tests__/__output/action.txt') - } + do: () => fs.writeFileSync('./__tests__/__output/action.txt', 'hi'), + undo: () => fs.removeSync('./__tests__/__output/action.txt'), }); describe('cleanAction', () => { - describe('clean actions', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -50,5 +45,4 @@ describe('cleanAction', () => { expect(helpers.fileDoesNotExist('./__tests__/__output/action.txt')).toBeTruthy(); }); }); - }); diff --git a/__tests__/cleanAllPlatforms.test.js b/__tests__/cleanAllPlatforms.test.js index 27436eefb..14bc57946 100644 --- a/__tests__/cleanAllPlatforms.test.js +++ b/__tests__/cleanAllPlatforms.test.js @@ -11,10 +11,10 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var config = helpers.fileToJSON(__dirname + '/__configs/test.json'); -var StyleDictionary = require('../index'); -var StyleDictionaryExtended = StyleDictionary.extend(config); +const helpers = require('./__helpers'); +const config = helpers.fileToJSON(`${__dirname}/__configs/test.json`); +const StyleDictionary = require('../index'); +const StyleDictionaryExtended = StyleDictionary.extend(config); describe('cleanAllPlatforms', () => { diff --git a/__tests__/cleanDir.test.js b/__tests__/cleanDir.test.js index 57508e165..fd73bef49 100644 --- a/__tests__/cleanDir.test.js +++ b/__tests__/cleanDir.test.js @@ -11,10 +11,10 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var buildFile = require('../lib/buildFile'); -var cleanFile = require('../lib/cleanFile'); -var cleanDir = require('../lib/cleanDir'); +const helpers = require('./__helpers'); +const buildFile = require('../lib/buildFile'); +const cleanFile = require('../lib/cleanFile'); +const cleanDir = require('../lib/cleanDir'); function format() { return "hi"; diff --git a/__tests__/cleanDirs.test.js b/__tests__/cleanDirs.test.js index eb547fd0b..7f7efc7ce 100644 --- a/__tests__/cleanDirs.test.js +++ b/__tests__/cleanDirs.test.js @@ -11,42 +11,37 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var buildFiles = require('../lib/buildFiles'); -var cleanFiles = require('../lib/cleanFiles'); -var cleanDirs = require('../lib/cleanDirs'); +const helpers = require('./__helpers'); +const buildFiles = require('../lib/buildFiles'); +const cleanFiles = require('../lib/cleanFiles'); +const cleanDirs = require('../lib/cleanDirs'); -var dictionary = { +const dictionary = { properties: { - foo: 'bar' - } + foo: 'bar', + }, }; -var platform = { +const platform = { files: [ { destination: '__tests__/__output/extradir1/extradir2/extradir1/extradir2/test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; -var platformWithBuildPath = { +const platformWithBuildPath = { buildPath: '__tests__/__output/extradir1/extradir2/', files: [ { destination: 'test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; describe('cleanDirs', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -56,17 +51,17 @@ describe('cleanDirs', () => { }); it('should delete without buildPath', () => { - buildFiles( dictionary, platform ); - cleanFiles( dictionary, platform ); - cleanDirs( dictionary, platform ); + buildFiles(dictionary, platform); + cleanFiles(dictionary, platform); + cleanDirs(dictionary, platform); expect(helpers.dirDoesNotExist('./__tests__/__output/extradir1/extradir2')).toBeTruthy(); expect(helpers.dirDoesNotExist('./__tests__/__output/extradir1')).toBeTruthy(); }); it('should delete with buildPath', () => { - buildFiles( dictionary, platformWithBuildPath ); - cleanFiles( dictionary, platformWithBuildPath ); - cleanDirs( dictionary, platformWithBuildPath ); + buildFiles(dictionary, platformWithBuildPath); + cleanFiles(dictionary, platformWithBuildPath); + cleanDirs(dictionary, platformWithBuildPath); expect(helpers.dirDoesNotExist('./__tests__/__output/extradir1/extradir2')).toBeTruthy(); expect(helpers.dirDoesNotExist('./__tests__/__output/extradir1')).toBeTruthy(); }); diff --git a/__tests__/cleanFile.test.js b/__tests__/cleanFile.test.js index ffcdee164..8022f3967 100644 --- a/__tests__/cleanFile.test.js +++ b/__tests__/cleanFile.test.js @@ -11,9 +11,9 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var buildFile = require('../lib/buildFile'); -var cleanFile = require('../lib/cleanFile'); +const helpers = require('./__helpers'); +const buildFile = require('../lib/buildFile'); +const cleanFile = require('../lib/cleanFile'); function format() { return "hi"; diff --git a/__tests__/cleanFiles.test.js b/__tests__/cleanFiles.test.js index cf9bd1e27..7d87f20c7 100644 --- a/__tests__/cleanFiles.test.js +++ b/__tests__/cleanFiles.test.js @@ -11,41 +11,36 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var buildFiles = require('../lib/buildFiles'); -var cleanFiles = require('../lib/cleanFiles'); +const helpers = require('./__helpers'); +const buildFiles = require('../lib/buildFiles'); +const cleanFiles = require('../lib/cleanFiles'); -var dictionary = { +const dictionary = { properties: { - foo: 'bar' - } + foo: 'bar', + }, }; -var platform = { +const platform = { files: [ { destination: '__tests__/__output/test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; -var platformWithBuildPath = { +const platformWithBuildPath = { buildPath: '__tests__/__output/', files: [ { destination: 'test.json', - format: function(dictionary) { - return JSON.stringify(dictionary.properties) - } - } - ] + format: ({ properties }) => JSON.stringify(properties), + }, + ], }; describe('cleanFiles', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -55,14 +50,14 @@ describe('cleanFiles', () => { }); it('should delete without buildPath', () => { - buildFiles( dictionary, platform ); - cleanFiles( dictionary, platform ); + buildFiles(dictionary, platform); + cleanFiles(dictionary, platform); expect(helpers.fileDoesNotExist('./__tests__/__output/test.json')).toBeTruthy(); }); it('should delete with buildPath', () => { - buildFiles( dictionary, platformWithBuildPath ); - cleanFiles( dictionary, platformWithBuildPath ); + buildFiles(dictionary, platformWithBuildPath); + cleanFiles(dictionary, platformWithBuildPath); expect(helpers.fileDoesNotExist('./__tests__/__output/test.json')).toBeTruthy(); }); }); diff --git a/__tests__/cleanPlatform.test.js b/__tests__/cleanPlatform.test.js index fbb6e39cf..932dcf85d 100644 --- a/__tests__/cleanPlatform.test.js +++ b/__tests__/cleanPlatform.test.js @@ -11,10 +11,10 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var config = helpers.fileToJSON(__dirname + '/__configs/test.json'); -var StyleDictionary = require('../index'); -var StyleDictionaryExtended = StyleDictionary.extend(config); +const helpers = require('./__helpers'); +const config = helpers.fileToJSON(`${__dirname}/__configs/test.json`); +const StyleDictionary = require('../index'); +const StyleDictionaryExtended = StyleDictionary.extend(config); describe('cleanPlatform', () => { diff --git a/__tests__/cliBuild.test.js b/__tests__/cliBuild.test.js index 9062a8afb..435b3b67c 100644 --- a/__tests__/cliBuild.test.js +++ b/__tests__/cliBuild.test.js @@ -11,8 +11,8 @@ * and limitations under the License. */ -var childProcess = require("child_process"); -var helpers = require('./__helpers'); +const childProcess = require("child_process"); +const helpers = require('./__helpers'); describe('cliBuildWithJsConfig', () => { diff --git a/__tests__/common/transforms.test.js b/__tests__/common/transforms.test.js index bcb8aff1a..099d76745 100644 --- a/__tests__/common/transforms.test.js +++ b/__tests__/common/transforms.test.js @@ -11,133 +11,156 @@ * and limitations under the License. */ -var transforms = require('../../lib/common/transforms'); -var path = require('path'); +const path = require('path'); +const transforms = require('../../lib/common/transforms'); describe('common', () => { describe('transforms', () => { - describe('name/cti/camel', () => { it('should handle prefix', () => { - expect(transforms["name/cti/camel"].transformer( - { - path: ['one','two','three'] - },{ - prefix: 'prefix' - } - )).toBe('prefixOneTwoThree'); + expect( + transforms['name/cti/camel'].transformer( + { + path: ['one', 'two', 'three'], + }, + { + prefix: 'prefix', + } + ) + ).toBe('prefixOneTwoThree'); }); it('should handle no prefix', () => { - expect(transforms["name/cti/camel"].transformer( - { - path: ['one','two','three'] - },{ - } - )).toBe('oneTwoThree'); + expect( + transforms['name/cti/camel'].transformer( + { + path: ['one', 'two', 'three'], + }, + {} + ) + ).toBe('oneTwoThree'); }); }); - describe('name/cti/kebab', () => { it('should handle prefix', () => { - expect(transforms["name/cti/kebab"].transformer( - { - path: ['one','two','three'] - },{ - prefix: 'prefix' - } - )).toBe('prefix-one-two-three'); + expect( + transforms['name/cti/kebab'].transformer( + { + path: ['one', 'two', 'three'], + }, + { + prefix: 'prefix', + } + ) + ).toBe('prefix-one-two-three'); }); it('should handle no prefix', () => { - expect(transforms["name/cti/kebab"].transformer( - { - path: ['one','two','three'] - },{ - } - )).toBe('one-two-three'); + expect( + transforms['name/cti/kebab'].transformer( + { + path: ['one', 'two', 'three'], + }, + {} + ) + ).toBe('one-two-three'); }); }); describe('name/cti/snake', () => { it('should handle prefix', () => { - expect(transforms["name/cti/snake"].transformer( - { - path: ['one','two','three'] - },{ - prefix: 'prefix' - } - )).toBe('prefix_one_two_three'); + expect( + transforms['name/cti/snake'].transformer( + { + path: ['one', 'two', 'three'], + }, + { + prefix: 'prefix', + } + ) + ).toBe('prefix_one_two_three'); }); it('should handle no prefix', () => { - expect(transforms["name/cti/snake"].transformer( - { - path: ['one','two','three'] - },{ - } - )).toBe('one_two_three'); + expect( + transforms['name/cti/snake'].transformer( + { + path: ['one', 'two', 'three'], + }, + {} + ) + ).toBe('one_two_three'); }); }); describe('name/cti/constant', () => { it('should handle prefix', () => { - expect(transforms["name/cti/constant"].transformer( - { - path: ['one','two','three'] - },{ - prefix: 'prefix' - } - )).toBe('PREFIX_ONE_TWO_THREE'); + expect( + transforms['name/cti/constant'].transformer( + { + path: ['one', 'two', 'three'], + }, + { + prefix: 'prefix', + } + ) + ).toBe('PREFIX_ONE_TWO_THREE'); }); it('should handle no prefix', () => { - expect(transforms["name/cti/constant"].transformer( - { - path: ['one','two','three'] - },{ - } - )).toBe('ONE_TWO_THREE'); + expect( + transforms['name/cti/constant'].transformer( + { + path: ['one', 'two', 'three'], + }, + {} + ) + ).toBe('ONE_TWO_THREE'); }); }); describe('name/ti/constant', () => { it('should handle prefix', () => { - expect(transforms["name/ti/constant"].transformer( - { - path: ['one','two','three'] - },{ - prefix: 'prefix' - } - )).toBe('PREFIX_TWO_THREE'); + expect( + transforms['name/ti/constant'].transformer( + { + path: ['one', 'two', 'three'], + }, + { + prefix: 'prefix', + } + ) + ).toBe('PREFIX_TWO_THREE'); }); it('should handle no prefix', () => { - expect(transforms["name/ti/constant"].transformer( - { - path: ['one','two','three'] - },{ - } - )).toBe('TWO_THREE'); + expect( + transforms['name/ti/constant'].transformer( + { + path: ['one', 'two', 'three'], + }, + {} + ) + ).toBe('TWO_THREE'); }); }); describe('attribute/color', () => { it('should handle normal colors', () => { - var attributes = transforms["attribute/color"].transformer({ - value: "#aaaaaa" + const attributes = transforms['attribute/color'].transformer({ + value: '#aaaaaa', }); expect(attributes).toHaveProperty('rgb.a', 1); expect(attributes).toHaveProperty('rgb.r', 170); expect(attributes).toHaveProperty('hsl.s', 0); }); it('should handle colors with transparency', () => { - var attributes = transforms["attribute/color"].transformer({ - value: "#aaaaaa99" + const attributes = transforms['attribute/color'].transformer({ + value: '#aaaaaa99', }); - var attributes2 = transforms["attribute/color"].transformer({ - value: "rgba(170,170,170,0.6)" + const attributes2 = transforms['attribute/color'].transformer({ + value: 'rgba(170,170,170,0.6)', }); expect(attributes).toHaveProperty('rgb.a', 0.6); expect(attributes).toHaveProperty('rgb.r', 170); @@ -150,234 +173,232 @@ describe('common', () => { describe('color/hex', () => { it('should handle hex colors', () => { - var value = transforms["color/hex"].transformer({ - value: "#aaaaaa" + const value = transforms['color/hex'].transformer({ + value: '#aaaaaa', }); - expect(value).toBe("#aaaaaa"); + expect(value).toBe('#aaaaaa'); }); it('should handle hex8 colors', () => { - var value = transforms["color/hex"].transformer({ - value: "#aaaaaaaa" + const value = transforms['color/hex'].transformer({ + value: '#aaaaaaaa', }); - expect(value).toBe("#aaaaaa"); + expect(value).toBe('#aaaaaa'); }); it('should handle rgb colors', () => { - var value = transforms["color/hex"].transformer({ - value: "rgb(170,170,170)" + const value = transforms['color/hex'].transformer({ + value: 'rgb(170,170,170)', }); - expect(value).toBe("#aaaaaa"); + expect(value).toBe('#aaaaaa'); }); it('should handle rgb (object) colors', () => { - var value = transforms["color/hex"].transformer({ + const value = transforms['color/hex'].transformer({ value: { r: '170', g: '170', - b: '170' - } + b: '170', + }, }); - var value2 = transforms["color/hex"].transformer({ - value: "rgb(170,170,170)" + const value2 = transforms['color/hex'].transformer({ + value: 'rgb(170,170,170)', }); - expect(value).toBe("#aaaaaa"); - expect(value2).toBe("#aaaaaa"); + expect(value).toBe('#aaaaaa'); + expect(value2).toBe('#aaaaaa'); }); it('should handle hsl colors', () => { - var value = transforms["color/hex"].transformer({ + const value = transforms['color/hex'].transformer({ value: { h: '0', s: '0', - l: '0.5' - } + l: '0.5', + }, }); - var value2 = transforms["color/hex"].transformer({ - value: "hsl(0,0,0.5)" + const value2 = transforms['color/hex'].transformer({ + value: 'hsl(0,0,0.5)', }); - expect(value).toBe("#808080"); - expect(value2).toBe("#808080"); + expect(value).toBe('#808080'); + expect(value2).toBe('#808080'); }); }); - describe('color/hex8', () => { it('should handle hex colors', () => { - var value = transforms["color/hex8"].transformer({ - value: "#aaaaaa" + const value = transforms['color/hex8'].transformer({ + value: '#aaaaaa', }); - expect(value).toBe("#aaaaaaff"); + expect(value).toBe('#aaaaaaff'); }); it('should handle rgb colors', () => { - var value = transforms["color/hex8"].transformer({ - value: "rgb(170,170,170)" + const value = transforms['color/hex8'].transformer({ + value: 'rgb(170,170,170)', }); - expect(value).toBe("#aaaaaaff"); + expect(value).toBe('#aaaaaaff'); }); it('should handle rgb colors', () => { - var value = transforms["color/hex8"].transformer({ - value: "rgb(170,170,170)" + const value = transforms['color/hex8'].transformer({ + value: 'rgb(170,170,170)', }); - var value2 = transforms["color/hex8"].transformer({ - value: "rgba(170,170,170,0.6)" + const value2 = transforms['color/hex8'].transformer({ + value: 'rgba(170,170,170,0.6)', }); - expect(value).toBe("#aaaaaaff"); - expect(value2).toBe("#aaaaaa99"); + expect(value).toBe('#aaaaaaff'); + expect(value2).toBe('#aaaaaa99'); }); }); describe('color/hex8android', () => { it('should handle colors without alpha', () => { - var value = transforms["color/hex8android"].transformer({ - value: "#aaaaaa" + const value = transforms['color/hex8android'].transformer({ + value: '#aaaaaa', }); - expect(value).toBe("#ffaaaaaa"); + expect(value).toBe('#ffaaaaaa'); }); it('should handle colors with alpha', () => { - var value = transforms["color/hex8android"].transformer({ - value: "#aaaaaa99" + const value = transforms['color/hex8android'].transformer({ + value: '#aaaaaa99', }); - expect(value).toBe("#99aaaaaa"); + expect(value).toBe('#99aaaaaa'); }); }); describe('color/rgb', () => { it('should handle normal colors', () => { - var value = transforms["color/rgb"].transformer({ - value: "#aaaaaa" + const value = transforms['color/rgb'].transformer({ + value: '#aaaaaa', }); - expect(value).toBe("rgb(170, 170, 170)"); + expect(value).toBe('rgb(170, 170, 170)'); }); it('should handle colors with transparency', () => { - var value = transforms["color/rgb"].transformer({ - value: "#aaaaaa99" + const value = transforms['color/rgb'].transformer({ + value: '#aaaaaa99', }); - expect(value).toBe("rgba(170, 170, 170, 0.6)"); + expect(value).toBe('rgba(170, 170, 170, 0.6)'); }); }); describe('color/UIColor', () => { it('should handle normal colors', () => { - var value = transforms["color/UIColor"].transformer({ - value: "#aaaaaa" + const value = transforms['color/UIColor'].transformer({ + value: '#aaaaaa', }); - expect(value).toBe("[UIColor colorWithRed:0.67f green:0.67f blue:0.67f alpha:1.00f]"); + expect(value).toBe('[UIColor colorWithRed:0.67f green:0.67f blue:0.67f alpha:1.00f]'); }); it('should handle colors with transparency', () => { - var value = transforms["color/UIColor"].transformer({ - value: "#aaaaaa99" + const value = transforms['color/UIColor'].transformer({ + value: '#aaaaaa99', }); - expect(value).toBe("[UIColor colorWithRed:0.67f green:0.67f blue:0.67f alpha:0.60f]"); + expect(value).toBe('[UIColor colorWithRed:0.67f green:0.67f blue:0.67f alpha:0.60f]'); }); }); - describe('color/css', () => { it('should handle normal colors', () => { - var value = transforms["color/css"].transformer({ - value: "rgb(170, 170, 170)" + const value = transforms['color/css'].transformer({ + value: 'rgb(170, 170, 170)', }); - expect(value).toBe("#aaaaaa"); + expect(value).toBe('#aaaaaa'); }); it('should handle colors with transparency', () => { - var value = transforms["color/css"].transformer({ - value: "#aaaaaa99" + const value = transforms['color/css'].transformer({ + value: '#aaaaaa99', }); - expect(value).toBe("rgba(170, 170, 170, 0.6)"); + expect(value).toBe('rgba(170, 170, 170, 0.6)'); }); }); describe('size/sp', () => { it('should work', () => { - var value = transforms["size/sp"].transformer({ - value: "12px" + const value = transforms['size/sp'].transformer({ + value: '12px', }); - var value2 = transforms["size/sp"].transformer({ - value: "12" + const value2 = transforms['size/sp'].transformer({ + value: '12', }); - expect(value).toBe("12.00sp"); - expect(value2).toBe("12.00sp"); + expect(value).toBe('12.00sp'); + expect(value2).toBe('12.00sp'); }); }); describe('size/dp', () => { it('should work', () => { - var value = transforms["size/dp"].transformer({ - value: "12px" + const value = transforms['size/dp'].transformer({ + value: '12px', }); - var value2 = transforms["size/dp"].transformer({ - value: "12" + const value2 = transforms['size/dp'].transformer({ + value: '12', }); - expect(value).toBe("12.00dp"); - expect(value2).toBe("12.00dp"); + expect(value).toBe('12.00dp'); + expect(value2).toBe('12.00dp'); }); }); describe('size/remToSp', () => { it('should work', () => { - var value = transforms["size/remToSp"].transformer({ - value: "1" + const value = transforms['size/remToSp'].transformer({ + value: '1', }); - expect(value).toBe("16.00sp"); + expect(value).toBe('16.00sp'); }); }); describe('size/remToDp', () => { it('should work', () => { - var value = transforms["size/remToDp"].transformer({ - value: "1" + const value = transforms['size/remToDp'].transformer({ + value: '1', }); - expect(value).toBe("16.00dp"); + expect(value).toBe('16.00dp'); }); }); describe('size/px', () => { it('should work', () => { - var value = transforms["size/px"].transformer({ - value: "10" + const value = transforms['size/px'].transformer({ + value: '10', }); - expect(value).toBe("10px"); + expect(value).toBe('10px'); }); }); describe('size/remToPt', () => { it('should work', () => { - var value = transforms["size/remToPt"].transformer({ - value: "1" + const value = transforms['size/remToPt'].transformer({ + value: '1', }); - expect(value).toBe("16.00f"); + expect(value).toBe('16.00f'); }); }); describe('size/remToPx', () => { it('should work', () => { - var value = transforms["size/remToPx"].transformer({ - value: "1" + const value = transforms['size/remToPx'].transformer({ + value: '1', }); - expect(value).toBe("16px"); + expect(value).toBe('16px'); }); }); describe('size/rem', () => { it('should work', () => { - var value = transforms["size/rem"].transformer({ - value: "1" + const value = transforms['size/rem'].transformer({ + value: '1', }); - expect(value).toBe("1rem"); + expect(value).toBe('1rem'); }); }); describe('content/quote', () => { it('should work', () => { - var value = transforms["content/quote"].transformer({ - value: "hello" + const value = transforms['content/quote'].transformer({ + value: 'hello', }); expect(value).toBe("'hello'"); }); @@ -385,8 +406,8 @@ describe('common', () => { describe('content/icon', () => { it('should work', () => { - var value = transforms["content/icon"].transformer({ - value: "" + const value = transforms['content/icon'].transformer({ + value: '', }); expect(value).toBe("'\\E001'"); }); @@ -394,8 +415,8 @@ describe('common', () => { describe('content/objC/literal', () => { it('should work', () => { - var value = transforms["content/objC/literal"].transformer({ - value: "hello" + const value = transforms['content/objC/literal'].transformer({ + value: 'hello', }); expect(value).toBe('@"hello"'); }); @@ -403,8 +424,8 @@ describe('common', () => { describe('asset/objC/literal', () => { it('should work', () => { - var value = transforms["asset/objC/literal"].transformer({ - value: "hello" + const value = transforms['asset/objC/literal'].transformer({ + value: 'hello', }); expect(value).toBe('@"hello"'); }); @@ -412,8 +433,8 @@ describe('common', () => { describe('font/objC/literal', () => { it('should work', () => { - var value = transforms["font/objC/literal"].transformer({ - value: "hello" + const value = transforms['font/objC/literal'].transformer({ + value: 'hello', }); expect(value).toBe('@"hello"'); }); @@ -421,21 +442,20 @@ describe('common', () => { describe('time/seconds', () => { it('should work', () => { - var value = transforms["time/seconds"].transformer({ - value: "1000" + const value = transforms['time/seconds'].transformer({ + value: '1000', }); - expect(value).toBe("1.00s"); + expect(value).toBe('1.00s'); }); }); describe('asset/path', () => { it('should work', () => { - var value = transforms["asset/path"].transformer({ - value: "foo.json" + const value = transforms['asset/path'].transformer({ + value: 'foo.json', }); - expect(value).toBe(path.join(process.cwd(), "foo.json")); + expect(value).toBe(path.join(process.cwd(), 'foo.json')); }); }); - }); }); diff --git a/__tests__/exportPlatform.test.js b/__tests__/exportPlatform.test.js index 62f961805..cce331dc6 100644 --- a/__tests__/exportPlatform.test.js +++ b/__tests__/exportPlatform.test.js @@ -11,16 +11,16 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var keys = require('lodash/keys'); -var config = helpers.fileToJSON(__dirname + '/__configs/test.json'); -var StyleDictionary = require('../index').extend(config); +const helpers = require('./__helpers'); +const keys = require('lodash/keys'); +const config = helpers.fileToJSON(`${__dirname}/__configs/test.json`); +const StyleDictionary = require('../index').extend(config); describe('exportPlatform', () => { it('should throw if not given a platform', () => { expect( - function(){ + () => { StyleDictionary.exportPlatform() } ).toThrow(); @@ -28,7 +28,7 @@ describe('exportPlatform', () => { it('should throw if not given a proper platform', () => { expect( - function(){ + () => { StyleDictionary.exportPlatform('foo'); } ).toThrow(); @@ -36,34 +36,34 @@ describe('exportPlatform', () => { it('should not throw if given a proper platform', () => { expect( - function(){ + () => { StyleDictionary.exportPlatform('web'); } ).not.toThrow(); }); it('should return an object', () => { - var dictionary = StyleDictionary.exportPlatform('web'); + const dictionary = StyleDictionary.exportPlatform('web'); expect(typeof dictionary).toBe('object'); }); it('should have the same structure as the original properties', () => { - var dictionary = StyleDictionary.exportPlatform('web'); + const dictionary = StyleDictionary.exportPlatform('web'); expect(keys(dictionary)).toEqual(keys(StyleDictionary.properties)); }); it('should have resolved references', () => { - var dictionary = StyleDictionary.exportPlatform('web'); + const dictionary = StyleDictionary.exportPlatform('web'); expect(dictionary.color.font.link.value).toEqual(dictionary.color.base.blue['100'].value); }); it('should have applied transforms', () => { - var dictionary = StyleDictionary.exportPlatform('web'); + const dictionary = StyleDictionary.exportPlatform('web'); expect(dictionary.size.padding.base.value.indexOf('px')).toBeGreaterThan(0); }); it('should not have mutated the original properties', () => { - var dictionary = StyleDictionary.exportPlatform('web'); + const dictionary = StyleDictionary.exportPlatform('web'); expect(dictionary.color.font.link.value).not.toEqual(StyleDictionary.properties.color.font.link.value); expect(StyleDictionary.properties.size.padding.base.value.indexOf('px')).toBe(-1); }); @@ -71,8 +71,8 @@ describe('exportPlatform', () => { // Make sure when we perform transforms and resolve references // we don't mutate the original object added to the property. it('properties should have original value untouched', () => { - var dictionary = StyleDictionary.exportPlatform('web'); - var properties = helpers.fileToJSON(__dirname + '/__properties/colors.json'); + const dictionary = StyleDictionary.exportPlatform('web'); + const properties = helpers.fileToJSON(`${__dirname}/__properties/colors.json`); expect(dictionary.color.font.link.original.value).toEqual(properties.color.font.link.value); }); diff --git a/__tests__/extend.test.js b/__tests__/extend.test.js index 5f3c92cdf..496b0b1cb 100644 --- a/__tests__/extend.test.js +++ b/__tests__/extend.test.js @@ -11,11 +11,11 @@ * and limitations under the License. */ -var helpers = require('./__helpers'); -var StyleDictionary = require('../index'); -var _ = require('lodash'); +const helpers = require('./__helpers'); +const StyleDictionary = require('../index'); +const _ = require('lodash'); -var test_props = { +const test_props = { size: { padding: { tiny: {value:'0'} @@ -27,18 +27,18 @@ describe('extend', () => { describe('method signature', () => { it('should accept a string as a path to a JSON file', () => { - var StyleDictionaryExtended = StyleDictionary.extend(__dirname + '/__configs/test.json'); + const StyleDictionaryExtended = StyleDictionary.extend(`${__dirname}/__configs/test.json`); expect(StyleDictionaryExtended).toHaveProperty('platforms.web'); }); it('should accept an object as options', () => { - var config = helpers.fileToJSON(__dirname + '/__configs/test.json'); - var StyleDictionaryExtended = StyleDictionary.extend(config); + const config = helpers.fileToJSON(`${__dirname}/__configs/test.json`); + const StyleDictionaryExtended = StyleDictionary.extend(config); expect(StyleDictionaryExtended).toHaveProperty('platforms.web'); }); it('should override attributes', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ properties: { foo: 'bar' } @@ -47,8 +47,8 @@ describe('extend', () => { }); it('should have all same properties', () => { - var StyleDictionaryExtended = StyleDictionary.extend({}); - _.each(_.keys(StyleDictionaryExtended), function(property) { + const StyleDictionaryExtended = StyleDictionary.extend({}); + _.each(_.keys(StyleDictionaryExtended), property => { expect(StyleDictionaryExtended).toHaveProperty(property); }); }); @@ -68,16 +68,16 @@ describe('extend', () => { }); it('should update properties if there are includes', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ - include: [__dirname + '/__configs/include.json'] + const StyleDictionaryExtended = StyleDictionary.extend({ + include: [`${__dirname}/__configs/include.json`] }); expect(typeof StyleDictionaryExtended.properties.size.padding.tiny).toBe('object'); }); it('should override existing properties if there are includes', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ properties: test_props, - include: [__dirname + '/__configs/include.json'] + include: [`${__dirname}/__configs/include.json`] }); expect(StyleDictionaryExtended).toHaveProperty('properties.size.padding.tiny.value', '3'); }); @@ -98,18 +98,18 @@ describe('extend', () => { }); it('should build the properties object if a source is given', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ - "source": [__dirname + "/__properties/paddings.json"] + const StyleDictionaryExtended = StyleDictionary.extend({ + "source": [`${__dirname}/__properties/paddings.json`] }); - expect(StyleDictionaryExtended.properties).toEqual(helpers.fileToJSON(__dirname + "/__properties/paddings.json")); + expect(StyleDictionaryExtended.properties).toEqual(helpers.fileToJSON(`${__dirname}/__properties/paddings.json`)); }); it('should override existing properties source is given', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ + const StyleDictionaryExtended = StyleDictionary.extend({ properties: test_props, - source: [__dirname + "/__properties/paddings.json"] + source: [`${__dirname}/__properties/paddings.json`] }); - expect(StyleDictionaryExtended.properties).toEqual(helpers.fileToJSON(__dirname + "/__properties/paddings.json")); + expect(StyleDictionaryExtended.properties).toEqual(helpers.fileToJSON(`${__dirname}/__properties/paddings.json`)); }); }); @@ -117,18 +117,18 @@ describe('extend', () => { // This is to allow style dictionaries to depend on other style dictionaries and // override properties. Useful for skinning it('should not throw a collision error if a source file collides with an include', () => { - var StyleDictionaryExtended = StyleDictionary.extend({ - include: [__dirname + "/__properties/paddings.json"], - source: [__dirname + "/__properties/paddings.json"], + const StyleDictionaryExtended = StyleDictionary.extend({ + include: [`${__dirname}/__properties/paddings.json`], + source: [`${__dirname}/__properties/paddings.json`], log: 'error' }); - expect(StyleDictionaryExtended.properties).toEqual(helpers.fileToJSON(__dirname + "/__properties/paddings.json")); + expect(StyleDictionaryExtended.properties).toEqual(helpers.fileToJSON(`${__dirname}/__properties/paddings.json`)); }); it('should throw a error if the collision is in source files and log is set to error', () => { expect( StyleDictionary.extend.bind(null, { - source: [__dirname + "/__properties/paddings.json", __dirname + "/__properties/paddings.json"], + source: [`${__dirname}/__properties/paddings.json`, `${__dirname}/__properties/paddings.json`], log: 'error' }) ).toThrow('Collision detected at:'); @@ -137,14 +137,14 @@ describe('extend', () => { it('should throw a warning if the collision is in source files and log is set to warn', () => { expect( StyleDictionary.extend.bind(null, { - source: [__dirname + "/__properties/paddings.json", __dirname + "/__properties/paddings.json"], + source: [`${__dirname}/__properties/paddings.json`, `${__dirname}/__properties/paddings.json`], log: 'warn' }) ).not.toThrow(); }); - it('should accept a string as a path to a JSON5 file', function() { - var StyleDictionaryExtended = StyleDictionary.extend(__dirname + '/__configs/test.json5'); + it('should accept a string as a path to a JSON5 file', () => { + const StyleDictionaryExtended = StyleDictionary.extend(`${__dirname}/__configs/test.json5`); expect(StyleDictionaryExtended).toHaveProperty('platforms.web'); }); }); diff --git a/__tests__/filterProperties.test.js b/__tests__/filterProperties.test.js index 35657833f..8e5782f41 100644 --- a/__tests__/filterProperties.test.js +++ b/__tests__/filterProperties.test.js @@ -11,12 +11,12 @@ * and limitations under the License. */ -var filterProperties = require('../lib/filterProperties'); -var helpers = require('./__helpers'); -var flattenProperties = require("../lib/utils/flattenProperties"); -var _ = require('lodash'); +const filterProperties = require('../lib/filterProperties'); +const helpers = require('./__helpers'); +const flattenProperties = require("../lib/utils/flattenProperties"); +const _ = require('lodash'); -var colorRed = { +const colorRed = { "value": "#FF0000", "original": { "value": "#FF0000", @@ -27,9 +27,9 @@ var colorRed = { "color", "red" ] -} +}; -var colorBlue = { +const colorBlue = { "value": "#0000FF", "original": { "value": "#0000FF", @@ -40,9 +40,9 @@ var colorBlue = { "color", "blue" ] -} +}; -var sizeSmall = { +const sizeSmall = { "value": "2px", "original": { "value": "2px", @@ -53,9 +53,9 @@ var sizeSmall = { "size", "small" ] -} +}; -var sizeLarge = { +const sizeLarge = { "value": "4px", "original": { "value": "4px", @@ -66,9 +66,9 @@ var sizeLarge = { "size", "large" ] -} +}; -var properties = { +const properties = { "color": { "red": colorRed, "blue": colorBlue, @@ -79,10 +79,10 @@ var properties = { } }; -var dictionary = { +const dictionary = { "properties": properties, "allProperties": flattenProperties(properties) -} +}; describe('filterProperties', () => { @@ -99,11 +99,9 @@ describe('filterProperties', () => { }); it('should work with a filter function', () => { - var filter = function(property) { - return property.path.includes("size"); - } - var filteredDictionary = filterProperties(dictionary, filter); - _.each(filteredDictionary.allProperties, function(property) { + const filter = ({path}) => path.includes("size"); + const filteredDictionary = filterProperties(dictionary, filter); + _.each(filteredDictionary.allProperties, property => { expect(property).not.toBe(colorRed); expect(property).not.toBe(colorBlue); }); @@ -113,9 +111,9 @@ describe('filterProperties', () => { }); it('should work with a filter object', () => { - var filter = { "attributes": { "category": "size" } }; - var filteredDictionary = filterProperties(dictionary, filter); - _.each(filteredDictionary.allProperties, function(property) { + const filter = { "attributes": { "category": "size" } }; + const filteredDictionary = filterProperties(dictionary, filter); + _.each(filteredDictionary.allProperties, property => { expect(property).not.toBe(colorRed); expect(property).not.toBe(colorBlue); }); diff --git a/__tests__/formats/all.test.js b/__tests__/formats/all.test.js index 5786e776c..5bf606665 100644 --- a/__tests__/formats/all.test.js +++ b/__tests__/formats/all.test.js @@ -11,21 +11,20 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var helpers = require('../__helpers'); -var _ = require('lodash'); - -var file = { - "destination": "__output/", - "format": "javascript/es6", - "filter": { - "attributes": { - "category": "color" - } - } +const _ = require('lodash'); +const formats = require('../../lib/common/formats'); + +const file = { + destination: '__output/', + format: 'javascript/es6', + filter: { + attributes: { + category: 'color', + }, + }, }; -var dictionary = { +const dictionary = { properties: { color: { red: { value: '#FF0000' }, @@ -34,12 +33,11 @@ var dictionary = { }; describe('formats', () => { - const constantDate = new Date('2000-01-01'); const globalDate = global.Date; beforeAll(() => { - global.Date = function() { return constantDate }; + global.Date = () => constantDate; }); afterAll(() => { @@ -47,14 +45,13 @@ describe('formats', () => { }); describe('all', () => { - _.each(_.keys(formats), function(key) { - it('should return ' + key + ' as a string', () => { - var formatter = formats[key].bind(file); - var output = formatter(dictionary, file); + _.each(_.keys(formats), key => { + it(`should return ${key} as a string`, () => { + const formatter = formats[key].bind(file); + const output = formatter(dictionary, file); expect(typeof output).toBe('string'); expect(output).toMatchSnapshot(); }); }); }); - }); diff --git a/__tests__/formats/es6Constants.test.js b/__tests__/formats/es6Constants.test.js index c0728424d..f88ffc985 100644 --- a/__tests__/formats/es6Constants.test.js +++ b/__tests__/formats/es6Constants.test.js @@ -10,43 +10,40 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ -var fs = require('fs-extra'); -var helpers = require('../__helpers'); -var formats = require('../../lib/common/formats'); +const fs = require('fs-extra'); +const helpers = require('../__helpers'); +const formats = require('../../lib/common/formats'); -var file = { - "destination": "__output/", - "format": "javascript/es6", - "filter": { - "attributes": { - "category": "color" - } - } +const file = { + destination: '__output/', + format: 'javascript/es6', + filter: { + attributes: { + category: 'color', + }, + }, }; -var dictionary = { - "allProperties": [{ - "name": "red", - "value": "#EF5350", - "original": { - "value": "#EF5350" - }, - "attributes": { - "category": "color", - "type": "base", - "item": "red", - "subitem": "400" +const dictionary = { + allProperties: [ + { + name: 'red', + value: '#EF5350', + original: { + value: '#EF5350', + }, + attributes: { + category: 'color', + type: 'base', + item: 'red', + subitem: '400', + }, + path: ['color', 'base', 'red', '400'], }, - "path": [ - "color", - "base", - "red", - "400" - ] - }] + ], }; -var formatter = formats['javascript/es6'].bind(file); +const formatter = formats['javascript/es6'].bind(file); describe('formats', () => { describe('javascript/es6', () => { @@ -59,10 +56,9 @@ describe('formats', () => { }); it('should be a valid JS file', () => { - fs.writeFileSync('./__tests__/__output/output.js', formatter(dictionary) ); - var test = require('../__output/output.js'); + fs.writeFileSync('./__tests__/__output/output.js', formatter(dictionary)); + const test = require('../__output/output.js'); expect(test.red).toEqual(dictionary.allProperties[0].value); }); }); - }); diff --git a/__tests__/formats/javascriptModule.test.js b/__tests__/formats/javascriptModule.test.js index 8b6b7556e..1cf710a6c 100644 --- a/__tests__/formats/javascriptModule.test.js +++ b/__tests__/formats/javascriptModule.test.js @@ -11,21 +11,21 @@ * and limitations under the License. */ -var fs = require('fs-extra'); -var helpers = require('../__helpers'); -var formats = require('../../lib/common/formats'); - -var file = { - "destination": "__output/", - "format": "javascript/module", - "filter": { - "attributes": { - "category": "color" - } - } +const fs = require('fs-extra'); +const helpers = require('../__helpers'); +const formats = require('../../lib/common/formats'); + +const file = { + destination: '__output/', + format: 'javascript/module', + filter: { + attributes: { + category: 'color', + }, + }, }; -var dictionary = { +const dictionary = { properties: { color: { red: { value: '#FF0000' }, @@ -33,11 +33,10 @@ var dictionary = { }, }; -var formatter = formats['javascript/module'].bind(file); +const formatter = formats['javascript/module'].bind(file); describe('formats', () => { describe('javascript/module', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -47,10 +46,9 @@ describe('formats', () => { }); it('should be a valid JS file', () => { - fs.writeFileSync('./__tests__/__output/output.js', formatter(dictionary) ); - var test = require('../__output/output.js'); + fs.writeFileSync('./__tests__/__output/output.js', formatter(dictionary)); + const test = require('../__output/output.js'); expect(test.color.red.value).toEqual(dictionary.properties.color.red.value); }); - }); }); diff --git a/__tests__/formats/javascriptObject.test.js b/__tests__/formats/javascriptObject.test.js index 2e9678973..51aeac29c 100644 --- a/__tests__/formats/javascriptObject.test.js +++ b/__tests__/formats/javascriptObject.test.js @@ -11,16 +11,16 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var vm = require('vm'); +const vm = require('vm'); +const formats = require('../../lib/common/formats'); -var file = { - "destination": "__output/", - "format": "javascript/object", - "name": "foo" +const file = { + destination: '__output/', + format: 'javascript/object', + name: 'foo', }; -var dictionary = { +const dictionary = { properties: { color: { red: { value: '#FF0000' }, @@ -28,11 +28,10 @@ var dictionary = { }, }; -var formatter = formats['javascript/object'].bind(file); +const formatter = formats['javascript/object'].bind(file); describe('formats', () => { describe('javascript/object', () => { - it('should be valid JS syntax', done => { try { vm.runInNewContext(formatter(dictionary)); @@ -41,6 +40,5 @@ describe('formats', () => { return done(new Error(err)); } }); - }); }); diff --git a/__tests__/formats/javascriptUmd.test.js b/__tests__/formats/javascriptUmd.test.js index 02aa4aa60..f926e2182 100644 --- a/__tests__/formats/javascriptUmd.test.js +++ b/__tests__/formats/javascriptUmd.test.js @@ -11,21 +11,21 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var fs = require('fs-extra'); -var helpers = require('../__helpers'); - -var file = { - "destination": "__output/", - "format": "javascript/umd", - "filter": { - "attributes": { - "category": "color" - } - } +const fs = require('fs-extra'); +const formats = require('../../lib/common/formats'); +const helpers = require('../__helpers'); + +const file = { + destination: '__output/', + format: 'javascript/umd', + filter: { + attributes: { + category: 'color', + }, + }, }; -var dictionary = { +const dictionary = { properties: { color: { red: { value: '#FF0000' }, @@ -33,11 +33,10 @@ var dictionary = { }, }; -var formatter = formats['javascript/umd'].bind(file); +const formatter = formats['javascript/umd'].bind(file); describe('formats', () => { describe('javascript/umd', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -47,10 +46,9 @@ describe('formats', () => { }); it('should be a valid JS file', () => { - fs.writeFileSync('./__tests__/__output/umd.js', formatter(dictionary) ); - var test = require('../__output/umd.js'); + fs.writeFileSync('./__tests__/__output/umd.js', formatter(dictionary)); + const test = require('../__output/umd.js'); expect(test.color.red.value).toEqual(dictionary.properties.color.red.value); }); - }); }); diff --git a/__tests__/formats/json.test.js b/__tests__/formats/json.test.js index 72b29ee5d..bb0d180e6 100644 --- a/__tests__/formats/json.test.js +++ b/__tests__/formats/json.test.js @@ -11,16 +11,16 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var fs = require('fs-extra'); -var helpers = require('../__helpers'); +const fs = require('fs-extra'); +const formats = require('../../lib/common/formats'); +const helpers = require('../__helpers'); -var file = { - "destination": "__output/", - "format": "json" +const file = { + destination: '__output/', + format: 'json', }; -var dictionary = { +const dictionary = { properties: { color: { red: { value: '#FF0000' }, @@ -28,11 +28,10 @@ var dictionary = { }, }; -var formatter = formats['json'].bind(file); +const formatter = formats.json.bind(file); describe('formats', () => { describe('json', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -42,10 +41,9 @@ describe('formats', () => { }); it('should be a valid JSON file', () => { - fs.writeFileSync('./__tests__/__output/output.json', formatter(dictionary) ); - var test = require('../__output/output.json'); + fs.writeFileSync('./__tests__/__output/output.json', formatter(dictionary)); + const test = require('../__output/output.json'); expect(test.color.red.value).toEqual(dictionary.properties.color.red.value); }); }); - }); diff --git a/__tests__/formats/lessIcons.test.js b/__tests__/formats/lessIcons.test.js index 26480e69f..ac8a4c8f1 100644 --- a/__tests__/formats/lessIcons.test.js +++ b/__tests__/formats/lessIcons.test.js @@ -11,20 +11,20 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var less = require('less'); +const less = require('less'); +const formats = require('../../lib/common/formats'); -var file = { - "destination": "__output/", - "format": "less/icons", - "name": "foo" +const file = { + destination: '__output/', + format: 'less/icons', + name: 'foo', }; -var propertyName = 'content-icon-email'; -var propertyValue = "'\\E001'"; -var itemClass = '3d_rotation'; +const propertyName = 'content-icon-email'; +const propertyValue = "'\\E001'"; +const itemClass = '3d_rotation'; -var dictionary = { +const dictionary = { allProperties: [ { name: propertyName, @@ -41,25 +41,24 @@ var dictionary = { ], }; -var config = { +const config = { prefix: 'sd', // Style-Dictionary Prefix }; -var formatter = formats['less/icons'].bind(file); +const formatter = formats['less/icons'].bind(file); describe('formats', () => { describe('less/icons', () => { - it('should have a valid less syntax', done => { - less.render(formatter(dictionary, config)) - .then(function(output) { + less + .render(formatter(dictionary, config)) + .then(output => { expect(output).toBeDefined(); done(); }) - .catch(function(err) { - done(new Error(err)) + .catch(err => { + done(new Error(err)); }); }); - }); }); diff --git a/__tests__/formats/lessVariables.test.js b/__tests__/formats/lessVariables.test.js index 07c2412fe..e31379e4b 100644 --- a/__tests__/formats/lessVariables.test.js +++ b/__tests__/formats/lessVariables.test.js @@ -11,19 +11,19 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var less = require('less'); +const less = require('less'); +const formats = require('../../lib/common/formats'); -var file = { - "destination": "__output/", - "format": "less/variables", - "name": "foo" +const file = { + destination: '__output/', + format: 'less/variables', + name: 'foo', }; -var propertyName = 'color-base-red-400'; -var propertyValue = '#EF5350'; +const propertyName = 'color-base-red-400'; +const propertyValue = '#EF5350'; -var dictionary = { +const dictionary = { allProperties: [ { name: propertyName, @@ -42,21 +42,20 @@ var dictionary = { ], }; -var formatter = formats['less/variables'].bind(file); +const formatter = formats['less/variables'].bind(file); describe('formats', () => { describe('less/variables', () => { - it('should have a valid less syntax', done => { - less.render(formatter(dictionary)) - .then(function(output) { + less + .render(formatter(dictionary)) + .then(output => { expect(output).toBeDefined(); done(); }) - .catch(function(err) { - done(new Error(err)) + .catch(err => { + done(new Error(err)); }); }); - }); }); diff --git a/__tests__/formats/scssIcons.test.js b/__tests__/formats/scssIcons.test.js index 016907d52..fa2d8832b 100644 --- a/__tests__/formats/scssIcons.test.js +++ b/__tests__/formats/scssIcons.test.js @@ -11,20 +11,20 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var scss = require('node-sass'); +const scss = require('node-sass'); +const formats = require('../../lib/common/formats'); -var file = { - "destination": "__output/", - "format": "scss/icons", - "name": "foo" +const file = { + destination: '__output/', + format: 'scss/icons', + name: 'foo', }; -var propertyName = 'content-icon-email'; -var propertyValue = "'\\E001'"; -var itemClass = '3d_rotation'; +const propertyName = 'content-icon-email'; +const propertyValue = "'\\E001'"; +const itemClass = '3d_rotation'; -var dictionary = { +const dictionary = { allProperties: [ { name: propertyName, @@ -41,26 +41,27 @@ var dictionary = { ], }; -var config = { +const config = { prefix: 'sd', // Style-Dictionary Prefix }; -var formatter = formats['scss/icons'].bind(file); +const formatter = formats['scss/icons'].bind(file); describe('formats', () => { describe('scss/icons', () => { - it('should have a valid scss syntax', done => { - scss.render({ - data: formatter(dictionary, config), - }, function(err, result) { - if(err) { - return done(new Error(err)); + scss.render( + { + data: formatter(dictionary, config), + }, + (err, result) => { + if (err) { + return done(new Error(err)); + } + expect(result.css).toBeDefined(); + return done(); } - expect(result.css).toBeDefined(); - return done(); - }); + ); }); - }); }); diff --git a/__tests__/formats/scssVariables.test.js b/__tests__/formats/scssVariables.test.js index a034bf494..a37a598bf 100644 --- a/__tests__/formats/scssVariables.test.js +++ b/__tests__/formats/scssVariables.test.js @@ -11,19 +11,19 @@ * and limitations under the License. */ -var formats = require('../../lib/common/formats'); -var scss = require('node-sass'); +const scss = require('node-sass'); +const formats = require('../../lib/common/formats'); -var file = { - "destination": "__output/", - "format": "scss/variables", - "name": "foo" +const file = { + destination: '__output/', + format: 'scss/variables', + name: 'foo', }; -var propertyName = 'color-base-red-400'; -var propertyValue = '#EF5350'; +const propertyName = 'color-base-red-400'; +const propertyValue = '#EF5350'; -var dictionary = { +const dictionary = { allProperties: [ { name: propertyName, @@ -42,22 +42,23 @@ var dictionary = { ], }; -var formatter = formats['scss/variables'].bind(file); +const formatter = formats['scss/variables'].bind(file); describe('formats', () => { describe('scss/variables', () => { - it('should have a valid scss syntax', done => { - scss.render({ - data: formatter(dictionary), - }, function(err, result) { - if(err) { - return done(new Error(err)); + scss.render( + { + data: formatter(dictionary), + }, + (err, result) => { + if (err) { + return done(new Error(err)); + } + expect(result.css).toBeDefined(); + return done(); } - expect(result.css).toBeDefined(); - return done(); - }); + ); }); - }); }); diff --git a/__tests__/performAction.test.js b/__tests__/performAction.test.js index aad21193e..32d42ed6a 100644 --- a/__tests__/performAction.test.js +++ b/__tests__/performAction.test.js @@ -11,29 +11,29 @@ * and limitations under the License. */ -var StyleDictionary = require('../index'); -var StyleDictionaryExtended = StyleDictionary.extend({ - "platforms": { - "android": { - "actions": ["test"] - } - } +const StyleDictionary = require('../index'); + +const StyleDictionaryExtended = StyleDictionary.extend({ + platforms: { + android: { + actions: ['test'], + }, + }, }); -var helpers = require('./__helpers'); -var fs = require('fs-extra'); +const helpers = require('./__helpers'); +const fs = require('fs-extra'); StyleDictionaryExtended.registerAction({ name: 'test', - do: function() { - fs.writeFileSync('./__tests__/__output/action.txt', 'hi') + do() { + fs.writeFileSync('./__tests__/__output/action.txt', 'hi'); + }, + undo() { + fs.removeSync('./__tests__/__output/action.txt'); }, - undo: function() { - fs.removeSync('./__tests__/__output/action.txt') - } }); describe('performAction', () => { - beforeEach(() => { helpers.clearOutput(); }); @@ -48,5 +48,4 @@ describe('performAction', () => { expect(helpers.fileExists('./__tests__/__output/action.txt')).toBeTruthy(); }); }); - }); diff --git a/__tests__/register/action.test.js b/__tests__/register/action.test.js index 889954acb..4b443884f 100644 --- a/__tests__/register/action.test.js +++ b/__tests__/register/action.test.js @@ -11,37 +11,37 @@ * and limitations under the License. */ -var StyleDictionary = require('../../index'); -var StyleDictionaryExtended = StyleDictionary.extend({}); +const StyleDictionary = require('../../index'); + +const StyleDictionaryExtended = StyleDictionary.extend({}); describe('register', () => { describe('action', () => { - it('should error if name is not a string', () => { expect( StyleDictionaryExtended.registerAction.bind(null, { - do: function() {} + do() {}, }) ).toThrow('name must be a string'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: 1, - do: function() {} + do() {}, }) ).toThrow('name must be a string'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: [], - do: function() {} + do() {}, }) ).toThrow('name must be a string'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: {}, - do: function() {} + do() {}, }) ).toThrow('name must be a string'); }); @@ -49,35 +49,35 @@ describe('register', () => { it('should error if do is not a function', () => { expect( StyleDictionaryExtended.registerAction.bind(null, { - name: 'test' + name: 'test', }) ).toThrow('do must be a function'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: 'test', - do: 1 + do: 1, }) ).toThrow('do must be a function'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: 'test', - do: 'name' + do: 'name', }) ).toThrow('do must be a function'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: 'test', - do: [] + do: [], }) ).toThrow('do must be a function'); expect( StyleDictionaryExtended.registerAction.bind(null, { name: 'test', - do: {} + do: {}, }) ).toThrow('do must be a function'); }); @@ -85,24 +85,23 @@ describe('register', () => { it('should work if name and do are good', () => { StyleDictionaryExtended.registerAction({ name: 'scss', - do: function() {} + do() {}, }); - expect(typeof StyleDictionaryExtended.action['scss'].do).toBe('function'); + expect(typeof StyleDictionaryExtended.action.scss.do).toBe('function'); }); it('should handle an undo function', () => { StyleDictionaryExtended.registerAction({ name: 'scss', - do: function() {}, - undo: function() {} + do() {}, + undo() {}, }); - expect(typeof StyleDictionaryExtended.action['scss'].undo).toBe('function'); + expect(typeof StyleDictionaryExtended.action.scss.undo).toBe('function'); }); it('should properly pass the registered format to instances', () => { - var SDE2 = StyleDictionaryExtended.extend({}); - expect(typeof SDE2.action['scss'].do).toBe('function'); + const SDE2 = StyleDictionaryExtended.extend({}); + expect(typeof SDE2.action.scss.do).toBe('function'); }); - }); }); diff --git a/__tests__/register/format.test.js b/__tests__/register/format.test.js index 282b4a050..207bfdf99 100644 --- a/__tests__/register/format.test.js +++ b/__tests__/register/format.test.js @@ -11,37 +11,37 @@ * and limitations under the License. */ -var StyleDictionary = require('../../index'); -var StyleDictionaryExtended = StyleDictionary.extend({}); +const StyleDictionary = require('../../index'); + +const StyleDictionaryExtended = StyleDictionary.extend({}); describe('register', () => { describe('format', () => { - it('should error if name is not a string', () => { expect( StyleDictionaryExtended.registerFormat.bind(null, { - formatter: function() {} + formatter() {}, }) ).toThrow('transform name must be a string'); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: 1, - formatter: function() {} + formatter() {}, }) ).toThrow('transform name must be a string'); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: [], - formatter: function() {} + formatter() {}, }) ); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: {}, - formatter: function() {} + formatter() {}, }) ).toThrow('transform name must be a string'); }); @@ -49,35 +49,35 @@ describe('register', () => { it('should error if formatter is not a function', () => { expect( StyleDictionaryExtended.registerFormat.bind(null, { - name: 'test' + name: 'test', }) ).toThrow('format formatter must be a function'); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: 'test', - formatter: 1 + formatter: 1, }) ).toThrow('format formatter must be a function'); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: 'test', - formatter: 'name' + formatter: 'name', }) ).toThrow('format formatter must be a function'); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: 'test', - formatter: [] + formatter: [], }) ).toThrow('format formatter must be a function'); expect( StyleDictionaryExtended.registerFormat.bind(null, { name: 'test', - formatter: {} + formatter: {}, }) ).toThrow('format formatter must be a function'); }); @@ -85,15 +85,14 @@ describe('register', () => { it('should work if name and formatter are good', () => { StyleDictionaryExtended.registerFormat({ name: 'scss', - formatter: function() {} + formatter() {}, }); - expect(typeof StyleDictionaryExtended.format['scss']).toBe('function'); + expect(typeof StyleDictionaryExtended.format.scss).toBe('function'); }); it('should properly pass the registered format to instances', () => { - var SDE2 = StyleDictionaryExtended.extend({}); - expect(typeof SDE2.format['scss']).toBe('function'); + const SDE2 = StyleDictionaryExtended.extend({}); + expect(typeof SDE2.format.scss).toBe('function'); }); - }); }); diff --git a/__tests__/register/template.test.js b/__tests__/register/template.test.js index c659a5ead..520d08791 100644 --- a/__tests__/register/template.test.js +++ b/__tests__/register/template.test.js @@ -11,17 +11,12 @@ * and limitations under the License. */ -var assert = require('chai').assert; -var StyleDictionary = require('../../index').extend({}); +const { assert } = require('chai'); +const StyleDictionary = require('../../index').extend({}); - -describe('registerTemplate', function() { - it('should error if name is not a string', function() { - assert.throws( - StyleDictionary.registerTemplate.bind(null, {}), - Error, - /Template name must be a string:/ - ); +describe('registerTemplate', () => { + it('should error if name is not a string', () => { + assert.throws(StyleDictionary.registerTemplate.bind(null, {}), Error, /Template name must be a string:/); assert.throws( StyleDictionary.registerTemplate.bind(null, { @@ -48,7 +43,7 @@ describe('registerTemplate', function() { ); }); - it('should error if path is not a string', function() { + it('should error if path is not a string', () => { assert.throws( StyleDictionary.registerTemplate.bind(null, { name: 'data', @@ -85,18 +80,18 @@ describe('registerTemplate', function() { ); }); - it('should error if path is not a file', function() { + it('should error if path is not a file', () => { assert.throws( StyleDictionary.registerTemplate.bind(null, { name: 'data', template: 'non_existent_file', }), Error, - /Can\'t find template: / + /Can't find template: / ); }); - it('should return StyleDictionary', function() { + it('should return StyleDictionary', () => { assert( StyleDictionary.registerTemplate.bind(null, { name: 'data', diff --git a/__tests__/register/transform.test.js b/__tests__/register/transform.test.js index c3364e870..5950c8d41 100644 --- a/__tests__/register/transform.test.js +++ b/__tests__/register/transform.test.js @@ -11,16 +11,16 @@ * and limitations under the License. */ -var StyleDictionary = require('../../index'); -var StyleDictionaryExtended = StyleDictionary.extend({}); +const StyleDictionary = require('../../index'); + +const StyleDictionaryExtended = StyleDictionary.extend({}); describe('register', () => { describe('transform', () => { - it('should error if type is not a string', () => { expect( StyleDictionaryExtended.registerTransform.bind(null, { - type: 3 + type: 3, }) ).toThrow('type must be a string'); }); @@ -28,7 +28,7 @@ describe('register', () => { it('should error if type is not a valid type', () => { expect( StyleDictionaryExtended.registerTransform.bind(null, { - type: 'foo' + type: 'foo', }) ).toThrow('foo type is not one of: name, value, attribute'); }); @@ -36,7 +36,7 @@ describe('register', () => { it('should error if name is not a string', () => { expect( StyleDictionaryExtended.registerTransform.bind(null, { - type: 'name' + type: 'name', }) ).toThrow('name must be a string'); }); @@ -46,7 +46,7 @@ describe('register', () => { StyleDictionaryExtended.registerTransform.bind(null, { type: 'name', name: 'name', - matcher: 'foo' + matcher: 'foo', }) ).toThrow('matcher must be a function'); }); @@ -56,8 +56,10 @@ describe('register', () => { StyleDictionaryExtended.registerTransform.bind(null, { type: 'name', name: 'name', - matcher: function() { return true; }, - transformer: 'foo' + matcher() { + return true; + }, + transformer: 'foo', }) ).toThrow('transformer must be a function'); }); @@ -66,8 +68,12 @@ describe('register', () => { StyleDictionaryExtended.registerTransform({ type: 'name', name: 'foo', - matcher: function() { return true; }, - transformer: function() { return true; } + matcher() { + return true; + }, + transformer() { + return true; + }, }); expect(typeof StyleDictionaryExtended.transform.foo).toBe('object'); expect(StyleDictionaryExtended).toHaveProperty('transform.foo.type', 'name'); @@ -75,14 +81,12 @@ describe('register', () => { expect(typeof StyleDictionaryExtended.transform.foo.transformer).toBe('function'); }); - it('should properly pass the registered transform to instances', () => { - var SDE2 = StyleDictionaryExtended.extend({}); + const SDE2 = StyleDictionaryExtended.extend({}); expect(typeof SDE2.transform.foo).toBe('object'); expect(SDE2).toHaveProperty('transform.foo.type', 'name'); expect(typeof SDE2.transform.foo.matcher).toBe('function'); expect(typeof SDE2.transform.foo.transformer).toBe('function'); }); - }); }); diff --git a/__tests__/register/transformGroup.test.js b/__tests__/register/transformGroup.test.js index 27e05ccbf..bdee5d701 100644 --- a/__tests__/register/transformGroup.test.js +++ b/__tests__/register/transformGroup.test.js @@ -11,42 +11,43 @@ * and limitations under the License. */ -var StyleDictionary = require('../../index'); -var StyleDictionaryExtended = StyleDictionary.extend({}); +const StyleDictionary = require('../../index'); + +const StyleDictionaryExtended = StyleDictionary.extend({}); describe('register/transformGroup', () => { it('should error if name is not a string', () => { expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { - transforms: ['foo'] + transforms: ['foo'], }) ).toThrow('transform name must be a string'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { name: 1, - transforms: ['foo'] + transforms: ['foo'], }) ).toThrow('transform name must be a string'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { name: [], - transforms: ['foo'] + transforms: ['foo'], }) ).toThrow('transform name must be a string'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { name: {}, - transforms: ['foo'] + transforms: ['foo'], }) ).toThrow('transform name must be a string'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { - name: function() {}, - transforms: ['foo'] + name() {}, + transforms: ['foo'], }) ).toThrow('transform name must be a string'); }); @@ -54,38 +55,37 @@ describe('register/transformGroup', () => { it('should error if transforms isnt an array', () => { expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { - name: 'foo' + name: 'foo', }) ).toThrow('transforms must be an array of registered value transforms'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { name: 'foo', - transforms: 'foo' + transforms: 'foo', }) ).toThrow('transforms must be an array of registered value transforms'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { name: 'foo', - transforms: {} + transforms: {}, }) ).toThrow('transforms must be an array of registered value transforms'); expect( StyleDictionaryExtended.registerTransformGroup.bind(null, { name: 'foo', - transforms: function() {} + transforms() {}, }) ).toThrow('transforms must be an array of registered value transforms'); }); it('should error if transforms arent registered', () => { expect( - StyleDictionaryExtended.registerTransformGroup.bind(StyleDictionary, - { + StyleDictionaryExtended.registerTransformGroup.bind(StyleDictionary, { name: 'foo', - transforms: ['foo'] + transforms: ['foo'], }) ).toThrow('transforms must be an array of registered value transforms'); }); @@ -93,7 +93,7 @@ describe('register/transformGroup', () => { it('should work if everything is good', () => { StyleDictionaryExtended.registerTransformGroup({ name: 'foo', - transforms: ['size/px'] + transforms: ['size/px'], }); expect(Array.isArray(StyleDictionaryExtended.transformGroup.foo)).toBeTruthy(); expect(typeof StyleDictionaryExtended.transformGroup.foo[0]).toBe('string'); @@ -101,7 +101,7 @@ describe('register/transformGroup', () => { }); it('should properly pass the registered format to instances', () => { - var SDE2 = StyleDictionaryExtended.extend({}); + const SDE2 = StyleDictionaryExtended.extend({}); expect(Array.isArray(SDE2.transformGroup.foo)).toBeTruthy(); expect(typeof SDE2.transformGroup.foo[0]).toBe('string'); expect(SDE2.transformGroup.foo[0]).toBe('size/px'); diff --git a/__tests__/transform/object.test.js b/__tests__/transform/object.test.js index af70b60b5..ba7615856 100644 --- a/__tests__/transform/object.test.js +++ b/__tests__/transform/object.test.js @@ -11,81 +11,81 @@ * and limitations under the License. */ -var transformObject = require('../../lib/transform/object'); +const transformObject = require('../../lib/transform/object'); const options = { transforms: [ { type: 'attribute', - transformer: function() { - return {foo: 'bar'} - } - }, { + transformer() { + return { foo: 'bar' }; + }, + }, + { type: 'attribute', - transformer: function() { - return {bar: 'foo'} - } - }, { + transformer() { + return { bar: 'foo' }; + }, + }, + { type: 'name', - matcher: function(prop) { - return prop.attributes.foo === 'bar'; + matcher({ attributes }) { + return attributes.foo === 'bar'; + }, + transformer() { + return 'transformer result'; }, - transformer: function() { - return "transformer result"; - } - } - ] + }, + ], }; describe('transform', () => { describe('object', () => { it('does not crash when called without parameters', () => { expect(transformObject()).toEqual({}); - }) + }); it('returns expected result when called with an object without value property', () => { const objectToTransform = { - "color": "#FFFF00" + color: '#FFFF00', }; const expected = { - "color": "#FFFF00" + color: '#FFFF00', }; const actual = transformObject(objectToTransform, options); expect(actual).toEqual(expected); - }) + }); it('returns expected result when called with an with value leaf', () => { const objectToTransform = { - "font": { - "base": { - "value": "16", - "comment": "the base size of the font" - } - } + font: { + base: { + value: '16', + comment: 'the base size of the font', + }, + }, }; const expected = { - "font": { - "base": { - "attributes": {"bar": "foo", "foo": "bar"}, - "comment": "the base size of the font", - "name": "transformer result", - "original": - { - "comment": "the base size of the font", - "value": "16" + font: { + base: { + attributes: { bar: 'foo', foo: 'bar' }, + comment: 'the base size of the font', + name: 'transformer result', + original: { + comment: 'the base size of the font', + value: '16', }, - "path": ["font", "base"], - "value": "16" - } - } + path: ['font', 'base'], + value: '16', + }, + }, }; const actual = transformObject(objectToTransform, options); expect(actual).toEqual(expected); - }) - + }); }); }); diff --git a/__tests__/transform/property.test.js b/__tests__/transform/property.test.js index 7b3009f49..d53dbf2ef 100644 --- a/__tests__/transform/property.test.js +++ b/__tests__/transform/property.test.js @@ -11,35 +11,40 @@ * and limitations under the License. */ -var property = require('../../lib/transform/property'); +const property = require('../../lib/transform/property'); -var options = { +const options = { transforms: [ { type: 'attribute', - transformer: function() { + transformer() { return { - foo: 'bar' - } - } - },{ + foo: 'bar', + }; + }, + }, + { type: 'attribute', - transformer: function() { - return {bar: 'foo'} - } - },{ + transformer() { + return { bar: 'foo' }; + }, + }, + { type: 'name', - matcher: function(prop) { return prop.attributes.foo === 'bar'; }, - transformer: function() { return "hello"; } - } - ] + matcher({ attributes }) { + return attributes.foo === 'bar'; + }, + transformer() { + return 'hello'; + }, + }, + ], }; describe('transform', () => { describe('property', () => { - it('should work', () => { - var test = property({attributes:{baz:'blah'}}, options); + const test = property({ attributes: { baz: 'blah' } }, options); expect(test).toHaveProperty('attributes.bar', 'foo'); expect(test).toHaveProperty('name', 'hello'); }); diff --git a/__tests__/transform/propertySetup.test.js b/__tests__/transform/propertySetup.test.js index aabc43abe..b7e45f850 100644 --- a/__tests__/transform/propertySetup.test.js +++ b/__tests__/transform/propertySetup.test.js @@ -11,36 +11,24 @@ * and limitations under the License. */ -var propertySetup = require('../../lib/transform/propertySetup'); +const propertySetup = require('../../lib/transform/propertySetup'); describe('transform', () => { describe('propertySetup', () => { - it('should error if property is not an object', () => { - expect( - propertySetup.bind(null, null, 'foo', []) - ).toThrow('Property object must be an object'); + expect(propertySetup.bind(null, null, 'foo', [])).toThrow('Property object must be an object'); }); it('should error if name in not a string', () => { - expect( - propertySetup.bind(null, {}, null, []) - ).toThrow('Name must be a string'); + expect(propertySetup.bind(null, {}, null, [])).toThrow('Name must be a string'); }); it('should error path is not an array', () => { - expect( - propertySetup.bind(null, {}, 'name', null) - ).toThrow('Path must be an array'); + expect(propertySetup.bind(null, {}, 'name', null)).toThrow('Path must be an array'); }); - it('should work if all the args are proper', () => { - var test = propertySetup( - {value: "#fff"}, - "white", - ["color","base"] - ); + const test = propertySetup({ value: '#fff' }, 'white', ['color', 'base']); expect(typeof test).toBe('object'); expect(test); expect(test).toHaveProperty('value'); @@ -49,45 +37,27 @@ describe('transform', () => { expect(test).toHaveProperty('path'); }); - it('should not do anything and return the property if it has been setup previously', () => { - var original = {value: "#fff", original:{}}; - var test = propertySetup( - original, - "white", - ["color","base"] - ); + const original = { value: '#fff', original: {} }; + const test = propertySetup(original, 'white', ['color', 'base']); expect(test).toMatchObject(original); }); it('should use attributes if already set', () => { - var attributes = {"foo":"bar"}; - var test = propertySetup( - {value:"#fff", attributes:attributes}, - "white", - ["color","base"] - ); + const attributes = { foo: 'bar' }; + const test = propertySetup({ value: '#fff', attributes }, 'white', ['color', 'base']); expect(test.attributes).toMatchObject(attributes); }); it('should use the name on the property if set', () => { - var name = "name"; - var test = propertySetup( - {value:"#fff", name:name}, - 'white', - ["color","base"] - ); + const name = 'name'; + const test = propertySetup({ value: '#fff', name }, 'white', ['color', 'base']); expect(test).toHaveProperty('name', name); }); it('should use the name passed in if not set on the property', () => { - var test = propertySetup( - {value:"#fff"}, - 'white', - ["color","base"] - ); + const test = propertySetup({ value: '#fff' }, 'white', ['color', 'base']); expect(test).toHaveProperty('name', 'white'); }); - }); }); diff --git a/__tests__/utils/combineJSON.test.js b/__tests__/utils/combineJSON.test.js index f143e2f22..c0058c66e 100644 --- a/__tests__/utils/combineJSON.test.js +++ b/__tests__/utils/combineJSON.test.js @@ -11,55 +11,52 @@ * and limitations under the License. */ -var combineJSON = require('../../lib/utils/combineJSON'); -var path = require('path'); +const path = require('path'); +const combineJSON = require('../../lib/utils/combineJSON'); describe('utils', () => { describe('combineJSON', () => { - it('should return an object', () => { - var test = combineJSON(["__tests__/__json_files/*.json"]); - expect(typeof test).toBe('object') + const test = combineJSON(['__tests__/__json_files/*.json']); + expect(typeof test).toBe('object'); }); it('should handle wildcards', () => { - var test = combineJSON(["__tests__/__json_files/*.json"]); - expect(typeof test).toBe('object') + const test = combineJSON(['__tests__/__json_files/*.json']); + expect(typeof test).toBe('object'); }); it('should handle js modules that export objects', () => { - var absPath = path.join(process.cwd(), 'test', 'json_files', '*.js'); - var relativePath = '__tests__/__json_files/*.js'; - var test = combineJSON([absPath, relativePath]); - expect(typeof test).toBe('object') + const absPath = path.join(process.cwd(), 'test', 'json_files', '*.js'); + const relativePath = '__tests__/__json_files/*.js'; + const test = combineJSON([absPath, relativePath]); + expect(typeof test).toBe('object'); }); it('should do a deep merge', () => { - var test = combineJSON(["__tests__/__json_files/shallow/*.json"], true); + const test = combineJSON(['__tests__/__json_files/shallow/*.json'], true); expect(test).toHaveProperty('a', 2); - expect(test.b).toMatchObject({"a":1, "c":2}) + expect(test.b).toMatchObject({ a: 1, c: 2 }); expect(test).toHaveProperty('d.e.f.g', 1); expect(test).toHaveProperty('d.e.f.h', 2); }); it('should do a shallow merge', () => { - var test = combineJSON(["__tests__/__json_files/shallow/*.json"]); + const test = combineJSON(['__tests__/__json_files/shallow/*.json']); expect(test).toHaveProperty('a', 2); - expect(test.b).toMatchObject({"c":2}); - expect(test).toHaveProperty('c', [3,4]); + expect(test.b).toMatchObject({ c: 2 }); + expect(test).toHaveProperty('c', [3, 4]); expect(test).not.toHaveProperty('d.e.f.g'); expect(test).toHaveProperty('d.e.f.h', 2); }); it('should fail on invalid JSON', () => { - expect( - combineJSON.bind(null, ["__tests__/__json_files/broken/*.json"], true) - ).toThrow(/Failed to load or parse/); + expect(combineJSON.bind(null, ['__tests__/__json_files/broken/*.json'], true)).toThrow(/Failed to load or parse/); }); it('should fail if there is a collision and it is passed a collision function', () => { expect( - combineJSON.bind(null, ["__tests__/__json_files/shallow/*.json"], true, function Collision(opts) { + combineJSON.bind(null, ['__tests__/__json_files/shallow/*.json'], true, (opts) => { expect(opts).toHaveProperty('key', 'a'); expect(opts.target[opts.key]).toBe(1); expect(opts.copy[opts.key]).toBe(2); @@ -69,7 +66,7 @@ describe('utils', () => { }); it('should support json5', () => { - var test = combineJSON(["__tests__/__json_files/shallow/*.json5"]); + const test = combineJSON(['__tests__/__json_files/shallow/*.json5']); expect(test).toHaveProperty('json5A', 5); expect(test.d).toHaveProperty('json5e', 1); }); diff --git a/__tests__/utils/convertToBase64.test.js b/__tests__/utils/convertToBase64.test.js index 13d5ad122..52e2b166f 100644 --- a/__tests__/utils/convertToBase64.test.js +++ b/__tests__/utils/convertToBase64.test.js @@ -11,26 +11,18 @@ * and limitations under the License. */ -var convertToBase64 = require('../../lib/utils/convertToBase64.js'); +const convertToBase64 = require('../../lib/utils/convertToBase64.js'); describe('utils', () => { describe('convertToBase64', () => { it('should error if filePath isnt a string', () => { - expect( - convertToBase64.bind(null) - ).toThrow('filePath name must be a string'); - expect( - convertToBase64.bind(null, []) - ).toThrow('filePath name must be a string'); - expect( - convertToBase64.bind(null, {}) - ).toThrow('filePath name must be a string'); + expect(convertToBase64.bind(null)).toThrow('filePath name must be a string'); + expect(convertToBase64.bind(null, [])).toThrow('filePath name must be a string'); + expect(convertToBase64.bind(null, {})).toThrow('filePath name must be a string'); }); it('should error if filePath isnt a file', () => { - expect( - convertToBase64.bind(null, 'foo') - ).toThrow("ENOENT: no such file or directory, open 'foo'"); + expect(convertToBase64.bind(null, 'foo')).toThrow("ENOENT: no such file or directory, open 'foo'"); }); it('should return a string', () => { diff --git a/__tests__/utils/deepExtend.test.js b/__tests__/utils/deepExtend.test.js index d2bde878e..534ec9372 100644 --- a/__tests__/utils/deepExtend.test.js +++ b/__tests__/utils/deepExtend.test.js @@ -11,45 +11,44 @@ * and limitations under the License. */ -var deepExtend = require('../../lib/utils/deepExtend'); +const deepExtend = require('../../lib/utils/deepExtend'); describe('utils', () => { describe('deepExtend', () => { - it('should return an object', () => { - var test = deepExtend(); - expect(typeof test).toBe('object') + const test = deepExtend(); + expect(typeof test).toBe('object'); }); it('should override properties from right to left', () => { - var test = deepExtend([{foo:'bar'}, {foo:'baz'}]); + const test = deepExtend([{ foo: 'bar' }, { foo: 'baz' }]); expect(test).toHaveProperty('foo', 'baz'); - var test2 = deepExtend([{foo:'bar'}, {foo:'baz'}, {foo:'blah'}]); + const test2 = deepExtend([{ foo: 'bar' }, { foo: 'baz' }, { foo: 'blah' }]); expect(test2).toHaveProperty('foo', 'blah'); }); it('should override nested properties', () => { - var test = deepExtend([{foo: {foo:'bar'}}, {foo: {foo:'baz'}}]); + const test = deepExtend([{ foo: { foo: 'bar' } }, { foo: { foo: 'baz' } }]); expect(test).toHaveProperty('foo.foo', 'baz'); - var test2 = deepExtend([{foo:{foo:'bar'}}, {foo:{foo:'baz'}}, {foo:{foo:'blah'}}]); + const test2 = deepExtend([{ foo: { foo: 'bar' } }, { foo: { foo: 'baz' } }, { foo: { foo: 'blah' } }]); expect(test2).toHaveProperty('foo.foo', 'blah'); }); it('should override nested properties', () => { - var test = deepExtend([{foo: {bar:'bar'}}, {foo: {baz:'baz'}}]); + const test = deepExtend([{ foo: { bar: 'bar' } }, { foo: { baz: 'baz' } }]); expect(test).toHaveProperty('foo.baz', 'baz'); expect(test).toHaveProperty('foo.bar', 'bar'); - var test2 = deepExtend([{foo:{bar:'bar'}}, {foo:{baz:'baz'}}, {foo:{blah:'blah'}}]); + const test2 = deepExtend([{ foo: { bar: 'bar' } }, { foo: { baz: 'baz' } }, { foo: { blah: 'blah' } }]); expect(test2).toHaveProperty('foo.baz', 'baz'); expect(test2).toHaveProperty('foo.bar', 'bar'); expect(test2).toHaveProperty('foo.blah', 'blah'); }); - it('shouldn\'t fail loudly if it is a normal deep extend', () => { - var test = deepExtend([{foo: {bar:'bar'}}, {foo: {baz:'baz'}}], function() {}); + it("shouldn't fail loudly if it is a normal deep extend", () => { + const test = deepExtend([{ foo: { bar: 'bar' } }, { foo: { baz: 'baz' } }], () => {}); expect(test).toHaveProperty('foo.baz', 'baz'); expect(test).toHaveProperty('foo.bar', 'bar'); }); @@ -57,14 +56,14 @@ describe('utils', () => { describe('collision detection', () => { it('should call the collision function if a collision happens', () => { expect( - deepExtend.bind(null, [{foo: {bar:'bar'}}, {foo: {bar:'baz'}}], function() { + deepExtend.bind(null, [{ foo: { bar: 'bar' } }, { foo: { bar: 'baz' } }], () => { throw new Error('danger danger. high voltage.'); }) ).toThrow('danger danger. high voltage.'); }); it('the collision function should have the proper arguments', () => { - var test = deepExtend([{foo: {bar:'bar'}}, {foo: {bar:'baz'}}], function(opts) { + const test = deepExtend([{ foo: { bar: 'bar' } }, { foo: { bar: 'baz' } }], opts => { expect(opts).toHaveProperty('target.bar', 'bar'); expect(opts).toHaveProperty('copy.bar', 'baz'); expect(opts.path[0]).toBe('foo'); @@ -73,6 +72,5 @@ describe('utils', () => { expect(test).toHaveProperty('foo.bar', 'baz'); }); }); - }); }); diff --git a/__tests__/utils/flattenProperties.test.js b/__tests__/utils/flattenProperties.test.js index a81ce0af6..97efc9cba 100644 --- a/__tests__/utils/flattenProperties.test.js +++ b/__tests__/utils/flattenProperties.test.js @@ -11,64 +11,57 @@ * and limitations under the License. */ -var flattenProperties = require('../../lib/utils/flattenProperties'); -var _ = require('lodash'); +const _ = require('lodash'); +const flattenProperties = require('../../lib/utils/flattenProperties'); describe('utils', () => { describe('flattenProperties', () => { - it('should return an empty array', () => { - var ret = flattenProperties({}); + const ret = flattenProperties({}); expect(ret).toEqual([]); }); it('should return the same array', () => { - var to_ret = []; - var ret = flattenProperties({}, to_ret); + const toRet = []; + const ret = flattenProperties({}, toRet); expect(ret).toBe(ret); }); it('should return leaf node values as an array', () => { - var properties = { - 'black': { - 'value': '#000000' + const properties = { + black: { + value: '#000000', + }, + white: { + value: '#FFFFFF', }, - 'white': { - 'value': '#FFFFFF' - } }; - var expected_ret = [ - properties.black, - properties.white - ]; + const expectedRet = [properties.black, properties.white]; - var sortedExpectedRet = _.sortBy(expected_ret, ['value']); - var ret = flattenProperties(properties); - var sortedRet = _.sortBy(ret, ['value']); + const sortedExpectedRet = _.sortBy(expectedRet, ['value']); + const ret = flattenProperties(properties); + const sortedRet = _.sortBy(ret, ['value']); expect(sortedRet).toEqual(sortedExpectedRet); }); it('should return nested leaf node values as an array', () => { - var properties = { - 'color': { - 'black': { - 'value': '#000000' + const properties = { + color: { + black: { + value: '#000000', }, - 'white': { - 'value': '#FFFFFF' - } - } + white: { + value: '#FFFFFF', + }, + }, }; - var expected_ret = [ - properties.color.black, - properties.color.white - ]; + const expectedRet = [properties.color.black, properties.color.white]; - var sortedExpectedRet = _.sortBy(expected_ret, ['value']); - var ret = flattenProperties(properties); - var sortedRet = _.sortBy(ret, ['value']); + const sortedExpectedRet = _.sortBy(expectedRet, ['value']); + const ret = flattenProperties(properties); + const sortedRet = _.sortBy(ret, ['value']); expect(sortedRet).toEqual(sortedExpectedRet); }); }); diff --git a/__tests__/utils/resolveObject.test.js b/__tests__/utils/resolveObject.test.js index c07d28323..eacca995a 100644 --- a/__tests__/utils/resolveObject.test.js +++ b/__tests__/utils/resolveObject.test.js @@ -11,52 +11,45 @@ * and limitations under the License. */ -var resolveObject = require('../../lib/utils/resolveObject'); -var helpers = require('../__helpers'); +const resolveObject = require('../../lib/utils/resolveObject'); +const helpers = require('../__helpers'); describe('utils', () => { describe('resolveObject', () => { - it('should error on non-objects', () => { - expect( - resolveObject.bind(null), - ).toThrow('Please pass an object in'); - expect( - resolveObject.bind(null, 'foo'), - ).toThrow('Please pass an object in'); - expect( - resolveObject.bind(null, 0), - ).toThrow('Please pass an object in'); + expect(resolveObject.bind(null)).toThrow('Please pass an object in'); + expect(resolveObject.bind(null, 'foo')).toThrow('Please pass an object in'); + expect(resolveObject.bind(null, 0)).toThrow('Please pass an object in'); }); it('should not mutate the original object', () => { - var original = helpers.fileToJSON(__dirname + '/../__json_files/nested_references.json'); - var test = resolveObject( original ); + const original = helpers.fileToJSON(`${__dirname}/../__json_files/nested_references.json`); + const test = resolveObject(original); expect(original).toHaveProperty('a.b.d', '{e.f.g}'); expect(test).toHaveProperty('a.b.d', 2); }); it('should do simple references', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/simple.json') ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/simple.json`)); expect(test).toHaveProperty('bar', 'bar'); }); it('should do nested references', () => { - var obj = helpers.fileToJSON(__dirname + '/../__json_files/nested_references.json'); - var test = resolveObject( obj ); + const obj = helpers.fileToJSON(`${__dirname}/../__json_files/nested_references.json`); + const test = resolveObject(obj); expect(test).toHaveProperty('i', 2); expect(test).toHaveProperty('a.b.d', 2); expect(test).toHaveProperty('e.f.h', 1); }); it('should handle nested pointers', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/nested_pointers.json') ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/nested_pointers.json`)); expect(test).toHaveProperty('b', 1); expect(test).toHaveProperty('c', 1); }); it('should handle deep nested pointers', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/nested_pointers_2.json') ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/nested_pointers_2.json`)); expect(test).toHaveProperty('a', 1); expect(test).toHaveProperty('b', 1); expect(test).toHaveProperty('c', 1); @@ -67,19 +60,18 @@ describe('utils', () => { }); it('should handle deep nested pointers with string interpolation', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/nested_pointers_3.json') ); - expect(test).toHaveProperty('a', 'foo bon bee bae boo bla baz bar'); - expect(test).toHaveProperty('b', 'foo bon bee bae boo bla baz'); - expect(test).toHaveProperty('c', 'foo bon bee bae boo bla'); - expect(test).toHaveProperty('d', 'foo bon bee bae boo'); - expect(test).toHaveProperty('e', 'foo bon bee bae'); - expect(test).toHaveProperty('f', 'foo bon bee'); - expect(test).toHaveProperty('g', 'foo bon'); - } - ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/nested_pointers_3.json`)); + expect(test).toHaveProperty('a', 'foo bon bee bae boo bla baz bar'); + expect(test).toHaveProperty('b', 'foo bon bee bae boo bla baz'); + expect(test).toHaveProperty('c', 'foo bon bee bae boo bla'); + expect(test).toHaveProperty('d', 'foo bon bee bae boo'); + expect(test).toHaveProperty('e', 'foo bon bee bae'); + expect(test).toHaveProperty('f', 'foo bon bee'); + expect(test).toHaveProperty('g', 'foo bon'); + }); it('should handle deep nested pointers and nested references', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/nested_pointers_4.json') ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/nested_pointers_4.json`)); expect(test).toHaveProperty('a.a.a', 1); expect(test).toHaveProperty('b.b.b', 1); expect(test).toHaveProperty('c.c.c', 1); @@ -89,9 +81,8 @@ describe('utils', () => { expect(test).toHaveProperty('g.g.g', 1); }); - it('should keep the type of the referenced property', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/reference_type.json') ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/reference_type.json`)); expect(test).toHaveProperty('d', 1); expect(typeof test.d).toBe('number'); expect(typeof test.e).toBe('object'); @@ -100,150 +91,152 @@ describe('utils', () => { }); it('should handle and evaluate items in an array', () => { - var test = resolveObject( helpers.fileToJSON(__dirname + '/../__json_files/array.json') ); + const test = resolveObject(helpers.fileToJSON(`${__dirname}/../__json_files/array.json`)); expect(test.d[0]).toBe(2); expect(test.d[1]).toBe(1); expect(test.e[0].a).toBe(1); expect(test.e[1].a).toBe(2); }); - it('should throw if pointers don\'t exist', () => { - expect( - resolveObject.bind( helpers.fileToJSON(__dirname + '/../__json_files/non_existent.json')) - ).toThrow(); + it("should throw if pointers don't exist", () => { + expect(resolveObject.bind(helpers.fileToJSON(`${__dirname}/../__json_files/non_existent.json`))).toThrow(); }); it('should gracefully handle circular references', () => { - expect( - resolveObject.bind(null, - helpers.fileToJSON(__dirname + '/../__json_files/circular.json') - ) - ).toThrow('Circular definition: a | d'); - expect( - resolveObject.bind(null, - helpers.fileToJSON(__dirname + '/../__json_files/circular_2.json') - ) - ).toThrow('Circular definition: a.b.c | d'); - expect( - resolveObject.bind(null, - helpers.fileToJSON(__dirname + '/../__json_files/circular_3.json') - ) - ).toThrow('Circular definition: a.b.c | d.e.f'); - expect( - resolveObject.bind(null, - helpers.fileToJSON(__dirname + '/../__json_files/circular_4.json') - ) - ).toThrow('Circular definition: a.b.c | g.h'); + expect(resolveObject.bind(null, helpers.fileToJSON(`${__dirname}/../__json_files/circular.json`))).toThrow( + 'Circular definition: a | d' + ); + expect(resolveObject.bind(null, helpers.fileToJSON(`${__dirname}/../__json_files/circular_2.json`))).toThrow( + 'Circular definition: a.b.c | d' + ); + expect(resolveObject.bind(null, helpers.fileToJSON(`${__dirname}/../__json_files/circular_3.json`))).toThrow( + 'Circular definition: a.b.c | d.e.f' + ); + expect(resolveObject.bind(null, helpers.fileToJSON(`${__dirname}/../__json_files/circular_4.json`))).toThrow( + 'Circular definition: a.b.c | g.h' + ); }); describe('ignoreKeys', () => { it('should handle default value of original', () => { - var test = resolveObject({ + const test = resolveObject({ foo: { value: 'bar' }, bar: { value: '{foo.value}', - original: '{foo.value}' - } + original: '{foo.value}', + }, }); - expect(test).toHaveProperty ('bar.original', '{foo.value}'); + expect(test).toHaveProperty('bar.original', '{foo.value}'); }); it('should handle any nested keys under the ignoreKey', () => { - var test = resolveObject({ + const test = resolveObject({ foo: { value: 'bar' }, bar: { value: '{foo.value}', original: { value: '{foo.value}', foo: { - bar: '{foo.value}' - } - } - } + bar: '{foo.value}', + }, + }, + }, }); - expect(test).toHaveProperty ('bar.original.value', '{foo.value}'); - expect(test).toHaveProperty ('bar.original.foo.bar', '{foo.value}'); + expect(test).toHaveProperty('bar.original.value', '{foo.value}'); + expect(test).toHaveProperty('bar.original.foo.bar', '{foo.value}'); }); it('should handle passing in custom ignoreKeys', () => { - var test = resolveObject({ - foo: { value: 'bar' }, - bar: { - value: '{foo.value}', - baz: '{foo.value}' + const test = resolveObject( + { + foo: { value: 'bar' }, + bar: { + value: '{foo.value}', + baz: '{foo.value}', + }, + }, + { + ignoreKeys: ['baz'], } - }, { - ignoreKeys: ['baz'] - }); - expect(test).toHaveProperty ('bar.baz', '{foo.value}'); + ); + expect(test).toHaveProperty('bar.baz', '{foo.value}'); }); it('should handle multiple keys', () => { - var test = resolveObject({ - foo: { value: 'bar' }, - bar: { - value: '{foo.value}', - original: '{foo.value}', - baz: '{foo.value}' + const test = resolveObject( + { + foo: { value: 'bar' }, + bar: { + value: '{foo.value}', + original: '{foo.value}', + baz: '{foo.value}', + }, + }, + { + ignoreKeys: ['baz', 'original'], } - },{ - ignoreKeys: ['baz','original'] - }); - expect(test).toHaveProperty ('bar.original', '{foo.value}'); - expect(test).toHaveProperty ('bar.baz', '{foo.value}'); + ); + expect(test).toHaveProperty('bar.original', '{foo.value}'); + expect(test).toHaveProperty('bar.baz', '{foo.value}'); }); it('should not ignore anything if set to null or empty array', () => { - var test = resolveObject({ - foo: { value: 'bar' }, - bar: { - value: '{foo.value}', - original: '{foo.value}' + const test = resolveObject( + { + foo: { value: 'bar' }, + bar: { + value: '{foo.value}', + original: '{foo.value}', + }, + }, + { + ignoreKeys: [], } - },{ - ignoreKeys: [] - }); - expect(test).toHaveProperty ('bar.original', 'bar'); + ); + expect(test).toHaveProperty('bar.original', 'bar'); - var test2 = resolveObject({ - foo: { value: 'bar' }, - bar: { - value: '{foo.value}', - original: '{foo.value}' + const test2 = resolveObject( + { + foo: { value: 'bar' }, + bar: { + value: '{foo.value}', + original: '{foo.value}', + }, + }, + { + ignoreKeys: null, } - },{ - ignoreKeys: null - }); - expect(test2).toHaveProperty ('bar.original', 'bar'); + ); + expect(test2).toHaveProperty('bar.original', 'bar'); - var test3 = resolveObject({ - foo: { value: 'bar' }, - bar: { - value: '{foo.value}', - original: '{foo.value}' + const test3 = resolveObject( + { + foo: { value: 'bar' }, + bar: { + value: '{foo.value}', + original: '{foo.value}', + }, + }, + { + ignoreKeys: undefined, } - },{ - ignoreKeys: undefined - }); - expect(test3).toHaveProperty ('bar.original', 'bar'); + ); + expect(test3).toHaveProperty('bar.original', 'bar'); }); }); it('should handle spaces', () => { - var test = resolveObject({ + const test = resolveObject({ foo: { value: 'bar' }, - bar: { value: '{ foo.value }'} + bar: { value: '{ foo.value }' }, }); - expect(test).toHaveProperty ('foo.value', test.bar.value); + expect(test).toHaveProperty('foo.value', test.bar.value); }); it('should collect multiple reference errors', () => { expect( - resolveObject.bind(null, - helpers.fileToJSON(__dirname + '/../__json_files/multiple_reference_errors.json') - ) + resolveObject.bind(null, helpers.fileToJSON(`${__dirname}/../__json_files/multiple_reference_errors.json`)) ).toThrow('Failed due to 3 errors:'); }); - }); }); diff --git a/example/react/web/webpack.config.js b/example/react/web/webpack.config.js index 358eb4713..a5c49a7aa 100644 --- a/example/react/web/webpack.config.js +++ b/example/react/web/webpack.config.js @@ -12,54 +12,55 @@ const PATHS = { sass: path.join(__dirname, 'src/sass'), build: path.join(__dirname, 'build'), images: path.join(__dirname, 'src/images'), - assets: path.join(__dirname, 'src/assets') + assets: path.join(__dirname, 'src/assets'), }; const common = { entry: { app: PATHS.app, - styles: PATHS.styles + styles: PATHS.styles, }, output: { path: PATHS.build, - filename: '[name].[hash].js' + filename: '[name].[hash].js', }, - devtool: "eval-source-map", + devtool: 'eval-source-map', resolve: { - extensions: ['', '.js', '.jsx'] - }, - postcss: function (webpack) { - return [autoprefixer]; + extensions: ['', '.js', '.jsx'], }, + postcss: webpack => [autoprefixer], plugins: [ new HtmlWebpackPlugin({ title: 'Style Dictionary', - template: 'index.ejs' + template: 'index.ejs', }), new webpack.HotModuleReplacementPlugin({ - multiStep: true + multiStep: true, }), ], module: { loaders: [ { - test : /\.(jsx|js)?$/, - loader : 'babel-loader', - exclude: /node_modules/ - },{ + test: /\.(jsx|js)?$/, + loader: 'babel-loader', + exclude: /node_modules/, + }, + { test: /\.(jpg|png)$/, loader: 'url?limit=25000', - include: PATHS.images - },{ + include: PATHS.images, + }, + { test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'], - include: PATHS.sass - },{ + include: PATHS.sass, + }, + { test: /\.ttf$|\.eot$|\.woff$|\.woff2$/, loader: 'file-loader', - include: PATHS.app - } - ] + include: PATHS.app, + }, + ], }, devServer: { historyApiFallback: true, @@ -67,10 +68,10 @@ const common = { inline: true, stats: 'errors-only', host: 'localhost', - port: '8080' - } + port: '8080', + }, }; module.exports = validate(common, { - quiet: true + quiet: true, }); diff --git a/index.js b/index.js index 251b284fc..7d6c0221d 100644 --- a/index.js +++ b/index.js @@ -23,7 +23,8 @@ * StyleDictionary.buildAllPlatforms(); * ``` */ -var StyleDictionary = { +/* eslint-disable global-require */ +const StyleDictionary = { VERSION: require('./package.json').version, properties: {}, allProperties: [], diff --git a/lib/buildAllPlatforms.js b/lib/buildAllPlatforms.js index 6ede1efe0..ddba77704 100644 --- a/lib/buildAllPlatforms.js +++ b/lib/buildAllPlatforms.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * The only top-level method that needs to be called @@ -27,15 +27,10 @@ var _ = require('lodash'); * ``` */ function buildAllPlatforms() { - var self = this; - - _.forIn(this.options.platforms, function (platform, key) { - self.buildPlatform(key); - }); + _.forIn(this.options.platforms, (platform, key) => this.buildPlatform(key)); // For chaining return this; } - module.exports = buildAllPlatforms; diff --git a/lib/buildFile.js b/lib/buildFile.js index 10b4c6d22..12b9cec50 100644 --- a/lib/buildFile.js +++ b/lib/buildFile.js @@ -11,10 +11,11 @@ * and limitations under the License. */ -var path = require('path'), - fs = require('fs-extra'), - chalk = require('chalk'), - filterProperties = require('./filterProperties'); +var path = require('path'); + +var fs = require('fs-extra'); +var chalk = require('chalk'); +var filterProperties = require('./filterProperties'); /** * Takes the style property object and a format and returns a @@ -43,7 +44,7 @@ function buildFile(destination, format, platform, dictionary, filter) { fs.mkdirsSync(dirname); fs.writeFileSync(destination, format(filterProperties(dictionary, filter), platform)); - console.log(chalk.bold.green('✔︎') + ' ' + destination); + console.log(`${chalk.bold.green('✔︎')} ${destination}`); } diff --git a/lib/buildFiles.js b/lib/buildFiles.js index ec347a16f..230053d53 100644 --- a/lib/buildFiles.js +++ b/lib/buildFiles.js @@ -11,8 +11,9 @@ * and limitations under the License. */ -var _ = require('lodash'), - buildFile = require('./buildFile'); +var _ = require('lodash'); + +var buildFile = require('./buildFile'); /** * Takes a platform config object and a properties @@ -29,7 +30,7 @@ function buildFiles(dictionary, platform) { throw new Error('Build path must end in a trailing slash or you will get weird file names.') } - _.each(platform.files, function (file) { + _.each(platform.files, file => { if (file.template) { buildFile(file.destination, file.template.bind(file), platform, dictionary, file.filter); } else if (file.format) { diff --git a/lib/buildPlatform.js b/lib/buildPlatform.js index 739afbfde..66977ffd6 100644 --- a/lib/buildPlatform.js +++ b/lib/buildPlatform.js @@ -11,12 +11,13 @@ * and limitations under the License. */ -var flattenProperties = require('./utils/flattenProperties'), - transformConfig = require('./transform/config'), - buildFiles = require('./buildFiles'), - performActions = require('./performActions'), - _ = require('lodash'), - chalk = require('chalk'); +var flattenProperties = require('./utils/flattenProperties'); + +var transformConfig = require('./transform/config'); +var buildFiles = require('./buildFiles'); +var performActions = require('./performActions'); +var _ = require('lodash'); +var chalk = require('chalk'); /** * Takes a platform and performs all transforms to @@ -40,10 +41,10 @@ var flattenProperties = require('./utils/flattenProperties'), * ``` */ function buildPlatform(platform) { - console.log('\n' + platform); + console.log(`\n${platform}`); if (!this.options || !_.has(this.options.platforms, platform)) { - throw new Error('Platform ' + platform + ' doesn\'t exist'); + throw new Error(`Platform ${platform} doesn't exist`); } var properties; @@ -60,7 +61,7 @@ function buildPlatform(platform) { // This is the dictionary object we pass to the file // building and action methods. var dictionary = { - properties: properties, + properties, allProperties: flattenProperties( properties ) }; diff --git a/lib/cleanActions.js b/lib/cleanActions.js index 9f7ac2594..441dfe7ea 100644 --- a/lib/cleanActions.js +++ b/lib/cleanActions.js @@ -26,7 +26,7 @@ var _ = require('lodash'); */ function cleanActions(dictionary, platform) { if (platform.actions) { - _.each(platform.actions, function(action, i) { + _.each(platform.actions, (action, i) => { if (typeof action.undo === 'function') { action.undo(dictionary, platform); } diff --git a/lib/cleanAllPlatforms.js b/lib/cleanAllPlatforms.js index 3d6e07226..45600c3dd 100644 --- a/lib/cleanAllPlatforms.js +++ b/lib/cleanAllPlatforms.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * Does the reverse of [buildAllPlatforms](#buildAllPlatforms) by @@ -23,15 +23,10 @@ var _ = require('lodash'); * @returns {module:style-dictionary} */ function cleanAllPlatforms() { - var self = this; - - _.forIn(this.options.platforms, function (platform, key) { - self.cleanPlatform(key); - }); + _.forIn(this.options.platforms, (platform, key) => this.cleanPlatform(key)); // For chaining return this; } - module.exports = cleanAllPlatforms; diff --git a/lib/cleanDir.js b/lib/cleanDir.js index 26a5456ae..a71a8addc 100644 --- a/lib/cleanDir.js +++ b/lib/cleanDir.js @@ -11,9 +11,10 @@ * and limitations under the License. */ -var path = require('path'), - fs = require('fs-extra'), - chalk = require('chalk'); +var path = require('path'); + +var fs = require('fs-extra'); +var chalk = require('chalk'); /** @@ -27,14 +28,14 @@ var path = require('path'), * @param {Function} filter (unused) * @returns {null} */ -function cleanDir(destination, format, platform, dictionary, filter) { +function cleanDir(destination, format, {buildPath}, dictionary, filter) { if (!destination || typeof destination !== 'string') throw new Error('Please enter a valid destination'); // if there is a clean path, prepend the destination with it - if (platform.buildPath) { - destination = platform.buildPath + destination; + if (buildPath) { + destination = buildPath + destination; } var dirname = path.dirname(destination); @@ -42,7 +43,7 @@ function cleanDir(destination, format, platform, dictionary, filter) { while(dirname) { if(fs.existsSync(dirname)) { if (fs.readdirSync(dirname).length===0) { - console.log(chalk.bold.red('-') + ' ' + dirname); + console.log(`${chalk.bold.red('-')} ${dirname}`); fs.rmdirSync(dirname); } else { diff --git a/lib/cleanDirs.js b/lib/cleanDirs.js index a5e0b8b8f..bdf02540f 100644 --- a/lib/cleanDirs.js +++ b/lib/cleanDirs.js @@ -11,8 +11,9 @@ * and limitations under the License. */ -var _ = require('lodash'), - cleanDir = require('./cleanDir'); +var _ = require('lodash'); + +var cleanDir = require('./cleanDir'); /** * Takes a platform config object and a properties @@ -30,7 +31,7 @@ function cleanDirs(dictionary, platform) { } // while neither the template, format, or dictionary are used by clean file I'm passing them in for symmetry to buildFile - _.each(platform.files, function (file) { + _.each(platform.files, file => { if (file.template) { cleanDir(file.destination, file.template.bind(file), platform, dictionary); } else if (file.format) { diff --git a/lib/cleanFile.js b/lib/cleanFile.js index 0d1febeae..65be555c2 100644 --- a/lib/cleanFile.js +++ b/lib/cleanFile.js @@ -11,9 +11,10 @@ * and limitations under the License. */ -var path = require('path'), - fs = require('fs-extra'), - chalk = require('chalk'); +var path = require('path'); + +var fs = require('fs-extra'); +var chalk = require('chalk'); /** @@ -27,20 +28,20 @@ var path = require('path'), * @param {Function} filter (unused) * @returns {null} */ -function cleanFile(destination, format, platform, dictionary, filter) { +function cleanFile(destination, format, {buildPath}, dictionary, filter) { if (!destination || typeof destination !== 'string') throw new Error('Please enter a valid destination'); // if there is a clean path, prepend the destination with it - if (platform.buildPath) { - destination = platform.buildPath + destination; + if (buildPath) { + destination = buildPath + destination; } var dirname = path.dirname(destination); fs.unlinkSync(destination); - console.log(chalk.bold.red('-') + ' ' + destination); + console.log(`${chalk.bold.red('-')} ${destination}`); } diff --git a/lib/cleanFiles.js b/lib/cleanFiles.js index e9ec068a1..e0d419d34 100644 --- a/lib/cleanFiles.js +++ b/lib/cleanFiles.js @@ -11,8 +11,9 @@ * and limitations under the License. */ -var _ = require('lodash'), - cleanFile = require('./cleanFile'); +var _ = require('lodash'); + +var cleanFile = require('./cleanFile'); /** * Takes a platform config object and a properties @@ -30,7 +31,7 @@ function cleanFiles(dictionary, platform) { } // while neither the template, format, or dictionary are used by clean file I'm passing them in for symmetry to buildFile - _.each(platform.files, function (file) { + _.each(platform.files, file => { if (file.template) { cleanFile(file.destination, file.template.bind(file), platform, dictionary); } else if (file.format) { diff --git a/lib/cleanPlatform.js b/lib/cleanPlatform.js index fbaddae9b..55f7d5996 100644 --- a/lib/cleanPlatform.js +++ b/lib/cleanPlatform.js @@ -11,13 +11,14 @@ * and limitations under the License. */ -var _ = require('lodash'), - flattenProperties = require('./utils/flattenProperties'), - transformConfig = require('./transform/config'), - cleanFiles = require('./cleanFiles'), - cleanDirs = require('./cleanDirs'), - cleanActions = require('./cleanActions'), - chalk = require('chalk'); +var _ = require('lodash'); + +var flattenProperties = require('./utils/flattenProperties'); +var transformConfig = require('./transform/config'); +var cleanFiles = require('./cleanFiles'); +var cleanDirs = require('./cleanDirs'); +var cleanActions = require('./cleanActions'); +var chalk = require('chalk'); /** * Takes a platform and performs all transforms to @@ -30,10 +31,10 @@ var _ = require('lodash'), * @returns {module:style-dictionary} */ function cleanPlatform(platform) { - console.log('\n' + platform); + console.log(`\n${platform}`); if (!this.options || !_.has(this.options.platforms, platform)) { - throw new Error('Platform ' + platform + ' doesn\'t exist'); + throw new Error(`Platform ${platform} doesn't exist`); } var properties; @@ -50,7 +51,7 @@ function cleanPlatform(platform) { // This is the dictionary object we pass to the file // cleaning and action methods. var dictionary = { - properties: properties, + properties, allProperties: flattenProperties( properties ) }; diff --git a/lib/common/actions.js b/lib/common/actions.js index 6ba533f18..ff4d6a059 100644 --- a/lib/common/actions.js +++ b/lib/common/actions.js @@ -11,9 +11,9 @@ * and limitations under the License. */ -var _ = require('lodash'), - fs = require('fs-extra'), - chalk = require('chalk'); +const _ = require('lodash'); + +const fs = require('fs-extra'); /** * @namespace Actions @@ -26,21 +26,21 @@ module.exports = { * @memberof Actions */ 'android/copyImages': { - do: function(dictionary, config) { - var imagesDir = config.buildPath + 'android/main/res/drawable-'; - _.each(dictionary.allProperties, function(prop) { - if (prop.attributes.category === 'asset' && prop.attributes.type === 'image') { - var name = prop.path.slice(2, 4).join('_'); - fs.copySync(prop.value, imagesDir + prop.attributes.state + '/' + name + '.png'); + do({ allProperties }, { buildPath }) { + const imagesDir = `${buildPath}android/main/res/drawable-`; + _.each(allProperties, ({ attributes, path, value }) => { + if (attributes.category === 'asset' && attributes.type === 'image') { + const name = path.slice(2, 4).join('_'); + fs.copySync(value, `${imagesDir + attributes.state}/${name}.png`); } }); }, - undo: function(dictionary, config) { - var imagesDir = config.buildPath + 'android/main/res/drawable-'; - _.each(dictionary.allProperties, function(prop) { - if (prop.attributes.category === 'asset' && prop.attributes.type === 'image') { - var name = prop.path.slice(2, 4).join('_'); - fs.removeSync(imagesDir + prop.attributes.state + '/' + name + '.png'); + undo({ allProperties }, { buildPath }) { + const imagesDir = `${buildPath}android/main/res/drawable-`; + _.each(allProperties, ({ attributes, path }) => { + if (attributes.category === 'asset' && attributes.type === 'image') { + const name = path.slice(2, 4).join('_'); + fs.removeSync(`${imagesDir + attributes.state}/${name}.png`); } }); }, @@ -53,13 +53,13 @@ module.exports = { * @memberof Actions */ copy_assets: { - do: function(dictionary, config) { - console.log('Copying assets directory to ' + config.buildPath + 'assets'); - fs.copySync('assets', config.buildPath + 'assets'); + do(dictionary, { buildPath }) { + console.log(`Copying assets directory to ${buildPath}assets`); + fs.copySync('assets', `${buildPath}assets`); }, - undo: function(dictionary, config) { - console.log('Removing assets directory from ' + config.buildPath + 'assets'); - fs.removeSync(config.buildPath + 'assets'); + undo(dictionary, { buildPath }) { + console.log(`Removing assets directory from ${buildPath}assets`); + fs.removeSync(`${buildPath}assets`); }, }, }; diff --git a/lib/common/formats.js b/lib/common/formats.js index 55fb73111..8f1fec4e1 100644 --- a/lib/common/formats.js +++ b/lib/common/formats.js @@ -11,46 +11,41 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); function fileHeader(options) { - var to_ret = ''; + let toRet = ''; // for backward compatibility we need to have the user explicitly hide them - var showFileHeader = options ? options.showFileHeader : true; + const showFileHeader = options ? options.showFileHeader : true; if (showFileHeader) { - to_ret += '/**\n'; - to_ret += ' * Do not edit directly\n'; - to_ret += ' * Generated on ' + new Date().toUTCString() + '\n'; - to_ret += ' */\n\n'; + toRet += '/**\n'; + toRet += ' * Do not edit directly\n'; + toRet += ` * Generated on ${new Date().toUTCString()}\n`; + toRet += ' */\n\n'; } - return to_ret; + return toRet; } function variablesWithPrefix(prefix, properties) { - return _.map(properties, function(prop) { - var to_ret_prop = - prefix + prop.name + ': ' + (prop.attributes.category === 'asset' ? '"' + prop.value + '"' : prop.value) + ';'; + return _.map(properties, ({ name, attributes, value, comment }) => { + let toRetProp = `${prefix + name}: ${attributes.category === 'asset' ? `"${value}"` : value};`; - if (prop.comment) to_ret_prop = to_ret_prop.concat(' // ' + prop.comment); - return to_ret_prop; + if (comment) toRetProp = toRetProp.concat(` // ${comment}`); + return toRetProp; }) - .filter(function(strVal) { - return !!strVal; - }) + .filter(strVal => !!strVal) .join('\n'); } function iconsWithPrefix(prefix, properties, config) { return _.chain(properties) - .filter(function(prop) { - return prop.attributes.category === 'content' && prop.attributes.type === 'icon'; - }) - .map(function(prop) { - var varName = prefix + prop.name + ': ' + prop.value + ';'; - var className = '.' + config.prefix + '-icon.' + prop.attributes.item + ':before '; - var declaration = '{ content: ' + prefix + prop.name + '; }'; - return varName + '\n' + className + declaration; + .filter(({ attributes }) => attributes.category === 'content' && attributes.type === 'icon') + .map(({ name, value, attributes }) => { + const varName = `${prefix + name}: ${value};`; + const className = `.${config.prefix}-icon.${attributes.item}:before `; + const declaration = `{ content: ${prefix}${name}; }`; + return `${varName}\n${className}${declaration}`; }) .value() .join('\n'); @@ -73,8 +68,8 @@ module.exports = { * } * ``` */ - 'css/variables': function(dictionary) { - return fileHeader(this.options) + ':root {\n' + variablesWithPrefix(' --', dictionary.allProperties) + '\n}\n'; + 'css/variables': function({ allProperties }) { + return `${fileHeader(this.options)}:root {\n${variablesWithPrefix(' --', allProperties)}\n}\n`; }, /** @@ -88,8 +83,8 @@ module.exports = { * $color-background-alt: #eeeeee; * ``` */ - 'scss/variables': function(dictionary) { - return fileHeader(this.options) + variablesWithPrefix('$', dictionary.allProperties); + 'scss/variables': function({ allProperties }) { + return fileHeader(this.options) + variablesWithPrefix('$', allProperties); }, /** @@ -103,8 +98,8 @@ module.exports = { * .icon.email:before { content:$content-icon-email; } * ``` */ - 'scss/icons': function(dictionary, config) { - return fileHeader(this.options) + iconsWithPrefix('$', dictionary.allProperties, config); + 'scss/icons': function({ allProperties }, config) { + return fileHeader(this.options) + iconsWithPrefix('$', allProperties, config); }, /** @@ -118,8 +113,8 @@ module.exports = { * @color-background-alt: #eeeeee; * ``` */ - 'less/variables': function(dictionary) { - return fileHeader(this.options) + variablesWithPrefix('@', dictionary.allProperties); + 'less/variables': function({ allProperties }) { + return fileHeader(this.options) + variablesWithPrefix('@', allProperties); }, /** @@ -133,8 +128,8 @@ module.exports = { * .icon.email:before { content:@content-icon-email; } * ``` */ - 'less/icons': function(dictionary, config) { - return fileHeader(this.options) + iconsWithPrefix('@', dictionary.allProperties, config); + 'less/icons': function({ allProperties }, config) { + return fileHeader(this.options) + iconsWithPrefix('@', allProperties, config); }, /** @@ -155,8 +150,8 @@ module.exports = { * } * ``` */ - 'javascript/module': function(dictionary) { - return fileHeader(this.options) + 'module.exports = ' + JSON.stringify(dictionary.properties, null, 2) + ';'; + 'javascript/module': function({ properties }) { + return `${fileHeader(this.options)}module.exports = ${JSON.stringify(properties, null, 2)};`; }, /** @@ -178,15 +173,11 @@ module.exports = { * } * ``` */ - 'javascript/object': function(dictionary) { - return ( - fileHeader(this.options) + - 'var ' + - (this.name || '_styleDictionary') + - ' = ' + - JSON.stringify(dictionary.properties, null, 2) + - ';' - ); + 'javascript/object': function({ properties }) { + const header = fileHeader(this.options); + const varName = this.name || '_styleDictionary'; + const varBody = JSON.stringify(properties, null, 2); + return `${header}var ${varName} = ${varBody};`; }, /** @@ -219,30 +210,15 @@ module.exports = { * })) * ``` */ - 'javascript/umd': function(dictionary) { - var name = this.name || '_styleDictionary'; - return ( - fileHeader(this.options) + - '(function(root, factory) {\n' + - ' if (typeof module === "object" && module.exports) {\n' + - ' module.exports = factory();\n' + - ' } else if (typeof exports === "object") {\n' + - ' exports["' + - name + - '"] = factory();\n' + - ' } else if (typeof define === "function" && define.amd) {\n' + - ' define([], factory);\n' + - ' } else {\n' + - ' root["' + - name + - '"] = factory();\n' + - ' }\n' + - '}(this, function() {\n' + - ' return ' + - JSON.stringify(dictionary.properties, null, 2) + - ';\n' + - '}))\n' - ); + 'javascript/umd': function({ properties }) { + const name = this.name || '_styleDictionary'; + return `${fileHeader( + this.options + )}(function(root, factory) {\n if (typeof module === "object" && module.exports) {\n module.exports = factory();\n } else if (typeof exports === "object") {\n exports["${name}"] = factory();\n } else if (typeof define === "function" && define.amd) {\n define([], factory);\n } else {\n root["${name}"] = factory();\n }\n}(this, function() {\n return ${JSON.stringify( + properties, + null, + 2 + )};\n}))\n`; }, /** @@ -277,13 +253,13 @@ module.exports = { * export const ColorBackgroundAlt = '#fcfcfcfc'; * ``` */ - 'javascript/es6': function(dictionary) { + 'javascript/es6': function({ allProperties }) { return ( fileHeader(this.options) + - _.map(dictionary.allProperties, function(prop) { - var to_ret_prop = 'export const ' + prop.name + ' = ' + JSON.stringify(prop.value) + ';'; - if (prop.comment) to_ret_prop = to_ret_prop.concat(' // ' + prop.comment); - return to_ret_prop; + _.map(allProperties, ({ name, value, comment }) => { + let toRetProp = `export const ${name} = ${JSON.stringify(value)};`; + if (comment) toRetProp = toRetProp.concat(` // ${comment}`); + return toRetProp; }).join('\n') ); }, @@ -306,9 +282,7 @@ module.exports = { * } * ``` */ - json: function(dictionary) { - return JSON.stringify(dictionary.properties, null, 2); - }, + json: ({ properties }) => JSON.stringify(properties, null, 2), /** * Creates a JSON file of just the assets defined in the style dictionary. @@ -328,9 +302,7 @@ module.exports = { * } * ``` */ - 'json/asset': function(dictionary) { - return JSON.stringify({ asset: dictionary.properties.asset }, null, 2); - }, + 'json/asset': ({ properties }) => JSON.stringify({ asset: properties.asset }, null, 2), /** * Creates a sketchpalette file of all the base colors @@ -350,19 +322,15 @@ module.exports = { * } * ``` */ - 'sketch/palette': function(dictionary) { - var to_ret = { + 'sketch/palette': function({ allProperties }) { + const toRet = { compatibleVersion: '1.0', pluginVersion: '1.1', }; - to_ret.colors = _.chain(dictionary.allProperties) - .filter(function(prop) { - return prop.attributes.category === 'color' && prop.attributes.type === 'base'; - }) - .map(function(prop) { - return prop.value; - }) + toRet.colors = _.chain(allProperties) + .filter(({ attributes }) => attributes.category === 'color' && attributes.type === 'base') + .map(({ value }) => value) .value(); - return JSON.stringify(to_ret, null, 2); + return JSON.stringify(toRet, null, 2); }, }; diff --git a/lib/common/templates.js b/lib/common/templates.js index a5e73041f..b76d00a66 100644 --- a/lib/common/templates.js +++ b/lib/common/templates.js @@ -11,8 +11,9 @@ * and limitations under the License. */ -var fs = require('fs'), - _ = require('lodash'); +const fs = require('fs'); + +const _ = require('lodash'); /** * @namespace Templates @@ -33,7 +34,7 @@ module.exports = { * #ffe19d9c * ``` */ - 'android/colors': _.template(fs.readFileSync(__dirname + '/templates/android/colors.template')), + 'android/colors': _.template(fs.readFileSync(`${__dirname}/templates/android/colors.template`)), /** * Creates a dimen resource xml file with all the sizes in your style dictionary. @@ -48,7 +49,7 @@ module.exports = { * 15.00dp * ``` */ - 'android/dimens': _.template(fs.readFileSync(__dirname + '/templates/android/dimens.template')), + 'android/dimens': _.template(fs.readFileSync(`${__dirname}/templates/android/dimens.template`)), /** * Creates a dimen resource xml file with all the font sizes in your style dictionary. @@ -63,7 +64,7 @@ module.exports = { * 15.00sp * ``` */ - 'android/fontDimens': _.template(fs.readFileSync(__dirname + '/templates/android/fontDimens.template')), + 'android/fontDimens': _.template(fs.readFileSync(`${__dirname}/templates/android/fontDimens.template`)), /** * Creates a resource xml file with all the integers in your style dictionary. It filters your @@ -80,7 +81,7 @@ module.exports = { * 4000 * ``` */ - 'android/integers': _.template(fs.readFileSync(__dirname + '/templates/android/integers.template')), + 'android/integers': _.template(fs.readFileSync(`${__dirname}/templates/android/integers.template`)), /** * Creates a resource xml file with all the strings in your style dictionary. Filters your @@ -96,7 +97,7 @@ module.exports = { * * ``` */ - 'android/strings': _.template(fs.readFileSync(__dirname + '/templates/android/strings.template')), + 'android/strings': _.template(fs.readFileSync(`${__dirname}/templates/android/strings.template`)), // iOS templates @@ -113,7 +114,7 @@ module.exports = { * #define SizeFontTiny 176.00f * ``` */ - 'ios/macros': _.template(fs.readFileSync(__dirname + '/templates/ios/macros.template')), + 'ios/macros': _.template(fs.readFileSync(`${__dirname}/templates/ios/macros.template`)), /** * Creates an Objective-C plist file @@ -121,7 +122,7 @@ module.exports = { * @memberof Templates * @todo Fix this template and add example and usage */ - 'ios/plist': _.template(fs.readFileSync(__dirname + '/templates/ios/plist.template')), + 'ios/plist': _.template(fs.readFileSync(`${__dirname}/templates/ios/plist.template`)), /** * Creates an Objective-C implementation file of a style dictionary singleton class @@ -129,7 +130,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/singleton.m': _.template(fs.readFileSync(__dirname + '/templates/ios/singleton.m.template')), + 'ios/singleton.m': _.template(fs.readFileSync(`${__dirname}/templates/ios/singleton.m.template`)), /** * Creates an Objective-C header file of a style dictionary singleton class @@ -137,7 +138,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/singleton.h': _.template(fs.readFileSync(__dirname + '/templates/ios/singleton.h.template')), + 'ios/singleton.h': _.template(fs.readFileSync(`${__dirname}/templates/ios/singleton.h.template`)), /** * Creates an Objective-C header file of a static style dictionary class @@ -145,7 +146,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/static.h': _.template(fs.readFileSync(__dirname + '/templates/ios/static.h.template')), + 'ios/static.h': _.template(fs.readFileSync(`${__dirname}/templates/ios/static.h.template`)), /** * Creates an Objective-C implementation file of a static style dictionary class @@ -153,7 +154,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/static.m': _.template(fs.readFileSync(__dirname + '/templates/ios/static.m.template')), + 'ios/static.m': _.template(fs.readFileSync(`${__dirname}/templates/ios/static.m.template`)), /** * Creates an Objective-C header file of a color class @@ -161,7 +162,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/colors.h': _.template(fs.readFileSync(__dirname + '/templates/ios/colors.h.template')), + 'ios/colors.h': _.template(fs.readFileSync(`${__dirname}/templates/ios/colors.h.template`)), /** * Creates an Objective-C implementation file of a color class @@ -169,7 +170,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/colors.m': _.template(fs.readFileSync(__dirname + '/templates/ios/colors.m.template')), + 'ios/colors.m': _.template(fs.readFileSync(`${__dirname}/templates/ios/colors.m.template`)), /** * Creates an Objective-C header file of strings @@ -177,7 +178,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/strings.h': _.template(fs.readFileSync(__dirname + '/templates/ios/strings.h.template')), + 'ios/strings.h': _.template(fs.readFileSync(`${__dirname}/templates/ios/strings.h.template`)), /** * Creates an Objective-C implementation file of strings @@ -185,7 +186,7 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'ios/strings.m': _.template(fs.readFileSync(__dirname + '/templates/ios/strings.m.template')), + 'ios/strings.m': _.template(fs.readFileSync(`${__dirname}/templates/ios/strings.m.template`)), // Css templates @@ -195,5 +196,5 @@ module.exports = { * @memberof Templates * @todo Add example and usage */ - 'css/fonts.css': _.template(fs.readFileSync(__dirname + '/templates/css/fonts.css.template')), + 'css/fonts.css': _.template(fs.readFileSync(`${__dirname}/templates/css/fonts.css.template`)), }; diff --git a/lib/common/transforms.js b/lib/common/transforms.js index 83eb1f008..480b8d1d2 100644 --- a/lib/common/transforms.js +++ b/lib/common/transforms.js @@ -11,26 +11,28 @@ * and limitations under the License. */ -var Color = require('tinycolor2'), - _ = require('lodash'), - path = require('path'), - convertToBase64 = require('../utils/convertToBase64'), - UNICODE_PATTERN = /&#x([^;]+);/g; - -function isColor(prop) { - return prop.attributes.category === 'color'; +const Color = require('tinycolor2'); + +const _ = require('lodash'); +const path = require('path'); +const convertToBase64 = require('../utils/convertToBase64'); + +const UNICODE_PATTERN = /&#x([^;]+);/g; + +function isColor({ attributes }) { + return attributes.category === 'color'; } -function isSize(prop) { - return prop.attributes.category === 'size'; +function isSize({ attributes }) { + return attributes.category === 'size'; } -function isFontSize(prop) { - return prop.attributes.category === 'size' && (prop.attributes.type === 'font' || prop.attributes.type === 'icon'); +function isFontSize({ attributes }) { + return attributes.category === 'size' && (attributes.type === 'font' || attributes.type === 'icon'); } -function isNotFontSize(prop) { - return prop.attributes.category === 'size' && prop.attributes.type !== 'font' && prop.attributes.type !== 'icon'; +function isNotFontSize({ attributes }) { + return attributes.category === 'size' && attributes.type !== 'font' && attributes.type !== 'icon'; } /** @@ -56,7 +58,7 @@ module.exports = { */ 'attribute/cti': { type: 'attribute', - transformer: function(prop) { + transformer(prop) { return { category: prop.path[0], type: prop.path[1], @@ -86,8 +88,8 @@ module.exports = { 'attribute/color': { type: 'attribute', matcher: isColor, - transformer: function(prop) { - var color = Color(prop.value); + transformer({ value }) { + const color = Color(value); return { hex: color.toHex(), rgb: color.toRgb(), @@ -110,8 +112,8 @@ module.exports = { */ 'name/human': { type: 'name', - transformer: function(prop) { - return [prop.attributes.item, prop.attributes.subitem].join(' '); + transformer({ attributes }) { + return [attributes.item, attributes.subitem].join(' '); }, }, @@ -129,8 +131,8 @@ module.exports = { */ 'name/cti/camel': { type: 'name', - transformer: function(prop, options) { - return _.camelCase([options.prefix].concat(prop.path).join(' ')); + transformer(prop, { prefix }) { + return _.camelCase([prefix].concat(prop.path).join(' ')); }, }, @@ -148,8 +150,8 @@ module.exports = { */ 'name/cti/kebab': { type: 'name', - transformer: function(prop, options) { - return _.kebabCase([options.prefix].concat(prop.path).join(' ')); + transformer(prop, { prefix }) { + return _.kebabCase([prefix].concat(prop.path).join(' ')); }, }, @@ -167,8 +169,8 @@ module.exports = { */ 'name/cti/snake': { type: 'name', - transformer: function(prop, options) { - return _.snakeCase([options.prefix].concat(prop.path).join(' ')); + transformer(prop, { prefix }) { + return _.snakeCase([prefix].concat(prop.path).join(' ')); }, }, @@ -186,8 +188,8 @@ module.exports = { */ 'name/cti/constant': { type: 'name', - transformer: function(prop, options) { - return _.snakeCase([options.prefix].concat(prop.path).join(' ')).toUpperCase(); + transformer(prop, { prefix }) { + return _.snakeCase([prefix].concat(prop.path).join(' ')).toUpperCase(); }, }, @@ -205,9 +207,9 @@ module.exports = { */ 'name/ti/constant': { type: 'name', - transformer: function(prop, options) { - var path = prop.path.slice(1); - return _.snakeCase([options.prefix].concat(path).join(' ')).toUpperCase(); + transformer(prop, { prefix }) { + const transformerPath = prop.path.slice(1); + return _.snakeCase([prefix].concat(transformerPath).join(' ')).toUpperCase(); }, }, @@ -225,8 +227,8 @@ module.exports = { */ 'name/cti/pascal': { type: 'name', - transformer: function(prop, options) { - return _.upperFirst(_.camelCase([options.prefix].concat(prop.path).join(' '))); + transformer(prop, { prefix }) { + return _.upperFirst(_.camelCase([prefix].concat(prop.path).join(' '))); }, }, @@ -244,8 +246,8 @@ module.exports = { 'color/rgb': { type: 'value', matcher: isColor, - transformer: function(prop) { - return Color(prop.value).toRgbString(); + transformer({ value }) { + return Color(value).toRgbString(); }, }, @@ -263,8 +265,8 @@ module.exports = { 'color/hex': { type: 'value', matcher: isColor, - transformer: function(prop) { - return Color(prop.value).toHexString(); + transformer({ value }) { + return Color(value).toHexString(); }, }, @@ -282,8 +284,8 @@ module.exports = { 'color/hex8': { type: 'value', matcher: isColor, - transformer: function(prop) { - return Color(prop.value).toHex8String(); + transformer({ value }) { + return Color(value).toHex8String(); }, }, @@ -301,9 +303,9 @@ module.exports = { 'color/hex8android': { type: 'value', matcher: isColor, - transformer: function(prop) { - var str = Color(prop.value).toHex8(); - return '#' + str.slice(6) + str.slice(0, 6); + transformer({ value }) { + const str = Color(value).toHex8(); + return `#${str.slice(6)}${str.slice(0, 6)}`; }, }, @@ -321,22 +323,11 @@ module.exports = { 'color/UIColor': { type: 'value', matcher: isColor, - transformer: function(prop) { - var rgb = Color(prop.value).toRgb(); - return ( - '[UIColor colorWithRed:' + - (rgb.r / 255).toFixed(2) + - 'f' + - ' green:' + - (rgb.g / 255).toFixed(2) + - 'f' + - ' blue:' + - (rgb.b / 255).toFixed(2) + - 'f' + - ' alpha:' + - rgb.a.toFixed(2) + - 'f]' - ); + transformer({ value }) { + const rgb = Color(value).toRgb(); + return `[UIColor colorWithRed:${(rgb.r / 255).toFixed(2)}f green:${(rgb.g / 255).toFixed(2)}f blue:${( + rgb.b / 255 + ).toFixed(2)}f alpha:${rgb.a.toFixed(2)}f]`; }, }, @@ -355,13 +346,12 @@ module.exports = { 'color/css': { type: 'value', matcher: isColor, - transformer: function(prop) { - var color = Color(prop.value); + transformer({ value }) { + const color = Color(value); if (color.getAlpha() === 1) { return color.toHexString(); - } else { - return color.toRgbString(); } + return color.toRgbString(); }, }, @@ -379,8 +369,8 @@ module.exports = { 'size/sp': { type: 'value', matcher: isFontSize, - transformer: function(prop) { - return parseFloat(prop.value, 10).toFixed(2) + 'sp'; + transformer({ value }) { + return `${parseFloat(value, 10).toFixed(2)}sp`; }, }, @@ -398,8 +388,8 @@ module.exports = { 'size/dp': { type: 'value', matcher: isNotFontSize, - transformer: function(prop) { - return parseFloat(prop.value, 10).toFixed(2) + 'dp'; + transformer({ value }) { + return `${parseFloat(value, 10).toFixed(2)}dp`; }, }, @@ -417,8 +407,8 @@ module.exports = { 'size/remToSp': { type: 'value', matcher: isFontSize, - transformer: function(prop) { - return (parseFloat(prop.value, 10) * 16).toFixed(2) + 'sp'; + transformer({ value }) { + return `${(parseFloat(value, 10) * 16).toFixed(2)}sp`; }, }, @@ -436,8 +426,8 @@ module.exports = { 'size/remToDp': { type: 'value', matcher: isNotFontSize, - transformer: function(prop) { - return (parseFloat(prop.value, 10) * 16).toFixed(2) + 'dp'; + transformer({ value }) { + return `${(parseFloat(value, 10) * 16).toFixed(2)}dp`; }, }, @@ -455,8 +445,8 @@ module.exports = { 'size/px': { type: 'value', matcher: isSize, - transformer: function(prop) { - return parseFloat(prop.value, 10) + 'px'; + transformer({ value }) { + return `${parseFloat(value, 10)}px`; }, }, @@ -474,8 +464,8 @@ module.exports = { 'size/rem': { type: 'value', matcher: isSize, - transformer: function(prop) { - return parseFloat(prop.value, 10) + 'rem'; + transformer({ value }) { + return `${parseFloat(value, 10)}rem`; }, }, @@ -493,8 +483,8 @@ module.exports = { 'size/remToPt': { type: 'value', matcher: isSize, - transformer: function(prop) { - return (parseFloat(prop.value, 10) * 16).toFixed(2) + 'f'; + transformer({ value }) { + return `${(parseFloat(value, 10) * 16).toFixed(2)}f`; }, }, @@ -512,8 +502,8 @@ module.exports = { 'size/remToPx': { type: 'value', matcher: isSize, - transformer: function(prop) { - return (parseFloat(prop.value, 10) * 16).toFixed(0) + 'px'; + transformer({ value }) { + return `${(parseFloat(value, 10) * 16).toFixed(0)}px`; }, }, @@ -530,13 +520,11 @@ module.exports = { */ 'content/icon': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'content' && prop.attributes.type === 'icon'; + matcher({ attributes }) { + return attributes.category === 'content' && attributes.type === 'icon'; }, - transformer: function(prop) { - return prop.value.replace(UNICODE_PATTERN, function(match, variable) { - return "'\\" + variable + "'"; - }); + transformer({ value }) { + return value.replace(UNICODE_PATTERN, (match, variable) => `'\\${variable}'`); }, }, @@ -553,11 +541,11 @@ module.exports = { */ 'content/quote': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'content'; + matcher({ attributes }) { + return attributes.category === 'content'; }, - transformer: function(prop) { - return "'" + prop.value + "'"; + transformer({ value }) { + return `'${value}'`; }, }, @@ -574,11 +562,11 @@ module.exports = { */ 'content/objC/literal': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'content'; + matcher({ attributes }) { + return attributes.category === 'content'; }, - transformer: function(prop) { - return '@"' + prop.value + '"'; + transformer({ value }) { + return `@"${value}"`; }, }, @@ -594,11 +582,11 @@ module.exports = { */ 'font/objC/literal': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'font'; + matcher({ attributes }) { + return attributes.category === 'font'; }, - transformer: function(prop) { - return '@"' + prop.value + '"'; + transformer({ value }) { + return `@"${value}"`; }, }, @@ -615,11 +603,11 @@ module.exports = { */ 'time/seconds': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'time'; + matcher({ attributes }) { + return attributes.category === 'time'; }, - transformer: function(prop) { - return (parseFloat(prop.value) / 1000).toFixed(2) + 's'; + transformer({ value }) { + return `${(parseFloat(value) / 1000).toFixed(2)}s`; }, }, @@ -636,11 +624,11 @@ module.exports = { */ 'asset/base64': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'asset'; + matcher({ attributes }) { + return attributes.category === 'asset'; }, - transformer: function(prop) { - return convertToBase64(prop.value); + transformer({ value }) { + return convertToBase64(value); }, }, @@ -657,11 +645,11 @@ module.exports = { */ 'asset/path': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'asset'; + matcher({ attributes }) { + return attributes.category === 'asset'; }, - transformer: function(prop) { - return path.join(process.cwd(), prop.value); + transformer({ value }) { + return path.join(process.cwd(), value); }, }, @@ -677,11 +665,11 @@ module.exports = { */ 'asset/objC/literal': { type: 'value', - matcher: function(prop) { - return prop.attributes.category === 'asset'; + matcher({ attributes }) { + return attributes.category === 'asset'; }, - transformer: function(prop) { - return '@"' + prop.value + '"'; + transformer({ value }) { + return `@"${value}"`; }, }, }; diff --git a/lib/exportPlatform.js b/lib/exportPlatform.js index 65b5b4346..6c88b9f3a 100644 --- a/lib/exportPlatform.js +++ b/lib/exportPlatform.js @@ -11,9 +11,10 @@ * and limitations under the License. */ -var resolveObject = require('./utils/resolveObject'), - transformObject = require('./transform/object'), - transformConfig = require('./transform/config'); +var resolveObject = require('./utils/resolveObject'); + +var transformObject = require('./transform/object'); +var transformConfig = require('./transform/config'); /** * Exports a properties object with applied diff --git a/lib/extend.js b/lib/extend.js index d46231916..3216bd927 100644 --- a/lib/extend.js +++ b/lib/extend.js @@ -13,11 +13,11 @@ require('json5/lib/register'); -var combineJSON = require('./utils/combineJSON'), - deepExtend = require('./utils/deepExtend'), - resolveCwd = require('resolve-cwd'), - _ = require('lodash'), - chalk = require('chalk'); +var combineJSON = require('./utils/combineJSON'); +var deepExtend = require('./utils/deepExtend'); +var resolveCwd = require('resolve-cwd'); +var _ = require('lodash'); +var chalk = require('chalk'); /** * Either a string to a JSON file that contains configuration for the style dictionary or a plain Javascript object @@ -81,7 +81,8 @@ var combineJSON = require('./utils/combineJSON'), * ``` */ function extend(opts) { - var options, to_ret; + var options; + var toRet; // Overloaded method, can accept a string as a path that points to a JS or // JSON file or a plain object. Potentially refactor. @@ -93,18 +94,18 @@ function extend(opts) { // Creating a new object and copying over the options // Also keeping an options object just in case - to_ret = deepExtend([{options: options}, this, options]); + toRet = deepExtend([{options}, this, options]); // Update properties with includes from dependencies if (options.include) { if (!_.isArray(options.include)) throw new Error('include must be an array'); - _.forEach(options.include, function(file){ - to_ret.properties = deepExtend([{}, to_ret.properties, require(file)]); + _.forEach(options.include, file => { + toRet.properties = deepExtend([{}, toRet.properties, require(file)]); }); - to_ret.include = null; // We don't want to carry over include references + toRet.include = null; // We don't want to carry over include references } // Update properties with current package's source @@ -124,11 +125,11 @@ function extend(opts) { } }); - to_ret.properties = deepExtend([{}, to_ret.properties, props]); - to_ret.source = null; // We don't want to carry over the source references + toRet.properties = deepExtend([{}, toRet.properties, props]); + toRet.source = null; // We don't want to carry over the source references } - return to_ret; + return toRet; } module.exports = extend; diff --git a/lib/performActions.js b/lib/performActions.js index c46a5dced..516e64c00 100644 --- a/lib/performActions.js +++ b/lib/performActions.js @@ -25,7 +25,7 @@ var _ = require('lodash'); */ function performActions(dictionary, platform) { if (platform.actions) { - _.each(platform.actions, function(action) { + _.each(platform.actions, action => { action.do(dictionary, platform); }); } diff --git a/lib/register/action.js b/lib/register/action.js index 3a9a034e1..86803697d 100644 --- a/lib/register/action.js +++ b/lib/register/action.js @@ -10,7 +10,6 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ -var chalk = require('chalk'); /** * Adds a custom action to the style property builder. Custom diff --git a/lib/register/format.js b/lib/register/format.js index aa3e8bf27..3a453f51f 100644 --- a/lib/register/format.js +++ b/lib/register/format.js @@ -30,11 +30,11 @@ * }) * ``` */ -function registerFormat(options) { - if (typeof options.name !== 'string') throw new Error('transform name must be a string'); - if (typeof options.formatter !== 'function') throw new Error('format formatter must be a function'); +function registerFormat({ name, formatter }) { + if (typeof name !== 'string') throw new Error('transform name must be a string'); + if (typeof formatter !== 'function') throw new Error('format formatter must be a function'); - this.format[options.name] = options.formatter; + this.format[name] = formatter; return this; } diff --git a/lib/register/template.js b/lib/register/template.js index 21f73e164..fa79acad9 100644 --- a/lib/register/template.js +++ b/lib/register/template.js @@ -11,9 +11,10 @@ * and limitations under the License. */ -var fs = require('fs'), - _ = require('lodash'), - chalk = require('chalk'); +const fs = require('fs'); + +const _ = require('lodash'); +const chalk = require('chalk'); /** * Add a custom template to the Style Dictionary @@ -31,17 +32,20 @@ var fs = require('fs'), * }); * ``` */ -function registerTemplate(options) { - if (typeof options.name !== 'string') - throw new Error('Template name must be a string: ' + chalk.red(JSON.stringify(options.name))); - if (typeof options.template !== 'string') - throw new Error('Template path must be a string: ' + chalk.red(JSON.stringify(options.template))); - if (!fs.existsSync(options.template)) - throw new Error("Can't find template: " + chalk.red(JSON.stringify(options.template))); +function registerTemplate({ name, template }) { + if (typeof name !== 'string') { + throw new Error(`Template name must be a string: ${chalk.red(JSON.stringify(name))}`); + } + if (typeof template !== 'string') { + throw new Error(`Template path must be a string: ${chalk.red(JSON.stringify(template))}`); + } + if (!fs.existsSync(template)) { + throw new Error(`Can't find template: ${chalk.red(JSON.stringify(template))}`); + } - var template_string = fs.readFileSync(options.template); + const templateString = fs.readFileSync(template); - this.template[options.name] = _.template(template_string); + this.template[name] = _.template(templateString); return this; } diff --git a/lib/register/transform.js b/lib/register/transform.js index c56d00896..73486d60e 100644 --- a/lib/register/transform.js +++ b/lib/register/transform.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var transformTypes = ['name', 'value', 'attribute']; +const transformTypes = ['name', 'value', 'attribute']; /** * Add a custom transform to the Style Dictionary @@ -44,18 +44,17 @@ var transformTypes = ['name', 'value', 'attribute']; * }); * ``` */ -function registerTransform(options) { - if (typeof options.type !== 'string') throw new Error('type must be a string'); - if (transformTypes.indexOf(options.type) < 0) - throw new Error(options.type + ' type is not one of: ' + transformTypes.join(', ')); - if (typeof options.name !== 'string') throw new Error('name must be a string'); - if (options.matcher && typeof options.matcher !== 'function') throw new Error('matcher must be a function'); - if (typeof options.transformer !== 'function') throw new Error('transformer must be a function'); +function registerTransform({ type, name, matcher, transformer }) { + if (typeof type !== 'string') throw new Error('type must be a string'); + if (!transformTypes.includes(type)) throw new Error(`${type} type is not one of: ${transformTypes.join(', ')}`); + if (typeof name !== 'string') throw new Error('name must be a string'); + if (matcher && typeof matcher !== 'function') throw new Error('matcher must be a function'); + if (typeof transformer !== 'function') throw new Error('transformer must be a function'); - this.transform[options.name] = { - type: options.type, - matcher: options.matcher, - transformer: options.transformer, + this.transform[name] = { + type, + matcher, + transformer, }; return this; diff --git a/lib/register/transformGroup.js b/lib/register/transformGroup.js index b5950c910..6a42bec0b 100644 --- a/lib/register/transformGroup.js +++ b/lib/register/transformGroup.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * Add a custom transformGroup to the Style Dictionary, which is a @@ -34,17 +34,15 @@ var _ = require('lodash'); * }); * ``` */ -function registerTransformGroup(options) { - if (typeof options.name !== 'string') throw new Error('transform name must be a string'); - if (!_.isArray(options.transforms)) throw new Error('transforms must be an array of registered value transforms'); +function registerTransformGroup({ name, transforms }) { + if (typeof name !== 'string') throw new Error('transform name must be a string'); + if (!_.isArray(transforms)) throw new Error('transforms must be an array of registered value transforms'); - options.transforms.forEach( - function(t) { - if (!_.has(this.transform, t)) throw new Error('transforms must be an array of registered value transforms'); - }.bind(this) - ); + transforms.forEach(t => { + if (!_.has(this.transform, t)) throw new Error('transforms must be an array of registered value transforms'); + }); - this.transformGroup[options.name] = options.transforms; + this.transformGroup[name] = transforms; return this; } diff --git a/lib/transform/config.js b/lib/transform/config.js index 5f3dfeca4..ca0f248da 100644 --- a/lib/transform/config.js +++ b/lib/transform/config.js @@ -11,8 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'), - chalk = require('chalk'); +const _ = require('lodash'); /** * Takes a platform config object and returns a new one @@ -24,58 +23,55 @@ var _ = require('lodash'), * @returns {Object} */ function transformConfig(config, dictionary) { - var to_ret = _.clone(config); + const toRet = _.clone(config); // The platform can define either a transformGroup or an array // of transforms. If given a transformGroup that doesn't exist, // it will throw an error so the user is aware the transformGroup doesn't // exist. A valid case is if the user defines neither, no transforms will be // applied. - var transforms = []; - if (to_ret.transforms) { - transforms = to_ret.transforms; - } else if (to_ret.transformGroup) { - transforms = dictionary.transformGroup[to_ret.transformGroup]; + let transforms = []; + if (toRet.transforms) { + /* eslint-disable prefer-destructuring */ + transforms = toRet.transforms; + } else if (toRet.transformGroup) { + transforms = dictionary.transformGroup[toRet.transformGroup]; if (!transforms) { - throw new Error('transformGroup ' + to_ret.transformGroup + " doesn't exist"); + throw new Error(`transformGroup ${toRet.transformGroup} doesn't exist`); } } // Transforms are an array of strings that map to functions on // the StyleDictionary module. We need to map the strings to // the actual functions. - to_ret.transforms = _.map(transforms, function(name) { - return dictionary.transform[name]; - }); + toRet.transforms = _.map(transforms, name => dictionary.transform[name]); - to_ret.files = _.map(config.files, function(file) { + toRet.files = _.map(config.files, file => { if (file.template) { if (dictionary.template[file.template]) { return _.extend({}, file, { template: dictionary.template[file.template], }); - } else { - throw new Error("Can't find template: " + file.template); } + throw new Error(`Can't find template: ${file.template}`); } else if (file.format) { if (dictionary.format[file.format]) { return _.extend({}, file, { format: dictionary.format[file.format] }); - } else { - throw new Error("Can't find format: " + file.format); } + throw new Error(`Can't find format: ${file.format}`); } else { - throw new Error('Please supply a format or template for file: ' + JSON.stringify(file)); + throw new Error(`Please supply a format or template for file: ${JSON.stringify(file)}`); } }); - to_ret.actions = _.map(config.actions, function(action) { + toRet.actions = _.map(config.actions, action => { if (typeof dictionary.action[action].undo !== 'function') { - console.warn(action + ' action does not have a clean function!'); + console.warn(`${action} action does not have a clean function!`); } return dictionary.action[action]; }); - return to_ret; + return toRet; } module.exports = transformConfig; diff --git a/lib/transform/object.js b/lib/transform/object.js index 9ba422452..9bf1a66a8 100644 --- a/lib/transform/object.js +++ b/lib/transform/object.js @@ -11,9 +11,10 @@ * and limitations under the License. */ -var _ = require('lodash'), - transformProperty = require('./property'), - propertySetup = require('./propertySetup'); +const _ = require('lodash'); + +const transformProperty = require('./property'); +const propertySetup = require('./propertySetup'); /** * Applies transforms on all properties. This @@ -25,29 +26,25 @@ var _ = require('lodash'), * @param {Object} obj * @param {Object} options * @param {Array} [path=[]] - * @param {Object} [to_ret={}] + * @param {Object} [toRet={}] * @returns {Object} */ -function transformObject(obj, options, path, to_ret) { - to_ret = to_ret || {}; - path = path || []; - - for (var name in obj) { - if (obj.hasOwnProperty(name)) { - path.push(name); - // Need better logic - if (_.isPlainObject(obj[name]) && _.has(obj[name], 'value')) { - to_ret[name] = transformProperty(propertySetup(obj[name], name, path), options); - } else if (_.isPlainObject(obj[name])) { - to_ret[name] = transformObject(obj[name], options, path, to_ret[name]); - } else { - to_ret[name] = obj[name]; - } - path.pop(); +function transformObject(obj, options, path = [], toRet = {}) { + /* eslint-disable no-param-reassign */ + Object.keys(obj || {}).forEach(name => { + path.push(name); + // Need better logic + if (_.isPlainObject(obj[name]) && _.has(obj[name], 'value')) { + toRet[name] = transformProperty(propertySetup(obj[name], name, path), options); + } else if (_.isPlainObject(obj[name])) { + toRet[name] = transformObject(obj[name], options, path, toRet[name]); + } else { + toRet[name] = obj[name]; } - } + path.pop(); + }); - return to_ret; + return toRet; } module.exports = transformObject; diff --git a/lib/transform/property.js b/lib/transform/property.js index 016b918d8..65a9da4a8 100644 --- a/lib/transform/property.js +++ b/lib/transform/property.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * Applies all transforms to a property. This is a pure function, @@ -22,24 +22,24 @@ var _ = require('lodash'); * @returns {Object} - A new property object with transforms applied. */ function transformProperty(property, options) { - var to_ret = _.clone(property); - var transforms = options.transforms; + const toRet = _.clone(property); + const { transforms } = options; - for (var i = 0; i < transforms.length; i++) { - var transform = transforms[i]; + for (let i = 0; i < transforms.length; i += 1) { + const transform = transforms[i]; - if (!transform.matcher || transform.matcher(to_ret)) { - if (transform.type === 'name') to_ret.name = transform.transformer(to_ret, options); + if (!transform.matcher || transform.matcher(toRet)) { + if (transform.type === 'name') toRet.name = transform.transformer(toRet, options); // Don't try to transform the value if it is referencing another value // Only try to transform if the value is not a string or if it has '{}' - if (transform.type === 'value' && (!_.isString(property.value) || property.value.indexOf('{') < 0)) - to_ret.value = transform.transformer(to_ret, options); + if (transform.type === 'value' && (!_.isString(property.value) || !property.value.includes('{'))) + toRet.value = transform.transformer(toRet, options); if (transform.type === 'attribute') - to_ret.attributes = _.extend({}, to_ret.attributes, transform.transformer(to_ret, options)); + toRet.attributes = _.extend({}, toRet.attributes, transform.transformer(toRet, options)); } } - return to_ret; + return toRet; } module.exports = transformProperty; diff --git a/lib/transform/propertySetup.js b/lib/transform/propertySetup.js index e0691b6a3..c14df8320 100644 --- a/lib/transform/propertySetup.js +++ b/lib/transform/propertySetup.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * Takes a property object, a leaf node in a properties object, and @@ -29,23 +29,23 @@ function propertySetup(property, name, path) { if (!name || !_.isString(name)) throw new Error('Name must be a string'); if (!path || !_.isArray(path)) throw new Error('Path must be an array'); - var to_ret = _.clone(property); + const toRet = _.clone(property); // Only do this once if (!property.original) { // Initial property setup // Keep the original object properties so we can key off them in the transforms - to_ret.original = _.clone(property); + toRet.original = _.clone(property); // Copy the name so we can have a base name to transform - to_ret.name = to_ret.name || name || ''; + toRet.name = toRet.name || name || ''; // Create an empty attributes object that we can transform on it later - to_ret.attributes = to_ret.attributes || {}; + toRet.attributes = toRet.attributes || {}; // An array of the path down the object tree so we can use it to build readable names // like color_font_base - to_ret.path = _.clone(path); + toRet.path = _.clone(path); } - return to_ret; + return toRet; } module.exports = propertySetup; diff --git a/lib/utils/combineJSON.js b/lib/utils/combineJSON.js index fdefded42..dc2fee0b5 100644 --- a/lib/utils/combineJSON.js +++ b/lib/utils/combineJSON.js @@ -13,11 +13,11 @@ require('json5/lib/register'); -var glob = require('glob'), - deepExtend = require('./deepExtend'), - extend = require('lodash/extend'), - path = require('path'), - resolveCwd = require('resolve-cwd'); +const glob = require('glob'); +const extend = require('lodash/extend'); +const path = require('path'); +const resolveCwd = require('resolve-cwd'); +const deepExtend = require('./deepExtend'); /** * Takes an array of json files and merges @@ -29,34 +29,35 @@ var glob = require('glob'), * @returns {Object} */ function combineJSON(arr, deep, collision) { - var i, - files = [], - to_ret = {}; - - for (i = 0; i < arr.length; i++) { - var new_files = glob.sync(arr[i], {}); - files = files.concat(new_files); + let i; + let files = []; + const toRet = {}; + let fileContent; + + for (i = 0; i < arr.length; i += 1) { + const newFiles = glob.sync(arr[i], {}); + files = files.concat(newFiles); } - for (i = 0; i < files.length; i++) { - var resolvedPath = resolveCwd(path.isAbsolute(files[i]) ? files[i] : './' + files[i]); - var file_content; + for (i = 0; i < files.length; i += 1) { + const resolvedPath = resolveCwd(path.isAbsolute(files[i]) ? files[i] : `./${files[i]}`); try { - file_content = require(resolvedPath); + /* eslint-disable global-require, import/no-dynamic-require */ + fileContent = require(resolvedPath); } catch (e) { - e.message = 'Failed to load or parse JSON or JS Object: ' + e.message; + e.message = `Failed to load or parse JSON or JS Object: ${e.message}`; throw e; } if (deep) { - deepExtend([to_ret, file_content], collision); + deepExtend([toRet, fileContent], collision); } else { - extend(to_ret, file_content); + extend(toRet, fileContent); } } - return to_ret; + return toRet; } module.exports = combineJSON; diff --git a/lib/utils/convertToBase64.js b/lib/utils/convertToBase64.js index 75c507536..36e7d3785 100644 --- a/lib/utils/convertToBase64.js +++ b/lib/utils/convertToBase64.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var fs = require('fs'); +const fs = require('fs'); /** * Takes a file and converts it to a base64 string. @@ -22,8 +22,8 @@ var fs = require('fs'); function convertToBase64(filePath) { if (!filePath || typeof filePath !== 'string') throw new Error('filePath name must be a string'); - var body = fs.readFileSync(filePath, 'binary'); - return new Buffer(body, 'binary').toString('base64'); + const body = fs.readFileSync(filePath, 'binary'); + return Buffer.from(body, 'binary').toString('base64'); } module.exports = convertToBase64; diff --git a/lib/utils/deepExtend.js b/lib/utils/deepExtend.js index 3c114930f..5426a4356 100644 --- a/lib/utils/deepExtend.js +++ b/lib/utils/deepExtend.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * Performs an deep extend on the objects, from right to left. @@ -21,64 +21,63 @@ var _ = require('lodash'); * @param {string[]} path - (for internal use) An array of strings which is the current path down the object when this is called recursively. * @returns {Object} */ -function deepExtend(objects, collision, path) { +function deepExtend(objects, collision, path = []) { if (objects == null) return {}; - var src, - copyIsArray, - copy, - name, - options, - clone, - target = objects[0] || {}, - i = 1, - length = objects.length; - - path = path || []; + let src; + let copyIsArray; + let copy; + let options; + let clone; + let target = objects[0] || {}; + const { length } = objects; // Handle case when target is a string or something (possible in deep copy) if (typeof target !== 'object') { target = {}; } - for (; i < length; i++) { - // Only deal with non-null/undefined values - if ((options = objects[i]) != null) { - // Extend the base object - for (name in options) { - if (!options.hasOwnProperty(name)) continue; - - src = target[name]; - copy = options[name]; + const optionsIterator = optionsName => { + src = target[optionsName]; + copy = options[optionsName]; - // Prevent never-ending loop - if (target === copy) { - continue; - } + // Prevent never-ending loop + if (target === copy) { + return; + } - // Recurse if we're merging plain objects or arrays - if (copy && (_.isPlainObject(copy) || (copyIsArray = _.isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && _.isArray(src) ? src : []; - } else { - clone = src && _.isPlainObject(src) ? src : {}; - } + // Recurse if we're merging plain objects or arrays + /* eslint-disable no-cond-assign */ + if (copy && (_.isPlainObject(copy) || (copyIsArray = _.isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && _.isArray(src) ? src : []; + } else { + clone = src && _.isPlainObject(src) ? src : {}; + } - path.push(name); + path.push(optionsName); - // Never move original objects, clone them - target[name] = deepExtend([clone, copy], collision, path); + // Never move original objects, clone them + target[optionsName] = deepExtend([clone, copy], collision, path); - // Don't bring in undefined values - } else if (copy !== undefined) { - if (src != null && typeof collision == 'function') { - collision({ target: target, copy: options, path: path, key: name }); - } - target[name] = copy; - } - path.pop(); + // Don't bring in undefined values + } else if (copy !== undefined) { + if (src != null && typeof collision === 'function') { + collision({ target, copy: options, path, key: optionsName }); } + target[optionsName] = copy; + } + path.pop(); + }; + + for (let i = 1; i < length; i += 1) { + options = objects[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + + Object.keys(options).forEach(optionsIterator); } } diff --git a/lib/utils/flattenProperties.js b/lib/utils/flattenProperties.js index 6507fcda3..05644551b 100644 --- a/lib/utils/flattenProperties.js +++ b/lib/utils/flattenProperties.js @@ -11,7 +11,7 @@ * and limitations under the License. */ -var _ = require('lodash'); +const _ = require('lodash'); /** * Takes an plain javascript object and will make a flat array of all the leaf nodes. @@ -19,24 +19,20 @@ var _ = require('lodash'); * be more generic. * @private * @param {Object} properties - The plain object you want flattened into an array. - * @param {Array} [to_ret=[]] - Properties array. This function is recursive so this is what gets passed along. + * @param {Array} [toRet=[]] - Properties array. This function is recursive so this is what gets passed along. * @return {Array} */ -function flattenProperties(properties, to_ret) { - to_ret = to_ret || []; - - for (var name in properties) { - if (properties.hasOwnProperty(name)) { - // TODO: this is a bit fragile and arbitrary to stop when we get to a 'value' property. - if (_.isPlainObject(properties[name]) && _.has(properties[name], 'value')) { - to_ret.push(properties[name]); - } else if (_.isPlainObject(properties[name])) { - flattenProperties(properties[name], to_ret); - } +function flattenProperties(properties, toRet = []) { + Object.keys(properties).forEach(name => { + // TODO: this is a bit fragile and arbitrary to stop when we get to a 'value' property. + if (_.isPlainObject(properties[name]) && _.has(properties[name], 'value')) { + toRet.push(properties[name]); + } else if (_.isPlainObject(properties[name])) { + flattenProperties(properties[name], toRet); } - } + }); - return to_ret; + return toRet; } module.exports = flattenProperties; diff --git a/lib/utils/resolveObject.js b/lib/utils/resolveObject.js index 4e0d72cef..3645fec2a 100644 --- a/lib/utils/resolveObject.js +++ b/lib/utils/resolveObject.js @@ -10,125 +10,103 @@ * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ +/* eslint-disable no-use-before-define */ -var _ = require('lodash'); +const _ = require('lodash'); -var current_context = []; // To maintain the context so we can test for circular definitions -var defaults = { +let currentContext = []; // To maintain the context so we can test for circular definitions +const defaults = { opening_character: '{', closing_character: '}', separator: '.', ignoreKeys: ['original'], }; -var updated_object, regex, options; +let updatedObject; +let regex; +let options; -function resolveObject(object, opts) { - options = _.extend({}, defaults, opts); - - updated_object = _.cloneDeep(object); // This object will be edited - - regex = new RegExp( - '\\' + options.opening_character + '([^' + options.closing_character + ']+)' + '\\' + options.closing_character, - 'g' - ); - - if (typeof object === 'object') { - current_context = []; - return traverseObj(updated_object); - } else { - throw new Error('Please pass an object in'); - } -} - -function traverseObj(obj) { - var key; - var errors = []; - - for (key in obj) { - // We want to check for ignoredKeys, this is so - // we can skip over attributes that should not be - // mutated, like a copy of the original property. - if (obj.hasOwnProperty(key) && (options.ignoreKeys || []).indexOf(key) < 0) { - current_context.push(key); - if (typeof obj[key] === 'object') { - traverseObj(obj[key]); - } else { - if (typeof obj[key] === 'string' && obj[key].indexOf('{') > -1) { - try { - obj[key] = compile_value(obj[key], [key]); - } catch (e) { - errors.push(e); - } - } - } - current_context.pop(); - } - } - - if (errors.length) { - throw new Error( - errors.length === 1 - ? errors[0] - : 'Failed due to ' + errors.length + ' errors:\n' + errors.join('\n').replace(/Error: /g, '\t') - ); - } - - return obj; -} - -function compile_value(value, stack) { - var to_ret, ref; +function compileValue(value, stack) { + let toRet; + let ref; stack.push(value.slice(1, -1)); // Replace the reference inline, but don't replace the whole string because // references can be part of the value such as "1px solid {color.border.light}" - value.replace(regex, function(match, variable) { + value.replace(regex, (match, variable) => { // Find what the value is referencing - ref = selfRef(variable.trim(), updated_object); + ref = selfRef(variable.trim(), updatedObject); if (ref) { if (typeof ref === 'string') { - to_ret = value.replace(match, ref); + toRet = value.replace(match, ref); // Recursive so we can compute multi-layer variables like a = b, b = c, so a = c - if (to_ret.indexOf('{') > -1) { - var reference = to_ret.slice(1, -1); - if (stack.indexOf(reference) !== -1) { + if (toRet.includes('{')) { + const reference = toRet.slice(1, -1); + if (stack.includes(reference)) { stack.push(reference); throw new Error( - "Variable reference for '" + - stack[0] + - "' resolves to circular definition cycle of '" + - reference + - "': " + - stack.join(', ') + `Variable reference for '${ + stack[0] + }' resolves to circular definition cycle of '${reference}': ${stack.join(', ')}` ); } else { - to_ret = compile_value(to_ret, stack); + toRet = compileValue(toRet, stack); } } } else { // if evaluated value is not a string, we want to keep the type - to_ret = ref; + toRet = ref; } } else { // Leave the circular reference unchanged - to_ret = value; + toRet = value; } - return to_ret; + return toRet; }); - return to_ret; + return toRet; +} + +function traverseObj(obj) { + const errors = []; + + Object.keys(obj) + .filter(keyToFilter => !(options.ignoreKeys || []).includes(keyToFilter)) + .forEach(key => { + currentContext.push(key); + if (typeof obj[key] === 'object') { + traverseObj(obj[key]); + } else if (typeof obj[key] === 'string' && obj[key].includes('{')) { + try { + /* eslint-disable no-param-reassign */ + obj[key] = compileValue(obj[key], [key]); + } catch (e) { + errors.push(e); + } + } + currentContext.pop(); + }); + + if (errors.length) { + throw new Error( + errors.length === 1 + ? errors[0] + : `Failed due to ${errors.length} errors:\n${errors.join('\n').replace(/Error: /g, '\t')}` + ); + } + + return obj; } function selfRef(string, obj) { - var i, - ref = obj, - array = string.split(options.separator), - context = current_context.join(options.separator); + let i; + let ref = obj; + const array = string.split(options.separator); + const context = currentContext.join(options.separator); - for (i = 0; i < array.length; i++) { + for (i = 0; i < array.length; i += 1) { if (ref[array[i]]) { ref = ref[array[i]]; } else { @@ -140,16 +118,33 @@ function selfRef(string, obj) { // If the reference doesn't change then it means // we didn't find it in the object if (ref === obj) { - throw new Error("Reference doesn't exist: " + context + ' tries to reference ' + string + ', which is not defined'); + throw new Error(`Reference doesn't exist: ${context} tries to reference ${string}, which is not defined`); } - var test = options.opening_character + context + options.closing_character; + const test = options.opening_character + context + options.closing_character; - if (typeof ref === 'string' && ref.indexOf(test) > -1) { - throw new Error('Circular definition: ' + context + ' | ' + string); + if (typeof ref === 'string' && ref.includes(test)) { + throw new Error(`Circular definition: ${context} | ${string}`); } else { return ref; } } +function resolveObject(object, opts) { + options = _.extend({}, defaults, opts); + + updatedObject = _.cloneDeep(object); // This object will be edited + + regex = new RegExp( + `\\${options.opening_character}([^${options.closing_character}]+)\\${options.closing_character}`, + 'g' + ); + + if (typeof object === 'object') { + currentContext = []; + return traverseObj(updatedObject); + } + throw new Error('Please pass an object in'); +} + module.exports = resolveObject; diff --git a/package-lock.json b/package-lock.json index 71ea422e8..1e7acec78 100644 --- a/package-lock.json +++ b/package-lock.json @@ -78,20 +78,12 @@ } }, "acorn-jsx": { - "version": "3.0.1", - "resolved": "http://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", - "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-4.1.1.tgz", + "integrity": "sha512-JY+iV6r+cO21KtntVvFkD+iqjtdpRUpGqKWgfkCdZq1R+kbreEl8EcdcJR4SmiIgsIQT33s6QzheQ9a275Q8xw==", "dev": true, "requires": { - "acorn": "^3.0.4" - }, - "dependencies": { - "acorn": { - "version": "3.3.0", - "resolved": "http://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", - "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=", - "dev": true - } + "acorn": "^5.0.3" } }, "acorn-walk": { @@ -112,12 +104,6 @@ "json-schema-traverse": "^0.3.0" } }, - "ajv-keywords": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=", - "dev": true - }, "amdefine": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", @@ -1774,18 +1760,6 @@ "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" }, - "concat-stream": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "dev": true, - "requires": { - "buffer-from": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^2.2.2", - "typedarray": "^0.0.6" - } - }, "config-master": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/config-master/-/config-master-3.1.0.tgz", @@ -1841,6 +1815,12 @@ "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", "dev": true }, + "contains-path": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", + "integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=", + "dev": true + }, "convert-source-map": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", @@ -2474,72 +2454,153 @@ } }, "eslint": { - "version": "4.19.1", - "resolved": "http://registry.npmjs.org/eslint/-/eslint-4.19.1.tgz", - "integrity": "sha512-bT3/1x1EbZB7phzYu7vCr1v3ONuzDtX8WjuM9c0iYxe+cq+pwcKEoQjl7zd3RpC6YOLgnSy3cTN58M2jcoPDIQ==", + "version": "5.7.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-5.7.0.tgz", + "integrity": "sha512-zYCeFQahsxffGl87U2aJ7DPyH8CbWgxBC213Y8+TCanhUTf2gEvfq3EKpHmEcozTLyPmGe9LZdMAwC/CpJBM5A==", "dev": true, "requires": { - "ajv": "^5.3.0", - "babel-code-frame": "^6.22.0", + "@babel/code-frame": "^7.0.0", + "ajv": "^6.5.3", "chalk": "^2.1.0", - "concat-stream": "^1.6.0", - "cross-spawn": "^5.1.0", - "debug": "^3.1.0", + "cross-spawn": "^6.0.5", + "debug": "^4.0.1", "doctrine": "^2.1.0", - "eslint-scope": "^3.7.1", + "eslint-scope": "^4.0.0", + "eslint-utils": "^1.3.1", "eslint-visitor-keys": "^1.0.0", - "espree": "^3.5.4", - "esquery": "^1.0.0", + "espree": "^4.0.0", + "esquery": "^1.0.1", "esutils": "^2.0.2", "file-entry-cache": "^2.0.0", "functional-red-black-tree": "^1.0.1", "glob": "^7.1.2", - "globals": "^11.0.1", - "ignore": "^3.3.3", + "globals": "^11.7.0", + "ignore": "^4.0.6", "imurmurhash": "^0.1.4", - "inquirer": "^3.0.6", - "is-resolvable": "^1.0.0", - "js-yaml": "^3.9.1", + "inquirer": "^6.1.0", + "is-resolvable": "^1.1.0", + "js-yaml": "^3.12.0", "json-stable-stringify-without-jsonify": "^1.0.1", "levn": "^0.3.0", - "lodash": "^4.17.4", - "minimatch": "^3.0.2", + "lodash": "^4.17.5", + "minimatch": "^3.0.4", "mkdirp": "^0.5.1", "natural-compare": "^1.4.0", "optionator": "^0.8.2", "path-is-inside": "^1.0.2", "pluralize": "^7.0.0", "progress": "^2.0.0", - "regexpp": "^1.0.1", + "regexpp": "^2.0.1", "require-uncached": "^1.0.3", - "semver": "^5.3.0", + "semver": "^5.5.1", "strip-ansi": "^4.0.0", - "strip-json-comments": "~2.0.1", - "table": "4.0.2", - "text-table": "~0.2.0" + "strip-json-comments": "^2.0.1", + "table": "^5.0.2", + "text-table": "^0.2.0" }, "dependencies": { + "ajv": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.5.4.tgz", + "integrity": "sha512-4Wyjt8+t6YszqaXnLDfMmG/8AlO5Zbcsy3ATHncCzjW/NoPzAId8AK6749Ybjmdt+kUY1gP60fCu46oDxPv/mg==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-escapes": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.1.0.tgz", + "integrity": "sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==", + "dev": true + }, "ansi-regex": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", "dev": true }, + "chardet": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", + "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", + "dev": true + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, "debug": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.5.tgz", - "integrity": "sha512-D61LaDQPQkxJ5AUM2mbSJRbPkNs/TmdmOeLAi1hgDkpDfIfetSrjmWhccwtuResSwMbACjx/xXQofvM9CE/aeg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.0.tgz", + "integrity": "sha512-heNPJUJIqC+xB6ayLAMHaIrmN9HKa7aQO8MGqKpvCA+uJYVcvR6l5kgdrhRuwPFHU7P5/A1w0BjByPHwpfTDKg==", "dev": true, "requires": { "ms": "^2.1.1" } }, + "external-editor": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.0.3.tgz", + "integrity": "sha512-bn71H9+qWoOQKyZDo25mOMVpSmXROAsTJVVVYzrrtol3d4y+AsKjf4Iwl2Q+IuT0kFSQ1qo166UuIwqYq7mGnA==", + "dev": true, + "requires": { + "chardet": "^0.7.0", + "iconv-lite": "^0.4.24", + "tmp": "^0.0.33" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, "globals": { "version": "11.8.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.8.0.tgz", "integrity": "sha512-io6LkyPVuzCHBSQV9fmOwxZkUk6nIaGmxheLDgmuFv89j0fm2aqDbIXKAGfzCMHqz3HLF2Zf8WSG6VqMh2qFmA==", "dev": true }, + "inquirer": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-6.2.0.tgz", + "integrity": "sha512-QIEQG4YyQ2UYZGDC4srMZ7BjHOmNk1lR2JQj5UknBapklm6WHA+VVH7N+sUdX3A7NeCfGF8o4X1S3Ao7nAcIeg==", + "dev": true, + "requires": { + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.0", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^3.0.0", + "figures": "^2.0.0", + "lodash": "^4.17.10", + "mute-stream": "0.0.7", + "run-async": "^2.2.0", + "rxjs": "^6.1.0", + "string-width": "^2.1.0", + "strip-ansi": "^4.0.0", + "through": "^2.3.6" + } + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", @@ -2557,6 +2618,17 @@ } } }, + "eslint-config-airbnb-base": { + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/eslint-config-airbnb-base/-/eslint-config-airbnb-base-13.1.0.tgz", + "integrity": "sha512-XWwQtf3U3zIoKO1BbHh6aUhJZQweOwSt4c2JrPDg9FP3Ltv3+YfEv7jIDB8275tVnO/qOHbfuYg3kzw6Je7uWw==", + "dev": true, + "requires": { + "eslint-restricted-globals": "^0.1.1", + "object.assign": "^4.1.0", + "object.entries": "^1.0.4" + } + }, "eslint-config-prettier": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-3.1.0.tgz", @@ -2566,6 +2638,184 @@ "get-stdin": "^6.0.0" } }, + "eslint-import-resolver-node": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.2.tgz", + "integrity": "sha512-sfmTqJfPSizWu4aymbPr4Iidp5yKm8yDkHp+Ir3YiTHiiDfxh69mOUsmiqW6RZ9zRXFaF64GtYmN7e+8GHBv6Q==", + "dev": true, + "requires": { + "debug": "^2.6.9", + "resolve": "^1.5.0" + }, + "dependencies": { + "resolve": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", + "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "dev": true, + "requires": { + "path-parse": "^1.0.5" + } + } + } + }, + "eslint-module-utils": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.2.0.tgz", + "integrity": "sha1-snA2LNiLGkitMIl2zn+lTphBF0Y=", + "dev": true, + "requires": { + "debug": "^2.6.8", + "pkg-dir": "^1.0.0" + }, + "dependencies": { + "pkg-dir": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-1.0.0.tgz", + "integrity": "sha1-ektQio1bstYp1EcFb/TpyTFM89Q=", + "dev": true, + "requires": { + "find-up": "^1.0.0" + } + } + } + }, + "eslint-plugin-import": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.14.0.tgz", + "integrity": "sha512-FpuRtniD/AY6sXByma2Wr0TXvXJ4nA/2/04VPlfpmUDPOpOY264x+ILiwnrk/k4RINgDAyFZByxqPUbSQ5YE7g==", + "dev": true, + "requires": { + "contains-path": "^0.1.0", + "debug": "^2.6.8", + "doctrine": "1.5.0", + "eslint-import-resolver-node": "^0.3.1", + "eslint-module-utils": "^2.2.0", + "has": "^1.0.1", + "lodash": "^4.17.4", + "minimatch": "^3.0.3", + "read-pkg-up": "^2.0.0", + "resolve": "^1.6.0" + }, + "dependencies": { + "doctrine": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz", + "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", + "dev": true, + "requires": { + "esutils": "^2.0.2", + "isarray": "^1.0.0" + } + }, + "find-up": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", + "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", + "dev": true, + "requires": { + "locate-path": "^2.0.0" + } + }, + "load-json-file": { + "version": "2.0.0", + "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", + "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" + } + }, + "locate-path": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", + "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", + "dev": true, + "requires": { + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" + } + }, + "p-limit": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-1.3.0.tgz", + "integrity": "sha512-vvcXsLAJ9Dr5rQOPk7toZQZJApBl2K4J6dANSsEuh6QI41JYcsS/qhTGa9ErIUUgK3WNQoJYvylxvjqmiqEA9Q==", + "dev": true, + "requires": { + "p-try": "^1.0.0" + } + }, + "p-locate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-2.0.0.tgz", + "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", + "dev": true, + "requires": { + "p-limit": "^1.1.0" + } + }, + "p-try": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-1.0.0.tgz", + "integrity": "sha1-y8ec26+P1CKOE/Yh8rGiN8GyB7M=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", + "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", + "dev": true, + "requires": { + "pify": "^2.0.0" + } + }, + "read-pkg": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", + "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", + "dev": true, + "requires": { + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" + } + }, + "read-pkg-up": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", + "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", + "dev": true, + "requires": { + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" + } + }, + "resolve": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.8.1.tgz", + "integrity": "sha512-AicPrAC7Qu1JxPCZ9ZgCZlY35QgFnNqc+0LtbRNxnVw4TXvjQ72wnuL9JQcEBgXkI9JM8MsT9kaQoHcpCRJOYA==", + "dev": true, + "requires": { + "path-parse": "^1.0.5" + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + } + } + }, "eslint-plugin-prettier": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/eslint-plugin-prettier/-/eslint-plugin-prettier-3.0.0.tgz", @@ -2575,16 +2825,28 @@ "prettier-linter-helpers": "^1.0.0" } }, + "eslint-restricted-globals": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/eslint-restricted-globals/-/eslint-restricted-globals-0.1.1.tgz", + "integrity": "sha1-NfDVy8ZMLj7WLpO0saevBbp+1Nc=", + "dev": true + }, "eslint-scope": { - "version": "3.7.3", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.3.tgz", - "integrity": "sha512-W+B0SvF4gamyCTmUc+uITPY0989iXVfKvhwtmJocTaYoc/3khEHmEmvfY/Gn9HA9VV75jrQECsHizkNw1b68FA==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.0.tgz", + "integrity": "sha512-1G6UTDi7Jc1ELFwnR58HV4fK9OQK4S6N985f166xqXxpjU6plxFISJa2Ba9KCQuFa8RCnj/lSFJbHo7UFDBnUA==", "dev": true, "requires": { "esrecurse": "^4.1.0", "estraverse": "^4.1.1" } }, + "eslint-utils": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.3.1.tgz", + "integrity": "sha512-Z7YjnIldX+2XMcjr7ZkgEsOj/bREONV60qYeB/bjMAqqqZ4zxKyWX+BOUkdmRmA9riiIPVvo5x86m5elviOk0Q==", + "dev": true + }, "eslint-visitor-keys": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz", @@ -2592,13 +2854,13 @@ "dev": true }, "espree": { - "version": "3.5.4", - "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.4.tgz", - "integrity": "sha512-yAcIQxtmMiB/jL32dzEp2enBeidsB7xWPLNiw3IIkpVds1P+h7qF9YwJq1yUNzp2OKXgAprs4F61ih66UsoD1A==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-4.0.0.tgz", + "integrity": "sha512-kapdTCt1bjmspxStVKX6huolXVV5ZfyZguY1lcfhVVZstce3bqxH9mcLzNn3/mlgW6wQ732+0fuG9v7h0ZQoKg==", "dev": true, "requires": { - "acorn": "^5.5.0", - "acorn-jsx": "^3.0.0" + "acorn": "^5.6.0", + "acorn-jsx": "^4.1.1" } }, "esprima": { @@ -4105,9 +4367,9 @@ } }, "ignore": { - "version": "3.3.10", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz", - "integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz", + "integrity": "sha512-cyFDKrqc/YdcWFniJhzI42+AzS+gNwmUzOSFcRCQYwySuBBBy/KjuxWLZ/FHEH6Moq1NizMOBWyTcv8O4OZIMg==", "dev": true }, "image-size": { @@ -6935,6 +7197,12 @@ "integrity": "sha512-AO81vsIO1k1sM4Zrd6Hu7regmJN1NSiAja10gc4bX3F0wd+9rQmcuHQaHVQCYIEC8iFXnE+mavh23GOt7wBgug==", "dev": true }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, "node-fetch": { "version": "1.6.3", "resolved": "http://registry.npmjs.org/node-fetch/-/node-fetch-1.6.3.tgz", @@ -7272,6 +7540,30 @@ } } }, + "object.assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" + } + }, + "object.entries": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.0.4.tgz", + "integrity": "sha1-G/mk3SKI9bM/Opk9JXZh8F0WGl8=", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.6.1", + "function-bind": "^1.1.0", + "has": "^1.0.1" + } + }, "object.getownpropertydescriptors": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz", @@ -7762,9 +8054,9 @@ "dev": true }, "progress": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.0.tgz", - "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.1.tgz", + "integrity": "sha512-OE+a6vzqazc+K6LxJrX5UPyKFvGnL5CYmq2jFGNIBWHpc4QyE49/YOumcrpQFJpfejmvRtbJzgO1zPmMCqlbBg==", "dev": true }, "promise": { @@ -8318,9 +8610,9 @@ } }, "regexpp": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-1.1.0.tgz", - "integrity": "sha512-LOPw8FpgdQF9etWMaAfG/WRthIdXJGYp4mJ2Jgn/2lpkbod9jPn0t9UqN7AxBOKNfzRbYyVfgc7Vk4t/MpnXgw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/regexpp/-/regexpp-2.0.1.tgz", + "integrity": "sha512-lv0M6+TkDVniA3aD1Eg0DVpfU/booSu7Eev3TDO/mZKHBfVjgCGTV4t4buppESEYDtkArYFOxTJWv6S5C+iaNw==", "dev": true }, "regexpu-core": { @@ -9553,17 +9845,41 @@ "dev": true }, "table": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/table/-/table-4.0.2.tgz", - "integrity": "sha512-UUkEAPdSGxtRpiV9ozJ5cMTtYiqz7Ni1OGqLXRCynrvzdtR1p+cfOWe2RJLwvUG8hNanaSRjecIqwOjqeatDsA==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/table/-/table-5.1.0.tgz", + "integrity": "sha512-e542in22ZLhD/fOIuXs/8yDZ9W61ltF8daM88rkRNtgTIct+vI2fTnAyu/Db2TCfEcI8i7mjZz6meLq0nW7TYg==", "dev": true, "requires": { - "ajv": "^5.2.3", - "ajv-keywords": "^2.1.0", - "chalk": "^2.1.0", - "lodash": "^4.17.4", + "ajv": "^6.5.3", + "lodash": "^4.17.10", "slice-ansi": "1.0.0", "string-width": "^2.1.1" + }, + "dependencies": { + "ajv": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.5.4.tgz", + "integrity": "sha512-4Wyjt8+t6YszqaXnLDfMmG/8AlO5Zbcsy3ATHncCzjW/NoPzAId8AK6749Ybjmdt+kUY1gP60fCu46oDxPv/mg==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + } } }, "table-layout": { @@ -9830,12 +10146,6 @@ "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", - "dev": true - }, "typical": { "version": "2.6.1", "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", @@ -10023,6 +10333,15 @@ "xdg-basedir": "^3.0.0" } }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, "urix": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", diff --git a/package.json b/package.json index d89173419..67d59988e 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,7 @@ "NOTICE" ], "scripts": { - "lint": "eslint index.js lib/**/*.js test/*.js test/**/*.js", + "lint": "eslint index.js lib/**/*.js __tests__/**/*.js", "test": "npm run prettier:check && npm run lint && jest --runInBand", "prettier:check": "prettier --list-different index.js lib/**/*.js test/**/*.js", "coverage": "istanbul cover ./node_modules/mocha/bin/_mocha -- test/*.js test/**/*.js", @@ -101,8 +101,10 @@ "chai": "^4.1.2", "docsify": "^4.6.10", "docsify-cli": "^4.2.1", - "eslint": "^4.19.1", + "eslint": "^5.7.0", + "eslint-config-airbnb-base": "^13.1.0", "eslint-config-prettier": "^3.1.0", + "eslint-plugin-import": "^2.14.0", "eslint-plugin-prettier": "^3.0.0", "husky": "^1.1.2", "istanbul": "^0.4.5",