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

chore: migrate tools to TypeScript #296

Merged
merged 14 commits into from
May 17, 2019
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ package-lock.json
build/
.eslintcache
!packages/cli/src/commands/init/__fixtures__/editTemplate/node_modules
*.tsbuildinfo
11 changes: 10 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
module.exports = {
babelrcRoots: ['packages/*'],
overrides: [
{
presets: ['@babel/preset-flow'],
test: '**/*.js',
},
{
presets: ['@babel/preset-typescript'],
test: '**/*.ts',
},
],
presets: [
[
require.resolve('@babel/preset-env'),
Expand All @@ -8,7 +18,6 @@ module.exports = {
useBuiltIns: 'entry',
},
],
require.resolve('@babel/preset-flow'),
],
plugins: [
require.resolve('@babel/plugin-transform-strict-mode'),
Expand Down
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module.exports = {
...common,
displayName: 'unit',
setupFiles: ['<rootDir>/jest/setupUnitTests.js'],
testMatch: ['<rootDir>/**/__tests__/*{.,-}test.js'],
testMatch: ['<rootDir>/**/__tests__/*{.,-}test.[jt]s'],
},
],
};
10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
"packages/*"
],
"scripts": {
"prebuild": "yarn build:ts",
"build": "node ./scripts/build.js",
"build-clean": "rm -rf ./packages/*/build",
"build:ts": "node ./scripts/buildTs.js",
"build-clean": "rm -rf ./packages/*/build ./packages/*/tsconfig.tsbuildinfo",
"watch": "node ./scripts/watch.js",
"test": "jest",
"test:ci:unit": "jest packages --ci --coverage",
Expand Down Expand Up @@ -34,5 +36,11 @@
"micromatch": "^3.1.10",
"mkdirp": "^0.5.1",
"string-length": "^2.0.0"
},
"devDependencies": {
"@babel/preset-typescript": "^7.3.3",
"@types/jest": "^24.0.11",
"@types/node": "^11.13.0",
"typescript": "^3.4.2"
}
}
8 changes: 6 additions & 2 deletions packages/tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
"main": "build/index.js",
"dependencies": {
"chalk": "^1.1.1",
"mime": "^1.3.4",
"lodash": "^4.17.5"
"lodash": "^4.17.5",
"mime": "^2.4.1"
},
"devDependencies": {
"@types/lodash": "^4.14.123",
"@types/mime": "^2.0.1"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/

module.exports.out = () => jest.fn();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @emails oncall+javascript_foundation
*/

import groupFilesByType from '../groupFilesByType';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,11 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import {groupBy} from 'lodash';
import { groupBy } from 'lodash';
import mime from 'mime';

/**
* Since there are no officially registered MIME types
* for ttf/otf yet http://www.iana.org/assignments/media-types/media-types.xhtml,
* we define two non-standard ones for the sake of parsing
*/
mime.define({
'font/opentype': ['otf'],
'font/truetype': ['ttf'],
});

/**
* Given an array of files, it groups it by it's type.
* Type of the file is inferred from it's mimetype based on the extension
Expand All @@ -32,5 +21,5 @@ mime.define({
* the returned object will be: {font: ['fonts/a.ttf'], image: ['images/b.jpg']}
*/
export default function groupFilesByType(assets: Array<string>) {
return groupBy(assets, type => mime.lookup(type).split('/')[0]);
return groupBy(assets, type => (mime.getType(type) || '').split('/')[0]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When this can return undefined?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When you try ot get mime type which doesn't exist.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was it always like that, even with the previous version? Trying to get an idea whether we had a hidden cannot read property split of undefined error or the method changed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably yes, because mime lib didn't have any flow typings. When upgraded mime lib and attaching typescript types, we caught this error.

}
3 changes: 0 additions & 3 deletions packages/tools/src/index.js → packages/tools/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
/**
* @flow
*/
export {default as logger} from './logger';
export {default as groupFilesByType} from './groupFilesByType';
3 changes: 0 additions & 3 deletions packages/tools/src/logger.js → packages/tools/src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
/**
* @flow
*/
import chalk from 'chalk';

const SEPARATOR = ', ';
Expand Down
7 changes: 7 additions & 0 deletions packages/tools/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "build"
}
}
31 changes: 12 additions & 19 deletions scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,21 @@ const mkdirp = require('mkdirp');
const babel = require('@babel/core');
const chalk = require('chalk');
const micromatch = require('micromatch');
const stringLength = require('string-length');
const {PACKAGES_DIR, getPackages} = require('./helpers');
const {
PACKAGES_DIR,
getPackages,
OK,
adjustToTerminalWidth,
} = require('./helpers');

const OK = chalk.reset.inverse.bold.green(' DONE ');
const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const JS_FILES_PATTERN = '**/*.js';
const TS_FILE_PATTERN = '**/*.ts';
const IGNORE_PATTERN = '**/__{tests,mocks,fixtures}__/**';

const transformOptions = require('../babel.config.js');

const adjustToTerminalWidth = str => {
const columns = process.stdout.columns || 80;
const WIDTH = columns - stringLength(OK) + 1;
const strs = str.match(new RegExp(`(.{1,${WIDTH}})`, 'g'));
let lastString = strs[strs.length - 1];
if (lastString.length < WIDTH) {
lastString += Array(WIDTH - lastString.length).join(chalk.dim('.'));
}
return strs
.slice(0, -1)
.concat(lastString)
.join('\n');
};

function getPackageName(file) {
return path.relative(PACKAGES_DIR, file).split(path.sep)[0];
}
Expand All @@ -59,7 +49,7 @@ function getBuildPath(file, buildFolder) {
const pkgSrcPath = path.resolve(PACKAGES_DIR, pkgName, SRC_DIR);
const pkgBuildPath = path.resolve(PACKAGES_DIR, pkgName, buildFolder);
const relativeToSrcPath = path.relative(pkgSrcPath, file);
return path.resolve(pkgBuildPath, relativeToSrcPath);
return path.resolve(pkgBuildPath, relativeToSrcPath).replace(/\.ts$/, '.js');
}

function buildNodePackage(p) {
Expand Down Expand Up @@ -89,7 +79,10 @@ function buildFile(file, silent) {

mkdirp.sync(path.dirname(destPath), '777');

if (!micromatch.isMatch(file, JS_FILES_PATTERN)) {
if (
!micromatch.isMatch(file, JS_FILES_PATTERN) &&
!micromatch.isMatch(file, TS_FILE_PATTERN)
) {
fs.createReadStream(file).pipe(fs.createWriteStream(destPath));
silent ||
process.stdout.write(
Expand Down
48 changes: 48 additions & 0 deletions scripts/buildTs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

const fs = require('fs');
const path = require('path');

const chalk = require('chalk');
const execa = require('execa');
const {getPackages, adjustToTerminalWidth, OK} = require('./helpers');

const packages = getPackages();

const packagesWithTs = packages.filter(p =>
fs.existsSync(path.resolve(p, 'tsconfig.json')),
);

const args = [
'--max-old-space-size=4096',
path.resolve(
require.resolve('typescript/package.json'),
'..',
require('typescript/package.json').bin.tsc,
),
'-b',
...packagesWithTs,
...process.argv.slice(2),
];

console.log(chalk.inverse('Building TypeScript definition files'));
process.stdout.write(adjustToTerminalWidth('Building\n'));

try {
execa.sync('node', args, {stdio: 'inherit'});
process.stdout.write(`${OK}\n`);
} catch (e) {
process.stdout.write('\n');
console.error(
chalk.inverse.red('Unable to build TypeScript definition files'),
);
console.error(e.stack);
process.exitCode = 1;
}
27 changes: 27 additions & 0 deletions scripts/helpers.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,43 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const stringLength = require('string-length');

const PACKAGES_DIR = path.resolve(__dirname, '../packages');

const OK = chalk.reset.inverse.bold.green(' DONE ');

function getPackages() {
return fs
.readdirSync(PACKAGES_DIR)
.map(file => path.resolve(PACKAGES_DIR, file))
.filter(f => fs.lstatSync(path.resolve(f)).isDirectory());
}

function adjustToTerminalWidth(str) {
const columns = process.stdout.columns || 80;
const WIDTH = columns - stringLength(OK) + 1;
const strs = str.match(new RegExp(`(.{1,${WIDTH}})`, 'g'));
let lastString = strs[strs.length - 1];
if (lastString.length < WIDTH) {
lastString += Array(WIDTH - lastString.length).join(chalk.dim('.'));
}
return strs
.slice(0, -1)
.concat(lastString)
.join('\n');
}

module.exports = {
getPackages,
PACKAGES_DIR,
adjustToTerminalWidth,
OK,
};
30 changes: 30 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": ["es2017"],
"declaration": true,
"declarationMap": true,
"composite": true,
"emitDeclarationOnly": true,

"strict": true,

/* Additional Checks */
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,

/* Module Resolution Options */
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true
},
"exclude": [
".yarn/releases/*",
"**/__tests__/**/*",
"**/build/**/*",
"**/build-es5/**/*"
]
}
Loading