-
Notifications
You must be signed in to change notification settings - Fork 7
feat: add opt-in CommonJS default interop for Node ESM #28
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
79653ab
fix: normalize rc dependency default imports in ESM builds
fireairforce 201952d
fix: normalize CommonJS defaults across Father compilers
fireairforce 8011d40
fix: preserve output with unsupported inspection syntax
fireairforce dcdb97c
fix: make CommonJS default interop opt-in
fireairforce 1d2bf5d
refactor: simplify default interop plumbing
fireairforce File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| import remapping from '@ampproject/remapping'; | ||
| import { parse as parseModule } from 'acorn'; | ||
| import { parse as parseCommonJS } from 'cjs-module-lexer'; | ||
| import { create } from 'enhanced-resolve'; | ||
| import fs from 'fs'; | ||
| import MagicString from 'magic-string'; | ||
| import { builtinModules, createRequire } from 'module'; | ||
| import path from 'path'; | ||
|
|
||
| // Match Node's import branch, rather than accidentally inspecting a dual package's require entry. | ||
| const resolveImport = create.sync({ | ||
| conditionNames: ['node', 'import', 'default'], | ||
| mainFields: ['main'], | ||
| extensions: ['.js', '.json', '.node'], | ||
| }); | ||
|
|
||
| function commonJSExports( | ||
| filename: string, | ||
| seen = new Set<string>(), | ||
| ): Set<string> { | ||
| if (seen.has(filename) || !/\.c?js$/.test(filename)) return new Set(); | ||
| seen.add(filename); | ||
|
|
||
| try { | ||
| const { exports, reexports } = parseCommonJS( | ||
| fs.readFileSync(filename, 'utf8'), | ||
| ); | ||
| const names = new Set(exports); | ||
| for (const request of reexports) { | ||
| try { | ||
| const dependency = createRequire(filename).resolve(request); | ||
| commonJSExports(dependency, seen).forEach((name) => names.add(name)); | ||
| } catch { | ||
| // Optional or unresolved re-exports cannot be classified statically. | ||
| } | ||
| } | ||
| return names; | ||
| } catch { | ||
| // Native ESM and unrecognized syntax must keep their original import semantics. | ||
| return new Set(); | ||
| } | ||
| } | ||
|
|
||
| function needsInterop(request: string, importer: string): boolean { | ||
| if ( | ||
| /^(?:[./#]|[a-z][\w+.-]*:)/i.test(request) || | ||
| builtinModules.includes(request) | ||
| ) | ||
| return false; | ||
|
|
||
| try { | ||
| const entry = resolveImport(path.dirname(importer), request); | ||
| if (!entry) return false; | ||
| const names = commonJSExports(entry); | ||
| return names.has('__esModule') && names.has('default'); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** Normalize statically identifiable transpiled CommonJS defaults after JS compilation. */ | ||
| export default function defaultInterop( | ||
| code: string, | ||
| importer: string, | ||
| sourceMap?: string | null, | ||
| ): [string, (string | null)?] { | ||
| const names = new Set<string>(); | ||
| let program: ReturnType<typeof parseModule>; | ||
| try { | ||
| program = parseModule(code, { | ||
| ecmaVersion: 'latest', | ||
| sourceType: 'module', | ||
| allowHashBang: true, | ||
| onToken(token) { | ||
| if ( | ||
| token.type.label === 'name' && | ||
| 'value' in token && | ||
| typeof token.value === 'string' | ||
| ) { | ||
| names.add(token.value); | ||
| } | ||
| }, | ||
| }); | ||
| } catch { | ||
| // Do not reject compiler output whose syntax this inspection parser cannot handle. | ||
| return [code, sourceMap]; | ||
| } | ||
| const uid = (name: string) => { | ||
| let candidate = `_${name}`; | ||
| while (names.has(candidate)) candidate += '_'; | ||
| names.add(candidate); | ||
| return candidate; | ||
| }; | ||
| const helper = uid('rcDefaultInterop'); | ||
| const output = new MagicString(code); | ||
| const declarations: string[] = []; | ||
|
|
||
| for (const statement of program.body) { | ||
| if (statement.type !== 'ImportDeclaration') continue; | ||
| const defaults = statement.specifiers.filter( | ||
| (specifier) => | ||
| specifier.type === 'ImportDefaultSpecifier' || | ||
| (specifier.type === 'ImportSpecifier' && | ||
| (specifier.imported.type === 'Identifier' | ||
| ? specifier.imported.name | ||
| : specifier.imported.value) === 'default'), | ||
| ); | ||
| if ( | ||
| !defaults.length || | ||
| !needsInterop(String(statement.source.value), importer) | ||
| ) | ||
| continue; | ||
|
|
||
| for (const specifier of defaults) { | ||
| const imported = uid(`${specifier.local.name}Module`); | ||
| output.overwrite(specifier.local.start, specifier.local.end, imported); | ||
| declarations.push( | ||
| `var ${specifier.local.name} = ${helper}(${imported});`, | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| if (!declarations.length) return [code, sourceMap]; | ||
|
|
||
| let insertion = code.startsWith('#!') ? code.indexOf('\n') + 1 : 0; | ||
| for (const statement of program.body) { | ||
| if (statement.type !== 'ExpressionStatement' || !statement.directive) break; | ||
| insertion = statement.end; | ||
| } | ||
| // TODO: Remove the bridge when the dependencies expose native ESM entries. | ||
| // Imports are hoisted; initialize aliases before any original executable statement. | ||
| output.appendLeft( | ||
| insertion, | ||
| ` | ||
| function ${helper}(value) { | ||
| return value && (typeof value === 'object' || typeof value === 'function') && | ||
| value.__esModule && 'default' in value ? value.default : value; | ||
| } | ||
| ${declarations.join('\n')} | ||
| `, | ||
| ); | ||
|
|
||
| const map = sourceMap | ||
| ? remapping( | ||
| [ | ||
| { | ||
| version: 3, | ||
| ...output.generateDecodedMap({ | ||
| source: importer, | ||
| includeContent: true, | ||
| hires: true, | ||
| }), | ||
| }, | ||
| sourceMap, | ||
| ], | ||
| () => null, | ||
| ).toString() | ||
| : sourceMap; | ||
| return [output.toString(), map]; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import type { IFatherConfig, IJSTransformer } from 'father'; | ||
| import { createRequire } from 'module'; | ||
| import path from 'path'; | ||
| import defaultInterop from './defaultInterop'; | ||
|
|
||
| type Transformer = NonNullable<IJSTransformer['fn']>; | ||
|
|
||
| // Delegate to Father's compiler so its JSX, aliases, targets, and source maps stay in effect. | ||
| const transformer: Transformer = async function (content) { | ||
| const { config, paths } = this; | ||
| const loadCompiler = createRequire(path.join(paths.cwd, 'package.json')); | ||
| const compile = loadCompiler( | ||
| `father/dist/builder/bundless/loaders/javascript/${config.transformer}`, | ||
| ).default; | ||
| const result = await compile.call(this, content); | ||
| return (config as IFatherConfig).cjsDefaultInterop === true && | ||
| config.format === 'esm' && | ||
| config.platform === 'node' | ||
| ? defaultInterop(result[0], paths.fileAbsPath, result[1]) | ||
| : result; | ||
| }; | ||
|
|
||
| export default transformer; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: react-component/father-plugin
Length of output: 245
🏁 Script executed:
Repository: react-component/father-plugin
Length of output: 913
🏁 Script executed:
Repository: react-component/father-plugin
Length of output: 18243
🏁 Script executed:
Repository: react-component/father-plugin
Length of output: 18004
🏁 Script executed:
Repository: react-component/father-plugin
Length of output: 18237
将 Father 的版本下限同步到发布元数据。
README.md要求启用cjsDefaultInterop时使用 Father4.6.37+,但package.json的devDependencies.father下限仍是^4.6.24,peerDependencies.father甚至是^4.0.0。消费者因此可以安装 README 不支持的 Father 版本。请将版本范围至少更新为^4.6.37,并同步更新测试基线和发布锁文件(如存在)。🤖 Prompt for AI Agents