@fastkit/plugboy 1.5.0 → 1.6.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/README.md +38 -18
- package/dist/cli.mjs +2 -2
- package/dist/plugboy.d.mts +86 -6
- package/dist/plugboy.mjs +2 -2
- package/dist/{workspace-Dngfi1p6.mjs → workspace-DdhCZjQE.mjs} +218 -60
- package/dist/workspace-DdhCZjQE.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/workspace-Dngfi1p6.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workspace-DdhCZjQE.mjs","names":["fs","fs","fs","fs","fs","fs","fs","fs","fs","fs","fs"],"sources":["../src/types/hook.ts","../src/types/dts.ts","../src/types/css.ts","../src/types/workspace.ts","../src/types/project.ts","../src/utils/general.ts","../src/utils/tsdown.ts","../src/utils/exit-hook.ts","../src/utils/dts-source-map.ts","../src/utils/bundled-config.ts","../src/utils/file.ts","../src/utils/expose.ts","../src/constants.ts","../src/utils/project.ts","../src/utils/plugin.ts","../src/utils/workspace.ts","../src/utils/hook.ts","../src/path.ts","../src/package.ts","../src/workspace/dts.ts","../src/env/constants.ts","../src/env/utils.ts","../src/env/plugin.ts","../src/workspace/builder.ts","../src/project/project.ts","../src/workspace/stylesheets.ts","../src/postcss/plugin.ts","../src/workspace/chunk-order.ts","../src/workspace/plugins/assemble-entry-css.ts","../src/workspace/plugins/raw-loader.ts","../src/workspace/plugins/preserve-css-imports.ts","../src/workspace/plugins/external-imports.ts","../src/workspace/plugins/suppress-dts-sourcemap-warning.ts","../src/workspace/workspace.ts","../src/workspace/generate.ts"],"sourcesContent":["import type { Listable } from '../utils';\nimport { WorkspaceSetupContext, WorkspacePackageJson } from './workspace';\nimport type { PlugboyWorkspace } from '../workspace';\n\nexport type TryGetWorkspace = () => PlugboyWorkspace | undefined;\n\n/** plugboy hook definition */\nexport interface HookTypes {\n /**\n * Hooks during workspace setup\n * @remarks Called just before the workspace instance is created\n * @param ctx - {@link WorkspaceSetupContext Workspace setup context object}\n */\n setupWorkspace: (\n ctx: WorkspaceSetupContext,\n getWorkspace: TryGetWorkspace,\n ) => any;\n /**\n * Hooks after workspace generation\n * @param workspace - {@link PlugboyWorkspace workspace instance}\n */\n createWorkspace: (workspace: PlugboyWorkspace) => any;\n /**\n * Hooks when correcting package.json\n * @param json - package.json just before it was modified and saved by the plugboy\n * @param workspace - {@link PlugboyWorkspace workspace instance}\n */\n preparePackageJSON: (\n json: WorkspacePackageJson,\n workspace: PlugboyWorkspace,\n ) => any;\n}\n\nexport function createHooksDefaults(): ResolvedHooks {\n return {\n setupWorkspace: [],\n createWorkspace: [],\n preparePackageJSON: [],\n };\n}\n\nexport type HookName = keyof HookTypes;\n\n/**\n * plugboy user hook definition\n * @see {@link HookTypes}\n */\nexport type UserHooks = {\n [Name in HookName]?: Listable<HookTypes[Name]>;\n};\n\n/**\n * Pre-setup hook definitions\n * @see {@link HookTypes}\n */\nexport type ResolvedHooks = {\n [Name in HookName]: HookTypes[Name][];\n};\n\nexport type HookArgs<Name extends HookName> = Parameters<HookTypes[Name]>;\n\nexport type UnPromisify<T> = T extends Promise<infer U> ? U : T;\n\nexport type HookReturnType<Name extends HookName> = UnPromisify<\n ReturnType<HookTypes[Name]>\n>;\n\n/**\n * Map of hook methods that can be initialized and called\n * @see {@link HookTypes}\n */\nexport type BuildedHooks = {\n [Name in HookName]: (\n ...args: HookArgs<Name>\n ) => Promise<HookReturnType<Name>>;\n};\n","import type { Builder } from '../workspace';\nimport type { PlugboyWorkspace } from '../workspace';\n\nexport interface EmitDTSOptions {\n cwd?: string;\n outDir?: string;\n}\n\n/**\n * Custom DTS compiler function\n */\nexport type DTSCompilerFunction = (\n opts: EmitDTSOptions & { workspace: PlugboyWorkspace },\n) => Promise<void>;\n\n/**\n * DTS compiler specification\n * - 'tsc': TypeScript compiler (default)\n * - 'vue-tsc': Vue SFC compatible compiler\n * - function: Custom compiler function\n */\nexport type DTSCompilerOption = 'tsc' | 'vue-tsc' | DTSCompilerFunction;\n\n/**\n * Type preservation target in declaration file\n */\nexport interface DTSPreserveTypeTarget {\n /** Type name */\n typeName: string;\n /**\n * String to be restored or regular expression to match\n */\n from: string | RegExp;\n}\n\n/**\n * Type preservation target in declaration file (normalized)\n *\n * @see {@link DTSPreserveTypeTarget}\n */\nexport interface NormalizedDTSPreserveTypeTarget extends Omit<\n DTSPreserveTypeTarget,\n 'from'\n> {\n /** Regular expression to match the string to be restored */\n from: RegExp;\n}\n\nexport function normalizeDTSPreserveTypeTarget(\n target: DTSPreserveTypeTarget,\n): NormalizedDTSPreserveTypeTarget {\n const { from, typeName } = target;\n return {\n from: typeof from === 'string' ? new RegExp(`${from}`, 'g') : from,\n typeName,\n };\n}\n\n/**\n * Type preservation setting for declaration files\n *\n * @remarks This setting is for restoring type information inlined by the TypeScript compiler to the original type name by string substitution.\n */\nexport interface DTSPreserveTypeSettings {\n /** Name of the package to which the type to be restored belongs */\n pkg?: string;\n /** List of preservation targets */\n targets: DTSPreserveTypeTarget[];\n}\n\n/**\n * Type preservation setting for declaration files (normalized)\n *\n * @see {@link DTSPreserveTypeSettings}\n */\nexport interface NormalizedDTSPreserveTypeSettings extends Omit<\n DTSPreserveTypeSettings,\n 'targets'\n> {\n /** List of normalized type preservation targets */\n targets: NormalizedDTSPreserveTypeTarget[];\n}\n\nexport function normalizeDTSPreserveTypeSettings(\n settings: DTSPreserveTypeSettings,\n): NormalizedDTSPreserveTypeSettings {\n return {\n ...settings,\n targets: settings.targets.map(normalizeDTSPreserveTypeTarget),\n };\n}\n\n/**\n * Function to normalize declaration strings\n * @param dts - Bundled declaration strings\n * @param builder - Builder\n */\nexport type DTSNormalizer = (\n dts: string,\n builder: Builder,\n) => string | undefined | void | Promise<string | undefined | void>;\n\n/**\n * declaration output setting\n */\nexport interface DTSSettings {\n /**\n * Inline output without bundling declaration\n *\n * @default false\n */\n inline?: boolean;\n\n /**\n * DTS compiler specification\n * @default 'tsc'\n */\n compiler?: DTSCompilerOption;\n\n /**\n * Whether to ignore compiler errors and continue\n * @default false\n */\n ignoreCompilerErrors?: boolean;\n\n /**\n * list of type preservation settings\n *\n * @remarks This setting is for restoring type information inlined by the TypeScript compiler to the original type name by string substitution.\n *\n * @see {@link DTSPreserveTypeSettings}\n */\n preserveType?: DTSPreserveTypeSettings[];\n\n /**\n * list of function to normalize declaration strings\n */\n normalizers?: DTSNormalizer[];\n}\n\n/**\n * declaration output setting (normalized)\n *\n * @see {@link DTSSettings}\n */\nexport interface NormalizedDTSSettings {\n /**\n * Inline output without bundling declaration\n */\n inline: boolean;\n\n /**\n * DTS compiler specification\n */\n compiler: DTSCompilerOption;\n\n /**\n * Whether to ignore compiler errors and continue\n */\n ignoreCompilerErrors: boolean;\n\n /**\n * list of type preservation settings\n */\n preserveType: NormalizedDTSPreserveTypeSettings[];\n\n /**\n * list of function to normalize declaration strings\n */\n normalizers: DTSNormalizer[];\n}\n\nexport function normalizeDTSSettings(\n settings: DTSSettings,\n): NormalizedDTSSettings {\n const {\n inline = false,\n compiler = 'tsc',\n ignoreCompilerErrors = false,\n preserveType = [],\n normalizers = [],\n } = settings || {};\n return {\n inline,\n compiler,\n ignoreCompilerErrors,\n preserveType: preserveType.map(normalizeDTSPreserveTypeSettings),\n normalizers,\n };\n}\n\nexport function mergeDTSSettingsList(\n ...settingsList: (DTSSettings | undefined)[]\n): NormalizedDTSSettings {\n const merged: DTSSettings = {};\n settingsList.forEach((settings) => {\n if (!settings) return;\n const { inline, preserveType, normalizers } = settings;\n if (inline !== undefined) merged.inline = inline;\n if (preserveType) {\n merged.preserveType = merged.preserveType || [];\n merged.preserveType.push(...preserveType);\n }\n if (normalizers) {\n merged.normalizers = merged.normalizers || [];\n merged.normalizers.push(...normalizers);\n }\n });\n return normalizeDTSSettings(merged);\n}\n","import type { Options } from 'cssnano';\nimport {\n OptimizeLayerOptions,\n OptimizeMediaOptions,\n CombineRulesOptions,\n} from '../postcss';\n\n/**\n * CSS optimization options\n */\nexport interface OptimizeCSSOptions {\n /**\n * Layer optimization options\n *\n * Disable the operation with `false`.\n *\n * @default true\n */\n layer?: OptimizeLayerOptions | boolean;\n /**\n * Media Query Optimization Options\n *\n * Disable the operation with `false`.\n *\n * @default true\n */\n media?: OptimizeMediaOptions | boolean;\n /**\n * Combine rules Options\n *\n * If unset, no optimization is performed\n */\n combineRules?: CombineRulesOptions;\n /**\n * Options for [cssnano](https://cssnano.co/)\n *\n * Disable the operation with `false`.\n *\n * @default { preset: ['default', { normalizeWhitespace: false }] }\n */\n cssnano?: Options | boolean;\n}\n\nexport interface ResolvedOptimizeCSSOptions {\n layer?: OptimizeLayerOptions;\n media?: OptimizeMediaOptions;\n combineRules?: CombineRulesOptions;\n cssnano?: Options;\n}\n\nexport function resolveOptimizeCSSOptions(options: OptimizeCSSOptions) {\n const resolved: ResolvedOptimizeCSSOptions = {};\n const { layer = true, media = true, combineRules, cssnano = true } = options;\n if (layer !== false) {\n resolved.layer = layer === true ? {} : layer;\n }\n if (media !== false) {\n resolved.media = media === true ? {} : media;\n }\n if (combineRules) {\n resolved.combineRules = combineRules;\n }\n if (cssnano !== false) {\n resolved.cssnano =\n cssnano === true\n ? { preset: ['default', { normalizeWhitespace: false }] }\n : cssnano;\n }\n return resolved;\n}\n","import type { UserConfig as TSDownConfig } from 'tsdown';\nimport type { Path } from '../path';\nimport { RequiredPackageJSON, MarkRequired } from './_utils';\nimport type { PlugboyProject } from '../project';\nimport type { UserPluginOption, Plugin } from './plugin';\nimport type { BuildedHooks, UserHooks } from './hook';\nimport { DTSSettings, NormalizedDTSSettings } from './dts';\nimport { OptimizeCSSOptions } from './css';\nimport type { ExternalOption } from '../types';\nimport { type NoExternalOption } from './tsdown';\nimport { type CssOptions } from '@tsdown/css';\n\nexport const WORKSPACE_REQUIRED_FIELDS = ['name', 'version'] as const;\n\ntype WorkspaceRequiredField = (typeof WORKSPACE_REQUIRED_FIELDS)[number];\n\n/**\n * Entry setting object\n */\nexport interface RawWorkspaceEntryObject {\n /**\n * Entry file path\n * @remarks It must be relative to the root directory of the workspace.\n */\n src: string;\n /**\n * Set to true if the entry outputs css at the same time\n * @remarks By doing this, the exports field in package.json will be set automatically.\n */\n css?: boolean;\n}\n\n/**\n * Entry setting object\n */\nexport type WorkspaceEntry = MarkRequired<\n RawWorkspaceEntryObject,\n 'src' | 'css'\n>;\n\nexport type RawWorkspaceEntry = string | RawWorkspaceEntryObject;\n\n/**\n * Configuration of all entries in the workspace (normalized)\n *\n * @see {@link RawWorkspaceEntries}\n */\nexport type WorkspaceEntries = Record<string, WorkspaceEntry>;\n\n/**\n * Configuration of all entries in the workspace\n *\n * @remarks The configuration must be `{ [id]: [Entry setting: }`. `\".\" ` is treated as a special ID and is the target of the main export.\n */\nexport type RawWorkspaceEntries = Record<string, RawWorkspaceEntry>;\n\nexport const TSDOWN_SYNC_OPTIONS = [\n 'define',\n 'skipNodeModulesBundle',\n 'onSuccess',\n 'copy',\n 'deps',\n 'target',\n] as const satisfies (keyof TSDownConfig)[];\n\ntype TSDownSyncOption = (typeof TSDOWN_SYNC_OPTIONS)[number];\n\ninterface TSDownSyncOptions extends Pick<TSDownConfig, TSDownSyncOption> {}\n\n/**\n * Workspace User Configuration\n */\nexport interface UserWorkspaceConfig extends TSDownSyncOptions {\n /**\n * Ignore project settings\n *\n * @remarks Normally, when processing a workspace, plugboy looks for and merges the settings of the entire project at the same time, but this action can be canceled.\n */\n ignoreProjectConfig?: boolean;\n /**\n * Configuration of all entries in the workspace\n *\n * @see {@link RawWorkspaceEntries}\n */\n entries?: RawWorkspaceEntries;\n /**\n * Hook Setting\n * @see {@link UserHooks}\n */\n hooks?: UserHooks;\n /**\n * Plug-in List\n * @see {@link UserPluginOption}\n */\n plugins?: UserPluginOption[];\n /**\n * declaration output setting\n * @see {@link DTSSettings}\n */\n dts?: DTSSettings;\n /**\n * Directory whose contents are copied into the output directory (`dist`).\n *\n * Owned by plugboy (not tsdown's `copy`) so the copy is performed identically\n * in both `build` and `stub`. Use tsdown's `copy` for advanced cases that\n * only need to run during a real build.\n *\n * - `true` (default): copy `./public`\n * - `false`: disable\n * - string: copy the given directory\n *\n * @default true\n */\n publicDir?: string | boolean;\n /**\n * tsdown's `copy` option — copy files into the output directory.\n *\n * @remarks\n * Runs during `build` only. `stub` does NOT execute this (it does not run\n * tsdown). For assets that must also be present in the stub output, use\n * {@link publicDir}, which plugboy copies identically in both `build` and\n * `stub`.\n */\n copy?: TSDownConfig['copy'];\n /**\n * tsdown's `target` option — the environment(s) the output syntax is\n * downleveled for.\n *\n * @remarks\n * Inherited from the project configuration when omitted. A value set here\n * replaces the project default outright (a target list describes one\n * environment set, so merging the two would be meaningless).\n *\n * Note that this only lowers *syntax*; runtime APIs are never polyfilled.\n * Unset at both layers, tsdown falls back to `engines.node` of the package,\n * and applies no transformation at all when that field is absent.\n *\n * @example `['node20.19', 'chrome111']`\n */\n target?: TSDownConfig['target'];\n /**\n * tsdown's `css` option — how stylesheets are processed and emitted.\n *\n * @remarks\n * Shallow-merged over the project configuration, so a workspace only needs to\n * restate the keys it changes.\n *\n * In a workspace with `css: true` entries, plugboy turns `splitting` on and\n * builds each declared `./<entry>.css` itself, in dependency order;\n * `fileName` names the stylesheet of a single CSS entry. Declaring `splitting`\n * leaves the merge to tsdown as written, which concatenates chunks in bundle\n * order — leave it unset unless that is what you want.\n *\n * Plugins may seed other defaults here during workspace setup. A value declared\n * in the configuration always wins over such a default.\n *\n * `css.target` defaults to {@link UserWorkspaceConfig.target}.\n *\n * @see {@link CssOptions}\n */\n css?: CssOptions;\n /**\n * CSS optimization options\n *\n * Disable the operation with `false`.\n *\n * @default true\n *\n * @see {@link OptimizeCSSOptions}\n */\n optimizeCSS?: OptimizeCSSOptions | boolean;\n}\n\n/**\n * Workspace Configuration\n */\nexport interface ResolvedWorkspaceConfig\n extends\n Required<\n Omit<\n UserWorkspaceConfig,\n | 'entries'\n | 'hooks'\n | 'plugins'\n | 'dts'\n | 'publicDir'\n | 'optimizeCSS'\n | 'css'\n | TSDownSyncOption\n >\n >,\n TSDownSyncOptions {\n /**\n * Configuration of all entries in the workspace\n *\n * @see {@link WorkspaceEntries}\n */\n entries: WorkspaceEntries;\n /**\n * Hook Setting\n * @see {@link UserHooks}\n */\n hooks?: UserHooks;\n /**\n * Plug-in List\n * @see {@link UserPluginOption}\n */\n plugins: Plugin[];\n /**\n * declaration output setting\n * @see {@link DTSSettings}\n */\n dts?: DTSSettings;\n /**\n * Directory whose contents are copied into the output directory (`dist`),\n * or `false` to disable. Resolved from {@link UserWorkspaceConfig.publicDir}\n * (`true` → `'public'`).\n */\n publicDir: string | false;\n /**\n * tsdown's `css` option — how stylesheets are processed and emitted.\n *\n * @see {@link CssOptions}\n */\n css?: CssOptions;\n /**\n * CSS optimization options\n *\n * Disable the operation with `false`.\n *\n * @see {@link OptimizeCSSOptions}\n */\n optimizeCSS: OptimizeCSSOptions | false;\n}\n\nexport type WorkspacePackageJson = RequiredPackageJSON<WorkspaceRequiredField>;\n\n/**\n * Workspace Directory Settings\n */\nexport interface WorkspaceDirs {\n /** Path instance of the source directory */\n src: Path;\n /** Path instance of the distribution directory */\n dist: Path;\n}\n\n/**\n * Workspace Meta Information\n *\n * @remarks This will be set to a value uniquely extended by the plugin\n */\n\nexport interface WorkspaceMeta {}\n\n/**\n * Workspace setup context object\n * @remarks Objects that are configured when the workspace is set up. Customization can be done before the workspace instance is created by a plug-in or other process.\n */\nexport interface WorkspaceSetupContext {\n /** Workspace directory path instance */\n dir: Path;\n /** package.json */\n json: WorkspacePackageJson;\n /**\n * Workspace Configuration\n * @see {@link ResolvedWorkspaceConfig}\n */\n config: ResolvedWorkspaceConfig;\n /** Plugboy Project */\n project: PlugboyProject | null;\n /** Workspace Directory Settings */\n dirs: WorkspaceDirs;\n /**\n * All package names on which the workspace depends\n */\n dependencies: string[];\n /**\n * Names of all in-project packages on which the workspace depends\n */\n projectDependencies: string[];\n /**\n * Package-name prefixes collected from string `deps.neverBundle` entries.\n *\n * Used by the external-imports plugin to externalize a declared package's\n * subpath imports (`pkg/foo.svg`) without emitting an `UNRESOLVED_IMPORT`\n * warning. `RegExp` / function externals are opaque and are not collected.\n */\n neverBundlePrefixes: string[];\n /**\n * Workspace Meta Information\n * @see {@link WorkspaceMeta}\n */\n meta: WorkspaceMeta;\n /**\n * Plugin list\n * @see {@link Plugin}\n */\n plugins: Plugin[];\n /**\n * Map of hook methods that can be initialized and called\n * @see {@link BuildedHooks}\n */\n hooks: BuildedHooks;\n /**\n * declaration output setting\n * @see {@link NormalizedDTSSettings}\n */\n dts: NormalizedDTSSettings;\n /**\n * tsdown's `css` option, seeded from the project and workspace\n * configurations.\n *\n * @remarks\n * Plugins may extend this during workspace setup, but must merge rather than\n * assign, and must let the configured value win — a plugin default belongs\n * *under* `...ctx.css`, never over it.\n *\n * @see {@link CssOptions}\n */\n css?: CssOptions;\n /**\n * CSS optimization options\n *\n * Disable the operation with `false`.\n *\n * @see {@link OptimizeCSSOptions}\n */\n optimizeCSS: OptimizeCSSOptions | false;\n // @TODO JSDoc\n mergeExternals(override: ExternalOption): void;\n // @TODO JSDoc\n mergeNoExternals(override: NoExternalOption): void;\n}\n","import type { CompilerOptions } from 'typescript';\nimport type { UserConfig as TSDownConfig } from 'tsdown';\nimport { RequiredPackageJSON } from './_utils';\nimport { WorkspacePackageJson } from './workspace';\nimport { UserPluginOption, Plugin } from './plugin';\nimport type { Path } from '../path';\nimport { UserHooks } from './hook';\nimport { DTSSettings } from './dts';\nimport { OptimizeCSSOptions } from './css';\nimport { type CssOptions } from '@tsdown/css';\n\nexport const PROJECT_REQUIRED_FIELDS = ['name'] as const;\n\ntype ProjectRequiredField = (typeof PROJECT_REQUIRED_FIELDS)[number];\n\nexport type TSConfigJSON = {\n compilerOptions?: CompilerOptions;\n} & Record<string, any>;\n\n/**\n * Template for package.json script in workspace\n */\nexport interface ProjectScriptsTemplate {\n /** Template Name */\n name: string;\n /** Script Map */\n scripts: Record<string, string>;\n}\n\n/**\n * Project User Configuration\n */\nexport interface UserProjectConfig {\n /**\n * Directory where the workspace is located\n * @remarks Used to create a new workspace with the `plugboy gen` CLI command.\n * @default packages\n */\n workspacesDir?: string;\n /**\n * Workspace script templates, or a list of them\n * @remarks Used to create a new workspace with the `plugboy gen` CLI command.\n */\n scripts?: Record<string, string> | ProjectScriptsTemplate[];\n /**\n * Workspace tsconfig template\n * @remarks Used to create a new workspace with the `plugboy gen` CLI command.\n */\n tsconfig?: TSConfigJSON;\n /**\n * Workspace README template\n * @remarks Used to create a new workspace with the `plugboy gen` CLI command.\n */\n readme?: (json: WorkspacePackageJson) => string;\n /**\n * Fixes the version of all peer dependencies in the project\n */\n peerDependencies?: Record<string, string>;\n /**\n * Hook Setting\n * @see {@link UserHooks}\n */\n hooks?: UserHooks;\n /**\n * Plug-in List\n * @see {@link UserPluginOption}\n */\n plugins?: UserPluginOption[];\n /**\n * declaration output setting\n * @see {@link DTSSettings}\n */\n dts?: DTSSettings;\n /**\n * CSS optimization options\n *\n * Disable the operation with `false`.\n *\n * @default true\n *\n * @see {@link OptimizeCSSOptions}\n */\n optimizeCSS?: OptimizeCSSOptions | boolean;\n /**\n * tsdown's `target` option — the environment(s) the output syntax is\n * downleveled for.\n *\n * @remarks\n * Applies to every workspace in the project. A workspace that declares its\n * own `target` replaces this value outright (a target list describes one\n * environment set, so merging the two would be meaningless).\n *\n * @example `['node20.19', 'chrome111']`\n */\n target?: TSDownConfig['target'];\n /**\n * tsdown's `css` option — how stylesheets are processed and emitted.\n *\n * @remarks\n * Applies to every workspace in the project. A workspace's own `css` is\n * shallow-merged over this value, so it only needs to restate the keys it\n * changes.\n *\n * @see {@link CssOptions}\n */\n css?: CssOptions;\n}\n\n/**\n * Project Configuration\n */\n\nexport interface ResolvedProjectConfig extends Required<\n Omit<\n UserProjectConfig,\n | 'scripts'\n | 'tsconfig'\n | 'hooks'\n | 'plugins'\n | 'dts'\n | 'optimizeCSS'\n | 'target'\n | 'css'\n >\n> {\n /**\n * Workspace script templates list\n * @remarks Used to create a new workspace with the `plugboy gen` CLI command.\n */\n scripts: ProjectScriptsTemplate[];\n /**\n * Workspace tsconfig template\n * @remarks Used to create a new workspace with the `plugboy gen` CLI command.\n */\n tsconfig?: TSConfigJSON;\n /**\n * Hook Setting\n * @see {@link UserHooks}\n */\n hooks?: UserHooks;\n /**\n * Plug-in List\n * @see {@link Plugin}\n */\n plugins: Plugin[];\n /**\n * declaration output setting\n * @see {@link DTSSettings}\n */\n dts?: DTSSettings;\n /**\n * CSS optimization options\n *\n * Disable the operation with `false`.\n *\n * @see {@link OptimizeCSSOptions}\n */\n optimizeCSS: OptimizeCSSOptions | false;\n /**\n * tsdown's `target` option applied to every workspace in the project, unless\n * the workspace declares its own.\n */\n target?: TSDownConfig['target'];\n /**\n * tsdown's `css` option applied to every workspace in the project, with the\n * workspace's own `css` shallow-merged over it.\n */\n css?: CssOptions;\n}\n\nexport type ProjectPackageJson = RequiredPackageJSON<ProjectRequiredField>;\n\n/**\n * Project setup context object\n * @remarks Objects that are configured when the project is set up.\n */\nexport interface ProjectSetupContext {\n /** Project directory path instance */\n dir: Path;\n /** package.json */\n json: ProjectPackageJson;\n /** Project Configuration */\n config: ResolvedProjectConfig;\n /**\n * List of directory names of workspaces located in the project\n * @remarks Note that it is the directory name, not the package name.\n */\n resolvedWorkspaces: string[];\n}\n","export function isPromise<T = any>(obj: any): obj is Promise<T> {\n return (\n !!obj &&\n (typeof obj === 'object' || typeof obj === 'function') &&\n typeof obj.then === 'function'\n );\n}\n\nexport type Listable<T> =\n | T\n | false\n | null\n | undefined\n | Listable<T>[]\n | Promise<T | false | null | undefined | Listable<T>[]>;\n\nexport async function resolveListable<T>(raw: Listable<T>): Promise<T[]> {\n const result: T[] = [];\n const list = Array.isArray(raw) ? raw : [raw];\n for (let row of list) {\n if (isPromise(row)) {\n row = await row;\n }\n if (!row) continue;\n if (Array.isArray(row)) {\n result.push(...(await resolveListable(row)));\n continue;\n }\n result.push(row);\n }\n return result;\n}\n","import {\n type ChunkAddon,\n type ChunkAddonObject,\n type ChunkAddonFunction,\n} from 'tsdown';\nimport type { NoExternalOption, ExternalOption } from '../types';\n\ntype ChunkAddonFunctionARGS = Parameters<ChunkAddonFunction>;\n\ntype MergeChunkAddonPosition = 'before' | 'after';\n\nconst _stringChunkToObject = (\n source: string | ChunkAddonObject,\n): ChunkAddonObject => {\n if (typeof source === 'object') return source;\n\n return {\n js: source,\n dts: source,\n css: source,\n } satisfies Required<ChunkAddonObject>;\n};\n\nconst _resolveChunkAddonToObject = (\n source: ChunkAddon,\n ...args: ChunkAddonFunctionARGS\n): ChunkAddonObject => {\n const tmp = typeof source === 'function' ? source(...args) || {} : source;\n return _stringChunkToObject(tmp);\n};\n\nconst _mergeChunkAddonObjects = (\n base: string | ChunkAddonObject,\n override: string | ChunkAddonObject,\n position: MergeChunkAddonPosition = 'after',\n): ChunkAddonObject => {\n const result = { ..._stringChunkToObject(base) };\n for (const [_key, value] of Object.entries(_stringChunkToObject(override))) {\n if (!value) continue;\n const key = _key as keyof ChunkAddonObject;\n const baseValue = result[key];\n const chunks = [value];\n if (baseValue) {\n if (position === 'before') {\n chunks.push(baseValue);\n } else {\n chunks.unshift(baseValue);\n }\n }\n result[key] = chunks.join('\\n\\n');\n }\n return result;\n};\n\nexport function mergeChunkAddons(\n base: ChunkAddon | undefined,\n override: ChunkAddon | undefined,\n position?: MergeChunkAddonPosition,\n): ChunkAddon | undefined {\n if (!override) return base;\n if (!base) return override;\n\n if (typeof base === 'function' || typeof override === 'function') {\n return (...args) => {\n const _base = _resolveChunkAddonToObject(base, ...args);\n const _override = _resolveChunkAddonToObject(override, ...args);\n return _mergeChunkAddonObjects(_base, _override, position);\n };\n }\n\n return _mergeChunkAddonObjects(base, override);\n}\n\ntype NullValue<T = void> = T | undefined | null | void;\n\nfunction isExternal(\n externalOption: ExternalOption,\n id: string,\n parentId: string | undefined,\n isResolved: boolean,\n): NullValue<boolean> {\n if (Array.isArray(externalOption)) {\n return externalOption.some((e) => isExternal(e, id, parentId, isResolved));\n }\n if (typeof externalOption === 'string') return id === externalOption;\n if (externalOption instanceof RegExp) return externalOption.test(id);\n if (typeof externalOption === 'function')\n return externalOption(id, parentId, isResolved);\n return false;\n}\n\n/**\n * Collect the plain string entries from an {@link ExternalOption}, flattening\n * nested arrays.\n *\n * Only string entries can be turned into package-name prefixes for subpath\n * matching (`RegExp` / function entries are opaque and are skipped). Used to\n * feed the external-imports plugin so that a `deps.neverBundle` package name\n * also externalizes its subpath imports (e.g. `pkg/foo.svg`).\n */\nexport function collectExternalStringPrefixes(\n option: ExternalOption | undefined,\n): string[] {\n const prefixes: string[] = [];\n const walk = (o: ExternalOption | undefined): void => {\n if (!o) return;\n if (typeof o === 'string') {\n prefixes.push(o);\n } else if (Array.isArray(o)) {\n o.forEach(walk);\n }\n };\n walk(option);\n return prefixes;\n}\n\nexport function mergeExternals(\n base: ExternalOption | undefined,\n override: ExternalOption | undefined,\n): ExternalOption | undefined {\n if (!override) return base;\n if (!base) return override;\n\n const externals = [base, override];\n\n return (id, parentId, isResolved) => {\n return externals.some((external) => {\n return isExternal(external, id, parentId, isResolved);\n });\n };\n}\n\nfunction isNoExternal(\n noExternalOption: NoExternalOption,\n id: string,\n importer: string | undefined,\n): NullValue<boolean> {\n if (Array.isArray(noExternalOption)) {\n return noExternalOption.some((e) => isNoExternal(e, id, importer));\n }\n if (typeof noExternalOption === 'string') return id === noExternalOption;\n if (noExternalOption instanceof RegExp) return noExternalOption.test(id);\n if (typeof noExternalOption === 'function')\n return noExternalOption(id, importer);\n return false;\n}\n\nexport function mergeNoExternals(\n base: NoExternalOption | undefined,\n override: NoExternalOption | undefined,\n): NoExternalOption | undefined {\n if (!override) return base;\n if (!base) return override;\n\n if (typeof base !== 'function' && typeof override !== 'function') {\n const _base = Array.isArray(base) ? base.slice() : [base];\n const _override = Array.isArray(override) ? override.slice() : [override];\n return [..._base, ..._override];\n }\n\n const noExternals = [base, override] as const;\n\n return (id, importer) => {\n return noExternals.some((spec) => {\n return isNoExternal(spec, id, importer);\n });\n };\n}\n","const EXIT_SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const;\n\ntype ExitHandler = () => void;\n\nconst _callbacks: ExitHandler[] = [];\n\nexport function exitHook(cb: ExitHandler): () => void {\n _callbacks.push(cb);\n const off = () => {\n const index = _callbacks.indexOf(cb);\n if (index !== -1) {\n _callbacks.splice(index, 1);\n }\n };\n return off;\n}\n\nfor (const signal of EXIT_SIGNALS) {\n process.on(signal, async () => {\n const callbacks = _callbacks.slice();\n _callbacks.length = 0;\n try {\n await Promise.all(callbacks.map((cb) => cb()));\n process.exit(0);\n } catch (_err) {\n // eslint-disable-next-line no-console\n console.error(_err);\n process.exit(1);\n }\n });\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { glob } from 'glob';\n\n/**\n * Matches a trailing `//# sourceMappingURL=<file>.d.(m)ts.map` comment at the\n * end of a declaration file. Capture group 1 is the referenced map file name.\n *\n * @see {@link stripDanglingDTSSourceMaps}\n */\nexport const DANGLING_DTS_SOURCE_MAP_RE =\n /\\r?\\n\\/\\/# sourceMappingURL=([^\\r\\n]*\\.d\\.m?ts\\.map)[ \\t]*\\r?\\n?$/;\n\n/**\n * Remove dangling declaration-map references from the emitted `.d.(m)ts` files\n * under `distDir`.\n *\n * tsdown (rolldown) appends a `//# sourceMappingURL=<file>.d.mts.map` comment to\n * every declaration file it emits, but does NOT emit the referenced\n * `.d.mts.map` itself. Consumers' editors/build tools then try to load a\n * declaration map that does not exist and report a resolution failure. Until\n * this is fixed upstream, strip the comment so shipped declarations don't point\n * at a missing map.\n *\n * As a safeguard it only strips the comment when the referenced map is genuinely\n * absent, so it becomes a no-op automatically if a future tsdown starts emitting\n * real declaration maps.\n *\n * Kept intentionally self-contained so this workaround can be removed in one\n * step: delete this file, its re-export from `../utils`, and the two call sites\n * (`Builder.build` and plugboy's own `tsdown.config.ts`, which self-builds via\n * bootstrap tsdown rather than through `Builder`).\n */\nexport async function stripDanglingDTSSourceMaps(\n distDir: string,\n): Promise<void> {\n const dtsFiles = await glob(path.join(distDir, '**/*.{d.ts,d.mts}'));\n await Promise.all(\n dtsFiles.map(async (filePath) => {\n const dts = await fs.readFile(filePath, 'utf-8');\n const matched = dts.match(DANGLING_DTS_SOURCE_MAP_RE);\n if (!matched) return;\n\n const mapPath = path.join(path.dirname(filePath), matched[1]);\n const mapExists = await fs.access(mapPath).then(\n () => true,\n () => false,\n );\n if (mapExists) return;\n\n await fs.writeFile(\n filePath,\n dts.replace(DANGLING_DTS_SOURCE_MAP_RE, '\\n'),\n 'utf-8',\n );\n }),\n );\n}\n","import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/**\n * Compute the temporary output path for a `bundle-require`-bundled plugboy\n * config file (`plugboy.project.*` / `plugboy.workspace.*`).\n *\n * `bundle-require` bundles the config to a throwaway `.mjs` next to the source\n * before importing it. Its default places that file in the config's own\n * directory — e.g. `plugboy.project.bundled_<id>.mjs` at the repo root — which\n * is noisy and can be left behind if the build is force-killed.\n *\n * Redirect it under the config's own `node_modules/.plugboy/` instead:\n * - It lives inside `node_modules`, so it is already gitignored and out of the\n * consumer's sight (and any straggler after a hard kill stays hidden there).\n * - Module resolution is unchanged: the bundled file keeps bare imports for\n * externalized dependencies, and Node resolves them by walking up to the same\n * `<configDir>/node_modules` it would have used at the original location.\n *\n * The random suffix from the default naming is preserved because turbo runs\n * many `plugboy build` processes in parallel, each loading the root\n * `plugboy.project.*`; a fixed name would collide across concurrent builds.\n */\nexport function resolveBundledConfigOutputFile(\n filepath: string,\n format: 'esm' | 'cjs',\n): string {\n const ext = format === 'esm' ? 'mjs' : 'cjs';\n const base = path.parse(filepath).name;\n const id = crypto.randomBytes(6).toString('hex');\n const outDir = path.join(path.dirname(filepath), 'node_modules', '.plugboy');\n // `bundle-require` writes the bundled file directly and does not create its\n // parent directory, so ensure `.plugboy/` exists first.\n fs.mkdirSync(outDir, { recursive: true });\n return path.join(outDir, `${base}.bundled_${id}.${ext}`);\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { exitHook } from './exit-hook';\n\nexport function getFilename(importMetaURL: string) {\n return fileURLToPath(importMetaURL);\n}\n\nexport function getDirname(importMetaURL: string) {\n return path.dirname(getFilename(importMetaURL));\n}\n\nconst FILE_NOT_FOUND_EXCEPTION_CODES = ['ENOTDIR', 'ENOENT'] as const;\n\nexport function isFileNotFoundException(\n source: unknown,\n): source is NodeJS.ErrnoException {\n return (\n !!source &&\n typeof source === 'object' &&\n FILE_NOT_FOUND_EXCEPTION_CODES.includes(\n (source as NodeJS.ErrnoException).code as any,\n )\n );\n}\n\nexport async function pathExists(\n target: string,\n type?: 'file' | 'dir',\n): Promise<boolean> {\n try {\n const stats = await fs.promises.stat(target);\n if (!type) return true;\n return type === 'file' ? stats.isFile() : stats.isDirectory();\n } catch (err) {\n if (isFileNotFoundException(err)) return false;\n throw err;\n }\n}\n\ntype FileMatcherFn = (\n file: fs.Dirent,\n dir: string,\n) => boolean | Promise<boolean>;\n\ntype FileMatcher = string | RegExp | FileMatcherFn;\n\nfunction normalizeFileMatcher(matcher: FileMatcher): FileMatcherFn {\n if (typeof matcher === 'function') {\n return matcher;\n }\n if (typeof matcher === 'string') {\n return (file) => file.name.includes(matcher);\n }\n return (file) => matcher.test(file.name);\n}\n\nexport async function findFile(\n dir: string,\n matcher: FileMatcher,\n recursive = true,\n): Promise<string | undefined> {\n const files = await fs.promises.readdir(dir, { withFileTypes: true });\n const _matcher = normalizeFileMatcher(matcher);\n\n const dirs: fs.Dirent[] | undefined = recursive ? [] : undefined;\n\n for (const file of files) {\n if (dirs && file.isDirectory()) {\n dirs.push(file);\n continue;\n }\n if (await _matcher(file, dir)) {\n return path.join(dir, file.name);\n }\n }\n\n if (dirs) {\n for (const subDir of dirs) {\n const hit = await findFile(\n path.join(dir, subDir.name),\n _matcher,\n recursive,\n );\n if (hit) return hit;\n }\n }\n}\n\nexport interface FindConfigResult {\n dir: string;\n fileName: string;\n path: string;\n code: string;\n}\n\ninterface FindConfigSettings<AllowMissing extends boolean | undefined> {\n fileName: string | string[];\n allowMissing?: AllowMissing;\n test?: (result: FindConfigResult) => boolean;\n /**\n * Trace up to how many directories above\n * @default 10\n */\n depth?: number;\n}\n\nconst FIND_CONFIG_OR_RE = /\\(.+?\\)/g;\n\nfunction parseFindConfigFileName(source: string): string[] {\n const matches = source.match(FIND_CONFIG_OR_RE);\n if (!matches) return [source];\n return matches\n .map((matched) => {\n const parts = matched.slice(1, matched.length - 1).split('|');\n return parts\n .map((part) => {\n const chunk = source.replace(matched, part);\n return parseFindConfigFileName(chunk);\n })\n .flat();\n })\n .flat();\n}\n\nfunction parseRawFindConfigFileName(source: string | string[]): string[] {\n return Array.isArray(source)\n ? source.map(parseFindConfigFileName).flat()\n : parseFindConfigFileName(source);\n}\n\nexport async function findConfig<\n AllowMissing extends boolean | undefined = false,\n>(\n fileNameOrSettings: string | string[] | FindConfigSettings<AllowMissing>,\n dir = process.cwd(),\n currentDepth = 0,\n): Promise<\n AllowMissing extends true ? FindConfigResult | null : FindConfigResult\n> {\n const settings: FindConfigSettings<AllowMissing> =\n typeof fileNameOrSettings === 'object' && !Array.isArray(fileNameOrSettings)\n ? fileNameOrSettings\n : { fileName: fileNameOrSettings };\n\n const { fileName, test, depth = 10, allowMissing } = settings;\n const fileNames = parseRawFindConfigFileName(fileName);\n if (depth && currentDepth === depth) {\n if (allowMissing) return null as any;\n throw new Error(\n `Failed to retrieve the \"${fileName}\" file because the maximum depth was reached.`,\n );\n }\n\n const next = (err?: unknown) => {\n const nextDir = path.dirname(dir);\n if (nextDir !== dir) {\n return findConfig(settings, nextDir, currentDepth + 1);\n }\n if (allowMissing) return null as any;\n throw err || new Error(`missing config \"${fileName}\"`);\n };\n\n const result = await (async () => {\n for (const fileName of fileNames) {\n try {\n const _path = path.join(dir, fileName);\n const code = await fs.promises.readFile(_path, 'utf-8');\n const _result: FindConfigResult = {\n fileName,\n dir,\n path: _path,\n code,\n };\n if (!test || test(_result)) {\n return _result;\n }\n } catch (err) {\n if (!isFileNotFoundException(err)) {\n throw err;\n }\n }\n }\n })();\n\n if (!result) {\n return next();\n }\n\n return result;\n}\n\nfunction _rmrf(_path: string): Promise<void> {\n return fs.promises\n .rm(_path, {\n recursive: true,\n force: true,\n })\n .catch((err) => {\n if (isFileNotFoundException(err)) return;\n throw err;\n });\n}\n\nexport async function rmrf(...paths: string[]): Promise<void> {\n await Promise.all(paths.map((_path) => _rmrf(_path)));\n}\n\nexport function copyDirSync(srcDir: string, destDir: string): void {\n if (!fs.existsSync(srcDir)) return;\n\n fs.mkdirSync(destDir, { recursive: true });\n for (const file of fs.readdirSync(srcDir)) {\n const srcFile = path.resolve(srcDir, file);\n if (srcFile === destDir) {\n continue;\n }\n const destFile = path.resolve(destDir, file);\n const stat = fs.statSync(srcFile);\n if (stat.isDirectory()) {\n copyDirSync(srcFile, destFile);\n } else {\n fs.copyFileSync(srcFile, destFile);\n }\n }\n}\n\nexport async function writeFileAtomic(filePath: string, content: string) {\n const tempFile = `${filePath}.${process.pid}.tmp`;\n const cleanup = () => {\n return fs.promises.unlink(tempFile).catch(() => {});\n };\n const off = exitHook(cleanup);\n try {\n await fs.promises.writeFile(tempFile, content);\n await fs.promises.rename(tempFile, filePath);\n off();\n } catch (error) {\n off();\n await cleanup();\n throw error;\n }\n}\n","import path from 'node:path';\nimport { glob } from 'glob';\nimport { RawWorkspaceEntryObject } from '../types';\n\nexport interface ExposeEntriesSettings {\n dir: string;\n /**\n * Path prefix at distribution\n */\n prefix?: string;\n}\n\nexport type RawExposeEntriesSettings = string | ExposeEntriesSettings;\n\nexport function resolveRawExposeEntriesSettings(\n rawSettings: RawExposeEntriesSettings,\n): ExposeEntriesSettings {\n return typeof rawSettings === 'string' ? { dir: rawSettings } : rawSettings;\n}\n\nconst TRIM_PATH_RE = /(^\\.?\\/|\\/$)/g;\nconst TRIM_EXT_RE = /\\.ts$/;\n\nexport async function exposeEntries(rawSettings: RawExposeEntriesSettings) {\n const { dir: _dir, prefix: _prefix } =\n resolveRawExposeEntriesSettings(rawSettings);\n const dir = path.resolve(_dir);\n const prefix = _prefix ? _prefix.replace(TRIM_PATH_RE, '') : '';\n const pattern = path.join(dir, '**/*.ts');\n // `glob` makes no ordering guarantee, and the insertion order here becomes the\n // key order of the generated `exports` / `typesVersions`, so an unsorted result\n // rewrites the workspace's package.json on an arbitrary subset of builds.\n const files = (await glob(pattern)).sort();\n const entries: Record<string, RawWorkspaceEntryObject> = {};\n for (const file of files) {\n const id = (prefix + file.replace(dir, ''))\n .replace(TRIM_EXT_RE, '')\n .replace(TRIM_PATH_RE, '');\n entries[id] = {\n src: file,\n };\n }\n return entries;\n}\n","export const PROJECT_CONFIG_BASENAME = 'plugboy.project';\n\nexport const WORKSPACE_CONFIG_BASENAME = 'plugboy.workspace';\n\nexport const PACKAGE_JSON_FILENAME = 'package.json';\n\nexport const WORKSPACE_SPEC_PREFIX = 'workspace:';\n\nexport const SEARCH_BUNDLE_EXTENSIONS_MATCH = '(ts|mjs|js|json)';\n","import { PackageJson } from 'pkg-types';\nimport { bundleRequire } from 'bundle-require';\nimport {\n ProjectPackageJson,\n PROJECT_REQUIRED_FIELDS,\n UserProjectConfig,\n ResolvedProjectConfig,\n} from '../types';\nimport {\n PROJECT_CONFIG_BASENAME,\n SEARCH_BUNDLE_EXTENSIONS_MATCH,\n} from '../constants';\nimport { findConfig } from './file';\nimport { resolveBundledConfigOutputFile } from './bundled-config';\nimport { resolveUserPluginOption } from './plugin';\n\nexport function isProjectPackageJson(\n json: PackageJson,\n): json is ProjectPackageJson {\n return (\n !!json.private && PROJECT_REQUIRED_FIELDS.every((filed) => !!json[filed])\n );\n}\n\nexport async function resolveUserProjectConfig(\n userConfig: UserProjectConfig,\n): Promise<ResolvedProjectConfig> {\n const {\n workspacesDir = 'packages',\n scripts = [],\n peerDependencies = {},\n tsconfig,\n readme = (json) => `# ${json.name}\\n`,\n plugins,\n optimizeCSS = true,\n hooks,\n target,\n css,\n } = userConfig;\n return {\n workspacesDir,\n scripts: Array.isArray(scripts) ? scripts : [{ name: '', scripts }],\n peerDependencies,\n tsconfig,\n readme,\n plugins: await resolveUserPluginOption(plugins),\n optimizeCSS: optimizeCSS === true ? {} : optimizeCSS,\n hooks,\n target,\n css,\n };\n}\n\nexport function defineProjectConfig(\n config: UserProjectConfig,\n): Promise<ResolvedProjectConfig> {\n return resolveUserProjectConfig(config);\n}\n\nexport async function loadProjectConfig(\n searchDir?: string,\n depth?: number,\n): Promise<ResolvedProjectConfig> {\n const hit = await findConfig(\n {\n fileName: `${PROJECT_CONFIG_BASENAME}.${SEARCH_BUNDLE_EXTENSIONS_MATCH}`,\n depth,\n allowMissing: true,\n },\n searchDir,\n );\n\n const userConfig = hit\n ? (\n await bundleRequire<{\n default: UserProjectConfig | Promise<UserProjectConfig>;\n }>({\n filepath: hit.path,\n getOutputFile: resolveBundledConfigOutputFile,\n })\n ).mod.default\n : ({} as UserProjectConfig);\n\n return resolveUserProjectConfig(await userConfig);\n}\n","import { UserPluginOption, Plugin } from '../types';\nimport { loadProjectConfig } from './project';\n\nexport async function resolveUserPluginOption(\n pluginOption: UserPluginOption | undefined,\n): Promise<Plugin[]> {\n if (!pluginOption) return [];\n\n const awaited = await pluginOption;\n if (!awaited) return [];\n\n if (Array.isArray(pluginOption)) {\n return (\n await Promise.all(\n pluginOption.map((o) => resolveUserPluginOption(o)).flat(),\n )\n ).flat();\n }\n return [awaited as Plugin];\n}\n\nexport function definePlugin<T extends Plugin>(options: T): T {\n return options;\n}\n\nexport async function extractProjectPlugins(\n searchDir?: string,\n): Promise<Plugin[]> {\n const config = await loadProjectConfig(searchDir);\n return config ? config.plugins : [];\n}\n\nexport async function findProjectPlugin<T extends Plugin = Plugin>(\n pluginName: string,\n searchDir?: string,\n): Promise<T | undefined> {\n const plugins = await extractProjectPlugins(searchDir);\n return plugins.find((plugin) => plugin.name === pluginName) as T | undefined;\n}\n","import { PackageJson } from 'pkg-types';\nimport { bundleRequire } from 'bundle-require';\nimport {\n WorkspacePackageJson,\n WORKSPACE_REQUIRED_FIELDS,\n UserWorkspaceConfig,\n ResolvedWorkspaceConfig,\n RawWorkspaceEntryObject,\n RawWorkspaceEntry,\n WorkspaceEntry,\n RawWorkspaceEntries,\n WorkspaceEntries,\n} from '../types';\nimport { findConfig } from './file';\nimport { resolveBundledConfigOutputFile } from './bundled-config';\nimport {\n WORKSPACE_CONFIG_BASENAME,\n SEARCH_BUNDLE_EXTENSIONS_MATCH,\n} from '../constants';\nimport { resolveUserPluginOption } from './plugin';\n\nexport function isWorkspacePackageJson(\n json: PackageJson,\n): json is WorkspacePackageJson {\n return (\n !json.private && WORKSPACE_REQUIRED_FIELDS.every((filed) => !!json[filed])\n );\n}\n\nexport function resolveRawWorkspaceEntry(\n entry: RawWorkspaceEntry,\n): WorkspaceEntry {\n const { src, css }: RawWorkspaceEntryObject =\n typeof entry === 'string' ? { src: entry } : entry;\n return {\n src,\n css: css || src.endsWith('.css') || src.endsWith('.scss'),\n };\n}\n\nexport function resolveRawWorkspaceEntries(\n entries: RawWorkspaceEntries | undefined,\n): WorkspaceEntries {\n if (!entries) return {};\n return Object.fromEntries(\n Object.entries(entries).map(([name, raw]) => [\n name,\n resolveRawWorkspaceEntry(raw),\n ]),\n );\n}\n\nexport async function resolveUserWorkspaceConfig(\n userConfig: UserWorkspaceConfig,\n): Promise<ResolvedWorkspaceConfig> {\n const {\n ignoreProjectConfig = false,\n entries,\n plugins,\n optimizeCSS = true,\n publicDir = true,\n hooks,\n } = userConfig;\n return {\n ...userConfig,\n ignoreProjectConfig,\n entries: resolveRawWorkspaceEntries(entries),\n plugins: await resolveUserPluginOption(plugins),\n optimizeCSS: optimizeCSS === true ? {} : optimizeCSS,\n publicDir: publicDir === true ? 'public' : publicDir,\n hooks,\n };\n}\n\nexport function defineWorkspaceConfig(\n config: UserWorkspaceConfig,\n): Promise<ResolvedWorkspaceConfig> {\n return resolveUserWorkspaceConfig(config);\n}\n\nexport async function loadWorkspaceConfig(\n searchDir?: string,\n depth?: number,\n): Promise<ResolvedWorkspaceConfig> {\n const hit = await findConfig(\n {\n fileName: `${WORKSPACE_CONFIG_BASENAME}.${SEARCH_BUNDLE_EXTENSIONS_MATCH}`,\n depth,\n allowMissing: true,\n },\n searchDir,\n );\n\n const userConfig = hit\n ? (\n await bundleRequire<{\n default: UserWorkspaceConfig | Promise<UserWorkspaceConfig>;\n }>({\n filepath: hit.path,\n getOutputFile: resolveBundledConfigOutputFile,\n })\n ).mod.default\n : ({} as UserWorkspaceConfig);\n\n return resolveUserWorkspaceConfig(await userConfig);\n}\n","import {\n UserHooks,\n ResolvedHooks,\n BuildedHooks,\n createHooksDefaults,\n} from '../types';\nimport { resolveListable } from './general';\n\nexport async function resolveUserHooks(\n ...userHooks: (UserHooks | undefined | null | false)[]\n): Promise<ResolvedHooks> {\n const hooks = createHooksDefaults();\n if (!userHooks) return hooks;\n for (const userHook of userHooks) {\n if (!userHook) continue;\n for (const [hookName, _hooks] of Object.entries(userHook)) {\n if (hooks) {\n (hooks as any)[hookName].push(...(await resolveListable(_hooks)));\n }\n }\n }\n return hooks;\n}\n\nexport function buildHooks(resolvedHooks: ResolvedHooks): BuildedHooks {\n const hooks: any = {};\n Object.entries(resolvedHooks).forEach(([hookName, fns]) => {\n hooks[hookName] = async (...args: any[]): Promise<any> => {\n const results: any[] = [];\n for (const fn of fns) {\n results.push(await (fn as any)(...args));\n }\n return results;\n };\n });\n return hooks;\n}\n","import path from 'node:path';\nimport fs from 'node:fs';\nimport { isFileNotFoundException } from './utils';\n\nexport class Path {\n private _value: string;\n\n private _stats?: fs.Stats;\n\n get value() {\n return this._value;\n }\n\n set value(value) {\n const _value = path.resolve(value);\n if (_value === this._value) return;\n this._value = path.resolve(value);\n delete this._stats;\n }\n\n get dirname() {\n return path.dirname(this.value);\n }\n\n get basename() {\n return path.basename(this.value);\n }\n\n get extname() {\n return path.extname(this.value);\n }\n\n get stats() {\n let { _stats } = this;\n if (!_stats) {\n _stats = fs.statSync(this.value);\n this._stats = _stats;\n }\n return _stats;\n }\n\n get isDirectory() {\n return this.stats.isDirectory;\n }\n\n get isFile() {\n return this.stats.isFile;\n }\n\n constructor(value: string) {\n this._value = path.resolve(value);\n }\n\n toString() {\n return this.value;\n }\n\n valueOf() {\n return this.value;\n }\n\n toJSON() {\n return this.value;\n }\n\n relative(to: string) {\n return new Path(path.relative(this.value, to));\n }\n\n join(...paths: string[]) {\n return new Path(path.join(this.value, ...paths));\n }\n\n resolve(...paths: string[]) {\n return new Path(path.resolve(this.value, ...paths));\n }\n\n private _join(...paths: (string | undefined)[]) {\n const _paths = paths.filter((_path): _path is string => !!_path);\n return _paths.length ? path.join(this.value, ..._paths) : this.value;\n }\n\n async readdir(...paths: string[]): Promise<Path[]> {\n const dir = this._join(...paths);\n const files = await fs.promises.readdir(dir);\n return files.map((file) => new Path(path.join(dir, file)));\n }\n\n readFile<D = undefined>(\n pathAppend?: string,\n defaults?: D,\n ): Promise<D extends undefined ? string : string | D> {\n return new Promise<any>((resolve, reject) => {\n fs.readFile(this._join(pathAppend), 'utf-8', (err, data) => {\n if (err) {\n if (defaults !== undefined && isFileNotFoundException(err)) {\n return resolve(defaults);\n }\n return reject(err);\n }\n resolve(data);\n });\n });\n }\n\n async readJSON<T = any, D = undefined>(\n pathAppend?: string,\n defaults?: D,\n ): Promise<D extends undefined ? T : T | D> {\n try {\n const file = await this.readFile(pathAppend);\n return JSON.parse(file);\n } catch (err) {\n if (defaults === undefined) {\n throw err;\n }\n return defaults as any;\n }\n }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { ProjectPackageJson, WorkspacePackageJson } from './types';\nimport {\n findConfig,\n isProjectPackageJson,\n isWorkspacePackageJson,\n} from './utils';\nimport { PACKAGE_JSON_FILENAME } from './constants';\nimport { Path } from './path';\n\nexport interface GetProjectPackageJsonResult {\n dir: Path;\n json: ProjectPackageJson;\n}\n\nexport async function getProjectPackageJson<\n AllowMissing extends boolean | undefined = false,\n>(\n searchDir?: string,\n allowMissing?: AllowMissing,\n): Promise<\n AllowMissing extends true\n ? GetProjectPackageJsonResult | null\n : GetProjectPackageJsonResult\n> {\n const hit = await findConfig(\n {\n fileName: PACKAGE_JSON_FILENAME,\n allowMissing,\n test: (result) => isProjectPackageJson(JSON.parse(result.code)),\n },\n searchDir,\n );\n if (!hit) {\n if (allowMissing) return null as any;\n throw new Error('missing project package.');\n }\n return {\n dir: new Path(hit.dir),\n json: JSON.parse(hit.code),\n } as any;\n}\n\nexport interface GetWorkspacePackageJsonResult {\n dir: Path;\n json: WorkspacePackageJson;\n}\n\nexport async function getWorkspacePackageJson<\n AllowMissing extends boolean | undefined = false,\n>(\n searchDir?: string,\n allowMissing?: AllowMissing,\n): Promise<\n AllowMissing extends true\n ? GetWorkspacePackageJsonResult | null\n : GetWorkspacePackageJsonResult\n> {\n const hit = await findConfig(\n {\n fileName: PACKAGE_JSON_FILENAME,\n allowMissing,\n test: (result) => isWorkspacePackageJson(JSON.parse(result.code)),\n },\n searchDir,\n );\n if (!hit) {\n if (allowMissing) return null as any;\n throw new Error('missing workspace package.');\n }\n return {\n dir: new Path(hit.dir),\n json: JSON.parse(hit.code),\n } as any;\n}\n\nexport async function findWorkspacePackages(\n dir: string,\n): Promise<GetWorkspacePackageJsonResult[]> {\n const results: GetWorkspacePackageJsonResult[] = [];\n const searchDir = path.resolve(dir);\n const dirs = await fs.readdir(searchDir);\n const pkgs = await Promise.all(\n dirs.map((dirName) =>\n getWorkspacePackageJson(path.join(searchDir, dirName), true),\n ),\n );\n pkgs.forEach((pkg) => {\n pkg && results.push(pkg);\n });\n return results;\n}\n","import { execa } from 'execa';\nimport path from 'node:path';\nimport type { DTSCompilerOption, EmitDTSOptions } from '../types/dts';\nimport type { PlugboyWorkspace } from './workspace';\n\nexport interface EmitDTSFullOptions extends EmitDTSOptions {\n workspace: PlugboyWorkspace;\n compiler?: DTSCompilerOption;\n ignoreCompilerErrors?: boolean;\n}\n// export interface EmitDTSOptions {\n// cwd?: string;\n// outDir?: string;\n// }\n\nexport async function runTsc(\n compiler: 'tsc' | 'vue-tsc',\n opts: EmitDTSOptions = {},\n ignoreErrors?: boolean,\n) {\n const { cwd = process.cwd(), outDir = path.join(cwd, 'dist/dts') } = opts;\n\n try {\n await execa(\n compiler,\n [\n '--declaration true',\n '--skipLibCheck',\n '--noEmit false',\n '--emitDeclarationOnly',\n `--outDir ${outDir}`,\n ],\n { cwd, shell: true, stdio: 'inherit' },\n );\n } catch (e) {\n if (!ignoreErrors) throw e;\n // eslint-disable-next-line no-console\n console.log(\n `Note: ${compiler} reported errors, but continuing with generated files...`,\n );\n }\n}\n\n/**\n * Emit DTS (declaration files)\n */\nexport async function emitDTS(opts: EmitDTSFullOptions) {\n const {\n compiler = 'tsc',\n ignoreCompilerErrors = false,\n workspace,\n ...baseOpts\n } = opts;\n\n if (typeof compiler === 'function') {\n // Custom compiler function\n await compiler({ ...baseOpts, workspace });\n } else {\n await runTsc(compiler, { ...baseOpts }, ignoreCompilerErrors);\n }\n}\n","import type { PlugboyEnvVarName } from './types';\n\n// Values starting with \"#\" have the \"#\" stripped and are transformed so that\n// references like import.meta.env are not removed by rolldown during bundling.\nexport const PLUGBOY_VAR_ENVS_FOR_BUNDLE: Record<PlugboyEnvVarName, string> = {\n __PLUGBOY_STUB__: 'false',\n __PLUGBOY_DEV__: `#(typeof process !== 'undefined' && process.env?.NODE_ENV === 'development') || (typeof import.meta !== 'undefined' && import.meta.env?.DEV === true)`,\n};\n\nexport const PLUGBOY_VAR_ENVS_FOR_STUB: Record<PlugboyEnvVarName, string> = {\n __PLUGBOY_STUB__: 'true',\n __PLUGBOY_DEV__: 'true',\n};\n","import { type InlineConfig } from 'tsdown';\nimport {\n PLUGBOY_VAR_ENVS_FOR_BUNDLE,\n PLUGBOY_VAR_ENVS_FOR_STUB,\n} from './constants';\n\nexport function applyPlugboyEnvs(\n config: Pick<InlineConfig, 'define' | 'banner'>,\n) {\n const DEFINE_VAR_INJECTS = Object.fromEntries(\n Object.entries(PLUGBOY_VAR_ENVS_FOR_BUNDLE).map(([envName, value]) => {\n const _value = value.startsWith('#') ? `$$${envName}` : value;\n return [envName, _value];\n }),\n );\n\n config.define = {\n ...config.define,\n ...DEFINE_VAR_INJECTS,\n };\n}\n\nexport function getPlugboyEnvCodeForStub() {\n return Object.entries(PLUGBOY_VAR_ENVS_FOR_STUB)\n .map(([envName, variable]) => `globalThis.${envName} = ${variable};`)\n .join('\\n');\n}\n","import type { PlugboyWorkspace } from '../workspace';\nimport type { Plugin } from '../types';\nimport { parse } from 'acorn';\nimport { PLUGBOY_VAR_ENVS_FOR_BUNDLE } from './constants';\n\nfunction findAfterImports(code: string): number {\n const ast = parse(code, {\n sourceType: 'module',\n ecmaVersion: 'latest',\n }) as any;\n\n let end = 0;\n\n for (const node of ast.body) {\n if (\n node.type === 'ImportDeclaration' ||\n node.type === 'ExportNamedDeclaration' ||\n node.type === 'ExportAllDeclaration' ||\n node.type === 'ExportDefaultDeclaration'\n ) {\n end = Math.max(end, node.end);\n continue;\n }\n break;\n }\n\n return end;\n}\n\nconst _replacements: [envName: string, value: string][] = [];\n\nObject.entries(PLUGBOY_VAR_ENVS_FOR_BUNDLE).forEach(([envName, value]) => {\n if (value.startsWith('#')) {\n _replacements.push([`$$${envName}`, value.substring(1)]);\n }\n});\n\nexport function WorkspaceEnvPlugin(_workspace: PlugboyWorkspace): Plugin {\n return {\n name: 'plugboy-workspace-env',\n async renderChunk(code, _chunk) {\n const injects = _replacements.filter(([envName]) =>\n code.includes(envName),\n );\n\n if (injects.length) {\n const MagicString = (await import('magic-string')).default;\n const ms = new MagicString(code);\n\n const insertPos = findAfterImports(code);\n const injectCode = injects\n .map(([eventName, value]) => `const ${eventName} = ${value};`)\n .join('\\n');\n ms.appendLeft(insertPos, `\\n${injectCode}`);\n\n return {\n code: ms.toString(),\n map: ms.generateMap({ hires: true }),\n };\n }\n },\n };\n}\n","import { type InlineConfig, build } from 'tsdown';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { glob } from 'glob';\nimport type { PlugboyWorkspace, WorkspaceObjectExport } from './workspace';\nimport {\n TSDOWN_SYNC_OPTIONS,\n NormalizedDTSPreserveTypeSettings,\n} from '../types';\nimport {\n copyDirSync,\n rmrf,\n mergeExternals,\n stripDanglingDTSSourceMaps,\n} from '../utils';\nimport { emitDTS } from './dts';\nimport { applyPlugboyEnvs, getPlugboyEnvCodeForStub } from '../env';\n\nconst SHEBANG_MATCH_RE = /^(#!.+?)\\n/;\n\n/**\n * Escape a string for use inside a `RegExp`.\n *\n * Kept local: plugboy builds every other package, so it cannot depend on one.\n */\nfunction escapeRegExp(source: string): string {\n return source.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Every name the declaration file already binds -- imported from any module, or\n * declared in the file itself.\n *\n * `X as Y` binds `Y`, so the local name is what matters rather than the\n * exported one.\n */\nfunction collectBoundNames(dts: string): Set<string> {\n const names = new Set<string>();\n\n for (const [, clause] of dts.matchAll(\n /^import\\s+([^;]+?)\\s+from\\s+['\"][^'\"]+['\"];?$/gm,\n )) {\n const braced = clause.match(/\\{([^{}]*)\\}/);\n if (braced) {\n for (const specifier of braced[1].split(',')) {\n const local = specifier.split(' as ').pop()?.trim();\n if (local) names.add(local);\n }\n }\n const head = clause\n .replace(/\\{[^{}]*\\}/, '')\n .replace(/,/g, ' ')\n .trim();\n const namespaced = head.match(/\\*\\s+as\\s+([\\w$]+)/);\n if (namespaced) {\n names.add(namespaced[1]);\n } else if (/^[\\w$]+$/.test(head)) {\n names.add(head);\n }\n }\n\n for (const [, name] of dts.matchAll(\n /^(?:export\\s+)?(?:declare\\s+)?(?:type|interface|class|const|function)\\s+([\\w$]+)/gm,\n )) {\n names.add(name);\n }\n\n return names;\n}\n\ninterface ResolvedOptions extends InlineConfig {}\n\nexport class Builder {\n readonly workspace: PlugboyWorkspace;\n\n private _tsdownOptions?: ResolvedOptions;\n\n get entry() {\n return this.workspace.entry;\n }\n\n get dts() {\n return this.workspace.dts;\n }\n\n constructor(workspace: PlugboyWorkspace) {\n this.workspace = workspace;\n }\n\n async tsdownOptions(overrides?: {\n watch?: boolean;\n }): Promise<ResolvedOptions> {\n const { _tsdownOptions } = this;\n if (_tsdownOptions) return _tsdownOptions;\n\n const { entry, dts } = this;\n\n const resolvedOptions: ResolvedOptions = {\n dts:\n dts.inline || typeof dts.compiler === 'function'\n ? false\n : dts.compiler === 'vue-tsc'\n ? { vue: true }\n : true,\n treeshake: true,\n css: this.workspace.cssOptions,\n plugins: this.workspace.plugins,\n entry,\n sourcemap: true,\n clean: true,\n ...overrides,\n };\n\n for (const opt of TSDOWN_SYNC_OPTIONS) {\n resolvedOptions[opt] = this.workspace.config[opt] as any;\n }\n\n applyPlugboyEnvs(resolvedOptions);\n\n resolvedOptions.deps ??= {};\n resolvedOptions.deps.neverBundle = mergeExternals(\n resolvedOptions.deps.neverBundle,\n [\n /^(@fastkit\\/)?plugboy(?!\\/runtime-utils)/,\n ...this.workspace.dependencies,\n ],\n );\n\n this._tsdownOptions = resolvedOptions;\n\n return resolvedOptions;\n }\n\n private async _stubLinkJS(from: string, to: string) {\n const fromParsed = path.parse(from);\n const fromDir = fromParsed.dir;\n const toParsed = path.parse(to);\n const toRelativeDir = path.relative(fromDir, toParsed.dir);\n const location = path.join(toRelativeDir, toParsed.base);\n const source = await fs.readFile(to, 'utf-8');\n const shebang = source.match(SHEBANG_MATCH_RE)?.[1];\n const disableChecks = '/* eslint-disable */\\n// @ts-nocheck\\n';\n const code = `${disableChecks}${getPlugboyEnvCodeForStub()}\\nexport * from '${location}';`;\n const dtsPath = path.join(fromDir, `${fromParsed.name}.d.mts`);\n const dtsCode = `${disableChecks}export * from '${location.replace(\n /\\.ts$/,\n '',\n )}';`;\n const srcFromDir = path.dirname(from);\n const dtsDir = path.dirname(dtsPath);\n await Promise.all(\n [srcFromDir, dtsDir].map((dir) => fs.mkdir(dir, { recursive: true })),\n );\n await Promise.all([\n fs.writeFile(from, `${shebang ? `${shebang}\\n` : ''}${code}`),\n fs.writeFile(dtsPath, dtsCode),\n ]);\n }\n\n private async _stubLinkCSS(from: string) {\n const code = `/* noop */`;\n await fs.writeFile(from, code);\n }\n\n /**\n * Copy the workspace's `publicDir` contents into the output directory.\n *\n * Owned by plugboy (not tsdown's `copy`) so the result is identical in `build`\n * and `stub`: both call this with plugboy's own recursive copy. `copyDirSync`\n * no-ops when the directory is absent, so packages without a public directory\n * are unaffected. tsdown's `copy` option is left to tsdown and only applies\n * during a real `build`.\n */\n copyPublicDir() {\n const { publicDir } = this.workspace.config;\n if (!publicDir) return;\n copyDirSync(\n this.workspace.dir.join(publicDir).value,\n this.workspace.dirs.dist.value,\n );\n }\n\n async stub() {\n const links = this.workspace.getStubLinks();\n this.copyPublicDir();\n await Promise.all(\n links.map((link) => {\n if (link.type === 'js') {\n return this._stubLinkJS(link.from, link.to);\n }\n if (link.type === 'css') {\n return this._stubLinkCSS(link.from);\n }\n throw new Error(`non supported type`);\n }),\n );\n await fs.writeFile(\n this.workspace.dirs.dist.join('.stub').value,\n '',\n 'utf-8',\n );\n }\n\n normalizeDTSBySettings(\n dts: string,\n settings: NormalizedDTSPreserveTypeSettings,\n ): string | undefined {\n const { targets, pkg } = settings;\n const myPackageName = this.workspace.json.name;\n const packageIsOwn = myPackageName === pkg;\n // The statement this normalizer merges into, if the file already imports\n // from the package. The declaration bundler quotes its specifiers with `\"`\n // while this normalizer wrote `'`, and matching only the latter made every\n // bundled import invisible here -- the names were then prepended as a\n // second import of the same module and each one ended up bound twice\n // (issue #234).\n const target = (() => {\n if (!pkg || packageIsOwn) return;\n const re = new RegExp(\n `import {([^{}]+)} from (['\"])${escapeRegExp(pkg)}\\\\2`,\n );\n const matched = dts.match(re);\n if (!matched) return;\n const [statement, specifiers, quote] = matched;\n return { statement, specifiers, quote };\n })();\n\n const hitTypeNames: string[] = [];\n targets.forEach(({ from, typeName }) => {\n const matched = dts.match(from);\n if (matched) {\n hitTypeNames.push(typeName);\n dts = dts.replace(from, typeName);\n }\n });\n\n if (!hitTypeNames.length) return;\n\n // Whether the file can already refer to a name, from any module -- these\n // types are re-exported (`ScopeName` reaches `@fastkit/vui` through both\n // `@fastkit/color-scheme` and `@fastkit/vue-color-scheme`), so importing\n // one a second time binds it twice even though the modules differ.\n const bound = collectBoundNames(dts);\n const appends = [...new Set(hitTypeNames)].filter(\n (typeName) => !bound.has(typeName),\n );\n\n if (!appends.length) return dts;\n\n if (target) {\n const { statement, specifiers, quote } = target;\n const merged = `import { ${specifiers.trim()}, ${appends.join(\n ', ',\n )} } from ${quote}${pkg}${quote}`;\n // A replacer function, because emitted names carry `$` suffixes\n // (`ColorVariant$1`) that `String.replace` reads as group references.\n dts = dts.replace(statement, () => merged);\n } else if (pkg && !packageIsOwn) {\n dts = `import { ${appends.join(', ')} } from '${pkg}';\\n${dts}`;\n }\n return dts;\n }\n\n async normalizeDTSFile(filePath: string) {\n const dts = await fs.readFile(filePath, 'utf-8');\n const { preserveType, normalizers } = this.dts;\n let normalized = dts;\n let processed = false;\n for (const settings of preserveType) {\n const _normalized = this.normalizeDTSBySettings(normalized, settings);\n if (_normalized) {\n processed = true;\n normalized = _normalized;\n }\n }\n for (const normalizer of normalizers) {\n const _normalized = await normalizer(normalized, this);\n if (_normalized && normalized !== _normalized) {\n processed = true;\n normalized = _normalized;\n }\n }\n if (!processed) {\n return;\n }\n await fs.writeFile(filePath, normalized, 'utf-8');\n }\n\n async normalizeDTSFiles(dtsFiles: string[] = this.workspace.dtsFiles) {\n const { preserveType } = this.dts;\n if (!preserveType.length || !dtsFiles.length) return;\n\n await Promise.all(\n dtsFiles.map((filePath) => this.normalizeDTSFile(filePath)),\n );\n }\n\n async emitDTSManually() {\n const { dir, dirs, exports } = this.workspace;\n const cwd = dir.value;\n const outDir = dirs.dist.join('.dts-generate').value;\n const dtsSrcDir = path.join(outDir, 'src');\n const dtsDest = dirs.dist.join('.dts').value;\n\n await emitDTS({\n cwd,\n outDir,\n workspace: this.workspace,\n compiler: this.workspace.dts.compiler,\n ignoreCompilerErrors: this.workspace.dts.ignoreCompilerErrors,\n });\n\n await fs.rename(dtsSrcDir, dtsDest);\n await rmrf(outDir);\n\n const objectExports: WorkspaceObjectExport[] = [];\n\n exports.forEach(({ at }) => {\n typeof at === 'object' && objectExports.push(at);\n });\n\n await Promise.all(\n objectExports.map(async (at) => {\n const typesDir = path.dirname(at.types);\n const dtsDestDir = path.dirname(at.dtsDest);\n const relativeDir = path.relative(typesDir, dtsDestDir);\n const relativePath = path.join(\n relativeDir,\n path.basename(at.dtsDest).replace(/\\.d\\.m?ts$/, ''),\n );\n const code = `export * from './${relativePath}';`;\n await fs.writeFile(at.types, code, 'utf-8');\n }),\n );\n\n const dtsFiles = await glob(path.join(dtsDest, '**/*.{d.ts,d.mts}'));\n await this.normalizeDTSFiles(dtsFiles);\n }\n\n async build() {\n const options = await this.tsdownOptions();\n await build(options);\n\n // After tsdown (its `clean` wipes `dist` first), so the copy survives.\n // Identical to the `stub()` path — plugboy owns the public-dir copy.\n this.copyPublicDir();\n\n if (this.dts.inline || typeof this.dts.compiler === 'function') {\n await this.emitDTSManually();\n } else {\n await this.normalizeDTSFiles();\n }\n\n await stripDanglingDTSSourceMaps(this.workspace.dirs.dist.value);\n }\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { glob } from 'glob';\nimport { Path } from '../path';\nimport {\n ProjectSetupContext,\n ProjectPackageJson,\n ResolvedProjectConfig,\n UserHooks,\n} from '../types';\nimport { getProjectPackageJson } from '../package';\nimport {\n isWorkspacePackageJson,\n loadProjectConfig,\n resolveUserProjectConfig,\n} from '../utils';\nimport { PACKAGE_JSON_FILENAME } from '../constants';\n\n/**\n * Plugboy Project\n *\n * @remarks This instance is only created if the project consists of a mono-repo.\n */\nexport class PlugboyProject {\n /** Path instance of the project directory */\n readonly dir: Path;\n\n /** package.json */\n readonly json: ProjectPackageJson;\n\n /**\n * Project Configuration\n * @see {@link ResolvedProjectConfig}\n */\n readonly config: ResolvedProjectConfig;\n\n /** Names of all packages on which the project depends */\n readonly dependencies: string[];\n\n /** Directory names of all workspaces owned by the project */\n readonly resolvedWorkspaces: string[];\n\n /**\n * Name of the project's package.json\n */\n get name() {\n return this.json.name;\n }\n\n /**\n * Plug-in List\n * @see {@link ResolvedProjectConfig.plugins}\n */\n get plugins() {\n return this.config.plugins;\n }\n\n /**\n * List of all user hook settings\n * @see {@link UserHooks}\n */\n get hooks(): UserHooks[] {\n const { hooks: _hooks, plugins } = this.config;\n const pluginHooks = plugins.map((plugin) => plugin.hooks);\n return [_hooks, ...pluginHooks].filter((hook) => !!hook);\n }\n\n constructor(ctx: ProjectSetupContext) {\n const { dir, json, config, resolvedWorkspaces } = ctx;\n\n this.dir = dir;\n this.json = json;\n this.config = config;\n\n const allDeps = {\n ...json.dependencies,\n ...json.devDependencies,\n };\n\n this.dependencies = Object.keys(allDeps);\n this.resolvedWorkspaces = resolvedWorkspaces;\n }\n}\n\nexport async function getProject<\n AllowMissing extends boolean | undefined = false,\n>(\n searchDir?: string,\n allowMissing?: AllowMissing,\n skipLoadConfig?: boolean,\n): Promise<AllowMissing extends true ? PlugboyProject | null : PlugboyProject> {\n const hit = await getProjectPackageJson(searchDir, allowMissing);\n if (!hit) {\n return null as any;\n }\n const { dir, json } = hit;\n const resolvedWorkspaces: string[] = [];\n const { workspaces = [] } = json;\n if (!Array.isArray(workspaces)) {\n throw new Error('workspaces only supports arrays.');\n }\n const workspacesPattern = workspaces.map(\n (workspace) => dir.join(workspace, PACKAGE_JSON_FILENAME).value,\n );\n const workspaceHits = await glob(workspacesPattern);\n for (const _hit of workspaceHits) {\n const _json = JSON.parse(await fs.readFile(_hit, 'utf-8'));\n if (!isWorkspacePackageJson(_json)) {\n continue;\n }\n resolvedWorkspaces.push(path.dirname(_hit));\n }\n resolvedWorkspaces.sort((a, b) => {\n if (a < b) return -1;\n if (a > b) return 1;\n return 0;\n });\n\n const config = skipLoadConfig\n ? await resolveUserProjectConfig({})\n : await loadProjectConfig(dir.value, 0);\n\n const ctx: ProjectSetupContext = {\n dir,\n json,\n config,\n resolvedWorkspaces,\n };\n\n return new PlugboyProject(ctx);\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { CssOptions } from '@tsdown/css';\nimport type { PlugboyWorkspace } from './workspace';\n\n/** `foo.mjs` -> `foo.css`, mirroring how `@tsdown/css` names a chunk's CSS. */\nexport function toCssFileName(jsFileName: string): string {\n return jsFileName.replace(/(?:\\.module)?(\\.[cm]?js)$/, '.css');\n}\n\n/** The stylesheets a package declares: `./<entry>.css` per `css: true` entry. */\nexport function declaredStylesheets(workspace: PlugboyWorkspace): Set<string> {\n return new Set(\n workspace.exports\n .filter((exp) => exp.id.endsWith('.css'))\n .map((exp) => path.posix.basename(exp.id)),\n );\n}\n\n/**\n * The file name of the package's one assembled stylesheet, or `undefined` when\n * plugboy does not assemble one.\n *\n * With a single CSS entry the package publishes one stylesheet holding all of its\n * CSS. `plugboy-assemble-entry-css` writes it under `css.fileName` when that is\n * set, and under the declared `<entry>.css` otherwise. With several CSS entries\n * each gets its own, so there is no package-wide one.\n */\nexport function assembledStylesheetName(\n workspace: PlugboyWorkspace,\n): string | undefined {\n const { cssOptions } = workspace;\n if (!cssOptions?.splitting || cssOptions.inject) return undefined;\n const declared = declaredStylesheets(workspace);\n if (declared.size !== 1) return undefined;\n return cssOptions.fileName ?? [...declared][0];\n}\n\n/**\n * Every stylesheet the build has written to `dir`, as file names.\n *\n * The bundle is not the whole story: `plugboy-assemble-entry-css` writes the\n * declared stylesheets directly to disk, often under a name the build emitted\n * nothing for, so a `writeBundle` stage that only walked the bundle assets would\n * skip exactly the file that needed the most work. The declared exports — and the\n * package stylesheet's `css.fileName`, when one is set — fill that in: they are\n * the stylesheets the package publishes, so anything present under one of those\n * names belongs in the set.\n */\nexport async function listEmittedStylesheets(\n workspace: PlugboyWorkspace,\n dir: string,\n bundle: Record<string, { type: string; fileName: string }>,\n): Promise<string[]> {\n const names = new Set<string>();\n for (const chunk of Object.values(bundle)) {\n if (chunk.type === 'asset' && chunk.fileName.endsWith('.css')) {\n names.add(chunk.fileName);\n }\n }\n\n const assembled = assembledStylesheetName(workspace);\n const candidates = new Set(declaredStylesheets(workspace));\n if (assembled) candidates.add(assembled);\n\n await Promise.all(\n [...candidates].map(async (name) => {\n if (names.has(name)) return;\n try {\n await fs.access(path.join(dir, name));\n names.add(name);\n } catch {\n // Not emitted — the entry produced no CSS at all.\n }\n }),\n );\n\n return [...names];\n}\n\n/**\n * Fill in the `css` options plugboy needs to deliver its declared stylesheets.\n *\n * `cssEntryIds` are the entries with `css: true`, named as plugboy names them\n * (`.` normalized to the package directory name).\n *\n * By default the build emits one stylesheet per chunk (`splitting: true`) and\n * `plugboy-assemble-entry-css` builds each declared stylesheet from them, in\n * dependency order. tsdown's own single-file merge is not used, because it\n * concatenates chunks in bundle order: a shared chunk lands after the entries\n * that compose from it, and loses to the base styles it was meant to override.\n * A `fileName` is still honored — it names the assembled stylesheet.\n *\n * tsdown merges into one file itself only where plugboy cannot assemble:\n * - `splitting` declared explicitly, which is applied as written;\n * - `inject`, where the JavaScript imports the per-chunk stylesheets by name, so\n * they have to stay as emitted. One CSS entry then keeps a single file.\n *\n * A single file is named after the CSS entry unless `fileName` says otherwise, so\n * it is the file the `./<entry>.css` export points at. A workspace without CSS\n * entries is left to tsdown's defaults.\n */\nexport function resolveCssOptions(\n css: CssOptions | undefined,\n cssEntryIds: readonly string[],\n): CssOptions | undefined {\n if (!cssEntryIds.length) return css;\n\n const splitting =\n css?.splitting ?? (css?.inject ? cssEntryIds.length > 1 : true);\n const resolved: CssOptions = { ...css, splitting };\n if (!splitting && cssEntryIds.length === 1) {\n resolved.fileName ??= `${cssEntryIds[0]}.css`;\n }\n return resolved;\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport type { PlugboyWorkspace } from '../workspace';\nimport type { Plugin, ResolvedOptimizeCSSOptions } from '../types';\nimport type { Processor, AcceptedPlugin as PostcssPlugin } from 'postcss';\nimport { listEmittedStylesheets } from '../workspace/stylesheets';\n\nasync function getPostcss(\n options: ResolvedOptimizeCSSOptions,\n): Promise<Processor> {\n const { layer, media, combineRules, cssnano } = options;\n const [postcss, _layer, _media, _combineRules, _cssnano] = await Promise.all([\n import('postcss').then((mod) => mod.default),\n layer &&\n import('../postcss/plugins/optimize-layer').then((mod) =>\n mod.OptimizeLayer(layer),\n ),\n media &&\n import('../postcss/plugins/optimize-media').then((mod) =>\n mod.OptimizeMedia(media),\n ),\n combineRules &&\n import('../postcss/plugins/combine-rules').then((mod) =>\n mod.CombineRules(combineRules),\n ),\n cssnano && import('cssnano').then((mod) => mod.default(cssnano)),\n ]);\n const plugins: PostcssPlugin[] = [];\n _layer && plugins.push(_layer);\n _media && plugins.push(_media);\n _combineRules && plugins.push(_combineRules);\n _cssnano && plugins.push(_cssnano);\n\n return postcss(plugins);\n}\n\nconst SOURCE_MAPPING_URL_COMMENT_RE = /\\/\\*# sourceMappingURL=.+? \\*\\//g;\nconst allLayerDefRe = /(^|\\n)@layer\\s+([a-zA-Z\\d\\-_$. ,]+);/g;\nconst layerDefTrimRe = /((^|\\n)@layer\\s+|;)/g;\n\nasync function optimizeCSS(\n css: string,\n fileName: string,\n options: ResolvedOptimizeCSSOptions,\n): Promise<string> {\n const postcss = await getPostcss(options);\n\n function prepare(source: string): string {\n const layerDefs = (() => {\n const matched = source.match(allLayerDefRe);\n if (!matched) return '';\n const layerNames: string[] = [];\n matched.forEach((row) => {\n const trimmed = row.replace(layerDefTrimRe, '');\n const chunks = trimmed.split(',');\n chunks.forEach((chunk) => layerNames.push(chunk.trim()));\n });\n const uniqued = Array.from(new Set(layerNames));\n const def = `@layer ${uniqued.join(', ')};\\n`;\n return def;\n })();\n return layerDefs + source.replace(allLayerDefRe, '');\n }\n\n const result = await postcss.process(prepare(css), {\n from: fileName,\n to: fileName,\n map: { inline: false },\n });\n\n return result.css.replace(SOURCE_MAPPING_URL_COMMENT_RE, '');\n}\n\n/**\n * Applies {@link PlugboyWorkspace.optimizeCSSOptions} to every stylesheet the\n * build writes.\n *\n * This runs in `writeBundle`, on the files on disk, rather than on the bundle\n * assets in `generateBundle` — because not every stylesheet exists as a bundle\n * asset by then. tsdown's own CSS pipeline emits from a *post* plugin, which\n * runs after every user plugin's `generateBundle`, so CSS that tsdown produces\n * (a plain `.css` / `.scss` import, or — since the vanilla-extract plugin routes\n * its `.css.ts` through tsdown — extracted CSS) used to skip these\n * optimizations entirely, while CSS a plugin emitted itself received them. By\n * `writeBundle` every producer has finished and the whole set is on disk.\n *\n * `preserve-css-imports` re-injects external `@import`s in its own\n * `writeBundle`; it is registered after this plugin, so it always sees the\n * optimized file.\n */\nexport function OptimizeCSSPlugin(workspace: PlugboyWorkspace): Plugin {\n // Files already optimized, so repeated output passes are idempotent.\n const processed = new Set<string>();\n\n return {\n name: 'plugboy-optimize-css',\n buildStart() {\n processed.clear();\n },\n async writeBundle(options, bundle) {\n const { optimizeCSSOptions } = workspace;\n if (!optimizeCSSOptions) return;\n\n const { dir } = options;\n if (!dir) return;\n\n const stylesheets = await listEmittedStylesheets(workspace, dir, bundle);\n\n await Promise.all(\n stylesheets.map(async (fileName) => {\n const filePath = path.join(dir, fileName);\n if (processed.has(filePath)) return;\n\n let css: string;\n try {\n css = await fs.readFile(filePath, 'utf8');\n } catch {\n // The asset may have been removed by another plugin.\n return;\n }\n processed.add(filePath);\n\n const optimized = await optimizeCSS(\n css,\n fileName,\n optimizeCSSOptions,\n );\n if (optimized !== css) {\n await fs.writeFile(filePath, optimized);\n }\n }),\n );\n },\n };\n}\n","/**\n * The order in which the chunks of a build load their stylesheets.\n *\n * A stylesheet's rules win over an earlier one's at equal specificity, so the\n * order chunks' CSS is concatenated in is part of what the CSS means. What a\n * package composes from — a shared reset, a vanilla-extract `style([base, …])`\n * — has to come before the rules that build on it.\n *\n * The bundle's own order does not give that. Entry chunks come first and the\n * chunks they import follow, so a shared chunk lands *after* the entries that\n * depend on it. `@tsdown/css` concatenates in that order when `css.splitting` is\n * off, and so did everything in plugboy that took `Object.values(bundle)` as the\n * load order.\n *\n * This walks the chunk graph the way Vite does for `build.cssCodeSplit: false`:\n * from each root, static imports first and the chunk itself after them; then the\n * dynamically imported chunks, which load later, in the order they were reached.\n * Every CSS producer in plugboy orders by this, so a package gets the same order\n * whichever of them emitted its styles.\n */\n\n/** What the ordering needs to know about a chunk. */\nexport interface ChunkGraphNode {\n /** The chunk's name — for an entry chunk, the entry id plugboy declared. */\n name: string;\n isEntry: boolean;\n /** File names of the chunks this one imports statically. */\n imports: string[];\n /** File names of the chunks this one imports with `import()`. */\n dynamicImports: string[];\n}\n\n/** Chunk file name -> its node. Iteration order is the bundle's. */\nexport type ChunkGraph = Map<string, ChunkGraphNode>;\n\ninterface BundleChunkLike {\n type: string;\n fileName: string;\n name?: string;\n isEntry?: boolean;\n imports?: string[];\n dynamicImports?: string[];\n}\n\n/**\n * Capture the chunk graph of a bundle.\n *\n * Call it from `generateBundle`, before `@tsdown/css` runs: that removes the\n * chunks holding nothing but CSS, together with every import of them, so a\n * graph captured later has lost exactly the edges that matter here.\n */\nexport function captureChunkGraph(\n bundle: Record<string, BundleChunkLike>,\n): ChunkGraph {\n const graph: ChunkGraph = new Map();\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'chunk') continue;\n graph.set(chunk.fileName, {\n name: chunk.name ?? chunk.fileName,\n isEntry: !!chunk.isEntry,\n imports: [...(chunk.imports ?? [])],\n dynamicImports: [...(chunk.dynamicImports ?? [])],\n });\n }\n return graph;\n}\n\n/**\n * The entry chunks of a graph, in the order the entries were declared.\n *\n * `entryIds` are the names plugboy gives the entries (`.` normalized to the\n * package directory name). Entry chunks it does not name keep the bundle's order,\n * after the named ones.\n */\nexport function entryChunksInDeclaredOrder(\n graph: ChunkGraph,\n entryIds: readonly string[] = [],\n): string[] {\n const rank = (node: ChunkGraphNode) => {\n const index = entryIds.indexOf(node.name);\n return index === -1 ? entryIds.length : index;\n };\n return [...graph]\n .filter(([, node]) => node.isEntry)\n .map(([fileName, node], position) => ({ fileName, node, position }))\n .sort((a, b) => rank(a.node) - rank(b.node) || a.position - b.position)\n .map(({ fileName }) => fileName);\n}\n\nexport interface OrderChunksOptions {\n /**\n * Append the chunks no root reaches, in bundle order. Set it when the result\n * stands for the whole package; leave it off when it stands for one entry.\n */\n includeUnreached?: boolean;\n}\n\n/**\n * Chunk file names in load order, starting from `roots`.\n *\n * Each chunk appears once, after every chunk it imports statically. Chunks\n * reached only through `import()` follow all of those.\n */\nexport function orderChunks(\n graph: ChunkGraph,\n roots: readonly string[],\n options: OrderChunksOptions = {},\n): string[] {\n const visited = new Set<string>();\n const ordered: string[] = [];\n const dynamic = new Set<string>();\n\n const walk = (fileName: string) => {\n if (visited.has(fileName)) return;\n visited.add(fileName);\n const node = graph.get(fileName);\n if (!node) return;\n for (const imported of node.imports) walk(imported);\n for (const imported of node.dynamicImports) dynamic.add(imported);\n ordered.push(fileName);\n };\n\n for (const root of roots) walk(root);\n // A `Set` visits what is added while it is being iterated, so a dynamic chunk\n // that imports another dynamically is covered too.\n for (const fileName of dynamic) walk(fileName);\n if (options.includeUnreached) {\n for (const fileName of graph.keys()) walk(fileName);\n }\n\n return ordered;\n}\n\n/**\n * Every chunk of the package in load order: the entries as declared, then what\n * they import dynamically, then anything left over.\n */\nexport function orderPackageChunks(\n graph: ChunkGraph,\n entryIds?: readonly string[],\n): string[] {\n return orderChunks(graph, entryChunksInDeclaredOrder(graph, entryIds), {\n includeUnreached: true,\n });\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { definePlugin } from '../../utils';\nimport type { PlugboyWorkspace } from '../workspace';\nimport {\n assembledStylesheetName,\n declaredStylesheets,\n toCssFileName,\n} from '../stylesheets';\nimport {\n captureChunkGraph,\n orderChunks,\n orderPackageChunks,\n type ChunkGraph,\n} from '../chunk-order';\n\n/**\n * Plugin that builds every stylesheet plugboy declares — `./<entry>.css` for each\n * `css: true` entry — from the per-chunk stylesheets the build emits, in the\n * order they load.\n *\n * plugboy runs tsdown with `css.splitting` on (see `resolveCssOptions`), which\n * emits one stylesheet per output *chunk*. Neither that nor tsdown's single-file\n * merge matches what plugboy publishes:\n *\n * - tsdown's merge concatenates the chunks in bundle order — entries first,\n * shared chunks after. A package that composes from a shared base style then\n * ships the base *after* the rules built on it, and the base wins.\n * - Per-chunk stylesheets are named after chunks. CSS reached from several\n * entries lands in a shared chunk under a hashed name no export points at, and\n * an entry whose CSS comes only from there gets no stylesheet at all.\n *\n * So each declared stylesheet is rebuilt here, with the chunks ordered as Vite\n * orders them for `build.cssCodeSplit: false` (`orderChunks`): static imports\n * before their importer, dynamically imported chunks after. Nothing is left for a\n * dynamic `import()` to load, since without `css.inject` the JavaScript imports no\n * stylesheet at all.\n *\n * - **One CSS entry**: the package publishes one stylesheet, so it gets the CSS of\n * every chunk — the same content tsdown's merge would have produced, in\n * dependency order. It is written under `css.fileName` when one is set.\n * - **Several**: each gets its own CSS and that of every chunk it reaches. CSS\n * shared between entries is duplicated into each, which is what makes a single\n * `./<entry>.css` import complete.\n *\n * The per-chunk stylesheets that were folded in are deleted, since nothing\n * exports them.\n *\n * The chunk graph has to be captured in `generateBundle`, because it is gone by\n * the time the stylesheets exist: a chunk holding nothing but CSS is dropped once\n * tsdown's CSS pipeline (a *post* plugin, so it runs after this hook) has emitted\n * its stylesheet, and its importers' `imports` are emptied along with it. By\n * `writeBundle` the shared chunk is neither in the bundle nor on disk — only its\n * orphaned stylesheet is.\n *\n * Nothing is assembled when tsdown merged the stylesheet itself (`splitting` off,\n * declared explicitly), or with `css.inject`, where the JavaScript imports the\n * per-chunk stylesheets by name.\n */\nexport function createAssembleEntryCssPlugin(workspace: PlugboyWorkspace) {\n let graph: ChunkGraph = new Map();\n\n return definePlugin({\n name: 'plugboy-assemble-entry-css',\n buildStart() {\n graph = new Map();\n },\n generateBundle(_options, bundle) {\n graph = captureChunkGraph(bundle);\n },\n async writeBundle(options, bundle) {\n const { dir } = options;\n if (!dir) return;\n\n const { cssOptions } = workspace;\n if (!cssOptions?.splitting || cssOptions.inject) return;\n\n const targets = declaredStylesheets(workspace);\n if (!targets.size) return;\n\n const emitted = new Set(\n Object.values(bundle)\n .filter(\n (chunk) =>\n chunk.type === 'asset' && chunk.fileName.endsWith('.css'),\n )\n .map((chunk) => chunk.fileName),\n );\n if (!emitted.size) return;\n\n /** The stylesheets of `chunks`, in the same order, each listed once. */\n const stylesheetsOf = (chunks: string[]): string[] => {\n const ordered: string[] = [];\n for (const fileName of chunks) {\n const css = toCssFileName(fileName);\n if (css === fileName || !emitted.has(css)) continue;\n if (!ordered.includes(css)) ordered.push(css);\n }\n return ordered;\n };\n\n /** Output file name -> the stylesheets it is built from. */\n const plan = new Map<string, string[]>();\n\n const packageStylesheet = assembledStylesheetName(workspace);\n if (packageStylesheet) {\n plan.set(\n packageStylesheet,\n stylesheetsOf(\n orderPackageChunks(graph, Object.keys(workspace.entry)),\n ),\n );\n } else {\n for (const [fileName, node] of graph) {\n if (!node.isEntry) continue;\n const target = `${node.name}.css`;\n if (!targets.has(target)) continue;\n plan.set(target, stylesheetsOf(orderChunks(graph, [fileName])));\n }\n }\n\n const outputs = new Set(plan.keys());\n const folded = new Set<string>();\n\n // Read everything before writing anything: an entry that imports another\n // entry lists that entry's stylesheet as a source, and must not read it\n // after it has been overwritten with its assembled form.\n const assembled = await Promise.all(\n [...plan].map(async ([target, sources]) => {\n // Nothing attributable to this stylesheet — one a plugin emitted\n // itself, or none at all. Either way there is nothing to rebuild.\n if (!sources.length) return undefined;\n sources.forEach((source) => folded.add(source));\n if (sources.length === 1 && sources[0] === target) return undefined;\n\n const parts = await Promise.all(\n sources.map((source) =>\n fs.readFile(path.join(dir, source), 'utf8').catch(() => ''),\n ),\n );\n const css = parts.filter(Boolean).join('\\n');\n return css ? { target, css } : undefined;\n }),\n );\n\n await Promise.all(\n assembled.map(\n (output) =>\n output && fs.writeFile(path.join(dir, output.target), output.css),\n ),\n );\n\n // Drop the per-chunk stylesheets that were folded into a declared one: they\n // are named after a chunk, so no export can point at them.\n await Promise.all(\n [...folded]\n .filter((css) => !outputs.has(css))\n .map((css) => fs.rm(path.join(dir, css), { force: true })),\n );\n },\n });\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { Plugin } from '../../types';\nimport type { PlugboyWorkspace } from '../workspace';\n\n/**\n * Plugin that inlines the contents of a `?raw` import.\n *\n * The virtual module id is kept **relative to the workspace** and turned back\n * into a path only inside `load`. rolldown normalizes an ordinary module id\n * against the project when it prints the `//#region <id>` comment that precedes\n * each module in the output, but a virtual id — anything starting with `\\0` — is\n * printed verbatim. Building the id from the resolved absolute path therefore\n * published the build machine's directory layout:\n *\n * ```js\n * //#region \\0raw:/home/runner/work/acme-ui/acme-ui/packages/core/src/logo.svg\n * ```\n *\n * A workspace-relative id makes the output independent of where the build ran,\n * which also keeps two machines' `dist` diffable.\n */\nconst PREFIX = '\\0raw:';\nconst SUFFIX = '?raw';\n\nexport function createRawLoaderPlugin(workspace: PlugboyWorkspace): Plugin {\n const root = workspace.dir.value;\n\n return {\n name: 'raw-loader',\n async resolveId(id, importer, options) {\n if (!id.endsWith(SUFFIX)) return null;\n\n const rawPath = id.slice(0, -SUFFIX.length);\n\n // Resolve a relative path to an absolute path\n const resolved = await this.resolve(rawPath, importer, {\n ...options,\n skipSelf: true,\n });\n\n if (!resolved) return null;\n\n // Posix separators keep the id — and with it the emitted comment —\n // identical on Windows.\n return `${PREFIX}${path\n .relative(root, resolved.id)\n .split(path.sep)\n .join(path.posix.sep)}`;\n },\n\n async load(id) {\n if (!id.startsWith(PREFIX)) return null;\n\n const content = await fs.readFile(\n path.resolve(root, id.slice(PREFIX.length)),\n 'utf-8',\n );\n return `export default ${JSON.stringify(content)};`;\n },\n };\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { definePlugin } from '../../utils';\nimport type { PlugboyWorkspace } from '../workspace';\nimport { listEmittedStylesheets } from '../stylesheets';\nimport { captureChunkGraph, orderPackageChunks } from '../chunk-order';\n\n/**\n * Plugin to preserve what tsdown's CSS pipeline would rewrite away at the top of\n * a stylesheet: external `@import` statements and the authored `@layer` order.\n *\n * **External `@import`s.** rolldown / tsdown's CSS pipeline (lightningcss)\n * resolves and inlines every `@import` it can. For bare package specifiers (e.g.\n * `@import url('material-symbols/rounded.css') layer(...)`) that is wrong for a\n * library build: it bloats the output and rebases the imported package's own\n * relative asset URLs (fonts) against our `dist`, breaking them. Such imports\n * should stay external so the consumer's bundler resolves them.\n *\n * **Layer order.** lightningcss drops a name from an `@layer a, b, c;` statement\n * when a block for it follows in the same stylesheet, since the block establishes\n * the same order. That holds for a standalone document, but not for a library\n * stylesheet whose statement also orders layers belonging to *other* packages:\n * once the name is gone, its position is decided by wherever its block happens to\n * land relative to those, and the authored order is lost. `@fastkit/vui` declares\n * `@layer vui-normalize, vui-color-scheme, …, vui;`, and losing `vui-normalize`\n * from it promoted the reset layer above the packages it is supposed to lose to.\n *\n * Both are captured from a `transform` hook declared `order: 'pre'`, which runs\n * ahead of tsdown's CSS handling even though that is registered as a *pre plugin*\n * — hook order wins over plugin order. It is the only point that sees the CSS of\n * **every** stylesheet in the graph, including a virtual one another plugin\n * supplies from `load`: vanilla-extract generates its `@layer` statements into\n * such a module, so a `load`-based capture would miss exactly the case where the\n * generated statement is the only record of the intended order. The captured\n * values are re-emitted in `writeBundle`, after every CSS producer has written\n * its final file to disk.\n */\n\n/**\n * Matches a single `@import` statement, capturing the quote (group 1) and the\n * imported specifier (group 2). Handles `url(...)`, quoted, and bare forms, and\n * tolerates trailing conditions (e.g. `layer(...)`, media queries).\n */\nconst IMPORT_RE = /@import\\s+(?:url\\(\\s*)?([\"']?)([^\"')\\s]+)\\1\\s*\\)?[^;]*;/g;\n\n/**\n * A specifier is \"internal\" (safe to bundle/inline) when it is relative,\n * absolute, a URL, a data URI, or a fragment. Anything else is treated as a\n * bare package specifier whose `@import` is preserved.\n */\nfunction isInternalImportSpecifier(spec: string): boolean {\n return /^(?:\\.{1,2}\\/|\\/|[a-z][a-z\\d+.-]*:|data:|#)/i.test(spec);\n}\n\n/** Matches a top-level `@layer <names>;` statement (declaration, not a block). */\nconst LAYER_STATEMENT_RE = /@layer\\s+([^{};]+);[ \\t]*\\n?/g;\n\n/** Stylesheet ids, with any query (`?source=…`, `?inline`) still attached. */\nconst STYLE_ID_RE = /\\.(?:css|scss|sass|less|styl|stylus)(?:$|\\?)/;\n\n/** The layer names a stylesheet declares, in the order it declares them. */\nfunction collectLayerNames(css: string): string[] {\n const names: string[] = [];\n for (const [, group] of css.matchAll(LAYER_STATEMENT_RE)) {\n for (const name of group.split(',')) {\n const trimmed = name.trim();\n if (trimmed && !names.includes(trimmed)) names.push(trimmed);\n }\n }\n return names;\n}\n\n/**\n * Merge several declaration orders into one that contradicts none of them.\n *\n * Concatenating them and dropping repeats does not work, because a name's first\n * appearance is rarely where its order is decided: vanilla-extract re-declares a\n * layer at the top of *every* stylesheet that puts a rule in it, so a single\n * `@layer that-one;` from some component is seen before the module that declares\n * how all the layers relate — and once the component's name is in the list, the\n * declaring module's order is silently dropped for it.\n *\n * Each sequence is therefore read as a set of \"must come before\" constraints and\n * the result is a topological sort of them, preferring the earliest-seen name when\n * several are free. Earlier sequences win: a constraint that would contradict one\n * already recorded is skipped, so a stylesheet's own surviving statement — whose\n * order tsdown may have rewritten — can add names without reordering anything.\n */\nfunction mergeLayerOrder(sequences: string[][]): string[] {\n const nodes: string[] = [];\n const next = new Map<string, Set<string>>();\n\n const add = (name: string) => {\n if (next.has(name)) return;\n nodes.push(name);\n next.set(name, new Set());\n };\n /** Whether `to` already has to come after `from`. */\n const precedes = (from: string, to: string): boolean => {\n const seen = new Set<string>();\n const stack = [from];\n while (stack.length) {\n const current = stack.pop()!;\n if (current === to) return true;\n if (seen.has(current)) continue;\n seen.add(current);\n stack.push(...(next.get(current) ?? []));\n }\n return false;\n };\n\n for (const sequence of sequences) {\n sequence.forEach(add);\n for (let i = 0; i + 1 < sequence.length; i++) {\n const from = sequence[i];\n const to = sequence[i + 1];\n if (from === to || precedes(to, from)) continue;\n next.get(from)!.add(to);\n }\n }\n\n const incoming = new Map(nodes.map((name) => [name, 0]));\n for (const [, targets] of next) {\n for (const target of targets) {\n incoming.set(target, (incoming.get(target) ?? 0) + 1);\n }\n }\n\n const remaining = new Set(nodes);\n const merged: string[] = [];\n while (remaining.size) {\n // A cycle can only come from contradicting sequences, which `precedes`\n // already rejects; the fallback keeps this terminating regardless.\n const name =\n nodes.find((it) => remaining.has(it) && incoming.get(it) === 0) ??\n nodes.find((it) => remaining.has(it))!;\n remaining.delete(name);\n merged.push(name);\n for (const target of next.get(name) ?? []) {\n incoming.set(target, (incoming.get(target) ?? 1) - 1);\n }\n }\n return merged;\n}\n\nexport function createPreserveCssImportsPlugin(workspace: PlugboyWorkspace) {\n // External `@import` statements, kept verbatim and in first-seen order.\n const externalImports: string[] = [];\n // Layer names per stylesheet module, captured before lightningcss can prune the\n // statements they came from. Keyed by module id, because the order modules are\n // transformed in is not the order their CSS ends up in.\n const layersByModule = new Map<string, string[]>();\n // The merged declaration order, filled in `generateBundle`.\n const declaredLayers: string[] = [];\n // Absolute paths already rewritten, to stay idempotent across output passes.\n const processed = new Set<string>();\n\n return definePlugin({\n name: 'preserve-css-imports',\n buildStart() {\n externalImports.length = 0;\n layersByModule.clear();\n declaredLayers.length = 0;\n processed.clear();\n },\n // Runs ahead of tsdown's CSS transform, which inlines the imports and prunes\n // the layer statements, so this is where both have to be captured.\n transform: {\n order: 'pre' as const,\n filter: { id: STYLE_ID_RE },\n handler(code: string, id: string) {\n const file = id.split('?')[0];\n if (!STYLE_ID_RE.test(file)) return null;\n\n const names = collectLayerNames(code);\n if (names.length) layersByModule.set(id, names);\n\n // Only plain CSS is rewritten here. A preprocessor's `@import` is its own\n // module system, resolved before any CSS ever reaches tsdown.\n if (!file.endsWith('.css') || !code.includes('@import')) return null;\n\n let changed = false;\n const stripped = code.replace(IMPORT_RE, (statement, _quote, spec) => {\n if (isInternalImportSpecifier(spec)) return statement;\n changed = true;\n const normalized = statement.trim();\n if (!externalImports.includes(normalized)) {\n externalImports.push(normalized);\n }\n return '';\n });\n if (!changed) return null;\n return { code: stripped, map: null };\n },\n },\n // Merge the per-module declarations into one order (see `mergeLayerOrder`).\n //\n // The sequences are visited in the order the stylesheets load: chunks in\n // dependency order (`orderPackageChunks`, which is also the order plugboy\n // assembles their CSS in), and modules in their position in `moduleIds`\n // within each chunk. That decides which sequence wins a contradiction, and\n // how free names are ordered; the order the `transform` hook happened to\n // visit modules in is not usable for either, and neither is the bundle's,\n // which puts a shared chunk after the entries that depend on it.\n generateBundle(_options, bundle) {\n if (!layersByModule.size) return;\n const sequences: string[][] = [];\n const ordered = orderPackageChunks(\n captureChunkGraph(bundle),\n Object.keys(workspace.entry),\n );\n for (const fileName of ordered) {\n const chunk = bundle[fileName];\n if (chunk?.type !== 'chunk') continue;\n for (const id of chunk.moduleIds) {\n const names = layersByModule.get(id);\n if (names) sequences.push(names);\n }\n }\n declaredLayers.length = 0;\n declaredLayers.push(...mergeLayerOrder(sequences));\n },\n // Re-emit the preserved imports and layer order into the final CSS files on\n // disk. Running in `writeBundle` (rather than `generateBundle`) lets every\n // other CSS producer — tsdown's own pipeline emits from a *post* plugin —\n // finish first.\n async writeBundle(options, bundle) {\n if (!externalImports.length && !declaredLayers.length) return;\n const { dir } = options;\n if (!dir) return;\n\n const importBlock = externalImports.length\n ? `${externalImports.join('\\n')}\\n`\n : '';\n\n const stylesheets = await listEmittedStylesheets(workspace, dir, bundle);\n\n await Promise.all(\n stylesheets.map(async (fileName) => {\n const filePath = path.join(dir, fileName);\n if (processed.has(filePath)) return;\n\n let css: string;\n try {\n css = await fs.readFile(filePath, 'utf8');\n } catch {\n // The asset may have been removed by another plugin.\n return;\n }\n processed.add(filePath);\n\n // Hoist all `@layer <names>;` declarations to the top so the cascade\n // order is fixed before any layered `@import` adds to a layer, then\n // place the imports right after (they must precede every style rule).\n //\n // The captured order decides; a name only this stylesheet declares is\n // merged in without reordering the rest.\n const layerNames = mergeLayerOrder([\n declaredLayers,\n collectLayerNames(css),\n ]);\n\n const body = css.replace(LAYER_STATEMENT_RE, '');\n const layerStatement = layerNames.length\n ? `@layer ${layerNames.join(', ')};\\n`\n : '';\n const next = `${layerStatement}${importBlock}${body}`;\n if (next !== css) await fs.writeFile(filePath, next);\n }),\n );\n },\n });\n}\n","import { Plugin } from '../../types';\nimport type { PlugboyWorkspace } from '../workspace';\n\n/**\n * A specifier is \"bare\" (a package specifier) when it is not relative, absolute,\n * a protocol-qualified id (`node:`, `data:`, `http:`, …) or a fragment. Only\n * bare specifiers are candidates for external resolution here.\n */\nfunction isBareSpecifier(id: string): boolean {\n return !/^(?:\\.{1,2}\\/|\\/|[a-z][a-z\\d+.-]*:|#)/i.test(id);\n}\n\n/** Whether `id` equals `name` or is a subpath of it (`name/...`). */\nfunction matchesPackage(id: string, name: string): boolean {\n return id === name || id.startsWith(`${name}/`);\n}\n\n/**\n * Resolve self-references and `deps.neverBundle` package imports as explicit\n * externals.\n *\n * rolldown only externalizes a specifier without warning when it matches the\n * `external` option *before* it tries to resolve it on disk. A `deps.neverBundle`\n * entry is a plain string, so it matches the package name exactly but not its\n * subpaths (`pkg/foo.svg`); and a package's own name is never in its\n * dependencies at all. Both therefore fall through to rolldown's\n * \"resolve failed → implicit external\" path, which emits a noisy\n * `UNRESOLVED_IMPORT` warning for every such import even though the resulting\n * external output is correct.\n *\n * This plugin intercepts those imports in `resolveId` and marks them external\n * up front, so the diagnostic never fires:\n *\n * - **Self-reference:** a package importing its own name (or a subpath of it).\n * The subpath is served at runtime from the consumer's `exports` map\n * (`\"./*\": \"./dist/*\"`); it cannot — and must not — be bundled into the build\n * that produces that very `dist`, so external is always the right answer.\n * - **`deps.neverBundle`:** the declared package names and any of their\n * subpaths.\n *\n * Specifiers that match neither are returned untouched, so genuine unresolved\n * imports (typos in a non-external package) still surface their warning.\n */\nexport function createExternalImportsPlugin(\n workspace: PlugboyWorkspace,\n): Plugin {\n const selfName = workspace.json.name;\n const { neverBundlePrefixes } = workspace;\n\n return {\n name: 'plugboy:external-imports',\n resolveId(id) {\n if (!isBareSpecifier(id)) return null;\n\n if (selfName && matchesPackage(id, selfName)) {\n return { id, external: true };\n }\n\n for (const prefix of neverBundlePrefixes) {\n if (matchesPackage(id, prefix)) {\n return { id, external: true };\n }\n }\n\n return null;\n },\n };\n}\n","import { Plugin } from '../../types';\n\n/**\n * The rolldown-plugin-dts sub-plugin that drives declaration bundling through a\n * \"fake JS\" module. Its `renderChunk` returns a bare `\"export { };\"` string\n * (with no sourcemap) whenever a `.d.ts` chunk reduces to an empty body — e.g.\n * an entry composed solely of external re-exports. With sourcemaps enabled\n * (plugboy sets `sourcemap: true` for the JS output, which the dts pipeline\n * inherits), rolldown then emits a spurious `[SOURCEMAP_BROKEN]` warning for a\n * declaration file that is perfectly correct.\n */\nconst DTS_FAKE_JS_PLUGIN_NAME = 'rolldown-plugin-dts:fake-js';\n\n/**\n * Suppress the harmless `[SOURCEMAP_BROKEN]` warning that rolldown-plugin-dts's\n * fake-js pass emits for empty declaration chunks.\n *\n * The filter is intentionally narrow — it only drops a `warn`-level\n * `SOURCEMAP_BROKEN` log **attributed to `rolldown-plugin-dts:fake-js`**. Real\n * sourcemap breakage on JS output (emitted by other plugins, or with no plugin\n * attribution) has a different `plugin` field and passes through untouched, so\n * genuine problems are still reported.\n *\n * The suppression is re-emitted at `debug` level so it can be traced by running\n * a build with a debug log level.\n *\n * TODO(upstream): remove this workaround once rolldown-plugin-dts returns a\n * valid (empty) sourcemap for empty chunks instead of a bare string. Track at\n * https://github.com/sxzz/rolldown-plugin-dts and, once fixed, bump the tsdown\n * (rolldown-plugin-dts) dependency range and delete this file, its re-export\n * from `./index`, and its registration in `workspace.ts`.\n */\nexport function createSuppressDtsSourcemapWarningPlugin(): Plugin {\n return {\n name: 'plugboy:suppress-dts-sourcemap-warning',\n onLog(level, log) {\n if (\n level === 'warn' &&\n log.code === 'SOURCEMAP_BROKEN' &&\n log.plugin === DTS_FAKE_JS_PLUGIN_NAME\n ) {\n this.debug(() => ({\n code: 'PLUGBOY_SUPPRESSED_DTS_SOURCEMAP_BROKEN',\n message: `Suppressed a spurious [SOURCEMAP_BROKEN] warning from ${DTS_FAKE_JS_PLUGIN_NAME} for an empty declaration chunk. Original message: ${log.message}`,\n }));\n return false;\n }\n },\n };\n}\n","import sortPackageJson from 'sort-package-json';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n rmrf,\n loadWorkspaceConfig,\n resolveUserHooks,\n buildHooks,\n mergeExternals,\n mergeNoExternals,\n collectExternalStringPrefixes,\n writeFileAtomic,\n} from '../utils';\nimport {\n type ProjectPackageJson,\n type WorkspacePackageJson,\n type ResolvedWorkspaceConfig,\n type WorkspaceDirs,\n type WorkspaceSetupContext,\n type WorkspaceMeta,\n type Plugin,\n type UserHooks,\n type BuildedHooks,\n mergeDTSSettingsList,\n type NormalizedDTSSettings,\n type ResolvedOptimizeCSSOptions,\n resolveOptimizeCSSOptions,\n} from '../types';\nimport { Path } from '../path';\nimport { WORKSPACE_SPEC_PREFIX, PACKAGE_JSON_FILENAME } from '../constants';\nimport { PlugboyProject, getProject } from '../project';\nimport { Builder } from './builder';\nimport { getWorkspacePackageJson } from '../package';\nimport { WorkspaceEnvPlugin } from '../env';\nimport { OptimizeCSSPlugin } from '../postcss/plugin';\nimport {\n createRawLoaderPlugin,\n createAssembleEntryCssPlugin,\n createPreserveCssImportsPlugin,\n createExternalImportsPlugin,\n createSuppressDtsSourcemapWarningPlugin,\n} from './plugins';\nimport { resolveCssOptions } from './stylesheets';\nimport { type CssOptions } from '@tsdown/css';\n\nexport type WorkspaceStubLink =\n | {\n type: 'js';\n from: string;\n to: string;\n }\n | {\n type: 'css';\n from: string;\n };\n\nexport type WorkspaceStubLinkType = WorkspaceStubLink['type'];\n\nexport interface WorkspaceObjectExport {\n src: string;\n types: string;\n dtsDest: string;\n import: {\n default: string;\n };\n}\n\nfunction extractWorkspaceObjectExport(at: string | WorkspaceObjectExport) {\n if (typeof at === 'string') return at;\n const { types, import: _import } = at;\n return {\n types,\n import: _import,\n };\n}\n\nexport interface WorkspaceExport {\n id: string;\n at: string | WorkspaceObjectExport;\n stubLink?: WorkspaceStubLink;\n}\n\nexport const WORKSPACE_PACKAGE_SYNC_FIELDS = [\n 'repository',\n 'author',\n 'publishConfig',\n 'license',\n] as const;\n\nexport function syncWorkspacePackageFields(\n projectJSON: ProjectPackageJson,\n workspaceJSON: WorkspacePackageJson,\n) {\n for (const field of WORKSPACE_PACKAGE_SYNC_FIELDS) {\n const value = projectJSON[field];\n if (value && !workspaceJSON[field]) {\n workspaceJSON[field] = value as any;\n }\n }\n}\n\nconst BUILD_TARGET_SRC_MATCH_RE = /\\.(tsx?|s?css)$/;\n\nexport class PlugboyWorkspace {\n readonly name: string;\n\n readonly dir: Path;\n\n readonly config: ResolvedWorkspaceConfig;\n\n readonly project: PlugboyProject | null;\n\n readonly dirs: WorkspaceDirs;\n\n readonly dependencies: string[];\n\n readonly projectDependencies: string[];\n\n readonly neverBundlePrefixes: string[];\n\n readonly meta: WorkspaceMeta;\n\n readonly entry: Record<string, string>;\n\n readonly exports: WorkspaceExport[];\n\n readonly builder: Builder;\n\n readonly plugins: Plugin[];\n\n readonly hooks: BuildedHooks;\n\n readonly dtsFiles: string[] = [];\n\n readonly dts: NormalizedDTSSettings;\n\n cssOptions: CssOptions | undefined;\n\n readonly optimizeCSSOptions: ResolvedOptimizeCSSOptions | false;\n\n private _json: WorkspacePackageJson;\n\n get json() {\n return this._json;\n }\n\n constructor(ctx: WorkspaceSetupContext) {\n const {\n dir,\n json,\n config,\n project,\n dirs,\n dependencies,\n projectDependencies,\n neverBundlePrefixes,\n meta,\n plugins,\n hooks,\n dts,\n css,\n optimizeCSS,\n } = ctx;\n\n this.name = dir.basename;\n this.dir = dir;\n this._json = json;\n this.project = project;\n this.dirs = dirs;\n this.dependencies = dependencies;\n this.projectDependencies = projectDependencies;\n this.neverBundlePrefixes = neverBundlePrefixes;\n this.meta = meta;\n this.config = config;\n this.plugins = [\n // Runs first so self-reference / `neverBundle` imports are marked external\n // before any resolver (built-in or user) can attempt — and fail — to\n // resolve them on disk.\n createExternalImportsPlugin(this),\n // Filters the spurious dts SOURCEMAP_BROKEN warning; harmless if the dts\n // pipeline is absent, so it can live alongside the other plugins.\n createSuppressDtsSourcemapWarningPlugin(),\n ...plugins,\n // Must precede the stages that post-process the written stylesheets.\n createAssembleEntryCssPlugin(this),\n OptimizeCSSPlugin(this),\n WorkspaceEnvPlugin(this),\n createRawLoaderPlugin(this),\n createPreserveCssImportsPlugin(this),\n ];\n this.hooks = hooks;\n this.dts = dts;\n this.optimizeCSSOptions = optimizeCSS\n ? resolveOptimizeCSSOptions(optimizeCSS)\n : false;\n\n const entry: Record<string, string> = {};\n const cssEntryIds: string[] = [];\n const exports: WorkspaceExport[] = [\n {\n id: `./${PACKAGE_JSON_FILENAME}`,\n at: `./${PACKAGE_JSON_FILENAME}`,\n },\n ];\n\n Object.entries(config.entries).forEach(([id, { src, css }]) => {\n if (!BUILD_TARGET_SRC_MATCH_RE.test(src)) return;\n\n const isMainEntry = id === '.';\n const normalizedId = isMainEntry ? this.name : id;\n const exportId = id.startsWith('.') ? id : `./${id}`;\n const srcIsCSS = src.endsWith('.css') || src.endsWith('.scss');\n const ext = srcIsCSS ? 'css' : 'mjs';\n const dest = `./dist/${normalizedId}.${ext}`;\n const destFullPath = dir.join(dest).value;\n\n entry[normalizedId] = src;\n\n if (css) {\n cssEntryIds.push(normalizedId);\n const cssDest = `./dist/${normalizedId}.css`;\n exports.push({\n id: `./${normalizedId}.css`,\n at: cssDest,\n stubLink: {\n type: 'css',\n from: cssDest,\n },\n });\n\n if (srcIsCSS) return;\n }\n\n const types = `./dist/${normalizedId}.d.mts`;\n const dtsDest = `./dist/${src\n .replace(/^\\.\\/src/, '.dts')\n .replace(/\\.ts$/, '.d.mts')}`;\n\n this.dtsFiles.push(dir.join(types).value);\n exports.push({\n id: exportId,\n at: {\n src,\n types,\n dtsDest,\n import: {\n default: dest,\n },\n },\n stubLink: {\n from: destFullPath,\n to: path.isAbsolute(src) ? src : dir.join(src).value,\n type: 'js',\n },\n });\n });\n\n this.entry = entry;\n this.exports = exports;\n this.cssOptions = resolveCssOptions(css, cssEntryIds);\n this.builder = new Builder(this);\n }\n\n clean(withDepsAndCache?: boolean) {\n const { dir, dirs } = this;\n const paths: string[] = [dirs.dist.value];\n if (withDepsAndCache) {\n paths.push(dir.join('node_modules').value, dir.join('.turbo').value);\n }\n return rmrf(...paths);\n }\n\n async preparePackageJSON() {\n const { exports, json, project } = this;\n const _exports: Record<string, any> = {};\n const typesVersions: Record<string, any> = {};\n let main: string | undefined;\n let mainTypes: string | undefined;\n\n exports.forEach(({ id, at }) => {\n const _at = extractWorkspaceObjectExport(at);\n _exports[id] = _at;\n if (typeof _at !== 'object') return;\n const isMainExport = id === '.';\n const trimmedId = isMainExport ? id : id.replace(/^\\.\\//, '');\n typesVersions[trimmedId] = [_at.types];\n\n if (isMainExport) {\n main = _at.import.default;\n mainTypes = _at.types;\n }\n });\n\n if (json.exports) {\n const entries = Object.entries(json.exports);\n entries.forEach(([id, at]) => {\n const types = Object.keys(at!);\n if (types.length === 1 && types[0] === 'types') {\n _exports[id] = at;\n }\n });\n }\n\n _exports['./*'] = './dist/*';\n\n // Compact: this doubles as the deep-clone source and as the left-hand side\n // of the change check below.\n const originalJSONString = JSON.stringify(json);\n const cloned: typeof json = JSON.parse(originalJSONString);\n cloned.exports = _exports;\n cloned.typesVersions = {\n '*': typesVersions,\n };\n if (main) cloned.main = main;\n if (mainTypes) cloned.types = mainTypes;\n\n // delete cloned.main;\n // delete cloned.types;\n // delete cloned.typesVersions;\n\n const projectPeerDependencies = project?.config.peerDependencies;\n (['dependencies', 'devDependencies', 'peerDependencies'] as const).forEach(\n (prop) => {\n const deps = cloned[prop];\n if (!deps) return;\n Object.keys(deps).forEach((dep) => {\n const version = deps[dep];\n if (version.startsWith(WORKSPACE_SPEC_PREFIX)) {\n deps[dep] = `${WORKSPACE_SPEC_PREFIX}^`;\n } else if (\n projectPeerDependencies &&\n projectPeerDependencies[dep] &&\n !deps[dep]\n ) {\n deps[dep] = projectPeerDependencies[dep];\n }\n });\n },\n );\n\n cloned.files = cloned.files || [];\n if (!cloned.files.some((file) => /(\\.\\/)?dist\\/?/.test(file))) {\n cloned.files.unshift('dist');\n }\n\n if (project) {\n syncWorkspacePackageFields(project.json, cloned);\n }\n\n cloned.type = cloned.type || 'module';\n\n await this.hooks.preparePackageJSON(json, this);\n\n const sorted = sortPackageJson(cloned);\n\n // Write only when the fields or their order actually changed. Both sides are\n // compact, so the check is about content and not about layout: plugboy owns\n // what the file says, and leaves the whitespace between it to whatever\n // formatter the repo runs.\n //\n // Key order counts as content. Ignoring it would quietly disable\n // `sortPackageJson` for every file that already exists, which is most of\n // them.\n //\n // This is what the check was always meant to be. It compared against the\n // *indented* output, which a compact string can never equal, so it fired on\n // every build of every workspace -- invisibly, because the bytes written\n // usually matched the bytes already there.\n if (originalJSONString !== JSON.stringify(sorted)) {\n // `.editorconfig` sets `insert_final_newline`, and `JSON.stringify` emits\n // none, so a built `package.json` used to lose the newline a formatter or\n // a hand edit had given it.\n await writeFileAtomic(\n this.dir.join(PACKAGE_JSON_FILENAME).value,\n `${JSON.stringify(sorted, null, 2)}\\n`,\n );\n }\n this._json = sorted;\n return sorted;\n }\n\n getStubLinks(): WorkspaceStubLink[] {\n const links: WorkspaceStubLink[] = [];\n this.exports.forEach(({ stubLink }) => {\n stubLink && links.push(stubLink);\n });\n return links;\n }\n\n async stub() {\n await this.clean();\n await fs.mkdir(this.dirs.dist.value);\n return this.builder.stub();\n }\n\n async build() {\n await this.clean();\n return this.builder.build();\n }\n}\n\nexport async function getWorkspace<\n AllowMissing extends boolean | undefined = false,\n>(\n searchDir?: string,\n allowMissing?: AllowMissing,\n): Promise<\n AllowMissing extends true ? PlugboyWorkspace | null : PlugboyWorkspace\n> {\n const hit = await getWorkspacePackageJson(searchDir, allowMissing);\n if (!hit) {\n return null as any;\n }\n const { dir, json } = hit;\n const config = await loadWorkspaceConfig(dir.value, 0);\n\n const project = await getProject(dir.value, true, config.ignoreProjectConfig);\n\n const dirs: WorkspaceDirs = {\n src: dir.join('src'),\n dist: dir.join('dist'),\n };\n\n const { dependencies, peerDependencies, optionalDependencies } = json;\n const allDeps = {\n ...dependencies,\n ...peerDependencies,\n ...optionalDependencies,\n };\n\n const _dependencies = Object.keys(allDeps);\n\n const projectDependencies = Object.entries(allDeps)\n .filter(([dep, spec]) => spec.startsWith(WORKSPACE_SPEC_PREFIX))\n .map(([dep]) => dep);\n\n const meta: WorkspaceMeta = {};\n\n // Prefixes for the external-imports plugin. Seeded from the user's initial\n // `deps.neverBundle` and extended by any `ctx.mergeExternals` calls made\n // during workspace setup (see below).\n const neverBundlePrefixes = collectExternalStringPrefixes(\n config.deps?.neverBundle,\n );\n\n const projectPlugins = project?.plugins || [];\n const projectHooks = project?.hooks || [];\n const plugins: Plugin[] = [...projectPlugins, ...config.plugins];\n const _hooks: UserHooks[] = [...projectHooks];\n if (config.hooks) {\n _hooks.push(config.hooks);\n }\n for (const plugin of config.plugins) {\n if (plugin.hooks) {\n _hooks.push(plugin.hooks);\n }\n }\n const resolvedHooks = await resolveUserHooks(..._hooks);\n const hooks = buildHooks(resolvedHooks);\n\n const dts = mergeDTSSettingsList(project?.config.dts, config.dts);\n\n let { optimizeCSS } = config;\n if (optimizeCSS !== false && project && project.config.optimizeCSS) {\n optimizeCSS = {\n ...project.config.optimizeCSS,\n ...optimizeCSS,\n };\n }\n\n // Unlike `target`, the keys of `css` are independent, so the workspace value\n // is shallow-merged over the project one (mirroring `optimizeCSS`). Stays\n // `undefined` when neither layer sets it, leaving tsdown's own defaults alone.\n const css =\n config.css || project?.config.css\n ? { ...project?.config.css, ...config.css }\n : undefined;\n\n // Inherit the project's `target` unless the workspace declares its own. A\n // target list describes one environment set, so the workspace value replaces\n // the project default rather than merging with it. `??` (not `||`) keeps an\n // explicit `false` — tsdown's \"apply no transformation\" — intact.\n config.target ??= project?.config.target;\n\n const ctx: WorkspaceSetupContext = {\n dir,\n json,\n config,\n project,\n dirs,\n dependencies: _dependencies,\n projectDependencies,\n neverBundlePrefixes,\n meta,\n plugins,\n hooks,\n dts,\n css,\n optimizeCSS,\n mergeExternals: (override) => {\n config.deps ??= {};\n config.deps.neverBundle = mergeExternals(\n config.deps.neverBundle,\n override,\n );\n neverBundlePrefixes.push(...collectExternalStringPrefixes(override));\n },\n mergeNoExternals: (override) => {\n config.deps ??= {};\n config.deps.alwaysBundle = mergeNoExternals(\n config.deps.alwaysBundle,\n override,\n );\n },\n };\n\n await hooks.setupWorkspace(ctx, () => {\n return typeof workspace === 'undefined' ? undefined : workspace;\n });\n\n const workspace = new PlugboyWorkspace(ctx);\n\n await hooks.createWorkspace(workspace);\n\n return workspace;\n}\n","/* eslint-disable no-console */\nimport path from 'node:path';\nimport fs from 'node:fs/promises';\nimport sortPackageJson from 'sort-package-json';\nimport * as prompts from '@inquirer/prompts';\nimport { getProject } from '../project';\nimport { getWorkspace, syncWorkspacePackageFields } from '../workspace';\nimport { WorkspacePackageJson, ProjectScriptsTemplate } from '../types';\nimport { WORKSPACE_CONFIG_BASENAME, WORKSPACE_SPEC_PREFIX } from '../constants';\n\nexport async function generateWorkspace(\n workspaceName?: string,\n cwd = process.cwd(),\n) {\n const project = await getProject(cwd);\n const { config } = project;\n\n // ====================\n // workspace name\n // ====================\n while (!workspaceName) {\n const value = await prompts.input({\n message: 'Enter a workspace name',\n });\n\n if (value) {\n workspaceName = value;\n }\n }\n\n // ====================\n // description\n // ====================\n const description = await prompts.input({\n default: workspaceName,\n message: 'Please enter a description of your package',\n });\n\n // ====================\n // version\n // ====================\n let version: string | undefined;\n while (!version) {\n const value = await prompts.input({\n default: '0.0.0',\n message: 'Please enter the initial version',\n });\n\n if (value) {\n version = value;\n }\n }\n\n // ====================\n // keywords\n // ====================\n const rawKeywords = await prompts.input({\n message: 'Enter as many keywords, if any, as needed, separated by commas',\n });\n\n const keywords = (rawKeywords as string)\n .split(',')\n .map((word) => word.trim())\n .filter((word) => word.length);\n\n // ====================\n // scripts\n // ====================\n const scriptsTemplates = config.scripts;\n let scriptsTemplate: ProjectScriptsTemplate | undefined;\n if (scriptsTemplates && scriptsTemplates.length) {\n const value = await prompts.rawlist({\n message: 'Select a scripts template',\n choices: [\n { name: 'None', value: '' },\n ...scriptsTemplates.map((tpl) => ({\n name: tpl.name,\n value: tpl.name,\n })),\n ],\n });\n scriptsTemplate = scriptsTemplates.find((tpl) => tpl.name === value);\n }\n const scripts = scriptsTemplate?.scripts || {};\n\n // ====================\n // peerDependencies\n // ====================\n const peerDependencies = await (async () => {\n const deps = await prompts.checkbox({\n message:\n 'Select the dependent packages, if any, to be used in the package',\n choices: Object.keys(config.peerDependencies).map((dep) => ({\n name: dep,\n value: dep,\n })),\n });\n if (!deps.length) return;\n return Object.fromEntries(\n deps.map((dep) => [dep, config.peerDependencies[dep]]),\n );\n })();\n\n // ====================\n // dependencies\n // ====================\n const dependencies = await (async () => {\n const deps = await prompts.checkbox({\n message: 'Select the internal package to be used, if any.',\n choices: project.resolvedWorkspaces.map((workspace) => {\n const name = path.basename(workspace);\n return {\n name,\n value: name,\n };\n }),\n });\n if (!deps.length) return;\n return Object.fromEntries(\n deps.map((dep) => [\n `@${project.name}/${dep}`,\n `${WORKSPACE_SPEC_PREFIX}^`,\n ]),\n );\n })();\n\n // ====================\n // Generate source files?\n // ====================\n const withGenSource = await prompts.confirm({\n message: 'Generate source files?',\n default: true,\n });\n\n // ====================\n // final confirmation\n // ====================\n const _json: WorkspacePackageJson = {\n name: `@${project.name}/${workspaceName}`,\n type: 'module',\n description,\n version,\n keywords,\n scripts,\n peerDependencies,\n dependencies,\n };\n\n syncWorkspacePackageFields(project.json, _json);\n\n const json = sortPackageJson(_json);\n\n const workspaceDir = path.join(config.workspacesDir, workspaceName);\n\n console.log('');\n console.log('========================================');\n console.log(`Directory: ${workspaceDir}`);\n console.log(`Generate source: ${withGenSource ? 'Yes' : 'No'}`);\n console.log(json);\n console.log('========================================');\n\n const confirmation = await prompts.confirm({\n message: 'Is this OK?',\n default: true,\n });\n\n if (!confirmation) {\n console.log('Skipped.');\n process.exit(1);\n }\n\n // 1. Create directory\n await fs.mkdir(workspaceDir);\n\n // 2. Write package.json\n await fs.writeFile(\n path.join(workspaceDir, 'package.json'),\n `${JSON.stringify(json, null, 2)}\\n`,\n );\n\n // 3. Write README.md\n await fs.writeFile(path.join(workspaceDir, 'README.md'), config.readme(json));\n\n // 3. Generate source\n if (withGenSource) {\n const srcDir = path.join(workspaceDir, 'src');\n await fs.mkdir(srcDir);\n\n const indexCode = `export * from './${workspaceName}';\\n`;\n const modCode = `export const PACKAGE_NAME = './${workspaceName}';\\n`;\n\n await fs.writeFile(path.join(srcDir, 'index.ts'), indexCode);\n await fs.writeFile(path.join(srcDir, `${workspaceName}.ts`), modCode);\n\n const { tsconfig } = config;\n if (tsconfig) {\n await fs.writeFile(\n path.join(workspaceDir, 'tsconfig.json'),\n `${JSON.stringify(tsconfig, null, 2)}\\n`,\n );\n }\n\n const configFileCode = `${`\nimport { defineWorkspaceConfig } from '@fastkit/plugboy';\n\nexport default defineWorkspaceConfig({\n entries: {\n '.': './src/index.ts',\n },\n});\n `.trim()}\\n`;\n await fs.writeFile(\n path.join(workspaceDir, `${WORKSPACE_CONFIG_BASENAME}.ts`),\n configFileCode,\n );\n\n const workspace = await getWorkspace(workspaceDir);\n await workspace.preparePackageJSON();\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAiCA,SAAgB,sBAAqC;CACnD,OAAO;EACL,gBAAgB,CAAC;EACjB,iBAAiB,CAAC;EAClB,oBAAoB,CAAC;CACvB;AACF;;;ACSA,SAAgB,+BACd,QACiC;CACjC,MAAM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