UNPKG

@sanity/pkg-utils

Version:

Simple utilities for modern npm packages.

115 lines (114 loc) 5.57 kB
import path from "node:path"; import { dts } from "rolldown-plugin-dts"; import { pkgExtMap } from "./resolveBuildContext.js"; function resolveRolldownConfig(ctx, buildTask) { const { format, runtime } = buildTask, { config, cwd, exports: _exports, external, distPath, logger, pkg, ts } = ctx, outputExt = pkgExtMap[pkg.type || "commonjs"][format], outDir = path.relative(cwd, distPath), pathAliases = Object.fromEntries( Object.entries(ts.config?.options.paths || {}).map(([key, val]) => [key, path.resolve(cwd, ts.config?.options.baseUrl || ".", val[0])]) ), entries = buildTask.entries.map((entry) => ({ ...entry, name: path.relative(outDir, entry.output).replace(/\.[^/.]+$/, "") }), {}), exportIds = _exports && Object.keys(_exports).map((exportPath) => path.join(pkg.name, exportPath)), sourcePaths = _exports && Object.values(_exports).map((e) => path.resolve(cwd, e.source)), replacements = Object.fromEntries( Object.entries(config?.define || {}).map(([key, val]) => [key, JSON.stringify(val)]) ), entryFileNames = `[name]${outputExt}`, inputOptions = { cwd, transform: { define: pkg.name === "@sanity/pkg-utils" ? { ...replacements } : { "process.env.PKG_FORMAT": JSON.stringify(format), "process.env.PKG_RUNTIME": JSON.stringify(runtime), "process.env.PKG_VERSION": JSON.stringify(process.env.PKG_VERSION || pkg.version), ...replacements } }, platform: buildTask.type === "rolldown:dts" || runtime === "node" ? "node" : runtime === "browser" ? "browser" : "neutral", resolve: { alias: pathAliases }, tsconfig: ctx.ts.configPath || "tsconfig.json", experimental: { attachDebugInfo: "none" }, external: (id, importer) => { if (buildTask.type === "rolldown:dts" && ctx.bundledPackages.length > 0 && !id.startsWith(".") && (id.includes("/node_modules/") || id.split("/").length < 3)) return !ctx.bundledPackages.some((name) => name === id || id.includes(`/${name}/`)); if (exportIds?.includes(id)) return !0; if (importer && (id.startsWith(".") || id.startsWith("/"))) { const idPath = path.resolve(path.dirname(importer), id); if (sourcePaths?.includes(idPath)) return logger.warn( `detected self-referencing import \u2013 treating as external: ${path.relative( cwd, idPath )}` ), !0; } const idParts = id.split("/"), idPackageName = idParts[0].startsWith("@") ? `${idParts[0]}/${idParts[1]}` : idParts[0]; return external.some( (name) => name === id || name === idPackageName || id.includes(`/node_modules/${name}/`) ); }, input: entries.reduce( (acc, entry) => Object.assign(acc, { [entry.name]: entry.source }), {} ), plugins: [ dts({ emitDtsOnly: !0, tsconfig: ctx.ts.configPath || "tsconfig.json", // When neither the config nor `@typescript/native-preview` decides, leave `tsgo` // undefined so `rolldown-plugin-dts` applies its own default: tsgo is auto-enabled when // the installed `typescript` is v7 (the Go-native compiler), and disabled otherwise tsgo: config?.tsgo !== void 0 ? config.tsgo : typeof pkg.devDependencies == "object" && "@typescript/native-preview" in pkg.devDependencies || void 0, // Always create dts from scratch, don't reuse contexts from previous builds newContext: !0 }) ] // Rely on rolldown's default tree-shaking (`moduleSideEffects: true`) instead of the // equivalent of `moduleSideEffects: 'no-external'`, which stripped intentional // side-effect-only imports of external packages. Unused declarations are still // tree-shaken (that happens at the binding level, independent of `moduleSideEffects`). }, outputOptions = { dir: outDir, entryFileNames, chunkFileNames: buildTask.type === "rolldown:dts" ? `_chunks-dts/[name]${outputExt}` : void 0, esModule: !0, format: buildTask.type === "rolldown:dts" ? "es" : format, sourcemap: buildTask.type === "rolldown:dts" ? !1 : config?.sourcemap ?? !0, hoistTransitiveImports: !1 /** * rolldown doesn't permit disabling chunks, we can only choose between automatic chunking (the default) * and manual chunking (using advancedChunks). * This matters for how we generate dts files. * While we use rolldown for dts generation, and rollup for the rest, we want to reduce the amount of dts files emitted as chunks, * and to make them predictable in how they're generated. */ // @TODO the following breaks the dts generation, report bug to rolldown // advancedChunks: // buildTask.type === 'rolldown:dts' // ? { // groups: [ // { // /** // * Groups all inlined typings specified by bundledPackages in extract.bundledPackages to its own chunk. // */ // name: 'bundled-packages', // test: (id) => ctx.bundledPackages.includes(id), // priority: 1, // }, // { // /** // * Put all other shared chunks into a single chunk. // */ // name: 'shared', // minShareCount: 1, // }, // ], // } // : {}, }; return { inputOptions, outputOptions }; } export { resolveRolldownConfig }; //# sourceMappingURL=resolveRolldownConfig.js.map