diff --git a/src/analyzer.ts b/src/analyzer.ts index 122a6ae..a582cf3 100644 --- a/src/analyzer.ts +++ b/src/analyzer.ts @@ -23,7 +23,7 @@ export function parseSpecifier(specifier: string): ParsedSpecifier { const ch = specifier.charCodeAt(i); if (ch === CHAR_EXCLAMATION) { lastBang = i; - } else if (ch === CHAR_QUESTION || ch === CHAR_HASH) { + } else if (ch === CHAR_QUESTION || (ch === CHAR_HASH && i !== lastBang + 1)) { suffixStart = i; break; } @@ -139,7 +139,9 @@ export async function buildExportMap( if (isAbsolute(resolvedPath)) { await processLocalExport(exports, node, resolvedPath, specifier, pos, sourceFileCache); - } else { + } else if (!specifier.startsWith("#")) { + // The resolver returns a bare string for external or unresolved imports. + // Without a concrete target, a package-private key cannot be moved safely. processExternalExport(exports, node, specifier, pos); } } @@ -190,7 +192,7 @@ async function processLocalExport( exportStar: !node.exportClause, exportStarIsTypeOnly: !node.exportClause ? node.isTypeOnly : undefined, reExportedNs: namespace, - externalSpecifier: specifier.startsWith(".") ? undefined : specifier, + externalSpecifier: specifier.startsWith(".") || specifier.startsWith("#") ? undefined : specifier, }); } } diff --git a/src/diff.ts b/src/diff.ts index 182772e..0e20413 100644 --- a/src/diff.ts +++ b/src/diff.ts @@ -7,7 +7,7 @@ import { createUnsafeNamespaceDeclaration, } from "./factory.ts"; import { printNode } from "./printer.ts"; -import { buildSpecifier } from "./resolver.ts"; +import { buildRewriteSpecifier } from "./resolver.ts"; import type { RewriteContext } from "./rewriter.ts"; import type { Rewrite } from "./types.ts"; @@ -15,6 +15,7 @@ export interface ExampleCandidate { original: string; targetMap: Map; filePath: string; + singleQuote: boolean; } export function extractImportLine(text: string): string { @@ -38,13 +39,7 @@ export function formatExampleDiff( const unsafeNsIdentifiers: string[] = []; for (const [targetFilePath, rewrite] of targetMap) { - const specifier = - rewrite.externalSpecifier ?? - buildSpecifier(filePath, targetFilePath, { - ext: ctx.ext, - originalSpecifier: rewrite.originalSpecifier, - aliases: ctx.aliases, - }); + const specifier = buildRewriteSpecifier(filePath, targetFilePath, rewrite, ctx); if (rewrite.unsafeNsName) { unsafeNsName = rewrite.unsafeNsName; @@ -54,11 +49,13 @@ export function formatExampleDiff( } if (rewrite.reExportedNs) { - replacements.push(printNode(createNsImportDeclaration(specifier, rewrite.reExportedNs), dummySource)); + replacements.push( + printNode(createNsImportDeclaration(specifier, rewrite.reExportedNs, ctx.singleQuote), dummySource), + ); } else if (rewrite.type === "import") { - replacements.push(printNode(createImportDeclaration(rewrite, specifier), dummySource)); + replacements.push(printNode(createImportDeclaration(rewrite, specifier, ctx.singleQuote), dummySource)); } else { - replacements.push(printNode(createReExportDeclaration(rewrite, specifier), dummySource)); + replacements.push(printNode(createReExportDeclaration(rewrite, specifier, ctx.singleQuote), dummySource)); } } diff --git a/src/main.ts b/src/main.ts index bfe7e40..2afd753 100644 --- a/src/main.ts +++ b/src/main.ts @@ -237,7 +237,10 @@ async function processFiles(files: string[], ctx: Context): Promise { } const exampleDiff = bestExample - ? formatExampleDiff(bestExample.original, bestExample.targetMap, bestExample.filePath, baseRewriteContext) + ? formatExampleDiff(bestExample.original, bestExample.targetMap, bestExample.filePath, { + ...baseRewriteContext, + singleQuote: bestExample.singleQuote, + }) : undefined; return { modified, deleted, preserved, untraceableImports: ctx.tracker.untraceableImports, exampleDiff }; @@ -318,7 +321,7 @@ function pickBestExample( if (targetMap.size > (current?.targetMap.size ?? 0)) { const [start, end] = posKey.split(":").map(Number); const original = extractImportLine(sourceFile.text.slice(start, end)); - return { original, targetMap, filePath }; + return { original, targetMap, filePath, singleQuote: detectSingleQuote(sourceFile) }; } } return current; diff --git a/src/resolver.ts b/src/resolver.ts index 3b981f4..9123446 100644 --- a/src/resolver.ts +++ b/src/resolver.ts @@ -1,9 +1,9 @@ -import { dirname, extname, relative } from "node:path"; +import { basename, dirname, extname, relative } from "node:path"; import { realpathSync } from "node:fs"; import { ResolverFactory } from "oxc-resolver"; import type { NapiResolveOptions } from "oxc-resolver"; import { getExtensionFromSpecifier, tryMapToAlias } from "./config.ts"; -import type { PathAliases } from "./types.ts"; +import type { PathAliases, Rewrite } from "./types.ts"; import { JS_EXT_PATTERN, RESOLVER_EXTENSIONS, TS_EXTENSIONS } from "./constants.ts"; const resolverOptions: NapiResolveOptions = { @@ -86,11 +86,22 @@ export function ensureExtension(path: string, ext: string | null): string { interface SpecifierOptions { ext?: string | null; originalSpecifier?: string; + packageImportSpecifier?: string; + packageTargetSpecifier?: string; aliases?: PathAliases | null; } export function buildSpecifier(from: string, to: string, options: SpecifierOptions = {}): string { - const { ext, originalSpecifier, aliases } = options; + const { ext, originalSpecifier, aliases, packageImportSpecifier, packageTargetSpecifier } = options; + const packageKey = packageImportSpecifier ?? (originalSpecifier?.startsWith("#") ? originalSpecifier : undefined); + if (packageKey) { + const slash = packageKey.lastIndexOf("/"); + const candidates = + slash < 0 ? [packageKey] : [packageKey, packageKey.slice(0, slash + 1) + basename(to, extname(to))]; + for (const candidate of candidates) { + if (resolveModule(from, candidate, aliases ?? null) === to) return candidate; + } + } if (originalSpecifier && aliases) { const aliasSpecifier = tryMapToAlias(to, aliases, originalSpecifier); @@ -117,7 +128,9 @@ export function buildSpecifier(from: string, to: string, options: SpecifierOptio if (ext !== undefined) { finalExt = ext; } else if (originalSpecifier) { - finalExt = getExtensionFromSpecifier(originalSpecifier); + finalExt = + getExtensionFromSpecifier(originalSpecifier) ?? + (packageKey ? (packageTargetSpecifier && getExtensionFromSpecifier(packageTargetSpecifier)) || null : null); } else { finalExt = extname(to) || null; } @@ -127,6 +140,23 @@ export function buildSpecifier(from: string, to: string, options: SpecifierOptio return relPath.startsWith(".") ? relPath : `./${relPath}`; } +export function buildRewriteSpecifier( + from: string, + to: string, + rewrite: Rewrite, + options: Pick, +): string { + const base = + rewrite.externalSpecifier ?? + buildSpecifier(from, to, { + ...options, + originalSpecifier: rewrite.originalSpecifier, + packageImportSpecifier: rewrite.packageImportSpecifier, + packageTargetSpecifier: rewrite.packageTargetSpecifier, + }); + return (rewrite.specifierPrefix ?? "") + base + (rewrite.specifierSuffix ?? ""); +} + function inferAliasSpecifier(originalSpecifier: string, targetPath: string): string | null { const origParts = originalSpecifier.split("/"); const targetParts = targetPath.replace(JS_EXT_PATTERN, "").split("/"); diff --git a/src/rewriter.ts b/src/rewriter.ts index d8e6c89..fe81bfe 100644 --- a/src/rewriter.ts +++ b/src/rewriter.ts @@ -10,7 +10,7 @@ import { import { isBarrel } from "./main.ts"; import { organizeImports } from "./organize.ts"; import { printNode } from "./printer.ts"; -import { buildSpecifier } from "./resolver.ts"; +import { buildRewriteSpecifier } from "./resolver.ts"; import type { Context, ExportData, @@ -45,6 +45,8 @@ export function buildRewriteItem(name: Name, importItem: ImportData, exportItem: reExportedNs: exportItem.reExportedNs, defaultName: isDefault && !isReExport ? (name.alias ?? importItem.name) : undefined, originalSpecifier: importItem.originalSpecifier, + packageTargetSpecifier: importItem.originalSpecifier?.startsWith("#") ? exportItem.specifier : undefined, + packageImportSpecifier: exportItem.specifier.startsWith("#") ? exportItem.specifier : undefined, specifierPrefix: importItem.specifierPrefix, specifierSuffix: importItem.specifierSuffix, }; @@ -74,14 +76,7 @@ export function applyRewrites( const unsafeNsIdentifiers: string[] = []; for (const [targetFilePath, rewrite] of rewriteMap) { - const baseSpecifier = - rewrite.externalSpecifier ?? - buildSpecifier(filePath, targetFilePath, { - ext: ctx.ext, - originalSpecifier: rewrite.originalSpecifier, - aliases: ctx.aliases, - }); - const specifier = (rewrite.specifierPrefix ?? "") + baseSpecifier + (rewrite.specifierSuffix ?? ""); + const specifier = buildRewriteSpecifier(filePath, targetFilePath, rewrite, ctx); if (rewrite.unsafeNsName) { unsafeNsName = rewrite.unsafeNsName; @@ -353,6 +348,7 @@ async function buildUnsafeNamespaceRewrites( members: [], unsafeNsName: item.name, originalSpecifier: item.originalSpecifier, + packageImportSpecifier: exportData.specifier.startsWith("#") ? exportData.specifier : undefined, specifierPrefix: item.specifierPrefix, specifierSuffix: item.specifierSuffix, }); @@ -445,6 +441,7 @@ async function traceStarExports( members: [], isTypeOnly, originalSpecifier: item.originalSpecifier, + packageImportSpecifier: exportData.specifier.startsWith("#") ? exportData.specifier : undefined, specifierPrefix: item.specifierPrefix, specifierSuffix: item.specifierSuffix, }); diff --git a/src/types.ts b/src/types.ts index a8b9ed6..c9c8ceb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -59,6 +59,8 @@ export interface Rewrite { defaultName?: string; isTypeOnly?: boolean; originalSpecifier?: string; + packageImportSpecifier?: string; + packageTargetSpecifier?: string; specifierPrefix?: string; specifierSuffix?: string; unsafeNsName?: string; // For --unsafe-namespace: the namespace identifier name diff --git a/test/integration/package-import-specifiers.test.ts b/test/integration/package-import-specifiers.test.ts new file mode 100644 index 0000000..49b3f02 --- /dev/null +++ b/test/integration/package-import-specifiers.test.ts @@ -0,0 +1,177 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { test, type TestContext } from "node:test"; +import { pathToFileURL } from "node:url"; +import { stripVTControlCharacters } from "node:util"; +import ts from "typescript"; +import { unbarrelify } from "../../src/main.ts"; +import { resolveModule } from "../../src/resolver.ts"; + +async function project(t: TestContext, files: Record): Promise { + const cwd = realpathSync(await mkdtemp(join(tmpdir(), "unbarrelify-package-imports-"))); + t.after(() => rm(cwd, { recursive: true, force: true })); + for (const [path, body] of Object.entries(files)) { + const target = join(cwd, path); + await mkdir(dirname(target), { recursive: true }); + await writeFile(target, body); + } + return cwd; +} + +test("rewrites both consumers of a barrel reached by a TypeScript package import", async (t) => { + const cwd = await project(t, { + "package.json": '{"type":"module","imports":{"#utils":"./src/utils/index.ts"}}', + "tsconfig.json": '{"compilerOptions":{"allowImportingTsExtensions":true,"noEmit":true}}', + "package-consumer.ts": 'import { value } from "#utils";\nexport const result = value;\n', + "relative-consumer.ts": 'import { value } from "./src/utils/index.ts";\nexport const result = value;\n', + "src/utils/index.ts": 'export { value } from "./value.ts";\n', + "src/utils/value.ts": "export const value = 1;\n", + }); + const result = await unbarrelify({ cwd, write: true }); + assert.deepEqual(result.deleted, [join(cwd, "src/utils/index.ts")]); + for (const path of ["package-consumer.ts", "relative-consumer.ts"]) { + assert.match(await readFile(join(cwd, path), "utf8"), /from "\.\/src\/utils\/value\.ts"/); + } +}); + +test("does not copy a package's private star-export key into another package", async (t) => { + const cwd = await project(t, { + "producer/package.json": '{"type":"module","imports":{"#internal":"./value.js"}}', + "producer/barrel.js": 'export * from "#internal";\n', + "producer/value.js": "export const value = 1;\n", + "consumer/package.json": '{"type":"module","imports":{"#internal":"./unrelated.js"}}', + "consumer/unrelated.js": "export const value = 99;\n", + "consumer/input.js": 'import { value } from "../producer/barrel.js";\nexport const result = value;\n', + }); + await unbarrelify({ cwd, write: true }); + const from = join(cwd, "consumer/input.js"); + assert.match(await readFile(from, "utf8"), /from "\.\.\/producer\/value\.js"/); + assert.equal(resolveModule(from, "../producer/value.js", null), join(cwd, "producer/value.js")); + assert.equal((await import(pathToFileURL(from).href)).result, 1); +}); + +test("reuses a wildcard package key only when it resolves to the target in the consumer", async (t) => { + const cwd = await project(t, { + "package.json": '{"type":"module","imports":{"#lib/*":"./src/*.js"}}', + "src/index.js": 'export { value } from "./value.js";\n', + "src/value.js": "export const value = 1;", + "consumer.js": 'import { value } from "#lib/index";\nexport const result = value;\n', + }); + await unbarrelify({ cwd, write: true }); + const from = join(cwd, "consumer.js"); + assert.match(await readFile(from, "utf8"), /from "#lib\/value"/); + assert.equal(resolveModule(from, "#lib/value", null), join(cwd, "src/value.js")); + assert.equal((await import(pathToFileURL(from).href)).result, 1); +}); + +test("keeps the ESM output extension when a TypeScript barrel uses a mapped .js target", async (t) => { + const cwd = await project(t, { + "package.json": '{"type":"module","imports":{"#utils":"./src/utils/index.js"}}', + "tsconfig.json": '{"compilerOptions":{"module":"NodeNext","moduleResolution":"NodeNext"}}', + "consumer.ts": "import { value } from '#utils';\nexport const result = value;\n", + "src/utils/index.ts": 'export { value } from "./value.js";\n', + "src/utils/value.ts": "export const value = 1;\n", + }); + const dry = await unbarrelify({ cwd, write: false }); + const written = await unbarrelify({ cwd, write: true }); + const actual = await readFile(join(cwd, "consumer.ts"), "utf8"); + assert.match(actual, /from '\.\/src\/utils\/value\.js'/); + assert.deepEqual(dry.modified, written.modified); + assert.ok( + stripVTControlCharacters(dry.exampleDiff ?? "") + .split("\n") + .includes("+ " + actual.split("\n")[0]), + ); +}); + +test("keeps a barrel used by a dynamic package import while rewriting a named consumer", async (t) => { + const cwd = await project(t, { + "package.json": '{"type":"module","imports":{"#utils":"./src/utils/index.js"}}', + "consumer.js": 'import { value } from "#utils";\nexport const result = value;\n', + "dynamic.js": 'export const load = () => import("#utils");\n', + "src/utils/index.js": 'export { value } from "./value.js";\n', + "src/utils/value.js": "export const value = 1;\n", + }); + const result = await unbarrelify({ cwd, write: true }); + assert.deepEqual(result.deleted, []); + assert.deepEqual(result.preserved, [ + { path: join(cwd, "src/utils/index.js"), reason: "dynamic-import", consumers: [join(cwd, "dynamic.js")] }, + ]); + assert.match(await readFile(join(cwd, "consumer.js"), "utf8"), /from "\.\/src\/utils\/value\.js"/); + assert.equal(await readFile(join(cwd, "dynamic.js"), "utf8"), 'export const load = () => import("#utils");\n'); +}); + +function assertBundlerTypeChecks(cwd: string, files: string[]): void { + const program = ts.createProgram( + files.map((file) => join(cwd, file)), + { + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + types: [], + noEmit: true, + allowImportingTsExtensions: false, + skipLibCheck: true, + }, + ); + assert.deepEqual( + ts.getPreEmitDiagnostics(program).map((d) => [d.code, ts.flattenDiagnosticMessageText(d.messageText, "\n")]), + [], + ); +} + +test("keeps extensionless TypeScript paths for both direct and cross-package consumers", async (t) => { + const cwd = await project(t, { + "app/package.json": '{"type":"module","imports":{"#utils":"./src/barrel.ts"}}', + "app/input.ts": + 'import { value } from "#utils";\nimport { shared } from "../lib/src/barrel";\nexport const result = value + shared;\n', + "app/src/barrel.ts": 'export { value } from "./value";\n', + "app/src/value.ts": "export const value = 1;", + "lib/package.json": '{"type":"module","imports":{"#internal":"./src/internal.ts"}}', + "lib/src/barrel.ts": 'export * from "#internal";\n', + "lib/src/internal.ts": "export const shared = 2;", + }); + assertBundlerTypeChecks(cwd, ["app/input.ts"]); + const result = await unbarrelify({ cwd, write: true }); + assert.deepEqual(result.deleted.sort(), [join(cwd, "app/src/barrel.ts"), join(cwd, "lib/src/barrel.ts")]); + const text = await readFile(join(cwd, "app/input.ts"), "utf8"); + assert.match(text, /from "\.\/src\/value"/); + assert.match(text, /from "\.\.\/lib\/src\/internal"/); + assertBundlerTypeChecks(cwd, ["app/input.ts"]); +}); + +test("reuses the barrel's own private star export for a consumer in the same package", async (t) => { + const cwd = await project(t, { + "package.json": '{"type":"module","imports":{"#internal":"./src/internal.js"}}', + "src/barrel.js": 'export * from "#internal";\n', + "src/internal.js": "export const value = 1;", + "consumer.js": 'import { value } from "./src/barrel.js";\nexport const result = value;\n', + }); + const result = await unbarrelify({ cwd, write: true }); + assert.deepEqual(result.deleted, [join(cwd, "src/barrel.js")]); + const from = join(cwd, "consumer.js"); + assert.match(await readFile(from, "utf8"), /from "#internal"/); + assert.equal((await import(pathToFileURL(from).href)).result, 1); +}); + +test("does not copy a package-private dependency key that resolves to a different package in the consumer", async (t) => { + const cwd = await project(t, { + "lib/package.json": '{"type":"module","imports":{"#dep":"original-dep"}}', + "lib/node_modules/original-dep/package.json": '{"name":"original-dep","type":"module","exports":"./index.js"}', + "lib/node_modules/original-dep/index.js": "export const value = 1;", + "lib/barrel.js": 'export { value } from "#dep";\n', + "app/package.json": '{"type":"module","imports":{"#dep":"./unrelated.js"}}', + "app/unrelated.js": "export const value = 99;", + "app/consumer.js": 'import { value } from "../lib/barrel.js";\nexport const result = value;\n', + }); + const result = await unbarrelify({ cwd, write: true }); + assert.deepEqual(result.deleted, []); + assert.deepEqual(result.preserved, [ + { path: join(cwd, "lib/barrel.js"), reason: "untraceable-import", consumers: [join(cwd, "app/consumer.js")] }, + ]); + const from = join(cwd, "app/consumer.js"); + assert.match(await readFile(from, "utf8"), /from "\.\.\/lib\/barrel\.js"/); + assert.equal((await import(pathToFileURL(from).href)).result, 1); +});