@sanity/pkg-utils 12.3.3 → 13.0.0
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/MIGRATE.md +1 -1
- package/README.md +2 -2
- package/dist/{buildAction-BPF82HZg.js → buildAction-kavz9FnJ.js} +5 -5
- package/dist/buildAction-kavz9FnJ.js.map +1 -0
- package/dist/{checkAction-DWSqzrZd.js → checkAction-BSYijAy1.js} +4 -4
- package/dist/{checkAction-DWSqzrZd.js.map → checkAction-BSYijAy1.js.map} +1 -1
- package/dist/cli.js +5 -5
- package/dist/index.d.ts +9 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/{resolveBuildContext-vVTRkIDl.js → resolveBuildContext-i4HOnPda.js} +4 -4
- package/dist/resolveBuildContext-i4HOnPda.js.map +1 -0
- package/dist/{resolveTsdownConfig-C6jUZqvp.js → resolveTsdownConfig-orfQXkE6.js} +14 -22
- package/dist/{resolveTsdownConfig-C6jUZqvp.js.map → resolveTsdownConfig-orfQXkE6.js.map} +1 -1
- package/dist/{watchAction-IMdjLKl4.js → watchAction-CIMqTWfx.js} +23 -18
- package/dist/watchAction-CIMqTWfx.js.map +1 -0
- package/dist/{watchConfigFiles-AGBDblwf.js → watchConfigFiles-Bt03CSXT.js} +5 -11
- package/dist/watchConfigFiles-Bt03CSXT.js.map +1 -0
- package/dist/{writeBundleCssExports-BO8zfc4U.js → writeBundleCssExports-CW1Lc_p6.js} +2 -2
- package/dist/{writeBundleCssExports-BO8zfc4U.js.map → writeBundleCssExports-CW1Lc_p6.js.map} +1 -1
- package/package.json +10 -9
- package/dist/buildAction-BPF82HZg.js.map +0 -1
- package/dist/resolveBuildContext-vVTRkIDl.js.map +0 -1
- package/dist/watchAction-IMdjLKl4.js.map +0 -1
- package/dist/watchConfigFiles-AGBDblwf.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveBuildContext-i4HOnPda.js","names":["typoMap","extMap","isTruthy","resolvePath"],"sources":["../src/node/core/config/findConfigFile.ts","../src/node/core/config/legacyConfig.ts","../src/node/core/config/loadConfig.ts","../src/node/core/pkg/dependencyPlacement.ts","../src/node/core/pkg/helpers.ts","../src/node/core/pkg/validatePkg.ts","../src/node/core/pkg/loadPkg.ts","../src/node/core/pkg/loadPkgWithReporting.ts","../src/node/core/config/resolveConfigProperty.ts","../src/node/core/defaults.ts","../src/node/core/findCommonPath.ts","../src/node/core/pkg/pkgExt.ts","../src/node/core/pkg/validateExports.ts","../src/node/core/pkg/parseAndValidateExports.ts","../src/node/core/ts/loadTSConfig.ts","../src/node/resolveBrowserTarget.ts","../src/node/resolveNodeTarget.ts","../src/node/strict.ts","../src/node/resolveBuildContext.ts"],"sourcesContent":["import path from 'node:path'\nimport findConfig from 'find-config'\nimport {fileExists} from '../../fileExists.ts'\n\nconst CONFIG_FILE_NAMES = [\n 'package.config.ts',\n 'package.config.js',\n 'package.config.cjs',\n 'package.config.mts',\n 'package.config.mjs',\n]\n\n/** @internal */\nexport function findConfigFile(cwd: string): string | undefined {\n const pkgJsonPath = findConfig('package.json', {cwd})\n\n if (!pkgJsonPath) return undefined\n\n const pkgPath = path.dirname(pkgJsonPath)\n\n for (const fileName of CONFIG_FILE_NAMES) {\n const configPath = path.resolve(pkgPath, fileName)\n\n const exists = fileExists(configPath)\n\n if (exists) {\n return configPath\n }\n }\n\n return undefined\n}\n","/**\n * Migration checks for `package.config.ts` options that were removed or deprecated in v12,\n * when `@sanity/pkg-utils` moved from its rollup/rolldown stack onto `tsdown` +\n * `@sanity/tsdown-config`.\n *\n * Removed options are \"tombstoned\": they stay declared on `PkgConfigOptions` (typed `never`,\n * tagged `@deprecated`) so editors surface the migration path, and the checks below throw a\n * runtime error with copy-pasteable migration instructions when they are set anyway — JS\n * configs bypass the types, and the error text is written to be actionable for humans and\n * agents alike.\n *\n * The checks are gated by the `legacyChecks` option, defaulting to on outside production\n * builds (`process.env.NODE_ENV !== 'production'`) so they add no overhead where migration\n * mistakes can no longer surface.\n */\n\nconst MIGRATION_GUIDE_URL =\n 'https://github.com/sanity-io/pkg-utils/blob/main/packages/@sanity/pkg-utils/MIGRATE.md'\n\ninterface LegacyCheck {\n option: string\n migration: string[]\n}\n\nconst tombstones: LegacyCheck[] = [\n {\n option: 'tsgo',\n migration: [\n 'The `dts` option is now passed through to tsdown as-is. Move the flag into it:',\n '',\n ' // package.config.ts',\n ' export default defineConfig({',\n \" dts: {generator: 'tsgo'},\",\n ' })',\n ],\n },\n {\n option: 'extract',\n migration: [\n 'TSDoc/release-tag checking is configured with the top-level `tsdoc` option:',\n '',\n ' // extract: {enabled: false} -> tsdoc: false',\n ' // extract: {rules: {...}} -> tsdoc: {rules: {...}}',\n ' // extract: {customTags: [...]} -> tsdoc: {customTags: [...]}',\n '',\n 'Type inlining (`extract.bundledPackages`) follows the bundling decisions now:',\n 'devDependencies that are imported are inlined automatically (types included), and',\n '`deps: {alwaysBundle: [...]}` forces inlining a dependency/peerDependency.',\n '',\n '`extract.checkTypes` has no successor: type generation no longer type-checks',\n '(run `tsc --noEmit` for type checking).',\n ],\n },\n {\n option: 'babel',\n migration: [\n 'The Babel options moved to the top level:',\n '',\n ' // babel: {reactCompiler: true} -> reactCompiler: true',\n ' // babel: {styledComponents: true} -> styledComponents: true',\n '',\n '`styledComponents` now uses oxc\\u2019s native port of `babel-plugin-styled-components`,',\n 'so `babel-plugin-styled-components` can be uninstalled.',\n '',\n 'Custom Babel plugins (`babel.plugins`) run through the `plugins` option instead,',\n 'with a self-installed `@rolldown/plugin-babel`:',\n '',\n ' import pluginBabel from \"@rolldown/plugin-babel\"',\n ' export default defineConfig({',\n ' plugins: [await pluginBabel({plugins: [\"babel-plugin-example\"]})],',\n ' })',\n ],\n },\n {\n option: 'rollup',\n migration: [\n 'The rollup stack was replaced with tsdown:',\n '',\n ' // rollup: {vanillaExtract: true} -> vanillaExtract: true',\n ' // rollup: {plugins: [...]} -> plugins: [...] (rolldown plugins; most',\n ' // Rollup plugins are compatible)',\n '',\n '`rollup.output`, `rollup.treeshake`, `rollup.experimentalLogSideEffects` and',\n '`rollup.hashChunkFileNames` have no successor (chunk filenames are content-hashed now).',\n '',\n '`rollup.optimizeLodash` has no successor either \\u2014 and neither does the implicit',\n 'lodash-import optimization that was applied whenever `lodash` was a dependency.',\n 'Preferably drop lodash altogether (see https://e18e.dev for module replacements like',\n '`es-toolkit`), or import from `lodash-es`, which tree-shakes in consumers without',\n 'build-time rewriting.',\n ],\n },\n {\n option: 'reactCompilerOptions',\n migration: [\n 'Pass the compiler options to `reactCompiler` instead:',\n '',\n ' // babel: {reactCompiler: true}, reactCompilerOptions: {target: \"18\"}',\n ' // becomes:',\n ' reactCompiler: {target: \"18\"}',\n ],\n },\n {\n option: 'jsx',\n migration: [\n 'Configure JSX through `tsconfig.json` \\u2014 the bundler reads it from there:',\n '',\n ' // tsconfig.json',\n ' {\"compilerOptions\": {\"jsx\": \"react-jsx\"}}',\n ],\n },\n {\n option: 'jsxFactory',\n migration: ['Configure JSX through `tsconfig.json` (`compilerOptions.jsxFactory`).'],\n },\n {\n option: 'jsxFragment',\n migration: ['Configure JSX through `tsconfig.json` (`compilerOptions.jsxFragmentFactory`).'],\n },\n {\n option: 'jsxImportSource',\n migration: ['Configure JSX through `tsconfig.json` (`compilerOptions.jsxImportSource`).'],\n },\n]\n\n/**\n * Throws for tombstoned options and warns for grandfathered ones. `config` is the raw loaded\n * config object (before it is narrowed to `PkgConfigOptions`), so removed options are still\n * observable.\n * @internal\n */\nexport function runLegacyConfigChecks(config: Record<string, unknown>): void {\n const legacyChecks =\n typeof config['legacyChecks'] === 'boolean'\n ? config['legacyChecks']\n : process.env['NODE_ENV'] !== 'production'\n\n if (!legacyChecks) return\n\n for (const {option, migration} of tombstones) {\n if (config[option] === undefined) continue\n\n throw new Error(\n [\n `package.config.ts: the \\`${option}\\` option was removed in @sanity/pkg-utils v12.`,\n '',\n ...migration,\n '',\n `Full migration guide: ${MIGRATION_GUIDE_URL}`,\n 'Set `legacyChecks: false` in package.config.ts to skip this validation (it is also',\n 'skipped when NODE_ENV=production).',\n ].join('\\n'),\n )\n }\n\n // `dts` survived, but as a tsdown passthrough object — the old mode strings are tombstoned\n // with value-specific migration instructions.\n const dts = config['dts']\n if (typeof dts === 'string') {\n throw new Error(\n [\n `package.config.ts: \\`dts: '${dts}'\\` was removed in @sanity/pkg-utils v12 — the \\`dts\\``,\n 'option is now passed through to tsdown as-is (an options object, or `false`).',\n '',\n ...(dts === 'rolldown'\n ? [\n \"`dts: 'rolldown'` is the default behavior now: delete the option. Options that\",\n \"accompanied it move into the object, e.g. `dts: {generator: 'tsgo'}`.\",\n ]\n : [\n \"`dts: 'api-extractor'` type generation was removed. Types are generated with\",\n 'tsdown (rolldown-plugin-dts); api-extractor remains as the TSDoc/release-tag',\n 'checking that runs during `pkg build`/`pkg check` — configure it with the',\n '`tsdoc` option.',\n ]),\n '',\n `Full migration guide: ${MIGRATION_GUIDE_URL}`,\n 'Set `legacyChecks: false` in package.config.ts to skip this validation (it is also',\n 'skipped when NODE_ENV=production).',\n ].join('\\n'),\n )\n }\n\n // Grandfathered: `inject: {nodeCompat: true}` still works (it means\n // `{inject: true, exports: {nodeCompat: true}}`), with a nudge toward its successor. The\n // option configures how the CSS file is published, not how the import is injected.\n for (const option of ['vanillaExtract', 'css'] as const) {\n const value = config[option]\n if (typeof value !== 'object' || value === null) continue\n // oxlint-disable-next-line no-unsafe-type-assertion\n const inject = (value as {inject?: unknown}).inject\n if (typeof inject !== 'object' || inject === null) continue\n // oxlint-disable-next-line no-unsafe-type-assertion\n if ((inject as {nodeCompat?: unknown}).nodeCompat === undefined) continue\n // eslint-disable-next-line no-console -- config-load-time deprecation warning\n console.warn(\n [\n `package.config.ts: \\`${option}.inject.nodeCompat\\` is deprecated. Use`,\n `\\`${option}: {inject: true, exports: {nodeCompat: true}}\\` instead — \\`nodeCompat\\``,\n 'configures the package exports, not the injected import.',\n ].join('\\n'),\n )\n }\n\n // Grandfathered: `external` still works (mapped onto tsdown's `deps`), with a nudge toward\n // its successor.\n if (config['external'] !== undefined) {\n // eslint-disable-next-line no-console -- config-load-time deprecation warning\n console.warn(\n [\n 'package.config.ts: `external` is deprecated. Use `deps: {neverBundle: [...]}` to mark',\n 'dependencies as external, and `deps: {alwaysBundle: [...]}` to bundle a dependency',\n '(the callback pattern that filtered entries out of the defaults).',\n ].join('\\n'),\n )\n }\n}\n","import path from 'node:path'\nimport {pathToFileURL} from 'node:url'\nimport {tsImport} from 'tsx/esm/api'\nimport {findConfigFile} from './findConfigFile.ts'\nimport {runLegacyConfigChecks} from './legacyConfig.ts'\nimport type {PkgConfigOptions} from './types.ts'\n\n/** @alpha */\nexport async function loadConfig(options: {\n cwd: string\n pkgPath: string\n}): Promise<PkgConfigOptions | undefined> {\n const {cwd, pkgPath} = options\n\n const root = path.dirname(pkgPath)\n\n const configFile = findConfigFile(root)\n\n if (!configFile) {\n return undefined\n }\n\n // Do not accept config files outside of the root\n if (!configFile.startsWith(cwd)) {\n return undefined\n }\n\n const mod = await tsImport(pathToFileURL(configFile).toString(), import.meta.url)\n\n const config = mod?.default || mod || undefined\n\n if (config && typeof config === 'object') {\n runLegacyConfigChecks(config)\n }\n\n return config\n}\n","import type {PackageJSON} from '@sanity/parse-package-json'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\n\n/**\n * The `package.json` fields a dependency placement rule can reference.\n */\ntype DependencyField = 'dependencies' | 'devDependencies' | 'peerDependencies'\n\n/**\n * Describes where a given package may, and may not, be declared in `package.json`.\n */\ninterface DependencyPlacementRule {\n /** The name of the package this rule applies to. */\n name: string\n /** The `strictOptions` toggle that controls whether this rule runs. */\n option: keyof StrictOptions\n /** Fields the package must _not_ be declared in. */\n disallowedIn: DependencyField[]\n /** Fields the package is allowed to be declared in (used for messaging). */\n allowedIn: DependencyField[]\n /**\n * When set and the package is declared in `peerDependencies`, the version range must be\n * exactly this value (e.g. `*` for `@types/*` packages).\n */\n requiredPeerVersion?: string\n}\n\n/**\n * The set of dependency placement rules enforced in `--strict` mode.\n */\nconst dependencyPlacementRules: DependencyPlacementRule[] = [\n {\n name: 'react-is',\n option: 'noReactIsPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: '@sanity/ui',\n option: 'noSanityUiPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: '@sanity/icons',\n option: 'noSanityIconsPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: 'sanity',\n option: 'noSanityDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: 'styled-components',\n option: 'noStyledComponentsDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: 'react',\n option: 'noReactDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: 'react-dom',\n option: 'noReactDomDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n },\n {\n name: '@types/react',\n option: 'noReactTypesDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n requiredPeerVersion: '*',\n },\n {\n name: '@types/react-dom',\n option: 'noReactDomTypesDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n requiredPeerVersion: '*',\n },\n {\n name: '@types/node',\n option: 'noNodeTypesDependency',\n disallowedIn: ['dependencies'],\n allowedIn: ['devDependencies', 'peerDependencies'],\n requiredPeerVersion: '*',\n },\n {\n name: 'rxjs',\n option: 'noRxjsPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n {\n name: '@sanity/client',\n option: 'noSanityClientPeerDependency',\n disallowedIn: ['peerDependencies'],\n allowedIn: ['dependencies', 'devDependencies'],\n },\n]\n\nfunction formatFields(fields: DependencyField[]): string {\n const labels = fields.map((field) => `\\`${field}\\``)\n\n if (labels.length <= 1) {\n return labels.join('')\n }\n\n return `${labels.slice(0, -1).join(', ')} or ${labels[labels.length - 1]}`\n}\n\n/**\n * Validates that well-known packages are declared in the correct `package.json` dependency\n * fields. Returns `true` if any rule with severity `error` was violated.\n * @internal\n */\nexport function checkDependencyPlacement(options: {\n pkg: PackageJSON\n logger: Logger\n strictOptions: StrictOptions\n}): boolean {\n const {pkg, logger, strictOptions} = options\n let shouldError = false\n\n const report = (level: 'error' | 'warn', message: string) => {\n if (level === 'error') {\n shouldError = true\n logger.error(message)\n } else {\n logger.warn(message)\n }\n }\n\n for (const rule of dependencyPlacementRules) {\n const level = strictOptions[rule.option]\n\n if (level === 'off') {\n continue\n }\n\n for (const field of rule.disallowedIn) {\n if (Object.hasOwn(pkg[field] ?? {}, rule.name)) {\n report(\n level,\n `package.json: \\`${rule.name}\\` should not be in \\`${field}\\`. It should be in ${formatFields(\n rule.allowedIn,\n )} instead.`,\n )\n }\n }\n\n if (rule.requiredPeerVersion !== undefined) {\n const peerDependencies = pkg.peerDependencies ?? {}\n\n if (\n Object.hasOwn(peerDependencies, rule.name) &&\n peerDependencies[rule.name] !== rule.requiredPeerVersion\n ) {\n report(\n level,\n `package.json: \\`${rule.name}\\` in \\`peerDependencies\\` should be set to \"${rule.requiredPeerVersion}\" (got \"${peerDependencies[rule.name]}\").`,\n )\n }\n }\n }\n\n return shouldError\n}\n","/** @internal */\nexport function assertLast<T>(a: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n\n // if not found, then we don't care\n if (aIdx === -1) {\n return true\n }\n\n return aIdx === arr.length - 1\n}\n\n/** @internal */\nexport function assertOrder<T>(a: T, b: T, arr: T[]): boolean {\n const aIdx = arr.indexOf(a)\n const bIdx = arr.indexOf(b)\n\n // if either is not found, then we don't care\n if (aIdx === -1 || bIdx === -1) {\n return true\n }\n\n return aIdx < bIdx\n}\n","import {parsePackage, _typoMap as typoMap, type PackageJSON} from '@sanity/parse-package-json'\n\nexport function validatePkg(input: unknown): PackageJSON {\n const pkg = parsePackage(input)\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- Need to check raw input for typos\n const invalidKey = Object.keys(input as PackageJSON).find((key) => {\n const needle = key.toUpperCase()\n\n return typoMap.has(needle) ? typoMap.get(needle) !== key : false\n })\n\n if (invalidKey) {\n throw new TypeError(\n `\n- package.json: \"${invalidKey}\" is not a valid key. Did you mean \"${typoMap.get(invalidKey.toUpperCase())}\"?`,\n )\n }\n\n return pkg\n}\n","import fs from 'node:fs/promises'\nimport type {PackageJSON} from '@sanity/parse-package-json'\nimport {validatePkg} from './validatePkg.ts'\n\n/** @internal */\nexport async function loadPkg(options: {pkgPath: string}): Promise<PackageJSON> {\n const {pkgPath} = options\n\n const raw = JSON.parse(await fs.readFile(pkgPath, 'utf-8'))\n\n validatePkg(raw)\n\n return raw\n}\n","import {ZodError, type PackageJSON} from '@sanity/parse-package-json'\nimport chalk from 'chalk'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\nimport {checkDependencyPlacement} from './dependencyPlacement.ts'\nimport {assertLast, assertOrder} from './helpers.ts'\nimport {loadPkg} from './loadPkg.ts'\n\n/** The conditions that only resolve before publishing, and are stripped from the publish map. */\nconst devConditions = new Set(['source', 'development', 'monorepo'])\n\n/**\n * A nested runtime condition (`node`, `browser`) may be condensed to a plain string when `default`\n * is the only condition left once the dev-only ones are stripped: the resolver treats\n * `\"node\": \"./dist/index.node.js\"` and `\"node\": {\"default\": \"./dist/index.node.js\"}` identically.\n * This is the same condensation `publishConfig.exports[\"<subpath>\"]` itself allows at entry level.\n */\nfunction condenseExportValue(value: unknown): unknown {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value\n\n const conditions = Object.entries(value).filter(([condition]) => !devConditions.has(condition))\n const [first] = conditions\n\n if (conditions.length === 1 && first?.[0] === 'default' && typeof first[1] === 'string') {\n return first[1]\n }\n\n return value\n}\n\n/**\n * Helper function to recursively compare export values, excluding source, development, and monorepo conditions\n */\nfunction areExportValuesEqual(input1: unknown, input2: unknown): boolean {\n const value1 = condenseExportValue(input1)\n const value2 = condenseExportValue(input2)\n\n // If both are strings, simple comparison\n if (typeof value1 === 'string' && typeof value2 === 'string') {\n return value1 === value2\n }\n\n // If types don't match, they're not equal\n if (typeof value1 !== typeof value2) {\n return false\n }\n\n // Both are objects, compare recursively\n if (\n typeof value1 === 'object' &&\n value1 !== null &&\n typeof value2 === 'object' &&\n value2 !== null &&\n !Array.isArray(value1) &&\n !Array.isArray(value2)\n ) {\n const obj1 = value1 as Record<string, any>\n const obj2 = value2 as Record<string, any>\n\n const keys1 = Object.keys(obj1).filter((k) => !devConditions.has(k))\n const keys2 = Object.keys(obj2).filter((k) => !devConditions.has(k))\n\n // Check if they have the same keys\n if (keys1.length !== keys2.length) {\n return false\n }\n\n for (const key of keys1) {\n if (!keys2.includes(key)) {\n return false\n }\n\n const val1 = obj1[key]\n const val2 = obj2[key]\n\n // Skip if either value is undefined\n if (val1 === undefined || val2 === undefined) {\n return false\n }\n\n // Recursively compare nested values\n if (!areExportValuesEqual(val1, val2)) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n\n/** @alpha */\nexport async function loadPkgWithReporting(options: {\n pkgPath: string\n logger: Logger\n strict: boolean\n strictOptions: StrictOptions\n}): Promise<PackageJSON> {\n const {pkgPath, logger, strict, strictOptions} = options\n\n try {\n const pkg = await loadPkg({pkgPath})\n let shouldError = false\n\n if (strict) {\n // Check for missing or commonjs type field\n if (strictOptions.preferModuleType !== 'off') {\n if (!pkg.type) {\n const msg =\n 'package.json: `type` field is missing. Future versions of pkg-utils will require `\"type\": \"module\"`. Consider adding `\"type\": \"module\"` to prepare for this change.'\n if (strictOptions.preferModuleType === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n } else if (pkg.type === 'commonjs') {\n const msg =\n 'package.json: `type` is set to \"commonjs\". Future versions of pkg-utils will require `\"type\": \"module\"`. Consider migrating to ES modules to prepare for this change.'\n if (strictOptions.preferModuleType === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n }\n\n // Check for banned root-level fields\n if (strictOptions.noPackageJsonBrowser !== 'off' && pkg.browser) {\n const msg =\n 'package.json: the `browser` field is no longer needed. Use the `browser` condition in `exports` instead for better support across modern bundlers.'\n if (strictOptions.noPackageJsonBrowser === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n if (strictOptions.noPackageJsonTypesVersions !== 'off' && pkg.typesVersions) {\n const msg =\n 'package.json: the `typesVersions` field is no longer needed. TypeScript has long supported conditional exports and the `types` condition. Remove the `typesVersions` field and use the `types` condition in `exports` instead.'\n if (strictOptions.noPackageJsonTypesVersions === 'error') {\n shouldError = true\n logger.error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n // Check that well-known packages are declared in the correct dependency fields\n if (checkDependencyPlacement({pkg, logger, strictOptions})) {\n shouldError = true\n }\n }\n\n // validate exports\n if (pkg.exports) {\n const _exports = Object.entries(pkg.exports)\n\n for (const [expPath, exp] of _exports) {\n // Skip plain string exports, svelte exports, and conditional CSS exports (a flat\n // condition -> path map at a `.css` subpath); none of these use standard export conditions.\n if (typeof exp === 'string' || expPath.endsWith('.css') || 'svelte' in exp) {\n continue\n }\n\n const keys = Object.keys(exp)\n\n if (exp.types) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`types\\` condition shouldn't be used as dts files are generated in such a way that both CJS and ESM is supported`,\n )\n }\n\n if (exp.module) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`module\\` condition shouldn't be used as it's not well supported in all bundlers.`,\n )\n }\n\n if (exp.development && exp.source && exp.development !== exp.source) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`development\\` condition must have the same value as \\`source\\` when both are present. Expected \"${exp.source}\" but got \"${exp.development}\"`,\n )\n }\n\n if (exp.monorepo && exp.source && exp.monorepo !== exp.source) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`monorepo\\` condition must have the same value as \\`source\\` when both are present. Expected \"${exp.source}\" but got \"${exp.monorepo}\"`,\n )\n }\n\n if (exp.node) {\n if (exp.import && exp.node.import && !assertOrder('node', 'import', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node\\` property should come before the \\`import\\` property`,\n )\n }\n\n if (exp.node.module) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.module\\` condition shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the \"dual package hazard\"`,\n )\n }\n\n if (\n !exp.node.source &&\n exp.node.import &&\n (exp.node.require || exp.require) &&\n (exp.node.import.endsWith('.cjs.js') || exp.node.import.endsWith('.cjs.mjs'))\n ) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.import\\` re-export pattern shouldn't be used as it's not well supported in all bundlers. A better strategy is to refactor the codebase to no longer be vulnerable to the \"dual package hazard\"`,\n )\n }\n\n if (exp.require && exp.node.require && exp.require === exp.node.require) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node.require\\` property isn't necessary as it's identical to \\`require\\``,\n )\n } else if (exp.require && exp.node.require && !assertOrder('node', 'require', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`node\\` property should come before the \\`require\\` property`,\n )\n }\n } else {\n if (!assertOrder('import', 'require', keys)) {\n logger.warn(\n `exports[\"${expPath}\"]: the \\`import\\` property should come before the \\`require\\` property`,\n )\n }\n }\n\n if (!assertLast('default', keys)) {\n shouldError = true\n logger.error(\n `exports[\"${expPath}\"]: the \\`default\\` property should be the last property`,\n )\n }\n }\n }\n\n // validate publishConfig.exports\n if (strict && pkg.exports && Object.keys(pkg.exports).length > 0) {\n // Check if exports contains source, development, or monorepo conditions\n const hasSourceOrDevelopment = Object.entries(pkg.exports).some(([, exp]) => {\n if (typeof exp === 'string') return false\n if (typeof exp === 'object' && 'svelte' in exp) return false\n return Boolean(exp.source || exp.development || exp.monorepo)\n })\n\n if (hasSourceOrDevelopment) {\n if (!pkg.publishConfig?.exports) {\n const msg =\n 'package.json: `publishConfig.exports` is missing. Adding it helps avoid publishing to npm with the `source`, `development`, or `monorepo` condition that points to code that cannot be used by the resolver. ' +\n 'See https://tsdown.dev/options/package-exports#dev-exports for more information.'\n if (strictOptions.noPublishConfigExports === 'error') {\n shouldError = true\n logger.error(msg)\n } else if (strictOptions.noPublishConfigExports !== 'off') {\n logger.warn(msg)\n }\n } else {\n // Validate publishConfig.exports structure\n const publishExports = pkg.publishConfig.exports\n\n // A `.css` subpath with a `source` is a stylesheet built by the CSS pipeline, which\n // fills the subpath into both maps. Until the first build runs, `exports` holds\n // nothing but the `source` the author wrote and `publishConfig.exports` holds\n // nothing at all — the documented way to declare one — so it is exempt from the\n // cross-map checks below.\n const isBuiltCssExport = (exportPath: string): boolean => {\n if (!exportPath.endsWith('.css')) return false\n const exp = pkg.exports?.[exportPath]\n return typeof exp === 'object' && exp !== null && 'source' in exp\n }\n\n // Check that all keys in exports exist in publishConfig.exports\n for (const exportPath of Object.keys(pkg.exports)) {\n if (!(exportPath in publishExports) && !isBuiltCssExport(exportPath)) {\n shouldError = true\n logger.error(\n `publishConfig.exports: missing export path \"${exportPath}\" that exists in exports`,\n )\n }\n }\n\n // Check that all keys in publishConfig.exports exist in exports\n for (const exportPath of Object.keys(publishExports)) {\n if (!(exportPath in pkg.exports)) {\n shouldError = true\n logger.error(\n `publishConfig.exports: unexpected export path \"${exportPath}\" that does not exist in exports`,\n )\n }\n }\n\n // Validate each export path\n for (const [exportPath, exp] of Object.entries(pkg.exports)) {\n if (isBuiltCssExport(exportPath)) continue\n if (typeof exp === 'string' || 'svelte' in exp) {\n // For string or svelte exports, publishConfig should match\n const publishExp = publishExports[exportPath]\n if (\n typeof publishExp !== 'string' &&\n (typeof publishExp !== 'object' || !('svelte' in publishExp))\n ) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should be a string matching exports[\"${exportPath}\"]`,\n )\n }\n continue\n }\n\n const publishExp = publishExports[exportPath]\n if (!publishExp) {\n continue\n }\n if (typeof publishExp === 'string') {\n // publishConfig has a string, validate it's correct\n // It should be a condensed form when only default remains after removing source/development/monorepo\n const conditions = Object.keys(exp).filter(\n (k) => k !== 'source' && k !== 'development' && k !== 'monorepo',\n )\n if (conditions.length !== 1 || conditions[0] !== 'default') {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: is a string but exports[\"${exportPath}\"] has multiple conditions besides source/development/monorepo: ${conditions.join(', ')}`,\n )\n } else {\n // Validate that the string value matches the default condition value\n const expectedValue = exp.default\n if (publishExp !== expectedValue) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should be \"${expectedValue}\" but got \"${publishExp}\"`,\n )\n }\n }\n continue\n }\n\n if ('svelte' in publishExp) {\n continue\n }\n\n // Validate conditions\n const exportConditions = Object.keys(exp).filter(\n (k) => k !== 'source' && k !== 'development' && k !== 'monorepo',\n )\n const publishConditions = Object.keys(publishExp)\n\n // Check for source, development, or monorepo in publishConfig\n if ('source' in publishExp) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should not contain the \\`source\\` condition`,\n )\n }\n\n if ('development' in publishExp) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should not contain the \\`development\\` condition`,\n )\n }\n\n if ('monorepo' in publishExp) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: should not contain the \\`monorepo\\` condition`,\n )\n }\n\n // Check that all conditions match (except source/development/monorepo)\n for (const condition of exportConditions) {\n if (!(condition in publishExp)) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: missing \\`${condition}\\` condition that exists in exports[\"${exportPath}\"]`,\n )\n }\n }\n\n for (const condition of publishConditions) {\n if (!exportConditions.includes(condition)) {\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"]: unexpected \\`${condition}\\` condition that does not exist in exports[\"${exportPath}\"]`,\n )\n }\n }\n\n // Validate that values match for all conditions\n for (const condition of exportConditions) {\n if (condition in publishExp) {\n const exportValue = (exp as Record<string, unknown>)[condition]\n const publishValue = (publishExp as Record<string, unknown>)[condition]\n\n // Compare values recursively for nested objects\n if (!areExportValuesEqual(exportValue, publishValue)) {\n const exportValueStr =\n typeof exportValue === 'string' ? exportValue : JSON.stringify(exportValue)\n const publishValueStr =\n typeof publishValue === 'string' ? publishValue : JSON.stringify(publishValue)\n shouldError = true\n logger.error(\n `publishConfig.exports[\"${exportPath}\"].${condition}: should be ${exportValueStr} but got ${publishValueStr}`,\n )\n }\n }\n }\n }\n }\n }\n }\n\n if (shouldError) {\n process.exit(1)\n }\n\n return pkg\n } catch (err) {\n if (err instanceof ZodError) {\n for (const issue of err.issues) {\n if (issue.code === 'invalid_type') {\n logger.error(\n [\n `\\`${formatPath(issue.path)}\\` `,\n `in \\`./package.json\\` must be of type ${chalk.magenta(issue.expected)} `,\n `(received ${chalk.magenta(issue.received)})`,\n ].join(''),\n )\n continue\n }\n\n // Every other issue carries its own message: report it against the path it was found at,\n // rather than dumping the raw issue object.\n logger.error(\n issue.path.length\n ? `\\`${formatPath(issue.path)}\\` in \\`./package.json\\` is invalid: ${issue.message}`\n : `\\`./package.json\\` is invalid: ${issue.message}`,\n )\n }\n } else {\n logger.error(err)\n }\n\n return process.exit(1)\n }\n}\n\nfunction formatPath(segments: Array<string | number>) {\n return segments\n .map((s, idx) => {\n if (idx === 0) return s\n\n if (typeof s === 'number') {\n return `[${s}]`\n }\n\n if (s.startsWith('.')) {\n return `[\"${s}\"]`\n }\n\n return `.${s}`\n })\n .join('')\n}\n","import type {PkgConfigProperty, PkgConfigPropertyResolver} from './types.ts'\n\nfunction isPkgConfigPropertyResolver<T>(\n prop: PkgConfigProperty<T>,\n): prop is PkgConfigPropertyResolver<T> {\n return typeof prop === 'function'\n}\n\n/** @internal */\nexport function resolveConfigProperty<T>(\n prop: PkgConfigProperty<T> | undefined,\n initialValue: T,\n): T {\n if (!prop) return initialValue\n\n if (isPkgConfigPropertyResolver(prop)) {\n return prop(initialValue)\n }\n\n return prop\n}\n","import config from '@sanity/browserslist-config'\n\n/** @public */\nexport const DEFAULT_BROWSERSLIST_QUERY: string[] = config\n","import path from 'node:path'\n\nexport function pathContains(containerPath: string, itemPath: string): boolean {\n return !path.relative(containerPath, itemPath).startsWith('..')\n}\n\nexport function findCommonDirPath(filePaths: string[]): string | undefined {\n let ret: string | undefined = undefined\n\n for (const filePath of filePaths) {\n let dirPath = path.dirname(filePath)\n\n if (!ret) {\n ret = dirPath\n continue\n }\n\n while (dirPath !== ret) {\n if (pathContains(dirPath, ret)) {\n ret = dirPath\n break\n }\n\n dirPath = path.dirname(dirPath)\n\n if (dirPath === ret) {\n break\n }\n\n if (dirPath === '.') return undefined\n }\n }\n\n return ret\n}\n","/** Matches the JS output file endings pkg-utils emits (`.js`, `.mjs`, `.cjs`). @internal */\nexport const fileEnding: RegExp = /\\.[mc]?js$/\n/** @internal */\nexport const defaultEnding = '.js'\nconst mjsEnding = '.mjs'\nconst cjsEnding = '.cjs'\n\n/** @internal */\nexport interface PkgExtMap {\n commonjs: {commonjs: string; esm: string}\n module: {commonjs: string; esm: string}\n}\n\n/** @internal */\nexport const pkgExtMap: PkgExtMap = {\n // pkg.type: \"commonjs\"\n commonjs: {\n commonjs: defaultEnding,\n esm: mjsEnding,\n },\n\n // pkg.type: \"module\"\n module: {\n commonjs: cjsEnding,\n esm: defaultEnding,\n },\n}\n","import type {PackageJSON} from '@sanity/parse-package-json'\nimport type {PkgExport} from '../config/types.ts'\nimport {pkgExtMap as extMap} from './pkgExt.ts'\n\nexport function validateExports(\n _exports: (PkgExport & {_path: string})[],\n options: {pkg: PackageJSON},\n): string[] {\n const {pkg} = options\n const type = pkg.type || 'commonjs'\n const ext = extMap[type]\n\n const errors: string[] = []\n\n for (const exp of _exports) {\n if (exp._path === '.') {\n if (exp.require && pkg.main && exp.require !== pkg.main) {\n errors.push(\n 'package.json: mismatch between \"main\" and \"exports.require\". These must be equal.',\n )\n }\n\n if (exp.import && pkg.module && exp.import !== pkg.module) {\n errors.push(\n 'package.json: mismatch between \"module\" and \"exports.import\". These must be equal.',\n )\n }\n }\n if (exp.require && !exp.require.endsWith(ext.commonjs)) {\n errors.push(\n `package.json with \\`type: \"${type}\"\\` - \\`exports[\"${exp._path}\"].require\\` must end with \"${ext.commonjs}\"`,\n )\n }\n\n if (exp.import && !exp.import.endsWith(ext.esm)) {\n errors.push(\n `package.json with \\`type: \"${type}\"\\` - \\`exports[\"${exp._path}\"].import\\` must end with \"${ext.esm}\"`,\n )\n }\n }\n\n return errors\n}\n","import {existsSync} from 'node:fs'\nimport {resolve as resolvePath} from 'node:path'\nimport {parseExports, type PackageJSON} from '@sanity/parse-package-json'\nimport type {Logger} from '../../logger.ts'\nimport type {StrictOptions} from '../../strict.ts'\nimport type {PkgExport} from '../config/types.ts'\nimport {isRecord} from '../isRecord.ts'\nimport {defaultEnding, fileEnding, pkgExtMap} from './pkgExt.ts'\nimport {validateExports} from './validateExports.ts'\n\n// Type guard to filter out falsy values\nfunction isTruthy<T>(value: T | false | null | undefined | 0 | ''): value is T {\n return Boolean(value)\n}\n\n/** @alpha */\nexport function parseAndValidateExports(options: {\n cwd: string\n pkg: PackageJSON\n strict: boolean\n strictOptions: StrictOptions\n logger: Logger\n}): (PkgExport & {_path: string})[] {\n const {cwd, pkg, strict, strictOptions, logger} = options\n const type = pkg.type || 'commonjs'\n const errors: string[] = []\n\n const report = (kind: 'warn' | 'error', message: string) => {\n if (kind === 'warn') {\n logger.warn(message)\n } else {\n errors.push(message)\n }\n }\n\n if (!Array.isArray(pkg.files) && strict && strictOptions.alwaysPackageJsonFiles !== 'off') {\n report(\n strictOptions.alwaysPackageJsonFiles,\n 'package.json: `files` should be used over `.npmignore`',\n )\n }\n\n if (pkg.source) {\n if (\n strict &&\n pkg.exports?.['.'] &&\n typeof pkg.exports['.'] === 'object' &&\n 'source' in pkg.exports['.'] &&\n pkg.exports['.'].source === pkg.source\n ) {\n errors.push(\n 'package.json: the \"source\" property can be removed, as it is equal to exports[\".\"].source.',\n )\n } else if (!pkg.exports && pkg.main) {\n const extMap = pkgExtMap[type]\n const importExport = pkg.main.replace(fileEnding, extMap.esm)\n const requireExport = pkg.main.replace(fileEnding, extMap.commonjs)\n const defaultExport = pkg.main.replace(fileEnding, defaultEnding)\n\n const maybeBrowserCondition = []\n\n if (pkg.browser) {\n const browserConditions = []\n\n if (pkg.module && pkg.browser?.[pkg.module]) {\n browserConditions.push(\n ` \"import\": ${JSON.stringify(pkg.browser[pkg.module]!.replace(fileEnding, extMap.esm))}`,\n )\n } else if (pkg.browser?.[pkg.main]) {\n browserConditions.push(\n ` \"import\": ${JSON.stringify(pkg.browser[pkg.main]!.replace(fileEnding, extMap.esm))}`,\n )\n }\n\n if (pkg.browser?.[pkg.main]) {\n browserConditions.push(\n ` \"require\": ${JSON.stringify(pkg.browser[pkg.main]!.replace(fileEnding, extMap.commonjs))}`,\n )\n }\n\n if (browserConditions.length) {\n maybeBrowserCondition.push(\n ` \"browser\": {`,\n ` \"source\": ${JSON.stringify(pkg.browser?.[pkg.source] || pkg.source)},`,\n ...browserConditions,\n ` }`,\n )\n }\n }\n\n errors.push(\n ...[\n 'package.json: `exports` are missing, it should be:',\n `\"exports\": {`,\n ` \".\": {`,\n ` \"source\": ${JSON.stringify(pkg.source)},`,\n // If browser conditions are detected then add them to the suggestion\n ...(maybeBrowserCondition.length > 0 ? maybeBrowserCondition : []),\n type === 'commonjs' && ` \"import\": ${JSON.stringify(importExport)},`,\n type === 'module' && ` \"require\": ${JSON.stringify(requireExport)},`,\n ` \"default\": ${JSON.stringify(defaultExport)}`,\n ` },`,\n ` \"./package.json\": \"./package.json\"`,\n `}`,\n ].filter(isTruthy),\n )\n }\n }\n\n if (errors.length) {\n throw new Error('\\n- ' + errors.join('\\n- '))\n }\n\n if (!pkg.exports) {\n throw new Error(\n '\\n- ' +\n [\n 'package.json: `exports` are missing, please set a minimal configuration, for example:',\n `\"exports\": {`,\n ` \".\": {`,\n ` \"source\": \"./src/index.js\",`,\n ` \"default\": \"./dist/index.js\"`,\n ` },`,\n ` \"./package.json\": \"./package.json\"`,\n `}`,\n ].join('\\n- '),\n )\n }\n\n const _exports = parseExports({pkg})\n\n if (strict && strictOptions.noPackageJsonTypings !== 'off' && 'typings' in pkg) {\n report(strictOptions.noPackageJsonTypings, 'package.json: `typings` should be `types`')\n }\n\n if (\n strict &&\n strictOptions.alwaysPackageJsonTypes !== 'off' &&\n !pkg.types &&\n typeof pkg.exports?.['.'] === 'object' &&\n 'source' in pkg.exports['.'] &&\n pkg.exports['.'].source?.endsWith('.ts')\n ) {\n report(\n strictOptions.alwaysPackageJsonTypes,\n 'package.json: `types` must be declared for the npm listing to show as a TypeScript module.',\n )\n }\n\n if (strict && !pkg.exports['./package.json']) {\n errors.push('package.json: `exports[\"./package.json\"] must be declared.')\n }\n\n for (const [exportPath, exportEntry] of Object.entries(pkg.exports)) {\n if (\n exportPath.endsWith('.json') ||\n (typeof exportEntry === 'string' && exportEntry.endsWith('.json'))\n ) {\n if (exportPath === './package.json') {\n if (exportEntry !== './package.json') {\n errors.push('package.json: `exports[\"./package.json\"]` must be \"./package.json\".')\n }\n }\n } else if (exportPath.endsWith('.css')) {\n if (typeof exportEntry === 'string') {\n if (!existsSync(resolvePath(cwd, exportEntry))) {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: file does not exist.`,\n )\n }\n } else if (isRecord(exportEntry)) {\n // Conditional CSS export, e.g.\n // \"./bundle.css\": { \"types\": \"./dist/bundle-css.d.ts\", \"browser\": \"./dist/bundle.css\", \"node\": \"./dist/bundle-css.js\", \"default\": \"./dist/bundle-css.js\" }\n // This lets a package re-add a `import \"<pkg>/bundle.css\"` that resolves to the real CSS in\n // bundler/browser environments and to a no-op JS shim in CSS-unaware runtimes (e.g. Node).\n // Only the shape is validated here: the targets usually point at generated `dist` files that\n // do not exist yet at validation time, so file existence is intentionally not checked.\n for (const [condition, target] of Object.entries(exportEntry)) {\n if (typeof target !== 'string') {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}][${JSON.stringify(condition)}]\\`: must be a string path.`,\n )\n continue\n }\n // With a `source`, the subpath is a build entry: the stylesheet is compiled by the\n // CSS pipeline, so unlike the generated conditions the source has to exist now.\n if (condition === 'source' && !existsSync(resolvePath(cwd, target))) {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}].source\\`: file does not exist.`,\n )\n }\n }\n } else {\n errors.push(\n `package.json: \\`exports[${JSON.stringify(exportPath)}]\\`: must be a string path or an object of export conditions.`,\n )\n }\n } else if (isRecord(exportEntry) && 'svelte' in exportEntry) {\n // @TODO should we report a warning or a debug message here about a detected svelte export that is ignored?\n } else if (isPkgExport(exportEntry)) {\n const exp = {\n _exported: true,\n _path: exportPath,\n ...exportEntry,\n } satisfies PkgExport & {_path: string}\n\n // Infer the `default` condition based on the `type` and other conditions\n if (!exp.default) {\n const fallback = type === 'module' ? exp.import : exp.require\n\n if (fallback) {\n exp.default = fallback\n }\n }\n\n // Infer the `require` condition based on the `type` and other conditions\n if (!exp.require && type === 'commonjs' && exp.default) {\n exp.require = exp.default\n }\n\n // Infer the `import` condition based on the `type` and other conditions\n if (!exp.import && type === 'module' && exp.default) {\n exp.import = exp.default\n }\n\n if (exportPath === '.') {\n if (exportEntry.require && pkg.main && exportEntry.require !== pkg.main) {\n errors.push(\n 'package.json: mismatch between \"main\" and \"exports.require\". These must be equal.',\n )\n }\n\n if (exportEntry.import && pkg.module && exportEntry.import !== pkg.module) {\n errors.push(\n 'package.json: mismatch between \"module\" and \"exports.import\" These must be equal.',\n )\n }\n }\n } else if (!isRecord(exportEntry)) {\n errors.push('package.json: exports must be an object')\n }\n }\n\n errors.push(...validateExports(_exports, {pkg}))\n\n if (errors.length) {\n throw new Error('\\n- ' + errors.join('\\n- '))\n }\n\n return _exports\n}\n\nfunction isPkgExport(value: unknown): value is PkgExport {\n return isRecord(value) && 'source' in value && typeof value['source'] === 'string'\n}\n","// The JS compiler API is loaded from the official `@typescript/typescript6` compat package\n// instead of the `typescript` peer dependency, as TypeScript 7 (the Go-native compiler) no longer\n// ships it\nimport ts from '@typescript/typescript6'\n\n/** @internal */\nexport async function loadTSConfig(options: {\n cwd: string\n tsconfigPath: string\n}): Promise<ReturnType<typeof ts.parseJsonConfigFileContent> | undefined> {\n const {cwd, tsconfigPath} = options\n\n // oxlint-disable-next-line unbound-method\n const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, tsconfigPath)\n\n if (!configPath) {\n return undefined\n }\n\n // oxlint-disable-next-line unbound-method\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile)\n\n return ts.parseJsonConfigFileContent(configFile.config, ts.sys, cwd)\n}\n","export function resolveBrowserTarget(versions: string[]): string[] | undefined {\n const target: string[] = versions.filter(\n (version) =>\n version.startsWith('chrome') ||\n version.startsWith('edge') ||\n version.startsWith('firefox') ||\n version.startsWith('ios') ||\n version.startsWith('safari') ||\n version.startsWith('opera'),\n )\n\n if (target.length === 0) {\n return undefined\n }\n\n return target\n}\n","export function resolveNodeTarget(versions: string[]): string[] | undefined {\n const target: string[] = versions.filter((version) => version.startsWith('node'))\n\n if (target.length === 0) {\n return undefined\n }\n\n return target\n}\n","import {errorMap} from 'zod-validation-error/v3'\nimport {z} from 'zod/v3'\n\nconst toggle = z.union([z.literal('error'), z.literal('warn'), z.literal('off')])\n\ntype ToggleType = 'error' | 'warn' | 'off'\n\nconst strictOptions = z\n .object({\n noPackageJsonTypings: toggle.default('error'),\n noImplicitSideEffects: toggle.default('warn'),\n noImplicitBrowsersList: toggle.default('warn'),\n alwaysPackageJsonTypes: toggle.default('error'),\n alwaysPackageJsonFiles: toggle.default('error'),\n noCheckTypes: toggle.default('warn'),\n noPackageJsonBrowser: toggle.default('warn'),\n noPackageJsonTypesVersions: toggle.default('warn'),\n preferModuleType: toggle.default('warn'),\n noPublishConfigExports: toggle.default('warn'),\n noReactIsPeerDependency: toggle.default('error'),\n noSanityUiPeerDependency: toggle.default('error'),\n noSanityIconsPeerDependency: toggle.default('error'),\n noSanityDependency: toggle.default('error'),\n noStyledComponentsDependency: toggle.default('error'),\n noReactDependency: toggle.default('error'),\n noReactDomDependency: toggle.default('error'),\n noReactTypesDependency: toggle.default('error'),\n noReactDomTypesDependency: toggle.default('error'),\n noNodeTypesDependency: toggle.default('error'),\n noRxjsPeerDependency: toggle.default('error'),\n noSanityClientPeerDependency: toggle.default('error'),\n })\n .strict()\n\n/**\n * To make error message paths line up with the paths in package.config.ts the schema is hoisted into a root schema\n * This way errors will say `Expected boolean, received string at \"strict.noPackageJsonTypings\"` instead of `Expected boolean, received string at \"noPackageJsonTypings\"`.\n */\nconst validationSchema = z.object({\n strictOptions: strictOptions.default({}),\n})\n\n/**\n * @public\n */\nexport interface StrictOptions {\n /**\n * Disallows a top level `typings` field in `package.json` if it is equal to `exports['.'].source`.\n * @defaultValue 'error'\n */\n noPackageJsonTypings: ToggleType\n /**\n * Requires specifying `sideEffects` in `package.json`.\n * @defaultValue 'warn'\n */\n noImplicitSideEffects: ToggleType\n /**\n * Requires specifying `browserslist` in `package.json`, instead of relying on it implicitly being:\n * @example\n * ```\n * \"browserslist\": \"extends @sanity/browserslist-config\"\n * ```\n * @defaultValue 'warn'\n */\n noImplicitBrowsersList: ToggleType\n /**\n * If typescript is used then `types` in `package.json` should be specified for npm listings to show the TS icon.\n * @defaultValue 'error'\n */\n alwaysPackageJsonTypes: ToggleType\n /**\n * Using `.npmignore` is error prone, it's best practice to always declare `files` instead\n * @defaultValue 'error'\n */\n alwaysPackageJsonFiles: ToggleType\n /**\n * It's slow to perform type checking while generating dts files, so it's best practice to disable it with a `\"noCheck\": true` in the tsconfig.json file used by `package.config.ts`\n * @defaultValue 'warn'\n */\n noCheckTypes: ToggleType\n /**\n * Disallows the `browser` field in `package.json` as the `browser` condition in `exports` is better supported.\n * @defaultValue 'warn'\n */\n noPackageJsonBrowser: ToggleType\n /**\n * Disallows the `typesVersions` field in `package.json` as TypeScript has long supported conditional exports and the `types` condition.\n * @defaultValue 'warn'\n */\n noPackageJsonTypesVersions: ToggleType\n /**\n * Warns if `type` field is missing or set to `commonjs`. Future versions will require `\"type\": \"module\"`.\n * @defaultValue 'warn'\n */\n preferModuleType: ToggleType\n /**\n * Warns if `publishConfig.exports` is missing when `source`, `development`, or `monorepo` conditions are used in exports.\n * @defaultValue 'warn'\n */\n noPublishConfigExports: ToggleType\n /**\n * Disallows `react-is` in `peerDependencies`. It should be in `dependencies` (or `devDependencies`) instead.\n * @defaultValue 'error'\n */\n noReactIsPeerDependency: ToggleType\n /**\n * Disallows `@sanity/ui` in `peerDependencies`. It should be in `dependencies` (or `devDependencies`) instead.\n * @defaultValue 'error'\n */\n noSanityUiPeerDependency: ToggleType\n /**\n * Disallows `@sanity/icons` in `peerDependencies`. It should be in `dependencies` (or `devDependencies`) instead.\n * @defaultValue 'error'\n */\n noSanityIconsPeerDependency: ToggleType\n /**\n * Disallows `sanity` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noSanityDependency: ToggleType\n /**\n * Disallows `styled-components` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noStyledComponentsDependency: ToggleType\n /**\n * Disallows `react` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noReactDependency: ToggleType\n /**\n * Disallows `react-dom` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`.\n * @defaultValue 'error'\n */\n noReactDomDependency: ToggleType\n /**\n * Disallows `@types/react` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`, and when declared as a peer dependency the version range should be `*`.\n * @defaultValue 'error'\n */\n noReactTypesDependency: ToggleType\n /**\n * Disallows `@types/react-dom` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`, and when declared as a peer dependency the version range should be `*`.\n * @defaultValue 'error'\n */\n noReactDomTypesDependency: ToggleType\n /**\n * Disallows `@types/node` in `dependencies`. It should only be in `devDependencies` and/or `peerDependencies`, and when declared as a peer dependency the version range should be `*`.\n * @defaultValue 'error'\n */\n noNodeTypesDependency: ToggleType\n /**\n * Disallows `rxjs` in `peerDependencies`. It should only be in `dependencies` and/or `devDependencies`.\n * @defaultValue 'error'\n */\n noRxjsPeerDependency: ToggleType\n /**\n * Disallows `@sanity/client` in `peerDependencies`. It should only be in `dependencies` and/or `devDependencies`.\n * @defaultValue 'error'\n */\n noSanityClientPeerDependency: ToggleType\n}\n\n/** @alpha */\nexport function parseStrictOptions(input: unknown): StrictOptions {\n return validationSchema.parse({strictOptions: input}, {errorMap}).strictOptions\n}\n","import path from 'node:path'\nimport {parseCssExports, type PackageJSON} from '@sanity/parse-package-json'\nimport browserslistToEsbuild from 'browserslist-to-esbuild'\nimport {resolveConfigProperty} from './core/config/resolveConfigProperty.ts'\nimport {type PkgConfigOptions, type PkgExports, type PkgRuntime} from './core/config/types.ts'\nimport type {BuildContext} from './core/contexts/buildContext.ts'\nimport {DEFAULT_BROWSERSLIST_QUERY} from './core/defaults.ts'\nimport {findCommonDirPath, pathContains} from './core/findCommonPath.ts'\nimport {parseAndValidateExports} from './core/pkg/parseAndValidateExports.ts'\nimport {loadTSConfig} from './core/ts/loadTSConfig.ts'\nimport type {Logger} from './logger.ts'\nimport {resolveBrowserTarget} from './resolveBrowserTarget.ts'\nimport {resolveNodeTarget} from './resolveNodeTarget.ts'\nimport {parseStrictOptions} from './strict.ts'\n\n// Type guard to filter out falsy values\nfunction isTruthy<T>(value: T | false | null | undefined | 0 | ''): value is T {\n return Boolean(value)\n}\n\nexport async function resolveBuildContext(options: {\n config?: PkgConfigOptions | undefined\n cwd: string\n emitDeclarationOnly?: boolean\n logger: Logger\n pkg: PackageJSON\n strict: boolean\n tsconfig: string\n}): Promise<BuildContext> {\n const {\n config,\n cwd,\n emitDeclarationOnly = false,\n logger,\n pkg,\n strict,\n tsconfig: tsconfigPath,\n } = options\n const tsconfig = await loadTSConfig({cwd, tsconfigPath})\n const strictOptions = parseStrictOptions(config?.strictOptions ?? {})\n\n let browserslist = pkg.browserslist\n if (!browserslist) {\n if (strict && strictOptions.noImplicitBrowsersList !== 'off') {\n if (strictOptions.noImplicitBrowsersList === 'error') {\n throw new Error(\n '\\n- ' +\n `package.json: \"browserslist\" is missing, set it to \\`\"browserslist\": \"extends @sanity/browserslist-config\"\\``,\n )\n } else {\n logger.warn(\n 'Could not detect a `browserslist` property in `package.json`, using default configuration. Add `\"browserslist\": \"extends @sanity/browserslist-config\"` to silence this warning.',\n )\n }\n }\n browserslist = DEFAULT_BROWSERSLIST_QUERY\n }\n const targetVersions = browserslistToEsbuild(browserslist)\n\n if (\n strict &&\n strictOptions.noImplicitSideEffects !== 'off' &&\n typeof pkg.sideEffects === 'undefined'\n ) {\n const msg =\n 'package.json: `sideEffects` is missing, see https://webpack.js.org/guides/tree-shaking/#clarifying-tree-shaking-and-sideeffects for how to define `sideEffects`'\n\n if (strictOptions.noImplicitSideEffects === 'error') {\n throw new Error(msg)\n } else {\n logger.warn(msg)\n }\n }\n\n const nodeTarget = resolveNodeTarget(targetVersions)\n const webTarget = resolveBrowserTarget(targetVersions)\n\n if (!nodeTarget) {\n throw new Error('no matching `node` target')\n }\n\n if (!webTarget) {\n throw new Error('no matching `web` target')\n }\n\n const target: Record<PkgRuntime, string[]> = {\n '*': webTarget.concat(nodeTarget),\n 'browser': webTarget,\n 'node': nodeTarget,\n }\n\n const parsedExports = parseAndValidateExports({\n cwd,\n pkg,\n strict,\n strictOptions,\n logger,\n }).reduce<PkgExports>(\n (acc, {_path: exportPath, ...exportEntry}) => Object.assign(acc, {[exportPath]: exportEntry}),\n {},\n )\n\n const exports = resolveConfigProperty(config?.exports, parsedExports)\n\n const cssExports = parseCssExports({pkg})\n\n const parsedExternal = [\n ...(pkg.dependencies ? Object.keys(pkg.dependencies) : []),\n ...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : []),\n ]\n\n // The deprecated (grandfathered) `external` option: merge if an array, replace if a function\n const external =\n config && Array.isArray(config.external)\n ? [...parsedExternal, ...config.external]\n : resolveConfigProperty(config?.external, parsedExternal)\n\n // Map `external` onto tsdown's `deps`: additions over the default (dependencies + peers)\n // become `neverBundle`, defaults filtered out by the callback pattern become `alwaysBundle`\n // (tsdown auto-externalizes dependencies/peers, so only the diff needs expressing). The v11\n // `external` semantics were subpath-aware (`name` also matched `name/subpath`), so package\n // names map to `^name(/|$)` patterns. The package's own name always stays external, so\n // self-referencing imports (e.g. the injected `import \"<pkg>/bundle.css\"`) never resolve\n // into the bundle.\n const packagePattern = (name: string) => new RegExp(`^${escapeRegExp(name)}(/|$)`)\n const neverBundleAdditions: (string | RegExp)[] = external\n .filter((name) => !parsedExternal.includes(name))\n .map(packagePattern)\n neverBundleAdditions.push(packagePattern(pkg.name))\n const alwaysBundleNames = parsedExternal.filter((name) => !external.includes(name))\n const deps = mergeDeps(config?.deps, {\n neverBundle: neverBundleAdditions,\n alwaysBundle: alwaysBundleNames.map(packagePattern),\n })\n\n // Packages whose types are inlined into the emitted declarations, used by the TSDoc check\n // (`tsdoc.bundledPackages`): devDependencies that are not external (like v11), plus any\n // string entries of the `deps.alwaysBundle` passthrough (force-bundled deps inline types too).\n const externalWithTypes = new Set([pkg.name, ...external, ...external.map(transformPackageName)])\n const bundledDependencies = (pkg.devDependencies ? Object.keys(pkg.devDependencies) : []).filter(\n // Do not bundle anything that is marked as external\n (_) => !externalWithTypes.has(_),\n )\n const bundledPackages = [\n ...bundledDependencies,\n ...alwaysBundleNames,\n ...(Array.isArray(config?.deps?.alwaysBundle)\n ? config.deps.alwaysBundle.filter((entry): entry is string => typeof entry === 'string')\n : typeof config?.deps?.alwaysBundle === 'string'\n ? [config.deps.alwaysBundle]\n : []),\n ]\n\n const outputPaths = Object.values(exports)\n .flatMap((exportEntry) => {\n return [\n exportEntry.import,\n exportEntry.require,\n exportEntry.browser?.import,\n exportEntry.browser?.require,\n exportEntry.browser?.default,\n exportEntry.node?.source && exportEntry.node.import,\n exportEntry.node?.source && exportEntry.node.require,\n exportEntry.node?.default,\n ].filter(isTruthy)\n })\n .map((p) => path.resolve(cwd, p))\n\n const commonDistPath = findCommonDirPath(outputPaths)\n\n if (commonDistPath === cwd) {\n throw new Error(\n 'all output files must share a common parent directory which is not the root package directory',\n )\n }\n\n if (commonDistPath && !pathContains(cwd, commonDistPath)) {\n throw new Error('all output files must be located within the package')\n }\n\n const configDistPath = config?.dist ? path.resolve(cwd, config.dist) : undefined\n\n if (\n configDistPath &&\n commonDistPath &&\n configDistPath !== commonDistPath &&\n !pathContains(configDistPath, commonDistPath)\n ) {\n logger.log(`did you mean to configure \\`dist: './${path.relative(cwd, commonDistPath)}'\\`?`)\n\n throw new Error('all output files must be located with the configured `dist` path')\n }\n\n const distPath = configDistPath || commonDistPath\n\n if (!distPath) {\n throw new Error('could not detect `dist` path')\n }\n\n const ctx: BuildContext = {\n config,\n cwd,\n deps,\n distPath,\n emitDeclarationOnly,\n exports,\n cssExports,\n external,\n bundledPackages,\n logger,\n pkg,\n runtime: config?.runtime ?? '*',\n strict,\n target,\n ts: {\n config: tsconfig,\n configPath: tsconfigPath,\n },\n }\n\n return ctx\n}\n\ntype DepsConfig = NonNullable<import('tsdown').UserConfig['deps']>\n\n/**\n * Merges the `deps` additions derived from the deprecated `external` option (and the\n * self-reference external) into the userland `deps` passthrough. Array forms concatenate, a\n * userland function is composed with the derived additions (the additions carry pipeline\n * invariants like the self-reference external, which must survive customization — the same\n * composition `@sanity/tsdown-config` applies to its `/^node:/` default), and a blanket\n * `true` (externalize all of `node_modules`) wins as the broadest request.\n * @internal Exported for tests.\n */\nexport function mergeDeps(\n configDeps: DepsConfig | undefined,\n additions: {neverBundle: (string | RegExp)[]; alwaysBundle: (string | RegExp)[]},\n): DepsConfig | undefined {\n const userNeverBundle = configDeps?.neverBundle\n let neverBundle: DepsConfig['neverBundle']\n if (userNeverBundle === undefined) {\n neverBundle = additions.neverBundle\n } else if (userNeverBundle === true) {\n neverBundle = userNeverBundle\n } else if (typeof userNeverBundle === 'function') {\n const patterns = additions.neverBundle\n neverBundle = (id, importer, isResolved) =>\n patterns.some((pattern) =>\n typeof pattern === 'string' ? pattern === id : pattern.test(id),\n ) || userNeverBundle(id, importer, isResolved)\n } else if (Array.isArray(userNeverBundle)) {\n neverBundle = [...additions.neverBundle, ...userNeverBundle]\n } else {\n neverBundle = [...additions.neverBundle, userNeverBundle]\n }\n\n const userAlwaysBundle = configDeps?.alwaysBundle\n let alwaysBundle: DepsConfig['alwaysBundle']\n if (userAlwaysBundle === undefined) {\n alwaysBundle = additions.alwaysBundle.length ? additions.alwaysBundle : undefined\n } else if (typeof userAlwaysBundle === 'function') {\n // A userland function wins over the derived additions\n alwaysBundle = userAlwaysBundle\n } else if (Array.isArray(userAlwaysBundle)) {\n alwaysBundle = [...additions.alwaysBundle, ...userAlwaysBundle]\n } else {\n alwaysBundle = [...additions.alwaysBundle, userAlwaysBundle]\n }\n\n const deps: DepsConfig = {\n ...configDeps,\n neverBundle,\n ...(alwaysBundle === undefined ? {} : {alwaysBundle}),\n }\n\n return deps\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction transformPackageName(packageName: string): string {\n if (packageName.startsWith('@types/')) {\n // If it already starts with @types, return it as is\n return packageName\n } else if (packageName.startsWith('@')) {\n // Handle scoped packages\n const [scope, name] = packageName.split('/')\n\n return `@types/${scope?.slice(1)}__${name}`\n } else {\n // Handle regular packages\n return `@types/${packageName}`\n }\n}\n"],"mappings":";;;;;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AA,GACtB,cAAc,UAAU;MACnB,IAAI,oBAAoB,IAC7B,cAAc;MACT,IAAI,OAAO,mBAAoB,YAAY;EAChD,IAAM,WAAW,UAAU;EAC3B,eAAe,IAAI,UAAU,eAC3B,SAAS,MAAM,YACb,OAAO,WAAY,WAAW,YAAY,KAAK,QAAQ,KAAK,EAAE,CAChE,KAAK,gBAAgB,IAAI,UAAU,UAAU;CACjD,OAAO,AAGL,cAHS,MAAM,QAAQ,eAAe,IACxB,CAAC,GAAG,UAAU,aAAa,GAAG,eAAe,IAE7C,CAAC,GAAG,UAAU,aAAa,eAAe;CAG1D,IAAM,mBAAmB,YAAY,cACjC;CAkBJ,OAjBA,AAQE,eARE,qBAAqB,KAAA,IACR,UAAU,aAAa,SAAS,UAAU,eAAe,KAAA,IAC/D,OAAO,oBAAqB,aAEtB,mBACN,MAAM,QAAQ,gBAAgB,IACxB,CAAC,GAAG,UAAU,cAAc,GAAG,gBAAgB,IAE/C,CAAC,GAAG,UAAU,cAAc,gBAAgB,GAStD;EALL,GAAG;EACH;EACA,GAAI,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAC,aAAY;CAG3C;AACZ;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAS,qBAAqB,aAA6B;CACzD,IAAI,YAAY,WAAW,SAAS,GAElC,OAAO;CACF,IAAI,YAAY,WAAW,GAAG,GAAG;EAEtC,IAAM,CAAC,OAAO,QAAQ,YAAY,MAAM,GAAG;EAE3C,OAAO,UAAU,OAAO,MAAM,CAAC,EAAE,IAAI;CACvC;CAEE,OAAO,UAAU;AAErB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as isRecord } from "./handleError-83GwKIFM.js";
|
|
2
|
-
import { i as pkgExtMap, r as fileEnding } from "./resolveBuildContext-
|
|
2
|
+
import { i as pkgExtMap, r as fileEnding } from "./resolveBuildContext-i4HOnPda.js";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { mergeConfig } from "tsdown";
|
|
5
5
|
import { defineConfig } from "@sanity/tsdown-config";
|
|
@@ -320,6 +320,9 @@ function pickCustomConditions(exp) {
|
|
|
320
320
|
return Object.entries(exp).filter(([condition, target]) => !managedConditions.has(condition) && !condition.startsWith("_") && target !== void 0);
|
|
321
321
|
}
|
|
322
322
|
const RE_TS_SOURCE = /\.[cm]?tsx?$/;
|
|
323
|
+
function hasNativePreview(pkg) {
|
|
324
|
+
return typeof pkg.devDependencies == "object" && pkg.devDependencies !== null && "@typescript/native-preview" in pkg.devDependencies;
|
|
325
|
+
}
|
|
323
326
|
/**
|
|
324
327
|
* Composes the tsdown config for one build of the waterfall: `@sanity/tsdown-config`'s
|
|
325
328
|
* `defineConfig()` provides the shared Sanity base, and the pkg-utils opinions (browserslist
|
|
@@ -358,10 +361,10 @@ async function resolveTsdownConfig(ctx, build, options) {
|
|
|
358
361
|
} : void 0, define = {};
|
|
359
362
|
pkg.name !== "@sanity/pkg-utils" && (define["process.env.PKG_VERSION"] = JSON.stringify(process.env.PKG_VERSION || pkg.version));
|
|
360
363
|
for (let [key, value] of Object.entries(config?.define || {})) define[key] = JSON.stringify(value);
|
|
361
|
-
let hasTsSources = !build.css && build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source)),
|
|
362
|
-
...
|
|
364
|
+
let hasTsSources = !build.css && build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source)), dtsObject = typeof config?.dts == "object" ? config.dts : void 0, nativePreviewGenerator = hasNativePreview(pkg) ? { generator: "tsgo" } : void 0, dts = hasTsSources && config?.dts !== !1 ? {
|
|
365
|
+
...nativePreviewGenerator,
|
|
363
366
|
newContext: !0,
|
|
364
|
-
...
|
|
367
|
+
...dtsObject,
|
|
365
368
|
...ctx.emitDeclarationOnly ? { emitDtsOnly: !0 } : {}
|
|
366
369
|
} : !1, exports = build.canonical && !ctx.emitDeclarationOnly && !options.watch && !build.css ? {
|
|
367
370
|
devExports: "source",
|
|
@@ -402,30 +405,19 @@ async function resolveTsdownConfig(ctx, build, options) {
|
|
|
402
405
|
}),
|
|
403
406
|
config: !1,
|
|
404
407
|
logLevel: "warn",
|
|
405
|
-
...options.watch ? {
|
|
408
|
+
...options.watch ? {
|
|
409
|
+
watch: !0,
|
|
410
|
+
ignoreWatch: [path.join(cwd, "package.json"), ctx.ts.configPath ?? "tsconfig.json"]
|
|
411
|
+
} : {}
|
|
406
412
|
};
|
|
407
413
|
}
|
|
408
|
-
/**
|
|
409
|
-
* Declares the conditional export of every CSS file a watch rebuild emitted.
|
|
410
|
-
*
|
|
411
|
-
* A full build leaves this to `cssNodeCompatPlugin`, which composes into tsdown's
|
|
412
|
-
* `exports.customExports`. Watch mode turns tsdown's `exports` feature off (a `package.json`
|
|
413
|
-
* write per rebuild would loop the watcher), so `pkg watch` maintains the exports itself. Most
|
|
414
|
-
* of them are known before the build and are written once per context in `watch.ts`, but the
|
|
415
|
-
* merged `style.css` of CSS imported from JS only exists when something actually imports CSS —
|
|
416
|
-
* declaring it from the config alone would point the export at files nobody produced.
|
|
417
|
-
*
|
|
418
|
-
* `build:done` is the only place that knows: in watch mode `build()` resolves before the first
|
|
419
|
-
* rebuild runs, so the returned bundle's chunks are still empty. The write is idempotent, so
|
|
420
|
-
* the `package.json` watcher settles after one extra rebuild rather than looping.
|
|
421
|
-
* @internal
|
|
422
|
-
*/
|
|
414
|
+
/** @internal */
|
|
423
415
|
function createWatchCssExportsHook(ctx, css) {
|
|
424
416
|
let mergedCssName = css.splitting ? void 0 : css.fileName || "style.css";
|
|
425
417
|
return (hooks) => {
|
|
426
418
|
hooks.hook("build:done", async ({ chunks }) => {
|
|
427
419
|
if (mergedCssName === void 0 || !chunks.some((chunk) => chunk.type === "asset" && chunk.fileName === mergedCssName)) return;
|
|
428
|
-
let { writeBundleCssExports } = await import("./writeBundleCssExports-
|
|
420
|
+
let { writeBundleCssExports } = await import("./writeBundleCssExports-CW1Lc_p6.js").then((n) => n.n);
|
|
429
421
|
await writeBundleCssExports({
|
|
430
422
|
cwd: ctx.cwd,
|
|
431
423
|
distPath: ctx.distPath,
|
|
@@ -437,4 +429,4 @@ function createWatchCssExportsHook(ctx, css) {
|
|
|
437
429
|
}
|
|
438
430
|
export { createConditionalCssExport as n, resolveTsdownBuilds as r, resolveTsdownConfig as t };
|
|
439
431
|
|
|
440
|
-
//# sourceMappingURL=resolveTsdownConfig-
|
|
432
|
+
//# sourceMappingURL=resolveTsdownConfig-orfQXkE6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveTsdownConfig-C6jUZqvp.js","names":[],"sources":["../src/node/tasks/tsdown/resolveTsdownBuilds.ts","../src/node/core/pkg/cssShimFileName.ts","../src/node/core/pkg/cssExport.ts","../src/node/tasks/tsdown/composeExports.ts","../src/node/tasks/tsdown/resolveTsdownConfig.ts"],"sourcesContent":["import path from 'node:path'\nimport type {PkgFormat, PkgRuntime} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {fileEnding} from '../../core/pkg/pkgExt.ts'\n\n/**\n * One entry of a tsdown build.\n * @internal\n */\nexport interface TsdownBuildEntry {\n /**\n * The entry alias handed to tsdown: the output path relative to `dist` without the\n * extension (e.g. `index`, `index.browser`, `sub/feature`), so the emitted filenames match\n * the hand-written `exports` targets exactly.\n */\n alias: string\n source: string\n /** The hand-written export subpath this entry backs (`undefined` for `bundles`). */\n exportPath?: string\n /** The formats the hand-written exports declare for this entry. */\n formats: PkgFormat[]\n}\n\n/**\n * One tsdown `build()` call of the waterfall. Builds run serially — variants and bundles\n * first, the canonical build last, so its exports generation and publint see every emitted\n * file on disk.\n * @internal\n */\nexport interface TsdownBuild {\n /** Stable identifier, e.g. `neutral`, `browser`, `node`, `bundles`, `css`. */\n key: string\n runtime: PkgRuntime\n /** The canonical build owns `dist` conventions: exports generation runs here. */\n canonical: boolean\n entries: TsdownBuildEntry[]\n /**\n * The stylesheet build: its entries are `.css` files rather than JS, so it emits CSS assets\n * (one per entry) and no JS at all. It runs on its own because a `.css` entry has nothing to\n * declare types for, and because its per-entry CSS output needs `css.splitting`.\n */\n css?: boolean\n}\n\n/** The build key of the stylesheet build. */\nconst CSS_BUILD_KEY = 'css'\n\n/**\n * Collapses the hand-written `exports` map (+ `bundles`) into the per-platform tsdown build\n * waterfall: one canonical build for the package's default runtime, plus a variant build per\n * `browser`/`node` exports condition, plus builds for `bundles` (which must not participate\n * in exports generation).\n * @internal\n */\nexport function resolveTsdownBuilds(ctx: BuildContext): TsdownBuild[] {\n const {config, cwd, distPath, logger} = ctx\n\n const entryAlias = (output: string): string => {\n const alias = path\n .relative(distPath, path.resolve(cwd, output))\n .replaceAll('\\\\', '/')\n .replace(fileEnding, '')\n if (alias.startsWith('..')) {\n throw new Error(`output file is outside the \\`dist\\` folder: ${output}`)\n }\n return alias\n }\n\n interface EntryDraft {\n alias: string\n source: string\n exportPath?: string | undefined\n formats: Set<PkgFormat>\n }\n\n const draftsByBuild = new Map<string, Map<string, EntryDraft>>()\n const runtimeByBuild = new Map<string, PkgRuntime>()\n\n const addEntry = (\n buildKey: string,\n runtime: PkgRuntime,\n entry: {\n source: string\n exportPath?: string | undefined\n import?: string | undefined\n require?: string | undefined\n },\n ) => {\n runtimeByBuild.set(buildKey, runtime)\n const {source, exportPath} = entry\n const aliases = new Set<string>()\n const formats = new Set<PkgFormat>()\n if (entry.import) {\n aliases.add(entryAlias(entry.import))\n formats.add('esm')\n }\n if (entry.require) {\n aliases.add(entryAlias(entry.require))\n formats.add('commonjs')\n }\n if (aliases.size === 0) return\n if (aliases.size > 1) {\n throw new Error(\n `the \\`import\\` and \\`require\\` targets of ${\n exportPath ? `exports[\"${exportPath}\"]` : `the bundle for ${source}`\n } must share a basename (e.g. \\`./dist/index.js\\` + \\`./dist/index.cjs\\`), ` +\n `got: ${entry.import} and ${entry.require}`,\n )\n }\n const [alias] = aliases\n let drafts = draftsByBuild.get(buildKey)\n if (!drafts) {\n drafts = new Map()\n draftsByBuild.set(buildKey, drafts)\n }\n const existing = drafts.get(alias!)\n if (existing) {\n if (existing.source !== source) {\n throw new Error(\n `conflicting sources for the output alias \"${alias}\": ${existing.source} and ${source}`,\n )\n }\n for (const format of formats) existing.formats.add(format)\n return\n }\n drafts.set(alias!, {alias: alias!, source, exportPath, formats})\n }\n\n const exports = Object.entries(ctx.exports || {})\n const packageType = ctx.pkg.type === 'module' ? 'module' : 'commonjs'\n const resolveRuntimeTargets = (condition: {\n import?: string\n require?: string\n default?: string\n }) => ({\n import: condition.import ?? (packageType === 'module' ? condition.default : undefined),\n require: condition.require ?? (packageType === 'commonjs' ? condition.default : undefined),\n })\n\n let hasRuntimeConditions = false\n\n for (const [exportPath, exp] of exports) {\n addEntry('canonical', ctx.runtime, {\n source: exp.source,\n exportPath,\n import: exp.import,\n require: exp.require,\n })\n\n const browserTargets = exp.browser && resolveRuntimeTargets(exp.browser)\n if (exp.browser && browserTargets && (browserTargets.import || browserTargets.require)) {\n hasRuntimeConditions = true\n addEntry('browser', 'browser', {\n source: exp.browser.source || exp.source,\n exportPath,\n ...browserTargets,\n })\n }\n\n const nodeTargets = exp.node && resolveRuntimeTargets(exp.node)\n if (exp.node && nodeTargets && (nodeTargets.import || nodeTargets.require)) {\n hasRuntimeConditions = true\n addEntry('node', 'node', {\n source: exp.node.source || exp.source,\n exportPath,\n ...nodeTargets,\n })\n }\n }\n\n // `bundles` are extra entrypoints that are deliberately not in the exports map (CLI workers\n // and similar), so they build separately from the canonical build — exports generation\n // derives subpaths from every entry of its build, and bundles must never become export\n // subpaths of their own.\n for (const bundle of config?.bundles || []) {\n const runtime = bundle.runtime || ctx.runtime\n addEntry(runtime === ctx.runtime ? 'bundles' : `bundles:${runtime}`, runtime, {\n source: bundle.source,\n import: bundle.import,\n require: bundle.require,\n })\n }\n\n if (hasRuntimeConditions) {\n logger.warn(\n [\n 'The `exports[].browser.source` / `exports[].node.source` pattern is not recommended: every',\n 'runtime condition adds a full extra build (complexity and build time). Consider instead:',\n ' 1. separate npm packages per platform/runtime, selected through export conditions that',\n ' pick the right package per environment,',\n ' 2. when possible, a single neutral build using JS that works in both runtimes without',\n ' special-casing (e.g. `new URL` over `require(\"url\")`, WebCrypto over',\n ' `require(\"crypto\")`), or',\n ' 3. using `tsdown` + `@sanity/tsdown-config` directly, exporting an array from',\n ' `tsdown.config.ts` with one config per `platform` — the fully supported path for',\n ' this level of customization.',\n ].join('\\n'),\n )\n }\n\n const builds: TsdownBuild[] = []\n\n // `.css` export subpaths that declare a `source` build in their own pass: their entries are\n // stylesheets, so the emitted file name follows the export subpath (`./ui/styles.css` ->\n // `dist/ui/styles.css`) instead of an `import`/`require` target, and `dts` has nothing to do.\n const cssEntries: TsdownBuildEntry[] = ctx.cssExports.map((cssExport) => ({\n alias: cssEntryAlias(cssExport._path),\n source: cssExport.source,\n exportPath: cssExport._path,\n formats: ['esm'],\n }))\n if (cssEntries.length) {\n builds.push({\n key: CSS_BUILD_KEY,\n runtime: ctx.runtime,\n canonical: false,\n entries: cssEntries,\n css: true,\n })\n }\n\n const toBuild = (key: string, runtime: PkgRuntime, canonical: boolean): TsdownBuild | null => {\n const drafts = draftsByBuild.get(key)\n if (!drafts || drafts.size === 0) return null\n return {\n key,\n runtime,\n canonical,\n entries: Array.from(drafts.values(), (draft) => ({\n alias: draft.alias,\n source: draft.source,\n ...(draft.exportPath === undefined ? {} : {exportPath: draft.exportPath}),\n formats: Array.from(draft.formats),\n })),\n }\n }\n\n // Variants and bundles run first; the canonical build runs last so its exports generation\n // and publint see the other builds' files on disk. Each build's runtime was recorded when\n // its entries were added, so nothing is re-derived from the build key (a bundle with\n // `runtime: '*'` in a `runtime: 'node'` package must build for `'*'`/neutral).\n for (const key of draftsByBuild.keys()) {\n if (key === 'canonical') continue\n const build = toBuild(key, runtimeByBuild.get(key) ?? ctx.runtime, false)\n if (build) builds.push(build)\n }\n\n const canonical = toBuild('canonical', ctx.runtime, true)\n if (canonical) builds.push(canonical)\n\n return builds\n}\n\n/**\n * The tsdown entry alias of a `.css` export subpath: the subpath without its leading `./` and\n * `.css` ending, so `@tsdown/css` (with `splitting`) emits the stylesheet at exactly the path\n * the subpath promises — `\"./ui/styles.css\"` -> alias `ui/styles` -> `dist/ui/styles.css`.\n */\nfunction cssEntryAlias(exportPath: string): string {\n return exportPath.replace(/^\\.\\//, '').replace(/\\.css$/, '')\n}\n","/**\n * The no-op JS shim file name for a CSS file under vanilla-extract compat mode.\n *\n * `bundle.css` → `bundle-css.js` — deliberately not `${cssFileName}.js` (`bundle.css.js`),\n * which vanilla-extract's `cssFileFilter` (`/\\.css\\.(js|cjs|mjs|jsx|ts|tsx)$/`) would treat as\n * a stylesheet module. Kept in sync with `cssShimFileName` in\n * `@sanity/vanilla-extract-rolldown-plugin`.\n *\n * @internal\n */\nexport function cssShimFileName(cssFileName: string): string {\n return `${cssFileName.replace(/\\.css$/, '-css')}.js`\n}\n\n/**\n * The `.d.ts` companion for {@link cssShimFileName}. `bundle.css` → `bundle-css.d.ts`.\n *\n * @internal\n */\nexport function cssShimDtsFileName(cssFileName: string): string {\n return `${cssFileName.replace(/\\.css$/, '-css')}.d.ts`\n}\n","import path from 'node:path'\nimport {cssShimDtsFileName, cssShimFileName} from './cssShimFileName.ts'\n\n/**\n * Build the conditional CSS export object that `exports.nodeCompat` expects, e.g.\n * ```json\n * {\n * \"types\": \"./dist/bundle-css.d.ts\",\n * \"browser\": \"./dist/bundle.css\",\n * \"style\": \"./dist/bundle.css\",\n * \"node\": \"./dist/bundle-css.js\",\n * \"default\": \"./dist/bundle-css.js\"\n * }\n * ```\n * The shim is named `bundle-css.js` (not `bundle.css.js`) so it does not match\n * vanilla-extract's `cssFileFilter`. An explicit `types` condition (rather than relying on\n * TypeScript's extension-substitution fallback, which only works when the shim shares the CSS\n * file's basename, and which TypeScript is deprecating anyway - microsoft/TypeScript#50762)\n * points resolvers straight at the shim's declaration file.\n *\n * Kept in sync with `createConditionalCssExport` in `@sanity/vanilla-extract-tsdown-plugin`,\n * which writes the same entry through tsdown's `exports.customExports` during full builds.\n *\n * @internal\n */\nexport function createConditionalCssExport(\n cssName: string,\n distRel: string,\n): Record<string, string> {\n const cssFile = `./${path.posix.join(distRel, cssName)}`\n const shimFile = `./${path.posix.join(distRel, cssShimFileName(cssName))}`\n const shimDtsFile = `./${path.posix.join(distRel, cssShimDtsFileName(cssName))}`\n return {types: shimDtsFile, browser: cssFile, style: cssFile, node: shimFile, default: shimFile}\n}\n","import path from 'node:path'\nimport type {PkgExport} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {isRecord} from '../../core/isRecord.ts'\nimport {createConditionalCssExport} from '../../core/pkg/cssExport.ts'\nimport type {TsdownBuild} from './resolveTsdownBuilds.ts'\n\ntype ExportsMap = Record<string, unknown>\ninterface ComposeContext {\n isPublish: boolean\n}\n\n/**\n * The pkg-utils opinion layer over tsdown's generated `exports` map, composed into\n * `exports.customExports` of the canonical build (the same composition hook\n * `@sanity/vanilla-extract-tsdown-plugin` uses for its conditional CSS export).\n *\n * tsdown generates subpaths from the entry aliases with `source`/`import`/`require` conditions\n * (`devExports: 'source'`) and a `source`-less `publishConfig.exports` — already the Sanity\n * convention. This composer reconciles the generated map with the hand-written one, which\n * remains the input:\n *\n * - generated keys are remapped to the hand-written subpaths (entry aliases are derived from\n * the output paths, which don't have to match the subpath names),\n * - the hand-written `types`, `browser`, `node`, `development` and `monorepo` conditions are\n * re-inserted (tsdown's generator cannot express them; the `browser`/`node` files are built\n * by the variant builds of the waterfall) — with `source`-like conditions stripped from the\n * publish variant,\n * - all hand-written conditions (`react-server`, `worker`, … included) retain their authored\n * order in each map independently, because earlier matching conditions take precedence,\n * - generated conditions for conditional entries are materialized in both `exports` and\n * `publishConfig.exports`, so they can be reordered directly in `package.json` and keep that\n * position on later builds (plain-string entries stay compact),\n * - a trailing `default` condition is kept on dual-format entries and nested runtime variants\n * (tsdown emits bare `import`/`require` pairs; the Sanity convention always ends with\n * `default`),\n * - hand-written subpaths that aren't build entries (`.css`/`.json` exports, `svelte`\n * entries) are carried over untouched, and\n * - the hand-written subpath and condition key order of each map is preserved.\n * @internal\n */\nexport function createExportsComposer(\n ctx: BuildContext,\n build: TsdownBuild,\n): (exportsMap: ExportsMap, context: ComposeContext) => ExportsMap {\n const {pkg} = ctx\n const type = pkg.type === 'module' ? 'module' : 'commonjs'\n\n // POSIX separators: on Windows `path.relative` yields backslashes, which must never leak\n // into generated `package.json` export targets.\n const distRel = (path.relative(ctx.cwd, ctx.distPath) || 'dist').split(path.sep).join('/')\n const cssExportPaths = new Set(ctx.cssExports.map((cssExport) => cssExport._path))\n const cssSources: Record<string, string> = {}\n for (const cssExport of ctx.cssExports) {\n cssSources[cssExport._path] = cssExport.source\n }\n\n // alias -> hand-written subpath, e.g. `index` -> `.`, `sub/feature` -> `./feature`\n const aliasToExportPath = new Map<string, string>()\n for (const entry of build.entries) {\n if (entry.exportPath !== undefined) {\n aliasToExportPath.set(entry.alias, entry.exportPath)\n }\n }\n\n return (exportsMap, context) => {\n const {isPublish} = context\n\n // 1. Remap the generated keys (`.` for the `index` alias, `./<alias>` otherwise) back to\n // the hand-written subpaths.\n const remapped: ExportsMap = {}\n for (const [key, value] of Object.entries(exportsMap)) {\n const alias = key === '.' ? 'index' : key.startsWith('./') ? key.slice(2) : key\n const exportPath = aliasToExportPath.get(alias) ?? key\n remapped[exportPath] = value\n }\n\n // 2. Reconcile each generated entry with its hand-written counterpart.\n const result: ExportsMap = {}\n const handwritten = ctx.exports || {}\n const sourceRaw: ExportsMap = pkg.exports || {}\n const publishRaw: ExportsMap | undefined = pkg.publishConfig?.exports\n const authoredRaw = isPublish && publishRaw ? publishRaw : sourceRaw\n\n const reconcile = (exportPath: string, value: unknown): unknown => {\n const exp = handwritten[exportPath]\n if (!exp) return value\n const raw = authoredRaw[exportPath]\n const source = sourceRaw[exportPath]\n // A configured exports map is itself authoritative. Otherwise use the raw package entry\n // for the map being generated. Fall back to `exports` when a new publish map/entry is\n // being generated, so inferred conditions don't masquerade as ordering choices.\n const authored =\n ctx.config?.exports === undefined\n ? isRecord(raw)\n ? raw\n : isRecord(source)\n ? source\n : exp\n : exp\n return reconcileEntry(exp, value, {authored, isPublish, type})\n }\n\n // 3. Follow the hand-written key order of the map being generated. Source-only passthrough\n // subpaths missing from an existing publish map are appended, followed by generated extras.\n const authoredPaths = Object.keys(authoredRaw)\n for (const exportPath of Object.keys(sourceRaw)) {\n if (!Object.prototype.hasOwnProperty.call(authoredRaw, exportPath)) {\n authoredPaths.push(exportPath)\n }\n }\n for (const exportPath of authoredPaths) {\n if (exportPath in remapped) {\n result[exportPath] = reconcile(exportPath, remapped[exportPath])\n } else if (cssExportPaths.has(exportPath)) {\n // A `.css` subpath with a `source` is built by the stylesheet build, which does not\n // participate in exports generation (its entries are stylesheets, not JS). Its\n // conditions are materialized here instead, from the export subpath: `./ui/styles.css`\n // is built to `<dist>/ui/styles.css` with the shim next to it.\n result[exportPath] = reconcileCssEntry(exportPath, {\n distRel,\n source: cssSources[exportPath],\n isPublish,\n })\n } else {\n // Hand-written subpaths that aren't build entries (plain `.css`/`.json` exports,\n // `svelte` entries) pass through untouched.\n result[exportPath] = Object.prototype.hasOwnProperty.call(authoredRaw, exportPath)\n ? authoredRaw[exportPath]\n : sourceRaw[exportPath]\n }\n }\n for (const [exportPath, value] of Object.entries(remapped)) {\n if (exportPath in result) continue\n result[exportPath] = reconcile(exportPath, value)\n }\n\n return result\n }\n}\n\n/**\n * The conditional CSS export of a `.css` subpath built by the stylesheet build. `source`\n * resolves at development time, so it is kept in `exports` and stripped from the publish\n * variant — the same split the build entries get.\n */\nfunction reconcileCssEntry(\n exportPath: string,\n options: {distRel: string; source: string | undefined; isPublish: boolean},\n): Record<string, string> {\n const {distRel, source, isPublish} = options\n const cssName = exportPath.replace(/^\\.\\//, '')\n const conditions = createConditionalCssExport(cssName, distRel)\n return isPublish || source === undefined ? conditions : {source, ...conditions}\n}\n\n/**\n * Rebuilds a generated subpath entry in its authored condition order, re-inserting the\n * hand-written conditions tsdown's generator cannot express.\n */\nfunction reconcileEntry(\n exp: PkgExport,\n generated: unknown,\n options: {authored: object; isPublish: boolean; type: 'commonjs' | 'module'},\n): unknown {\n const {authored, isPublish, type} = options\n const authoredRecord = isRecord(authored) ? authored : {}\n\n // tsdown's publish variant of a single-format entry is a plain string\n const gen: Record<string, unknown> | undefined =\n typeof generated === 'string'\n ? {default: generated}\n : isRecord(generated)\n ? generated\n : undefined\n if (!gen) return generated\n\n const browserOrder = isRecord(authoredRecord['browser']) ? authoredRecord['browser'] : exp.browser\n const browser =\n exp.browser && (exp.browser.import || exp.browser.require || exp.browser.default)\n ? pickConditions(exp.browser, {\n authored: browserOrder ?? exp.browser,\n isPublish,\n type,\n })\n : undefined\n const nodeOrder = isRecord(authoredRecord['node']) ? authoredRecord['node'] : exp.node\n const node =\n exp.node && (exp.node.import || exp.node.require || exp.node.default)\n ? pickConditions(exp.node, {\n authored: nodeOrder ?? exp.node,\n isPublish,\n type,\n })\n : undefined\n const custom = pickCustomConditions(exp)\n\n // Preserve tsdown's compact single-format publish shape unless hand-written conditions need\n // to be re-inserted. There is no condition ordering to preserve in a plain string entry.\n if (typeof generated === 'string' && !exp.types && !browser && !node && custom.length === 0) {\n return generated\n }\n\n const next: Record<string, unknown> = {}\n\n // `source`-like conditions resolve at development time and are stripped from the publish\n // variant (tsdown already does this for `source`; `development`/`monorepo` follow)\n if (!isPublish) {\n if (typeof gen['source'] === 'string') next['source'] = gen['source']\n else if (exp.source) next['source'] = exp.source\n if (exp.development) next['development'] = exp.development\n if (exp.monorepo) next['monorepo'] = exp.monorepo\n }\n\n if (exp.types) next['types'] = exp.types\n if (browser) next['browser'] = browser\n if (node) next['node'] = node\n\n // Hand-written custom conditions (`react-server`, `worker`, …) aren't built, but they are\n // the author's: carry their targets over, then restore every condition's authored position.\n for (const [condition, target] of custom) {\n const authoredTarget = authoredRecord[condition]\n next[condition] =\n isRecord(target) && isRecord(authoredTarget)\n ? preserveConditionOrder(target, authoredTarget)\n : target\n }\n\n if (typeof gen['import'] === 'string' && typeof gen['require'] === 'string') {\n next['import'] = gen['import']\n next['require'] = gen['require']\n // tsdown emits bare `import`/`require` pairs; the Sanity convention ends with `default`\n next['default'] = type === 'module' ? gen['import'] : gen['require']\n } else {\n // Single-format entries keep the generated shape (`{source, default}` in development)\n for (const [condition, target] of Object.entries(gen)) {\n if (condition in next || condition === 'source') continue\n next[condition] = target\n }\n }\n\n return preserveConditionOrder(next, authored)\n}\n\n/**\n * The hand-written `browser`/`node` condition object, minus `source` for the publish map.\n * A nested runtime condition must have its own fallback: once a resolver matches `node` or\n * `browser`, an unmatched module-format condition otherwise backtracks to the outer entry.\n */\nfunction pickConditions(\n conditions: {source?: string; import?: string; require?: string; default?: string},\n options: {\n authored?: object\n isPublish: boolean\n type: 'commonjs' | 'module'\n },\n): Record<string, string> {\n const {authored = conditions, isPublish, type} = options\n const next: Record<string, string> = {}\n if (!isPublish && conditions.source) next['source'] = conditions.source\n if (conditions.import) next['import'] = conditions.import\n if (conditions.require) next['require'] = conditions.require\n const fallback =\n conditions.default ?? (type === 'module' ? conditions.import : conditions.require)\n if (fallback) next['default'] = fallback\n return preserveConditionOrder(next, authored)\n}\n\n/**\n * Reorders reconciled conditions to match their hand-written order. Conditions generated by\n * tsdown but absent from the hand-written entry are inserted before its `default` fallback.\n */\nfunction preserveConditionOrder<T>(\n conditions: Record<string, T>,\n authored: object,\n): Record<string, T> {\n const entries: [string, T][] = []\n const added = new Set<string>()\n const conditionEntries = Object.entries(conditions)\n const entriesByCondition = new Map(conditionEntries.map((entry) => [entry[0], entry]))\n const authoredOrder = Object.keys(authored).filter((condition) => !condition.startsWith('_'))\n const authoredConditions = new Set(authoredOrder)\n\n const addGeneratedConditions = () => {\n for (const entry of conditionEntries) {\n if (!authoredConditions.has(entry[0]) && !added.has(entry[0])) {\n entries.push(entry)\n added.add(entry[0])\n }\n }\n }\n\n for (const condition of authoredOrder) {\n // A generated condition has no authored position. Keep the explicit `default` as the final\n // fallback by placing generated conditions immediately before it.\n if (condition === 'default') addGeneratedConditions()\n const entry = entriesByCondition.get(condition)\n if (!entry) continue\n entries.push(entry)\n added.add(condition)\n }\n\n addGeneratedConditions()\n\n return Object.fromEntries(entries)\n}\n\n/** The conditions the pipeline owns (or re-inserts itself) on a build entry. */\nconst managedConditions = new Set([\n 'source',\n 'development',\n 'monorepo',\n 'types',\n 'browser',\n 'node',\n 'import',\n 'require',\n 'default',\n])\n\n/**\n * Hand-written conditions the pipeline knows nothing about (`react-server`, `worker`,\n * `edge-light`, …), in authored order. `parseExports` spreads the raw entry, so they survive\n * on the parsed `PkgExport` beyond its typed fields.\n */\nfunction pickCustomConditions(exp: PkgExport): [string, unknown][] {\n return Object.entries(exp).filter(\n ([condition, target]) =>\n !managedConditions.has(condition) && !condition.startsWith('_') && target !== undefined,\n )\n}\n","import path from 'node:path'\nimport {\n defineConfig,\n type ReactCompilerOptions as TsdownConfigReactCompilerOptions,\n} from '@sanity/tsdown-config'\nimport {mergeConfig, type InlineConfig, type UserConfig} from 'tsdown'\nimport type {PkgConfigOptions} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {pkgExtMap} from '../../core/pkg/pkgExt.ts'\nimport {createExportsComposer} from './composeExports.ts'\nimport type {TsdownBuild} from './resolveTsdownBuilds.ts'\n\nconst RE_TS_SOURCE = /\\.[cm]?tsx?$/\n\n/**\n * Composes the tsdown config for one build of the waterfall: `@sanity/tsdown-config`'s\n * `defineConfig()` provides the shared Sanity base, and the pkg-utils opinions (browserslist\n * targets, `PKG_*` defines, exports reconciliation, dts selection) layer over it with\n * tsdown's `mergeConfig`.\n *\n * pkg-utils owns its own experience: the returned config carries `config: false`, so tsdown\n * never loads `tsdown.config.*` files — `package.config.ts` is the sole config source — and\n * `logLevel: 'warn'` keeps tsdown's info chatter out of pkg-utils' own output.\n * @internal\n */\nexport async function resolveTsdownConfig(\n ctx: BuildContext,\n build: TsdownBuild,\n options: {\n /**\n * Whether this build may clean: only the first build of the waterfall cleans (so later\n * builds can't wipe earlier output), and `--no-clean` turns it off for the whole run.\n */\n clean: boolean\n watch?: boolean\n },\n): Promise<InlineConfig> {\n const {config, cwd, distPath, pkg} = ctx\n\n // `?? false` up front (like tsdown-config's own normalization): JS configs bypass the\n // types, and a `reactCompiler: null` would pass the `typeof … === 'object'` checks below\n const reactCompiler = config?.reactCompiler ?? false\n if (typeof reactCompiler === 'object' && reactCompiler.reactServer === true) {\n throw new Error(\n [\n 'package.config.ts: `reactCompiler.reactServer` is not supported by `pkg build` — the',\n 'dual React Server Components build needs one tsdown run driving multiple configs.',\n 'Use `tsdown` + `@sanity/tsdown-config` directly instead: export the config from',\n '`tsdown.config.ts` and build with `tsdown`.',\n ].join('\\n'),\n )\n }\n // Pin the `'babel'` default before forwarding: `@sanity/tsdown-config` defaults to `'oxc'`\n // since 0.27, and inheriting the flip would break published configs.\n const reactCompilerOption: TsdownConfigReactCompilerOptions | boolean =\n typeof reactCompiler === 'object'\n ? reactCompiler.transform === 'oxc'\n ? reactCompiler\n : {...reactCompiler, transform: 'babel'}\n : reactCompiler\n ? {transform: 'babel'}\n : false\n\n const entry: Record<string, string> = {}\n for (const buildEntry of build.entries) {\n entry[buildEntry.alias] = buildEntry.source\n }\n\n // tsdown's `format` applies to the whole build (and its exports generation composes the\n // dual `import`/`require` map from both formats' chunks of one build), so the entries'\n // formats union: every entry is emitted in every format of the build. Mixed per-entry\n // coverage gets a heads-up — the extra files are emitted, and local exports generation\n // will declare them.\n const formats = new Set(build.entries.flatMap((buildEntry) => buildEntry.formats))\n if (formats.size > 1) {\n const partial = build.entries.filter((buildEntry) => buildEntry.formats.length < formats.size)\n if (partial.length) {\n const names = partial\n .map((buildEntry) =>\n buildEntry.exportPath ? `exports[\"${buildEntry.exportPath}\"]` : buildEntry.source,\n )\n .join(', ')\n ctx.logger.warn(\n `${names} declare${partial.length === 1 ? 's' : ''} fewer formats than the rest of the package. tsdown emits every format of a build for every entry, so the missing format is built anyway (and local exports generation will declare it). Declare both \\`import\\` and \\`require\\` targets for every subpath — or for none — to keep the exports map unambiguous.`,\n )\n }\n }\n const format = [\n ...(formats.has('esm') ? ['esm' as const] : []),\n ...(formats.has('commonjs') ? ['cjs' as const] : []),\n ]\n\n const platform =\n build.runtime === 'node' ? 'node' : build.runtime === 'browser' ? 'browser' : 'neutral'\n\n // The `@tsdown/css` pipeline turns on when it's configured, and automatically for a package\n // that declares a `.css` export subpath with a `source`. The stylesheet build needs\n // `splitting` so each entry emits its own file at the path its subpath promises; the JS\n // builds keep `@tsdown/css`'s merged default, so CSS imported from JS lands in a single\n // `style.css` with one export and one injected import - the `bundle.css` shape of\n // `vanillaExtract`.\n const css: PkgConfigOptions['css'] | undefined =\n config?.css || ctx.cssExports.length\n ? {...config?.css, ...(build.css ? {splitting: true} : {})}\n : undefined\n\n // Build-time constants: `PKG_VERSION` reads the environment override first, like v11.\n // pkg-utils' own build skips it so the replacement logic in this very file survives its own\n // bundling. (`PKG_FORMAT`, `PKG_RUNTIME` and `PKG_FILE_PATH` were removed in v12 — see\n // MIGRATE.md for the `package.json#imports` / `import.meta.url` replacements.)\n const define: Record<string, string> = {}\n if (pkg.name !== '@sanity/pkg-utils') {\n define['process.env.PKG_VERSION'] = JSON.stringify(process.env['PKG_VERSION'] || pkg.version)\n }\n for (const [key, value] of Object.entries(config?.define || {})) {\n define[key] = JSON.stringify(value)\n }\n\n // Types are generated with tsdown (rolldown-plugin-dts). `@typescript/native-preview` in\n // devDependencies auto-enables tsgo, like v11; an explicit `dts.tsgo` wins. Only the object\n // form spreads: when the `legacyChecks` migration errors are skipped\n // (`NODE_ENV=production` / `legacyChecks: false`), a leftover v11 string like\n // `dts: 'rolldown'` must degrade to the default behavior (which is what it meant) instead\n // of spreading into numeric character keys.\n const hasTsSources =\n !build.css && build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source))\n const dtsPassthrough = typeof config?.dts === 'object' ? config.dts : undefined\n const dts =\n hasTsSources && config?.dts !== false\n ? {\n ...(typeof pkg.devDependencies === 'object' &&\n '@typescript/native-preview' in pkg.devDependencies\n ? {tsgo: true}\n : {}),\n // Always create dts from scratch, don't reuse contexts from previous builds\n newContext: true,\n ...dtsPassthrough,\n ...(ctx.emitDeclarationOnly ? {emitDtsOnly: true} : {}),\n }\n : false\n\n // Exports generation runs on the canonical build only, with `devExports: 'source'` — the\n // hand-written Sanity convention (`source` conditions in `exports`, a `source`-less\n // `publishConfig.exports`) — and the pkg-utils composer reconciling the generated map with\n // the hand-written one. `@sanity/tsdown-config`'s always-on exports default applies: the map\n // is rewritten on every build (CI included), so environments that set `CI=true` without\n // meaning \"skip package.json\" (Cursor Cloud, …) still keep exports in sync. A types-only\n // build never rewrites `package.json`, and neither do watch builds (a rewrite would\n // re-trigger the `package.json` watcher).\n const exports: UserConfig['exports'] =\n build.canonical && !ctx.emitDeclarationOnly && !options.watch && !build.css\n ? {\n devExports: 'source',\n customExports: createExportsComposer(ctx, build),\n // Keep the hand-written legacy fields (`main`/`module`) in sync instead of deleting\n // them; packages without them don't gain them\n ...(pkg.main || pkg.module ? {legacy: true} : {}),\n }\n : false\n\n // `@sanity/tsdown-config` defaults `tsdoc` to `false`; pkg-utils keeps the historical\n // default of enabled (`true`), and forwards an options object (with `bundledPackages` for\n // API Extractor's type resolution of inlined deps) when the user customized rules/tags.\n const tsdocOption =\n config?.tsdoc === false\n ? false\n : {\n ...(typeof config?.tsdoc === 'object' ? config.tsdoc : {}),\n bundledPackages: ctx.bundledPackages,\n }\n\n const base = await defineConfig({\n cwd,\n tsconfig: ctx.ts.configPath,\n platform,\n format,\n entry,\n // POSIX separators: on Windows `path.relative` yields backslashes, which would leak into\n // generated `package.json` export targets (e.g. the conditional vanilla-extract export)\n outDir: path.relative(cwd, distPath).replaceAll('\\\\', '/') || '.',\n target: ctx.target[build.runtime],\n define,\n sourcemap: config?.sourcemap,\n // tsdown owns cleaning: the first build of the waterfall carries the effective `clean`\n // (the config passthrough, or tsdown's default `true`), every later build gets `false`.\n // A types-only build never cleans, so it can't delete JS output.\n clean: options.clean && !ctx.emitDeclarationOnly ? config?.clean : false,\n dts,\n deps: ctx.deps,\n exports,\n css,\n reactCompiler: reactCompilerOption,\n styledComponents: config?.styledComponents,\n vanillaExtract: config?.vanillaExtract,\n bundleAnalyzer: config?.bundleAnalyzer,\n // Types-only builds still emit `.d.ts` files that deserve the check; watch mode skips it\n // so a failing TSDoc rule doesn't tear down the watcher on every save.\n tsdoc: options.watch ? false : tsdocOption,\n })\n\n // The hand-written exports define the emitted extensions (`.js`/`.mjs`/`.cjs` per\n // `package.json#type`, enforced by `validateExports`), so the extensions are pinned\n // explicitly instead of relying on tsdown's defaults (whose `fixedExtension` kicks in for\n // `platform: 'node'` and would emit `.mjs` for `type: module` packages).\n const extMap = pkgExtMap[pkg.type === 'module' ? 'module' : 'commonjs']\n const outExtensions: UserConfig['outExtensions'] = ({format: outputFormat}) => ({\n js: outputFormat === 'cjs' ? extMap.commonjs : extMap.esm,\n })\n\n const merged = mergeConfig(base, {\n outExtensions,\n // publint runs during `pkg check` (via its node API), not inside the build\n publint: false,\n // the per-file size report logs through tsdown's info channel; pkg-utils prints its own\n report: false,\n ...(config?.minify === true ? {minify: true} : {}),\n ...(config?.plugins === undefined ? {} : {plugins: config.plugins}),\n ...(options.watch && css ? {hooks: createWatchCssExportsHook(ctx, css)} : {}),\n })\n\n return {\n ...merged,\n config: false,\n logLevel: 'warn',\n ...(options.watch ? {watch: true} : {}),\n }\n}\n\n/**\n * Declares the conditional export of every CSS file a watch rebuild emitted.\n *\n * A full build leaves this to `cssNodeCompatPlugin`, which composes into tsdown's\n * `exports.customExports`. Watch mode turns tsdown's `exports` feature off (a `package.json`\n * write per rebuild would loop the watcher), so `pkg watch` maintains the exports itself. Most\n * of them are known before the build and are written once per context in `watch.ts`, but the\n * merged `style.css` of CSS imported from JS only exists when something actually imports CSS —\n * declaring it from the config alone would point the export at files nobody produced.\n *\n * `build:done` is the only place that knows: in watch mode `build()` resolves before the first\n * rebuild runs, so the returned bundle's chunks are still empty. The write is idempotent, so\n * the `package.json` watcher settles after one extra rebuild rather than looping.\n * @internal\n */\nfunction createWatchCssExportsHook(\n ctx: BuildContext,\n css: NonNullable<PkgConfigOptions['css']>,\n): NonNullable<UserConfig['hooks']> {\n // Only the merged mode has a CSS file name to declare up front. With `splitting` the names\n // follow the chunk names and the export is the host's to wire up, so a full build declares\n // nothing either.\n const mergedCssName = css.splitting ? undefined : css.fileName || 'style.css'\n\n return (hooks) => {\n hooks.hook('build:done', async ({chunks}) => {\n if (mergedCssName === undefined) return\n const emitted = chunks.some(\n (chunk) => chunk.type === 'asset' && chunk.fileName === mergedCssName,\n )\n if (!emitted) return\n\n const {writeBundleCssExports} = await import('../../core/pkg/writeBundleCssExports.ts')\n await writeBundleCssExports({\n cwd: ctx.cwd,\n distPath: ctx.distPath,\n cssNames: [mergedCssName],\n logger: ctx.logger,\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;AAsDA,SAAgB,oBAAoB,KAAkC;CACpE,IAAM,EAAC,QAAQ,KAAK,UAAU,WAAU,KAElC,cAAc,WAA2B;EAC7C,IAAM,QAAQ,KACX,SAAS,UAAU,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAC7C,WAAW,MAAM,GAAG,CAAC,CACrB,QAAQ,YAAY,EAAE;EACzB,IAAI,MAAM,WAAW,IAAI,GACvB,MAAU,MAAM,+CAA+C,QAAQ;EAEzE,OAAO;CACT,GASM,gCAAgB,IAAI,IAAqC,GACzD,iCAAiB,IAAI,IAAwB,GAE7C,YACJ,UACA,SACA,UAMG;EACH,eAAe,IAAI,UAAU,OAAO;EACpC,IAAM,EAAC,QAAQ,eAAc,OACvB,0BAAU,IAAI,IAAY,GAC1B,0BAAU,IAAI,IAAe;EASnC,IARI,MAAM,WACR,QAAQ,IAAI,WAAW,MAAM,MAAM,CAAC,GACpC,QAAQ,IAAI,KA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AAC;EAC7E,CAGU;EACR,QAAQ;EACR,UAAU;EACV,GAAI,QAAQ,QAAQ,EAAC,OAAO,GAAI,IAAI,CAAC;CACvC;AACF;;;;;;;;;;;;;;;;AAiBA,SAAS,0BACP,KACA,KACkC;CAIlC,IAAM,gBAAgB,IAAI,YAAY,KAAA,IAAY,IAAI,YAAY;CAElE,QAAQ,UAAU;EAChB,MAAM,KAAK,cAAc,OAAO,EAAC,aAAY;GAK3C,IAJI,kBAAkB,KAAA,KAIlB,CAHY,OAAO,MACpB,UAAU,MAAM,SAAS,WAAW,MAAM,aAAa,aAE/C,GAAG;GAEd,IAAM,EAAC,0BAAyB,MAAM,OAAO,sCAA0C,CAAA,MAAA,MAAA,EAAA,CAAA;GACvF,MAAM,sBAAsB;IAC1B,KAAK,IAAI;IACT,UAAU,IAAI;IACd,UAAU,CAAC,aAAa;IACxB,QAAQ,IAAI;GACd,CAAC;EACH,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"resolveTsdownConfig-orfQXkE6.js","names":[],"sources":["../src/node/tasks/tsdown/resolveTsdownBuilds.ts","../src/node/core/pkg/cssShimFileName.ts","../src/node/core/pkg/cssExport.ts","../src/node/tasks/tsdown/composeExports.ts","../src/node/tasks/tsdown/resolveTsdownConfig.ts"],"sourcesContent":["import path from 'node:path'\nimport type {PkgFormat, PkgRuntime} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {fileEnding} from '../../core/pkg/pkgExt.ts'\n\n/**\n * One entry of a tsdown build.\n * @internal\n */\nexport interface TsdownBuildEntry {\n /**\n * The entry alias handed to tsdown: the output path relative to `dist` without the\n * extension (e.g. `index`, `index.browser`, `sub/feature`), so the emitted filenames match\n * the hand-written `exports` targets exactly.\n */\n alias: string\n source: string\n /** The hand-written export subpath this entry backs (`undefined` for `bundles`). */\n exportPath?: string\n /** The formats the hand-written exports declare for this entry. */\n formats: PkgFormat[]\n}\n\n/**\n * One tsdown `build()` call of the waterfall. Builds run serially — variants and bundles\n * first, the canonical build last, so its exports generation and publint see every emitted\n * file on disk.\n * @internal\n */\nexport interface TsdownBuild {\n /** Stable identifier, e.g. `neutral`, `browser`, `node`, `bundles`, `css`. */\n key: string\n runtime: PkgRuntime\n /** The canonical build owns `dist` conventions: exports generation runs here. */\n canonical: boolean\n entries: TsdownBuildEntry[]\n /**\n * The stylesheet build: its entries are `.css` files rather than JS, so it emits CSS assets\n * (one per entry) and no JS at all. It runs on its own because a `.css` entry has nothing to\n * declare types for, and because its per-entry CSS output needs `css.splitting`.\n */\n css?: boolean\n}\n\n/** The build key of the stylesheet build. */\nconst CSS_BUILD_KEY = 'css'\n\n/**\n * Collapses the hand-written `exports` map (+ `bundles`) into the per-platform tsdown build\n * waterfall: one canonical build for the package's default runtime, plus a variant build per\n * `browser`/`node` exports condition, plus builds for `bundles` (which must not participate\n * in exports generation).\n * @internal\n */\nexport function resolveTsdownBuilds(ctx: BuildContext): TsdownBuild[] {\n const {config, cwd, distPath, logger} = ctx\n\n const entryAlias = (output: string): string => {\n const alias = path\n .relative(distPath, path.resolve(cwd, output))\n .replaceAll('\\\\', '/')\n .replace(fileEnding, '')\n if (alias.startsWith('..')) {\n throw new Error(`output file is outside the \\`dist\\` folder: ${output}`)\n }\n return alias\n }\n\n interface EntryDraft {\n alias: string\n source: string\n exportPath?: string | undefined\n formats: Set<PkgFormat>\n }\n\n const draftsByBuild = new Map<string, Map<string, EntryDraft>>()\n const runtimeByBuild = new Map<string, PkgRuntime>()\n\n const addEntry = (\n buildKey: string,\n runtime: PkgRuntime,\n entry: {\n source: string\n exportPath?: string | undefined\n import?: string | undefined\n require?: string | undefined\n },\n ) => {\n runtimeByBuild.set(buildKey, runtime)\n const {source, exportPath} = entry\n const aliases = new Set<string>()\n const formats = new Set<PkgFormat>()\n if (entry.import) {\n aliases.add(entryAlias(entry.import))\n formats.add('esm')\n }\n if (entry.require) {\n aliases.add(entryAlias(entry.require))\n formats.add('commonjs')\n }\n if (aliases.size === 0) return\n if (aliases.size > 1) {\n throw new Error(\n `the \\`import\\` and \\`require\\` targets of ${\n exportPath ? `exports[\"${exportPath}\"]` : `the bundle for ${source}`\n } must share a basename (e.g. \\`./dist/index.js\\` + \\`./dist/index.cjs\\`), ` +\n `got: ${entry.import} and ${entry.require}`,\n )\n }\n const [alias] = aliases\n let drafts = draftsByBuild.get(buildKey)\n if (!drafts) {\n drafts = new Map()\n draftsByBuild.set(buildKey, drafts)\n }\n const existing = drafts.get(alias!)\n if (existing) {\n if (existing.source !== source) {\n throw new Error(\n `conflicting sources for the output alias \"${alias}\": ${existing.source} and ${source}`,\n )\n }\n for (const format of formats) existing.formats.add(format)\n return\n }\n drafts.set(alias!, {alias: alias!, source, exportPath, formats})\n }\n\n const exports = Object.entries(ctx.exports || {})\n const packageType = ctx.pkg.type === 'module' ? 'module' : 'commonjs'\n const resolveRuntimeTargets = (condition: {\n import?: string\n require?: string\n default?: string\n }) => ({\n import: condition.import ?? (packageType === 'module' ? condition.default : undefined),\n require: condition.require ?? (packageType === 'commonjs' ? condition.default : undefined),\n })\n\n let hasRuntimeConditions = false\n\n for (const [exportPath, exp] of exports) {\n addEntry('canonical', ctx.runtime, {\n source: exp.source,\n exportPath,\n import: exp.import,\n require: exp.require,\n })\n\n const browserTargets = exp.browser && resolveRuntimeTargets(exp.browser)\n if (exp.browser && browserTargets && (browserTargets.import || browserTargets.require)) {\n hasRuntimeConditions = true\n addEntry('browser', 'browser', {\n source: exp.browser.source || exp.source,\n exportPath,\n ...browserTargets,\n })\n }\n\n const nodeTargets = exp.node && resolveRuntimeTargets(exp.node)\n if (exp.node && nodeTargets && (nodeTargets.import || nodeTargets.require)) {\n hasRuntimeConditions = true\n addEntry('node', 'node', {\n source: exp.node.source || exp.source,\n exportPath,\n ...nodeTargets,\n })\n }\n }\n\n // `bundles` are extra entrypoints that are deliberately not in the exports map (CLI workers\n // and similar), so they build separately from the canonical build — exports generation\n // derives subpaths from every entry of its build, and bundles must never become export\n // subpaths of their own.\n for (const bundle of config?.bundles || []) {\n const runtime = bundle.runtime || ctx.runtime\n addEntry(runtime === ctx.runtime ? 'bundles' : `bundles:${runtime}`, runtime, {\n source: bundle.source,\n import: bundle.import,\n require: bundle.require,\n })\n }\n\n if (hasRuntimeConditions) {\n logger.warn(\n [\n 'The `exports[].browser.source` / `exports[].node.source` pattern is not recommended: every',\n 'runtime condition adds a full extra build (complexity and build time). Consider instead:',\n ' 1. separate npm packages per platform/runtime, selected through export conditions that',\n ' pick the right package per environment,',\n ' 2. when possible, a single neutral build using JS that works in both runtimes without',\n ' special-casing (e.g. `new URL` over `require(\"url\")`, WebCrypto over',\n ' `require(\"crypto\")`), or',\n ' 3. using `tsdown` + `@sanity/tsdown-config` directly, exporting an array from',\n ' `tsdown.config.ts` with one config per `platform` — the fully supported path for',\n ' this level of customization.',\n ].join('\\n'),\n )\n }\n\n const builds: TsdownBuild[] = []\n\n // `.css` export subpaths that declare a `source` build in their own pass: their entries are\n // stylesheets, so the emitted file name follows the export subpath (`./ui/styles.css` ->\n // `dist/ui/styles.css`) instead of an `import`/`require` target, and `dts` has nothing to do.\n const cssEntries: TsdownBuildEntry[] = ctx.cssExports.map((cssExport) => ({\n alias: cssEntryAlias(cssExport._path),\n source: cssExport.source,\n exportPath: cssExport._path,\n formats: ['esm'],\n }))\n if (cssEntries.length) {\n builds.push({\n key: CSS_BUILD_KEY,\n runtime: ctx.runtime,\n canonical: false,\n entries: cssEntries,\n css: true,\n })\n }\n\n const toBuild = (key: string, runtime: PkgRuntime, canonical: boolean): TsdownBuild | null => {\n const drafts = draftsByBuild.get(key)\n if (!drafts || drafts.size === 0) return null\n return {\n key,\n runtime,\n canonical,\n entries: Array.from(drafts.values(), (draft) => ({\n alias: draft.alias,\n source: draft.source,\n ...(draft.exportPath === undefined ? {} : {exportPath: draft.exportPath}),\n formats: Array.from(draft.formats),\n })),\n }\n }\n\n // Variants and bundles run first; the canonical build runs last so its exports generation\n // and publint see the other builds' files on disk. Each build's runtime was recorded when\n // its entries were added, so nothing is re-derived from the build key (a bundle with\n // `runtime: '*'` in a `runtime: 'node'` package must build for `'*'`/neutral).\n for (const key of draftsByBuild.keys()) {\n if (key === 'canonical') continue\n const build = toBuild(key, runtimeByBuild.get(key) ?? ctx.runtime, false)\n if (build) builds.push(build)\n }\n\n const canonical = toBuild('canonical', ctx.runtime, true)\n if (canonical) builds.push(canonical)\n\n return builds\n}\n\n/**\n * The tsdown entry alias of a `.css` export subpath: the subpath without its leading `./` and\n * `.css` ending, so `@tsdown/css` (with `splitting`) emits the stylesheet at exactly the path\n * the subpath promises — `\"./ui/styles.css\"` -> alias `ui/styles` -> `dist/ui/styles.css`.\n */\nfunction cssEntryAlias(exportPath: string): string {\n return exportPath.replace(/^\\.\\//, '').replace(/\\.css$/, '')\n}\n","/**\n * The no-op JS shim file name for a CSS file under vanilla-extract compat mode.\n *\n * `bundle.css` → `bundle-css.js` — deliberately not `${cssFileName}.js` (`bundle.css.js`),\n * which vanilla-extract's `cssFileFilter` (`/\\.css\\.(js|cjs|mjs|jsx|ts|tsx)$/`) would treat as\n * a stylesheet module. Kept in sync with `cssShimFileName` in\n * `@sanity/vanilla-extract-rolldown-plugin`.\n *\n * @internal\n */\nexport function cssShimFileName(cssFileName: string): string {\n return `${cssFileName.replace(/\\.css$/, '-css')}.js`\n}\n\n/**\n * The `.d.ts` companion for {@link cssShimFileName}. `bundle.css` → `bundle-css.d.ts`.\n *\n * @internal\n */\nexport function cssShimDtsFileName(cssFileName: string): string {\n return `${cssFileName.replace(/\\.css$/, '-css')}.d.ts`\n}\n","import path from 'node:path'\nimport {cssShimDtsFileName, cssShimFileName} from './cssShimFileName.ts'\n\n/**\n * Build the conditional CSS export object that `exports.nodeCompat` expects, e.g.\n * ```json\n * {\n * \"types\": \"./dist/bundle-css.d.ts\",\n * \"browser\": \"./dist/bundle.css\",\n * \"style\": \"./dist/bundle.css\",\n * \"node\": \"./dist/bundle-css.js\",\n * \"default\": \"./dist/bundle-css.js\"\n * }\n * ```\n * The shim is named `bundle-css.js` (not `bundle.css.js`) so it does not match\n * vanilla-extract's `cssFileFilter`. An explicit `types` condition (rather than relying on\n * TypeScript's extension-substitution fallback, which only works when the shim shares the CSS\n * file's basename, and which TypeScript is deprecating anyway - microsoft/TypeScript#50762)\n * points resolvers straight at the shim's declaration file.\n *\n * Kept in sync with `createConditionalCssExport` in `@sanity/vanilla-extract-tsdown-plugin`,\n * which writes the same entry through tsdown's `exports.customExports` during full builds.\n *\n * @internal\n */\nexport function createConditionalCssExport(\n cssName: string,\n distRel: string,\n): Record<string, string> {\n const cssFile = `./${path.posix.join(distRel, cssName)}`\n const shimFile = `./${path.posix.join(distRel, cssShimFileName(cssName))}`\n const shimDtsFile = `./${path.posix.join(distRel, cssShimDtsFileName(cssName))}`\n return {types: shimDtsFile, browser: cssFile, style: cssFile, node: shimFile, default: shimFile}\n}\n","import path from 'node:path'\nimport type {PkgExport} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {isRecord} from '../../core/isRecord.ts'\nimport {createConditionalCssExport} from '../../core/pkg/cssExport.ts'\nimport type {TsdownBuild} from './resolveTsdownBuilds.ts'\n\ntype ExportsMap = Record<string, unknown>\ninterface ComposeContext {\n isPublish: boolean\n}\n\n/**\n * The pkg-utils opinion layer over tsdown's generated `exports` map, composed into\n * `exports.customExports` of the canonical build (the same composition hook\n * `@sanity/vanilla-extract-tsdown-plugin` uses for its conditional CSS export).\n *\n * tsdown generates subpaths from the entry aliases with `source`/`import`/`require` conditions\n * (`devExports: 'source'`) and a `source`-less `publishConfig.exports` — already the Sanity\n * convention. This composer reconciles the generated map with the hand-written one, which\n * remains the input:\n *\n * - generated keys are remapped to the hand-written subpaths (entry aliases are derived from\n * the output paths, which don't have to match the subpath names),\n * - the hand-written `types`, `browser`, `node`, `development` and `monorepo` conditions are\n * re-inserted (tsdown's generator cannot express them; the `browser`/`node` files are built\n * by the variant builds of the waterfall) — with `source`-like conditions stripped from the\n * publish variant,\n * - all hand-written conditions (`react-server`, `worker`, … included) retain their authored\n * order in each map independently, because earlier matching conditions take precedence,\n * - generated conditions for conditional entries are materialized in both `exports` and\n * `publishConfig.exports`, so they can be reordered directly in `package.json` and keep that\n * position on later builds (plain-string entries stay compact),\n * - a trailing `default` condition is kept on dual-format entries and nested runtime variants\n * (tsdown emits bare `import`/`require` pairs; the Sanity convention always ends with\n * `default`),\n * - hand-written subpaths that aren't build entries (`.css`/`.json` exports, `svelte`\n * entries) are carried over untouched, and\n * - the hand-written subpath and condition key order of each map is preserved.\n * @internal\n */\nexport function createExportsComposer(\n ctx: BuildContext,\n build: TsdownBuild,\n): (exportsMap: ExportsMap, context: ComposeContext) => ExportsMap {\n const {pkg} = ctx\n const type = pkg.type === 'module' ? 'module' : 'commonjs'\n\n // POSIX separators: on Windows `path.relative` yields backslashes, which must never leak\n // into generated `package.json` export targets.\n const distRel = (path.relative(ctx.cwd, ctx.distPath) || 'dist').split(path.sep).join('/')\n const cssExportPaths = new Set(ctx.cssExports.map((cssExport) => cssExport._path))\n const cssSources: Record<string, string> = {}\n for (const cssExport of ctx.cssExports) {\n cssSources[cssExport._path] = cssExport.source\n }\n\n // alias -> hand-written subpath, e.g. `index` -> `.`, `sub/feature` -> `./feature`\n const aliasToExportPath = new Map<string, string>()\n for (const entry of build.entries) {\n if (entry.exportPath !== undefined) {\n aliasToExportPath.set(entry.alias, entry.exportPath)\n }\n }\n\n return (exportsMap, context) => {\n const {isPublish} = context\n\n // 1. Remap the generated keys (`.` for the `index` alias, `./<alias>` otherwise) back to\n // the hand-written subpaths.\n const remapped: ExportsMap = {}\n for (const [key, value] of Object.entries(exportsMap)) {\n const alias = key === '.' ? 'index' : key.startsWith('./') ? key.slice(2) : key\n const exportPath = aliasToExportPath.get(alias) ?? key\n remapped[exportPath] = value\n }\n\n // 2. Reconcile each generated entry with its hand-written counterpart.\n const result: ExportsMap = {}\n const handwritten = ctx.exports || {}\n const sourceRaw: ExportsMap = pkg.exports || {}\n const publishRaw: ExportsMap | undefined = pkg.publishConfig?.exports\n const authoredRaw = isPublish && publishRaw ? publishRaw : sourceRaw\n\n const reconcile = (exportPath: string, value: unknown): unknown => {\n const exp = handwritten[exportPath]\n if (!exp) return value\n const raw = authoredRaw[exportPath]\n const source = sourceRaw[exportPath]\n // A configured exports map is itself authoritative. Otherwise use the raw package entry\n // for the map being generated. Fall back to `exports` when a new publish map/entry is\n // being generated, so inferred conditions don't masquerade as ordering choices.\n const authored =\n ctx.config?.exports === undefined\n ? isRecord(raw)\n ? raw\n : isRecord(source)\n ? source\n : exp\n : exp\n return reconcileEntry(exp, value, {authored, isPublish, type})\n }\n\n // 3. Follow the hand-written key order of the map being generated. Source-only passthrough\n // subpaths missing from an existing publish map are appended, followed by generated extras.\n const authoredPaths = Object.keys(authoredRaw)\n for (const exportPath of Object.keys(sourceRaw)) {\n if (!Object.prototype.hasOwnProperty.call(authoredRaw, exportPath)) {\n authoredPaths.push(exportPath)\n }\n }\n for (const exportPath of authoredPaths) {\n if (exportPath in remapped) {\n result[exportPath] = reconcile(exportPath, remapped[exportPath])\n } else if (cssExportPaths.has(exportPath)) {\n // A `.css` subpath with a `source` is built by the stylesheet build, which does not\n // participate in exports generation (its entries are stylesheets, not JS). Its\n // conditions are materialized here instead, from the export subpath: `./ui/styles.css`\n // is built to `<dist>/ui/styles.css` with the shim next to it.\n result[exportPath] = reconcileCssEntry(exportPath, {\n distRel,\n source: cssSources[exportPath],\n isPublish,\n })\n } else {\n // Hand-written subpaths that aren't build entries (plain `.css`/`.json` exports,\n // `svelte` entries) pass through untouched.\n result[exportPath] = Object.prototype.hasOwnProperty.call(authoredRaw, exportPath)\n ? authoredRaw[exportPath]\n : sourceRaw[exportPath]\n }\n }\n for (const [exportPath, value] of Object.entries(remapped)) {\n if (exportPath in result) continue\n result[exportPath] = reconcile(exportPath, value)\n }\n\n return result\n }\n}\n\n/**\n * The conditional CSS export of a `.css` subpath built by the stylesheet build. `source`\n * resolves at development time, so it is kept in `exports` and stripped from the publish\n * variant — the same split the build entries get.\n */\nfunction reconcileCssEntry(\n exportPath: string,\n options: {distRel: string; source: string | undefined; isPublish: boolean},\n): Record<string, string> {\n const {distRel, source, isPublish} = options\n const cssName = exportPath.replace(/^\\.\\//, '')\n const conditions = createConditionalCssExport(cssName, distRel)\n return isPublish || source === undefined ? conditions : {source, ...conditions}\n}\n\n/**\n * Rebuilds a generated subpath entry in its authored condition order, re-inserting the\n * hand-written conditions tsdown's generator cannot express.\n */\nfunction reconcileEntry(\n exp: PkgExport,\n generated: unknown,\n options: {authored: object; isPublish: boolean; type: 'commonjs' | 'module'},\n): unknown {\n const {authored, isPublish, type} = options\n const authoredRecord = isRecord(authored) ? authored : {}\n\n // tsdown's publish variant of a single-format entry is a plain string\n const gen: Record<string, unknown> | undefined =\n typeof generated === 'string'\n ? {default: generated}\n : isRecord(generated)\n ? generated\n : undefined\n if (!gen) return generated\n\n const browserOrder = isRecord(authoredRecord['browser']) ? authoredRecord['browser'] : exp.browser\n const browser =\n exp.browser && (exp.browser.import || exp.browser.require || exp.browser.default)\n ? pickConditions(exp.browser, {\n authored: browserOrder ?? exp.browser,\n isPublish,\n type,\n })\n : undefined\n const nodeOrder = isRecord(authoredRecord['node']) ? authoredRecord['node'] : exp.node\n const node =\n exp.node && (exp.node.import || exp.node.require || exp.node.default)\n ? pickConditions(exp.node, {\n authored: nodeOrder ?? exp.node,\n isPublish,\n type,\n })\n : undefined\n const custom = pickCustomConditions(exp)\n\n // Preserve tsdown's compact single-format publish shape unless hand-written conditions need\n // to be re-inserted. There is no condition ordering to preserve in a plain string entry.\n if (typeof generated === 'string' && !exp.types && !browser && !node && custom.length === 0) {\n return generated\n }\n\n const next: Record<string, unknown> = {}\n\n // `source`-like conditions resolve at development time and are stripped from the publish\n // variant (tsdown already does this for `source`; `development`/`monorepo` follow)\n if (!isPublish) {\n if (typeof gen['source'] === 'string') next['source'] = gen['source']\n else if (exp.source) next['source'] = exp.source\n if (exp.development) next['development'] = exp.development\n if (exp.monorepo) next['monorepo'] = exp.monorepo\n }\n\n if (exp.types) next['types'] = exp.types\n if (browser) next['browser'] = browser\n if (node) next['node'] = node\n\n // Hand-written custom conditions (`react-server`, `worker`, …) aren't built, but they are\n // the author's: carry their targets over, then restore every condition's authored position.\n for (const [condition, target] of custom) {\n const authoredTarget = authoredRecord[condition]\n next[condition] =\n isRecord(target) && isRecord(authoredTarget)\n ? preserveConditionOrder(target, authoredTarget)\n : target\n }\n\n if (typeof gen['import'] === 'string' && typeof gen['require'] === 'string') {\n next['import'] = gen['import']\n next['require'] = gen['require']\n // tsdown emits bare `import`/`require` pairs; the Sanity convention ends with `default`\n next['default'] = type === 'module' ? gen['import'] : gen['require']\n } else {\n // Single-format entries keep the generated shape (`{source, default}` in development)\n for (const [condition, target] of Object.entries(gen)) {\n if (condition in next || condition === 'source') continue\n next[condition] = target\n }\n }\n\n return preserveConditionOrder(next, authored)\n}\n\n/**\n * The hand-written `browser`/`node` condition object, minus `source` for the publish map.\n * A nested runtime condition must have its own fallback: once a resolver matches `node` or\n * `browser`, an unmatched module-format condition otherwise backtracks to the outer entry.\n */\nfunction pickConditions(\n conditions: {source?: string; import?: string; require?: string; default?: string},\n options: {\n authored?: object\n isPublish: boolean\n type: 'commonjs' | 'module'\n },\n): Record<string, string> {\n const {authored = conditions, isPublish, type} = options\n const next: Record<string, string> = {}\n if (!isPublish && conditions.source) next['source'] = conditions.source\n if (conditions.import) next['import'] = conditions.import\n if (conditions.require) next['require'] = conditions.require\n const fallback =\n conditions.default ?? (type === 'module' ? conditions.import : conditions.require)\n if (fallback) next['default'] = fallback\n return preserveConditionOrder(next, authored)\n}\n\n/**\n * Reorders reconciled conditions to match their hand-written order. Conditions generated by\n * tsdown but absent from the hand-written entry are inserted before its `default` fallback.\n */\nfunction preserveConditionOrder<T>(\n conditions: Record<string, T>,\n authored: object,\n): Record<string, T> {\n const entries: [string, T][] = []\n const added = new Set<string>()\n const conditionEntries = Object.entries(conditions)\n const entriesByCondition = new Map(conditionEntries.map((entry) => [entry[0], entry]))\n const authoredOrder = Object.keys(authored).filter((condition) => !condition.startsWith('_'))\n const authoredConditions = new Set(authoredOrder)\n\n const addGeneratedConditions = () => {\n for (const entry of conditionEntries) {\n if (!authoredConditions.has(entry[0]) && !added.has(entry[0])) {\n entries.push(entry)\n added.add(entry[0])\n }\n }\n }\n\n for (const condition of authoredOrder) {\n // A generated condition has no authored position. Keep the explicit `default` as the final\n // fallback by placing generated conditions immediately before it.\n if (condition === 'default') addGeneratedConditions()\n const entry = entriesByCondition.get(condition)\n if (!entry) continue\n entries.push(entry)\n added.add(condition)\n }\n\n addGeneratedConditions()\n\n return Object.fromEntries(entries)\n}\n\n/** The conditions the pipeline owns (or re-inserts itself) on a build entry. */\nconst managedConditions = new Set([\n 'source',\n 'development',\n 'monorepo',\n 'types',\n 'browser',\n 'node',\n 'import',\n 'require',\n 'default',\n])\n\n/**\n * Hand-written conditions the pipeline knows nothing about (`react-server`, `worker`,\n * `edge-light`, …), in authored order. `parseExports` spreads the raw entry, so they survive\n * on the parsed `PkgExport` beyond its typed fields.\n */\nfunction pickCustomConditions(exp: PkgExport): [string, unknown][] {\n return Object.entries(exp).filter(\n ([condition, target]) =>\n !managedConditions.has(condition) && !condition.startsWith('_') && target !== undefined,\n )\n}\n","import path from 'node:path'\nimport {\n defineConfig,\n type ReactCompilerOptions as TsdownConfigReactCompilerOptions,\n} from '@sanity/tsdown-config'\nimport {mergeConfig, type InlineConfig, type UserConfig} from 'tsdown'\nimport type {PkgConfigOptions} from '../../core/config/types.ts'\nimport type {BuildContext} from '../../core/contexts/buildContext.ts'\nimport {pkgExtMap} from '../../core/pkg/pkgExt.ts'\nimport {createExportsComposer} from './composeExports.ts'\nimport type {TsdownBuild} from './resolveTsdownBuilds.ts'\n\nconst RE_TS_SOURCE = /\\.[cm]?tsx?$/\n\nfunction hasNativePreview(pkg: {devDependencies?: unknown}): boolean {\n return (\n typeof pkg.devDependencies === 'object' &&\n pkg.devDependencies !== null &&\n '@typescript/native-preview' in pkg.devDependencies\n )\n}\n\n/**\n * Composes the tsdown config for one build of the waterfall: `@sanity/tsdown-config`'s\n * `defineConfig()` provides the shared Sanity base, and the pkg-utils opinions (browserslist\n * targets, `PKG_*` defines, exports reconciliation, dts selection) layer over it with\n * tsdown's `mergeConfig`.\n *\n * pkg-utils owns its own experience: the returned config carries `config: false`, so tsdown\n * never loads `tsdown.config.*` files — `package.config.ts` is the sole config source — and\n * `logLevel: 'warn'` keeps tsdown's info chatter out of pkg-utils' own output.\n * @internal\n */\nexport async function resolveTsdownConfig(\n ctx: BuildContext,\n build: TsdownBuild,\n options: {\n /**\n * Whether this build may clean: only the first build of the waterfall cleans (so later\n * builds can't wipe earlier output), and `--no-clean` turns it off for the whole run.\n */\n clean: boolean\n watch?: boolean\n },\n): Promise<InlineConfig> {\n const {config, cwd, distPath, pkg} = ctx\n\n // `?? false` up front (like tsdown-config's own normalization): JS configs bypass the\n // types, and a `reactCompiler: null` would pass the `typeof … === 'object'` checks below\n const reactCompiler = config?.reactCompiler ?? false\n if (typeof reactCompiler === 'object' && reactCompiler.reactServer === true) {\n throw new Error(\n [\n 'package.config.ts: `reactCompiler.reactServer` is not supported by `pkg build` — the',\n 'dual React Server Components build needs one tsdown run driving multiple configs.',\n 'Use `tsdown` + `@sanity/tsdown-config` directly instead: export the config from',\n '`tsdown.config.ts` and build with `tsdown`.',\n ].join('\\n'),\n )\n }\n // Pin the `'babel'` default before forwarding: `@sanity/tsdown-config` defaults to `'oxc'`\n // since 0.27, and inheriting the flip would break published configs.\n const reactCompilerOption: TsdownConfigReactCompilerOptions | boolean =\n typeof reactCompiler === 'object'\n ? reactCompiler.transform === 'oxc'\n ? reactCompiler\n : {...reactCompiler, transform: 'babel'}\n : reactCompiler\n ? {transform: 'babel'}\n : false\n\n const entry: Record<string, string> = {}\n for (const buildEntry of build.entries) {\n entry[buildEntry.alias] = buildEntry.source\n }\n\n // tsdown's `format` applies to the whole build (and its exports generation composes the\n // dual `import`/`require` map from both formats' chunks of one build), so the entries'\n // formats union: every entry is emitted in every format of the build. Mixed per-entry\n // coverage gets a heads-up — the extra files are emitted, and local exports generation\n // will declare them.\n const formats = new Set(build.entries.flatMap((buildEntry) => buildEntry.formats))\n if (formats.size > 1) {\n const partial = build.entries.filter((buildEntry) => buildEntry.formats.length < formats.size)\n if (partial.length) {\n const names = partial\n .map((buildEntry) =>\n buildEntry.exportPath ? `exports[\"${buildEntry.exportPath}\"]` : buildEntry.source,\n )\n .join(', ')\n ctx.logger.warn(\n `${names} declare${partial.length === 1 ? 's' : ''} fewer formats than the rest of the package. tsdown emits every format of a build for every entry, so the missing format is built anyway (and local exports generation will declare it). Declare both \\`import\\` and \\`require\\` targets for every subpath — or for none — to keep the exports map unambiguous.`,\n )\n }\n }\n const format = [\n ...(formats.has('esm') ? ['esm' as const] : []),\n ...(formats.has('commonjs') ? ['cjs' as const] : []),\n ]\n\n const platform =\n build.runtime === 'node' ? 'node' : build.runtime === 'browser' ? 'browser' : 'neutral'\n\n // The `@tsdown/css` pipeline turns on when it's configured, and automatically for a package\n // that declares a `.css` export subpath with a `source`. The stylesheet build needs\n // `splitting` so each entry emits its own file at the path its subpath promises; the JS\n // builds keep `@tsdown/css`'s merged default, so CSS imported from JS lands in a single\n // `style.css` with one export and one injected import - the `bundle.css` shape of\n // `vanillaExtract`.\n const css: PkgConfigOptions['css'] | undefined =\n config?.css || ctx.cssExports.length\n ? {...config?.css, ...(build.css ? {splitting: true} : {})}\n : undefined\n\n // Build-time constants: `PKG_VERSION` reads the environment override first, like v11.\n // pkg-utils' own build skips it so the replacement logic in this very file survives its own\n // bundling. (`PKG_FORMAT`, `PKG_RUNTIME` and `PKG_FILE_PATH` were removed in v12 — see\n // MIGRATE.md for the `package.json#imports` / `import.meta.url` replacements.)\n const define: Record<string, string> = {}\n if (pkg.name !== '@sanity/pkg-utils') {\n define['process.env.PKG_VERSION'] = JSON.stringify(process.env['PKG_VERSION'] || pkg.version)\n }\n for (const [key, value] of Object.entries(config?.define || {})) {\n define[key] = JSON.stringify(value)\n }\n\n const hasTsSources =\n !build.css && build.entries.some((buildEntry) => RE_TS_SOURCE.test(buildEntry.source))\n const dtsObject = typeof config?.dts === 'object' ? config.dts : undefined\n const nativePreviewGenerator = hasNativePreview(pkg) ? ({generator: 'tsgo'} as const) : undefined\n const dts =\n hasTsSources && config?.dts !== false\n ? {\n ...nativePreviewGenerator,\n newContext: true,\n ...dtsObject,\n ...(ctx.emitDeclarationOnly ? {emitDtsOnly: true} : {}),\n }\n : false\n\n // Exports generation runs on the canonical build only, with `devExports: 'source'` — the\n // hand-written Sanity convention (`source` conditions in `exports`, a `source`-less\n // `publishConfig.exports`) — and the pkg-utils composer reconciling the generated map with\n // the hand-written one. `@sanity/tsdown-config`'s always-on exports default applies: the map\n // is rewritten on every build (CI included), so environments that set `CI=true` without\n // meaning \"skip package.json\" (Cursor Cloud, …) still keep exports in sync. A types-only\n // build never rewrites `package.json`, and neither do watch builds (a rewrite would\n // re-trigger the `package.json` watcher).\n const exports: UserConfig['exports'] =\n build.canonical && !ctx.emitDeclarationOnly && !options.watch && !build.css\n ? {\n devExports: 'source',\n customExports: createExportsComposer(ctx, build),\n // Keep the hand-written legacy fields (`main`/`module`) in sync instead of deleting\n // them; packages without them don't gain them\n ...(pkg.main || pkg.module ? {legacy: true} : {}),\n }\n : false\n\n // `@sanity/tsdown-config` defaults `tsdoc` to `false`; pkg-utils keeps the historical\n // default of enabled (`true`), and forwards an options object (with `bundledPackages` for\n // API Extractor's type resolution of inlined deps) when the user customized rules/tags.\n const tsdocOption =\n config?.tsdoc === false\n ? false\n : {\n ...(typeof config?.tsdoc === 'object' ? config.tsdoc : {}),\n bundledPackages: ctx.bundledPackages,\n }\n\n const base = await defineConfig({\n cwd,\n tsconfig: ctx.ts.configPath,\n platform,\n format,\n entry,\n // POSIX separators: on Windows `path.relative` yields backslashes, which would leak into\n // generated `package.json` export targets (e.g. the conditional vanilla-extract export)\n outDir: path.relative(cwd, distPath).replaceAll('\\\\', '/') || '.',\n target: ctx.target[build.runtime],\n define,\n sourcemap: config?.sourcemap,\n // tsdown owns cleaning: the first build of the waterfall carries the effective `clean`\n // (the config passthrough, or tsdown's default `true`), every later build gets `false`.\n // A types-only build never cleans, so it can't delete JS output.\n clean: options.clean && !ctx.emitDeclarationOnly ? config?.clean : false,\n dts,\n deps: ctx.deps,\n exports,\n css,\n reactCompiler: reactCompilerOption,\n styledComponents: config?.styledComponents,\n vanillaExtract: config?.vanillaExtract,\n bundleAnalyzer: config?.bundleAnalyzer,\n // Types-only builds still emit `.d.ts` files that deserve the check; watch mode skips it\n // so a failing TSDoc rule doesn't tear down the watcher on every save.\n tsdoc: options.watch ? false : tsdocOption,\n })\n\n // The hand-written exports define the emitted extensions (`.js`/`.mjs`/`.cjs` per\n // `package.json#type`, enforced by `validateExports`), so the extensions are pinned\n // explicitly instead of relying on tsdown's defaults (whose `fixedExtension` kicks in for\n // `platform: 'node'` and would emit `.mjs` for `type: module` packages).\n const extMap = pkgExtMap[pkg.type === 'module' ? 'module' : 'commonjs']\n const outExtensions: UserConfig['outExtensions'] = ({format: outputFormat}) => ({\n js: outputFormat === 'cjs' ? extMap.commonjs : extMap.esm,\n })\n\n const merged = mergeConfig(base, {\n outExtensions,\n // publint runs during `pkg check` (via its node API), not inside the build\n publint: false,\n // the per-file size report logs through tsdown's info channel; pkg-utils prints its own\n report: false,\n ...(config?.minify === true ? {minify: true} : {}),\n ...(config?.plugins === undefined ? {} : {plugins: config.plugins}),\n ...(options.watch && css ? {hooks: createWatchCssExportsHook(ctx, css)} : {}),\n })\n\n return {\n ...merged,\n config: false,\n logLevel: 'warn',\n ...(options.watch\n ? {\n watch: true,\n // tsdown restarts itself on these paths and discards the handle pkg-utils\n // holds. pkg watch reloads the waterfall instead.\n ignoreWatch: [path.join(cwd, 'package.json'), ctx.ts.configPath ?? 'tsconfig.json'],\n }\n : {}),\n }\n}\n\n/** @internal */\nfunction createWatchCssExportsHook(\n ctx: BuildContext,\n css: NonNullable<PkgConfigOptions['css']>,\n): NonNullable<UserConfig['hooks']> {\n // Only the merged mode has a CSS file name to declare up front. With `splitting` the names\n // follow the chunk names and the export is the host's to wire up, so a full build declares\n // nothing either.\n const mergedCssName = css.splitting ? undefined : css.fileName || 'style.css'\n\n return (hooks) => {\n hooks.hook('build:done', async ({chunks}) => {\n if (mergedCssName === undefined) return\n const emitted = chunks.some(\n (chunk) => chunk.type === 'asset' && chunk.fileName === mergedCssName,\n )\n if (!emitted) return\n\n const {writeBundleCssExports} = await import('../../core/pkg/writeBundleCssExports.ts')\n await writeBundleCssExports({\n cwd: ctx.cwd,\n distPath: ctx.distPath,\n cssNames: [mergedCssName],\n logger: ctx.logger,\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;AAsDA,SAAgB,oBAAoB,KAAkC;CACpE,IAAM,EAAC,QAAQ,KAAK,UAAU,WAAU,KAElC,cAAc,WAA2B;EAC7C,IAAM,QAAQ,KACX,SAAS,UAAU,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,CAC7C,WAAW,MAAM,GAAG,CAAC,CACrB,QAAQ,YAAY,EAAE;EACzB,IAAI,MAAM,WAAW,IAAI,GACvB,MAAU,MAAM,+CAA+C,QAAQ;EAEzE,OAAO;CACT,GASM,gCAAgB,IAAI,IAAqC,GACzD,iCAAiB,IAAI,IAAwB,GAE7C,YACJ,UACA,SACA,UAMG;EACH,eAAe,IAAI,UAAU,OAAO;EACpC,IAAM,EAAC,QAAQ,eAAc,OACvB,0BAAU,IAAI,IAAY,GAC1B,0BAAU,IAAI,IAAe;EASnC,IARI,MAAM,WACR,QAAQ,IAAI,WAAW,MAAM,MAAM,CAAC,GACpC,QAAQ,IAAI,KAAK,IAEf,MAAM,YACR,QAAQ,IAAI,WAAW,MAAM,OAAO,CAAC,GACrC,QAAQ,IAAI,UAAU,IAEpB,QAAQ,SAAS,GAAG;EACxB,IAAI,QAAQ,OAAO,GACjB,MAAU,MACR,6CACE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