susee 0.1.1 → 0.1.2

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/dist/index.mjs CHANGED
@@ -6,95 +6,29 @@ this file except in compliance with the License. You may obtain a copy of the
6
6
  License at http://www.apache.org/licenses/LICENSE-2.0
7
7
  ***************************************************************************** */
8
8
  import TsConfig from "@suseejs/tsconfig";
9
- import anonymous from "@suseejs/anonymous";
10
9
  import dependencies from "@suseejs/dependencies";
11
- import duplicateHandlers from "@suseejs/duplicates";
12
10
  import fs from "node:fs";
13
11
  import path from "node:path";
14
12
  import resolves from "@phothinmaung/resolves";
15
13
  import tcolor from "@suseejs/tcolor";
16
14
  import transformFunction from "@suseejs/transformer";
17
15
  import ts from "typescript";
18
- import utils from "@suseejs/utils";
19
- function removeExportExpressionHandler(compilerOptions) {
20
- return ({ file, content }) => {
21
- const sourceFile = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true);
16
+ import utilities from "@suseejs/utils";
17
+ import { Buffer } from "node:buffer";
18
+ const bundleCreator = (bundleVisitor, compilerOptions, ...args) => {
19
+ return (depsTree) => {
20
+ const sourceFile = ts.createSourceFile(depsTree.file, depsTree.content, ts.ScriptTarget.Latest, true);
22
21
  const transformer = (context) => {
23
- const { factory } = context;
24
- const visitor = (node) => {
25
- if (ts.isFunctionDeclaration(node) ||
26
- ts.isClassDeclaration(node) ||
27
- ts.isInterfaceDeclaration(node) ||
28
- ts.isTypeAliasDeclaration(node) ||
29
- ts.isEnumDeclaration(node) ||
30
- ts.isVariableStatement(node)) {
31
- const modifiers = node.modifiers?.filter((m) => m.kind !== ts.SyntaxKind.ExportKeyword &&
32
- m.kind !== ts.SyntaxKind.DefaultKeyword);
33
- if (modifiers?.length !== node.modifiers?.length) {
34
- if (ts.isFunctionDeclaration(node)) {
35
- return factory.updateFunctionDeclaration(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
36
- }
37
- if (ts.isClassDeclaration(node)) {
38
- return factory.updateClassDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
39
- }
40
- if (ts.isInterfaceDeclaration(node)) {
41
- return factory.updateInterfaceDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
42
- }
43
- if (ts.isTypeAliasDeclaration(node)) {
44
- return factory.updateTypeAliasDeclaration(node, modifiers, node.name, node.typeParameters, node.type);
45
- }
46
- if (ts.isEnumDeclaration(node)) {
47
- return factory.updateEnumDeclaration(node, modifiers, node.name, node.members);
48
- }
49
- if (ts.isVariableStatement(node)) {
50
- return factory.updateVariableStatement(node, modifiers, node.declarationList);
51
- }
52
- }
53
- }
54
- if (ts.isExportDeclaration(node)) {
55
- return factory.createEmptyStatement();
56
- }
57
- if (ts.isExportAssignment(node)) {
58
- const expr = node.expression;
59
- if (ts.isIdentifier(expr)) {
60
- return factory.createEmptyStatement();
61
- }
62
- }
63
- return ts.visitEachChild(node, visitor, context);
64
- };
65
- return (rootNode) => ts.visitNode(rootNode, visitor);
66
- };
67
- let _content = transformFunction(transformer, sourceFile, compilerOptions);
68
- _content = _content.replace(/^s*;\s*$/gm, "").trim();
69
- return { file, content: _content };
70
- };
71
- }
72
- function removeImportExpressionHandler(removedStatements, compilerOptions) {
73
- return ({ file, content }) => {
74
- const sourceFile = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true);
75
- const transformer = (context) => {
76
- const { factory } = context;
77
- const visitor = (node) => {
78
- if (ts.isImportDeclaration(node)) {
79
- const text = node.getText(sourceFile);
80
- removedStatements.push(text);
81
- return factory.createEmptyStatement();
82
- }
83
- if (ts.isImportEqualsDeclaration(node)) {
84
- const text = node.getText(sourceFile);
85
- removedStatements.push(text);
86
- return factory.createEmptyStatement();
87
- }
88
- return ts.visitEachChild(node, visitor, context);
89
- };
22
+ const visitor = bundleVisitor(context, depsTree, sourceFile, ...args);
90
23
  return (rootNode) => ts.visitNode(rootNode, visitor);
91
24
  };
92
25
  let _content = transformFunction(transformer, sourceFile, compilerOptions);
93
26
  _content = _content.replace(/^s*;\s*$/gm, "").trim();
94
- return { file, content: _content };
27
+ const { content, ...rest } = depsTree;
28
+ return { content: _content, ...rest };
95
29
  };
96
- }
97
- function mergeImports(imports) {
30
+ };
31
+ function mergeImportsStatement(imports) {
98
32
  const importMap = new Map();
99
33
  const typeImportMap = new Map();
100
34
  const defaultImports = new Map();
@@ -192,8 +126,714 @@ function mergeImports(imports) {
192
126
  }
193
127
  return mergedImports.sort();
194
128
  }
195
- async function bundler({ depsFiles, compilerOptions, renameDuplicates, }) {
196
- const reName = renameDuplicates ?? true;
129
+ const anonymousCallExpressionVisitor = (context, depsTree, _sourceFile, exportDefaultImportNameMap) => {
130
+ const { factory } = context;
131
+ const visit = (node) => {
132
+ if (ts.isCallExpression(node)) {
133
+ if (ts.isIdentifier(node.expression)) {
134
+ const base = node.expression.text;
135
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
136
+ if (mapping) {
137
+ return factory.updateCallExpression(node, factory.createIdentifier(mapping.newName), node.typeArguments, node.arguments);
138
+ }
139
+ }
140
+ }
141
+ else if (ts.isPropertyAccessExpression(node)) {
142
+ if (ts.isIdentifier(node.expression)) {
143
+ const base = node.expression.text;
144
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
145
+ if (mapping) {
146
+ return factory.updatePropertyAccessExpression(node, factory.createIdentifier(mapping.newName), node.name);
147
+ }
148
+ }
149
+ }
150
+ else if (ts.isNewExpression(node)) {
151
+ if (ts.isIdentifier(node.expression)) {
152
+ const base = node.expression.text;
153
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
154
+ if (mapping) {
155
+ return factory.updateNewExpression(node, factory.createIdentifier(mapping.newName), node.typeArguments, node.arguments);
156
+ }
157
+ }
158
+ }
159
+ else if (ts.isExportSpecifier(node)) {
160
+ if (ts.isIdentifier(node.name)) {
161
+ const base = node.name.text;
162
+ const mapping = exportDefaultImportNameMap.find((m) => m.base === base && m.file === depsTree.file);
163
+ if (mapping) {
164
+ return factory.updateExportSpecifier(node, node.isTypeOnly, node.propertyName, factory.createIdentifier(mapping.newName));
165
+ }
166
+ }
167
+ }
168
+ return ts.visitEachChild(node, visit, context);
169
+ };
170
+ return visit;
171
+ };
172
+ const normalizePathKey = (filePath) => {
173
+ const parsed = path.parse(filePath);
174
+ let noExt = path.join(parsed.dir, parsed.name);
175
+ if (parsed.name === "index") {
176
+ noExt = parsed.dir;
177
+ }
178
+ return path.normalize(noExt);
179
+ };
180
+ const getFileKey = (filePath) => normalizePathKey(filePath);
181
+ const getModuleKeyFromSpecifier = (moduleSpecifier, sourceFile, containingFile) => {
182
+ let spec = "";
183
+ if (ts.isStringLiteral(moduleSpecifier)) {
184
+ spec = moduleSpecifier.text;
185
+ }
186
+ else {
187
+ spec = moduleSpecifier.getText(sourceFile).replace(/^['"]|['"]$/g, "");
188
+ }
189
+ if (spec.startsWith(".") || spec.startsWith("/")) {
190
+ const baseDir = path.dirname(containingFile);
191
+ return normalizePathKey(path.resolve(baseDir, spec));
192
+ }
193
+ return spec;
194
+ };
195
+ function uniqueName() {
196
+ const storedPrefix = new Map();
197
+ const obj = {
198
+ setPrefix({ key, value }) {
199
+ const names = [];
200
+ let _fix;
201
+ if (storedPrefix.has(key)) {
202
+ console.warn(`${key} already exist`);
203
+ throw new Error();
204
+ }
205
+ else {
206
+ _fix = value;
207
+ storedPrefix.set(key, value);
208
+ }
209
+ function getName(input) {
210
+ const length = names.length;
211
+ const _name = _fix
212
+ ? `${_fix}${input}_${length + 1}`
213
+ : `$nyein${input}_${length + 1}`;
214
+ names.push(_name);
215
+ return _name;
216
+ }
217
+ return { getName };
218
+ },
219
+ getPrefix(key) {
220
+ if (storedPrefix.has(key)) {
221
+ return storedPrefix.get(key);
222
+ }
223
+ },
224
+ };
225
+ return obj;
226
+ }
227
+ const prefixKey = "AnonymousName";
228
+ const genName = uniqueName().setPrefix({ key: prefixKey, value: "a_" });
229
+ const anonymousExportVisitor = (context, depsTree, sourceFile, exportDefaultExportNameMap) => {
230
+ const { factory } = context;
231
+ const visit = (node) => {
232
+ const fileName = path.basename(depsTree.file).split(".")[0];
233
+ if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) &&
234
+ node.name === undefined) {
235
+ let exp = false;
236
+ let def = false;
237
+ node.modifiers?.forEach((mod) => {
238
+ if (mod.kind === ts.SyntaxKind.ExportKeyword) {
239
+ exp = true;
240
+ }
241
+ if (mod.kind === ts.SyntaxKind.DefaultKeyword) {
242
+ def = true;
243
+ }
244
+ });
245
+ if (exp && def) {
246
+ const base = genName.getName(fileName);
247
+ exportDefaultExportNameMap.push({
248
+ base,
249
+ file: fileName,
250
+ newName: base,
251
+ isEd: true,
252
+ });
253
+ if (ts.isFunctionDeclaration(node)) {
254
+ return factory.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, factory.createIdentifier(base), node.typeParameters, node.parameters, node.type, node.body);
255
+ }
256
+ else if (ts.isClassDeclaration(node)) {
257
+ return factory.updateClassDeclaration(node, node.modifiers, factory.createIdentifier(base), node.typeParameters, node.heritageClauses, node.members);
258
+ }
259
+ }
260
+ }
261
+ else if (ts.isExportAssignment(node) &&
262
+ !node.name &&
263
+ !node.isExportEquals) {
264
+ if (ts.isArrowFunction(node.expression)) {
265
+ const base = genName.getName(fileName);
266
+ const arrowFunctionNode = factory.createArrowFunction(node.expression.modifiers, node.expression.typeParameters, node.expression.parameters, node.expression.type, node.expression.equalsGreaterThanToken, node.expression.body);
267
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), node.expression.exclamationToken, node.expression.type, arrowFunctionNode);
268
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], ts.NodeFlags.Const);
269
+ const variableStatementNode = factory.createVariableStatement(node.expression.modifiers, variableDeclarationListNode);
270
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
271
+ exportDefaultExportNameMap.push({
272
+ base,
273
+ file: fileName,
274
+ newName: base,
275
+ isEd: true,
276
+ });
277
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
278
+ }
279
+ else if (ts.isObjectLiteralExpression(node.expression)) {
280
+ const base = genName.getName(fileName);
281
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, node.expression);
282
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], ts.NodeFlags.Const);
283
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
284
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
285
+ exportDefaultExportNameMap.push({
286
+ base,
287
+ file: fileName,
288
+ newName: base,
289
+ isEd: true,
290
+ });
291
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
292
+ }
293
+ else if (ts.isArrayLiteralExpression(node.expression)) {
294
+ const base = genName.getName(fileName);
295
+ const arrayLiteralExpressionNode = factory.createArrayLiteralExpression(node.expression.elements, true);
296
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, arrayLiteralExpressionNode);
297
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], ts.NodeFlags.Const);
298
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
299
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
300
+ exportDefaultExportNameMap.push({
301
+ base,
302
+ file: fileName,
303
+ newName: base,
304
+ isEd: true,
305
+ });
306
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
307
+ }
308
+ else if (ts.isStringLiteral(node.expression)) {
309
+ const base = genName.getName(fileName);
310
+ const stringLiteralNode = factory.createStringLiteral(node.expression.text);
311
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, stringLiteralNode);
312
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], ts.NodeFlags.Const);
313
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
314
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
315
+ exportDefaultExportNameMap.push({
316
+ base,
317
+ file: fileName,
318
+ newName: base,
319
+ isEd: true,
320
+ });
321
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
322
+ }
323
+ else if (ts.isNumericLiteral(node.expression)) {
324
+ const base = genName.getName(fileName);
325
+ const numericLiteralNode = factory.createNumericLiteral(node.expression.text);
326
+ const variableDeclarationNode = factory.createVariableDeclaration(factory.createIdentifier(base), undefined, undefined, numericLiteralNode);
327
+ const variableDeclarationListNode = factory.createVariableDeclarationList([variableDeclarationNode], ts.NodeFlags.Const);
328
+ const variableStatementNode = factory.createVariableStatement(undefined, variableDeclarationListNode);
329
+ const exportAssignmentNode = factory.createExportAssignment(undefined, undefined, factory.createIdentifier(base));
330
+ exportDefaultExportNameMap.push({
331
+ base,
332
+ file: fileName,
333
+ newName: base,
334
+ isEd: true,
335
+ });
336
+ return factory.updateSourceFile(sourceFile, [variableStatementNode, exportAssignmentNode], sourceFile.isDeclarationFile, sourceFile.referencedFiles, sourceFile.typeReferenceDirectives, sourceFile.hasNoDefaultLib, sourceFile.libReferenceDirectives);
337
+ }
338
+ }
339
+ return ts.visitEachChild(node, visit, context);
340
+ };
341
+ return visit;
342
+ };
343
+ const anonymousImportVisitor = (context, depsTree, sourceFile, exportDefaultExportNameMap, exportDefaultImportNameMap) => {
344
+ const { factory } = context;
345
+ const visit = (node) => {
346
+ if (ts.isImportDeclaration(node)) {
347
+ const fileName = node.moduleSpecifier.getText(sourceFile);
348
+ const _name = path.basename(fileName).split(".")[0].trim();
349
+ if (node.importClause?.name && ts.isIdentifier(node.importClause.name)) {
350
+ const base = node.importClause.name.text.trim();
351
+ const mapping = exportDefaultExportNameMap.find((v) => v.file === _name);
352
+ if (mapping) {
353
+ exportDefaultImportNameMap.push({
354
+ base,
355
+ file: depsTree.file,
356
+ newName: mapping.newName,
357
+ isEd: true,
358
+ });
359
+ const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, factory.createIdentifier(mapping.newName), node.importClause.namedBindings);
360
+ return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
361
+ }
362
+ }
363
+ }
364
+ return ts.visitEachChild(node, visit, context);
365
+ };
366
+ return visit;
367
+ };
368
+ const duplicateCallExpressionVisitor = (context, depsTree, _sourceFile, callNameMap, importNameMap) => {
369
+ const { factory } = context;
370
+ const visit = (node) => {
371
+ if (ts.isCallExpression(node)) {
372
+ if (ts.isIdentifier(node.expression)) {
373
+ const base = node.expression.text;
374
+ let new_name = null;
375
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
376
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
377
+ if (mapping) {
378
+ new_name = mapping.newName;
379
+ }
380
+ else if (importMapping) {
381
+ new_name = importMapping.newName;
382
+ }
383
+ if (new_name) {
384
+ return factory.updateCallExpression(node, factory.createIdentifier(new_name), node.typeArguments, node.arguments);
385
+ }
386
+ }
387
+ }
388
+ else if (ts.isPropertyAccessExpression(node)) {
389
+ if (ts.isIdentifier(node.expression)) {
390
+ const base = node.expression.text;
391
+ let new_name = null;
392
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
393
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
394
+ if (mapping) {
395
+ new_name = mapping.newName;
396
+ }
397
+ else if (importMapping) {
398
+ new_name = importMapping.newName;
399
+ }
400
+ if (new_name) {
401
+ return factory.updatePropertyAccessExpression(node, factory.createIdentifier(new_name), node.name);
402
+ }
403
+ }
404
+ }
405
+ else if (ts.isNewExpression(node)) {
406
+ if (ts.isIdentifier(node.expression)) {
407
+ const base = node.expression.text;
408
+ let new_name = null;
409
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
410
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
411
+ if (mapping) {
412
+ new_name = mapping.newName;
413
+ }
414
+ else if (importMapping) {
415
+ new_name = importMapping.newName;
416
+ }
417
+ if (new_name) {
418
+ return factory.updateNewExpression(node, factory.createIdentifier(new_name), node.typeArguments, node.arguments);
419
+ }
420
+ }
421
+ }
422
+ return ts.visitEachChild(node, visit, context);
423
+ };
424
+ return visit;
425
+ };
426
+ const duplicateCollectionVisitor = (context, depsTree, _sourceFile, namesMap) => {
427
+ const visit = (node, isGlobalScope = true) => {
428
+ if (isGlobalScope) {
429
+ if (ts.isVariableStatement(node)) {
430
+ node.declarationList.declarations.forEach((decl) => {
431
+ if (ts.isIdentifier(decl.name)) {
432
+ const $name = decl.name.text;
433
+ if (!namesMap.has($name)) {
434
+ namesMap.set($name, new Set([{ file: depsTree.file }]));
435
+ }
436
+ else {
437
+ namesMap.get($name).add({ file: depsTree.file });
438
+ }
439
+ }
440
+ });
441
+ }
442
+ else if (ts.isFunctionDeclaration(node) ||
443
+ ts.isClassDeclaration(node) ||
444
+ ts.isEnumDeclaration(node) ||
445
+ ts.isInterfaceDeclaration(node) ||
446
+ ts.isTypeAliasDeclaration(node)) {
447
+ const $name = node.name?.text;
448
+ if ($name) {
449
+ if (!namesMap.has($name)) {
450
+ namesMap.set($name, new Set([{ file: depsTree.file }]));
451
+ }
452
+ else {
453
+ namesMap.get($name).add({ file: depsTree.file });
454
+ }
455
+ }
456
+ }
457
+ }
458
+ if (ts.isBlock(node) ||
459
+ ts.isFunctionDeclaration(node) ||
460
+ ts.isFunctionExpression(node) ||
461
+ ts.isArrowFunction(node) ||
462
+ ts.isMethodDeclaration(node) ||
463
+ ts.isClassDeclaration(node)) {
464
+ if (ts.isBlock(node)) {
465
+ ts.visitNodes(node.statements, (child) => visit(child, false));
466
+ }
467
+ else {
468
+ ts.forEachChild(node, (child) => {
469
+ visit(child, false);
470
+ });
471
+ }
472
+ }
473
+ else {
474
+ return ts.visitEachChild(node, (child) => visit(child, isGlobalScope), context);
475
+ }
476
+ return node;
477
+ };
478
+ return visit;
479
+ };
480
+ const duplicateExportExpressionVisitor = (context, depsTree, _sourceFile, callNameMap, importNameMap, exportNameMap) => {
481
+ const { factory } = context;
482
+ const visit = (node) => {
483
+ if (ts.isExportSpecifier(node)) {
484
+ if (ts.isIdentifier(node.name)) {
485
+ const base = node.name.text;
486
+ let new_name = null;
487
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
488
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
489
+ if (mapping) {
490
+ exportNameMap.push({
491
+ base,
492
+ file: getFileKey(depsTree.file),
493
+ newName: mapping.newName,
494
+ });
495
+ new_name = mapping.newName;
496
+ }
497
+ else if (importMapping) {
498
+ new_name = importMapping.newName;
499
+ }
500
+ if (new_name) {
501
+ return factory.updateExportSpecifier(node, node.isTypeOnly, node.propertyName, factory.createIdentifier(new_name));
502
+ }
503
+ }
504
+ }
505
+ else if (ts.isExportAssignment(node)) {
506
+ const expr = node.expression;
507
+ if (ts.isIdentifier(expr)) {
508
+ const base = expr.text;
509
+ let new_name = null;
510
+ const mapping = callNameMap.find((m) => m.base === base && m.file === depsTree.file);
511
+ const importMapping = importNameMap.find((m) => m.base === base && m.file === depsTree.file);
512
+ if (mapping) {
513
+ exportNameMap.push({
514
+ base,
515
+ file: getFileKey(depsTree.file),
516
+ newName: mapping.newName,
517
+ });
518
+ new_name = mapping.newName;
519
+ }
520
+ else if (importMapping) {
521
+ new_name = importMapping.newName;
522
+ }
523
+ if (new_name) {
524
+ return factory.updateExportAssignment(node, node.modifiers, factory.createIdentifier(new_name));
525
+ }
526
+ }
527
+ }
528
+ return ts.visitEachChild(node, visit, context);
529
+ };
530
+ return visit;
531
+ };
532
+ const duplicateImportExpressionVisitor = (context, depsTree, sourceFile, exportNameMap, importNameMap) => {
533
+ const { factory } = context;
534
+ const visit = (node) => {
535
+ if (ts.isImportDeclaration(node)) {
536
+ const moduleKey = getModuleKeyFromSpecifier(node.moduleSpecifier, sourceFile, depsTree.file);
537
+ let baseNames = [];
538
+ if (node.importClause?.namedBindings &&
539
+ ts.isNamedImports(node.importClause.namedBindings)) {
540
+ baseNames = node.importClause.namedBindings.elements.map((el) => el.name.text.trim());
541
+ }
542
+ if (node.importClause?.name && ts.isIdentifier(node.importClause.name)) {
543
+ const base = node.importClause.name.text.trim();
544
+ const mapping = exportNameMap.find((m) => m.base === base && m.file === moduleKey);
545
+ if (mapping) {
546
+ importNameMap.push({
547
+ base: mapping.base,
548
+ file: depsTree.file,
549
+ newName: mapping.newName,
550
+ });
551
+ const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, factory.createIdentifier(mapping.newName), node.importClause.namedBindings);
552
+ return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
553
+ }
554
+ }
555
+ if (baseNames.length > 0 &&
556
+ node.importClause &&
557
+ node.importClause.namedBindings &&
558
+ ts.isNamedImports(node.importClause.namedBindings)) {
559
+ const updatedElements = node.importClause.namedBindings.elements.map((el) => {
560
+ const mapping = exportNameMap.find((m) => m.base === el.name.text.trim() && m.file === moduleKey);
561
+ if (mapping) {
562
+ importNameMap.push({
563
+ base: mapping.base,
564
+ file: depsTree.file,
565
+ newName: mapping.newName,
566
+ });
567
+ return factory.updateImportSpecifier(el, el.isTypeOnly, el.propertyName, factory.createIdentifier(mapping.newName));
568
+ }
569
+ return el;
570
+ });
571
+ const newNamedImports = factory.updateNamedImports(node.importClause.namedBindings, updatedElements);
572
+ const newImportClause = factory.updateImportClause(node.importClause, node.importClause.phaseModifier, node.importClause.name, newNamedImports);
573
+ return factory.updateImportDeclaration(node, node.modifiers, newImportClause, node.moduleSpecifier, node.attributes);
574
+ }
575
+ }
576
+ return ts.visitEachChild(node, visit, context);
577
+ };
578
+ return visit;
579
+ };
580
+ const dupName = uniqueName().setPrefix({
581
+ key: "DuplicatesNames",
582
+ value: "d_",
583
+ });
584
+ const duplicateUpdateVisitor = (context, depsTree, _sourceFile, namesMap, callNameMap) => {
585
+ const { factory } = context;
586
+ const visit = (node) => {
587
+ if (ts.isVariableStatement(node)) {
588
+ const newDeclarations = node.declarationList.declarations.map((decl) => {
589
+ if (ts.isIdentifier(decl.name)) {
590
+ const base = decl.name.text;
591
+ if (namesMap.has(base) && namesMap.get(base).size > 1) {
592
+ const newName = dupName.getName(base);
593
+ callNameMap.push({ base, file: depsTree.file, newName });
594
+ return factory.updateVariableDeclaration(decl, factory.createIdentifier(newName), decl.exclamationToken, decl.type, decl.initializer);
595
+ }
596
+ }
597
+ return decl;
598
+ });
599
+ const newDeclList = factory.updateVariableDeclarationList(node.declarationList, newDeclarations);
600
+ return factory.updateVariableStatement(node, node.modifiers, newDeclList);
601
+ }
602
+ else if (ts.isFunctionDeclaration(node)) {
603
+ if (node.name && ts.isIdentifier(node.name)) {
604
+ const base = node.name.text;
605
+ if (namesMap.has(base) && namesMap.get(base).size > 1) {
606
+ const newName = dupName.getName(base);
607
+ callNameMap.push({ base, file: depsTree.file, newName });
608
+ return factory.updateFunctionDeclaration(node, node.modifiers, node.asteriskToken, factory.createIdentifier(newName), node.typeParameters, node.parameters, node.type, node.body);
609
+ }
610
+ }
611
+ }
612
+ else if (ts.isClassDeclaration(node)) {
613
+ if (node.name && ts.isIdentifier(node.name)) {
614
+ const base = node.name.text;
615
+ if (namesMap.has(base) && namesMap.get(base).size > 1) {
616
+ const newName = dupName.getName(base);
617
+ callNameMap.push({ base, file: depsTree.file, newName });
618
+ return factory.updateClassDeclaration(node, node.modifiers, factory.createIdentifier(newName), node.typeParameters, node.heritageClauses, node.members);
619
+ }
620
+ }
621
+ }
622
+ return ts.visitEachChild(node, visit, context);
623
+ };
624
+ return visit;
625
+ };
626
+ const removeExportsVisitor = (context) => {
627
+ const { factory } = context;
628
+ const visit = (node) => {
629
+ const inside_nameSpace = utilities.isInsideNamespace(node);
630
+ if (!inside_nameSpace) {
631
+ if (ts.isFunctionDeclaration(node) ||
632
+ ts.isClassDeclaration(node) ||
633
+ ts.isInterfaceDeclaration(node) ||
634
+ ts.isTypeAliasDeclaration(node) ||
635
+ ts.isEnumDeclaration(node) ||
636
+ ts.isVariableStatement(node)) {
637
+ const modifiers = node.modifiers?.filter((m) => m.kind !== ts.SyntaxKind.ExportKeyword &&
638
+ m.kind !== ts.SyntaxKind.DefaultKeyword);
639
+ if (modifiers?.length !== node.modifiers?.length) {
640
+ if (ts.isFunctionDeclaration(node)) {
641
+ return factory.updateFunctionDeclaration(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
642
+ }
643
+ if (ts.isClassDeclaration(node)) {
644
+ return factory.updateClassDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
645
+ }
646
+ if (ts.isInterfaceDeclaration(node)) {
647
+ return factory.updateInterfaceDeclaration(node, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members);
648
+ }
649
+ if (ts.isTypeAliasDeclaration(node)) {
650
+ return factory.updateTypeAliasDeclaration(node, modifiers, node.name, node.typeParameters, node.type);
651
+ }
652
+ if (ts.isEnumDeclaration(node)) {
653
+ return factory.updateEnumDeclaration(node, modifiers, node.name, node.members);
654
+ }
655
+ if (ts.isVariableStatement(node)) {
656
+ return factory.updateVariableStatement(node, modifiers, node.declarationList);
657
+ }
658
+ }
659
+ }
660
+ }
661
+ if (ts.isExportDeclaration(node)) {
662
+ return factory.createEmptyStatement();
663
+ }
664
+ if (ts.isExportAssignment(node)) {
665
+ const expr = node.expression;
666
+ if (ts.isIdentifier(expr)) {
667
+ return factory.createEmptyStatement();
668
+ }
669
+ }
670
+ return ts.visitEachChild(node, visit, context);
671
+ };
672
+ return visit;
673
+ };
674
+ let properties = [];
675
+ const typeObj = {};
676
+ const typesNames = [];
677
+ function findProperty(node) {
678
+ const properties = [];
679
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
680
+ properties.push(node.expression.text);
681
+ }
682
+ node.forEachChild((n) => findProperty(n));
683
+ return properties;
684
+ }
685
+ const removeImportsVisitor = (context, depsTree, sourceFile, removedStatements) => {
686
+ const typeOnlyImportEquals = new Set();
687
+ for (const stmt of sourceFile.statements) {
688
+ if (ts.isImportEqualsDeclaration(stmt) && stmt.isTypeOnly) {
689
+ const moduleReference = stmt.moduleReference;
690
+ if (ts.isExternalModuleReference(moduleReference) &&
691
+ ts.isStringLiteral(moduleReference.expression)) {
692
+ typeOnlyImportEquals.add(stmt.name.text);
693
+ }
694
+ }
695
+ }
696
+ const { factory } = context;
697
+ const visit = (node) => {
698
+ properties = [...properties, ...findProperty(node)];
699
+ const obj = {
700
+ isNamespace: false,
701
+ isTypeOnly: false,
702
+ isTypeNamespace: false,
703
+ source: "",
704
+ importedString: undefined,
705
+ importedObject: undefined,
706
+ };
707
+ if (ts.isTypeReferenceNode(node) &&
708
+ ts.isQualifiedName(node.typeName) &&
709
+ ts.isIdentifier(node.typeName.left) &&
710
+ ts.isIdentifier(node.typeName.right)) {
711
+ const left = node.typeName.left.text;
712
+ const right = node.typeName.right.text;
713
+ typesNames.push(left);
714
+ if (left in typeObj) {
715
+ typeObj[left]?.push(right);
716
+ }
717
+ else {
718
+ typeObj[left] = [right];
719
+ }
720
+ if (utilities.checkModuleType(sourceFile, depsTree.file).isCommonJs) {
721
+ if (left !== "ts" && !typeOnlyImportEquals.has(left)) {
722
+ return factory.updateTypeReferenceNode(node, factory.createIdentifier(right), undefined);
723
+ }
724
+ }
725
+ }
726
+ if (ts.isImportDeclaration(node)) {
727
+ const text = node.getText(sourceFile);
728
+ removedStatements.push(text);
729
+ return factory.createEmptyStatement();
730
+ }
731
+ if (ts.isImportEqualsDeclaration(node)) {
732
+ const name = node.name.text;
733
+ const moduleReference = node.moduleReference;
734
+ if (node.isTypeOnly) {
735
+ obj.isTypeOnly = true;
736
+ }
737
+ obj.importedString = name;
738
+ if (!obj.isTypeOnly) {
739
+ if (properties.includes(name)) {
740
+ obj.isNamespace = true;
741
+ }
742
+ }
743
+ if (ts.isExternalModuleReference(moduleReference) &&
744
+ ts.isStringLiteral(moduleReference.expression)) {
745
+ obj.source = moduleReference.expression.text;
746
+ }
747
+ let t;
748
+ if (obj.importedString && !obj.importedObject) {
749
+ if (obj.isTypeOnly) {
750
+ if (typeOnlyImportEquals.has(obj.importedString)) {
751
+ t = `import type * as ${obj.importedString} from "${obj.source}";`;
752
+ }
753
+ else {
754
+ if (typesNames.includes(obj.importedString)) {
755
+ t = `import type { ${typeObj[obj.importedString]?.join(",")} } from "${obj.source}";`;
756
+ }
757
+ else {
758
+ t = `import type ${obj.importedString} from "${obj.source}";`;
759
+ }
760
+ }
761
+ }
762
+ else {
763
+ if (obj.isNamespace && obj.source && obj.source !== "typescript") {
764
+ t = `import * as ${obj.importedString} from "${obj.source}";`;
765
+ }
766
+ else {
767
+ t = `import ${obj.importedString} from "${obj.source}";`;
768
+ }
769
+ }
770
+ }
771
+ if (!obj.importedString && obj.importedObject) {
772
+ t = `import { ${obj.importedObject.join(", ")} } from "${obj.source}";`;
773
+ }
774
+ if (t) {
775
+ removedStatements.push(t);
776
+ return factory.createEmptyStatement();
777
+ }
778
+ }
779
+ if (ts.isVariableStatement(node)) {
780
+ const decls = node.declarationList.declarations;
781
+ if (decls.length === 1) {
782
+ const decl = decls[0];
783
+ if (decl.initializer &&
784
+ ts.isCallExpression(decl.initializer) &&
785
+ ts.isIdentifier(decl.initializer.expression) &&
786
+ decl.initializer.expression.escapedText === "require") {
787
+ const arg = decl.initializer.arguments[0];
788
+ if (ts.isStringLiteral(arg)) {
789
+ obj.source = arg.text;
790
+ }
791
+ if (ts.isIdentifier(decl.name)) {
792
+ const _n = decl.name.text;
793
+ obj.importedString = _n;
794
+ if (properties.includes(_n)) {
795
+ obj.isNamespace = true;
796
+ }
797
+ }
798
+ else if (ts.isObjectBindingPattern(decl.name)) {
799
+ const _names = [];
800
+ for (const ele of decl.name.elements) {
801
+ if (ts.isIdentifier(ele.name)) {
802
+ _names.push(ele.name.text);
803
+ }
804
+ }
805
+ if (_names.length > 0) {
806
+ obj.importedObject = _names;
807
+ }
808
+ }
809
+ let tt;
810
+ if (obj.importedString && !obj.importedObject) {
811
+ if (obj.isNamespace) {
812
+ tt = `import * as ${obj.importedString} from "${obj.source}";`;
813
+ }
814
+ else {
815
+ tt = `import ${obj.importedString} from "${obj.source}";`;
816
+ }
817
+ }
818
+ if (!obj.importedString && obj.importedObject) {
819
+ tt = `import { ${obj.importedObject.join(", ")} } from "${obj.source}";`;
820
+ }
821
+ if (tt) {
822
+ removedStatements.push(tt);
823
+ return factory.createEmptyStatement();
824
+ }
825
+ }
826
+ }
827
+ }
828
+ return ts.visitEachChild(node, visit, context);
829
+ };
830
+ return visit;
831
+ };
832
+ async function bundler(point) {
833
+ let depsFiles = point.depFiles;
834
+ const reName = point.rename;
835
+ const compilerOptions = point.tsOptions.default;
836
+ const plugins = point.plugins;
197
837
  const namesMap = new Map();
198
838
  const callNameMap = [];
199
839
  const importNameMap = [];
@@ -201,30 +841,136 @@ async function bundler({ depsFiles, compilerOptions, renameDuplicates, }) {
201
841
  const exportDefaultExportNameMap = [];
202
842
  const exportDefaultImportNameMap = [];
203
843
  let removedStatements = [];
204
- if (reName) {
205
- depsFiles = await duplicateHandlers.renamed(depsFiles, namesMap, callNameMap, importNameMap, exportNameMap, compilerOptions);
844
+ const duplicate = async (reName) => {
845
+ if (reName) {
846
+ const re_name = resolves([
847
+ [bundleCreator, duplicateCollectionVisitor, compilerOptions, namesMap],
848
+ [
849
+ bundleCreator,
850
+ duplicateUpdateVisitor,
851
+ compilerOptions,
852
+ namesMap,
853
+ callNameMap,
854
+ ],
855
+ [
856
+ bundleCreator,
857
+ duplicateCallExpressionVisitor,
858
+ compilerOptions,
859
+ callNameMap,
860
+ importNameMap,
861
+ ],
862
+ [
863
+ bundleCreator,
864
+ duplicateExportExpressionVisitor,
865
+ compilerOptions,
866
+ importNameMap,
867
+ exportNameMap,
868
+ ],
869
+ [
870
+ bundleCreator,
871
+ duplicateImportExpressionVisitor,
872
+ compilerOptions,
873
+ exportNameMap,
874
+ importNameMap,
875
+ ],
876
+ [
877
+ bundleCreator,
878
+ duplicateExportExpressionVisitor,
879
+ compilerOptions,
880
+ importNameMap,
881
+ exportNameMap,
882
+ ],
883
+ [
884
+ bundleCreator,
885
+ duplicateExportExpressionVisitor,
886
+ compilerOptions,
887
+ importNameMap,
888
+ exportNameMap,
889
+ ],
890
+ ]);
891
+ const re_name_call = await re_name.concurrent();
892
+ for (const call of re_name_call) {
893
+ await utilities.wait(500);
894
+ depsFiles = depsFiles.map(call);
895
+ }
896
+ }
897
+ else {
898
+ let _err = false;
899
+ const un_rename = resolves([
900
+ [bundleCreator, duplicateCollectionVisitor, compilerOptions, namesMap],
901
+ ]);
902
+ const un_rename_call = await un_rename.concurrent();
903
+ depsFiles.map(un_rename_call[0]);
904
+ await utilities.wait(1000);
905
+ namesMap.forEach((files, name) => {
906
+ if (files.size > 1) {
907
+ _err = true;
908
+ console.warn(`Name -> ${name} declared in multiple files :`);
909
+ files.forEach((f) => console.warn(` - ${f.file}`));
910
+ }
911
+ });
912
+ await utilities.wait(1000);
913
+ if (_err) {
914
+ process.exit(1);
915
+ }
916
+ }
917
+ };
918
+ if (plugins.length) {
919
+ for (let plugin of plugins) {
920
+ plugin = typeof plugin === "function" ? plugin() : plugin;
921
+ if (plugin.type === "dependency") {
922
+ if (plugin.async) {
923
+ depsFiles = await plugin.func(depsFiles);
924
+ }
925
+ else {
926
+ depsFiles = plugin.func(depsFiles);
927
+ }
928
+ }
929
+ }
206
930
  }
207
- else {
208
- depsFiles = await duplicateHandlers.notRenamed(depsFiles, namesMap, compilerOptions);
931
+ await utilities.wait(1000);
932
+ await duplicate(reName);
933
+ const anonymous = resolves([
934
+ [
935
+ bundleCreator,
936
+ anonymousExportVisitor,
937
+ compilerOptions,
938
+ exportDefaultExportNameMap,
939
+ ],
940
+ [
941
+ bundleCreator,
942
+ anonymousImportVisitor,
943
+ compilerOptions,
944
+ exportDefaultImportNameMap,
945
+ exportDefaultImportNameMap,
946
+ ],
947
+ [
948
+ bundleCreator,
949
+ anonymousCallExpressionVisitor,
950
+ compilerOptions,
951
+ exportDefaultImportNameMap,
952
+ ],
953
+ ]);
954
+ const anonymousCall = await anonymous.concurrent();
955
+ for (const call of anonymousCall) {
956
+ depsFiles = depsFiles.map(call);
209
957
  }
210
- await utils.wait(1000);
211
- depsFiles = await anonymous(depsFiles, exportDefaultExportNameMap, exportDefaultImportNameMap, compilerOptions);
212
- await utils.wait(1000);
958
+ await utilities.wait(1000);
213
959
  const removeImports = resolves([
214
- [removeImportExpressionHandler, removedStatements, compilerOptions],
960
+ [bundleCreator, removeImportsVisitor, compilerOptions, removedStatements],
215
961
  ]);
216
962
  const removeImport = await removeImports.concurrent();
217
963
  depsFiles = depsFiles.map(removeImport[0]);
218
- await utils.wait(1000);
964
+ await utilities.wait(500);
219
965
  const removeExports = resolves([
220
- [removeExportExpressionHandler, compilerOptions],
966
+ [bundleCreator, removeExportsVisitor, compilerOptions],
221
967
  ]);
222
968
  const removeExport = await removeExports.concurrent();
223
969
  const deps_files = depsFiles.slice(0, -1).map(removeExport[0]);
224
970
  const mainFile = depsFiles.slice(-1);
225
971
  const regexp = /["']((?!\.\/|\.\.\/)[^"']+)["']/;
226
972
  removedStatements = removedStatements.filter((i) => regexp.test(i));
227
- removedStatements = mergeImports(removedStatements);
973
+ removedStatements = mergeImportsStatement(removedStatements);
228
974
  const importStatements = removedStatements.join("\n").trim();
229
975
  const depFilesContent = deps_files
230
976
  .map((i) => {
@@ -240,80 +986,35 @@ async function bundler({ depsFiles, compilerOptions, renameDuplicates, }) {
240
986
  })
241
987
  .join("\n")
242
988
  .trim();
243
- await utils.wait(1000);
244
- const content = `${importStatements}\n${depFilesContent}\n${mainFileContent}`;
245
- return content;
246
- }
247
- function checkExports(file, str) {
248
- const sourceFile = ts.createSourceFile(file, str, ts.ScriptTarget.Latest, true);
249
- let nameExport = false;
250
- let defExport = false;
251
- const transformer = (context) => {
252
- const visitor = (node) => {
253
- if (ts.isExportAssignment(node) &&
254
- !node.isExportEquals &&
255
- node.modifiers === undefined &&
256
- ts.isIdentifier(node.expression)) {
257
- defExport = true;
258
- }
259
- else if (ts.isFunctionDeclaration(node) ||
260
- ts.isClassDeclaration(node)) {
261
- let exp = false;
262
- let def = false;
263
- node.modifiers?.forEach((mod) => {
264
- if (mod.kind === ts.SyntaxKind.ExportKeyword) {
265
- exp = true;
266
- }
267
- if (mod.kind === ts.SyntaxKind.DefaultKeyword) {
268
- def = true;
269
- }
270
- });
271
- if (exp && def)
272
- defExport = true;
273
- }
274
- else if (ts.isExportAssignment(node) &&
275
- ts.isObjectLiteralExpression(node.expression)) {
276
- const pros = node.expression.properties;
277
- for (const pro of pros) {
278
- if (pro.name && ts.isIdentifier(pro.name)) {
279
- defExport = true;
280
- }
989
+ await utilities.wait(1000);
990
+ let content = `${importStatements}\n${depFilesContent}\n${mainFileContent}`;
991
+ if (plugins.length) {
992
+ for (let plugin of plugins) {
993
+ plugin = typeof plugin === "function" ? plugin() : plugin;
994
+ if (plugin.type === "pre-process") {
995
+ if (plugin.async) {
996
+ content = await plugin.func(content);
997
+ }
998
+ else {
999
+ content = plugin.func(content);
281
1000
  }
282
1001
  }
283
- else if (ts.isNamedExports(node)) {
284
- nameExport = true;
285
- }
286
- else if (ts.isVariableStatement(node) ||
287
- ts.isFunctionDeclaration(node) ||
288
- ts.isInterfaceDeclaration(node) ||
289
- ts.isTypeAliasDeclaration(node)) {
290
- const isInsideNamespace = (n) => {
291
- let current = n.parent;
292
- while (current) {
293
- if (ts.isModuleDeclaration(current) &&
294
- current.flags === ts.NodeFlags.Namespace) {
295
- return true;
296
- }
297
- current = current.parent;
298
- }
299
- return false;
300
- };
301
- node?.modifiers?.forEach((mod) => {
302
- if (mod.kind === ts.SyntaxKind.ExportKeyword) {
303
- if (!isInsideNamespace(node)) {
304
- nameExport = true;
305
- }
306
- }
307
- });
308
- }
309
- return ts.visitEachChild(node, visitor, context);
310
- };
311
- return (rootNode) => ts.visitNode(rootNode, visitor);
1002
+ }
1003
+ }
1004
+ return { bundledContent: content, ...point };
1005
+ }
1006
+ async function bundle(object) {
1007
+ const points = [];
1008
+ for (const point of object.points) {
1009
+ const _point = await bundler(point);
1010
+ points.push(_point);
1011
+ }
1012
+ return {
1013
+ points,
1014
+ allowUpdatePackageJson: object.allowUpdatePackageJson,
312
1015
  };
313
- ts.transform(sourceFile, [transformer]);
314
- return { nameExport, defExport };
315
1016
  }
316
- const createHost = (sourceCode, fileName) => {
1017
+ function createHost(sourceCode, fileName) {
317
1018
  const createdFiles = {};
318
1019
  const host = {
319
1020
  getSourceFile: (file, languageVersion) => {
@@ -335,80 +1036,106 @@ const createHost = (sourceCode, fileName) => {
335
1036
  getNewLine: () => "\n",
336
1037
  };
337
1038
  return { createdFiles, host };
338
- };
339
- function replaceInJs(fileName, sourceCode, compilerOptions) {
340
- const sourceFile = ts.createSourceFile(fileName, sourceCode, ts.ScriptTarget.Latest, true);
341
- const transformer = (context) => {
342
- const { factory } = context;
343
- const visitor = (node) => {
344
- if (ts.isExpressionStatement(node)) {
345
- const expr = node.expression;
346
- if (ts.isBinaryExpression(expr) &&
347
- ts.isPropertyAccessExpression(expr.left) &&
348
- ts.isIdentifier(expr.left.expression) &&
349
- expr.left.expression.escapedText === "exports" &&
350
- ts.isIdentifier(expr.left.name) &&
351
- expr.left.name.escapedText === "default" &&
352
- expr.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
353
- ts.isIdentifier(expr.right)) {
354
- const newLeftExpr = factory.createIdentifier("module");
355
- const newName = factory.createIdentifier("exports");
356
- const newLeft = factory.updatePropertyAccessExpression(expr.left, newLeftExpr, newName);
357
- const newExpr = factory.updateBinaryExpression(expr, newLeft, expr.operatorToken, expr.right);
358
- return factory.updateExpressionStatement(node, newExpr);
359
- }
360
- }
361
- return ts.visitEachChild(node, visitor, context);
362
- };
363
- return (rootNode) => ts.visitNode(rootNode, visitor);
364
- };
365
- return transformFunction(transformer, sourceFile, compilerOptions);
366
1039
  }
367
- function replaceInTs(fileName, sourceCode, compilerOptions) {
368
- const sourceFile = ts.createSourceFile(fileName, sourceCode, ts.ScriptTarget.Latest, true);
369
- const transformer = (context) => {
370
- const { factory } = context;
371
- const visitor = (node) => {
372
- if (ts.isExportAssignment(node) &&
373
- node.modifiers === undefined &&
374
- !node.isExportEquals) {
375
- return factory.createExportAssignment(node.modifiers, true, node.expression);
376
- }
377
- return ts.visitEachChild(node, visitor, context);
378
- };
379
- return (rootNode) => ts.visitNode(rootNode, visitor);
380
- };
381
- return transformFunction(transformer, sourceFile, compilerOptions);
1040
+ const isCjs = (files) => files.commonjs && files.commonjsTypes;
1041
+ const isEsm = (files) => files.esm && files.esmTypes;
1042
+ function getExports(files, exportPath) {
1043
+ return isCjs(files) && isEsm(files)
1044
+ ? {
1045
+ [exportPath]: {
1046
+ import: {
1047
+ default: `./${path.relative(process.cwd(), files.esm)}`,
1048
+ types: `./${path.relative(process.cwd(), files.esmTypes)}`,
1049
+ },
1050
+ require: {
1051
+ default: `./${path.relative(process.cwd(), files.commonjs)}`,
1052
+ types: `./${path.relative(process.cwd(), files.commonjsTypes)}`,
1053
+ },
1054
+ },
1055
+ }
1056
+ : isCjs(files) && !isEsm(files)
1057
+ ? {
1058
+ [exportPath]: {
1059
+ require: {
1060
+ default: `./${path.relative(process.cwd(), files.commonjs)}`,
1061
+ types: `./${path.relative(process.cwd(), files.commonjsTypes)}`,
1062
+ },
1063
+ },
1064
+ }
1065
+ : !isCjs(files) && isEsm(files)
1066
+ ? {
1067
+ [exportPath]: {
1068
+ import: {
1069
+ default: `./${path.relative(process.cwd(), files.esm)}`,
1070
+ types: `./${path.relative(process.cwd(), files.esmTypes)}`,
1071
+ },
1072
+ },
1073
+ }
1074
+ : {};
382
1075
  }
383
- async function clearFolder(folderPath) {
384
- folderPath = path.resolve(process.cwd(), folderPath);
385
- try {
386
- const entries = await fs.promises.readdir(folderPath, {
387
- withFileTypes: true,
388
- });
389
- await Promise.all(entries.map((entry) => fs.promises.rm(path.join(folderPath, entry.name), {
390
- recursive: true,
391
- })));
1076
+ async function writePackage(files, exportPath) {
1077
+ let isMain = true;
1078
+ if (exportPath !== ".") {
1079
+ isMain = false;
392
1080
  }
393
- catch (error) {
394
- if (error.code !== "ENOENT") {
395
- throw error;
396
- }
1081
+ const pkgFile = ts.sys.resolvePath("package.json");
1082
+ const _pkgtext = fs.readFileSync(pkgFile, "utf8");
1083
+ const pkgtext = JSON.parse(_pkgtext);
1084
+ let { name, version, description, main, module, type, types, exports, ...rest } = pkgtext;
1085
+ await utilities.wait(500);
1086
+ type = "module";
1087
+ let _main = {};
1088
+ let _module = {};
1089
+ let _types = {};
1090
+ let _exports = {};
1091
+ if (isMain) {
1092
+ _main = files.main
1093
+ ? { main: path.relative(process.cwd(), files.main) }
1094
+ : {};
1095
+ _module = files.module
1096
+ ? { module: path.relative(process.cwd(), files.module) }
1097
+ : {};
1098
+ _types = files.types
1099
+ ? { types: path.relative(process.cwd(), files.types) }
1100
+ : {};
1101
+ _exports = { exports: { ...getExports(files, exportPath) } };
1102
+ }
1103
+ else {
1104
+ _main = main ? { main: main } : {};
1105
+ _module = module ? { module: module } : {};
1106
+ _types = types ? { types: types } : {};
1107
+ const normalizedExports = exports && typeof exports === "object" && !Array.isArray(exports)
1108
+ ? { ...exports }
1109
+ : {};
1110
+ _exports = {
1111
+ exports: { ...normalizedExports, ...getExports(files, exportPath) },
1112
+ };
397
1113
  }
1114
+ await utilities.wait(1000);
1115
+ const pkgJson = {
1116
+ name,
1117
+ version,
1118
+ description,
1119
+ type,
1120
+ ..._main,
1121
+ ..._types,
1122
+ ..._module,
1123
+ ..._exports,
1124
+ ...rest,
1125
+ };
1126
+ utilities.writeCompileFile(pkgFile, JSON.stringify(pkgJson, null, 2));
398
1127
  }
399
- async function writeCompileFile(file, content) {
400
- const filePath = ts.sys.resolvePath(file);
401
- const dir = path.dirname(filePath);
402
- if (!ts.sys.directoryExists(dir)) {
403
- await fs.promises.mkdir(dir, { recursive: true });
404
- }
405
- await utils.wait(500);
406
- await fs.promises.writeFile(filePath, content);
1128
+ function splitCamelCase(str) {
1129
+ const splitString = str
1130
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
1131
+ .replace(/(_|-|\/)([a-z] || [A-Z])/g, " ")
1132
+ .replace(/([A-Z])/g, (match) => match.toLowerCase())
1133
+ .replace(/^([a-z])/, (match) => match.toUpperCase());
1134
+ return splitString;
407
1135
  }
408
- class Compilers {
409
- constructor(options) {
410
- this._target = options?.target ?? "both";
411
- this._configPath = options?.configPath;
1136
+ class Compiler {
1137
+ constructor(object) {
1138
+ this.object = object;
412
1139
  this.files = {
413
1140
  commonjs: undefined,
414
1141
  commonjsTypes: undefined,
@@ -418,48 +1145,46 @@ class Compilers {
418
1145
  module: undefined,
419
1146
  types: undefined,
420
1147
  };
421
- this.outDir = "";
422
1148
  }
423
- async commonjs(sourceCode, fileName, compilerOptions, isMain, hooks, isUpdate = true) {
424
- console.time(tcolor.green("Compiled Commonjs"));
425
- const ck = checkExports(fileName, sourceCode);
426
- if (ck.defExport && ck.nameExport) {
427
- console.warn(tcolor.yellow("Both name export and default export are exported from your project,that will effect on default export for commonjs output"));
428
- }
1149
+ _isUpdate() {
1150
+ return this.object.allowUpdatePackageJson;
1151
+ }
1152
+ async _commonjs(point) {
1153
+ const isMain = point.exportPath === ".";
1154
+ const _name = isMain ? "Main" : splitCamelCase(point.exportPath.slice(2));
1155
+ console.time(tcolor.cyan(`Compiled commonjs for ${_name} export path`));
1156
+ const fileName = point.fileName;
1157
+ const sourceCode = point.bundledContent;
1158
+ const format = point.format;
1159
+ const plugins = point.plugins;
1160
+ const compilerOptions = point.tsOptions.cjs;
429
1161
  const _host = createHost(sourceCode, fileName);
430
1162
  const createdFiles = _host.createdFiles;
431
1163
  const host = _host.host;
432
1164
  const program = ts.createProgram([fileName], compilerOptions, host);
433
1165
  program.emit();
434
1166
  Object.entries(createdFiles).map(async ([outName, content]) => {
435
- if (ck.defExport && !ck.nameExport) {
436
- const ext = utils.extname(outName);
437
- if (ext === ".js") {
438
- content = replaceInJs(fileName, content, compilerOptions);
439
- }
440
- if (ext === ".ts") {
441
- content = replaceInTs(fileName, content, compilerOptions);
442
- }
443
- }
444
- if (hooks?.length) {
445
- for (const hook of hooks) {
446
- if (hook.async) {
447
- content = await hook.func(content, outName);
448
- }
449
- else {
450
- content = hook.func(content, outName);
1167
+ if (plugins.length) {
1168
+ for (let plugin of plugins) {
1169
+ plugin = typeof plugin === "function" ? plugin() : plugin;
1170
+ if (plugin.type === "post-process") {
1171
+ if (plugin.async) {
1172
+ content = await plugin.func(content, outName);
1173
+ }
1174
+ else {
1175
+ content = plugin.func(content, outName);
1176
+ }
451
1177
  }
452
1178
  }
453
1179
  }
454
- if (isUpdate) {
1180
+ if (this._isUpdate()) {
455
1181
  if (outName.match(/.js/g)) {
456
1182
  this.files.commonjs = outName.replace(/.js/g, ".cjs");
457
1183
  }
458
1184
  if (outName.match(/.d.ts/g)) {
459
1185
  this.files.commonjsTypes = outName.replace(/.d.ts/g, ".d.cts");
460
1186
  }
461
- if (isMain &&
462
- (this._target === "both" || this._target === "commonjs")) {
1187
+ if (isMain && (format === "both" || format === "commonjs")) {
463
1188
  if (this.files.commonjs)
464
1189
  this.files.main = this.files.commonjs;
465
1190
  if (this.files.commonjsTypes)
@@ -469,59 +1194,98 @@ class Compilers {
469
1194
  outName = outName.replace(/.js/g, ".cjs");
470
1195
  outName = outName.replace(/.map.js/g, ".map.cjs");
471
1196
  outName = outName.replace(/.d.ts/g, ".d.cts");
472
- await utils.wait(500);
473
- if (this._target !== "both" && this._target !== "esm") {
474
- await clearFolder(utils.dirname(outName));
1197
+ await utilities.wait(500);
1198
+ if (format === "commonjs") {
1199
+ await utilities.clearFolder(path.dirname(outName));
475
1200
  }
476
- await writeCompileFile(outName, content);
1201
+ await utilities.writeCompileFile(outName, content);
477
1202
  });
478
- console.timeEnd(tcolor.green("Compiled Commonjs"));
1203
+ console.timeEnd(tcolor.cyan(`Compiled commonjs for ${_name} export path`));
479
1204
  }
480
- async esm(sourceCode, fileName, compilerOptions, isMain, hooks, isUpdate = true) {
481
- console.time(tcolor.green("Compiled ESM"));
1205
+ async _esm(point) {
1206
+ const isMain = point.exportPath === ".";
1207
+ const _name = isMain ? "Main" : splitCamelCase(point.exportPath.slice(2));
1208
+ console.time(tcolor.cyan(`Compiled esm for ${_name} export path`));
1209
+ const fileName = point.fileName;
1210
+ const sourceCode = point.bundledContent;
1211
+ const format = point.format;
1212
+ const plugins = point.plugins;
1213
+ const compilerOptions = point.tsOptions.esm;
482
1214
  const _host = createHost(sourceCode, fileName);
483
1215
  const createdFiles = _host.createdFiles;
484
1216
  const host = _host.host;
485
1217
  const program = ts.createProgram([fileName], compilerOptions, host);
486
1218
  program.emit();
487
1219
  Object.entries(createdFiles).map(async ([outName, content]) => {
488
- if (hooks?.length) {
489
- for (const hook of hooks) {
490
- if (hook.async) {
491
- content = await hook.func(content, outName);
492
- }
493
- else {
494
- content = hook.func(content, outName);
1220
+ if (plugins.length) {
1221
+ for (let plugin of plugins) {
1222
+ plugin = typeof plugin === "function" ? plugin() : plugin;
1223
+ if (plugin.type === "post-process") {
1224
+ if (plugin.async) {
1225
+ content = await plugin.func(content, outName);
1226
+ }
1227
+ else {
1228
+ content = plugin.func(content, outName);
1229
+ }
495
1230
  }
496
1231
  }
497
1232
  }
498
- if (isUpdate) {
1233
+ if (this._isUpdate()) {
499
1234
  if (outName.match(/.js/g)) {
500
1235
  this.files.esm = outName.replace(/.js/g, ".mjs");
501
1236
  }
502
1237
  if (outName.match(/.d.ts/g)) {
503
1238
  this.files.esmTypes = outName.replace(/.d.ts/g, ".d.mts");
504
1239
  }
505
- if (isMain && this._target === "both" && this.files.esm) {
1240
+ if (isMain && format === "both" && this.files.esm) {
506
1241
  this.files.module = this.files.esm;
507
1242
  }
508
1243
  }
509
1244
  outName = outName.replace(/.js/g, ".mjs");
510
1245
  outName = outName.replace(/.map.js/g, ".map.mjs");
511
1246
  outName = outName.replace(/.d.ts/g, ".d.mts");
512
- await utils.wait(500);
513
- if (this._target !== "commonjs") {
514
- await clearFolder(utils.dirname(outName));
1247
+ await utilities.wait(500);
1248
+ if (format !== "commonjs") {
1249
+ await utilities.clearFolder(path.dirname(outName));
515
1250
  }
516
- await writeCompileFile(outName, content);
1251
+ await utilities.writeCompileFile(outName, content);
517
1252
  });
518
- console.timeEnd(tcolor.green("Compiled ESM"));
1253
+ console.timeEnd(tcolor.cyan(`Compiled esm for ${_name} export path`));
1254
+ }
1255
+ async compile() {
1256
+ for (const point of this.object.points) {
1257
+ await utilities.wait(500);
1258
+ switch (point.format) {
1259
+ case "commonjs":
1260
+ await this._commonjs(point);
1261
+ if (this._isUpdate()) {
1262
+ await writePackage(this.files, point.exportPath);
1263
+ }
1264
+ break;
1265
+ case "esm":
1266
+ await this._esm(point);
1267
+ if (this._isUpdate()) {
1268
+ await writePackage(this.files, point.exportPath);
1269
+ }
1270
+ break;
1271
+ case "both":
1272
+ await this._esm(point);
1273
+ await utilities.wait(1000);
1274
+ await this._commonjs(point);
1275
+ if (this._isUpdate()) {
1276
+ await writePackage(this.files, point.exportPath);
1277
+ }
1278
+ break;
1279
+ }
1280
+ await utilities.wait(500);
1281
+ }
519
1282
  }
520
1283
  }
521
- const depsCheck = {
522
- types(deps, compilerOptions) {
1284
+ var checks;
1285
+ (function (checks) {
1286
+ function typesCheck(dep, compilerOptions) {
523
1287
  if (!compilerOptions.noCheck) {
524
- const filePaths = deps.map((i) => i.file);
1288
+ const filePaths = dep.map((i) => i.file);
525
1289
  let _err = false;
526
1290
  const program = ts.createProgram(filePaths, compilerOptions);
527
1291
  for (const filePath of filePaths) {
@@ -552,23 +1316,12 @@ const depsCheck = {
552
1316
  return true;
553
1317
  }
554
1318
  }
555
- },
556
- ext(deps) {
557
- const tsExt = new Set([".ts", ".mts", ".cts", ".tsx"]);
558
- for (const dep of deps) {
559
- const ext = utils.extname(dep.file);
560
- if (!tsExt.has(ext)) {
561
- console.error(tcolor.magenta(`${dep.file} has no valid TypeScript extension`));
562
- ts.sys.exit(1);
563
- }
564
- }
565
- return true;
566
- },
567
- moduleType(deps) {
1319
+ }
1320
+ function moduleType(_dep) {
568
1321
  let _esmCount = 0;
569
1322
  let cjsCount = 0;
570
- let unknowCount = 0;
571
- for (const dep of deps) {
1323
+ let unknownCount = 0;
1324
+ for (const dep of _dep) {
572
1325
  try {
573
1326
  const sourceFile = ts.createSourceFile(dep.file, dep.content, ts.ScriptTarget.Latest, true);
574
1327
  let hasESMImports = false;
@@ -619,10 +1372,10 @@ const depsCheck = {
619
1372
  }
620
1373
  catch (error) {
621
1374
  console.error(tcolor.magenta(`Error checking module format for ${dep.file} : \n ${error}`));
622
- unknowCount++;
1375
+ unknownCount++;
623
1376
  }
624
1377
  }
625
- if (unknowCount) {
1378
+ if (unknownCount) {
626
1379
  console.error(tcolor.magenta("Unknown error when checking module types in the dependencies tree."));
627
1380
  ts.sys.exit(1);
628
1381
  }
@@ -631,126 +1384,29 @@ const depsCheck = {
631
1384
  ts.sys.exit(1);
632
1385
  }
633
1386
  return true;
634
- },
635
- nodeCheck(nodeEnvOption, nodeModules) {
636
- if (!nodeEnvOption && nodeModules.length > 0) {
637
- console.error();
638
- ts.sys.exit(1);
1387
+ }
1388
+ function ext(_dep) {
1389
+ const tsExt = new Set([".ts", ".mts", ".cts", ".tsx"]);
1390
+ for (const dep of _dep) {
1391
+ const ext = path.extname(dep.file);
1392
+ if (!tsExt.has(ext)) {
1393
+ console.error(tcolor.magenta(`${dep.file} has no valid TypeScript extension`));
1394
+ ts.sys.exit(1);
1395
+ }
639
1396
  }
640
1397
  return true;
641
- },
642
- async make(deps, compilerOptions, nodeModules, nodeEnv = true) {
1398
+ }
1399
+ async function init(_dep, options) {
643
1400
  const res = resolves([
644
- [depsCheck.ext, deps],
645
- [depsCheck.nodeCheck, nodeEnv, nodeModules],
646
- [depsCheck.moduleType, deps],
647
- [depsCheck.types, deps, compilerOptions],
1401
+ [ext, _dep],
1402
+ [moduleType, _dep],
1403
+ [typesCheck, _dep, options],
648
1404
  ]);
649
1405
  const results = await res.concurrent();
650
1406
  return results.every((r) => r === true);
651
- },
652
- };
653
- async function getDependencies(entry) {
654
- const deps = await dependencies(entry);
655
- const sorted = deps.sort();
656
- const circularMessages = [];
657
- const nodeModules = deps.node();
658
- const depFiles = [];
659
- await utils.wait(100);
660
- for (const dep of sorted) {
661
- const file = utils.resolvePath(dep);
662
- const content = utils.readFile(file);
663
- depFiles.push({ file, content });
664
- }
665
- const circular = deps
666
- .mutual()
667
- .map((i) => `${i[0]} -> ${i[1]} \n ${i[1]} -> ${i[0]} \n`);
668
- const unknown = deps.warn().map((i) => `${i}\n`);
669
- if (circular.length)
670
- circularMessages.push(circular.join(""));
671
- if (unknown.length)
672
- circularMessages.push(unknown.join(""));
673
- return {
674
- depFiles,
675
- sorted,
676
- circularMessages,
677
- nodeModules,
678
- };
679
- }
680
- const getCompilerOptions = (exportPath, configPath) => {
681
- const config = new TsConfig(configPath);
682
- const generalOptions = () => config.getCompilerOptions();
683
- const commonjs = () => {
684
- const _config = new TsConfig(configPath);
685
- _config.addCompilerOptions({ outDir: "dist" });
686
- _config.removeCompilerOption("rootDir");
687
- _config.removeCompilerOption("module");
688
- const _options = _config.getCompilerOptions();
689
- let out_dir = _options.outDir;
690
- let isMain = true;
691
- if (exportPath !== ".") {
692
- out_dir = `${out_dir}/${exportPath.slice(2)}`;
693
- isMain = false;
694
- }
695
- const { outDir, module, ...restOptions } = _options;
696
- const compilerOptions = {
697
- outDir: out_dir,
698
- module: ts.ModuleKind.CommonJS,
699
- ...restOptions,
700
- };
701
- return {
702
- isMain,
703
- compilerOptions,
704
- out_dir,
705
- };
706
- };
707
- const esm = () => {
708
- const __config = new TsConfig(configPath);
709
- __config.addCompilerOptions({ outDir: "dist" });
710
- __config.removeCompilerOption("rootDir");
711
- const _options = __config.getCompilerOptions();
712
- let out_dir = _options.outDir;
713
- let isMain = true;
714
- if (exportPath !== ".") {
715
- out_dir = `${out_dir}/${exportPath.slice(2)}`;
716
- isMain = false;
717
- }
718
- const { outDir, module, ...restOptions } = _options;
719
- const compilerOptions = {
720
- outDir: out_dir,
721
- module: ts.ModuleKind.ES2022,
722
- ...restOptions,
723
- };
724
- return {
725
- isMain,
726
- compilerOptions,
727
- out_dir,
728
- };
729
- };
730
- return { commonjs, esm, generalOptions };
731
- };
732
- async function entry({ entryPath, exportPath, configPath, nodeEnv, }) {
733
- const deps = await getDependencies(entryPath);
734
- const depFiles = deps.depFiles;
735
- const nodeModules = deps.nodeModules;
736
- await utils.wait(1000);
737
- const opts = getCompilerOptions(exportPath, configPath);
738
- const generalOptions = opts.generalOptions();
739
- const modOpts = {
740
- commonjs: () => opts.commonjs(),
741
- esm: () => opts.esm(),
742
- };
743
- await utils.wait(1000);
744
- const checked = await depsCheck.make(depFiles, generalOptions, nodeModules, nodeEnv);
745
- if (!checked) {
746
- ts.sys.exit(1);
747
1407
  }
748
- return {
749
- depFiles,
750
- modOpts,
751
- generalOptions,
752
- };
753
- }
1408
+ checks.init = init;
1409
+ })(checks || (checks = {}));
754
1410
  const getConfigPath = () => {
755
1411
  const fileNames = ["susee.config.ts", "susee.config.js", "susee.config.mjs"];
756
1412
  let configFile;
@@ -769,18 +1425,18 @@ function checkEntries(entries) {
769
1425
  ts.sys.exit(1);
770
1426
  }
771
1427
  const objectStore = {};
772
- const duplicates = [];
1428
+ const duplicateExportPaths = [];
773
1429
  for (const obj of entries) {
774
1430
  const value = obj.exportPath;
775
1431
  if (objectStore[value]) {
776
- duplicates.push(`"${value}"`);
1432
+ duplicateExportPaths.push(`"${value}"`);
777
1433
  }
778
1434
  else {
779
1435
  objectStore[value] = true;
780
1436
  }
781
1437
  }
782
- if (duplicates.length > 0) {
783
- console.error(tcolor.magenta(`Duplicate export paths/path (${duplicates.join(",")}) found in your susee.config file , that will error for bundled output`));
1438
+ if (duplicateExportPaths.length > 0) {
1439
+ console.error(tcolor.magenta(`Duplicate export paths/path (${duplicateExportPaths.join(",")}) found in your susee.config file , that will error for bundled output`));
784
1440
  ts.sys.exit(1);
785
1441
  }
786
1442
  for (const obj of entries) {
@@ -800,151 +1456,178 @@ async function getConfig() {
800
1456
  const config = _default.default;
801
1457
  const entryCheck = resolves([[checkEntries, config.entryPoints]]);
802
1458
  await entryCheck.series();
803
- await utils.wait(1000);
1459
+ await utilities.wait(1000);
1460
+ const points = [];
1461
+ for (const ent of config.entryPoints) {
1462
+ const point = {
1463
+ entry: ent.entry,
1464
+ exportPath: ent.exportPath,
1465
+ format: ent.format ?? "esm",
1466
+ tsconfigFilePath: ent.tsconfigFilePath ?? undefined,
1467
+ renameDuplicates: ent.renameDuplicates ?? true,
1468
+ outDir: config.outDir ?? "dist",
1469
+ };
1470
+ points.push(point);
1471
+ }
804
1472
  return {
805
- entryPoints: config.entryPoints,
806
- postProcessHooks: config.postProcessHooks ?? [],
1473
+ points,
1474
+ plugins: config.plugins ?? [],
807
1475
  allowUpdatePackageJson: config.allowUpdatePackageJson ?? true,
808
- nodeEnv: config.nodeEnv ?? true,
809
- renameDuplicates: config.renameDuplicates ?? true,
810
1476
  };
811
1477
  }
812
- const isCjs = (files) => files.commonjs && files.commonjsTypes;
813
- const isEsm = (files) => files.esm && files.esmTypes;
814
- function getExports(files, exportPath) {
815
- return isCjs(files) && isEsm(files)
816
- ? {
817
- [exportPath]: {
818
- import: {
819
- default: `./${path.relative(process.cwd(), files.esm)}`,
820
- types: `./${path.relative(process.cwd(), files.esmTypes)}`,
821
- },
822
- require: {
823
- default: `./${path.relative(process.cwd(), files.commonjs)}`,
824
- types: `./${path.relative(process.cwd(), files.commonjsTypes)}`,
825
- },
826
- },
827
- }
828
- : isCjs(files) && !isEsm(files)
829
- ? {
830
- [exportPath]: {
831
- require: {
832
- default: `./${path.relative(process.cwd(), files.commonjs)}`,
833
- types: `./${path.relative(process.cwd(), files.commonjsTypes)}`,
834
- },
835
- },
836
- }
837
- : !isCjs(files) && isEsm(files)
838
- ? {
839
- [exportPath]: {
840
- import: {
841
- default: `./${path.relative(process.cwd(), files.esm)}`,
842
- types: `./${path.relative(process.cwd(), files.esmTypes)}`,
843
- },
844
- },
845
- }
846
- : {};
1478
+ async function fileSizes(path) {
1479
+ const s = await fs.promises.stat(path);
1480
+ const logical = s.size;
1481
+ const allocated = s.blocks !== null ? s.blocks * 512 : null;
1482
+ return { logical, allocated };
847
1483
  }
848
- async function writePackage(files, exportPath) {
849
- let isMain = true;
850
- if (exportPath !== ".") {
851
- isMain = false;
852
- }
853
- const pkgFile = utils.resolvePath("package.json");
854
- const _pkgtext = utils.readFile(pkgFile);
855
- const pkgtext = JSON.parse(_pkgtext);
856
- let { name, version, description, main, module, type, types, exports, ...rest } = pkgtext;
857
- await utils.wait(500);
858
- type = isEsm(files) ? "module" : "commonjs";
859
- let _main = {};
860
- let _module = {};
861
- let _types = {};
862
- let _exports = {};
863
- if (isMain) {
864
- _main = files.main
865
- ? { main: path.relative(process.cwd(), files.main) }
866
- : {};
867
- _module = files.module
868
- ? { module: path.relative(process.cwd(), files.module) }
869
- : {};
870
- _types = files.types
871
- ? { types: path.relative(process.cwd(), files.types) }
872
- : {};
873
- _exports = { exports: { ...getExports(files, exportPath) } };
1484
+ const checkExport = (str, file) => {
1485
+ const esmRex = /export default .*/gm;
1486
+ const cjsRex = /export = .*/gm;
1487
+ const ctsRex = /.cts/g;
1488
+ if (str.match(esmRex) || (str.match(cjsRex) && file.match(ctsRex))) {
1489
+ return true;
874
1490
  }
875
1491
  else {
876
- _main = main ? { main: main } : {};
877
- _module = module ? { module: module } : {};
878
- _types = types ? { types: types } : {};
879
- const normalizedExports = exports && typeof exports === "object" && !Array.isArray(exports)
880
- ? { ...exports }
881
- : {};
882
- _exports = {
883
- exports: { ...normalizedExports, ...getExports(files, exportPath) },
1492
+ return false;
1493
+ }
1494
+ };
1495
+ async function generateDependencies(entryFile, plugins) {
1496
+ const deps = await dependencies(entryFile);
1497
+ const sorted = deps.sort();
1498
+ let depsFiles = [];
1499
+ await utilities.wait(1000);
1500
+ for (const dep of sorted) {
1501
+ const file = ts.sys.resolvePath(dep);
1502
+ const content = await fs.promises.readFile(file, "utf8");
1503
+ const s = await fileSizes(file);
1504
+ const length = content.length;
1505
+ const includeDefExport = checkExport(content, file);
1506
+ const _files = {
1507
+ file,
1508
+ content,
1509
+ length,
1510
+ includeDefExport,
1511
+ size: {
1512
+ logical: s.logical,
1513
+ allocated: s.allocated,
1514
+ utf8: new TextEncoder().encode(content).length,
1515
+ buffBytes: Buffer.byteLength(content, "utf8"),
1516
+ },
884
1517
  };
1518
+ depsFiles.push(_files);
885
1519
  }
886
- await utils.wait(1000);
887
- const pkgJson = {
888
- name,
889
- version,
890
- description,
891
- type,
892
- ..._main,
893
- ..._types,
894
- ..._module,
895
- ..._exports,
896
- ...rest,
897
- };
898
- utils.writeFile(pkgFile, JSON.stringify(pkgJson, null, 2));
1520
+ if (plugins.length) {
1521
+ for (const plugin of plugins) {
1522
+ const _plug = typeof plugin === "function" ? plugin() : plugin;
1523
+ if (_plug.type === "dependency") {
1524
+ if (_plug.async) {
1525
+ depsFiles = await _plug.func(depsFiles);
1526
+ }
1527
+ else {
1528
+ depsFiles = _plug.func(depsFiles);
1529
+ }
1530
+ await utilities.wait(1000);
1531
+ }
1532
+ }
1533
+ }
1534
+ return depsFiles;
899
1535
  }
900
- async function susee() {
901
- const config = await getConfig();
902
- console.info(tcolor.cyan("Start Bundle"));
903
- const compile = async (e) => {
904
- const target = e.moduleType ? e.moduleType : "esm";
905
- const configPath = e.tsconfigFilePath;
906
- const ent = await entry({
907
- entryPath: e.entry,
908
- exportPath: e.exportPath,
909
- configPath: e.tsconfigFilePath,
910
- nodeEnv: config.nodeEnv,
911
- });
912
- const sourceCode = await bundler({
913
- depsFiles: ent.depFiles,
914
- compilerOptions: ent.generalOptions,
915
- renameDuplicates: config.renameDuplicates,
1536
+ class GetOptions {
1537
+ constructor(point) {
1538
+ this._point = point;
1539
+ this._options = {};
1540
+ }
1541
+ __init() {
1542
+ const __opts = new TsConfig(this._point.tsconfigFilePath);
1543
+ const __outDir = this._point.exportPath === "."
1544
+ ? this._point.outDir
1545
+ : `${this._point.outDir}/${this._point.exportPath.slice(2)}`;
1546
+ __opts.removeCompilerOption("rootDir");
1547
+ __opts.removeCompilerOption("module");
1548
+ __opts.editCompilerOptions({
1549
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
1550
+ outDir: __outDir,
916
1551
  });
917
- const mdOpts = ent.modOpts;
918
- const cjsOpts = mdOpts.commonjs();
919
- const esmOpts = mdOpts.esm();
920
- const compiler = new Compilers({ target, configPath });
921
- if (target === "commonjs") {
922
- await compiler.commonjs(sourceCode, e.entry, cjsOpts.compilerOptions, cjsOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
1552
+ this._options = __opts.getCompilerOptions();
1553
+ }
1554
+ __init2() {
1555
+ this.__init();
1556
+ let { types, lib, ...restOptions } = this._options;
1557
+ if (types) {
1558
+ if (!types.includes("node")) {
1559
+ types = ["node", ...types];
1560
+ }
923
1561
  }
924
- else if (target === "esm") {
925
- await compiler.esm(sourceCode, e.entry, esmOpts.compilerOptions, esmOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
1562
+ else {
1563
+ types = ["node"];
926
1564
  }
927
- else if (target === "both") {
928
- await compiler.esm(sourceCode, e.entry, esmOpts.compilerOptions, esmOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
929
- await utils.wait(1000);
930
- await compiler.commonjs(sourceCode, e.entry, cjsOpts.compilerOptions, cjsOpts.isMain, config.postProcessHooks, config.allowUpdatePackageJson);
1565
+ if (lib) {
1566
+ lib = [...new Set(["ESNext", ...lib])];
931
1567
  }
932
- await utils.wait(1000);
933
- if (config.allowUpdatePackageJson) {
934
- await writePackage(compiler.files, e.exportPath);
1568
+ else {
1569
+ lib = ["ESNext"];
935
1570
  }
936
- };
937
- for (const entry of config.entryPoints) {
938
- const entName = entry.exportPath === "." ? "main" : entry.exportPath.slice(2);
939
- await utils.wait(1000);
940
- console.info(tcolor.cyan(`Start ${tcolor.green("->")} "${entName}" export path`));
941
- await compile(entry);
942
- console.info(tcolor.cyan(`End ${tcolor.green("->")} "${entName}" export path`));
943
- if (config.entryPoints.indexOf(entry) + 1 < config.entryPoints.length) {
944
- console.info("-----------------------------------");
1571
+ return { types, lib, ...restOptions };
1572
+ }
1573
+ get commonjs() {
1574
+ const opts = this.__init2();
1575
+ const { module, ...rest } = opts;
1576
+ return { module: ts.ModuleKind.CommonJS, ...rest };
1577
+ }
1578
+ get esm() {
1579
+ const opts = this.__init2();
1580
+ const { module, ...rest } = opts;
1581
+ return { module: ts.ModuleKind.ES2020, ...rest };
1582
+ }
1583
+ get default() {
1584
+ return this.__init2();
1585
+ }
1586
+ }
1587
+ function getOptions(point) {
1588
+ return new GetOptions(point);
1589
+ }
1590
+ async function collections() {
1591
+ const __config = await getConfig();
1592
+ const points = __config.points;
1593
+ const result = [];
1594
+ for (const point of points) {
1595
+ const __opts = getOptions(point);
1596
+ const __deps = await generateDependencies(point.entry, __config.plugins);
1597
+ const checked = await checks.init(__deps, __opts.esm);
1598
+ if (!checked) {
1599
+ ts.sys.exit(1);
945
1600
  }
1601
+ const c = {
1602
+ fileName: point.entry,
1603
+ exportPath: point.exportPath,
1604
+ format: point.format,
1605
+ rename: point.renameDuplicates,
1606
+ outDir: point.outDir,
1607
+ tsOptions: {
1608
+ cjs: __opts.commonjs,
1609
+ esm: __opts.esm,
1610
+ default: __opts.default,
1611
+ },
1612
+ depFiles: __deps,
1613
+ plugins: __config.plugins,
1614
+ };
1615
+ result.push(c);
946
1616
  }
947
- console.info(tcolor.cyan("Finished Bundle"));
1617
+ return {
1618
+ points: result,
1619
+ allowUpdatePackageJson: __config.allowUpdatePackageJson,
1620
+ };
1621
+ }
1622
+ async function susee() {
1623
+ console.info(`${tcolor.green("Start")} : ${tcolor.cyan("bundling")}`);
1624
+ const collected = await collections();
1625
+ await utilities.wait(1000);
1626
+ const bundled = await bundle(collected);
1627
+ await utilities.wait(1000);
1628
+ const compiler = new Compiler(bundled);
1629
+ await compiler.compile();
1630
+ console.info(`${tcolor.green("End")} : ${tcolor.cyan("bundling")}`);
948
1631
  }
949
1632
  export { susee };
950
1633
  //# sourceMappingURL=index.js.map