Skip to content

Commit

Permalink
Fully switch to ESM (scripts, tests, etc.)
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanGoncharov committed May 27, 2022
1 parent 9df43fa commit fea1499
Show file tree
Hide file tree
Showing 245 changed files with 1,492 additions and 1,447 deletions.
7 changes: 3 additions & 4 deletions .eslintrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ rules:
node/no-exports-assign: error
node/no-extraneous-import: error
node/no-extraneous-require: error
node/no-missing-import: [error, { allowModules: ['graphql'] }]
node/no-missing-import: off # Blocked by https://github.com/mysticatea/eslint-plugin-node/issues/248
node/no-missing-require: error
node/no-new-require: error
node/no-path-concat: error
Expand Down Expand Up @@ -84,7 +84,7 @@ rules:

# Static analysis
# https://github.com/benmosher/eslint-plugin-import#static-analysis
import/no-unresolved: [error, { ignore: ['graphql'] }]
import/no-unresolved: off # blocked by https://github.com/import-js/eslint-plugin-import/issues/2170
import/named: error
import/default: error
import/namespace: error
Expand Down Expand Up @@ -130,7 +130,6 @@ rules:
import/extensions:
- error
- ignorePackages
- ts: never # TODO: remove once TS supports extensions
import/order: [error, { newlines-between: always-and-inside-groups }]
import/newline-after-import: error
import/prefer-default-export: off
Expand Down Expand Up @@ -696,6 +695,7 @@ overrides:
rules:
node/no-sync: off
import/no-unresolved: off
import/no-namespace: off
import/no-nodejs-modules: off
- files: 'resources/**'
env:
Expand Down Expand Up @@ -734,7 +734,6 @@ overrides:
version: detect
rules:
node/no-unpublished-require: off
node/no-missing-import: off
import/no-default-export: off
import/no-commonjs: off
import/no-nodejs-modules: off
Expand Down
6 changes: 3 additions & 3 deletions .mocharc.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
fail-zero: true
throw-deprecation: true
check-leaks: true
require:
- 'ts-node/register/transpile-only'
extension:
- 'ts'
- ts
node-option:
- 'loader=ts-node/esm/transpile-only'
10 changes: 5 additions & 5 deletions integrationTests/integration-test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as childProcess from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import childProcess from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import { describe, it } from 'mocha';

Expand All @@ -26,7 +26,7 @@ describe('Integration Tests', () => {
);

function testOnNodeProject(projectName: string) {
const projectPath = path.join(__dirname, projectName);
const projectPath = new URL(projectName, import.meta.url).pathname;

const packageJSONPath = path.join(projectPath, 'package.json');
const packageJSON = JSON.parse(fs.readFileSync(packageJSONPath, 'utf-8'));
Expand Down
1 change: 0 additions & 1 deletion integrationTests/webpack/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import assert from 'assert';

// eslint-disable-next-line import/no-unresolved, node/no-missing-import
import mainCJS from './dist/main.cjs';

assert.deepStrictEqual(mainCJS.result, {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "A Query Language and Runtime which can target any service.",
"license": "MIT",
"private": true,
"type": "module",
"typesVersions": {
">=4.4.0": {
"*": [
Expand Down
68 changes: 0 additions & 68 deletions resources/add-extension-to-import-paths.ts

This file was deleted.

37 changes: 14 additions & 23 deletions resources/benchmark.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as assert from 'node:assert';
import * as cp from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import assert from 'node:assert';
import cp from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import { exec, execOutput, localRepoPath } from './utils.js';

const NS_PER_SEC = 1e9;
const LOCAL = 'local';
Expand All @@ -22,19 +24,6 @@ function runBenchmarks() {
}
}

function localDir(...paths: ReadonlyArray<string>) {
return path.join(__dirname, '..', ...paths);
}

function exec(command: string, options = {}) {
const result = cp.execSync(command, {
encoding: 'utf-8',
stdio: ['inherit', 'pipe', 'inherit'],
...options,
});
return result?.trimEnd();
}

interface BenchmarkProject {
revision: string;
projectPath: string;
Expand All @@ -58,7 +47,7 @@ function prepareBenchmarkProjects(
fs.rmSync(projectPath, { recursive: true, force: true });
fs.mkdirSync(projectPath);

fs.cpSync(localDir('benchmark'), path.join(projectPath, 'benchmark'), {
fs.cpSync(localRepoPath('benchmark'), path.join(projectPath, 'benchmark'), {
recursive: true,
});

Expand All @@ -80,14 +69,14 @@ function prepareBenchmarkProjects(

function prepareNPMPackage(revision: string) {
if (revision === LOCAL) {
const repoDir = localDir();
const repoDir = localRepoPath();
const archivePath = path.join(tmpDir, 'graphql-local.tgz');
fs.renameSync(buildNPMArchive(repoDir), archivePath);
return archivePath;
}

// Returns the complete git hash for a given git revision reference.
const hash = exec(`git rev-parse "${revision}"`);
const hash = execOutput(`git rev-parse "${revision}"`);

const archivePath = path.join(tmpDir, `graphql-${hash}.tgz`);
if (fs.existsSync(archivePath)) {
Expand All @@ -108,7 +97,9 @@ function prepareBenchmarkProjects(
exec('npm --quiet run build:npm', { cwd: repoDir });

const distDir = path.join(repoDir, 'npmDist');
const archiveName = exec(`npm --quiet pack ${distDir}`, { cwd: repoDir });
const archiveName = execOutput(`npm --quiet pack ${distDir}`, {
cwd: repoDir,
});
return path.join(repoDir, archiveName);
}
}
Expand Down Expand Up @@ -334,7 +325,7 @@ function getArguments(argv: ReadonlyArray<string>) {

function findAllBenchmarks() {
return fs
.readdirSync(localDir('benchmark'), { withFileTypes: true })
.readdirSync(localRepoPath('benchmark'), { withFileTypes: true })
.filter((dirent) => dirent.isFile())
.map((dirent) => dirent.name)
.filter((name) => name.endsWith('-benchmark.js'))
Expand Down
77 changes: 70 additions & 7 deletions resources/build-deno.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import util from 'node:util';

import * as ts from 'typescript';
import ts from 'typescript';

import { addExtensionToImportPaths } from './add-extension-to-import-paths';
import { inlineInvariant } from './inline-invariant';
import { readdirRecursive, showDirStats, writeGeneratedFile } from './utils';
import { inlineInvariant } from './inline-invariant.js';
import { readdirRecursive, showDirStats, writeGeneratedFile } from './utils.js';

fs.rmSync('./denoDist', { recursive: true, force: true });
fs.mkdirSync('./denoDist');
Expand All @@ -22,8 +23,8 @@ for (const filepath of srcFiles) {
);

const transformed = ts.transform(sourceFile, [
addExtensionToImportPaths({ extension: '.ts' }),
inlineInvariant,
addExtensionToImportPaths,
]);
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const newContent = printer.printBundle(
Expand All @@ -42,3 +43,65 @@ fs.copyFileSync('./LICENSE', './denoDist/LICENSE');
fs.copyFileSync('./README.md', './denoDist/README.md');

showDirStats('./denoDist');

/**
* Adds extension to all paths imported inside MJS files
*
* Transforms:
*
* ```
* import { foo } from './bar.js';
* export { foo } from './bar.js';
* ```
*
* to:
*
* ```
* import { foo } from './bar.ts';
* export { foo } from './bar.ts';
* ```
*
*/
export function addExtensionToImportPaths(context: ts.TransformationContext) {
const { factory } = context;

return visitSourceFile;

function visitSourceFile(sourceFile: ts.SourceFile) {
return ts.visitNode(sourceFile, visitNode);
}

function visitNode(node: ts.Node): ts.Node {
const source: string | undefined = (node as any).moduleSpecifier?.text;
if (source?.startsWith('./') || source?.startsWith('../')) {
const tsSource = ts.createStringLiteral(source.replace(/\.js$/, '.ts'));
if (ts.isImportDeclaration(node)) {
return factory.updateImportDeclaration(
node,
node.decorators,
node.modifiers,
node.importClause,
tsSource,
node.assertClause,
);
}
if (ts.isExportDeclaration(node)) {
return factory.updateExportDeclaration(
node,
node.decorators,
node.modifiers,
node.isTypeOnly,
node.exportClause,
tsSource,
node.assertClause,
);
}

assert(
false,
'Unexpected node with moduleSpecifier: ' + util.inspect(node),
);
}
return ts.visitEachChild(node, visitNode, context);
}
}
19 changes: 9 additions & 10 deletions resources/build-npm.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import * as assert from 'node:assert';
import * as fs from 'node:fs';
import * as path from 'node:path';
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';

import * as ts from 'typescript';
import ts from 'typescript';

import { addExtensionToImportPaths } from './add-extension-to-import-paths';
import { inlineInvariant } from './inline-invariant';
import { inlineInvariant } from './inline-invariant.js';
import {
localRepoPath,
readdirRecursive,
readPackageJSON,
showDirStats,
writeGeneratedFile,
} from './utils';
} from './utils.js';

fs.rmSync('./npmDist', { recursive: true, force: true });
fs.mkdirSync('./npmDist');

// 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'),
fs.readFileSync(localRepoPath('tsconfig.json'), 'utf-8'),
);
assert(
tsConfig.compilerOptions,
Expand Down Expand Up @@ -51,7 +51,7 @@ tsHost.writeFile = (filepath, body) => {

const tsProgram = ts.createProgram(['src/index.ts'], tsOptions, tsHost);
const tsResult = tsProgram.emit(undefined, undefined, undefined, undefined, {
after: [addExtensionToImportPaths({ extension: '.js' }), inlineInvariant],
after: [inlineInvariant],
});
assert(
!tsResult.emitSkipped,
Expand Down Expand Up @@ -95,7 +95,6 @@ function buildPackageJSON() {
'*': { '*': [notSupportedTSVersionFile] },
};

packageJSON.type = 'module';
packageJSON.exports = {};

for (const filepath of readdirRecursive('./src', { ignoreDir: /^__.*__$/ })) {
Expand Down
Loading

0 comments on commit fea1499

Please sign in to comment.