-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat.ts
More file actions
773 lines (674 loc) · 23.5 KB
/
format.ts
File metadata and controls
773 lines (674 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
import type { ParseResult } from 'oxc-parser'
import type { FormatterOptions, ExportsMeta } from './types.js'
import MagicString from 'magic-string'
import { identifier } from '#formatters/identifier.js'
import { metaProperty } from '#formatters/metaProperty.js'
import { memberExpression } from '#formatters/memberExpression.js'
import { assignmentExpression } from '#formatters/assignmentExpression.js'
import { isValidUrl } from '#utils/url.js'
import { exportsRename, collectCjsExports } from '#utils/exports.js'
import { collectModuleIdentifiers } from '#utils/identifiers.js'
import { isIdentifierName } from '#helpers/identifier.js'
import { ancestorWalk } from '#walk'
const isValidIdent = (name: string) => /^[$A-Z_a-z][$\w]*$/.test(name)
const exportAssignment = (
name: string,
expr: string,
live: 'strict' | 'loose' | 'off',
) => {
const prop = isValidIdent(name) ? `.${name}` : `[${JSON.stringify(name)}]`
if (live === 'strict') {
const key = JSON.stringify(name)
return `Object.defineProperty(exports, ${key}, { enumerable: true, get: () => ${expr} });`
}
return `exports${prop} = ${expr};`
}
const defaultInteropName = '__interopDefault'
const interopHelper = `const ${defaultInteropName} = mod => (mod && mod.__esModule ? mod.default : mod);\n`
const isRequireCallee = (callee: any, shadowed: Set<string>) => {
if (
callee.type === 'Identifier' &&
callee.name === 'require' &&
!shadowed.has('require')
) {
return true
}
if (
callee.type === 'MemberExpression' &&
callee.object.type === 'Identifier' &&
callee.object.name === 'module' &&
!shadowed.has('module') &&
callee.property.type === 'Identifier' &&
callee.property.name === 'require'
) {
return true
}
return false
}
const isStaticRequire = (node: any, shadowed: Set<string>) =>
node.type === 'CallExpression' &&
isRequireCallee(node.callee, shadowed) &&
node.arguments.length === 1 &&
node.arguments[0].type === 'Literal' &&
typeof node.arguments[0].value === 'string'
const isRequireCall = (node: any, shadowed: Set<string>) =>
node.type === 'CallExpression' && isRequireCallee(node.callee, shadowed)
type RequireTransform = {
start: number
end: number
code: string
}
const lowerCjsRequireToImports = (
program: any,
code: MagicString,
shadowed: Set<string>,
) => {
const transforms: RequireTransform[] = []
const imports: string[] = []
let nsIndex = 0
let needsCreateRequire = false
for (const stmt of program.body as any[]) {
if (stmt.type === 'VariableDeclaration') {
const decls = stmt.declarations
const allStatic =
decls.length > 0 &&
decls.every((decl: any) => decl.init && isStaticRequire(decl.init, shadowed))
if (allStatic) {
for (const decl of decls) {
const init = decl.init!
const source = code.slice(init.arguments[0].start, init.arguments[0].end)
if (decl.id.type === 'Identifier') {
imports.push(`import * as ${decl.id.name} from ${source};\n`)
} else if (decl.id.type === 'ObjectPattern') {
const ns = `__cjsImport${nsIndex++}`
const pattern = code.slice(decl.id.start, decl.id.end)
imports.push(`import * as ${ns} from ${source};\n`)
imports.push(`const ${pattern} = ${ns};\n`)
} else {
needsCreateRequire = true
}
}
transforms.push({ start: stmt.start, end: stmt.end, code: ';\n' })
continue
}
for (const decl of decls) {
const init = decl.init
if (init && isRequireCall(init, shadowed)) {
needsCreateRequire = true
}
}
}
if (stmt.type === 'ExpressionStatement') {
const expr = stmt.expression
if (expr && isStaticRequire(expr, shadowed)) {
const source = code.slice(expr.arguments[0].start, expr.arguments[0].end)
imports.push(`import ${source};\n`)
transforms.push({ start: stmt.start, end: stmt.end, code: ';\n' })
continue
}
if (expr && isRequireCall(expr, shadowed)) {
needsCreateRequire = true
}
}
}
return { transforms, imports, needsCreateRequire }
}
const isRequireMainMember = (node: any, shadowed: Set<string>) =>
node &&
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
node.object.name === 'require' &&
!shadowed.has('require') &&
node.property.type === 'Identifier' &&
node.property.name === 'main'
const hasTopLevelAwait = (program: any) => {
let found = false
const walkNode = (node: any, inFunction: boolean) => {
if (found) return
switch (node.type) {
case 'FunctionDeclaration':
case 'FunctionExpression':
case 'ArrowFunctionExpression':
case 'ClassDeclaration':
case 'ClassExpression':
inFunction = true
break
}
if (!inFunction && node.type === 'AwaitExpression') {
found = true
return
}
const keys = Object.keys(node)
for (const key of keys) {
const value = (node as any)[key]
if (!value) continue
if (Array.isArray(value)) {
for (const item of value) {
if (item && typeof item === 'object') {
walkNode(item, inFunction)
if (found) return
}
}
} else if (value && typeof value === 'object') {
walkNode(value, inFunction)
if (found) return
}
}
}
walkNode(program, false)
return found
}
const lowerEsmToCjs = (
program: any,
code: MagicString,
opts: FormatterOptions,
containsTopLevelAwait: boolean,
) => {
const live = opts.liveBindings ?? 'strict'
const importTransforms: ImportTransform[] = []
const exportTransforms: ExportTransform[] = []
let needsInterop = false
let importIndex = 0
for (const node of program.body as any[]) {
if (node.type === 'ImportDeclaration') {
const srcLiteral = code.slice(node.source.start, node.source.end)
const specifiers = node.specifiers ?? []
const defaultSpec = specifiers.find((s: any) => s.type === 'ImportDefaultSpecifier')
const namespaceSpec = specifiers.find(
(s: any) => s.type === 'ImportNamespaceSpecifier',
)
const namedSpecs = specifiers.filter((s: any) => s.type === 'ImportSpecifier')
// Side-effect import
if (!specifiers.length) {
importTransforms.push({
start: node.start,
end: node.end,
code: `require(${srcLiteral});\n`,
needsInterop: false,
})
continue
}
const modIdent = `__mod${importIndex++}`
const lines: string[] = []
lines.push(`const ${modIdent} = require(${srcLiteral});`)
if (namespaceSpec) {
lines.push(`const ${namespaceSpec.local.name} = ${modIdent};`)
}
if (defaultSpec) {
let init = modIdent
switch (opts.cjsDefault) {
case 'module-exports':
init = modIdent
break
case 'none':
init = `${modIdent}.default`
break
case 'auto':
default:
init = `${defaultInteropName}(${modIdent})`
needsInterop = true
break
}
lines.push(`const ${defaultSpec.local.name} = ${init};`)
}
if (namedSpecs.length) {
const pairs = namedSpecs.map((s: any) => {
const imported = s.imported.name
const local = s.local.name
return imported === local ? imported : `${imported}: ${local}`
})
lines.push(`const { ${pairs.join(', ')} } = ${modIdent};`)
}
importTransforms.push({
start: node.start,
end: node.end,
code: `${lines.join('\n')}\n`,
needsInterop,
})
}
if (node.type === 'ExportNamedDeclaration') {
// Handle declaration exports
if (node.declaration) {
const decl = node.declaration
const declSrc = code.slice(decl.start, decl.end)
const exportedNames: string[] = []
if (decl.type === 'VariableDeclaration') {
for (const d of decl.declarations) {
if (d.id.type === 'Identifier') {
exportedNames.push(d.id.name)
}
}
} else if ((decl as any).id?.type === 'Identifier') {
exportedNames.push((decl as any).id.name)
}
const exportLines = exportedNames.map(name =>
exportAssignment(name, name, live as any),
)
exportTransforms.push({
start: node.start,
end: node.end,
code: `${declSrc}\n${exportLines.join('\n')}\n`,
})
continue
}
// Handle re-export or local specifiers
if (node.specifiers?.length) {
if (node.source) {
const srcLiteral = code.slice(node.source.start, node.source.end)
const modIdent = `__mod${importIndex++}`
const lines = [`const ${modIdent} = require(${srcLiteral});`]
for (const spec of node.specifiers) {
if (spec.type !== 'ExportSpecifier') continue
const exported = spec.exported.name
const imported = spec.local.name
let rhs = `${modIdent}.${imported}`
if (imported === 'default') {
rhs = `${defaultInteropName}(${modIdent})`
needsInterop = true
}
lines.push(exportAssignment(exported, rhs, live as any))
}
exportTransforms.push({
start: node.start,
end: node.end,
code: `${lines.join('\n')}\n`,
needsInterop,
})
} else {
const lines: string[] = []
for (const spec of node.specifiers) {
if (spec.type !== 'ExportSpecifier') continue
const exported = spec.exported.name
const local = spec.local.name
lines.push(exportAssignment(exported, local, live as any))
}
exportTransforms.push({
start: node.start,
end: node.end,
code: `${lines.join('\n')}\n`,
})
}
}
}
if (node.type === 'ExportDefaultDeclaration') {
const decl = node.declaration
const useExportsObject = containsTopLevelAwait && opts.topLevelAwait !== 'error'
if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') {
if (decl.id?.name) {
const declSrc = code.slice(decl.start, decl.end)
const assign = useExportsObject
? `exports.default = ${decl.id.name};`
: `module.exports = ${decl.id.name};`
exportTransforms.push({
start: node.start,
end: node.end,
code: `${declSrc}\n${assign}\n`,
})
} else {
const declSrc = code.slice(decl.start, decl.end)
const assign = useExportsObject
? `exports.default = ${declSrc};`
: `module.exports = ${declSrc};`
exportTransforms.push({
start: node.start,
end: node.end,
code: `${assign}\n`,
})
}
} else {
const exprSrc = code.slice(decl.start, decl.end)
const assign = useExportsObject
? `exports.default = ${exprSrc};`
: `module.exports = ${exprSrc};`
exportTransforms.push({
start: node.start,
end: node.end,
code: `${assign}\n`,
})
}
}
if (node.type === 'ExportAllDeclaration') {
const srcLiteral = code.slice(node.source.start, node.source.end)
if ((node as any).exported) {
const exported = (node as any).exported.name
const modIdent = `__mod${importIndex++}`
const lines = [
`const ${modIdent} = require(${srcLiteral});`,
exportAssignment(exported, modIdent, live as any),
]
exportTransforms.push({
start: node.start,
end: node.end,
code: `${lines.join('\n')}\n`,
})
} else {
const modIdent = `__mod${importIndex++}`
const lines = [`const ${modIdent} = require(${srcLiteral});`]
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}`
lines.push(loop)
exportTransforms.push({
start: node.start,
end: node.end,
code: `${lines.join('\n')}\n`,
})
}
}
}
return { importTransforms, exportTransforms, needsInterop }
}
type ImportTransform = {
start: number
end: number
code: string
needsInterop: boolean
}
type ExportTransform = {
start: number
end: number
code: string
needsInterop?: boolean
}
/**
* Node added support for import.meta.main.
* Added in: v24.2.0, v22.18.0
* @see https://nodejs.org/api/esm.html#importmetamain
*/
const format = async (src: string, ast: ParseResult, opts: FormatterOptions) => {
const code = new MagicString(src)
const exportsMeta = {
hasExportsBeenReassigned: false,
defaultExportValue: undefined,
hasDefaultExportBeenReassigned: false,
hasDefaultExportBeenAssigned: false,
} satisfies ExportsMeta
const moduleIdentifiers = await collectModuleIdentifiers(ast.program)
const shadowedBindings = new Set(
[...moduleIdentifiers.entries()]
.filter(([, meta]) => meta.declare.length > 0)
.map(([name]) => name),
)
if (opts.target === 'module' && opts.transformSyntax) {
if (shadowedBindings.has('module') || shadowedBindings.has('exports')) {
throw new Error(
'Cannot transform to ESM: module or exports is shadowed in module scope.',
)
}
}
const exportTable =
opts.target === 'module' ? await collectCjsExports(ast.program) : null
const shouldCheckTopLevelAwait = opts.target === 'commonjs' && opts.transformSyntax
const containsTopLevelAwait = shouldCheckTopLevelAwait
? hasTopLevelAwait(ast.program)
: false
const shouldLowerCjs = opts.target === 'commonjs' && opts.transformSyntax
const shouldRaiseEsm = opts.target === 'module' && opts.transformSyntax
let hoistedImports: string[] = []
let pendingRequireTransforms: RequireTransform[] = []
let needsCreateRequire = false
let pendingCjsTransforms: {
transforms: Array<ImportTransform | ExportTransform>
needsInterop: boolean
} | null = null
if (shouldLowerCjs && opts.topLevelAwait === 'error' && containsTopLevelAwait) {
throw new Error(
'Top-level await is not supported when targeting CommonJS (set topLevelAwait to "wrap" or "preserve" to override).',
)
}
if (shouldRaiseEsm) {
const {
transforms,
imports,
needsCreateRequire: reqCreate,
} = lowerCjsRequireToImports(ast.program, code, shadowedBindings)
pendingRequireTransforms = transforms
hoistedImports = imports
needsCreateRequire = reqCreate
}
await ancestorWalk(ast.program, {
async enter(node, ancestors) {
const parent = ancestors[ancestors.length - 2] ?? null
if (shouldRaiseEsm && node.type === 'BinaryExpression') {
const op = node.operator
const isEquality = op === '===' || op === '==' || op === '!==' || op === '!='
if (isEquality) {
const leftMain = isRequireMainMember(node.left, shadowedBindings)
const rightMain = isRequireMainMember(node.right, shadowedBindings)
const leftModule =
node.left.type === 'Identifier' &&
node.left.name === 'module' &&
!shadowedBindings.has('module')
const rightModule =
node.right.type === 'Identifier' &&
node.right.name === 'module' &&
!shadowedBindings.has('module')
if ((leftMain && rightModule) || (rightMain && leftModule)) {
const negate = op === '!==' || op === '!='
code.update(
node.start,
node.end,
negate ? '!import.meta.main' : 'import.meta.main',
)
return
}
}
}
if (shouldRaiseEsm && node.type === 'WithStatement') {
throw new Error('Cannot transform to ESM: with statements are not supported.')
}
if (
shouldRaiseEsm &&
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'eval' &&
!shadowedBindings.has('eval')
) {
throw new Error('Cannot transform to ESM: eval is not supported.')
}
if (
shouldRaiseEsm &&
node.type === 'CallExpression' &&
isRequireCall(node, shadowedBindings)
) {
const isStatic = isStaticRequire(node, shadowedBindings)
const parent = ancestors[ancestors.length - 2] ?? null
const grandparent = ancestors[ancestors.length - 3] ?? null
const greatGrandparent = ancestors[ancestors.length - 4] ?? null
// Hoistable cases are handled separately and don't need createRequire.
const topLevelExprStmt =
parent?.type === 'ExpressionStatement' && grandparent?.type === 'Program'
const topLevelVarDecl =
parent?.type === 'VariableDeclarator' &&
grandparent?.type === 'VariableDeclaration' &&
greatGrandparent?.type === 'Program'
const hoistableTopLevel = isStatic && (topLevelExprStmt || topLevelVarDecl)
if (!isStatic || !hoistableTopLevel) {
needsCreateRequire = true
}
}
if (
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression'
) {
const skipped = ['__filename', '__dirname']
const skippedParams = node.params.filter(
param => param.type === 'Identifier' && skipped.includes(param.name),
)
const skippedFuncIdentifier =
node.id?.type === 'Identifier' && skipped.includes(node.id.name)
if (skippedParams.length || skippedFuncIdentifier) {
this.skip()
}
}
/**
* Check for assignment to `import.meta.url`.
*/
if (
node.type === 'AssignmentExpression' &&
node.left.type === 'MemberExpression' &&
node.left.object.type === 'MetaProperty' &&
node.left.property.type === 'Identifier' &&
node.left.property.name === 'url'
) {
if (node.right.type === 'Literal' && typeof node.right.value === 'string') {
if (!isValidUrl(node.right.value)) {
const rhs = code.snip(node.right.start, node.right.end).toString()
const assignment = code.snip(node.start, node.end).toString()
code.update(
node.start,
node.end,
`/* Invalid assignment: ${rhs} is not a URL. ${assignment} */`,
)
this.skip()
}
}
}
/**
* Skip module scope CJS globals when they are object properties.
* Ignoring `exports` here.
*/
if (
node.type === 'MemberExpression' &&
node.property.type === 'Identifier' &&
['__filename', '__dirname'].includes(node.property.name)
) {
this.skip()
}
/**
* Check for bare `module.exports` expressions.
*/
if (
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
node.object.name === 'module' &&
node.property.type === 'Identifier' &&
node.property.name === 'exports' &&
parent?.type === 'ExpressionStatement'
) {
if (opts.target === 'module') {
code.update(node.start, node.end, ';')
// Prevent parsing the `exports` identifier again.
this.skip()
}
}
/**
* Format `module.exports` and `exports` assignments.
*/
if (node.type === 'AssignmentExpression') {
await assignmentExpression({
node,
parent,
code,
opts,
meta: exportsMeta,
})
}
if (node.type === 'MetaProperty') {
metaProperty(node, parent, code, opts)
}
if (node.type === 'MemberExpression') {
memberExpression(node, parent, code, opts, shadowedBindings)
}
if (isIdentifierName(node)) {
identifier({
node,
ancestors,
code,
opts,
meta: exportsMeta,
shadowed: shadowedBindings,
})
}
},
})
if (pendingRequireTransforms.length) {
for (const t of pendingRequireTransforms) {
code.overwrite(t.start, t.end, t.code)
}
}
if (shouldLowerCjs) {
const { importTransforms, exportTransforms, needsInterop } = lowerEsmToCjs(
ast.program,
code,
opts,
containsTopLevelAwait,
)
pendingCjsTransforms = {
transforms: [...importTransforms, ...exportTransforms].sort(
(a, b) => a.start - b.start,
),
needsInterop,
}
}
if (pendingCjsTransforms) {
for (const t of pendingCjsTransforms.transforms) {
code.overwrite(t.start, t.end, t.code)
}
if (pendingCjsTransforms.needsInterop) {
code.prepend(`${interopHelper}exports.__esModule = true;\n`)
}
}
if (opts.target === 'module' && opts.transformSyntax && exportTable) {
const isValidExportName = (name: string) => /^[$A-Z_a-z][$\w]*$/.test(name)
const asExportName = (name: string) =>
isValidExportName(name) ? name : JSON.stringify(name)
const accessProp = (name: string) =>
isValidExportName(name)
? `${exportsRename}.${name}`
: `${exportsRename}[${JSON.stringify(name)}]`
const tempNameFor = (name: string) => {
const sanitized = name.replace(/[^$\w]/g, '_') || 'value'
const safe = /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized
return `__export_${safe}`
}
const lines: string[] = []
const defaultEntry = exportTable.get('default')
if (defaultEntry) {
const def = defaultEntry.fromIdentifier ?? exportsRename
lines.push(`export default ${def};`)
}
for (const [key, entry] of exportTable) {
if (key === 'default') continue
if (entry.fromIdentifier) {
lines.push(`export { ${entry.fromIdentifier} as ${asExportName(key)} };`)
} else {
const temp = tempNameFor(key)
lines.push(`const ${temp} = ${accessProp(key)};`)
lines.push(`export { ${temp} as ${asExportName(key)} };`)
}
}
if (lines.length) {
code.append(`\n${lines.join('\n')}\n`)
}
}
if (shouldRaiseEsm && opts.transformSyntax) {
const importPrelude: string[] = []
if (needsCreateRequire) {
importPrelude.push('import { createRequire } from "node:module";\n')
}
if (hoistedImports.length) {
importPrelude.push(...hoistedImports)
}
const requireInit = needsCreateRequire
? 'const require = createRequire(import.meta.url);\n'
: ''
const prelude = `${importPrelude.join('')}${
importPrelude.length ? '\n' : ''
}${requireInit}let ${exportsRename} = {};
void import.meta.filename;
`
code.prepend(prelude)
}
if (opts.target === 'commonjs' && opts.transformSyntax && containsTopLevelAwait) {
const body = code.toString()
if (opts.topLevelAwait === 'wrap') {
const tlaPromise = `const __tla = (async () => {\n${body}\nreturn module.exports;\n})();\n`
const setPromise = `const __setTla = target => {\n if (!target) return;\n const type = typeof target;\n if (type !== 'object' && type !== 'function') return;\n target.__tla = __tla;\n};\n`
const attach = `__setTla(module.exports);\n__tla.then(resolved => __setTla(resolved), err => { throw err; });\n`
return `${tlaPromise}${setPromise}${attach}`
}
return `;(async () => {\n${body}\n})();\n`
}
return code.toString()
}
export { format }