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 ESM (scripts, tests, etc.) #3564

Merged
merged 2 commits into from
Sep 1, 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
9 changes: 5 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,8 +695,11 @@ overrides:
node: true
rules:
node/no-sync: off
node/no-extraneous-import: [error, { allowModules: ['graphql'] }]
import/no-unresolved: off
import/no-namespace: off
import/no-nodejs-modules: off
import/no-extraneous-dependencies: off
- files: 'resources/**'
env:
node: true
Expand Down Expand Up @@ -735,7 +737,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 @@ -28,7 +28,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
6 changes: 4 additions & 2 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 Expand Up @@ -44,8 +45,9 @@
"prettier:check": "prettier --cache --cache-strategy metadata --check .",
"check:spelling": "cspell --cache --no-progress '**/*'",
"check:integrations": "npm run build:npm && npm run build:deno && mocha --full-trace integrationTests/*-test.ts",
"start": "DOCUSAURUS_GENERATED_FILES_DIR_NAME=\"$(pwd)/.docusaurus\" docusaurus start ./website",
"build:website": "DOCUSAURUS_GENERATED_FILES_DIR_NAME=\"$(pwd)/.docusaurus\" docusaurus build --out-dir=\"$(pwd)/websiteDist\" ./website",
"serve": "docusaurus serve --dir websiteDist/ --config website/docusaurus.config.cjs",
"start": "npm run build:website && npm run serve",
"build:website": "ts-node resources/build-docusaurus.ts",
"build:npm": "ts-node resources/build-npm.ts",
"build:deno": "ts-node resources/build-deno.ts",
"diff:npm": "ts-node resources/diff-npm-package.ts",
Expand Down
16 changes: 8 additions & 8 deletions resources/benchmark.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
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 * as url from 'node:url';

import { git, localRepoPath, npm } from './utils';
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 url from 'node:url';

import { git, localRepoPath, npm } from './utils.js';

const NS_PER_SEC = 1e9;
const LOCAL = 'local';
Expand Down
14 changes: 7 additions & 7 deletions resources/build-deno.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
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 { readdirRecursive, showDirStats, writeGeneratedFile } from './utils';
import { changeExtensionInImportPaths } from './change-extension-in-import-paths.js';
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,7 +22,7 @@ for (const filepath of srcFiles) {
);

const transformed = ts.transform(sourceFile, [
addExtensionToImportPaths({ extension: '.ts' }),
changeExtensionInImportPaths({ extension: '.ts' }),
inlineInvariant,
]);
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
Expand Down
46 changes: 46 additions & 0 deletions resources/build-docusaurus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// The whole script is a hack to allow building Docusaurus in ESM project
// https://github.com/facebook/docusaurus/issues/6520
// Should be just: `docusaurus build --out-dir ./websiteDist ./website`

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import { localRepoPath, npm, readPackageJSON } from './utils.js';

const tmpDir = path.join(os.tmpdir(), 'graphql-run-docusaurus');
fs.rmSync(tmpDir, { recursive: true, force: true });
fs.mkdirSync(tmpDir);

const packageJSON = readPackageJSON();
delete packageJSON.type;
fs.writeFileSync(tmpDirPath('package.json'), JSON.stringify(packageJSON));

copyToTmpDir('package-lock.json');
copyToTmpDir('tsconfig.json');
copyToTmpDir('src');
copyToTmpDir('website');

npm(['install', 'ci'], { cwd: tmpDir });

const env = {
...process.env,
DOCUSAURUS_GENERATED_FILES_DIR_NAME: tmpDirPath('.docusaurus'),
};
const docusaurusArgs = [
'build',
'--out-dir',
localRepoPath('websiteDist'),
tmpDirPath('website'),
];
npm(['exec', 'docusaurus', '--', ...docusaurusArgs], { env, cwd: tmpDir });

function copyToTmpDir(relativePath: string) {
fs.cpSync(localRepoPath(relativePath), tmpDirPath(relativePath), {
recursive: true,
});
}

function tmpDirPath(...paths: ReadonlyArray<string>): string {
return path.join(tmpDir, ...paths);
}
16 changes: 7 additions & 9 deletions resources/build-npm.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
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');
Expand Down Expand Up @@ -52,7 +51,7 @@ tsHost.writeFile = writeGeneratedFile;

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 @@ -96,7 +95,6 @@ function buildPackageJSON() {
'*': { '*': [notSupportedTSVersionFile] },
};

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

for (const filepath of readdirRecursive('./src', { ignoreDir: /^__.*__$/ })) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
import * as assert from 'node:assert';
import * as util from 'node:util';
import assert from 'node:assert';
import util from 'node:util';

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

/**
* Adds extension to all paths imported inside MJS files
*
* Transforms:
*
* ```
* import { foo } from './bar';
* export { foo } from './bar';
* import { foo } from './bar.js';
* export { foo } from './bar.js';
* ```
*
* to:
*
* ```
* import { foo } from './bar.mjs';
* export { foo } from './bar.mjs';
* import { foo } from './bar.ts';
* export { foo } from './bar.ts';
* ```
*
*/
export function addExtensionToImportPaths(config: { extension: string }) {
export function changeExtensionInImportPaths(config: { extension: string }) {
const { extension } = config;
return (context: ts.TransformationContext) => {
const { factory } = context;
Expand All @@ -35,13 +35,15 @@ export function addExtensionToImportPaths(config: { extension: string }) {
function visitNode(node: ts.Node): ts.Node {
const source: string | undefined = (node as any).moduleSpecifier?.text;
if (source?.startsWith('./') || source?.startsWith('../')) {
const newSource = source.replace(/\.js$/, extension);

if (ts.isImportDeclaration(node)) {
return factory.updateImportDeclaration(
node,
node.decorators,
node.modifiers,
node.importClause,
ts.createStringLiteral(source + extension),
factory.createStringLiteral(newSource),
node.assertClause,
);
}
Expand All @@ -52,7 +54,7 @@ export function addExtensionToImportPaths(config: { extension: string }) {
node.modifiers,
node.isTypeOnly,
node.exportClause,
ts.createStringLiteral(source + extension),
factory.createStringLiteral(newSource),
node.assertClause,
);
}
Expand Down
12 changes: 6 additions & 6 deletions resources/diff-npm-package.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as assert from 'node:assert';
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 assert from 'node:assert';
import childProcess from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import { git, localRepoPath, npm, writeGeneratedFile } from './utils';
import { git, localRepoPath, npm, writeGeneratedFile } from './utils.js';

const LOCAL = 'local';
const tmpDir = path.join(os.tmpdir(), 'graphql-js-npm-diff');
Expand Down
2 changes: 1 addition & 1 deletion resources/gen-changelog.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { git, readPackageJSON } from './utils';
import { git, readPackageJSON } from './utils.js';

const packageJSON = readPackageJSON();
const labelsConfig: { [label: string]: { section: string; fold?: boolean } } = {
Expand Down
2 changes: 1 addition & 1 deletion resources/gen-version.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { readPackageJSON, writeGeneratedFile } from './utils';
import { readPackageJSON, writeGeneratedFile } from './utils.js';

const { version } = readPackageJSON();
const versionMatch = /^(\d+)\.(\d+)\.(\d+)-?(.*)?$/.exec(version);
Expand Down
2 changes: 1 addition & 1 deletion resources/inline-invariant.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as ts from 'typescript';
import ts from 'typescript';

/**
* Eliminates function call to `invariant` if the condition is met.
Expand Down
16 changes: 10 additions & 6 deletions resources/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import * as assert from 'node:assert';
import * as childProcess from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import assert from 'node:assert';
import childProcess from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';

import * as prettier from 'prettier';
import prettier from 'prettier';

export function localRepoPath(...paths: ReadonlyArray<string>): string {
return path.join(__dirname, '..', ...paths);
const repoDir = new URL('..', import.meta.url).pathname;
return path.join(repoDir, ...paths);
}

export function npm(
Expand All @@ -25,6 +26,7 @@ export function git(

interface SpawnOptions {
cwd?: string;
env?: typeof process.env;
}

function spawn(
Expand Down Expand Up @@ -62,6 +64,8 @@ export function readdirRecursive(
);
result.push(...list);
}

result.sort((a, b) => a.localeCompare(b));
return result.map((filepath) => './' + filepath);
}

Expand Down
2 changes: 1 addition & 1 deletion src/__testUtils__/__tests__/dedent-test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';

import { dedent, dedentString } from '../dedent';
import { dedent, dedentString } from '../dedent.js';

describe('dedentString', () => {
it('removes indentation in typical usage', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';

import { expectEqualPromisesOrValues } from '../expectEqualPromisesOrValues';
import { expectPromise } from '../expectPromise';
import { expectEqualPromisesOrValues } from '../expectEqualPromisesOrValues.js';
import { expectPromise } from '../expectPromise.js';

describe('expectEqualPromisesOrValues', () => {
it('throws when given unequal values', () => {
Expand Down
Loading