@bunup/dts 0.14.43 → 0.14.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +190 -17
  2. package/package.json +1 -2
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ var IMPORT_EXPORT_WITH_DEFAULT_RE = /(import|export)(\s+[^{,]+,)?\s*{([^}]*)}/g;
18
18
  var TYPE_WORD_RE = /\btype\s+/g;
19
19
  var EXPORT_DEFAULT_RE = /\bexport\s+default\s+/g;
20
20
  var EXPORT_RE = /\bexport\s+/g;
21
- var TOKENIZE_RE = /(\s+|\/\/.*?(?:\n|$)|\/\*[\s\S]*?\*\/|[a-zA-Z_$][a-zA-Z0-9_$]*|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|[(){}[\],.;:]|=>|&&|\|\||[=!<>]=?|\+\+|--|[-+*/%&|^!~?]|\.{3}|::|\.)/g;
21
+ var TOKENIZE_RE = /(\s+|\/\/.*?(?:\n|$)|\/\*[\s\S]*?\*\/|import\s*\((?:[^()]*|\([^()]*\))*\)(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\])*|[a-zA-Z_$][a-zA-Z0-9_$]*|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|[(){}[\],.;:]|=>|&&|\|\||[=!<>]=?|\+\+|--|[-+*/%&|^!~?]|\.{3}|::|\.)/g;
22
22
  var CAPITAL_LETTER_RE = /[A-Z]/;
23
23
  var JS_RE = /\.[cm]?jsx?$/;
24
24
  var TS_RE = /\.[cm]?tsx?$|\.d\.[cm]?ts$/;
@@ -318,7 +318,10 @@ async function dtsToFakeJs(dtsContent) {
318
318
  if (isExported) {
319
319
  statementTextWithCommentsAttached = removeExportSyntaxes(statementTextWithCommentsAttached);
320
320
  }
321
- const tokens = tokenizeText(statementTextWithCommentsAttached, referencedNames);
321
+ const { tokens, extras } = tokenizeText(statementTextWithCommentsAttached, referencedNames);
322
+ for (const extra of extras) {
323
+ result.push(extra);
324
+ }
322
325
  result.push(`var ${jsVarName} = [${tokens.join(", ")}];`);
323
326
  if (isExported && !isDefaultExport && !exportedNames.has(jsVarName)) {
324
327
  if (isDefaultExport) {
@@ -342,6 +345,7 @@ function jsifyImportExport(text) {
342
345
  }
343
346
  function tokenizeText(text, referencedNames) {
344
347
  const tokens = [];
348
+ const extras = [];
345
349
  let match;
346
350
  TOKENIZE_RE.lastIndex = 0;
347
351
  while (true) {
@@ -349,13 +353,102 @@ function tokenizeText(text, referencedNames) {
349
353
  if (match === null)
350
354
  break;
351
355
  const token = match[0];
352
- if (isLikelyVariableOrTypeName(token) || referencedNames.has(token)) {
356
+ if (token.startsWith("import(")) {
357
+ const staticImport = convertDynamicImportToStatic(token);
358
+ extras.push(staticImport.declarations);
359
+ tokens.push(staticImport.variableName);
360
+ } else if (isLikelyVariableOrTypeName(token) || referencedNames.has(token)) {
353
361
  tokens.push(token);
354
362
  } else {
355
363
  tokens.push(JSON.stringify(escapeNewlinesAndTabs(token)));
356
364
  }
357
365
  }
358
- return tokens;
366
+ return { tokens, extras };
367
+ }
368
+ function convertDynamicImportToStatic(dynamicImport) {
369
+ const importMatch = dynamicImport.match(/^import\s*\(\s*(['"`])(.+?)\1\s*\)((?:\.[a-zA-Z_$][a-zA-Z0-9_$]*|\[(['"`]).+?\4\])*)$/);
370
+ if (!importMatch) {
371
+ throw new Error("Invalid dynamic import format");
372
+ }
373
+ const modulePath = importMatch[2];
374
+ const propertyAccess = importMatch[3] || "";
375
+ if (!propertyAccess) {
376
+ const importIdentifier = `import_${generateRandomString()}`;
377
+ return {
378
+ declarations: `import * as ${importIdentifier} from '${modulePath}';`,
379
+ variableName: importIdentifier
380
+ };
381
+ }
382
+ const firstProperty = extractFirstProperty(propertyAccess);
383
+ const remainingAccess = propertyAccess.slice(firstProperty.accessLength);
384
+ if (firstProperty.isValidIdentifier) {
385
+ const uniqueName = `${createValidIdentifier(firstProperty.name)}_${generateRandomString()}`;
386
+ let declarations = `import { ${firstProperty.name} as ${uniqueName} } from '${modulePath}';`;
387
+ let finalVariable = uniqueName;
388
+ if (remainingAccess) {
389
+ const lastProperty = extractLastProperty(remainingAccess);
390
+ const varName = `${createValidIdentifier(lastProperty)}_${generateRandomString()}`;
391
+ declarations += `
392
+ var ${varName} = ${uniqueName}${remainingAccess};`;
393
+ finalVariable = varName;
394
+ }
395
+ return {
396
+ declarations,
397
+ variableName: finalVariable
398
+ };
399
+ } else {
400
+ const importIdentifier = `import_${generateRandomString()}`;
401
+ const lastProperty = extractLastProperty(propertyAccess);
402
+ const varName = `${createValidIdentifier(lastProperty)}_${generateRandomString()}`;
403
+ const declarations = `import * as ${importIdentifier} from '${modulePath}';
404
+ var ${varName} = ${importIdentifier}${propertyAccess};`;
405
+ return {
406
+ declarations,
407
+ variableName: varName
408
+ };
409
+ }
410
+ }
411
+ function extractFirstProperty(propertyAccess) {
412
+ const dotMatch = propertyAccess.match(/^\.([a-zA-Z_$][a-zA-Z0-9_$]*)/);
413
+ if (dotMatch) {
414
+ return {
415
+ name: dotMatch[1],
416
+ accessLength: dotMatch[0].length,
417
+ isValidIdentifier: true
418
+ };
419
+ }
420
+ const bracketMatch = propertyAccess.match(/^\[(['"`])(.+?)\1\]/);
421
+ if (bracketMatch) {
422
+ const propName = bracketMatch[2];
423
+ const isValid = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(propName);
424
+ return {
425
+ name: propName,
426
+ accessLength: bracketMatch[0].length,
427
+ isValidIdentifier: isValid
428
+ };
429
+ }
430
+ throw new Error("Invalid property access");
431
+ }
432
+ function extractLastProperty(propertyAccess) {
433
+ const bracketMatch = propertyAccess.match(/\[(['"`])(.+?)\1\]$/);
434
+ if (bracketMatch) {
435
+ return bracketMatch[2];
436
+ }
437
+ const dotMatch = propertyAccess.match(/\.([a-zA-Z_$][a-zA-Z0-9_$]*)$/);
438
+ if (dotMatch) {
439
+ return dotMatch[1];
440
+ }
441
+ return "value";
442
+ }
443
+ function createValidIdentifier(name) {
444
+ let identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
445
+ if (/^\d/.test(identifier)) {
446
+ identifier = `_${identifier}`;
447
+ }
448
+ if (!identifier) {
449
+ identifier = "_value";
450
+ }
451
+ return identifier;
359
452
  }
360
453
  // src/fake/fake-js-to-dts.ts
361
454
  import { parse as parse2 } from "@babel/parser";
@@ -388,6 +481,18 @@ async function fakeJsToDts(fakeJsContent) {
388
481
  }
389
482
  if (statement.type === "VariableDeclaration") {
390
483
  for (const declaration of statement.declarations) {
484
+ if (declaration.id.type === "Identifier") {
485
+ const init = declaration.init;
486
+ if (init?.type === "Identifier") {
487
+ resultParts.push(`type ${declaration.id.name} = ${init.name};`);
488
+ } else if (init?.type === "MemberExpression") {
489
+ const memberExpr = convertMemberExpressionToComputed(init);
490
+ resultParts.push(`type ${declaration.id.name} = ${memberExpr};`);
491
+ } else if (init?.type === "CallExpression") {
492
+ const callExpr = convertCallExpressionToString(init);
493
+ resultParts.push(`type ${declaration.id.name} = ${callExpr};`);
494
+ }
495
+ }
391
496
  if (declaration.init?.type === "ArrayExpression") {
392
497
  const dtsContent = processTokenArray(declaration.init);
393
498
  if (dtsContent) {
@@ -400,6 +505,44 @@ async function fakeJsToDts(fakeJsContent) {
400
505
  return resultParts.join(`
401
506
  `);
402
507
  }
508
+ function convertMemberExpressionToComputed(node) {
509
+ let object = "";
510
+ if (node.object.type === "Identifier") {
511
+ object = node.object.name;
512
+ } else if (node.object.type === "MemberExpression") {
513
+ object = convertMemberExpressionToComputed(node.object);
514
+ }
515
+ let property = "";
516
+ if (node.property.type === "Identifier") {
517
+ property = `'${node.property.name}'`;
518
+ } else if (node.property.type === "StringLiteral") {
519
+ property = `'${node.property.value}'`;
520
+ } else if (node.property.type === "NumericLiteral") {
521
+ property = String(node.property.value);
522
+ }
523
+ return `${object}[${property}]`;
524
+ }
525
+ function convertCallExpressionToString(node) {
526
+ let callee = "";
527
+ if (node.callee.type === "Identifier") {
528
+ callee = node.callee.name;
529
+ } else if (node.callee.type === "MemberExpression") {
530
+ callee = convertMemberExpressionToComputed(node.callee);
531
+ }
532
+ const args = node.arguments.map((arg) => {
533
+ if (arg.type === "Identifier") {
534
+ return arg.name;
535
+ } else if (arg.type === "StringLiteral") {
536
+ return `'${arg.value}'`;
537
+ } else if (arg.type === "NumericLiteral") {
538
+ return String(arg.value);
539
+ } else if (arg.type === "MemberExpression") {
540
+ return convertMemberExpressionToComputed(arg);
541
+ }
542
+ return "";
543
+ }).filter(Boolean).join(", ");
544
+ return `${callee}(${args})`;
545
+ }
403
546
  function processTokenArray(arrayLiteral) {
404
547
  if (arrayLiteral.type !== "ArrayExpression") {
405
548
  return null;
@@ -528,13 +671,15 @@ async function runTypescriptCompiler(root, tsgo, tsconfig) {
528
671
  "--emitDeclarationOnly",
529
672
  "--isolatedDeclarations",
530
673
  "false",
674
+ "--rootDir",
675
+ root,
531
676
  ...tsconfig ? ["-p", tsconfig] : [],
532
677
  "--outDir",
533
678
  dist,
534
- "--rootDir",
535
- root,
536
679
  "--noCheck"
537
- ]);
680
+ ], {
681
+ cwd: root
682
+ });
538
683
  const exitCode = await proc.exited;
539
684
  if (exitCode !== 0) {
540
685
  const stderr = await new Response(proc.stdout).text();
@@ -568,6 +713,10 @@ async function generateDts(entrypoints, options = {}) {
568
713
  if (!filterTypescriptFiles([...resolvedEntrypoints, ...absoluteEntrypoints]).length) {
569
714
  throw new Error("One or more of the entrypoints you provided do not exist. Please check that each entrypoint points to a valid file.");
570
715
  }
716
+ const finalEntryPoints = [
717
+ ...filterTypescriptFiles(resolvedEntrypoints).map((entry) => path2.resolve(path2.join(cwd, entry))),
718
+ ...filterTypescriptFiles(absoluteEntrypoints)
719
+ ];
571
720
  const collectedErrors = [];
572
721
  const resolver = createResolver({
573
722
  cwd,
@@ -645,10 +794,7 @@ async function generateDts(entrypoints, options = {}) {
645
794
  }
646
795
  };
647
796
  const result = await Bun.build({
648
- entrypoints: [
649
- ...filterTypescriptFiles(resolvedEntrypoints).map((entry) => path2.resolve(path2.join(cwd, entry))),
650
- ...filterTypescriptFiles(absoluteEntrypoints)
651
- ],
797
+ entrypoints: finalEntryPoints,
652
798
  format: "esm",
653
799
  target: "node",
654
800
  naming,
@@ -661,7 +807,39 @@ async function generateDts(entrypoints, options = {}) {
661
807
  tsconfig: options.preferredTsconfig ? path2.resolve(cwd, options.preferredTsconfig) : undefined
662
808
  });
663
809
  if (!result.success) {
664
- throw new Error(`DTS bundling failed: ${result.logs}`);
810
+ const logsStr = `${result.logs}`;
811
+ if (logsStr.includes("ENOENT: no such file or directory, open") && logsStr.endsWith(".d.ts'")) {
812
+ let errorMsg = `One or more of your entrypoints are not included in your TypeScript configuration.
813
+
814
+ `;
815
+ if (tsconfig.filepath) {
816
+ errorMsg += `Using: ${path2.relative(cwd, tsconfig.filepath)}
817
+
818
+ `;
819
+ }
820
+ const currentInclude = tsconfig.config?.include;
821
+ if (currentInclude && Array.isArray(currentInclude) && currentInclude.length > 0) {
822
+ errorMsg += `Current "include" patterns:
823
+ `;
824
+ for (const pattern of currentInclude) {
825
+ errorMsg += ` - "${pattern}"
826
+ `;
827
+ }
828
+ errorMsg += `
829
+ Ensure all your entrypoints match these patterns, or add them explicitly.
830
+ `;
831
+ } else {
832
+ errorMsg += `Add an "include" field to your tsconfig.json:
833
+ ` + ` {
834
+ ` + ` "include": ["src/**/*"]
835
+ ` + ` }
836
+
837
+ ` + `Make sure the pattern matches all your entrypoint files.
838
+ `;
839
+ }
840
+ throw new Error(errorMsg);
841
+ }
842
+ throw new Error(logsStr);
665
843
  }
666
844
  const outputs = result.outputs.filter((output) => output.kind === "chunk" || output.kind === "entry-point");
667
845
  const bundledFiles = [];
@@ -675,11 +853,6 @@ async function generateDts(entrypoints, options = {}) {
675
853
  if (!treeshakedDts.code.length && !treeshakedDts.errors.length) {
676
854
  continue;
677
855
  }
678
- if (treeshakedDts.errors.length && !treeshakedDts.code) {
679
- throw new Error(`DTS treeshaking failed for ${entrypoint || outputPath}
680
-
681
- ${JSON.stringify(treeshakedDts.errors, null, 2)}`);
682
- }
683
856
  bundledFiles.push({
684
857
  kind: output.kind === "entry-point" ? "entry-point" : "chunk",
685
858
  entrypoint,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bunup/dts",
3
- "version": "0.14.43",
3
+ "version": "0.14.46",
4
4
  "description": "An extremely fast TypeScript declaration bundler built on Bun's native bundler.",
5
5
  "homepage": "https://github.com/bunup/dts#readme",
6
6
  "bugs": {
@@ -31,7 +31,6 @@
31
31
  "lint": "biome check .",
32
32
  "lint:fix": "biome check --write .",
33
33
  "release": "bumpp --commit --push --tag",
34
- "play": "bun run playground/play.ts",
35
34
  "test": "bun test",
36
35
  "test:coverage": "bun test --coverage",
37
36
  "test:watch": "bun test --watch",