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

Fully switch to tsc and remove babel #3557

Merged
merged 1 commit into from
May 4, 2022
Merged
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
2 changes: 1 addition & 1 deletion .mocharc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ fail-zero: true
throw-deprecation: true
check-leaks: true
require:
- 'resources/ts-register.js'
- 'ts-node/register/transpile-only'
extension:
- 'ts'
1,469 changes: 677 additions & 792 deletions package-lock.json

Large diffs are not rendered by default.

6 changes: 1 addition & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,6 @@
"gitpublish:deno": "bash ./resources/gitpublish.sh deno denoDist"
},
"devDependencies": {
"@babel/core": "7.17.10",
"@babel/plugin-syntax-typescript": "7.17.10",
"@babel/plugin-transform-typescript": "7.16.8",
"@babel/preset-env": "7.17.10",
"@babel/register": "7.17.7",
"@docusaurus/core": "2.0.0-beta.18",
"@docusaurus/preset-classic": "2.0.0-beta.18",
"@mdx-js/react": "1.6.22",
Expand Down Expand Up @@ -84,6 +79,7 @@
"prism-react-renderer": "1.3.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"ts-node": "10.7.0",
"typedoc": "0.22.15",
"typescript": "4.6.4",
"url-loader": "4.1.1"
Expand Down
55 changes: 35 additions & 20 deletions resources/add-extension-to-import-paths.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
'use strict';

const assert = require('assert');

const ts = require('typescript');

/**
* Adds extension to all paths imported inside MJS files
*
Expand All @@ -14,26 +18,37 @@
* export { foo } from './bar.mjs';
*
*/
module.exports = function addExtensionToImportPaths(context, { extension }) {
const { types } = context;
module.exports = function addExtensionToImportPaths({ extension }) {
return (context) => {
const { factory } = context;

return {
visitor: {
ImportDeclaration: replaceImportPath,
ExportNamedDeclaration: replaceImportPath,
},
return function visit(node) {
const source = node.moduleSpecifier?.text;
if (source?.startsWith('./') || source?.startsWith('../')) {
if (ts.isImportDeclaration(node)) {
return factory.updateImportDeclaration(
node,
node.decorators,
node.modifiers,
node.importClause,
ts.createStringLiteral(source + extension),
node.assertClause,
);
}
if (ts.isExportDeclaration(node)) {
return factory.updateExportDeclaration(
node,
node.decorators,
node.modifiers,
node.isTypeOnly,
node.exportClause,
ts.createStringLiteral(source + extension),
node.assertClause,
);
}
assert(false, 'Unexpected node with moduleSpecifier: ' + node);
}
return ts.visitEachChild(node, visit, context);
};
};

function replaceImportPath(path) {
// bail if the declaration doesn't have a source, e.g. "export { foo };"
if (!path.node.source) {
return;
}

const source = path.node.source.value;
if (source.startsWith('./') || source.startsWith('../')) {
const newSourceNode = types.stringLiteral(source + '.' + extension);
path.get('source').replaceWith(newSourceNode);
}
}
};
33 changes: 25 additions & 8 deletions resources/build-deno.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
const fs = require('fs');
const path = require('path');

const babel = require('@babel/core');
const ts = require('typescript');

const inlineInvariant = require('./inline-invariant.js');
const addExtensionToImportPaths = require('./add-extension-to-import-paths.js');
const {
writeGeneratedFile,
readdirRecursive,
Expand All @@ -17,14 +19,29 @@ if (require.main === module) {

const srcFiles = readdirRecursive('./src', { ignoreDir: /^__.*__$/ });
for (const filepath of srcFiles) {
const srcPath = path.join('./src', filepath);
const destPath = path.join('./denoDist', filepath);

fs.mkdirSync(path.dirname(destPath), { recursive: true });
if (filepath.endsWith('.ts')) {
const options = { babelrc: false, configFile: './.babelrc-deno.json' };
const output = babel.transformFileSync(srcPath, options).code + '\n';
writeGeneratedFile(destPath, output);
const srcPath = path.join('./src', filepath);

const sourceFile = ts.createSourceFile(
srcPath,
fs.readFileSync(srcPath, 'utf-8'),
ts.ScriptTarget.Latest,
);

const transformed = ts.transform(sourceFile, [
addExtensionToImportPaths({ extension: '.ts' }),
inlineInvariant,
]);
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const newContent = printer.printBundle(
ts.createBundle(transformed.transformed),
);

transformed.dispose();

const destPath = path.join('./denoDist', filepath);
fs.mkdirSync(path.dirname(destPath), { recursive: true });
writeGeneratedFile(destPath, newContent);
}
}

Expand Down
68 changes: 31 additions & 37 deletions resources/build-npm.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,17 @@ const path = require('path');
const assert = require('assert');

const ts = require('typescript');
const babel = require('@babel/core');

const {
writeGeneratedFile,
readdirRecursive,
showDirStats,
} = require('./utils.js');
const inlineInvariant = require('./inline-invariant.js');
const addExtensionToImportPaths = require('./add-extension-to-import-paths.js');
const { writeGeneratedFile, showDirStats } = require('./utils.js');

if (require.main === module) {
fs.rmSync('./npmDist', { recursive: true, force: true });
fs.mkdirSync('./npmDist');

const packageJSON = buildPackageJSON();

const srcFiles = readdirRecursive('./src', { ignoreDir: /^__.*__$/ });
for (const srcFilePath of srcFiles) {
if (srcFilePath.endsWith('.ts')) {
const destFilePath = srcFilePath.replace(/\.ts$/, '.js');

const srcPath = path.join('./src', srcFilePath);
const destPath = path.join('./npmDist', destFilePath);

fs.mkdirSync(path.dirname(destPath), { recursive: true });

const { code } = babel.transformFileSync(srcPath, {
babelrc: false,
configFile: './.babelrc-npm.json',
});
writeGeneratedFile(destPath, code + '\n');

if (path.basename(destFilePath) === 'index.js') {
const key = destFilePath.replace(/\/index.js$/, '');
packageJSON.exports[key] = destFilePath;
}
}
}

// Based on https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#getting-the-dts-from-a-javascript-file
const tsConfig = JSON.parse(
fs.readFileSync(require.resolve('../tsconfig.json'), 'utf-8'),
Expand All @@ -50,21 +24,41 @@ if (require.main === module) {
tsConfig.compilerOptions,
'"tsconfig.json" should have `compilerOptions`',
);
const tsOptions = {
...tsConfig.compilerOptions,
noEmit: false,
declaration: true,
declarationDir: './npmDist',
emitDeclarationOnly: true,
};

const { options: tsOptions, errors: tsOptionsErrors } =
ts.convertCompilerOptionsFromJson(
{
...tsConfig.compilerOptions,
module: 'es2020',
noEmit: false,
declaration: true,
declarationDir: './npmDist',
outDir: './npmDist',
},
process.cwd(),
);

assert(
tsOptionsErrors.length === 0,
'Fail to parse options: ' + tsOptionsErrors,
);

const tsHost = ts.createCompilerHost(tsOptions);
tsHost.writeFile = (filepath, body) => {
if (path.basename(filepath) === 'index.js') {
const relative = './' + path.relative('./npmDist', filepath);
const key = relative.replace(/\/?index.js$/, '');
packageJSON.exports[key] = relative;
}

fs.mkdirSync(path.dirname(filepath), { recursive: true });
writeGeneratedFile(filepath, body);
};

const tsProgram = ts.createProgram(['src/index.ts'], tsOptions, tsHost);
const tsResult = tsProgram.emit();
const tsResult = tsProgram.emit(undefined, undefined, undefined, undefined, {
after: [addExtensionToImportPaths({ extension: '.js' }), inlineInvariant],
});
assert(
!tsResult.emitSkipped,
'Fail to generate `*.d.ts` files, please run `npm run check`',
Expand Down
50 changes: 22 additions & 28 deletions resources/inline-invariant.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const ts = require('typescript');

/**
* Eliminates function call to `invariant` if the condition is met.
*
Expand All @@ -12,37 +14,29 @@
* (<cond>) || invariant(false ...)
*/
module.exports = function inlineInvariant(context) {
const invariantTemplate = context.template(`
(%%cond%%) || invariant(false, %%args%%)
`);
const assertTemplate = context.template(`
(%%cond%%) || devAssert(false, %%args%%)
`);

return {
visitor: {
CallExpression(path) {
const node = path.node;
const parent = path.parent;
const { factory } = context;

if (
parent.type !== 'ExpressionStatement' ||
node.callee.type !== 'Identifier' ||
node.arguments.length === 0
) {
return;
}
return function visit(node) {
if (ts.isCallExpression(node)) {
const { expression, arguments: args } = node;

const calleeName = node.callee.name;
if (calleeName === 'invariant') {
const [cond, args] = node.arguments;
if (ts.isIdentifier(expression) && args.length > 0) {
const funcName = expression.escapedText;
if (funcName === 'invariant' || funcName === 'devAssert') {
const [condition, ...otherArgs] = args;

path.replaceWith(invariantTemplate({ cond, args }));
} else if (calleeName === 'devAssert') {
const [cond, args] = node.arguments;
path.replaceWith(assertTemplate({ cond, args }));
return factory.createBinaryExpression(
factory.createParenthesizedExpression(condition),
ts.SyntaxKind.BarBarToken,
factory.createCallExpression(
factory.createIdentifier(funcName),
undefined,
[factory.createFalse(), ...otherArgs],
),
);
}
},
},
}
}
return ts.visitEachChild(node, visit, context);
};
};
3 changes: 0 additions & 3 deletions resources/ts-register.js

This file was deleted.

12 changes: 6 additions & 6 deletions src/execution/__tests__/mapAsyncIterator-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ describe('mapAsyncIterator', () => {
async function* source() {
try {
yield 1;
/* c8 ignore next 2 */
/* c8 ignore next 3 */
yield 2;
yield 3; // Shouldn't be reached.
} finally {
Expand Down Expand Up @@ -155,7 +155,7 @@ describe('mapAsyncIterator', () => {
async function* source() {
try {
yield 'a';
/* c8 ignore next 2 */
/* c8 ignore next 3 */
yield 'b';
yield 'c'; // Shouldn't be reached.
} finally {
Expand Down Expand Up @@ -211,7 +211,7 @@ describe('mapAsyncIterator', () => {
// Throw error
let caughtError;
try {
/* c8 ignore next */
/* c8 ignore next 2 */
await doubles.throw('ouch');
} catch (e) {
caughtError = e;
Expand Down Expand Up @@ -267,7 +267,7 @@ describe('mapAsyncIterator', () => {

let caughtError;
try {
/* c8 ignore next */
/* c8 ignore next 2 */
await doubles.next();
} catch (e) {
caughtError = e;
Expand All @@ -284,7 +284,7 @@ describe('mapAsyncIterator', () => {
async function* source() {
try {
yield 1;
/* c8 ignore next 2 */
/* c8 ignore next 3 */
yield 2;
yield 3; // Shouldn't be reached.
} finally {
Expand All @@ -299,7 +299,7 @@ describe('mapAsyncIterator', () => {

let expectedError;
try {
/* c8 ignore next */
/* c8 ignore next 2 */
await throwOver1.next();
} catch (error) {
expectedError = error;
Expand Down
2 changes: 1 addition & 1 deletion src/execution/__tests__/subscribe-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -835,7 +835,7 @@ describe('Subscription Publish Phase', () => {
// Throw error
let caughtError;
try {
/* c8 ignore next */
/* c8 ignore next 2 */
await subscription.throw('ouch');
} catch (e) {
caughtError = e;
Expand Down
2 changes: 1 addition & 1 deletion src/validation/rules/KnownDirectivesRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ function getDirectiveLocationForASTPath(
: DirectiveLocation.ARGUMENT_DEFINITION;
}
// Not reachable, all possible types have been considered.
/* c8 ignore next */
/* c8 ignore next 2 */
default:
invariant(false, 'Unexpected kind: ' + inspect(appliedTo.kind));
}
Expand Down
2 changes: 1 addition & 1 deletion src/validation/rules/PossibleTypeExtensionsRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ function extensionKindToTypeName(kind: Kind): string {
case Kind.INPUT_OBJECT_TYPE_EXTENSION:
return 'input object';
// Not reachable. All possible types have been considered
/* c8 ignore next */
/* c8 ignore next 2 */
default:
invariant(false, 'Unexpected kind: ' + inspect(kind));
}
Expand Down
Loading