From dacfa55c829d07ff29182f4d7b098b1bf1bd4759 Mon Sep 17 00:00:00 2001 From: Aaron Francis Date: Thu, 26 Aug 2021 17:23:16 -0500 Subject: [PATCH] Switch everything to ECMAScript modules --- .gitignore | 3 +- index.js | 9 +- jest.config.js | 194 ------------------------------------ package.json | 41 ++++++-- src/bin/torchlight.js | 4 + src/block.js | 20 ++-- src/cache/file.js | 28 ++---- src/cache/memory.js | 4 +- src/cli.js | 39 +++----- src/commands/cache/clear.js | 2 +- src/commands/highlight.js | 30 +++--- src/commands/init.js | 18 ++-- src/support/bus.js | 9 +- src/support/guid.js | 2 +- src/support/log.js | 14 ++- src/torchlight.js | 26 ++--- tests/highlight.test.js | 6 +- tests/support/helpers.js | 8 +- 18 files changed, 137 insertions(+), 320 deletions(-) delete mode 100644 jest.config.js create mode 100755 src/bin/torchlight.js diff --git a/.gitignore b/.gitignore index c2659c5..9615802 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ torchlight.config.js -source -built +lib .idea node_modules tests/tmp diff --git a/index.js b/index.js index a8ed3a1..7aeb2f9 100755 --- a/index.js +++ b/index.js @@ -1,4 +1,7 @@ -#! /usr/bin/env node -const { makeProgram } = require('./src/cli') +import torchlight from './src/torchlight' +import Block from './src/block' -makeProgram().parse() +export { + torchlight, + Block +} diff --git a/jest.config.js b/jest.config.js deleted file mode 100644 index 042b4c4..0000000 --- a/jest.config.js +++ /dev/null @@ -1,194 +0,0 @@ -/* - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ - -module.exports = { - // All imported modules in your tests should be mocked automatically - // automock: false, - - // Stop running tests after `n` failures - // bail: 0, - - // The directory where Jest should store its cached dependency information - // cacheDirectory: "/private/var/folders/j1/5f7lqrt121d60r8q0rsxqtm00000gn/T/jest_dx", - - // Automatically clear mock calls and instances between every test - clearMocks: true, - - // Indicates whether the coverage information should be collected while executing the test - // collectCoverage: false, - - // An array of glob patterns indicating a set of files for which coverage information should be collected - // collectCoverageFrom: undefined, - - // The directory where Jest should output its coverage files - // coverageDirectory: undefined, - - // An array of regexp pattern strings used to skip coverage collection - // coveragePathIgnorePatterns: [ - // "/node_modules/" - // ], - - // Indicates which provider should be used to instrument code for coverage - coverageProvider: 'v8' - - // A list of reporter names that Jest uses when writing coverage reports - // coverageReporters: [ - // "json", - // "text", - // "lcov", - // "clover" - // ], - - // An object that configures minimum threshold enforcement for coverage results - // coverageThreshold: undefined, - - // A path to a custom dependency extractor - // dependencyExtractor: undefined, - - // Make calling deprecated APIs throw helpful error messages - // errorOnDeprecated: false, - - // Force coverage collection from ignored files using an array of glob patterns - // forceCoverageMatch: [], - - // A path to a module which exports an async function that is triggered once before all test suites - // globalSetup: undefined, - - // A path to a module which exports an async function that is triggered once after all test suites - // globalTeardown: undefined, - - // A set of global variables that need to be available in all test environments - // globals: {}, - - // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. - // maxWorkers: "50%", - - // An array of directory names to be searched recursively up from the requiring module's location - // moduleDirectories: [ - // "node_modules" - // ], - - // An array of file extensions your modules use - // moduleFileExtensions: [ - // "js", - // "jsx", - // "ts", - // "tsx", - // "json", - // "node" - // ], - - // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module - // moduleNameMapper: {}, - - // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader - // modulePathIgnorePatterns: [], - - // Activates notifications for test results - // notify: false, - - // An enum that specifies notification mode. Requires { notify: true } - // notifyMode: "failure-change", - - // A preset that is used as a base for Jest's configuration - // preset: undefined, - - // Run tests from one or more projects - // projects: undefined, - - // Use this configuration option to add custom reporters to Jest - // reporters: undefined, - - // Automatically reset mock state between every test - // resetMocks: false, - - // Reset the module registry before running each individual test - // resetModules: false, - - // A path to a custom resolver - // resolver: undefined, - - // Automatically restore mock state between every test - // restoreMocks: false, - - // The root directory that Jest should scan for tests and modules within - // rootDir: undefined, - - // A list of paths to directories that Jest should use to search for files in - // roots: [ - // "" - // ], - - // Allows you to use a custom runner instead of Jest's default test runner - // runner: "jest-runner", - - // The paths to modules that run some code to configure or set up the testing environment before each test - // setupFiles: [], - - // A list of paths to modules that run some code to configure or set up the testing framework before each test - // setupFilesAfterEnv: [], - - // The number of seconds after which a test is considered as slow and reported as such in the results. - // slowTestThreshold: 5, - - // A list of paths to snapshot serializer modules Jest should use for snapshot testing - // snapshotSerializers: [], - - // The test environment that will be used for testing - // testEnvironment: "jest-environment-node", - - // Options that will be passed to the testEnvironment - // testEnvironmentOptions: {}, - - // Adds a location field to test results - // testLocationInResults: false, - - // The glob patterns Jest uses to detect test files - // testMatch: [ - // "**/__tests__/**/*.[jt]s?(x)", - // "**/?(*.)+(spec|test).[tj]s?(x)" - // ], - - // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped - // testPathIgnorePatterns: [ - // "/node_modules/" - // ], - - // The regexp pattern or array of patterns that Jest uses to detect test files - // testRegex: [], - - // This option allows the use of a custom results processor - // testResultsProcessor: undefined, - - // This option allows use of a custom test runner - // testRunner: "jest-circus/runner", - - // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href - // testURL: "http://localhost", - - // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" - // timers: "real", - - // A map from regular expressions to paths to transformers - // transform: undefined, - - // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation - // transformIgnorePatterns: [ - // "/node_modules/", - // "\\.pnp\\.[^\\/]+$" - // ], - - // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them - // unmockedModulePathPatterns: undefined, - - // Indicates whether each individual test should be reported during the run - // verbose: undefined, - - // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode - // watchPathIgnorePatterns: [], - - // Whether to use watchman for file crawling - // watchman: true, -} diff --git a/package.json b/package.json index db77833..3726dd7 100644 --- a/package.json +++ b/package.json @@ -1,24 +1,20 @@ { "name": "@torchlight-api/torchlight-cli", - "version": "0.0.8", + "version": "0.1.0", "description": "A CLI for Torchlight - the syntax highlighting API", "main": "index.js", "scripts": { - "test": "standard --env jest && jest" + "test": "standard --env jest && jest", + "build": "babel src --out-dir lib --copy-files \"--ignore\" \"src/stubs/**/*\"" }, "bin": { - "torchlight": "index.js" + "torchlight": "lib/bin/torchlight.js" }, "keywords": [ "syntax", "highlighting", "torchlight" ], - "standard": { - "ignore": [ - "tests" - ] - }, "author": "Aaron Francis (https://torchlight.dev)", "license": "MIT", "dependencies": { @@ -34,7 +30,36 @@ "md5": "^2.3.0" }, "devDependencies": { + "@babel/preset-env": "^7.15.0", + "@babel/cli": "^7.14.8", + "@babel/core": "^7.15.0", + "@babel/node": "^7.12.13", + "babel-jest": "^27.0.6", "jest": "^27.0.6", "standard": "^16.0.3" + }, + "standard": { + "ignore": [ + "tests", + "lib" + ] + }, + "jest": { + "clearMocks": true, + "transform": { + "^.+\\.[t|j]sx?$": "babel-jest" + } + }, + "babel": { + "presets": [ + [ + "@babel/preset-env", + { + "targets": { + "node": "12.13.0" + } + } + ] + ] } } diff --git a/src/bin/torchlight.js b/src/bin/torchlight.js new file mode 100755 index 0000000..10ac0e5 --- /dev/null +++ b/src/bin/torchlight.js @@ -0,0 +1,4 @@ +#! /usr/bin/env node +import { makeProgram } from '../cli' + +makeProgram().parse() diff --git a/src/block.js b/src/block.js index 2b5f845..9e3e8d4 100644 --- a/src/block.js +++ b/src/block.js @@ -1,8 +1,8 @@ -const md5 = require('md5') -const guid = require('./support/guid') -const torchlight = require('./torchlight') +import md5 from 'md5' +import guid from './support/guid' +import torchlight from './torchlight' -const Block = function (opts = {}) { +export default function Block (opts = {}) { opts = { id: guid(), theme: torchlight.config('theme', 'nord'), @@ -21,11 +21,11 @@ const Block = function (opts = {}) { Block.prototype.hash = function () { return md5('' + - this.language + - this.theme + - this.code + - torchlight.config('bust', 0) + - JSON.stringify(torchlight.config('options')) + this.language + + this.theme + + this.code + + torchlight.config('bust', 0) + + JSON.stringify(torchlight.config('options')) ) } @@ -74,5 +74,3 @@ Block.prototype.toRequestParams = function () { code: this.code } } - -module.exports = Block diff --git a/src/cache/file.js b/src/cache/file.js index 6004271..b0a4c2c 100644 --- a/src/cache/file.js +++ b/src/cache/file.js @@ -1,25 +1,19 @@ -const md5 = require('md5') -const path = require('path') -const { - readJsonSync, - writeJsonSync, - ensureDirSync, - pathExistsSync, - removeSync -} = require('fs-extra') +import md5 from 'md5' +import path from 'path' +import fs from 'fs-extra' /** * @param options * @constructor */ -const File = function (options = {}) { +export default function File (options = {}) { if (!options.directory) { throw new Error('No cache directory specified.') } this.directory = path.resolve(options.directory) - ensureDirSync(this.directory) + fs.ensureDirSync(this.directory) } /** @@ -30,11 +24,11 @@ const File = function (options = {}) { * @return {*} */ File.prototype.get = function (key, def) { - if (!pathExistsSync(this.filename(key))) { + if (!fs.pathExistsSync(this.filename(key))) { return def } - const entry = readJsonSync(this.filename(key)) + const entry = fs.readJsonSync(this.filename(key)) if (Date.now() / 1000 > entry.expires) { this.delete(key) @@ -53,7 +47,7 @@ File.prototype.get = function (key, def) { * @param {number} ttlSeconds */ File.prototype.set = function (key, value, ttlSeconds = 60 * 24 * 7) { - writeJsonSync(this.filename(key), { + fs.writeJsonSync(this.filename(key), { expires: (Date.now() / 1000) + ttlSeconds, value: value }) @@ -65,14 +59,14 @@ File.prototype.set = function (key, value, ttlSeconds = 60 * 24 * 7) { * @param key */ File.prototype.delete = function (key) { - removeSync(this.filename(key)) + fs.removeSync(this.filename(key)) } /** * Clear the cache. */ File.prototype.clear = function () { - removeSync(this.directory) + fs.removeSync(this.directory) } /** @@ -82,5 +76,3 @@ File.prototype.clear = function () { File.prototype.filename = function (key) { return path.join(this.directory, md5(key) + '.json') } - -module.exports = File diff --git a/src/cache/memory.js b/src/cache/memory.js index 05121fa..95b69a1 100644 --- a/src/cache/memory.js +++ b/src/cache/memory.js @@ -1,6 +1,6 @@ let store = {} -const Memory = function () { +export default function Memory () { // } @@ -56,5 +56,3 @@ Memory.prototype.delete = function (key) { Memory.prototype.clear = function () { store = {} } - -module.exports = Memory diff --git a/src/cli.js b/src/cli.js index 4f0b648..5444593 100644 --- a/src/cli.js +++ b/src/cli.js @@ -1,5 +1,8 @@ -const { program } = require('commander') -const torchlight = require('./torchlight') +import { program } from 'commander' +import torchlight from './torchlight' +import highlight from './commands/highlight' +import init from './commands/init' +import cacheClear from './commands/cache/clear' /** * Configure the commander CLI application. @@ -7,7 +10,7 @@ const torchlight = require('./torchlight') * @param options * @return {Command} */ -function makeProgram (options = {}) { +export function makeProgram (options = {}) { if (options?.testing) { // Don't exit when there are errors, so we // can catch them. @@ -30,7 +33,7 @@ function makeProgram (options = {}) { torchlight.init(thisCommand.opts().config) }) - makeCommand('_default_') + makeCommand('_default_', highlight) .description('Highlight code blocks in source files') .option( '-i, --input ', @@ -43,26 +46,26 @@ function makeProgram (options = {}) { .option( '-n, --include ', 'Glob patterns used to search for source files. Separate ' + - 'multiple patterns with commas. Defaults to "**/*.htm,**/*.html".' + 'multiple patterns with commas. Defaults to "**/*.htm,**/*.html".' ) .option( '-x, --exclude ', 'String patterns to ignore (not globs). Separate multiple ' + - 'patterns with commas. Defaults to "/node_modules/,/vendor/".' + 'patterns with commas. Defaults to "/node_modules/,/vendor/".' ) .option( '-w, --watch', 'Watch source files for changes.' ) - makeCommand('init') + makeCommand('init', init) .description('Publish the Torchlight configuration file.') .option( '-p, --path ', 'Location for the configuration file.' ) - makeCommand('cache:clear') + makeCommand('cache:clear', cacheClear) .description('Clear the cache') return program @@ -74,7 +77,7 @@ function makeProgram (options = {}) { * @param args * @param opts */ -function testCli (args, opts) { +export function testCli (args, opts) { // https://github.com/shadowspawn/forest-arborist/blob/master/src/command.ts#L345 return makeProgram({ ...opts, @@ -88,25 +91,14 @@ function testCli (args, opts) { * @param name * @return {Command} */ -function makeCommand (name) { +function makeCommand (name, handler) { let cmd = program - let action = name - if (name === '_default_') { - // The default command has a handler at - // highlight.js, and no command name. - action = 'highlight' - } else { + if (name !== '_default_') { // Name the other commands. cmd = cmd.command(name) } - // Namespaced command convention. E.g. The config:cache - // command has a handler at config/cache.js. - action = action.replace(':', '/') - - const handler = require(`./commands/${action}`) - // Add a little shim around the handler so we can pass the // torchlight variable in, just for convenience. cmd.action(function (options) { @@ -120,6 +112,3 @@ function makeCommand (name) { 'Path to the Torchlight configuration file.' ) } - -exports.testCli = testCli -exports.makeProgram = makeProgram diff --git a/src/commands/cache/clear.js b/src/commands/cache/clear.js index 2450126..a958959 100644 --- a/src/commands/cache/clear.js +++ b/src/commands/cache/clear.js @@ -1,3 +1,3 @@ -module.exports = function (torchlight, options) { +export default function (torchlight, options) { torchlight.cache.clear() } diff --git a/src/commands/highlight.js b/src/commands/highlight.js index f94fa6e..ae62cc6 100644 --- a/src/commands/highlight.js +++ b/src/commands/highlight.js @@ -1,13 +1,13 @@ -const { readFileSync, writeFileSync, ensureFileSync } = require('fs-extra') -const path = require('path') -const torchlight = require('../torchlight') -const Block = require('../block') -const cheerio = require('cheerio').default -const chokidar = require('chokidar') -const log = require('../support/log') -const { bus, FILE_WATCHING_COMPLETE } = require('../support/bus') - -module.exports = function (torchlight, options) { +import path from 'path' +import torchlight from '../torchlight' +import Block from '../block' +import cheerio from 'cheerio' +import chokidar from 'chokidar' +import log from '../support/log' +import fs from 'fs-extra' +import { bus, FILE_WATCHING_COMPLETE } from '../support/bus' + +export default function (torchlight, options) { options = { input: torchlight.config('highlight.input', ''), output: torchlight.config('highlight.output', ''), @@ -41,18 +41,18 @@ module.exports = function (torchlight, options) { log.info('Highlighting %s', file) - const source = readFileSync(path.join(input, file), 'utf-8') + const source = fs.readFileSync(path.join(input, file), 'utf-8') highlight(torchlight, source).then(highlighted => { const destination = path.join(output, file) - ensureFileSync(destination) - if (highlighted === readFileSync(destination, 'utf-8')) { + fs.ensureFileSync(destination) + if (highlighted === fs.readFileSync(destination, 'utf-8')) { return } log.info('Writing to %s', destination) - writeFileSync(destination, highlighted, 'utf-8') + fs.writeFileSync(destination, highlighted, 'utf-8') }) }) @@ -191,7 +191,7 @@ function decipherFromElement ($el) { const classes = ($el.attr('class') || '') .split(' ') - // These classes are commonly used to denote code languages. + // These classes are commonly used to denote code languages. .filter(c => c.startsWith('language-') || c.startsWith('lang-')) .map(c => c.replace('language-', '').replace('lang-', '')) diff --git a/src/commands/init.js b/src/commands/init.js index 99fa835..1e188c8 100644 --- a/src/commands/init.js +++ b/src/commands/init.js @@ -1,18 +1,18 @@ -const { writeFileSync, existsSync, readFileSync, ensureFileSync } = require('fs-extra') -const path = require('path') -const inquirer = require('inquirer') -const log = require('../support/log') +import fs from 'fs-extra' +import path from 'path' +import inquirer from 'inquirer' +import log from '../support/log' function write (location) { const source = path.resolve(path.join(__dirname, '../stubs/config.js')) - const stub = readFileSync(source, 'utf-8') + const stub = fs.readFileSync(source, 'utf-8') - ensureFileSync(location) - writeFileSync(location, stub) + fs.ensureFileSync(location) + fs.writeFileSync(location, stub) log.info('File written to %s', location) } -module.exports = function (torchlight, options) { +export default function (torchlight, options) { options = { path: 'torchlight.config.js', ...options @@ -20,7 +20,7 @@ module.exports = function (torchlight, options) { const location = path.resolve(options.path) - if (!existsSync(location)) { + if (!fs.existsSync(location)) { return write(location) } diff --git a/src/support/bus.js b/src/support/bus.js index 080904c..5e520f0 100644 --- a/src/support/bus.js +++ b/src/support/bus.js @@ -1,8 +1,5 @@ -const EventEmitter = require('events').EventEmitter +import { EventEmitter } from 'events' -module.exports = { - bus: new EventEmitter(), +export const bus = new EventEmitter() - // Event names - FILE_WATCHING_COMPLETE: 1 -} +export const FILE_WATCHING_COMPLETE = 1 diff --git a/src/support/guid.js b/src/support/guid.js index 20a4e5f..7cb5ae7 100644 --- a/src/support/guid.js +++ b/src/support/guid.js @@ -1,4 +1,4 @@ -module.exports = function guid () { +export default function guid () { const S4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`.toLowerCase() } diff --git a/src/support/log.js b/src/support/log.js index 8674955..3abc1df 100644 --- a/src/support/log.js +++ b/src/support/log.js @@ -1,4 +1,4 @@ -const chalk = require('chalk') +import chalk from 'chalk' let silent = false function log (fn, args) { @@ -9,14 +9,20 @@ function log (fn, args) { } } -exports.error = function error () { +function error () { log(chalk.bold.bgRed, arguments) } -exports.info = function error () { +function info () { log(chalk.green, arguments) } -exports.silence = function (silence = true) { +function silence (silence = true) { silent = silence } + +export default { + error, + info, + silence +} diff --git a/src/torchlight.js b/src/torchlight.js index 006a4fa..28d1eb0 100644 --- a/src/torchlight.js +++ b/src/torchlight.js @@ -1,14 +1,14 @@ -const axios = require('axios') -const FileCache = require('./cache/file') -const MemoryCache = require('./cache/memory') -const { readJsonSync, pathExistsSync } = require('fs-extra') -const path = require('path') -const md5 = require('md5') -const get = require('lodash.get') -const chunk = require('lodash.chunk') -const log = require('./support/log') - -const VERSION = readJsonSync(path.resolve('package.json')).version +import axios from 'axios' +import FileCache from './cache/file' +import fs from 'fs-extra' +import MemoryCache from './cache/memory' +import path from 'path' +import md5 from 'md5' +import get from 'lodash.get' +import chunk from 'lodash.chunk' +import log from './support/log' + +const VERSION = fs.readJsonSync(path.resolve('package.json')).version /** * @constructor @@ -68,7 +68,7 @@ Torchlight.prototype.normalizeConfiguration = function (config) { // Allow the developer to pass another path to us. if (typeof config === 'string') { - config = pathExistsSync(path.resolve(config)) ? require(path.resolve(config)) : {} + config = fs.pathExistsSync(path.resolve(config)) ? require(path.resolve(config)) : {} } if (process.env.TORCHLIGHT_TOKEN && !config.token) { @@ -220,4 +220,4 @@ function htmlEntities (str) { return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') } -module.exports = new Torchlight() +export default new Torchlight() diff --git a/tests/highlight.test.js b/tests/highlight.test.js index 894b2d3..d4952de 100644 --- a/tests/highlight.test.js +++ b/tests/highlight.test.js @@ -1,6 +1,6 @@ -const torchlight = require('../src/torchlight') -const { mockApi, fixture } = require('./support/helpers') -const log = require('../src/support/log') +import torchlight from '../src/torchlight'; +import {mockApi, fixture} from './support/helpers'; +import log from '../src/support/log'; process.env.TORCHLIGHT_TOKEN = 'test' diff --git a/tests/support/helpers.js b/tests/support/helpers.js index 12359b5..4d9b6f6 100644 --- a/tests/support/helpers.js +++ b/tests/support/helpers.js @@ -1,7 +1,7 @@ -const { bus, FILE_WATCHING_COMPLETE } = require('../../src/support/bus') -const { testCli } = require('../../src/cli') -const { readFileSync } = require('fs-extra') -const torchlight = require('../../src/torchlight') +import { bus, FILE_WATCHING_COMPLETE } from '../../src/support/bus' +import { testCli } from '../../src/cli' +import { readFileSync } from 'fs-extra' +import torchlight from '../../src/torchlight' function fixture (file, callback, options = {}) { options = {