@knighted/module 1.0.0-rc.5 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -10
- package/dist/cjs/format.cjs +212 -11
- package/dist/cjs/formatters/identifier.cjs +3 -2
- package/dist/cjs/formatters/memberExpression.cjs +27 -5
- package/dist/cjs/memberExpression.d.cts +1 -1
- package/dist/cjs/module.cjs +2 -1
- package/dist/cjs/specifier.cjs +3 -0
- package/dist/cjs/types.d.cts +12 -3
- package/dist/cjs/utils/exports.cjs +33 -5
- package/dist/format.js +212 -11
- package/dist/formatters/identifier.js +3 -2
- package/dist/formatters/memberExpression.js +27 -5
- package/dist/memberExpression.d.ts +1 -1
- package/dist/module.js +2 -1
- package/dist/specifier.js +3 -0
- package/dist/src/formatters/identifier.d.ts +2 -1
- package/dist/src/formatters/memberExpression.d.ts +1 -1
- package/dist/src/types.d.ts +12 -3
- package/dist/types.d.ts +12 -3
- package/dist/utils/exports.js +33 -5
- package/package.json +7 -7
- package/dist/assignmentExpression.d.cts +0 -12
- package/dist/cjs/helpers/scope.cjs +0 -12
- package/dist/cjs/scope.d.cts +0 -6
- package/dist/exports.d.cts +0 -6
- package/dist/expressionStatement.d.cts +0 -4
- package/dist/format.d.cts +0 -9
- package/dist/formatters/assignmentExpression.d.ts +0 -12
- package/dist/formatters/expressionStatement.d.ts +0 -4
- package/dist/formatters/identifier.d.ts +0 -12
- package/dist/formatters/memberExpression.d.ts +0 -4
- package/dist/formatters/metaProperty.d.ts +0 -4
- package/dist/helpers/identifier.d.ts +0 -31
- package/dist/helpers/scope.d.ts +0 -6
- package/dist/helpers/scope.js +0 -7
- package/dist/identifier.d.cts +0 -31
- package/dist/identifiers.d.cts +0 -19
- package/dist/lang.d.cts +0 -3
- package/dist/memberExpression.d.cts +0 -13
- package/dist/metaProperty.d.cts +0 -4
- package/dist/module.d.cts +0 -3
- package/dist/parse.d.cts +0 -2
- package/dist/scope.d.cts +0 -6
- package/dist/scope.d.ts +0 -6
- package/dist/scopeNodes.d.cts +0 -2
- package/dist/specifier.d.cts +0 -16
- package/dist/src/helpers/scope.d.ts +0 -6
- package/dist/types.d.cts +0 -82
- package/dist/url.d.cts +0 -2
- package/dist/utils.d.cts +0 -23
- package/dist/walk.d.cts +0 -20
package/README.md
CHANGED
|
@@ -11,14 +11,16 @@ Node.js utility for transforming a JavaScript or TypeScript file from an ES modu
|
|
|
11
11
|
|
|
12
12
|
Highlights
|
|
13
13
|
|
|
14
|
+
- ESM ➡️ CJS and CJS ➡️ ESM with one function call.
|
|
14
15
|
- Defaults to safe CommonJS output: strict live bindings, import.meta shims, and specifier preservation.
|
|
15
|
-
-
|
|
16
|
-
-
|
|
16
|
+
- Configurable lowering modes: full syntax transforms or globals-only.
|
|
17
|
+
- Specifier tools: add extensions, add directory indexes, or map with a custom callback.
|
|
18
|
+
- Output control: write to disk (`out`/`inPlace`) or return the transformed string.
|
|
17
19
|
|
|
18
20
|
> [!IMPORTANT]
|
|
19
21
|
> All parsing logic is applied under the assumption the code is in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) which [modules run under by default](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#other_differences_between_modules_and_classic_scripts).
|
|
20
22
|
|
|
21
|
-
By default `@knighted/module` transforms the one-to-one [differences between ES modules and CommonJS](https://nodejs.org/api/esm.html#differences-between-es-modules-and-commonjs). Options let you control syntax rewriting, specifier updates, and output.
|
|
23
|
+
By default `@knighted/module` transforms the one-to-one [differences between ES modules and CommonJS](https://nodejs.org/api/esm.html#differences-between-es-modules-and-commonjs). Options let you control syntax rewriting (full vs globals-only), specifier updates, and output.
|
|
22
24
|
|
|
23
25
|
## Requirements
|
|
24
26
|
|
|
@@ -30,9 +32,9 @@ By default `@knighted/module` transforms the one-to-one [differences between ES
|
|
|
30
32
|
npm install @knighted/module
|
|
31
33
|
```
|
|
32
34
|
|
|
33
|
-
##
|
|
35
|
+
## Quick examples
|
|
34
36
|
|
|
35
|
-
|
|
37
|
+
ESM ➡️ CJS:
|
|
36
38
|
|
|
37
39
|
**file.js**
|
|
38
40
|
|
|
@@ -93,13 +95,24 @@ use@computer: $ node file.cjs
|
|
|
93
95
|
invoked directly by node
|
|
94
96
|
```
|
|
95
97
|
|
|
98
|
+
CJS ➡️ ESM:
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
import { transform } from '@knighted/module'
|
|
102
|
+
|
|
103
|
+
await transform('./file.cjs', {
|
|
104
|
+
target: 'module',
|
|
105
|
+
out: './file.mjs',
|
|
106
|
+
})
|
|
107
|
+
```
|
|
108
|
+
|
|
96
109
|
## Options
|
|
97
110
|
|
|
98
111
|
```ts
|
|
99
112
|
type ModuleOptions = {
|
|
100
113
|
target: 'module' | 'commonjs'
|
|
101
114
|
sourceType?: 'auto' | 'module' | 'commonjs'
|
|
102
|
-
transformSyntax?: boolean
|
|
115
|
+
transformSyntax?: boolean | 'globals-only'
|
|
103
116
|
liveBindings?: 'strict' | 'loose' | 'off'
|
|
104
117
|
appendJsExtension?: 'off' | 'relative-only' | 'all'
|
|
105
118
|
appendDirectoryIndex?: string | false
|
|
@@ -124,20 +137,21 @@ type ModuleOptions = {
|
|
|
124
137
|
}
|
|
125
138
|
```
|
|
126
139
|
|
|
127
|
-
Behavior notes (defaults in parentheses)
|
|
140
|
+
### Behavior notes (defaults in parentheses)
|
|
128
141
|
|
|
129
142
|
- `target` (`commonjs`): output module system.
|
|
130
|
-
- `transformSyntax` (true): enable/disable the ESM↔CJS lowering pass.
|
|
143
|
+
- `transformSyntax` (true): enable/disable the ESM↔CJS lowering pass; set to `'globals-only'` to rewrite module globals (`import.meta.*`, `__dirname`, `__filename`, `require.main` shims) while leaving import/export syntax untouched. In `'globals-only'`, no helpers are injected (e.g., `__requireResolve`), `require.resolve` rewrites to `import.meta.resolve`, and `idiomaticExports` is skipped. See [globals-only](#globals-only-scope).
|
|
131
144
|
- `liveBindings` (`strict`): getter-based live bindings, or snapshot (`loose`/`off`).
|
|
132
145
|
- `appendJsExtension` (`relative-only` when targeting ESM): append `.js` to relative specifiers; never touches bare specifiers.
|
|
133
146
|
- `appendDirectoryIndex` (`index.js`): when a relative specifier ends with a slash, append this index filename (set `false` to disable).
|
|
147
|
+
- `appenders` precedence: `rewriteSpecifier` runs first; if it returns a string, that result is used. If it returns `undefined` or `null`, `appendJsExtension` and `appendDirectoryIndex` still run. Bare specifiers are never modified by appenders.
|
|
134
148
|
- `dirFilename` (`inject`): inject `__dirname`/`__filename`, preserve existing, or throw.
|
|
135
149
|
- `importMeta` (`shim`): rewrite `import.meta.*` to CommonJS equivalents.
|
|
136
150
|
- `importMetaMain` (`shim`): gate `import.meta.main` with shimming/warning/error when Node support is too old.
|
|
137
151
|
- `requireMainStrategy` (`import-meta-main`): use `import.meta.main` or the realpath-based `pathToFileURL(realpathSync(process.argv[1])).href` check.
|
|
138
152
|
- `detectCircularRequires` (`off`): optionally detect relative static require cycles and warn/throw.
|
|
139
153
|
- `topLevelAwait` (`error`): throw, wrap, or preserve when TLA appears in CommonJS output.
|
|
140
|
-
- `rewriteSpecifier` (off): rewrite relative specifiers to a chosen extension or via a callback.
|
|
154
|
+
- `rewriteSpecifier` (off): rewrite relative specifiers to a chosen extension or via a callback. Precedence: the callback (if provided) runs first; if it returns a string, that wins. If it returns `undefined` or `null`, the appenders still apply.
|
|
141
155
|
- `requireSource` (`builtin`): whether `require` comes from Node or `createRequire`.
|
|
142
156
|
- `cjsDefault` (`auto`): bundler-style default interop vs direct `module.exports`.
|
|
143
157
|
- `out`/`inPlace`: write the transformed code to a file; otherwise the function returns the transformed string only.
|
|
@@ -151,6 +165,13 @@ See [docs/esm-to-cjs.md](docs/esm-to-cjs.md) for deeper notes on live bindings,
|
|
|
151
165
|
> [!NOTE]
|
|
152
166
|
> Known limitations: `with` and unshadowed `eval` are rejected when raising CJS to ESM because the rewrite would be unsound; bare specifiers are not rewritten—only relative specifiers participate in `rewriteSpecifier`.
|
|
153
167
|
|
|
168
|
+
### Globals-only scope
|
|
169
|
+
|
|
170
|
+
- Rewrites module globals (`import.meta.*`, `__dirname`, `__filename`, `require.main` shims) for the target side.
|
|
171
|
+
- Optional specifier rewrites still run (`rewriteSpecifier`, `appendJsExtension`, `appendDirectoryIndex`).
|
|
172
|
+
- Leaves imports/exports and interop untouched (no export bag, no idiomaticExports, no live-binding synthesis, no helpers like `__requireResolve`).
|
|
173
|
+
- CJS→ESM: `require.resolve` maps to `import.meta.resolve` (URL return, ESM resolver) and may differ from CJS resolution. ESM→CJS: `import.meta` maps to CJS globals; no import lowering.
|
|
174
|
+
|
|
154
175
|
### Diagnostics callback example
|
|
155
176
|
|
|
156
177
|
Pass a `diagnostics` callback to surface CJS→ESM edge cases (mixed `module.exports`/`exports`, top-level `return`, legacy `require.cache`/`require.extensions`, live-binding reassignments, string-literal export names):
|
|
@@ -183,7 +204,7 @@ console.log(diagnostics)
|
|
|
183
204
|
|
|
184
205
|
## Pre-`tsc` transforms for TypeScript diagnostics
|
|
185
206
|
|
|
186
|
-
TypeScript reports asymmetric module-global errors (e.g., `import.meta` in CJS, `__dirname` in ESM) as tracked in [microsoft/TypeScript#58658](https://github.com/microsoft/TypeScript/issues/58658). You can mitigate this by running `@knighted/module` **before** `tsc` so the checker sees already-rewritten sources.
|
|
207
|
+
TypeScript reports asymmetric module-global errors (e.g., `import.meta` in CJS, `__dirname` in ESM) as tracked in [microsoft/TypeScript#58658](https://github.com/microsoft/TypeScript/issues/58658). You can mitigate this by running `@knighted/module` **before** `tsc` so the checker sees already-rewritten sources. For a specifier + globals-only pass that leaves import/export syntax for `tsc`, set `transformSyntax: 'globals-only'`.
|
|
187
208
|
|
|
188
209
|
Minimal flow:
|
|
189
210
|
|
package/dist/cjs/format.cjs
CHANGED
|
@@ -16,6 +16,36 @@ var _identifier2 = require("#helpers/identifier.js");
|
|
|
16
16
|
var _walk = require("#walk");
|
|
17
17
|
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
18
18
|
const isValidIdent = name => /^[$A-Z_a-z][$\w]*$/.test(name);
|
|
19
|
+
const expressionHasRequireCall = (node, shadowed) => {
|
|
20
|
+
let found = false;
|
|
21
|
+
const walkNode = n => {
|
|
22
|
+
if (!n || found) return;
|
|
23
|
+
if (n.type === 'CallExpression' && n.callee?.type === 'Identifier' && n.callee.name === 'require' && !shadowed.has('require')) {
|
|
24
|
+
found = true;
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (n.type === 'CallExpression' && n.callee?.type === 'MemberExpression' && n.callee.object?.type === 'Identifier' && n.callee.object.name === 'require' && !shadowed.has('require')) {
|
|
28
|
+
found = true;
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const keys = Object.keys(n);
|
|
32
|
+
for (const key of keys) {
|
|
33
|
+
const value = n[key];
|
|
34
|
+
if (!value) continue;
|
|
35
|
+
if (Array.isArray(value)) {
|
|
36
|
+
for (const item of value) {
|
|
37
|
+
if (item && typeof item === 'object') walkNode(item);
|
|
38
|
+
if (found) return;
|
|
39
|
+
}
|
|
40
|
+
} else if (value && typeof value === 'object') {
|
|
41
|
+
walkNode(value);
|
|
42
|
+
if (found) return;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
walkNode(node);
|
|
47
|
+
return found;
|
|
48
|
+
};
|
|
19
49
|
const exportAssignment = (name, expr, live) => {
|
|
20
50
|
const prop = isValidIdent(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
|
|
21
51
|
if (live === 'strict') {
|
|
@@ -397,14 +427,20 @@ const format = async (src, ast, opts) => {
|
|
|
397
427
|
loc
|
|
398
428
|
});
|
|
399
429
|
};
|
|
430
|
+
const transformMode = opts.transformSyntax;
|
|
431
|
+
const fullTransform = transformMode === true;
|
|
400
432
|
const moduleIdentifiers = await (0, _identifiers.collectModuleIdentifiers)(ast.program);
|
|
401
433
|
const shadowedBindings = new Set([...moduleIdentifiers.entries()].filter(([, meta]) => meta.declare.length > 0).map(([name]) => name));
|
|
402
|
-
if (opts.target === 'module' &&
|
|
434
|
+
if (opts.target === 'module' && fullTransform) {
|
|
403
435
|
if (shadowedBindings.has('module') || shadowedBindings.has('exports')) {
|
|
404
436
|
throw new Error('Cannot transform to ESM: module or exports is shadowed in module scope.');
|
|
405
437
|
}
|
|
406
438
|
}
|
|
407
439
|
const exportTable = opts.target === 'module' ? await (0, _exports.collectCjsExports)(ast.program) : null;
|
|
440
|
+
const idiomaticMode = opts.target === 'module' && fullTransform ? opts.idiomaticExports ?? 'safe' : 'off';
|
|
441
|
+
let useExportsBag = fullTransform;
|
|
442
|
+
let idiomaticPlan = null;
|
|
443
|
+
let idiomaticFallbackReason;
|
|
408
444
|
if (opts.target === 'module' && exportTable) {
|
|
409
445
|
const hasExportsVia = [...exportTable.values()].some(entry => entry.via.has('exports'));
|
|
410
446
|
const hasModuleExportsVia = [...exportTable.values()].some(entry => entry.via.has('module.exports'));
|
|
@@ -416,15 +452,163 @@ const format = async (src, ast, opts) => {
|
|
|
416
452
|
end: firstExports?.end ?? 0
|
|
417
453
|
});
|
|
418
454
|
}
|
|
455
|
+
const reservedExports = new Set(['await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield']);
|
|
456
|
+
const isValidExportName = name => /^[$A-Z_a-z][$\w]*$/.test(name) && !reservedExports.has(name);
|
|
457
|
+
const isAllowedRhs = node => {
|
|
458
|
+
return node.type === 'Identifier' || node.type === 'Literal' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' || node.type === 'ClassExpression';
|
|
459
|
+
};
|
|
460
|
+
const buildIdiomaticPlan = () => {
|
|
461
|
+
if (idiomaticMode === 'off') return {
|
|
462
|
+
ok: false,
|
|
463
|
+
reason: 'disabled'
|
|
464
|
+
};
|
|
465
|
+
const entries = [...exportTable.values()];
|
|
466
|
+
if (!entries.length) return {
|
|
467
|
+
ok: false,
|
|
468
|
+
reason: 'no-exports'
|
|
469
|
+
};
|
|
470
|
+
if (exportTable.hasUnsupportedExportWrite) {
|
|
471
|
+
return {
|
|
472
|
+
ok: false,
|
|
473
|
+
reason: 'unsupported-left'
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
const viaSet = new Set();
|
|
477
|
+
for (const entry of entries) {
|
|
478
|
+
entry.via.forEach(v => viaSet.add(v));
|
|
479
|
+
if (entry.hasGetter) return {
|
|
480
|
+
ok: false,
|
|
481
|
+
reason: 'getter-present'
|
|
482
|
+
};
|
|
483
|
+
if (entry.reassignments.length) return {
|
|
484
|
+
ok: false,
|
|
485
|
+
reason: 'reassignment'
|
|
486
|
+
};
|
|
487
|
+
if (entry.hasNonTopLevelWrite) return {
|
|
488
|
+
ok: false,
|
|
489
|
+
reason: 'non-top-level'
|
|
490
|
+
};
|
|
491
|
+
if (entry.writes.length !== 1) return {
|
|
492
|
+
ok: false,
|
|
493
|
+
reason: 'multiple-writes'
|
|
494
|
+
};
|
|
495
|
+
if (!isValidExportName(entry.key)) return {
|
|
496
|
+
ok: false,
|
|
497
|
+
reason: 'non-identifier-key'
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
if (viaSet.size > 1) return {
|
|
501
|
+
ok: false,
|
|
502
|
+
reason: 'mixed-exports'
|
|
503
|
+
};
|
|
504
|
+
const replacements = [];
|
|
505
|
+
const exportsOut = [];
|
|
506
|
+
const seen = new Set();
|
|
507
|
+
const requireShadowed = shadowedBindings;
|
|
508
|
+
const rhsSourceFor = node => {
|
|
509
|
+
const raw = code.slice(node.start, node.end);
|
|
510
|
+
return raw.replace(/\b__dirname\b/g, 'import.meta.dirname').replace(/\b__filename\b/g, 'import.meta.filename');
|
|
511
|
+
};
|
|
512
|
+
for (const entry of entries) {
|
|
513
|
+
const write = entry.writes[0];
|
|
514
|
+
if (write.type !== 'AssignmentExpression') {
|
|
515
|
+
return {
|
|
516
|
+
ok: false,
|
|
517
|
+
reason: 'unsupported-write-kind'
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
const left = write.left;
|
|
521
|
+
if (left.type !== 'MemberExpression' || left.computed || left.property.type !== 'Identifier') {
|
|
522
|
+
return {
|
|
523
|
+
ok: false,
|
|
524
|
+
reason: 'unsupported-left'
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
const base = left.object;
|
|
528
|
+
const propName = left.property.name;
|
|
529
|
+
const baseIsExports = base.type === 'Identifier' && base.name === 'exports';
|
|
530
|
+
const baseIsModuleExports = base.type === 'MemberExpression' && base.object.type === 'Identifier' && base.object.name === 'module' && base.property.type === 'Identifier' && base.property.name === 'exports';
|
|
531
|
+
if (!baseIsExports && !baseIsModuleExports) {
|
|
532
|
+
return {
|
|
533
|
+
ok: false,
|
|
534
|
+
reason: 'unsupported-base'
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
const rhs = write.right;
|
|
538
|
+
if (!isAllowedRhs(rhs)) return {
|
|
539
|
+
ok: false,
|
|
540
|
+
reason: 'unsupported-rhs'
|
|
541
|
+
};
|
|
542
|
+
if (expressionHasRequireCall(rhs, requireShadowed)) {
|
|
543
|
+
return {
|
|
544
|
+
ok: false,
|
|
545
|
+
reason: 'rhs-require'
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
const rhsSrc = rhsSourceFor(rhs);
|
|
549
|
+
if (propName === 'exports' && baseIsModuleExports) {
|
|
550
|
+
// module.exports = ... handles default
|
|
551
|
+
if (seen.has('default')) return {
|
|
552
|
+
ok: false,
|
|
553
|
+
reason: 'duplicate-default'
|
|
554
|
+
};
|
|
555
|
+
seen.add('default');
|
|
556
|
+
exportsOut.push(`export default ${rhsSrc};`);
|
|
557
|
+
} else {
|
|
558
|
+
if (seen.has(propName)) return {
|
|
559
|
+
ok: false,
|
|
560
|
+
reason: 'duplicate-key'
|
|
561
|
+
};
|
|
562
|
+
seen.add(propName);
|
|
563
|
+
if (rhs.type === 'Identifier') {
|
|
564
|
+
const rhsId = rhsSourceFor(rhs);
|
|
565
|
+
if (rhsId === rhs.name) {
|
|
566
|
+
exportsOut.push(`export { ${rhsId} as ${propName} };`);
|
|
567
|
+
} else {
|
|
568
|
+
exportsOut.push(`export const ${propName} = ${rhsId};`);
|
|
569
|
+
}
|
|
570
|
+
} else {
|
|
571
|
+
exportsOut.push(`export const ${propName} = ${rhsSrc};`);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
replacements.push({
|
|
575
|
+
start: write.start,
|
|
576
|
+
end: write.end
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
if (!seen.size) return {
|
|
580
|
+
ok: false,
|
|
581
|
+
reason: 'no-seen'
|
|
582
|
+
};
|
|
583
|
+
return {
|
|
584
|
+
ok: true,
|
|
585
|
+
plan: {
|
|
586
|
+
replacements,
|
|
587
|
+
exports: exportsOut
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
};
|
|
591
|
+
if (idiomaticMode !== 'off') {
|
|
592
|
+
const res = buildIdiomaticPlan();
|
|
593
|
+
if (res.ok && res.plan) {
|
|
594
|
+
useExportsBag = false;
|
|
595
|
+
idiomaticPlan = res.plan;
|
|
596
|
+
} else if (res.reason) {
|
|
597
|
+
idiomaticFallbackReason = res.reason;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
419
600
|
}
|
|
420
|
-
const shouldCheckTopLevelAwait = opts.target === 'commonjs' &&
|
|
601
|
+
const shouldCheckTopLevelAwait = opts.target === 'commonjs' && fullTransform;
|
|
421
602
|
const containsTopLevelAwait = shouldCheckTopLevelAwait ? hasTopLevelAwait(ast.program) : false;
|
|
603
|
+
if (idiomaticFallbackReason && idiomaticMode !== 'off') {
|
|
604
|
+
warnOnce('idiomatic-exports-fallback', `Idiomatic exports disabled for this file: ${idiomaticFallbackReason}. Falling back to helper exports.`);
|
|
605
|
+
}
|
|
422
606
|
const requireMainStrategy = opts.requireMainStrategy ?? 'import-meta-main';
|
|
423
607
|
let requireMainNeedsRealpath = false;
|
|
424
608
|
let needsRequireResolveHelper = false;
|
|
425
609
|
const nestedRequireStrategy = opts.nestedRequireStrategy ?? 'create-require';
|
|
426
|
-
const shouldLowerCjs = opts.target === 'commonjs' &&
|
|
427
|
-
const shouldRaiseEsm = opts.target === 'module' &&
|
|
610
|
+
const shouldLowerCjs = opts.target === 'commonjs' && fullTransform;
|
|
611
|
+
const shouldRaiseEsm = opts.target === 'module' && fullTransform;
|
|
428
612
|
let hoistedImports = [];
|
|
429
613
|
let hoistedStatements = [];
|
|
430
614
|
let pendingRequireTransforms = [];
|
|
@@ -574,7 +758,7 @@ const format = async (src, ast, opts) => {
|
|
|
574
758
|
onDiagnostic: (codeId, message, loc) => {
|
|
575
759
|
if (shouldRaiseEsm) warnOnce(codeId, message, loc);
|
|
576
760
|
}
|
|
577
|
-
});
|
|
761
|
+
}, useExportsBag, fullTransform);
|
|
578
762
|
}
|
|
579
763
|
if (shouldRaiseEsm && node.type === 'ThisExpression') {
|
|
580
764
|
const bindsThis = ancestor => {
|
|
@@ -594,7 +778,8 @@ const format = async (src, ast, opts) => {
|
|
|
594
778
|
code,
|
|
595
779
|
opts,
|
|
596
780
|
meta: exportsMeta,
|
|
597
|
-
shadowed: shadowedBindings
|
|
781
|
+
shadowed: shadowedBindings,
|
|
782
|
+
useExportsBag
|
|
598
783
|
});
|
|
599
784
|
}
|
|
600
785
|
}
|
|
@@ -604,6 +789,20 @@ const format = async (src, ast, opts) => {
|
|
|
604
789
|
code.overwrite(t.start, t.end, t.code);
|
|
605
790
|
}
|
|
606
791
|
}
|
|
792
|
+
if (!useExportsBag && idiomaticPlan) {
|
|
793
|
+
if (idiomaticPlan.exports.length === idiomaticPlan.replacements.length) {
|
|
794
|
+
idiomaticPlan.replacements.forEach((rep, idx) => {
|
|
795
|
+
code.overwrite(rep.start, rep.end, idiomaticPlan.exports[idx]);
|
|
796
|
+
});
|
|
797
|
+
} else {
|
|
798
|
+
for (const rep of idiomaticPlan.replacements) {
|
|
799
|
+
code.overwrite(rep.start, rep.end, ';');
|
|
800
|
+
}
|
|
801
|
+
if (idiomaticPlan.exports.length) {
|
|
802
|
+
code.append(`\n${idiomaticPlan.exports.join('\n')}\n`);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
}
|
|
607
806
|
if (shouldLowerCjs) {
|
|
608
807
|
const {
|
|
609
808
|
importTransforms,
|
|
@@ -623,7 +822,7 @@ const format = async (src, ast, opts) => {
|
|
|
623
822
|
code.prepend(`${interopHelper}exports.__esModule = true;\n`);
|
|
624
823
|
}
|
|
625
824
|
}
|
|
626
|
-
if (opts.target === 'module' &&
|
|
825
|
+
if (useExportsBag && opts.target === 'module' && fullTransform && exportTable) {
|
|
627
826
|
const isValidExportName = name => /^[$A-Z_a-z][$\w]*$/.test(name);
|
|
628
827
|
const asExportName = name => isValidExportName(name) ? name : JSON.stringify(name);
|
|
629
828
|
const accessProp = name => isValidExportName(name) ? `${_exports.exportsRename}.${name}` : `${_exports.exportsRename}[${JSON.stringify(name)}]`;
|
|
@@ -683,7 +882,7 @@ const format = async (src, ast, opts) => {
|
|
|
683
882
|
code.append(`\n${lines.join('\n')}\n`);
|
|
684
883
|
}
|
|
685
884
|
}
|
|
686
|
-
if (shouldRaiseEsm &&
|
|
885
|
+
if (shouldRaiseEsm && fullTransform) {
|
|
687
886
|
const importPrelude = [];
|
|
688
887
|
if (needsCreateRequire || needsRequireResolveHelper) {
|
|
689
888
|
importPrelude.push('import { createRequire } from "node:module";\n');
|
|
@@ -714,12 +913,14 @@ const format = async (src, ast, opts) => {
|
|
|
714
913
|
const resolved = req.resolve(id, parent);
|
|
715
914
|
return resolved.startsWith("file://") ? fileURLToPath(resolved) : resolved;
|
|
716
915
|
};\n` : '';
|
|
717
|
-
const
|
|
718
|
-
|
|
916
|
+
const exportsBagInit = useExportsBag ? `let ${_exports.exportsRename} = {};
|
|
917
|
+
` : '';
|
|
918
|
+
const modulePrelude = '';
|
|
919
|
+
const prelude = `${importPrelude.join('')}${importPrelude.length ? '\n' : ''}${setupPrelude.join('')}${setupPrelude.length ? '\n' : ''}${requireInit}${requireResolveInit}${exportsBagInit}${modulePrelude}void import.meta.filename;
|
|
719
920
|
`;
|
|
720
921
|
code.prepend(prelude);
|
|
721
922
|
}
|
|
722
|
-
if (opts.target === 'commonjs' &&
|
|
923
|
+
if (opts.target === 'commonjs' && fullTransform && containsTopLevelAwait) {
|
|
723
924
|
const body = code.toString();
|
|
724
925
|
if (opts.topLevelAwait === 'wrap') {
|
|
725
926
|
const tlaPromise = `const __tla = (async () => {\n${body}\nreturn module.exports;\n})();\n`;
|
|
@@ -12,7 +12,8 @@ const identifier = ({
|
|
|
12
12
|
code,
|
|
13
13
|
opts,
|
|
14
14
|
meta,
|
|
15
|
-
shadowed
|
|
15
|
+
shadowed,
|
|
16
|
+
useExportsBag = true
|
|
16
17
|
}) => {
|
|
17
18
|
if (opts.target === 'module') {
|
|
18
19
|
const {
|
|
@@ -33,7 +34,7 @@ const identifier = ({
|
|
|
33
34
|
case 'exports':
|
|
34
35
|
{
|
|
35
36
|
const parent = ancestors[ancestors.length - 2];
|
|
36
|
-
if (opts.transformSyntax) {
|
|
37
|
+
if (opts.transformSyntax && useExportsBag) {
|
|
37
38
|
if (parent.type === 'AssignmentExpression' && parent.left === node) {
|
|
38
39
|
// The code is reassigning `exports` to something else.
|
|
39
40
|
|
|
@@ -5,15 +5,33 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
exports.memberExpression = void 0;
|
|
7
7
|
var _exports = require("#utils/exports.js");
|
|
8
|
-
const memberExpression = (node, parent, src, options, shadowed, extras) => {
|
|
8
|
+
const memberExpression = (node, parent, src, options, shadowed, extras, useExportsBag = true, rewriteExports = true) => {
|
|
9
9
|
if (options.target === 'module') {
|
|
10
|
-
if (
|
|
11
|
-
|
|
10
|
+
if (rewriteExports && !useExportsBag) {
|
|
11
|
+
if (parent?.type === 'MemberExpression' && parent.object === node && parent.property.type === 'Identifier') {
|
|
12
|
+
const baseIsExportsIdent = node.object.type === 'Identifier' && node.object.name === 'exports';
|
|
13
|
+
const baseIsModuleExports = node.object.type === 'Identifier' && node.object.name === 'module' && node.property.type === 'Identifier' && node.property.name === 'exports';
|
|
14
|
+
if (baseIsExportsIdent || baseIsModuleExports) {
|
|
15
|
+
src.update(parent.start, parent.end, parent.property.name);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
if (node.object.type === 'Identifier' && node.property.type === 'Identifier' && node.object.name === 'module' && node.property.name === 'exports') {
|
|
20
|
+
src.update(node.start, node.end, 'undefined');
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
12
23
|
}
|
|
13
|
-
if (node.object.type === 'Identifier' && node.
|
|
14
|
-
src.update(node.start, node.end, _exports.exportsRename);
|
|
24
|
+
if (rewriteExports && (node.object.type === 'Identifier' && shadowed?.has(node.object.name) || node.property.type === 'Identifier' && shadowed?.has(node.property.name))) {
|
|
15
25
|
return;
|
|
16
26
|
}
|
|
27
|
+
if (rewriteExports) {
|
|
28
|
+
if (node.object.type === 'Identifier' && node.property.type === 'Identifier' && node.object.name === 'module' && node.property.name === 'exports') {
|
|
29
|
+
if (useExportsBag) {
|
|
30
|
+
src.update(node.start, node.end, _exports.exportsRename);
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
17
35
|
if (node.object.type === 'Identifier' && node.property.type === 'Identifier' && node.object.name === 'require') {
|
|
18
36
|
const {
|
|
19
37
|
start,
|
|
@@ -32,6 +50,10 @@ const memberExpression = (node, parent, src, options, shadowed, extras) => {
|
|
|
32
50
|
src.update(start, end, 'import.meta.main');
|
|
33
51
|
break;
|
|
34
52
|
case 'resolve':
|
|
53
|
+
if (options.transformSyntax !== true) {
|
|
54
|
+
src.update(start, end, 'import.meta.resolve');
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
35
57
|
extras?.onRequireResolve?.();
|
|
36
58
|
src.update(start, end, extras?.requireResolveName ?? 'import.meta.resolve');
|
|
37
59
|
break;
|
|
@@ -9,5 +9,5 @@ type MemberExpressionExtras = {
|
|
|
9
9
|
end: number;
|
|
10
10
|
}) => void;
|
|
11
11
|
};
|
|
12
|
-
export declare const memberExpression: (node: MemberExpression, parent: Node | null, src: MagicString, options: FormatterOptions, shadowed?: Set<string>, extras?: MemberExpressionExtras) => void;
|
|
12
|
+
export declare const memberExpression: (node: MemberExpression, parent: Node | null, src: MagicString, options: FormatterOptions, shadowed?: Set<string>, extras?: MemberExpressionExtras, useExportsBag?: boolean, rewriteExports?: boolean) => void;
|
|
13
13
|
export {};
|
package/dist/cjs/module.cjs
CHANGED
|
@@ -47,7 +47,7 @@ const rewriteSpecifierValue = (value, rewriteSpecifier) => {
|
|
|
47
47
|
const collapsed = collapseSpecifier(value);
|
|
48
48
|
const relative = /^(?:\.\.?)\//;
|
|
49
49
|
if (relative.test(collapsed)) {
|
|
50
|
-
return value.replace(/(.+)\.(?:m|c)?(?:j|t)
|
|
50
|
+
return value.replace(/(.+)\.(?:m|c)?(?:j|t)sx?([)'"]*)?$/, `$1${rewriteSpecifier}$2`);
|
|
51
51
|
}
|
|
52
52
|
};
|
|
53
53
|
const normalizeBuiltinSpecifier = value => {
|
|
@@ -160,6 +160,7 @@ const defaultOptions = {
|
|
|
160
160
|
requireSource: 'builtin',
|
|
161
161
|
nestedRequireStrategy: 'create-require',
|
|
162
162
|
cjsDefault: 'auto',
|
|
163
|
+
idiomaticExports: 'safe',
|
|
163
164
|
topLevelAwait: 'error',
|
|
164
165
|
out: undefined,
|
|
165
166
|
inPlace: false
|
package/dist/cjs/specifier.cjs
CHANGED
|
@@ -118,6 +118,9 @@ const formatSpecifiers = async (src, ast, cb) => {
|
|
|
118
118
|
};
|
|
119
119
|
await (0, _walk.walk)(ast.program, {
|
|
120
120
|
enter(node) {
|
|
121
|
+
if (node.type === 'ImportExpression') {
|
|
122
|
+
formatExpression(node);
|
|
123
|
+
}
|
|
121
124
|
if (node.type === 'ExpressionStatement') {
|
|
122
125
|
const {
|
|
123
126
|
expression
|
package/dist/cjs/types.d.cts
CHANGED
|
@@ -6,8 +6,13 @@ export type ModuleOptions = {
|
|
|
6
6
|
target: 'module' | 'commonjs';
|
|
7
7
|
/** Explicit source type; auto infers from file extension. */
|
|
8
8
|
sourceType?: 'auto' | 'module' | 'commonjs';
|
|
9
|
-
/**
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Enable syntax transforms beyond parsing.
|
|
11
|
+
* - true: full CJS↔ESM lowering/raising
|
|
12
|
+
* - 'globals-only': rewrite module-global differences (import.meta, __dirname/filename, require.main shims) while leaving import/export shapes untouched
|
|
13
|
+
* - false/undefined: no syntax transforms
|
|
14
|
+
*/
|
|
15
|
+
transformSyntax?: boolean | 'globals-only';
|
|
11
16
|
/** How to emit live bindings for ESM exports. */
|
|
12
17
|
liveBindings?: 'strict' | 'loose' | 'off';
|
|
13
18
|
/** Rewrite import specifiers (e.g. add extensions). */
|
|
@@ -16,7 +21,8 @@ export type ModuleOptions = {
|
|
|
16
21
|
appendJsExtension?: 'off' | 'relative-only' | 'all';
|
|
17
22
|
/** Add directory index (e.g. /index.js) or disable. */
|
|
18
23
|
appendDirectoryIndex?: string | false;
|
|
19
|
-
/**
|
|
24
|
+
/** Precedence: rewriteSpecifier runs first; if it returns a string that wins. If it returns undefined or null, appenders apply. Bare specifiers are never modified by appenders. */
|
|
25
|
+
/** Control __dirname/__filename handling (inject shims, preserve existing, or throw on use). */
|
|
20
26
|
dirFilename?: 'inject' | 'preserve' | 'error';
|
|
21
27
|
/** How to treat import.meta. */
|
|
22
28
|
importMeta?: 'preserve' | 'shim' | 'error';
|
|
@@ -32,6 +38,8 @@ export type ModuleOptions = {
|
|
|
32
38
|
nestedRequireStrategy?: 'create-require' | 'dynamic-import';
|
|
33
39
|
/** Default interop style for CommonJS default imports. */
|
|
34
40
|
cjsDefault?: 'module-exports' | 'auto' | 'none';
|
|
41
|
+
/** Emit idiomatic exports when raising CJS to ESM. */
|
|
42
|
+
idiomaticExports?: 'off' | 'safe' | 'aggressive';
|
|
35
43
|
/** Handling for top-level await constructs. */
|
|
36
44
|
topLevelAwait?: 'error' | 'wrap' | 'preserve';
|
|
37
45
|
/** Optional diagnostics sink for warnings/errors emitted during transform. */
|
|
@@ -67,6 +75,7 @@ export type CjsExport = {
|
|
|
67
75
|
via: Set<'exports' | 'module.exports'>;
|
|
68
76
|
reassignments: SpannedNode[];
|
|
69
77
|
hasGetter?: boolean;
|
|
78
|
+
hasNonTopLevelWrite?: boolean;
|
|
70
79
|
};
|
|
71
80
|
export type IdentMeta = {
|
|
72
81
|
declare: SpannedNode[];
|
|
@@ -69,6 +69,12 @@ const collectCjsExports = async ast => {
|
|
|
69
69
|
const localToExport = new Map();
|
|
70
70
|
const aliases = new Map();
|
|
71
71
|
const literals = new Map();
|
|
72
|
+
let hasUnsupportedExportWrite = false;
|
|
73
|
+
const isTopLevelWrite = ancestors => {
|
|
74
|
+
const parent = ancestors[ancestors.length - 2];
|
|
75
|
+
const grandparent = ancestors[ancestors.length - 3];
|
|
76
|
+
return grandparent?.type === 'Program' && (parent?.type === 'ExpressionStatement' || parent?.type === 'VariableDeclaration');
|
|
77
|
+
};
|
|
72
78
|
const addExport = (ref, node, rhs, options) => {
|
|
73
79
|
const entry = exportsMap.get(ref.key) ?? {
|
|
74
80
|
key: ref.key,
|
|
@@ -81,6 +87,9 @@ const collectCjsExports = async ast => {
|
|
|
81
87
|
if (options?.hasGetter) {
|
|
82
88
|
entry.hasGetter = true;
|
|
83
89
|
}
|
|
90
|
+
if (options?.topLevel === false) {
|
|
91
|
+
entry.hasNonTopLevelWrite = true;
|
|
92
|
+
}
|
|
84
93
|
if (rhs) {
|
|
85
94
|
entry.fromIdentifier ??= rhs.name;
|
|
86
95
|
const set = localToExport.get(rhs.name) ?? new Set();
|
|
@@ -110,9 +119,15 @@ const collectCjsExports = async ast => {
|
|
|
110
119
|
const target = resolveExportTarget(node.left, aliases, literals, ancestors);
|
|
111
120
|
if (target) {
|
|
112
121
|
const rhsIdent = node.right.type === 'Identifier' ? node.right : undefined;
|
|
113
|
-
|
|
122
|
+
const topLevel = isTopLevelWrite(ancestors);
|
|
123
|
+
addExport(target, node, rhsIdent, {
|
|
124
|
+
topLevel
|
|
125
|
+
});
|
|
114
126
|
return;
|
|
115
127
|
}
|
|
128
|
+
if (node.left.type === 'MemberExpression' && resolveBase(node.left.object, aliases, ancestors)) {
|
|
129
|
+
hasUnsupportedExportWrite = true;
|
|
130
|
+
}
|
|
116
131
|
if (node.left.type === 'Identifier') {
|
|
117
132
|
const keys = localToExport.get(node.left.name);
|
|
118
133
|
if (keys) {
|
|
@@ -129,7 +144,12 @@ const collectCjsExports = async ast => {
|
|
|
129
144
|
const findExportRefs = pattern => {
|
|
130
145
|
if (pattern.type === 'MemberExpression') {
|
|
131
146
|
const ref = resolveExportTarget(pattern, aliases, literals, ancestors);
|
|
132
|
-
if (ref)
|
|
147
|
+
if (ref) {
|
|
148
|
+
const topLevel = isTopLevelWrite(ancestors);
|
|
149
|
+
addExport(ref, node, undefined, {
|
|
150
|
+
topLevel
|
|
151
|
+
});
|
|
152
|
+
}
|
|
133
153
|
return;
|
|
134
154
|
}
|
|
135
155
|
if (pattern.type === 'ObjectPattern') {
|
|
@@ -171,10 +191,13 @@ const collectCjsExports = async ast => {
|
|
|
171
191
|
if (prop.value.type === 'Identifier') {
|
|
172
192
|
rhsIdent = prop.value;
|
|
173
193
|
}
|
|
194
|
+
const topLevel = isTopLevelWrite(ancestors);
|
|
174
195
|
addExport({
|
|
175
196
|
key: keyName,
|
|
176
197
|
via: ref
|
|
177
|
-
}, node, rhsIdent
|
|
198
|
+
}, node, rhsIdent, {
|
|
199
|
+
topLevel
|
|
200
|
+
});
|
|
178
201
|
}
|
|
179
202
|
}
|
|
180
203
|
}
|
|
@@ -203,11 +226,13 @@ const collectCjsExports = async ast => {
|
|
|
203
226
|
// Setter-only doesn’t create a readable export; ignore beyond marking write
|
|
204
227
|
}
|
|
205
228
|
}
|
|
229
|
+
const topLevel = isTopLevelWrite(ancestors);
|
|
206
230
|
addExport({
|
|
207
231
|
key: keyName,
|
|
208
232
|
via: target
|
|
209
233
|
}, node, rhsIdent, {
|
|
210
|
-
hasGetter
|
|
234
|
+
hasGetter,
|
|
235
|
+
topLevel
|
|
211
236
|
});
|
|
212
237
|
}
|
|
213
238
|
|
|
@@ -234,17 +259,20 @@ const collectCjsExports = async ast => {
|
|
|
234
259
|
hasGetter = true;
|
|
235
260
|
}
|
|
236
261
|
}
|
|
262
|
+
const topLevel = isTopLevelWrite(ancestors);
|
|
237
263
|
addExport({
|
|
238
264
|
key: keyName,
|
|
239
265
|
via: target
|
|
240
266
|
}, node, rhsIdent, {
|
|
241
|
-
hasGetter
|
|
267
|
+
hasGetter,
|
|
268
|
+
topLevel
|
|
242
269
|
});
|
|
243
270
|
}
|
|
244
271
|
}
|
|
245
272
|
}
|
|
246
273
|
}
|
|
247
274
|
});
|
|
275
|
+
exportsMap.hasUnsupportedExportWrite = hasUnsupportedExportWrite;
|
|
248
276
|
return exportsMap;
|
|
249
277
|
};
|
|
250
278
|
exports.collectCjsExports = collectCjsExports;
|