@kubb/plugin-barrel 5.8.4 → 5.9.1
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 +17 -17
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/docs/options.md +1 -1
- package/docs/overview.md +13 -11
- package/kubb-extension.json +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
|
|
25
25
|
### Barrel-file plugin for Kubb
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
Generates `index.ts` re-export files for each plugin output directory, and a root `index.ts` when `output.barrel` is set on `defineConfig`.
|
|
28
28
|
|
|
29
29
|
## Installation
|
|
30
30
|
|
|
@@ -38,42 +38,42 @@ npm install @kubb/plugin-barrel
|
|
|
38
38
|
|
|
39
39
|
## Usage
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
`defineConfig` adds `pluginBarrel()` to `plugins` for you, so you do not add it yourself. Set `output.barrel` on `defineConfig` to write a root barrel and to give every plugin without its own `output.barrel` the same setting:
|
|
42
42
|
|
|
43
43
|
```typescript
|
|
44
44
|
import { defineConfig } from 'kubb'
|
|
45
|
-
import {
|
|
45
|
+
import { pluginTs } from '@kubb/plugin-ts'
|
|
46
46
|
|
|
47
47
|
export default defineConfig({
|
|
48
48
|
input: './openapi.yaml',
|
|
49
49
|
output: {
|
|
50
50
|
path: './src/gen',
|
|
51
|
+
barrel: { type: 'named' },
|
|
51
52
|
},
|
|
52
|
-
plugins: [
|
|
53
|
-
pluginBarrel({
|
|
54
|
-
type: 'named',
|
|
55
|
-
}),
|
|
56
|
-
],
|
|
53
|
+
plugins: [pluginTs()],
|
|
57
54
|
})
|
|
58
55
|
```
|
|
59
56
|
|
|
60
57
|
## Options
|
|
61
58
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
|
59
|
+
`pluginBarrel()` takes no arguments. You configure it through `output.barrel`, on `defineConfig` or on a single plugin.
|
|
60
|
+
|
|
61
|
+
| Option | Type | Default | Description |
|
|
62
|
+
| ---------------------- | ------------------------------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
63
|
+
| `output.barrel` | `{ type: 'all' \| 'named', nested?: boolean } \| false` | `false` on `defineConfig` | Barrel settings. `false` on a plugin turns its barrel off and leaves its files out of the root one |
|
|
64
|
+
| `output.barrel.type` | `'all' \| 'named'` | None | Export style for the generated barrel files |
|
|
65
|
+
| `output.barrel.nested` | `boolean` | `false` | Plugin only. Each barrel re-exports its own directory and the barrels below it |
|
|
65
66
|
|
|
66
67
|
### Export types
|
|
67
68
|
|
|
68
|
-
| Value
|
|
69
|
-
|
|
|
70
|
-
| `'all'`
|
|
71
|
-
| `'named'`
|
|
72
|
-
| `'propagate'` | `export * from './...'` on index files only, propagating up through directories |
|
|
69
|
+
| Value | Output |
|
|
70
|
+
| --------- | ----------------------------------------------------------------------- |
|
|
71
|
+
| `'all'` | `export * from './...'` — wildcard re-exports |
|
|
72
|
+
| `'named'` | `export { ... } from './...'` — named re-exports, tree-shaking friendly |
|
|
73
73
|
|
|
74
74
|
## How it works
|
|
75
75
|
|
|
76
|
-
After every plugin finishes generating files, `@kubb/plugin-barrel` walks the output tree and creates an `index.ts` in each directory
|
|
76
|
+
After every plugin finishes generating files, `@kubb/plugin-barrel` walks the output tree and creates an `index.ts` in each directory of every plugin output with a barrel enabled. When `output.barrel` is set on `defineConfig`, it also creates a root `index.ts` at the top of the output path that re-exports the files of every plugin that does not set `output.barrel: false`.
|
|
77
77
|
|
|
78
78
|
`@kubb/plugin-barrel` uses `enforce: 'post'` so it always runs after all regular plugins complete, giving it access to the full set of generated files.
|
|
79
79
|
|
package/dist/index.cjs
CHANGED
|
@@ -71,7 +71,7 @@ var compatibility = {
|
|
|
71
71
|
};
|
|
72
72
|
//#endregion
|
|
73
73
|
//#region package.json
|
|
74
|
-
var version = "5.
|
|
74
|
+
var version = "5.9.1";
|
|
75
75
|
//#endregion
|
|
76
76
|
//#region src/utils.ts
|
|
77
77
|
const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
@@ -347,7 +347,8 @@ const pluginBarrel = (0, _kubb_kit.defineExtension)({
|
|
|
347
347
|
meta: {
|
|
348
348
|
name: pluginBarrelName,
|
|
349
349
|
version,
|
|
350
|
-
compatibility
|
|
350
|
+
compatibility,
|
|
351
|
+
issues: "https://github.com/kubb-labs/kubb/issues"
|
|
351
352
|
},
|
|
352
353
|
enforce: "post",
|
|
353
354
|
hooks: {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["resolve","relative","isAbsolute","posix","Diagnostics","ast","extname","defineExtension","path","Diagnostics"],"sources":["../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport { toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name in sorted order.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/**\n * Orders paths split into segments the way a directory listing sorts them: by name at each level.\n */\nfunction compareSegments(a: ReadonlyArray<string>, b: ReadonlyArray<string>): number {\n const index = a.findIndex((segment, i) => segment !== b[i])\n if (index === -1) return a.length - b.length\n if (index >= b.length) return 1\n\n return a[index]! < b[index]! ? -1 : 1\n}\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n return `./${posix.relative(fromDir, filePath)}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, { sourceFiles, reportedCollisions }: WalkContext): ast.FileNode {\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = item.name == null ? (sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []) : [item.name].flat()\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n return ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\nfunction indexableNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is indexable.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const sources = sourceFile?.sources ?? []\n return sources.length > 0 && !sources.some((source) => source.isIndexable) ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n if (!sourceFile?.sources.length) return [ast.factory.createExport({ path })]\n\n const valueNames = indexableNames(sourceFile.sources, false)\n const typeNames = indexableNames(sourceFile.sources, true)\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = [...node.children.values()].map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = [...node.children.values()].map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, ctx)\n const exports = barrels.length > 0 ? [ast.factory.createExport({ path: toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`) })] : []\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex(outputPath: string, files: ReadonlyArray<ast.FileNode>): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = filePath.startsWith(`${tree.path}/`) && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n // Inserting paths in per-segment order keeps every directory's children sorted by name.\n const entries = [...sourceFiles.keys()]\n .map((filePath) =>\n filePath\n .slice(tree.path.length + 1)\n .split('/')\n .filter(Boolean),\n )\n .sort(compareSegments)\n entries.forEach((parts) => {\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child: TreeNode = dir.children.get(part) ?? (i === parts.length - 1 ? { path } : { path, children: new Map() })\n dir.children.set(part, child)\n return child.children ? child : dir\n }, tree)\n })\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /**\n * Absolute directory the barrel(s) should be rooted at, a subtree of the index root.\n * Defaults to the index root.\n */\n targetPath?: string\n /**\n * Export strategy used when emitting each barrel.\n * - `'all'` re-exports the whole module (`export * from './x'`)\n * - `'named'` re-exports only the indexable named symbols\n */\n barrelType: BarrelType\n /**\n * Generate an `index.ts` in every sub-directory, each re-exporting only what's directly inside it (hierarchical).\n * When false, uses flat generation strategy with optional recursive subdirectory barrels.\n */\n nested?: boolean\n /**\n * Also generate a barrel for each sub-directory when nested is false.\n * No effect when nested is true (always generates hierarchical structure).\n */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex(outputPath, files)\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n reportedCollisions,\n recursive,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside } from '@internals/utils'\nimport { defineExtension, Diagnostics } from '@kubb/kit'\nimport type { ast, Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a\n * banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const resolver = plugin.resolver\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!resolver || (!hasBanner && !hasFooter)) return file\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = new WeakMap<Config, BarrelState>()\n\nfunction getState(config: Config): BarrelState {\n const state = states.get(config) ?? { excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }\n states.set(config, state)\n return state\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`, but generates\n * nothing until a barrel is configured.\n *\n * Each plugin inherits `output.barrel` from `config.output.barrel` (which\n * defaults to `false`, no barrel). Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n const index = buildBarrelIndex(outputPath, relevantFiles)\n const reportedCollisions = new Set<string>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+JA,SAAgB,YAAY,UAA0B;CACpD,OAAO,SAAS,WAAW,MAAM,GAAG;AACtC;;;;;;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AC;EACH;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["resolve","relative","isAbsolute","posix","Diagnostics","ast","extname","defineExtension","path","Diagnostics"],"sources":["../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport { toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name in sorted order.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/**\n * Orders paths split into segments the way a directory listing sorts them: by name at each level.\n */\nfunction compareSegments(a: ReadonlyArray<string>, b: ReadonlyArray<string>): number {\n const index = a.findIndex((segment, i) => segment !== b[i])\n if (index === -1) return a.length - b.length\n if (index >= b.length) return 1\n\n return a[index]! < b[index]! ? -1 : 1\n}\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n return `./${posix.relative(fromDir, filePath)}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, { sourceFiles, reportedCollisions }: WalkContext): ast.FileNode {\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = item.name == null ? (sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []) : [item.name].flat()\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n return ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\nfunction indexableNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is indexable.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const sources = sourceFile?.sources ?? []\n return sources.length > 0 && !sources.some((source) => source.isIndexable) ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n if (!sourceFile?.sources.length) return [ast.factory.createExport({ path })]\n\n const valueNames = indexableNames(sourceFile.sources, false)\n const typeNames = indexableNames(sourceFile.sources, true)\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = [...node.children.values()].map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = [...node.children.values()].map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, ctx)\n const exports = barrels.length > 0 ? [ast.factory.createExport({ path: toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`) })] : []\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex(outputPath: string, files: ReadonlyArray<ast.FileNode>): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = filePath.startsWith(`${tree.path}/`) && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n // Inserting paths in per-segment order keeps every directory's children sorted by name.\n const entries = [...sourceFiles.keys()]\n .map((filePath) =>\n filePath\n .slice(tree.path.length + 1)\n .split('/')\n .filter(Boolean),\n )\n .sort(compareSegments)\n entries.forEach((parts) => {\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child: TreeNode = dir.children.get(part) ?? (i === parts.length - 1 ? { path } : { path, children: new Map() })\n dir.children.set(part, child)\n return child.children ? child : dir\n }, tree)\n })\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /**\n * Absolute directory the barrel(s) should be rooted at, a subtree of the index root.\n * Defaults to the index root.\n */\n targetPath?: string\n /**\n * Export strategy used when emitting each barrel.\n * - `'all'` re-exports the whole module (`export * from './x'`)\n * - `'named'` re-exports only the indexable named symbols\n */\n barrelType: BarrelType\n /**\n * Generate an `index.ts` in every sub-directory, each re-exporting only what's directly inside it (hierarchical).\n * When false, uses flat generation strategy with optional recursive subdirectory barrels.\n */\n nested?: boolean\n /**\n * Also generate a barrel for each sub-directory when nested is false.\n * No effect when nested is true (always generates hierarchical structure).\n */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex(outputPath, files)\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n reportedCollisions,\n recursive,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside } from '@internals/utils'\nimport { defineExtension, Diagnostics } from '@kubb/kit'\nimport type { ast, Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a\n * banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const resolver = plugin.resolver\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!resolver || (!hasBanner && !hasFooter)) return file\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = new WeakMap<Config, BarrelState>()\n\nfunction getState(config: Config): BarrelState {\n const state = states.get(config) ?? { excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }\n states.set(config, state)\n return state\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`, but generates\n * nothing until a barrel is configured.\n *\n * Each plugin inherits `output.barrel` from `config.output.barrel` (which\n * defaults to `false`, no barrel). Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n const index = buildBarrelIndex(outputPath, relevantFiles)\n const reportedCollisions = new Set<string>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+JA,SAAgB,YAAY,UAA0B;CACpD,OAAO,SAAS,WAAW,MAAM,GAAG;AACtC;;;;;;;;;;;;;;;AAkCA,SAAgB,aAAa,MAAc,QAAyB;CAClE,MAAM,gBAAA,GAAeA,UAAAA,QAAAA,CAAQ,IAAI;CACjC,MAAM,kBAAA,GAAiBA,UAAAA,QAAAA,CAAQ,MAAM;CACrC,IAAI,iBAAiB,gBACnB,OAAO;CAGT,MAAM,OAAA,GAAMC,UAAAA,SAAAA,CAAS,gBAAgB,YAAY;CAEjD,OAAO,QAAQ,MAAM,CAAC,IAAI,WAAW,IAAI,KAAK,EAAA,GAACC,UAAAA,WAAAA,CAAW,GAAG;AAC/D;;;;;;;;;;;;AGxMA,MAAM,o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AChD,MAAM,EAAE,iBAAiB,iBAAiB,mBAAmB,SAAS,MAAM;GAC5E,MAAM,mBAAmB,OAAO,OAAO,UAAU;GACjD,MAAM,aAAaD,UAAAA,QAAK,QAAQ,OAAO,MAAM,OAAO,OAAO,IAAI;GAI/D,MAAM,gBAAgB,MAAM,QAAQ,SAAS;IAC3C,MAAM,QAAS,KAAK,MAA8C;IAClE,IAAI,OAAO,OAAO,CAAC,gBAAgB,IAAI,KAAK;IAE5C,OAAO,CAAC,gBAAgB,MAAM,WAAW,aAAa,KAAK,MAAM,MAAM,CAAC;GAC1E,CAAC;GACD,gBAAgB,MAAM;GACtB,gBAAgB,SAAS;GAEzB,MAAM,QAAQ,iBAAiB,YAAY,aAAa;GACxD,MAAM,qCAAqB,IAAI,IAAY;GAE3C,eAAe,SAAS,EAAE,QAAQ,QAAQ,YAAY,aAAa;IACjE,eAAe;KAAE;KAAO,YAAY;KAAQ;KAAY;KAAQ,WAAW;KAAM;IAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;KACvH,WAAW,uBAAuB;MAAE;MAAM;MAAQ;KAAO,CAAC,CAAC;IAC7D,CAAC;GACH,CAAC;GACD,eAAe,SAAS;GAExB,IAAI,qBAAqB,OAAO;GAEhC,eAAe;IAAE;IAAO,YAAY,iBAAiB;IAAM;GAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;IACjG,WAAW,IAAI;GACjB,CAAC;EACH;CACF;AACF,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -38,7 +38,7 @@ export declare const pluginBarrelName = "plugin-barrel";
|
|
|
38
38
|
* })
|
|
39
39
|
* ```
|
|
40
40
|
*/
|
|
41
|
-
export declare const pluginBarrel: import("@kubb/core").PluginFactory<import("@kubb/core").
|
|
41
|
+
export declare const pluginBarrel: import("@kubb/core").PluginFactory<import("@kubb/core").PluginType<string, object, object, import("@kubb/core").Resolver>>;
|
|
42
42
|
//#endregion
|
|
43
43
|
//#region src/types.d.ts
|
|
44
44
|
/**
|
package/dist/index.js
CHANGED
|
@@ -48,7 +48,7 @@ var compatibility = {
|
|
|
48
48
|
};
|
|
49
49
|
//#endregion
|
|
50
50
|
//#region package.json
|
|
51
|
-
var version = "5.
|
|
51
|
+
var version = "5.9.1";
|
|
52
52
|
//#endregion
|
|
53
53
|
//#region src/utils.ts
|
|
54
54
|
const SOURCE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
@@ -324,7 +324,8 @@ const pluginBarrel = defineExtension({
|
|
|
324
324
|
meta: {
|
|
325
325
|
name: pluginBarrelName,
|
|
326
326
|
version,
|
|
327
|
-
compatibility
|
|
327
|
+
compatibility,
|
|
328
|
+
issues: "https://github.com/kubb-labs/kubb/issues"
|
|
328
329
|
},
|
|
329
330
|
enforce: "post",
|
|
330
331
|
hooks: {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport { toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name in sorted order.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/**\n * Orders paths split into segments the way a directory listing sorts them: by name at each level.\n */\nfunction compareSegments(a: ReadonlyArray<string>, b: ReadonlyArray<string>): number {\n const index = a.findIndex((segment, i) => segment !== b[i])\n if (index === -1) return a.length - b.length\n if (index >= b.length) return 1\n\n return a[index]! < b[index]! ? -1 : 1\n}\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n return `./${posix.relative(fromDir, filePath)}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, { sourceFiles, reportedCollisions }: WalkContext): ast.FileNode {\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = item.name == null ? (sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []) : [item.name].flat()\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n return ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\nfunction indexableNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is indexable.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const sources = sourceFile?.sources ?? []\n return sources.length > 0 && !sources.some((source) => source.isIndexable) ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n if (!sourceFile?.sources.length) return [ast.factory.createExport({ path })]\n\n const valueNames = indexableNames(sourceFile.sources, false)\n const typeNames = indexableNames(sourceFile.sources, true)\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = [...node.children.values()].map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = [...node.children.values()].map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, ctx)\n const exports = barrels.length > 0 ? [ast.factory.createExport({ path: toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`) })] : []\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex(outputPath: string, files: ReadonlyArray<ast.FileNode>): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = filePath.startsWith(`${tree.path}/`) && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n // Inserting paths in per-segment order keeps every directory's children sorted by name.\n const entries = [...sourceFiles.keys()]\n .map((filePath) =>\n filePath\n .slice(tree.path.length + 1)\n .split('/')\n .filter(Boolean),\n )\n .sort(compareSegments)\n entries.forEach((parts) => {\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child: TreeNode = dir.children.get(part) ?? (i === parts.length - 1 ? { path } : { path, children: new Map() })\n dir.children.set(part, child)\n return child.children ? child : dir\n }, tree)\n })\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /**\n * Absolute directory the barrel(s) should be rooted at, a subtree of the index root.\n * Defaults to the index root.\n */\n targetPath?: string\n /**\n * Export strategy used when emitting each barrel.\n * - `'all'` re-exports the whole module (`export * from './x'`)\n * - `'named'` re-exports only the indexable named symbols\n */\n barrelType: BarrelType\n /**\n * Generate an `index.ts` in every sub-directory, each re-exporting only what's directly inside it (hierarchical).\n * When false, uses flat generation strategy with optional recursive subdirectory barrels.\n */\n nested?: boolean\n /**\n * Also generate a barrel for each sub-directory when nested is false.\n * No effect when nested is true (always generates hierarchical structure).\n */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex(outputPath, files)\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n reportedCollisions,\n recursive,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside } from '@internals/utils'\nimport { defineExtension, Diagnostics } from '@kubb/kit'\nimport type { ast, Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a\n * banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const resolver = plugin.resolver\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!resolver || (!hasBanner && !hasFooter)) return file\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = new WeakMap<Config, BarrelState>()\n\nfunction getState(config: Config): BarrelState {\n const state = states.get(config) ?? { excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }\n states.set(config, state)\n return state\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`, but generates\n * nothing until a barrel is configured.\n *\n * Each plugin inherits `output.barrel` from `config.output.barrel` (which\n * defaults to `false`, no barrel). Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n const index = buildBarrelIndex(outputPath, relevantFiles)\n const reportedCollisions = new Set<string>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+JA,SAAgB,YAAY,UAA0B;CACpD,OAAO,SAAS,WAAW,MAAM,GAAG;AAC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IAAE;IAAQ;IAAQ,YAAY,aAAa;IAAM,QAAQ,aAAa,UAAU;GAAM,CAAC;EAC7G;EACA,mBAAmB,EAAE,OAAO,QAAQ,cAAc;GAChD,MAAM,EAAE,iBAAiB,iBAAiB,mBAAmB,SAAS,MAAM;GAC5E,MAAM,mBAAmB,OAAO,OAAO,UAAU;GACjD,MAAM,aAAa,KAAK,QAAQ,OAAO,MAAM,OAAO,OAAO,IAAI;GAI/D,MAAM,gBAAgB,MAAM,QAAQ,SAAS;IAC3C,MAAM,QAAS,KAAK,MAA8C;IAClE,IAAI,OAAO,OAAO,CAAC,gBAAgB,IAAI,KAAK;IAE5C,OAAO,CAAC,gBAAgB,MAAM,WAAW,aAAa,KAAK,MAAM,MAAM,CAAC;GAC1E,CAAC;GACD,gBAAgB,MAAM;GACtB,gBAAgB,SAAS;GAEzB,MAAM,QAAQ,iBAAiB,YAAY,aAAa;GACxD,MAAM,qCAAqB,IAAI,IAAY;GAE3C,eAAe,SAAS,EAAE,QAAQ,QAAQ,YAAY,aAAa;IACjE,eAAe;KAAE;KAAO,YAAY;KAAQ;KAAY;KAAQ,WAAW;KAAM;IAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;KACvH,WAAW,uBAAuB;MAAE;MAAM;MAAQ;KAAO,CAAC,CAAC;IAC7D,CAAC;GACH,CAAC;GACD,eAAe,SAAS;GAExB,IAAI,qBAAqB,OAAO;GAEhC,eAAe;IAAE;IAAO,YAAY,iBAAiB;IAAM;GAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;IACjG,WAAW,IAAI;GACjB,CAAC;EACH;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../internals/utils/src/fs.ts","../kubb-extension.json","../package.json","../src/utils.ts","../src/plugin.ts"],"sourcesContent":["import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { runtime } from './runtime.ts'\n\n/**\n * Resolves to `true` when the file or directory at `path` exists.\n * Uses `Bun.file().exists()` when running under Bun, `fs.access` otherwise.\n *\n * @example\n * ```ts\n * if (await exists('./kubb.config.ts')) {\n * const content = await read('./kubb.config.ts')\n * }\n * ```\n */\nexport async function exists(path: string): Promise<boolean> {\n if (runtime.isBun) {\n return Bun.file(path).exists()\n }\n return access(path).then(\n () => true,\n () => false,\n )\n}\n\n/**\n * Reads the file at `path` as a UTF-8 string.\n * Uses `Bun.file().text()` when running under Bun, `fs.readFile` otherwise.\n *\n * @example\n * ```ts\n * const source = await read('./src/Pet.ts')\n * ```\n */\nexport async function read(path: string): Promise<string> {\n if (runtime.isBun) {\n return Bun.file(path).text()\n }\n return readFile(path, { encoding: 'utf8' })\n}\n\ntype WriteOptions = {\n /**\n * Previously read content, or `null` when the file does not exist.\n * Omitting this value reads the file before writing.\n */\n stored?: string | null\n /**\n * When `true`, re-reads the file immediately after writing and throws if the\n * content does not match — useful for catching write failures on unreliable file systems.\n */\n sanity?: boolean\n}\n\n/**\n * Whether `stored` already holds `source`, comparing on the trimmed text rather than the exact\n * bytes. Surrounding whitespace is what a formatter adds and what editors strip, and neither is a\n * reason to rewrite the file.\n *\n * Both sides are trimmed, so a storage that keeps bytes verbatim settles on the same answer as one\n * that normalizes what it stores. Trimming only `stored` would leave a source with leading\n * whitespace rewritten on every build, since the stored copy keeps the whitespace the comparison\n * has already dropped.\n */\nexport function matchesStored({ stored, source }: { stored: string; source: string }): boolean {\n return stored.trim() === source.trim()\n}\n\n/**\n * Writes `data` to `path`, trimming surrounding whitespace and ending the file with a single newline\n * the way prettier, biome, and oxfmt all do.\n * Skips the write when the trimmed content is empty, or when the file already holds that content.\n * Creates any missing parent directories automatically.\n * When `sanity` is `true`, re-reads the file after writing and throws if the content does not match.\n *\n * @example\n * ```ts\n * await write('./src/Pet.ts', source) // writes and returns the trimmed content plus a newline\n * await write('./src/Pet.ts', source) // null — file unchanged\n * await write('./src/Pet.ts', ' ') // null — empty content skipped\n * ```\n */\nexport async function write(path: string, data: string, options: WriteOptions = {}): Promise<string | null> {\n const trimmed = data.trim()\n if (trimmed === '') return null\n\n const content = `${trimmed}\\n`\n const resolved = resolve(path)\n let stored = options.stored\n\n if (stored === undefined) {\n if (runtime.isBun) {\n const file = Bun.file(resolved)\n stored = (await file.exists()) ? await file.text() : null\n } else {\n try {\n stored = await readFile(resolved, { encoding: 'utf-8' })\n } catch {\n /* file doesn't exist yet */\n stored = null\n }\n }\n }\n if (matchesStored({ stored: stored ?? '', source: trimmed })) return null\n\n if (runtime.isBun) {\n await Bun.write(resolved, content)\n return content\n }\n\n // Creating the directory up front costs a syscall per file, and every file after the first in a\n // directory pays it for nothing. Write first and only fall back when the directory is missing,\n // which also stays correct when something removed it mid-run.\n try {\n await writeFile(resolved, content, { encoding: 'utf-8' })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n\n await mkdir(dirname(resolved), { recursive: true })\n await writeFile(resolved, content, { encoding: 'utf-8' })\n }\n\n if (options.sanity) {\n const savedData = await readFile(resolved, { encoding: 'utf-8' })\n if (savedData !== content) {\n throw new Error(`Sanity check failed for ${path}\\n\\nData[${data.length}]:\\n${data}\\n\\nSaved[${savedData.length}]:\\n${savedData}\\n`)\n }\n return savedData\n }\n\n return content\n}\n\n/**\n * Recursively removes `path`. Silently succeeds when `path` does not exist.\n *\n * @example\n * ```ts\n * await clean('./dist')\n * ```\n */\nexport async function clean(path: string): Promise<void> {\n return rm(path, { recursive: true, force: true })\n}\n\n/**\n * Converts a filesystem path to use POSIX (`/`) separators.\n *\n * Most of the codebase compares and composes paths as strings (prefix matching, joining for\n * import specifiers, splitting on `/`). On POSIX `path.resolve` already returns `/`-separated\n * paths, but on Windows it returns `\\`-separated paths, which breaks every such comparison.\n *\n * Routing every path that crosses a module boundary through `toPosixPath` keeps the rest of the\n * code platform-agnostic. The conversion runs unconditionally so Windows-specific behavior is\n * exercisable from POSIX CI.\n *\n * @example\n * toPosixPath('C:\\\\repo\\\\src\\\\pet.ts') // 'C:/repo/src/pet.ts'\n */\nexport function toPosixPath(filePath: string): string {\n return filePath.replaceAll('\\\\', '/')\n}\n\n/**\n * Strips the file extension from a path or file name.\n * Only removes the last `.ext` segment when the dot is not part of a directory name.\n *\n * @example\n * trimExtName('petStore.ts') // 'petStore'\n * trimExtName('/src/models/pet.ts') // '/src/models/pet'\n * trimExtName('/project.v2/gen/pet.ts') // '/project.v2/gen/pet'\n * trimExtName('noExtension') // 'noExtension'\n */\nexport function trimExtName(text: string): string {\n const dotIndex = text.lastIndexOf('.')\n if (dotIndex > 0 && !text.includes('/', dotIndex)) {\n return text.slice(0, dotIndex)\n }\n return text\n}\n\n/**\n * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved\n * to absolute paths first, so relative and `..`-containing inputs compare correctly.\n *\n * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that\n * it does not contain the project root, and before loading a path a caller supplied, check that it\n * did not escape the directory it is allowed to read from.\n *\n * @example\n * isPathInside('./src/gen', '.') // true — nested inside the root\n * isPathInside('.', '.') // true — the same directory counts as inside\n * isPathInside('.', './src/gen') // false — the root is not inside its own output\n * isPathInside('../other', '.') // false — escapes the root\n */\nexport function isPathInside(path: string, parent: string): boolean {\n const resolvedPath = resolve(path)\n const resolvedParent = resolve(parent)\n if (resolvedPath === resolvedParent) {\n return true\n }\n\n const rel = relative(resolvedParent, resolvedPath)\n\n return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)\n}\n","","","import { extname, posix } from 'node:path'\nimport { ast, Diagnostics } from '@kubb/kit'\nimport { toPosixPath } from '@internals/utils'\nimport type { BarrelType } from './types.ts'\n\nconst SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx'])\nconst BARREL_SUFFIX = `/index.ts`\n\n/**\n * A file (no `children`) or directory in the tree barrels are computed from. `path` is absolute and\n * POSIX-normalized, and a directory's `children` are keyed by entry name in sorted order.\n */\ntype TreeNode = { path: string; children?: undefined } | DirectoryNode\ntype DirectoryNode = { path: string; children: Map<string, TreeNode> }\n\n/**\n * Orders paths split into segments the way a directory listing sorts them: by name at each level.\n */\nfunction compareSegments(a: ReadonlyArray<string>, b: ReadonlyArray<string>): number {\n const index = a.findIndex((segment, i) => segment !== b[i])\n if (index === -1) return a.length - b.length\n if (index >= b.length) return 1\n\n return a[index]! < b[index]! ? -1 : 1\n}\n\nfunction toRelativeModulePath(fromDir: string, filePath: string): string {\n return `./${posix.relative(fromDir, filePath)}`\n}\n\ntype WalkContext = {\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n reportedCollisions: Set<string>\n recursive: boolean\n leafExports: (dirPath: string, leafPath: string) => Array<ast.ExportNode>\n}\n\n/**\n * Builds the `index.ts` for `dirPath`. Keeps the first export of each name and reports later duplicates once per build.\n */\nfunction makeBarrel(dirPath: string, exports: Array<ast.ExportNode>, { sourceFiles, reportedCollisions }: WalkContext): ast.FileNode {\n const owners = new Map<string, string>()\n const uniqueExports = exports.flatMap((item) => {\n const itemPath = posix.join(dirPath, item.path)\n // A wildcard export carries no names, so collisions are checked against its source file.\n const names = item.name == null ? (sourceFiles.get(itemPath)?.sources.flatMap((source) => source.name || []) ?? []) : [item.name].flat()\n const uniqueNames = names.filter((name) => {\n const first = owners.get(name)\n if (!first) {\n owners.set(name, item.path)\n return true\n }\n\n const key = [name, posix.join(dirPath, first), itemPath].join('\\0')\n if (!reportedCollisions.has(key)) {\n reportedCollisions.add(key)\n Diagnostics.report({\n code: Diagnostics.code.barrelDuplicateExport,\n severity: 'error',\n message: `\"${name}\" is exported by both \"${first}\" and \"${item.path}\", so \"${dirPath}${BARREL_SUFFIX}\" cannot re-export both.`,\n help: 'Rename one of the colliding declarations, or configure the plugin resolver to produce distinct names.',\n })\n }\n return false\n })\n\n if (item.name == null) return [item]\n return uniqueNames.length > 0 ? [ast.factory.createExport({ ...item, name: Array.isArray(item.name) ? uniqueNames : uniqueNames[0] })] : []\n })\n\n return ast.factory.createFile({ baseName: 'index.ts', path: `${dirPath}${BARREL_SUFFIX}`, exports: uniqueExports })\n}\n\ntype LeafStrategy = (path: string, sourceFile: ast.FileNode | undefined) => Array<ast.ExportNode>\n\nfunction indexableNames(sources: ReadonlyArray<ast.SourceNode>, isTypeOnly: boolean): Array<string> {\n const names = sources.flatMap((source) => (source.isIndexable && source.name && Boolean(source.isTypeOnly) === isTypeOnly ? [source.name] : []))\n return [...new Set(names)].sort()\n}\n\n/**\n * Re-exports the whole module, unless it has sources and none of them is indexable.\n */\nconst allStrategy: LeafStrategy = (path, sourceFile) => {\n const sources = sourceFile?.sources ?? []\n return sources.length > 0 && !sources.some((source) => source.isIndexable) ? [] : [ast.factory.createExport({ path })]\n}\n\n/**\n * Re-exports the indexable names, values and types separately, or the whole module when it has no sources.\n */\nconst namedStrategy: LeafStrategy = (path, sourceFile) => {\n if (!sourceFile?.sources.length) return [ast.factory.createExport({ path })]\n\n const valueNames = indexableNames(sourceFile.sources, false)\n const typeNames = indexableNames(sourceFile.sources, true)\n return [\n ...(valueNames.length > 0 ? [ast.factory.createExport({ name: valueNames, path })] : []),\n ...(typeNames.length > 0 ? [ast.factory.createExport({ name: typeNames, path, isTypeOnly: true })] : []),\n ]\n}\n\ntype FlatWalk = { barrels: Array<ast.FileNode>; leaves: Array<string> }\n\n/**\n * Post-order walk that builds a barrel re-exporting every leaf below the visited directory, for\n * the start node and, with `recursive`, every sub-directory. Also returns the subtree's leaf paths.\n */\nfunction walkFlat(node: DirectoryNode, ctx: WalkContext, isRoot = true): FlatWalk {\n const results = [...node.children.values()].map((child): FlatWalk => (child.children ? walkFlat(child, ctx, false) : { barrels: [], leaves: [child.path] }))\n const barrels = results.flatMap((result) => result.barrels)\n const leaves = results.flatMap((result) => result.leaves)\n const exports = isRoot || ctx.recursive ? leaves.flatMap((leaf) => ctx.leafExports(node.path, leaf)) : []\n\n return { barrels: exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels, leaves }\n}\n\n/**\n * Recursive walk that builds one barrel per directory, re-exporting files and sub-barrels.\n * Used when nested: true. Leaf files honor the barrel `strategy`, so `named` emits explicit\n * named exports instead of wildcards. Sub-directory barrels are chained with a wildcard\n * re-export, which forwards the names the child barrel already curated. A sub-directory that\n * produced no barrel is never re-exported.\n */\nfunction walkNested(node: DirectoryNode, ctx: WalkContext): Array<ast.FileNode> {\n const results = [...node.children.values()].map((child) => {\n if (!child.children) return { barrels: [], exports: ctx.leafExports(node.path, child.path) }\n\n // A sub-directory has barrels only when it has its own `index.ts`.\n const barrels = walkNested(child, ctx)\n const exports = barrels.length > 0 ? [ast.factory.createExport({ path: toRelativeModulePath(node.path, `${child.path}${BARREL_SUFFIX}`) })] : []\n return { barrels, exports }\n })\n const barrels = results.flatMap((result) => result.barrels)\n const exports = results.flatMap((result) => result.exports)\n\n return exports.length > 0 ? [...barrels, makeBarrel(node.path, exports, ctx)] : barrels\n}\n\n/**\n * A directory tree plus the source-file lookup it was built from, scoped to a single output root.\n * Build it once with {@link buildBarrelIndex} and derive every barrel (per-plugin and root) from\n * it via {@link getBarrelFiles}, instead of re-scanning the full file set once per barrel.\n */\ntype BarrelIndex = {\n tree: DirectoryNode\n sourceFiles: ReadonlyMap<string, ast.FileNode>\n}\n\n/**\n * Indexes `files` once for the directory rooted at `outputPath`: filters to indexable source\n * files under that path and builds their directory tree. Reuse the result across every barrel\n * derived from the same root rather than re-filtering and re-building per barrel.\n */\nexport function buildBarrelIndex(outputPath: string, files: ReadonlyArray<ast.FileNode>): BarrelIndex {\n const tree: DirectoryNode = { path: toPosixPath(outputPath), children: new Map() }\n const sourceFiles = new Map(\n files.flatMap((file) => {\n const filePath = toPosixPath(file.path)\n const isSource = filePath.startsWith(`${tree.path}/`) && !filePath.endsWith(BARREL_SUFFIX) && SOURCE_EXTENSIONS.has(extname(filePath))\n return isSource ? [[filePath, file] as const] : []\n }),\n )\n\n // Inserting paths in per-segment order keeps every directory's children sorted by name.\n const entries = [...sourceFiles.keys()]\n .map((filePath) =>\n filePath\n .slice(tree.path.length + 1)\n .split('/')\n .filter(Boolean),\n )\n .sort(compareSegments)\n entries.forEach((parts) => {\n parts.reduce<DirectoryNode>((dir, part, i) => {\n const path = `${dir.path}/${part}`\n const child: TreeNode = dir.children.get(part) ?? (i === parts.length - 1 ? { path } : { path, children: new Map() })\n dir.children.set(part, child)\n return child.children ? child : dir\n }, tree)\n })\n\n return { tree, sourceFiles }\n}\n\n/**\n * Locates the directory node for `targetPath` within an index tree. Returns `undefined` when no\n * file exists under `targetPath` (nothing to barrel).\n */\nfunction findDirectory(tree: DirectoryNode, targetPath: string): DirectoryNode | undefined {\n if (targetPath === tree.path) return tree\n if (!targetPath.startsWith(`${tree.path}/`)) return undefined\n\n const node = targetPath\n .slice(tree.path.length + 1)\n .split('/')\n .reduce<TreeNode | undefined>((current, part) => current?.children?.get(part), tree)\n return node?.children ? node : undefined\n}\n\ntype GetBarrelFilesParams = {\n /**\n * Index built once via {@link buildBarrelIndex} for the shared output root.\n */\n index: BarrelIndex\n /**\n * Absolute directory the barrel(s) should be rooted at, a subtree of the index root.\n * Defaults to the index root.\n */\n targetPath?: string\n /**\n * Export strategy used when emitting each barrel.\n * - `'all'` re-exports the whole module (`export * from './x'`)\n * - `'named'` re-exports only the indexable named symbols\n */\n barrelType: BarrelType\n /**\n * Generate an `index.ts` in every sub-directory, each re-exporting only what's directly inside it (hierarchical).\n * When false, uses flat generation strategy with optional recursive subdirectory barrels.\n */\n nested?: boolean\n /**\n * Also generate a barrel for each sub-directory when nested is false.\n * No effect when nested is true (always generates hierarchical structure).\n */\n recursive?: boolean\n /**\n * Collision identities reported by related barrel generations in the same build.\n */\n reportedCollisions?: Set<string>\n}\n\n/**\n * Returns the barrel `ast.FileNode`s for `targetPath` (or the index root), derived from a shared index.\n * Locating the subtree is a bounded walk down from the root, so deriving many barrels (one per\n * plugin, plus the root) from one index avoids re-scanning the full file set for each.\n *\n * @example\n * ```ts\n * const index = buildBarrelIndex(outputPath, files)\n * getBarrelFiles({ index, targetPath, barrelType }).forEach((file) => upsertFile(file))\n * ```\n */\nexport function getBarrelFiles({\n index,\n targetPath,\n barrelType,\n nested = false,\n recursive = false,\n reportedCollisions = new Set(),\n}: GetBarrelFilesParams): Array<ast.FileNode> {\n const node = targetPath ? findDirectory(index.tree, toPosixPath(targetPath)) : index.tree\n if (!node) return []\n\n const strategy = barrelType === 'named' ? namedStrategy : allStrategy\n const ctx: WalkContext = {\n sourceFiles: index.sourceFiles,\n reportedCollisions,\n recursive,\n leafExports: (dirPath, leafPath) => strategy(toRelativeModulePath(dirPath, leafPath), index.sourceFiles.get(leafPath)),\n }\n\n return nested ? walkNested(node, ctx) : walkFlat(node, ctx).barrels\n}\n","import path from 'node:path'\nimport { isPathInside } from '@internals/utils'\nimport { defineExtension, Diagnostics } from '@kubb/kit'\nimport type { ast, Config, NormalizedPlugin, Plugin } from '@kubb/kit'\nimport { compatibility } from '../kubb-extension.json'\nimport { version } from '../package.json'\nimport type { BarrelType, PluginBarrelConfig } from './types.ts'\nimport { buildBarrelIndex, getBarrelFiles } from './utils.ts'\n\n/**\n * Applies a plugin's configured `output.banner`/`footer` to a barrel file, flagged as `isBarrel`.\n *\n * Resolves through the plugin's own resolver, and only when the plugin explicitly sets a\n * banner/footer, so barrels stay banner-free by default and never inherit the implicit\n * \"Generated by Kubb\" notice.\n */\nfunction withBarrelBannerFooter({ file, plugin, config }: { file: ast.FileNode; plugin: NormalizedPlugin; config: Config }): ast.FileNode {\n const output = plugin.options?.output\n const resolver = plugin.resolver\n const hasBanner = output?.banner !== undefined\n const hasFooter = output?.footer !== undefined\n if (!resolver || (!hasBanner && !hasFooter)) return file\n\n const context = { output, config, file: { path: file.path, baseName: file.baseName, isBarrel: true } }\n return {\n ...file,\n banner: hasBanner ? resolver.default.banner(undefined, context) : file.banner,\n footer: hasFooter ? resolver.default.footer(undefined, context) : file.footer,\n }\n}\n\n/**\n * Canonical plugin name for `@kubb/plugin-barrel`. Used for driver lookups\n * and to guard the `kubb:plugin:end` handler against reacting to its own lifecycle hook.\n */\nexport const pluginBarrelName = 'plugin-barrel' satisfies Plugin['name']\n\ntype PendingBarrel = {\n plugin: NormalizedPlugin\n target: string\n barrelType: BarrelType\n nested: boolean\n}\n\ntype BarrelState = {\n excludedPlugins: Set<string>\n // Subdirectories of `barrel: false` plugins, for files without a `meta.pluginName` owner.\n excludedTargets: Array<string>\n pendingBarrels: Array<PendingBarrel>\n}\n\n// One state per build, keyed by the build's `config`. The object form has no factory closure to hold it.\nconst states = new WeakMap<Config, BarrelState>()\n\nfunction getState(config: Config): BarrelState {\n const state = states.get(config) ?? { excludedPlugins: new Set(), excludedTargets: [], pendingBarrels: [] }\n states.set(config, state)\n return state\n}\n\n/**\n * Generates an `index.ts` for every plugin output directory and one root\n * barrel at `config.output.path/index.ts` after the build completes. Ships\n * with Kubb and is registered by default in `defineConfig`, but generates\n * nothing until a barrel is configured.\n *\n * Each plugin inherits `output.barrel` from `config.output.barrel` (which\n * defaults to `false`, no barrel). Set `barrel: { type: 'named' | 'all' }` on\n * the root config, a plugin, or both to opt in; a plugin-level `false`\n * overrides an enabled root barrel and also excludes that plugin's files\n * from the root barrel.\n *\n * A plugin with `output.mode: 'file'` gets no per-plugin barrel, since its output\n * is a single file. The root barrel re-exports that file directly.\n *\n * @example\n * ```ts\n * import { defineConfig } from '@kubb/core'\n * import { pluginBarrel } from '@kubb/plugin-barrel'\n * import { pluginTs } from '@kubb/plugin-ts'\n * import { pluginZod } from '@kubb/plugin-zod'\n *\n * export default defineConfig({\n * input: './petStore.yaml',\n * output: { path: 'src/gen', barrel: { type: 'named' } },\n * plugins: [\n * pluginTs({ output: { path: 'types', barrel: { type: 'all' } } }),\n * pluginZod({ output: { path: 'schemas' } }),\n * pluginBarrel(),\n * ],\n * })\n * ```\n */\nexport const pluginBarrel = defineExtension({\n kind: 'plugin',\n meta: { name: pluginBarrelName, version, compatibility, issues: 'https://github.com/kubb-labs/kubb/issues' },\n enforce: 'post',\n hooks: {\n 'kubb:plugin:end'({ plugin, config }) {\n // Skip reactions to the barrel plugin's own lifecycle hook\n if (plugin.name === pluginBarrelName) return\n\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n\n // A plugin-level `false` wins over an enabled root barrel.\n const barrelConfig: PluginBarrelConfig | false = plugin.options.output?.barrel ?? config.output.barrel ?? false\n const base = path.resolve(config.root, config.output.path)\n const target = path.resolve(base, plugin.options.output.path ?? '.')\n\n if (barrelConfig === false) {\n excludedPlugins.add(plugin.name)\n // The output root holds every plugin's files, so there only the owner match applies.\n if (target !== base && isPathInside(target, base)) {\n excludedTargets.push(target)\n }\n return\n }\n\n // A plugin at the output root (no own `output.path`) gets no per-plugin barrel, which would\n // claim every other plugin's directory. The root barrel picks up its files.\n if (target === base) {\n return\n }\n\n // `mode: 'file'` writes a single file, so there is no directory to barrel. The root barrel\n // re-exports that file as a direct leaf of `config.output.path`.\n if (plugin.options.output.mode === 'file') {\n return\n }\n\n if (!isPathInside(target, base)) {\n throw new Diagnostics.Error({\n code: Diagnostics.code.pathTraversal,\n severity: 'error',\n message: `Output path \"${plugin.options.output.path}\" of plugin \"${plugin.name}\" resolves outside the output directory \"${base}\".`,\n help: 'Keep the plugin `output.path` within `config.output.path`.',\n location: { kind: 'config' },\n })\n }\n\n // Only the target directory and barrel strategy are recorded here. The actual file-set\n // scan and directory-tree build happen once, in `kubb:plugins:end`, and are shared by\n // every plugin barrel plus the root barrel instead of repeating per plugin.\n pendingBarrels.push({ plugin, target, barrelType: barrelConfig.type, nested: barrelConfig.nested ?? false })\n },\n 'kubb:plugins:end'({ files, config, upsertFile }) {\n const { excludedPlugins, excludedTargets, pendingBarrels } = getState(config)\n const rootBarrelConfig = config.output.barrel ?? false\n const outputPath = path.resolve(config.root, config.output.path)\n\n // A `barrel: false` plugin gets no barrel and stays out of the root, so drop its files\n // once here. Every barrel below then derives from a single index of what remains.\n const relevantFiles = files.filter((file) => {\n const owner = (file.meta as { pluginName?: string } | undefined)?.pluginName\n if (owner) return !excludedPlugins.has(owner)\n\n return !excludedTargets.some((target) => isPathInside(file.path, target))\n })\n excludedPlugins.clear()\n excludedTargets.length = 0\n\n const index = buildBarrelIndex(outputPath, relevantFiles)\n const reportedCollisions = new Set<string>()\n\n pendingBarrels.forEach(({ plugin, target, barrelType, nested }) => {\n getBarrelFiles({ index, targetPath: target, barrelType, nested, recursive: true, reportedCollisions }).forEach((file) => {\n upsertFile(withBarrelBannerFooter({ file, plugin, config }))\n })\n })\n pendingBarrels.length = 0\n\n if (rootBarrelConfig === false) return\n\n getBarrelFiles({ index, barrelType: rootBarrelConfig.type, reportedCollisions }).forEach((file) => {\n upsertFile(file)\n })\n },\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+JA,SAAgB,YAAY,UAA0B;CACpD,OAAO,SAAS,WAAW,MAAM,GAAG;AACtC;;;;;;;;;;;;;;;AAkCA,SAAgB,aAAa,MAAc,QAAyB;CAClE,MAAM,eAAe,QAAQ,IAAI;CACjC,MAAM,iBAAiB,QAAQ,MAAM;CACrC,IAAI,iBAAiB,gBACnB,OAAO;CAGT,MAAM,MAAM,SAAS,gBAAgB,YAAY;CAEjD,OAAO,QAAQ,MAAM,CAAC,IAAI,WAAW,IAAI,KAAK,CAAC,WAAW,GAAG;AAC/D;;;;;;;;;;;;AGxMA,MAAM,oCAAoB,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAO;AAAM,CAAC;AAChE,MAAM,gBAAgB;;;;AAYtB,SAAS,gBAAgB,GAA0B,GAAkC;CACnF,MAAM,QAAQ,EAAE,WAAW,SAAS,MAAM,YAAY,EAAE,EAAE;CAC1D,IAAI,UAAU,IAAI,OAAO,EAAE,SAAS,EAAE;CACtC,IAAI,SAAS,EAAE,QAAQ,OAAO;CAE9B,OAAO,EAAE,SAAU,EAAE,SAAU,KAAK;AACtC;AAEA,SAAS,qBAAqB,SAAiB,UAA0B;CACvE,OAAO,KAAK,MAAM,SAAS,SAAS,QAAQ;AAC9C;;;;AAYA,SAAS,WAAW,SAA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mB,CAAC,CAAC,CAAC,SAAS,SAAS;KACvH,WAAW,uBAAuB;MAAE;MAAM;MAAQ;KAAO,CAAC,CAAC;IAC7D,CAAC;GACH,CAAC;GACD,eAAe,SAAS;GAExB,IAAI,qBAAqB,OAAO;GAEhC,eAAe;IAAE;IAAO,YAAY,iBAAiB;IAAM;GAAmB,CAAC,CAAC,CAAC,SAAS,SAAS;IACjG,WAAW,IAAI;GACjB,CAAC;EACH;CACF;AACF,CAAC"}
|
package/docs/options.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
### output.barrel
|
|
16
16
|
|
|
17
|
-
Kubb writes
|
|
17
|
+
Kubb writes an `index.ts` in every directory of a plugin's output, and a root barrel when `output.barrel` is set on `defineConfig`. For two plugins that write to `models` and `clients`, with `output.barrel` set on `defineConfig`:
|
|
18
18
|
|
|
19
19
|
```text
|
|
20
20
|
src/gen
|
package/docs/overview.md
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
|
-
# Barrel
|
|
1
|
+
# Barrel
|
|
2
2
|
|
|
3
|
-
The
|
|
4
|
-
|
|
5
|
-
Kubb adds it to `plugins` for you. Do not add it yourself. It generates nothing until you configure `output.barrel`.
|
|
3
|
+
The Barrel plugin writes `index.ts` files that re-export generated code, so you can import everything from a single entry point. It writes a barrel in every folder of each plugin output that has a barrel setting, plus a root barrel when you set `output.barrel` on `defineConfig`.
|
|
6
4
|
|
|
7
5
|
## Setup
|
|
8
6
|
|
|
9
|
-
|
|
7
|
+
Kubb adds the plugin to `plugins` for you, so no setup is needed. Generator plugins such as `pluginTs()` turn on their own barrels by default. Plugins without their own `output.barrel` inherit the root setting.
|
|
10
8
|
|
|
11
|
-
## Options
|
|
9
|
+
## Options worth knowing
|
|
12
10
|
|
|
13
|
-
|
|
11
|
+
`pluginBarrel()` takes no arguments. You configure it through `output.barrel`, on `defineConfig` or on a single plugin.
|
|
14
12
|
|
|
15
13
|
- `type: 'named'` re-exports each symbol by name, which suits tree-shaking. `type: 'all'` writes `export *`.
|
|
16
|
-
- `nested: true`, on a plugin only, makes each barrel re-export just its own
|
|
14
|
+
- `nested: true`, on a plugin only, makes each barrel re-export just its own folder and the barrels below it. The root barrel is always flat.
|
|
17
15
|
- `false` on a plugin turns its barrel off and leaves its files out of the root barrel.
|
|
18
16
|
|
|
19
|
-
A plugin with `output.mode: 'file'` gets no barrel of its own
|
|
17
|
+
A plugin with `output.mode: 'file'` gets no barrel of its own, and the root barrel re-exports that file directly. Passing your own `output` object to a plugin replaces its default `barrel: { type: 'named' }`, so that plugin falls back to the root setting. When two files export the same name, Kubb reports an error, and a `named` barrel keeps only the first one.
|
|
20
18
|
|
|
21
|
-
See [Options](https://kubb.dev/extensions/kubb-labs/plugin-barrel/options) for
|
|
19
|
+
See [Options](https://kubb.dev/extensions/kubb-labs/plugin-barrel/options) for every option and its default.
|
|
22
20
|
|
|
23
21
|
## Example
|
|
24
22
|
|
|
23
|
+
The config below writes a root `src/gen/index.ts` that re-exports the generated types by name.
|
|
24
|
+
|
|
25
25
|
```typescript [kubb.config.ts]
|
|
26
26
|
import { defineConfig } from 'kubb/config'
|
|
27
27
|
import { pluginTs } from '@kubb/plugin-ts'
|
|
@@ -29,6 +29,8 @@ import { pluginTs } from '@kubb/plugin-ts'
|
|
|
29
29
|
export default defineConfig({
|
|
30
30
|
input: './petStore.yaml',
|
|
31
31
|
output: { path: './src/gen', barrel: { type: 'named' } },
|
|
32
|
-
plugins: [
|
|
32
|
+
plugins: [
|
|
33
|
+
pluginTs(),
|
|
34
|
+
],
|
|
33
35
|
})
|
|
34
36
|
```
|
package/kubb-extension.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"name": "plugin-barrel",
|
|
5
5
|
"export": "pluginBarrel",
|
|
6
6
|
"displayName": "Barrel",
|
|
7
|
-
"description": "Generates index.ts barrel files for every plugin output
|
|
7
|
+
"description": "Generates index.ts barrel files for every plugin output, plus a root barrel when output.barrel is set on defineConfig.",
|
|
8
8
|
"category": "output",
|
|
9
9
|
"icon": {
|
|
10
10
|
"light": "https://kubb.dev/feature/plugins-light.svg"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubb/plugin-barrel",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.9.1",
|
|
4
4
|
"description": "Barrel-file plugin for Kubb. Automatically generates index.ts re-export files per plugin output directory.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"barrel",
|
|
@@ -61,11 +61,11 @@
|
|
|
61
61
|
"registry": "https://registry.npmjs.org/"
|
|
62
62
|
},
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@kubb/kit": "5.
|
|
64
|
+
"@kubb/kit": "5.9.1"
|
|
65
65
|
},
|
|
66
66
|
"devDependencies": {
|
|
67
67
|
"@internals/utils": "0.0.1",
|
|
68
|
-
"@kubb/core": "5.
|
|
68
|
+
"@kubb/core": "5.9.1"
|
|
69
69
|
},
|
|
70
70
|
"engines": {
|
|
71
71
|
"node": ">=22"
|