Skip to content

Commit

Permalink
feat: migrate to esmodules
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Require node >= 14.16 & ESM support
- Require Node.js 14.16 or greater
- This package is now pure ESM. Please [read this](codfi.sh/esm).

Closes #3
  • Loading branch information
codfish committed Aug 12, 2022
1 parent f5d9d34 commit 6d079b5
Show file tree
Hide file tree
Showing 9 changed files with 95 additions and 64 deletions.
5 changes: 0 additions & 5 deletions .github/workflows/validate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,6 @@ jobs:
- name: lint js
run: npm run lint

- name: build
run: npm run build
env:
CI: true

- name: run tests
run: npm run test
env:
Expand Down
8 changes: 8 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import jestConfig from 'cod-scripts/jest.js';

export default Object.assign(jestConfig, {
// make esmodules work
moduleNameMapper: {
'#(.*)': '<rootDir>/node_modules/$1',
},
});
24 changes: 12 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,52 +9,52 @@
"url": "https://codfish.io"
},
"files": [
"dist"
"src"
],
"bin": {
"vercel-redirects": "dist/cli.js"
"vercel-redirects": "src/cli.js"
},
"main": "dist/index.js",
"type": "module",
"exports": "./src/index.js",
"keywords": [],
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.9.2",
"chalk": "^5.0.1",
"commander": "^9.4.0",
"find-up": "^4.1.0",
"load-json-file": "^6.2.0",
"find-up": "^6.3.0",
"load-json-file": "^7.0.1",
"normalizr": "^3.6.0",
"vercel": "^27.4.0",
"write-json-file": "^4.3.0"
"write-json-file": "^5.0.0"
},
"devDependencies": {
"cod-scripts": "^10.0.0",
"husky": "^8.0.0"
},
"engines": {
"node": ">=14",
"node": ">=14.16",
"npm": ">=6"
},
"repository": {
"type": "git",
"url": "https://github.com/codfish/vercel-redirects.git"
},
"scripts": {
"build": "cod-scripts build",
"build:watch": "npm run build -- --watch --verbose",
"format": "cod-scripts format",
"lint": "cod-scripts lint",
"lint:commit": "cod-scripts commitlint",
"test": "cod-scripts test",
"shorten": "node dist/cli.js",
"test": "NODE_OPTIONS=--experimental-vm-modules cod-scripts test",
"shorten": "node src/cli.js",
"prepare": "husky install"
},
"eslintConfig": {
"extends": [
"./node_modules/cod-scripts/eslint.js"
],
"rules": {
"no-console": "off"
"no-console": "off",
"import/extensions": "off"
}
}
}
12 changes: 12 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vercel Redirects</title>
</head>
<body>
<p>Testing [vercel-redirects](https://github.com/codfish/vercel-redirects).</p>
</body>
</html>
2 changes: 1 addition & 1 deletion src/__tests__/utils.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const utils = require('../utils');
import * as utils from '../utils';

it('utils should be tested', () => {
expect(utils).toBeDefined();
Expand Down
17 changes: 12 additions & 5 deletions src/cli.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
#!/usr/bin/env node

const { program } = require('commander');
const add = require('./commands/add');
const { parseStatusCode } = require('./utils');
const { name, version } = require('../package.json');
import { program } from 'commander';
import { createRequire } from 'module';
import add from './commands/add.js';
import { parseStatusCode } from './utils.js';

program.name(name).version(version, '-v, --version', 'Output the current version.');
// Possible alternative in future:
// import packageJson from '../package.json' assert { type: 'json' };
const esmRequire = createRequire(import.meta.url);
const packageJson = esmRequire('../package.json');

program
.name(packageJson.name)
.version(packageJson.version, '-v, --version', 'Output the current version.');

/**
* Add a new redirect.
Expand Down
11 changes: 6 additions & 5 deletions src/commands/add.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const path = require('path');
const chalk = require('chalk');
const {
import chalk from 'chalk';
import path from 'path';
import {
loadConfig,
loadVercelConfig,
writeVercelConfig,
gitPull,
gitCommitAndPush,
shorten,
validateUniqueness,
} = require('../utils');
} from '../utils.js';

/**
* Add a new redirect to your Vercel project configuration.
Expand All @@ -33,6 +33,7 @@ async function add(destination, source, options = {}) {
const config = await loadConfig();
const [vercelConfigPath, vercelConfig] = await loadVercelConfig();
const cwd = path.dirname(vercelConfigPath);
vercelConfig.redirects = vercelConfig.redirects || [];

validateUniqueness(source, vercelConfig.redirects);

Expand Down Expand Up @@ -68,4 +69,4 @@ async function add(destination, source, options = {}) {
return redirect;
}

module.exports = add;
export default add;
4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
const add = require('./commands/add');
import add from './commands/add';

module.exports = { add };
export default { add };
76 changes: 42 additions & 34 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
const crypto = require('crypto');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const loadJsonFile = require('load-json-file');
const writeJsonFile = require('write-json-file');
const findUp = require('find-up');
import childProcess from 'child_process';
import crypto from 'crypto';
import util from 'util';
import { loadJsonFile } from 'load-json-file';
import { writeJsonFile } from 'write-json-file';
import { findUp } from 'find-up';
import chalk from 'chalk';

function parseStatusCode(code) {
const exec = util.promisify(childProcess.exec);

export function parseStatusCode(code) {
const codeInt = parseInt(code, 10);
if (codeInt < 301 || codeInt > 308) {
console.error(`error: invalid status code ${code}`);
Expand All @@ -17,7 +20,7 @@ function parseStatusCode(code) {
/**
* Load vercel-redirects cli configuration.
*/
async function loadConfig() {
export async function loadConfig() {
const pkgPath = await findUp('package.json');
const pkg = pkgPath ? await loadJsonFile(pkgPath) : {};

Expand All @@ -30,62 +33,67 @@ async function loadConfig() {
return config || { autoPush: false };
}

/**
* Load vercel.json configuration.
*/
async function loadVercelConfig() {
const configPath = await findUp(['vercel.json', 'now.json']);
const config = await loadJsonFile(configPath);
return [configPath, config];
}

/**
* Write to vercel.json configuration.
*
* @param {object} config - Full vercel.json config object.
* @param {object} configPath - Full path to configuration file.
* @param {object} [configPath] - Full path to configuration file.
*/
async function writeVercelConfig(config, configPath) {
export async function writeVercelConfig(config, configPath) {
let path = configPath;
if (!path) {
path = await findUp(['vercel.json', 'now.json']);
}
return writeJsonFile(path, config, { indent: ' ', detectIndent: true });
}

function gitPull(cwd) {
/**
* Load vercel.json configuration.
*/
export async function loadVercelConfig() {
const configPath = await findUp(['vercel.json', 'now.json']);
if (!configPath) {
console.warn(
'\n',
chalk.yellow(
`[vercel-redirects]: Could not find vercel config file. Creating ${chalk.cyan(
'vercel.json',
)}.`,
),
'\n',
);
const pkgPath = await findUp('package.json');
const path = pkgPath.replace('package.json', 'vercel.json');
const config = { redirects: [] };
await writeVercelConfig(config, path);
return [path, config];
}
const config = await loadJsonFile(configPath);
return [configPath, config];
}

export function gitPull(cwd) {
return exec('git pull', { stdio: 'inherit', cwd });
}

async function gitCommitAndPush(message = 'feat: new redirect', cwd) {
export async function gitCommitAndPush(message = 'feat: new redirect', cwd) {
await exec(`git commit -am "${message}"`, { stdio: 'inherit', cwd });
await exec('git push', { stdio: 'inherit', cwd });
}

async function shorten(longUrl) {
export async function shorten(longUrl) {
return `/${await crypto
.createHash('md5')
.update(longUrl + Date.now())
.digest('hex')
.substring(0, 4)}`;
}

function validateUniqueness(source, redirects) {
export function validateUniqueness(source, redirects = []) {
const existingRedirect = redirects.find(redirect => redirect.source === source);
if (existingRedirect) {
console.error(`error: ${source} already redirects to ${existingRedirect.destination}`);
process.exit(1);
}
return true;
}

module.exports = {
parseStatusCode,
loadConfig,
loadVercelConfig,
writeVercelConfig,
gitPull,
gitCommitAndPush,
shorten,
validateUniqueness,
};

0 comments on commit 6d079b5

Please sign in to comment.