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

Preserve require() calls for nodejs builtin modules #1483

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
88 changes: 88 additions & 0 deletions src/googmodule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,93 @@ export function extractModuleMarker(
return literalTypeOfSymbol(localSymbol);
}

// node -p "require('module').builtinModules"
const NODEJS_BUILTIN_MODULES = new Set([
'_http_agent',
'_http_client',
'_http_common',
'_http_incoming',
'_http_outgoing',
'_http_server',
'_stream_duplex',
'_stream_passthrough',
'_stream_readable',
'_stream_transform',
'_stream_wrap',
'_stream_writable',
'_tls_common',
'_tls_wrap',
'assert',
'assert/strict',
'async_hooks',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'diagnostics_channel',
'dns',
'dns/promises',
'domain',
'events',
'fs',
'fs/promises',
'http',
'http2',
'https',
'inspector',
'module',
'net',
'os',
'path',
'path/posix',
'path/win32',
'perf_hooks',
'process',
'punycode',
'querystring',
'readline',
'readline/promises',
'repl',
'stream',
'stream/consumers',
'stream/promises',
'stream/web',
'string_decoder',
'sys',
'timers',
'timers/promises',
'tls',
'trace_events',
'tty',
'url',
'util',
'util/types',
'v8',
'vm',
'wasi',
'worker_threads',
'zlib',
]);

// Possible patterns:
// - "fs" (\w+)
// - "node:fs" (node:\w+)
// - "fs/promises" (\w+/\w+)
// - "node:fs/promises" (node:\w+/\w+)
const NODEJS_BUILTIN_PATTERN = /^(?:node:)?(\w+(?:\/\w+)?)$/;
function isNodeJSBuiltin(specifier: string, original: string): boolean {
const match = original.match(NODEJS_BUILTIN_PATTERN);
if (match === null || !NODEJS_BUILTIN_MODULES.has(match[1])) {
return false;
}

const normalized = original.replace(':', '_').replace('/', '.');
return specifier === normalized;
}

/** Internal TypeScript APIs on ts.Declaration. */
declare interface InternalTsDeclaration {
locals?: ts.SymbolTable;
Expand Down Expand Up @@ -717,6 +804,7 @@ export function commonJsToGoogmoduleTransformer(
host, importedUrl, ignoredDiagnostics, sf, importedUrl.text,
() => getAmbientModuleSymbol(typeChecker, importedUrl));
modulesManifest.addReferencedModule(sf.fileName, imp);
if (isNodeJSBuiltin(imp, importedUrl.text)) return null;
const existingImport: ts.Identifier|undefined =
namespaceToModuleVarName.get(imp);
let initializer: ts.Expression;
Expand Down
40 changes: 40 additions & 0 deletions test/googmodule_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,46 @@ describe('convertCommonJsToGoogModule', () => {
`));
});

describe('nodejs builtin imports', () => {
it('converts builtin imports to require (not goog.require)', () => {
const before = `
import {readFile as a} from 'fs';
import {readFile as b} from 'fs/promises';
import {readFile as c} from 'node:fs';
import {readFile as d} from 'node:fs/promises';
console.log(a, b, c, d);
`;

expectCommonJs('a.ts', before, false).toBe(outdent(`
goog.module('a');
var module = module || { id: 'a.ts' };
goog.require('tslib');
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const node_fs_1 = require("node:fs");
const promises_2 = require("node:fs/promises");
console.log(fs_1.readFile, promises_1.readFile, node_fs_1.readFile, promises_2.readFile);
`));
});

it('allows a trailing slash as an escape hatch', () => {
const before = `
import {readFile as a} from 'fs/';
import {readFile as b} from 'fs/promises/';
console.log(a, b);
`;

expectCommonJs('a.ts', before, false).toBe(outdent(`
goog.module('a');
var module = module || { id: 'a.ts' };
goog.require('tslib');
const fs_1 = goog.require('fs');
const promises_1 = goog.require('fs.promises');
console.log(fs_1.readFile, promises_1.readFile);
`));
});
});

describe('dynamic import', () => {
it('handles dynamic imports', () => {
const before = `
Expand Down
Loading