@knighted/module 1.3.0 → 1.3.1

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.
Files changed (46) hide show
  1. package/dist/ast.d.ts +1 -0
  2. package/dist/async.d.ts +4 -0
  3. package/dist/buildEsmPrelude.d.ts +14 -0
  4. package/dist/cjs/ast.d.cts +1 -0
  5. package/dist/cjs/async.d.cts +4 -0
  6. package/dist/cjs/buildEsmPrelude.d.cts +14 -0
  7. package/dist/cjs/exportBagToEsm.d.cts +13 -0
  8. package/dist/cjs/format.cjs +78 -852
  9. package/dist/cjs/formatVisitor.d.cts +42 -0
  10. package/dist/cjs/helpers/async.cjs +57 -0
  11. package/dist/cjs/idiomaticPlan.d.cts +28 -0
  12. package/dist/cjs/interopHelpers.d.cts +5 -0
  13. package/dist/cjs/lowerCjsRequireToImports.d.cts +17 -0
  14. package/dist/cjs/lowerEsmToCjs.d.cts +22 -0
  15. package/dist/cjs/pipeline/buildEsmPrelude.cjs +65 -0
  16. package/dist/cjs/pipeline/exportBagToEsm.cjs +81 -0
  17. package/dist/cjs/pipeline/formatVisitor.cjs +171 -0
  18. package/dist/cjs/pipeline/idiomaticPlan.cjs +224 -0
  19. package/dist/cjs/pipeline/interopHelpers.cjs +10 -0
  20. package/dist/cjs/pipeline/lowerCjsRequireToImports.cjs +110 -0
  21. package/dist/cjs/pipeline/lowerEsmToCjs.cjs +204 -0
  22. package/dist/exportBagToEsm.d.ts +13 -0
  23. package/dist/format.js +74 -848
  24. package/dist/formatVisitor.d.ts +42 -0
  25. package/dist/helpers/ast.d.ts +1 -0
  26. package/dist/helpers/async.d.ts +4 -0
  27. package/dist/helpers/async.js +50 -0
  28. package/dist/idiomaticPlan.d.ts +28 -0
  29. package/dist/interopHelpers.d.ts +5 -0
  30. package/dist/lowerCjsRequireToImports.d.ts +17 -0
  31. package/dist/lowerEsmToCjs.d.ts +22 -0
  32. package/dist/pipeline/buildEsmPrelude.d.ts +14 -0
  33. package/dist/pipeline/buildEsmPrelude.js +59 -0
  34. package/dist/pipeline/exportBagToEsm.d.ts +13 -0
  35. package/dist/pipeline/exportBagToEsm.js +75 -0
  36. package/dist/pipeline/formatVisitor.d.ts +42 -0
  37. package/dist/pipeline/formatVisitor.js +166 -0
  38. package/dist/pipeline/idiomaticPlan.d.ts +28 -0
  39. package/dist/pipeline/idiomaticPlan.js +218 -0
  40. package/dist/pipeline/interopHelpers.d.ts +5 -0
  41. package/dist/pipeline/interopHelpers.js +5 -0
  42. package/dist/pipeline/lowerCjsRequireToImports.d.ts +17 -0
  43. package/dist/pipeline/lowerCjsRequireToImports.js +102 -0
  44. package/dist/pipeline/lowerEsmToCjs.d.ts +22 -0
  45. package/dist/pipeline/lowerEsmToCjs.js +197 -0
  46. package/package.json +1 -1
package/dist/format.js CHANGED
@@ -1,403 +1,23 @@
1
- import { getModuleExportName, isAstNode, isCallExpressionNode, isIdentifierNode, isMemberExpressionNode } from './helpers/ast.js';
2
1
  import MagicString from 'magic-string';
2
+ import { hasTopLevelAwait, isAsyncContext } from './helpers/async.js';
3
+ import { isIdentifierName } from './helpers/identifier.js';
4
+ import { assignmentExpression } from './formatters/assignmentExpression.js';
3
5
  import { identifier } from './formatters/identifier.js';
4
- import { metaProperty } from './formatters/metaProperty.js';
5
6
  import { memberExpression } from './formatters/memberExpression.js';
6
- import { assignmentExpression } from './formatters/assignmentExpression.js';
7
- import { isValidUrl } from './utils/url.js';
8
- import { exportsRename, collectCjsExports } from './utils/exports.js';
7
+ import { metaProperty } from './formatters/metaProperty.js';
8
+ import { buildIdiomaticPlan } from './pipeline/idiomaticPlan.js';
9
+ import { buildEsmPrelude } from './pipeline/buildEsmPrelude.js';
10
+ import { exportBagToEsm } from './pipeline/exportBagToEsm.js';
11
+ import { isRequireCall, isStaticRequire, lowerCjsRequireToImports } from './pipeline/lowerCjsRequireToImports.js';
12
+ import { lowerEsmToCjs } from './pipeline/lowerEsmToCjs.js';
13
+ import { buildFormatVisitor } from './pipeline/formatVisitor.js';
14
+ import { interopHelper } from './pipeline/interopHelpers.js';
15
+ import { collectCjsExports } from './utils/exports.js';
9
16
  import { collectModuleIdentifiers } from './utils/identifiers.js';
10
- import { isIdentifierName } from './helpers/identifier.js';
17
+ import { isValidUrl } from './utils/url.js';
11
18
  import { ancestorWalk } from './walk.js';
12
- const isValidIdent = name => /^[$A-Z_a-z][$\w]*$/.test(name);
13
- const expressionHasRequireCall = (node, shadowed) => {
14
- let found = false;
15
- const walkNode = n => {
16
- if (!isAstNode(n) || found) return;
17
- if (isCallExpressionNode(n) && isIdentifierNode(n.callee) && n.callee.name === 'require' && !shadowed.has('require')) {
18
- found = true;
19
- return;
20
- }
21
- if (isCallExpressionNode(n) && isMemberExpressionNode(n.callee) && isIdentifierNode(n.callee.object) && n.callee.object.name === 'require' && !shadowed.has('require')) {
22
- found = true;
23
- return;
24
- }
25
- const record = n;
26
- const keys = Object.keys(record);
27
- for (const key of keys) {
28
- const value = record[key];
29
- if (!value) continue;
30
- if (Array.isArray(value)) {
31
- for (const item of value) {
32
- if (item && typeof item === 'object') walkNode(item);
33
- if (found) return;
34
- }
35
- } else if (value && typeof value === 'object') {
36
- walkNode(value);
37
- if (found) return;
38
- }
39
- }
40
- };
41
- walkNode(node);
42
- return found;
43
- };
44
- const exportAssignment = (name, expr, live) => {
45
- const prop = isValidIdent(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
46
- if (live === 'strict') {
47
- const key = JSON.stringify(name);
48
- return `Object.defineProperty(exports, ${key}, { enumerable: true, get: () => ${expr} });`;
49
- }
50
- return `exports${prop} = ${expr};`;
51
- };
52
- const defaultInteropName = '__interopDefault';
53
- const interopHelper = `const ${defaultInteropName} = mod => (mod && mod.__esModule ? mod.default : mod);\n`;
54
- const requireInteropName = '__requireDefault';
55
- const requireInteropHelper = `const ${requireInteropName} = mod => (mod && typeof mod === 'object' && 'default' in mod ? mod.default : mod);\n`;
56
- const isRequireCallee = (callee, shadowed) => {
57
- if (callee.type === 'Identifier' && callee.name === 'require' && !shadowed.has('require')) {
58
- return true;
59
- }
60
- if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'module' && !shadowed.has('module') && callee.property.type === 'Identifier' && callee.property.name === 'require') {
61
- return true;
62
- }
63
- return false;
64
- };
65
- const isStaticRequire = (node, shadowed) => node.type === 'CallExpression' && isRequireCallee(node.callee, shadowed) && node.arguments.length === 1 && node.arguments[0].type === 'Literal' && typeof node.arguments[0].value === 'string';
66
- const isRequireCall = (node, shadowed) => node.type === 'CallExpression' && isRequireCallee(node.callee, shadowed);
67
- const lowerCjsRequireToImports = (program, code, shadowed) => {
68
- const transforms = [];
69
- const imports = [];
70
- const hoisted = [];
71
- let nsIndex = 0;
72
- let needsCreateRequire = false;
73
- let needsInteropHelper = false;
74
- const isJsonSpecifier = value => {
75
- const base = value.split(/[?#]/)[0] ?? value;
76
- return base.endsWith('.json');
77
- };
78
- for (const stmt of program.body) {
79
- if (stmt.type === 'VariableDeclaration') {
80
- const decls = stmt.declarations;
81
- const allStatic = decls.length > 0 && decls.every(decl => decl.init && isStaticRequire(decl.init, shadowed));
82
- if (allStatic) {
83
- for (const decl of decls) {
84
- const init = decl.init;
85
- if (!init || !isCallExpressionNode(init)) {
86
- needsCreateRequire = true;
87
- continue;
88
- }
89
- const arg = init.arguments[0];
90
- const source = code.slice(arg.start, arg.end);
91
- const value = arg.value;
92
- const isJson = typeof value === 'string' && isJsonSpecifier(value);
93
- const ns = `__cjsImport${nsIndex++}`;
94
- const jsonImport = isJson ? `${source} with { type: "json" }` : source;
95
- if (decl.id.type === 'Identifier') {
96
- imports.push(isJson ? `import ${ns} from ${jsonImport};\n` : `import * as ${ns} from ${jsonImport};\n`);
97
- hoisted.push(isJson ? `const ${decl.id.name} = ${ns};\n` : `const ${decl.id.name} = ${requireInteropName}(${ns});\n`);
98
- needsInteropHelper ||= !isJson;
99
- } else if (decl.id.type === 'ObjectPattern' || decl.id.type === 'ArrayPattern') {
100
- const pattern = code.slice(decl.id.start, decl.id.end);
101
- imports.push(isJson ? `import ${ns} from ${jsonImport};\n` : `import * as ${ns} from ${jsonImport};\n`);
102
- hoisted.push(isJson ? `const ${pattern} = ${ns};\n` : `const ${pattern} = ${requireInteropName}(${ns});\n`);
103
- needsInteropHelper ||= !isJson;
104
- } else {
105
- needsCreateRequire = true;
106
- }
107
- }
108
- transforms.push({
109
- start: stmt.start,
110
- end: stmt.end,
111
- code: ';\n'
112
- });
113
- continue;
114
- }
115
- for (const decl of decls) {
116
- const init = decl.init;
117
- if (init && isRequireCall(init, shadowed)) {
118
- needsCreateRequire = true;
119
- }
120
- }
121
- }
122
- if (stmt.type === 'ExpressionStatement') {
123
- const expr = stmt.expression;
124
- if (expr && isStaticRequire(expr, shadowed)) {
125
- if (!isCallExpressionNode(expr)) {
126
- needsCreateRequire = true;
127
- continue;
128
- }
129
- const arg = expr.arguments[0];
130
- const source = code.slice(arg.start, arg.end);
131
- const value = arg.value;
132
- const isJson = typeof value === 'string' && isJsonSpecifier(value);
133
- const jsonImport = isJson ? `${source} with { type: "json" }` : source;
134
- imports.push(`import ${jsonImport};\n`);
135
- transforms.push({
136
- start: stmt.start,
137
- end: stmt.end,
138
- code: ';\n'
139
- });
140
- continue;
141
- }
142
- if (expr && isRequireCall(expr, shadowed)) {
143
- needsCreateRequire = true;
144
- }
145
- }
146
- }
147
- return {
148
- transforms,
149
- imports,
150
- hoisted,
151
- needsCreateRequire,
152
- needsInteropHelper
153
- };
154
- };
155
19
  const isRequireMainMember = (node, shadowed) => node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'require' && !shadowed.has('require') && node.property.type === 'Identifier' && node.property.name === 'main';
156
- const hasTopLevelAwait = program => {
157
- let found = false;
158
- const walkNode = (node, inFunction) => {
159
- if (found) return;
160
- if (!isAstNode(node)) return;
161
- switch (node.type) {
162
- case 'FunctionDeclaration':
163
- case 'FunctionExpression':
164
- case 'ArrowFunctionExpression':
165
- case 'ClassDeclaration':
166
- case 'ClassExpression':
167
- inFunction = true;
168
- break;
169
- }
170
- if (!inFunction && node.type === 'AwaitExpression') {
171
- found = true;
172
- return;
173
- }
174
- const record = node;
175
- const keys = Object.keys(record);
176
- for (const key of keys) {
177
- const value = record[key];
178
- if (!value) continue;
179
- if (Array.isArray(value)) {
180
- for (const item of value) {
181
- if (item && typeof item === 'object') {
182
- walkNode(item, inFunction);
183
- if (found) return;
184
- }
185
- }
186
- } else if (value && typeof value === 'object') {
187
- walkNode(value, inFunction);
188
- if (found) return;
189
- }
190
- }
191
- };
192
- walkNode(program, false);
193
- return found;
194
- };
195
- const isAsyncContext = ancestors => {
196
- for (let i = ancestors.length - 1; i >= 0; i -= 1) {
197
- const node = ancestors[i];
198
- if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
199
- return !!node.async;
200
- }
201
- if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
202
- return false;
203
- }
204
- }
205
-
206
- // Program scope (top-level) supports await in ESM.
207
- return true;
208
- };
209
- const lowerEsmToCjs = (program, code, opts, containsTopLevelAwait) => {
210
- const live = opts.liveBindings ?? 'strict';
211
- const importTransforms = [];
212
- const exportTransforms = [];
213
- let needsInterop = false;
214
- let importIndex = 0;
215
- for (const node of program.body) {
216
- if (node.type === 'ImportDeclaration') {
217
- const srcLiteral = code.slice(node.source.start, node.source.end);
218
- const specifiers = node.specifiers ?? [];
219
- const defaultSpec = specifiers.find(s => s.type === 'ImportDefaultSpecifier');
220
- const namespaceSpec = specifiers.find(s => s.type === 'ImportNamespaceSpecifier');
221
- const namedSpecs = specifiers.filter(s => s.type === 'ImportSpecifier');
222
20
 
223
- // Side-effect import
224
- if (!specifiers.length) {
225
- importTransforms.push({
226
- start: node.start,
227
- end: node.end,
228
- code: `require(${srcLiteral});\n`,
229
- needsInterop: false
230
- });
231
- continue;
232
- }
233
- const modIdent = `__mod${importIndex++}`;
234
- const lines = [];
235
- lines.push(`const ${modIdent} = require(${srcLiteral});`);
236
- if (namespaceSpec) {
237
- lines.push(`const ${namespaceSpec.local.name} = ${modIdent};`);
238
- }
239
- if (defaultSpec) {
240
- let init = modIdent;
241
- switch (opts.cjsDefault) {
242
- case 'module-exports':
243
- init = modIdent;
244
- break;
245
- case 'none':
246
- init = `${modIdent}.default`;
247
- break;
248
- case 'auto':
249
- default:
250
- init = `${defaultInteropName}(${modIdent})`;
251
- needsInterop = true;
252
- break;
253
- }
254
- lines.push(`const ${defaultSpec.local.name} = ${init};`);
255
- }
256
- if (namedSpecs.length) {
257
- const pairs = namedSpecs.map(s => {
258
- const imported = getModuleExportName(s.imported);
259
- if (!imported) return s.local.name;
260
- const local = s.local.name;
261
- return imported === local ? imported : `${imported}: ${local}`;
262
- });
263
- lines.push(`const { ${pairs.join(', ')} } = ${modIdent};`);
264
- }
265
- importTransforms.push({
266
- start: node.start,
267
- end: node.end,
268
- code: `${lines.join('\n')}\n`,
269
- needsInterop
270
- });
271
- }
272
- if (node.type === 'ExportNamedDeclaration') {
273
- // Handle declaration exports
274
- if (node.declaration) {
275
- const decl = node.declaration;
276
- const declSrc = code.slice(decl.start, decl.end);
277
- const exportedNames = [];
278
- if (decl.type === 'VariableDeclaration') {
279
- for (const d of decl.declarations) {
280
- if (d.id.type === 'Identifier') {
281
- exportedNames.push(d.id.name);
282
- }
283
- }
284
- } else if ('id' in decl && decl.id?.type === 'Identifier') {
285
- exportedNames.push(decl.id.name);
286
- }
287
- const exportLines = exportedNames.map(name => exportAssignment(name, name, live));
288
- exportTransforms.push({
289
- start: node.start,
290
- end: node.end,
291
- code: `${declSrc}\n${exportLines.join('\n')}\n`
292
- });
293
- continue;
294
- }
295
-
296
- // Handle re-export or local specifiers
297
- if (node.specifiers?.length) {
298
- if (node.source) {
299
- const srcLiteral = code.slice(node.source.start, node.source.end);
300
- const modIdent = `__mod${importIndex++}`;
301
- const lines = [`const ${modIdent} = require(${srcLiteral});`];
302
- for (const spec of node.specifiers) {
303
- if (spec.type !== 'ExportSpecifier') continue;
304
- const exported = getModuleExportName(spec.exported);
305
- const imported = getModuleExportName(spec.local);
306
- if (!exported || !imported) continue;
307
- let rhs = `${modIdent}.${imported}`;
308
- if (imported === 'default') {
309
- rhs = `${defaultInteropName}(${modIdent})`;
310
- needsInterop = true;
311
- }
312
- lines.push(exportAssignment(exported, rhs, live));
313
- }
314
- exportTransforms.push({
315
- start: node.start,
316
- end: node.end,
317
- code: `${lines.join('\n')}\n`,
318
- needsInterop
319
- });
320
- } else {
321
- const lines = [];
322
- for (const spec of node.specifiers) {
323
- if (spec.type !== 'ExportSpecifier') continue;
324
- const exported = getModuleExportName(spec.exported);
325
- const local = getModuleExportName(spec.local);
326
- if (!exported || !local) continue;
327
- lines.push(exportAssignment(exported, local, live));
328
- }
329
- exportTransforms.push({
330
- start: node.start,
331
- end: node.end,
332
- code: `${lines.join('\n')}\n`
333
- });
334
- }
335
- }
336
- }
337
- if (node.type === 'ExportDefaultDeclaration') {
338
- const decl = node.declaration;
339
- const useExportsObject = containsTopLevelAwait && opts.topLevelAwait !== 'error';
340
- if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') {
341
- if (decl.id?.name) {
342
- const declSrc = code.slice(decl.start, decl.end);
343
- const assign = useExportsObject ? `exports.default = ${decl.id.name};` : `module.exports = ${decl.id.name};`;
344
- exportTransforms.push({
345
- start: node.start,
346
- end: node.end,
347
- code: `${declSrc}\n${assign}\n`
348
- });
349
- } else {
350
- const declSrc = code.slice(decl.start, decl.end);
351
- const assign = useExportsObject ? `exports.default = ${declSrc};` : `module.exports = ${declSrc};`;
352
- exportTransforms.push({
353
- start: node.start,
354
- end: node.end,
355
- code: `${assign}\n`
356
- });
357
- }
358
- } else {
359
- const exprSrc = code.slice(decl.start, decl.end);
360
- const assign = useExportsObject ? `exports.default = ${exprSrc};` : `module.exports = ${exprSrc};`;
361
- exportTransforms.push({
362
- start: node.start,
363
- end: node.end,
364
- code: `${assign}\n`
365
- });
366
- }
367
- }
368
- if (node.type === 'ExportAllDeclaration') {
369
- const srcLiteral = code.slice(node.source.start, node.source.end);
370
- if ('exported' in node && node.exported) {
371
- const exported = getModuleExportName(node.exported);
372
- if (!exported) {
373
- continue;
374
- }
375
- const modIdent = `__mod${importIndex++}`;
376
- const lines = [`const ${modIdent} = require(${srcLiteral});`, exportAssignment(exported, modIdent, live)];
377
- exportTransforms.push({
378
- start: node.start,
379
- end: node.end,
380
- code: `${lines.join('\n')}\n`
381
- });
382
- } else {
383
- const modIdent = `__mod${importIndex++}`;
384
- const lines = [`const ${modIdent} = require(${srcLiteral});`];
385
- const loop = `for (const k in ${modIdent}) {\n if (k === 'default') continue;\n if (!Object.prototype.hasOwnProperty.call(${modIdent}, k)) continue;\n Object.defineProperty(exports, k, { enumerable: true, get: () => ${modIdent}[k] });\n}`;
386
- lines.push(loop);
387
- exportTransforms.push({
388
- start: node.start,
389
- end: node.end,
390
- code: `${lines.join('\n')}\n`
391
- });
392
- }
393
- }
394
- }
395
- return {
396
- importTransforms,
397
- exportTransforms,
398
- needsInterop
399
- };
400
- };
401
21
  /**
402
22
  * Node added support for import.meta.main.
403
23
  * Added in: v24.2.0, v22.18.0
@@ -463,200 +83,18 @@ const format = async (src, ast, opts) => {
463
83
  end: firstExports?.end ?? 0
464
84
  });
465
85
  }
466
- 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']);
467
- const isValidExportName = name => /^[$A-Z_a-z][$\w]*$/.test(name) && !reservedExports.has(name);
468
- const isAllowedRhs = node => {
469
- return node.type === 'Identifier' || node.type === 'Literal' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression' || node.type === 'ClassExpression';
470
- };
471
- const buildIdiomaticPlan = () => {
472
- if (idiomaticMode === 'off') return {
473
- ok: false,
474
- reason: 'disabled'
475
- };
476
- const entries = [...exportTable.values()];
477
- if (!entries.length) return {
478
- ok: false,
479
- reason: 'no-exports'
480
- };
481
- if (exportTable.hasUnsupportedExportWrite) {
482
- return {
483
- ok: false,
484
- reason: 'unsupported-left'
485
- };
486
- }
487
- const viaSet = new Set();
488
- for (const entry of entries) {
489
- entry.via.forEach(v => viaSet.add(v));
490
- if (entry.hasGetter) return {
491
- ok: false,
492
- reason: 'getter-present'
493
- };
494
- if (entry.reassignments.length) return {
495
- ok: false,
496
- reason: 'reassignment'
497
- };
498
- if (entry.hasNonTopLevelWrite) return {
499
- ok: false,
500
- reason: 'non-top-level'
501
- };
502
- if (entry.writes.length !== 1) return {
503
- ok: false,
504
- reason: 'multiple-writes'
505
- };
506
- if (entry.key !== 'default' && !isValidExportName(entry.key)) return {
507
- ok: false,
508
- reason: 'non-identifier-key'
509
- };
510
- }
511
- if (viaSet.size > 1) return {
512
- ok: false,
513
- reason: 'mixed-exports'
514
- };
515
- const replacements = [];
516
- const exportsOut = [];
517
- const seen = new Set();
518
- const requireShadowed = shadowedBindings;
519
- const rhsSourceFor = node => {
520
- const raw = code.slice(node.start, node.end);
521
- return raw.replace(/\b__dirname\b/g, 'import.meta.dirname').replace(/\b__filename\b/g, 'import.meta.filename');
522
- };
523
- const tryObjectLiteralExport = (rhs, baseIsModuleExports, propName) => {
524
- if (!baseIsModuleExports || propName !== 'exports') return null;
525
- if (rhs.type !== 'ObjectExpression') return null;
526
- const exportsOut = [];
527
- const seenKeys = new Set();
528
- for (const prop of rhs.properties) {
529
- if (prop.type !== 'Property') return null;
530
- if (prop.kind !== 'init') return null;
531
- if (prop.computed || prop.method) return null;
532
- if (prop.key.type !== 'Identifier') return null;
533
- const key = prop.key.name;
534
- if (key === '__proto__' || key === 'prototype') return null;
535
- if (!isValidExportName(key)) return null;
536
- if (seenKeys.has(key)) return null;
537
- const value = prop.value.type === 'Identifier' && prop.shorthand ? prop.key : prop.value;
538
- if (!isAllowedRhs(value)) return null;
539
- if (expressionHasRequireCall(value, requireShadowed)) return null;
540
- const rhsSrc = rhsSourceFor(value);
541
- if (value.type === 'Identifier' && value.name === key) {
542
- exportsOut.push(`export { ${key} };`);
543
- } else if (value.type === 'Identifier') {
544
- exportsOut.push(`export { ${rhsSrc} as ${key} };`);
545
- } else {
546
- exportsOut.push(`export const ${key} = ${rhsSrc};`);
547
- }
548
- seenKeys.add(key);
549
- }
550
- exportsOut.push(`export default ${rhsSourceFor(rhs)};`);
551
- return {
552
- exportsOut,
553
- seenKeys
554
- };
555
- };
556
- for (const entry of entries) {
557
- const write = entry.writes[0];
558
- if (write.type !== 'AssignmentExpression') {
559
- return {
560
- ok: false,
561
- reason: 'unsupported-write-kind'
562
- };
563
- }
564
- const left = write.left;
565
- if (left.type !== 'MemberExpression' || left.computed || left.property.type !== 'Identifier') {
566
- return {
567
- ok: false,
568
- reason: 'unsupported-left'
569
- };
570
- }
571
- const base = left.object;
572
- const propName = left.property.name;
573
- const baseIsExports = base.type === 'Identifier' && base.name === 'exports';
574
- const baseIsModuleExports = base.type === 'Identifier' && base.name === 'module' && propName === 'exports' || base.type === 'MemberExpression' && base.object.type === 'Identifier' && base.object.name === 'module' && base.property.type === 'Identifier' && base.property.name === 'exports';
575
- if (!baseIsExports && !baseIsModuleExports) {
576
- return {
577
- ok: false,
578
- reason: 'unsupported-base'
579
- };
580
- }
581
- const rhs = write.right;
582
- const objectLiteralPlan = tryObjectLiteralExport(rhs, baseIsModuleExports, propName);
583
- if (!objectLiteralPlan) {
584
- if (!isAllowedRhs(rhs)) return {
585
- ok: false,
586
- reason: 'unsupported-rhs'
587
- };
588
- if (expressionHasRequireCall(rhs, requireShadowed)) {
589
- return {
590
- ok: false,
591
- reason: 'rhs-require'
592
- };
593
- }
594
- }
595
- const rhsSrc = rhsSourceFor(rhs);
596
- if (propName === 'exports' && baseIsModuleExports) {
597
- if (objectLiteralPlan) {
598
- for (const line of objectLiteralPlan.exportsOut) {
599
- exportsOut.push(line);
600
- }
601
- objectLiteralPlan.seenKeys.forEach(k => seen.add(k));
602
- } else {
603
- // module.exports = ... handles default
604
- if (seen.has('default')) return {
605
- ok: false,
606
- reason: 'duplicate-default'
607
- };
608
- seen.add('default');
609
- exportsOut.push(`export default ${rhsSrc};`);
610
- }
611
- } else {
612
- if (seen.has(propName)) return {
613
- ok: false,
614
- reason: 'duplicate-key'
615
- };
616
- seen.add(propName);
617
- if (rhs.type === 'Identifier') {
618
- const rhsId = rhsSourceFor(rhs);
619
- const rhsName = rhs.name;
620
- if (rhsId === rhsName && rhsName === propName) {
621
- exportsOut.push(`export { ${propName} };`);
622
- } else if (rhsId === rhsName) {
623
- exportsOut.push(`export { ${rhsId} as ${propName} };`);
624
- } else {
625
- exportsOut.push(`export const ${propName} = ${rhsId};`);
626
- }
627
- } else {
628
- exportsOut.push(`export const ${propName} = ${rhsSrc};`);
629
- }
630
- }
631
-
632
- // Trim trailing whitespace and one optional semicolon so the idiomatic export
633
- // replacement does not leave the original `;` behind (avoids emitting `;;`).
634
- let end = write.end;
635
- while (end < src.length && (src[end] === ' ' || src[end] === '\t')) end++;
636
- if (end < src.length && src[end] === ';') end++;
637
- replacements.push({
638
- start: write.start,
639
- end
640
- });
641
- }
642
- if (!seen.size) return {
643
- ok: false,
644
- reason: 'no-seen'
645
- };
646
- return {
647
- ok: true,
648
- plan: {
649
- replacements,
650
- exports: exportsOut
651
- }
652
- };
653
- };
654
86
  if (idiomaticMode !== 'off') {
655
- const res = buildIdiomaticPlan();
656
- if (res.ok && res.plan) {
87
+ const res = buildIdiomaticPlan({
88
+ src,
89
+ code,
90
+ exportTable,
91
+ shadowedBindings,
92
+ idiomaticMode
93
+ });
94
+ if (res.ok) {
657
95
  useExportsBag = false;
658
96
  idiomaticPlan = res.plan;
659
- } else if (res.reason) {
97
+ } else {
660
98
  idiomaticFallbackReason = res.reason;
661
99
  }
662
100
  }
@@ -697,165 +135,42 @@ const format = async (src, ast, opts) => {
697
135
  needsCreateRequire = reqCreate;
698
136
  needsImportInterop = reqInteropHelper;
699
137
  }
138
+ const walkState = {
139
+ importMetaRef,
140
+ requireMainNeedsRealpath,
141
+ needsCreateRequire,
142
+ needsRequireResolveHelper
143
+ };
700
144
  await ancestorWalk(ast.program, {
701
- async enter(node, ancestors) {
702
- const parent = ancestors[ancestors.length - 2] ?? null;
703
- if (shouldRaiseEsm && node.type === 'ReturnStatement' && parent?.type === 'Program') {
704
- warnOnce('top-level-return', 'Top-level return is not allowed in ESM; the transformed module will fail to parse.', {
705
- start: node.start,
706
- end: node.end
707
- });
708
- }
709
- if (shouldRaiseEsm && node.type === 'BinaryExpression') {
710
- const op = node.operator;
711
- const isEquality = op === '===' || op === '==' || op === '!==' || op === '!=';
712
- if (isEquality) {
713
- const leftMain = isRequireMainMember(node.left, shadowedBindings);
714
- const rightMain = isRequireMainMember(node.right, shadowedBindings);
715
- const leftModule = node.left.type === 'Identifier' && node.left.name === 'module' && !shadowedBindings.has('module');
716
- const rightModule = node.right.type === 'Identifier' && node.right.name === 'module' && !shadowedBindings.has('module');
717
- if (leftMain && rightModule || rightMain && leftModule) {
718
- const negate = op === '!==' || op === '!=';
719
- const mainExpr = requireMainStrategy === 'import-meta-main' ? 'import.meta.main' : 'import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href';
720
- if (requireMainStrategy === 'realpath') {
721
- requireMainNeedsRealpath = true;
722
- importMetaRef = true;
723
- }
724
- if (requireMainStrategy === 'import-meta-main') {
725
- importMetaRef = true;
726
- }
727
- code.update(node.start, node.end, negate ? `!(${mainExpr})` : mainExpr);
728
- return;
729
- }
730
- }
731
- }
732
- if (shouldRaiseEsm && node.type === 'WithStatement') {
733
- throw new Error('Cannot transform to ESM: with statements are not supported.');
734
- }
735
- if (shouldRaiseEsm && node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'eval' && !shadowedBindings.has('eval')) {
736
- throw new Error('Cannot transform to ESM: eval is not supported.');
737
- }
738
- if (shouldRaiseEsm && node.type === 'CallExpression' && isRequireCall(node, shadowedBindings)) {
739
- const isStatic = isStaticRequire(node, shadowedBindings);
740
- const parent = ancestors[ancestors.length - 2] ?? null;
741
- const grandparent = ancestors[ancestors.length - 3] ?? null;
742
- const greatGrandparent = ancestors[ancestors.length - 4] ?? null;
743
-
744
- // Hoistable cases are handled separately and don't need createRequire.
745
- const topLevelExprStmt = parent?.type === 'ExpressionStatement' && grandparent?.type === 'Program';
746
- const topLevelVarDecl = parent?.type === 'VariableDeclarator' && grandparent?.type === 'VariableDeclaration' && greatGrandparent?.type === 'Program';
747
- const hoistableTopLevel = isStatic && (topLevelExprStmt || topLevelVarDecl);
748
- if (!isStatic || !hoistableTopLevel) {
749
- if (nestedRequireStrategy === 'dynamic-import') {
750
- const asyncCapable = isAsyncContext(ancestors);
751
- if (asyncCapable) {
752
- const arg = node.arguments[0];
753
- const argSrc = arg ? code.slice(arg.start, arg.end) : 'undefined';
754
- const literalVal = arg?.value;
755
- const isJson = arg?.type === 'Literal' && typeof literalVal === 'string' && (literalVal.split(/[?#]/)[0] ?? literalVal).endsWith('.json');
756
- const importTarget = isJson ? `${argSrc} with { type: "json" }` : argSrc;
757
- code.update(node.start, node.end, `(await import(${importTarget}))`);
758
- return;
759
- }
760
- }
761
- needsCreateRequire = true;
762
- }
763
- }
764
- if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
765
- const skipped = ['__filename', '__dirname'];
766
- const skippedParams = node.params.filter(param => param.type === 'Identifier' && skipped.includes(param.name));
767
- const skippedFuncIdentifier = node.id?.type === 'Identifier' && skipped.includes(node.id.name);
768
- if (skippedParams.length || skippedFuncIdentifier) {
769
- this.skip();
770
- }
771
- }
772
-
773
- /**
774
- * Check for assignment to `import.meta.url`.
775
- */
776
- if (node.type === 'AssignmentExpression' && node.left.type === 'MemberExpression' && node.left.object.type === 'MetaProperty' && node.left.property.type === 'Identifier' && node.left.property.name === 'url') {
777
- if (node.right.type === 'Literal' && typeof node.right.value === 'string') {
778
- if (!isValidUrl(node.right.value)) {
779
- const rhs = code.snip(node.right.start, node.right.end).toString();
780
- const assignment = code.snip(node.start, node.end).toString();
781
- code.update(node.start, node.end, `/* Invalid assignment: ${rhs} is not a URL. ${assignment} */`);
782
- this.skip();
783
- }
784
- }
785
- }
786
-
787
- /**
788
- * Skip module scope CJS globals when they are object properties.
789
- * Ignoring `exports` here.
790
- */
791
- if (node.type === 'MemberExpression' && node.property.type === 'Identifier' && ['__filename', '__dirname'].includes(node.property.name)) {
792
- this.skip();
793
- }
794
-
795
- /**
796
- * Check for bare `module.exports` expressions.
797
- */
798
- if (node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'module' && node.property.type === 'Identifier' && node.property.name === 'exports' && parent?.type === 'ExpressionStatement') {
799
- if (opts.target === 'module') {
800
- code.update(node.start, node.end, ';');
801
- // Prevent parsing the `exports` identifier again.
802
- this.skip();
803
- }
804
- }
805
-
806
- /**
807
- * Format `module.exports` and `exports` assignments.
808
- */
809
- if (node.type === 'AssignmentExpression') {
810
- await assignmentExpression({
811
- node,
812
- parent,
813
- code,
814
- opts,
815
- meta: exportsMeta
816
- });
817
- }
818
- if (node.type === 'MetaProperty') {
819
- metaProperty(node, parent, code, opts);
820
- }
821
- if (node.type === 'MemberExpression') {
822
- memberExpression(node, parent, code, opts, shadowedBindings, {
823
- onRequireResolve: () => {
824
- if (shouldRaiseEsm) needsRequireResolveHelper = true;
825
- },
826
- requireResolveName: '__requireResolve',
827
- onDiagnostic: (codeId, message, loc) => {
828
- if (shouldRaiseEsm) warnOnce(codeId, message, loc);
829
- }
830
- }, useExportsBag, fullTransform);
831
- }
832
- if (shouldRaiseEsm && node.type === 'ThisExpression') {
833
- const bindsThis = ancestor => {
834
- return ancestor.type === 'FunctionDeclaration' || ancestor.type === 'FunctionExpression' || ancestor.type === 'ClassDeclaration' || ancestor.type === 'ClassExpression';
835
- };
836
- const bindingAncestor = ancestors.find(ancestor => bindsThis(ancestor));
837
- const isTopLevel = !bindingAncestor;
838
- if (isTopLevel) {
839
- code.update(node.start, node.end, exportsRename);
840
- return;
841
- }
842
- }
843
- if (isIdentifierName(node)) {
844
- if (shouldRaiseEsm && node.type === 'Identifier' && (node.name === '__dirname' || node.name === '__filename')) {
845
- importMetaRef = true;
846
- }
847
- identifier({
848
- node,
849
- ancestors,
850
- code,
851
- opts,
852
- meta: exportsMeta,
853
- shadowed: shadowedBindings,
854
- useExportsBag
855
- });
856
- }
857
- }
145
+ enter: buildFormatVisitor({
146
+ code,
147
+ opts,
148
+ warnOnce,
149
+ shadowedBindings,
150
+ requireMainStrategy,
151
+ nestedRequireStrategy,
152
+ shouldRaiseEsm,
153
+ fullTransform,
154
+ useExportsBag,
155
+ exportsMeta,
156
+ isRequireMainMember,
157
+ isRequireCall,
158
+ isStaticRequire,
159
+ isAsyncContext,
160
+ isValidUrl,
161
+ isIdentifierName,
162
+ assignmentExpression,
163
+ metaProperty,
164
+ memberExpression,
165
+ identifier
166
+ }, walkState)
858
167
  });
168
+ ({
169
+ importMetaRef,
170
+ requireMainNeedsRealpath,
171
+ needsCreateRequire,
172
+ needsRequireResolveHelper
173
+ } = walkState);
859
174
  if (pendingRequireTransforms.length) {
860
175
  for (const t of pendingRequireTransforms) {
861
176
  code.overwrite(t.start, t.end, t.code);
@@ -898,115 +213,26 @@ const format = async (src, ast, opts) => {
898
213
  }
899
214
  }
900
215
  if (useExportsBag && opts.target === 'module' && fullTransform && exportTable) {
901
- const isValidExportName = name => /^[$A-Z_a-z][$\w]*$/.test(name);
902
- const asExportName = name => isValidExportName(name) ? name : JSON.stringify(name);
903
- const accessProp = name => isValidExportName(name) ? `${exportsRename}.${name}` : `${exportsRename}[${JSON.stringify(name)}]`;
904
- const exportValueFor = name => {
905
- if (name === '__dirname') {
906
- importMetaRef = true;
907
- return 'import.meta.dirname';
908
- }
909
- if (name === '__filename') {
910
- importMetaRef = true;
911
- return 'import.meta.filename';
912
- }
913
- return name;
914
- };
915
- const tempNameFor = name => {
916
- const sanitized = name.replace(/[^$\w]/g, '_') || 'value';
917
- const safe = /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
918
- return `__export_${safe}`;
919
- };
920
- for (const [key, entry] of exportTable) {
921
- if (entry.reassignments.length) {
922
- const loc = entry.reassignments[0];
923
- warnOnce(`cjs-export-reassignment:${key}`, `Export '${key}' is reassigned after export; ESM live bindings may change consumer behavior.`, {
924
- start: loc.start,
925
- end: loc.end
926
- });
927
- }
928
- }
929
- const lines = [];
930
- const defaultEntry = exportTable.get('default');
931
- if (defaultEntry) {
932
- const def = defaultEntry.fromIdentifier ?? exportsRename;
933
- const defExpr = exportValueFor(def);
934
- if (defExpr !== def) {
935
- const temp = tempNameFor(def);
936
- lines.push(`const ${temp} = ${defExpr};`);
937
- lines.push(`export default ${temp};`);
938
- } else {
939
- lines.push(`export default ${defExpr};`);
940
- }
941
- }
942
- for (const [key, entry] of exportTable) {
943
- if (key === 'default') continue;
944
- if (!isValidExportName(key)) {
945
- warnOnce(`cjs-string-export:${key}`, `Synthesized string-literal export '${key}'. Some tooling may require bracket access to use it.`);
946
- }
947
- if (entry.fromIdentifier) {
948
- const resolved = exportValueFor(entry.fromIdentifier);
949
- if (resolved !== entry.fromIdentifier) {
950
- const temp = tempNameFor(entry.fromIdentifier);
951
- lines.push(`const ${temp} = ${resolved};`);
952
- lines.push(`export { ${temp} as ${asExportName(key)} };`);
953
- } else {
954
- lines.push(`export { ${resolved} as ${asExportName(key)} };`);
955
- }
956
- } else {
957
- const temp = tempNameFor(key);
958
- lines.push(`const ${temp} = ${accessProp(key)};`);
959
- lines.push(`export { ${temp} as ${asExportName(key)} };`);
960
- }
961
- }
962
- if (lines.length) {
963
- code.append(`\n${lines.join('\n')}\n`);
964
- }
216
+ importMetaRef = exportBagToEsm({
217
+ code,
218
+ exportTable,
219
+ warnOnce,
220
+ importMetaRef
221
+ });
965
222
  }
966
223
  if (shouldRaiseEsm && fullTransform) {
967
- const importPrelude = [];
968
- if (needsCreateRequire || needsRequireResolveHelper) {
969
- importMetaRef = true;
970
- }
971
- if (needsCreateRequire || needsRequireResolveHelper) {
972
- importPrelude.push('import { createRequire } from "node:module";\n');
973
- }
974
- if (needsRequireResolveHelper) {
975
- importPrelude.push('import { fileURLToPath } from "node:url";\n');
976
- }
977
- if (requireMainNeedsRealpath) {
978
- importPrelude.push('import { realpathSync } from "node:fs";\n');
979
- importPrelude.push('import { pathToFileURL } from "node:url";\n');
980
- }
981
- if (hoistedImports.length) {
982
- importPrelude.push(...hoistedImports);
983
- }
984
- const setupPrelude = [];
985
- if (needsImportInterop) {
986
- setupPrelude.push(requireInteropHelper);
987
- }
988
- if (hoistedStatements.length) {
989
- setupPrelude.push(...hoistedStatements);
990
- }
991
- const requireInit = needsCreateRequire ? 'const require = createRequire(import.meta.url);\n' : '';
992
- const requireResolveInit = needsRequireResolveHelper ? needsCreateRequire ? `const __requireResolve = (id, parent) => {
993
- const resolved = require.resolve(id, parent);
994
- return resolved.startsWith("file://") ? fileURLToPath(resolved) : resolved;
995
- };\n` : `const __requireResolve = (id, parent) => {
996
- const req = createRequire(parent ?? import.meta.url);
997
- const resolved = req.resolve(id, parent);
998
- return resolved.startsWith("file://") ? fileURLToPath(resolved) : resolved;
999
- };\n` : '';
1000
- const exportsBagInit = useExportsBag ? `let ${exportsRename} = {};
1001
- ` : '';
1002
- const modulePrelude = '';
1003
- const prelude = `${importPrelude.join('')}${importPrelude.length ? '\n' : ''}${setupPrelude.join('')}${setupPrelude.length ? '\n' : ''}${requireInit}${requireResolveInit}${exportsBagInit}${modulePrelude}`;
1004
- const importMetaTouch = (() => {
1005
- if (importMetaPreludeMode === 'on') return 'void import.meta.filename;\n';
1006
- if (importMetaPreludeMode === 'off') return '';
1007
- return importMetaRef ? 'void import.meta.filename;\n' : '';
1008
- })();
1009
- code.prepend(`${prelude}${importMetaTouch}`);
224
+ const prelude = buildEsmPrelude({
225
+ needsCreateRequire,
226
+ needsRequireResolveHelper,
227
+ requireMainNeedsRealpath,
228
+ hoistedImports,
229
+ hoistedStatements,
230
+ needsImportInterop,
231
+ importMetaPreludeMode,
232
+ importMetaRef,
233
+ useExportsBag
234
+ });
235
+ code.prepend(prelude);
1010
236
  }
1011
237
  if (opts.target === 'commonjs' && fullTransform && containsTopLevelAwait) {
1012
238
  const body = code.toString();