Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: migrate to using esms #83

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
29 changes: 29 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @type {import('eslint').Linter.Config}
*/
module.exports = {
extends: [require.resolve('@vercel/style-guide/eslint/node')],
root: true,
reportUnusedDisableDirectives: true,
parserOptions: {
babelOptions: {
plugins: [
[
'@babel/plugin-syntax-import-attributes',
{
deprecatedAssertSyntax: true,
},
],
],
},
},
rules: {},
overrides: [
{
files: 'bin/title.js',
rules: {
'no-console': 'off',
},
},
],
};
17 changes: 12 additions & 5 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,18 @@ jobs:
strategy:
matrix:
node-version:
- 16
- 18
- 20
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v1
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v2
with:
version: 8
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
cache: 'pnpm'
- run: pnpm install
- run: pnpm run test
- run: pnpm run lint
- run: pnpm run format
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.log
node_modules
.vscode
.vscode
dist/
6 changes: 6 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

# Disable concurrency to avoid potential race condition between file editing
# tasks.
pnpm exec lint-staged --concurrent false
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
pnpm-lock.yaml
54 changes: 28 additions & 26 deletions bin/title.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
#!/usr/bin/env node

// Packages
const parse = require('arg')
const { red, grey, blue } = require('chalk')
const clipboardy = require('clipboardy')

// Utilities
const pkg = require('../package')
const convert = require('../')
const help = require('../lib/help')
import parse from 'arg';
import chalk from 'chalk';
import clipboardy from 'clipboardy';
import pkg from '../package.json' assert { type: 'json' };
import convert from '../lib/index.js';
import { helpText } from '../lib/help.js';

// Parse the supplied commands and options
const { _, ...args } = parse({
Expand All @@ -19,44 +17,48 @@ const { _, ...args } = parse({
'-v': '--version',
'-h': '--help',
'-n': '--no-copy',
'-s': '--special'
})
'-s': '--special',
});

// Output the package's version if
// the `--version was supplied
if (args['--version']) {
console.log(pkg.version)
process.exit(0)
console.log(pkg.version);
process.exit(0);
}

if (args['--help']) {
console.log(help)
process.exit(0)
console.log(helpText);
process.exit(0);
}

const main = async () => {
const sub = _.join(' ')
const sub = _.join(' ');

if (!sub) {
console.error(`${red('Error!')} Please specify an input: ${grey('title "input"')}`)
process.exit(1)
console.error(
`${chalk.red('Error!')} Please specify an input: ${chalk.grey(
'title "input"',
)}`,
);
process.exit(1);
}

const specials = args['--special']
const specials = args['--special'];

const output = convert(sub, { specials })
const copy = !args['--no-copy']
const output = convert(sub, { specials });
const copy = !args['--no-copy'];

if (copy) {
try {
await clipboardy.write(output)
await clipboardy.write(output);
} catch (err) {
console.error(`${red('Error!')} Could not write to clipboard`)
process.exit(1)
console.error(`${chalk.red('Error!')} Could not write to clipboard`);
process.exit(1);
}
}

console.log(`${output}${copy ? ' ' + blue('[copied]') : ''}`)
}
console.log(`${output}${copy ? ` ${chalk.blue('[copied]')}` : ''}`);
};

main()
main();
10 changes: 10 additions & 0 deletions build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineBuildConfig } from 'unbuild';

export default defineBuildConfig([
{
entries: ['./lib/index.js', './bin/title.js'],
rollup: {
emitCJS: true,
},
},
]);
16 changes: 8 additions & 8 deletions lib/help.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// Packages
const { yellow, grey } = require('chalk')
import chalk from 'chalk';

module.exports = `
Usage: ${yellow('title')} [options] <input>
export const helpText = `
Usage: ${chalk.yellow('title')} [options] <input>

Options:

${yellow('-h, --help')} Show the usage information
${yellow('-v, --version')} Show the version number
${yellow('-s, --special')} Words to capitalize as they are passed
${yellow('-n, --no-copy')} Don't copy output to clipboard
`
${chalk.yellow('-h, --help')} Show the usage information
${chalk.yellow('-v, --version')} Show the version number
${chalk.yellow('-s, --special')} Words to capitalize as they are passed
${chalk.yellow('-n, --no-copy')} Don't copy output to clipboard
`;
69 changes: 38 additions & 31 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,54 +1,61 @@
// Utilities
const lowerCase = require('./lower-case')
const specials = require('./specials')
import { lowerCaseWords } from './lower-case.js';
import { specials } from './specials.js';

const word = "[^\\s'’\\(\\)!?;:\"-]"
const regex = new RegExp(`(?:(?:(\\s?(?:^|[.\\(\\)!?;:"-])\\s*)(${word}))|(${word}))(${word}*[’']*${word}*)`, "g")
const word = '[^\\s\'’\\(\\)!?;:"-]';
const regex = new RegExp(
`(?:(?:(\\s?(?:^|[.\\(\\)!?;:"-])\\s*)(${word}))|(${word}))(${word}*[’']*${word}*)`,
'g',
);

const convertToRegExp = specials => specials.map(s => [new RegExp(`\\b${s}\\b`, 'gi'), s])
const convertToRegExp = (specials) =>
specials.map((s) => [new RegExp(`\\b${s}\\b`, 'gi'), s]);

function parseMatch(match) {
const firstCharacter = match[0]
const firstCharacter = match[0];

// test first character
if (/\s/.test(firstCharacter)) {
// if whitespace - trim and return
return match.slice(1)
return match.slice(1);
}
if (/[\(\)]/.test(firstCharacter)) {
if (/[()]/.test(firstCharacter)) {
// if parens - this shouldn't be replaced
return null
return null;
}

return match
return match;
}

module.exports = (str, options = {}) => {
str = str.toLowerCase().replace(regex, (m, lead = '', forced, lower, rest, offset, string) => {
const isLastWord = m.length + offset >= string.length;
// eslint-disable-next-line import/no-default-export -- Fixing the issue would be a breaking change.
export default (str, options = {}) => {
let title = str
.toLowerCase()
.replace(regex, (m, lead = '', forced, lower, rest, offset, string) => {
const isLastWord = m.length + offset >= string.length;

const parsedMatch = parseMatch(m)
if (!parsedMatch) {
return m
}
if (!forced) {
const fullLower = lower + rest
const parsedMatch = parseMatch(m);
if (!parsedMatch) {
return m;
}
if (!forced) {
const fullLower = lower + rest;

if (lowerCase.has(fullLower) && !isLastWord) {
return parsedMatch
if (lowerCaseWords.has(fullLower) && !isLastWord) {
return parsedMatch;
}
}
}

return lead + (lower || forced).toUpperCase() + rest
})
return lead + (lower || forced).toUpperCase() + rest;
});

const customSpecials = options.special || []
const replace = [...specials, ...customSpecials]
const replaceRegExp = convertToRegExp(replace)
const customSpecials = options.special || [];
const replace = [...specials, ...customSpecials];
const replaceRegExp = convertToRegExp(replace);

replaceRegExp.forEach(([pattern, s]) => {
str = str.replace(pattern, s)
})
title = title.replace(pattern, s);
});

return str
}
return title;
};
26 changes: 7 additions & 19 deletions lib/lower-case.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
const conjunctions = [
'for',
'and',
'nor',
'but',
'or',
'yet',
'so'
]
const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];

const articles = [
'a',
'an',
'the'
]
const articles = ['a', 'an', 'the'];

const prepositions = [
'aboard',
Expand Down Expand Up @@ -83,11 +71,11 @@ const prepositions = [
'via',
'with',
'within',
'without'
]
'without',
];

module.exports = new Set([
export const lowerCaseWords = new Set([
...conjunctions,
...articles,
...prepositions
])
...prepositions,
]);
8 changes: 3 additions & 5 deletions lib/specials.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const intended = [
export const specials = [
'ZEIT',
'ZEIT Inc.',
'Vercel',
Expand Down Expand Up @@ -57,7 +57,5 @@ const intended = [
'GraphQL',
'GraphiQL',
'JWT',
'JWTs'
]

module.exports = intended
'JWTs',
];
8 changes: 8 additions & 0 deletions lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* @type {import('lint-staged').Config}
*/
// eslint-disable-next-line import/no-default-export -- The tool expects a default export.
export default {
'*': 'pnpm run format --write',
'*.js': 'pnpm run lint-js --fix',
};
Loading