@kubb/cli 5.0.0-beta.5 → 5.0.0-beta.7

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.
Files changed (150) hide show
  1. package/README.md +177 -26
  2. package/dist/agent-DN7o8nlE.js +68 -0
  3. package/dist/agent-DN7o8nlE.js.map +1 -0
  4. package/dist/agent-Fm9_8BBH.cjs +70 -0
  5. package/dist/agent-Fm9_8BBH.cjs.map +1 -0
  6. package/dist/{chunk--u3MIqq1.js → chunk-BvFE5Tac.js} +1 -0
  7. package/dist/constants-B2JTeRBb.js +42 -0
  8. package/dist/constants-B2JTeRBb.js.map +1 -0
  9. package/dist/constants-BINTA5VZ.cjs +77 -0
  10. package/dist/constants-BINTA5VZ.cjs.map +1 -0
  11. package/dist/constants-BYGmiFs0.cjs +139 -0
  12. package/dist/constants-BYGmiFs0.cjs.map +1 -0
  13. package/dist/constants-DSJ-Xrbv.js +116 -0
  14. package/dist/constants-DSJ-Xrbv.js.map +1 -0
  15. package/dist/define-Bdn8j5VM.cjs.map +1 -1
  16. package/dist/{define-Ctii4bel.js → define-m_fp-Aqm.js} +2 -2
  17. package/dist/{define-Ctii4bel.js.map → define-m_fp-Aqm.js.map} +1 -1
  18. package/dist/{errors-CjPmyZHy.js → errors-CINO1EIv.js} +2 -2
  19. package/dist/{errors-CjPmyZHy.js.map → errors-CINO1EIv.js.map} +1 -1
  20. package/dist/errors-CLCjoSg0.cjs.map +1 -1
  21. package/dist/{generate-BqeFFQGD.js → generate-BY-juRdH.js} +12 -6
  22. package/dist/generate-BY-juRdH.js.map +1 -0
  23. package/dist/{generate-7td_hs73.cjs → generate-Bod9YCbF.cjs} +10 -4
  24. package/dist/generate-Bod9YCbF.cjs.map +1 -0
  25. package/dist/index.cjs +20 -11
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +22 -13
  29. package/dist/index.js.map +1 -1
  30. package/dist/init-BIkZU6mB.cjs +53 -0
  31. package/dist/init-BIkZU6mB.cjs.map +1 -0
  32. package/dist/init-Cs3Fp6nN.js +53 -0
  33. package/dist/init-Cs3Fp6nN.js.map +1 -0
  34. package/dist/mcp-BSNulBcC.js +39 -0
  35. package/dist/mcp-BSNulBcC.js.map +1 -0
  36. package/dist/mcp-DcSrFhhP.cjs +39 -0
  37. package/dist/mcp-DcSrFhhP.cjs.map +1 -0
  38. package/dist/package-D5wmvFl4.js +6 -0
  39. package/dist/package-D5wmvFl4.js.map +1 -0
  40. package/dist/{package-BmYRU2hz.cjs → package-DrUndPET.cjs} +2 -2
  41. package/dist/package-DrUndPET.cjs.map +1 -0
  42. package/dist/{generate-DVmGtwWe.js → run-BAJubgdA.js} +298 -315
  43. package/dist/run-BAJubgdA.js.map +1 -0
  44. package/dist/{agent-IP0eLV3C.js → run-BzpYYOQs.js} +46 -43
  45. package/dist/run-BzpYYOQs.js.map +1 -0
  46. package/dist/run-CCZ24VKk.js +51 -0
  47. package/dist/run-CCZ24VKk.js.map +1 -0
  48. package/dist/{init-Cag3082g.js → run-CF97BWVa.js} +102 -147
  49. package/dist/run-CF97BWVa.js.map +1 -0
  50. package/dist/run-CQbj3ley.cjs +52 -0
  51. package/dist/run-CQbj3ley.cjs.map +1 -0
  52. package/dist/{generate-CUd1dUY5.cjs → run-CqKd6JNc.cjs} +295 -312
  53. package/dist/run-CqKd6JNc.cjs.map +1 -0
  54. package/dist/run-D0hmRpHy.js +49 -0
  55. package/dist/run-D0hmRpHy.js.map +1 -0
  56. package/dist/{agent-CS45W0kL.cjs → run-DwdAwnLG.cjs} +44 -41
  57. package/dist/run-DwdAwnLG.cjs.map +1 -0
  58. package/dist/{mcp-BfORW-mY.cjs → run-Lr0Ctnu0.cjs} +24 -21
  59. package/dist/run-Lr0Ctnu0.cjs.map +1 -0
  60. package/dist/{init-C5sZulT6.cjs → run-YsoCk5we.cjs} +100 -145
  61. package/dist/run-YsoCk5we.cjs.map +1 -0
  62. package/dist/shell-475fQKaX.cjs.map +1 -1
  63. package/dist/{shell-DLzN4fRo.js → shell-CN6DNqeC.js} +2 -2
  64. package/dist/{shell-DLzN4fRo.js.map → shell-CN6DNqeC.js.map} +1 -1
  65. package/dist/{telemetry-BU25EoI-.cjs → telemetry-B2iWkY5e.cjs} +5 -7
  66. package/dist/telemetry-B2iWkY5e.cjs.map +1 -0
  67. package/dist/{telemetry-CaNU4-Bf.js → telemetry-BkektVz6.js} +6 -8
  68. package/dist/telemetry-BkektVz6.js.map +1 -0
  69. package/dist/validate-Bfpf_UIh.cjs +26 -0
  70. package/dist/validate-Bfpf_UIh.cjs.map +1 -0
  71. package/dist/validate-lbUkWQ5o.js +26 -0
  72. package/dist/validate-lbUkWQ5o.js.map +1 -0
  73. package/package.json +12 -12
  74. package/src/commands/agent/start.ts +10 -7
  75. package/src/commands/agent.ts +3 -1
  76. package/src/commands/generate.ts +5 -3
  77. package/src/commands/init.ts +34 -3
  78. package/src/commands/mcp.ts +28 -4
  79. package/src/commands/validate.ts +6 -4
  80. package/src/constants.ts +1 -57
  81. package/src/index.ts +5 -3
  82. package/src/loggers/clackLogger.ts +45 -43
  83. package/src/loggers/fileSystemLogger.ts +11 -1
  84. package/src/loggers/githubActionsLogger.ts +13 -25
  85. package/src/loggers/plainLogger.ts +12 -23
  86. package/src/loggers/types.ts +6 -0
  87. package/src/loggers/utils.ts +155 -9
  88. package/src/runners/agent/run.ts +113 -0
  89. package/src/runners/agent/utils.ts +98 -0
  90. package/src/runners/generate/run.ts +276 -0
  91. package/src/runners/generate/utils.ts +209 -0
  92. package/src/runners/init/run.ts +211 -0
  93. package/src/{utils/packageManager.ts → runners/init/utils.ts} +10 -0
  94. package/src/runners/mcp/run.ts +55 -0
  95. package/src/runners/validate/run.ts +63 -0
  96. package/src/{utils/telemetry.ts → telemetry.ts} +12 -5
  97. package/dist/agent-BcUEl9yB.js +0 -56
  98. package/dist/agent-BcUEl9yB.js.map +0 -1
  99. package/dist/agent-CS45W0kL.cjs.map +0 -1
  100. package/dist/agent-CsMvXeqI.cjs +0 -58
  101. package/dist/agent-CsMvXeqI.cjs.map +0 -1
  102. package/dist/agent-IP0eLV3C.js.map +0 -1
  103. package/dist/constants-B4iBDvCe.cjs +0 -148
  104. package/dist/constants-B4iBDvCe.cjs.map +0 -1
  105. package/dist/constants-DmPrkaz8.js +0 -95
  106. package/dist/constants-DmPrkaz8.js.map +0 -1
  107. package/dist/generate-7td_hs73.cjs.map +0 -1
  108. package/dist/generate-BqeFFQGD.js.map +0 -1
  109. package/dist/generate-CUd1dUY5.cjs.map +0 -1
  110. package/dist/generate-DVmGtwWe.js.map +0 -1
  111. package/dist/init-C5sZulT6.cjs.map +0 -1
  112. package/dist/init-Cag3082g.js.map +0 -1
  113. package/dist/init-CfAn19gC.js +0 -25
  114. package/dist/init-CfAn19gC.js.map +0 -1
  115. package/dist/init-CfsYoyGe.cjs +0 -25
  116. package/dist/init-CfsYoyGe.cjs.map +0 -1
  117. package/dist/mcp-BfORW-mY.cjs.map +0 -1
  118. package/dist/mcp-BtOV6acy.js +0 -16
  119. package/dist/mcp-BtOV6acy.js.map +0 -1
  120. package/dist/mcp-CIbuLGMx.cjs +0 -16
  121. package/dist/mcp-CIbuLGMx.cjs.map +0 -1
  122. package/dist/mcp-DtQ5o0On.js +0 -46
  123. package/dist/mcp-DtQ5o0On.js.map +0 -1
  124. package/dist/package-BmYRU2hz.cjs.map +0 -1
  125. package/dist/package-DBU5ii-k.js +0 -6
  126. package/dist/package-DBU5ii-k.js.map +0 -1
  127. package/dist/telemetry-BU25EoI-.cjs.map +0 -1
  128. package/dist/telemetry-CaNU4-Bf.js.map +0 -1
  129. package/dist/validate-CQqM9siF.js +0 -25
  130. package/dist/validate-CQqM9siF.js.map +0 -1
  131. package/dist/validate-DBXLaLIn.cjs +0 -34
  132. package/dist/validate-DBXLaLIn.cjs.map +0 -1
  133. package/dist/validate-DI23zgmL.js +0 -33
  134. package/dist/validate-DI23zgmL.js.map +0 -1
  135. package/dist/validate-DwX4LzYq.cjs +0 -25
  136. package/dist/validate-DwX4LzYq.cjs.map +0 -1
  137. package/src/runners/agent.ts +0 -155
  138. package/src/runners/generate.ts +0 -333
  139. package/src/runners/init.ts +0 -296
  140. package/src/runners/mcp.ts +0 -51
  141. package/src/runners/validate.ts +0 -39
  142. package/src/types.ts +0 -11
  143. package/src/utils/Writables.ts +0 -17
  144. package/src/utils/executeHooks.ts +0 -45
  145. package/src/utils/flags.ts +0 -9
  146. package/src/utils/getConfig.ts +0 -10
  147. package/src/utils/getCosmiConfig.ts +0 -75
  148. package/src/utils/getSummary.ts +0 -68
  149. package/src/utils/runHook.ts +0 -91
  150. package/src/utils/watcher.ts +0 -19
@@ -0,0 +1,209 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { styleText } from 'node:util'
3
+ import type { AsyncEventEmitter } from '@internals/utils'
4
+ import { toError, tokenize } from '@internals/utils'
5
+ import type { CLIOptions, Config, KubbHooks, PossibleConfig } from '@kubb/core'
6
+ import { cosmiconfig } from 'cosmiconfig'
7
+ import { createJiti } from 'jiti'
8
+ import { NonZeroExitError, x } from 'tinyexec'
9
+ import type { HookSinkOptions } from '../../loggers/utils.ts'
10
+ import { WATCHER_IGNORED_PATHS } from '../../constants.ts'
11
+
12
+ type CosmiconfigResult = {
13
+ filepath: string
14
+ isEmpty?: boolean
15
+ config: PossibleConfig<CLIOptions>
16
+ }
17
+
18
+ const jiti = createJiti(import.meta.url, {
19
+ jsx: { runtime: 'automatic', importSource: '@kubb/renderer-jsx' },
20
+ moduleCache: false,
21
+ })
22
+
23
+ const tsLoader = (configFile: string) => jiti.import(configFile, { default: true })
24
+
25
+ const MODULE_NAME = 'kubb'
26
+
27
+ const BASE_SEARCH_PLACES = [
28
+ 'package.json',
29
+ `.${MODULE_NAME}rc`,
30
+ `.${MODULE_NAME}rc.json`,
31
+ `.${MODULE_NAME}rc.yaml`,
32
+ `.${MODULE_NAME}rc.yml`,
33
+ `.${MODULE_NAME}rc.ts`,
34
+ `.${MODULE_NAME}rc.mts`,
35
+ `.${MODULE_NAME}rc.cts`,
36
+ `.${MODULE_NAME}rc.js`,
37
+ `.${MODULE_NAME}rc.mjs`,
38
+ `.${MODULE_NAME}rc.cjs`,
39
+ `${MODULE_NAME}.config.ts`,
40
+ `${MODULE_NAME}.config.mts`,
41
+ `${MODULE_NAME}.config.cts`,
42
+ `${MODULE_NAME}.config.js`,
43
+ `${MODULE_NAME}.config.mjs`,
44
+ `${MODULE_NAME}.config.cjs`,
45
+ ]
46
+
47
+ const SEARCH_PLACES = ['', '.config/', 'configs/'].flatMap((prefix) => BASE_SEARCH_PLACES.map((p) => `${prefix}${p}`))
48
+
49
+ async function getCosmiConfig(configFile?: string): Promise<CosmiconfigResult> {
50
+ const explorer = cosmiconfig(MODULE_NAME, {
51
+ cache: false,
52
+ searchPlaces: SEARCH_PLACES,
53
+ loaders: { '.ts': tsLoader, '.mts': tsLoader, '.cts': tsLoader },
54
+ })
55
+
56
+ let result: CosmiconfigResult
57
+ try {
58
+ result = (configFile ? await explorer.load(configFile) : await explorer.search()) as CosmiconfigResult
59
+ } catch (error) {
60
+ throw new Error('Config failed loading', { cause: error })
61
+ }
62
+
63
+ if (!result?.config || result.isEmpty) {
64
+ throw new Error('Config not defined, create a kubb.config.js or pass through your config with the option --config')
65
+ }
66
+
67
+ return result
68
+ }
69
+
70
+ type GetConfigsOptions = {
71
+ /**
72
+ * Explicit path to the Kubb config file. When omitted, cosmiconfig searches from the current directory.
73
+ */
74
+ configPath?: string
75
+ /**
76
+ * Optional OpenAPI input path that overrides `config.input.path` for this run.
77
+ */
78
+ input?: string
79
+ }
80
+
81
+ type GetConfigsResult = {
82
+ /**
83
+ * Absolute path to the resolved config file.
84
+ */
85
+ configPath: string
86
+ /**
87
+ * Resolved and normalized array of Kubb configs, each guaranteed to have a `plugins` array.
88
+ */
89
+ configs: Array<Config>
90
+ }
91
+
92
+ /**
93
+ * Discovers the Kubb config via cosmiconfig and resolves it into a normalized array of configs.
94
+ * Every config in the result is guaranteed to have a `plugins` array.
95
+ */
96
+ export async function getConfigs({ configPath, input }: GetConfigsOptions): Promise<GetConfigsResult> {
97
+ const result = await getCosmiConfig(configPath)
98
+ const resolved = await (typeof result.config === 'function' ? result.config({ input } as CLIOptions) : result.config)
99
+ const userConfigs = Array.isArray(resolved) ? resolved : [resolved]
100
+
101
+ return {
102
+ configPath: result.filepath,
103
+ configs: userConfigs.map((item) => ({ ...item, plugins: item.plugins ?? [] }) as Config),
104
+ }
105
+ }
106
+
107
+ type ExecuteHooksOptions = {
108
+ configHooks: NonNullable<Config['hooks']>
109
+ hooks: AsyncEventEmitter<KubbHooks>
110
+ makeSink?: (commandWithArgs: string) => HookSinkOptions | undefined
111
+ }
112
+
113
+ /**
114
+ * Runs the `done` hooks defined in a Kubb config in sequence.
115
+ */
116
+ export async function executeHooks({ configHooks, hooks, makeSink }: ExecuteHooksOptions): Promise<void> {
117
+ const commands = Array.isArray(configHooks.done) ? configHooks.done : [configHooks.done].filter(Boolean)
118
+
119
+ for (const command of commands) {
120
+ const [cmd, ...args] = tokenize(command)
121
+ if (!cmd) continue
122
+
123
+ const hookId = createHash('sha256').update(command).digest('hex')
124
+ const commandWithArgs = [cmd, ...args].join(' ')
125
+
126
+ await hooks.emit('kubb:hook:start', { id: hookId, command: cmd, args })
127
+
128
+ const { stream = false, onLine, onStdout, onStderr } = makeSink?.(commandWithArgs) ?? {}
129
+ await runHook({ id: hookId, command: cmd, args, commandWithArgs, context: hooks, stream, sink: { onLine, onStdout, onStderr } })
130
+ }
131
+ }
132
+
133
+ type RunHookOptions = {
134
+ id: string
135
+ command: string
136
+ args?: readonly string[]
137
+ commandWithArgs: string
138
+ context: AsyncEventEmitter<KubbHooks>
139
+ stream?: boolean
140
+ sink?: HookSinkOptions
141
+ }
142
+
143
+ async function runHook({ id, command, args, commandWithArgs, context, stream = false, sink }: RunHookOptions): Promise<void> {
144
+ const emitEnd = (success: boolean, error: Error | null) => context.emit('kubb:hook:end', { command, args, id, success, error })
145
+
146
+ try {
147
+ const proc = x(command, [...(args ?? [])], {
148
+ nodeOptions: { detached: process.platform !== 'win32' },
149
+ throwOnError: true,
150
+ })
151
+
152
+ if (stream && sink?.onLine) {
153
+ for await (const line of proc) {
154
+ sink.onLine(line)
155
+ }
156
+ }
157
+
158
+ const result = await proc
159
+ await context.emit('kubb:debug', { date: new Date(), logs: [result.stdout.trimEnd()] })
160
+ await context.emit('kubb:success', { message: `${styleText('dim', commandWithArgs)} successfully executed` })
161
+ await emitEnd(true, null)
162
+ } catch (err) {
163
+ if (!(err instanceof NonZeroExitError)) {
164
+ const error = toError(err)
165
+ await emitEnd(false, error)
166
+ await context.emit('kubb:error', { error })
167
+ return
168
+ }
169
+
170
+ const stderr = err.output?.stderr ?? ''
171
+ const stdout = err.output?.stdout ?? ''
172
+
173
+ await context.emit('kubb:debug', { date: new Date(), logs: [stdout, stderr].filter(Boolean) })
174
+
175
+ if (stderr) sink?.onStderr?.(stderr)
176
+ if (stdout) sink?.onStdout?.(stdout)
177
+
178
+ const error = new Error(`Hook execute failed: ${commandWithArgs}`)
179
+ await emitEnd(false, error)
180
+ await context.emit('kubb:error', { error })
181
+ }
182
+ }
183
+
184
+ type WatcherLog = {
185
+ info: (message: string) => void
186
+ error: (message: string) => void
187
+ }
188
+
189
+ /**
190
+ * Starts a file watcher on the given paths and calls `cb` on any change.
191
+ * Ignores `.git` and `node_modules` directories.
192
+ */
193
+ export async function startWatcher(
194
+ path: string[],
195
+ cb: (path: string[]) => Promise<void>,
196
+ log: WatcherLog = { info: console.log, error: console.log },
197
+ ): Promise<void> {
198
+ const { watch } = await import('chokidar')
199
+ const watcher = watch(path, { ignorePermissionErrors: true, ignored: WATCHER_IGNORED_PATHS })
200
+
201
+ watcher.on('all', async (type, file) => {
202
+ log.info(styleText('yellow', styleText('bold', `Change detected: ${type} ${file}`)))
203
+ try {
204
+ await cb(path)
205
+ } catch (_e) {
206
+ log.error(styleText('red', 'Watcher failed'))
207
+ }
208
+ })
209
+ }
@@ -0,0 +1,211 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import process from 'node:process'
4
+ import { styleText } from 'node:util'
5
+ import * as clack from '@clack/prompts'
6
+ import { detectPackageManager } from '@internals/utils'
7
+ import { availablePlugins, generateConfigFile, initDefaults, KUBB_CONFIG_FILENAME, type PluginOption } from '@internals/shared'
8
+ import { hasPackageJson, initPackageJson, installPackages } from './utils.ts'
9
+
10
+ function cancelAndExit(message = 'Operation cancelled.'): never {
11
+ clack.cancel(message)
12
+ process.exit(0)
13
+ }
14
+
15
+ type InitOptions = {
16
+ /**
17
+ * When `true`, skips all interactive prompts and uses default values.
18
+ */
19
+ yes: boolean
20
+ /**
21
+ * Current `@kubb/cli` version string, shown in the outro and used for package installation.
22
+ */
23
+ version: string
24
+ /**
25
+ * Input path flag value from `--input`. When provided, skips the input prompt.
26
+ */
27
+ input?: string
28
+ /**
29
+ * Output directory flag value from `--output`. When provided, skips the output prompt.
30
+ */
31
+ output?: string
32
+ /**
33
+ * Comma-separated plugin list from `--plugins`, e.g. `'plugin-ts,plugin-zod'`. When provided, skips the plugin selection prompt.
34
+ */
35
+ plugins?: string
36
+ }
37
+
38
+ /**
39
+ * Runs the interactive Kubb scaffolding wizard.
40
+ * Detects the package manager, prompts for input/output paths and plugins, installs packages, and writes `kubb.config.ts`.
41
+ * Pass `yes: true` to skip all prompts and use defaults.
42
+ */
43
+ export async function run({ yes, version, input: inputFlag, output: outputFlag, plugins: pluginsFlag }: InitOptions): Promise<void> {
44
+ const cwd = process.cwd()
45
+
46
+ clack.intro(styleText('bgCyan', styleText('black', ' Kubb Init ')))
47
+
48
+ /**
49
+ * Returns `flag` when provided, the `defaultValue` when `yes` is set,
50
+ * or calls `prompt()` for interactive input. Exits on cancellation.
51
+ */
52
+ async function resolveOrPrompt<T>(flag: T | undefined, defaultValue: T, logLabel: string, prompt: () => Promise<T | symbol>): Promise<T> {
53
+ if (flag !== undefined) {
54
+ clack.log.info(`${logLabel}: ${styleText('cyan', String(flag))}`)
55
+ return flag
56
+ }
57
+ if (yes) {
58
+ clack.log.info(`${logLabel}: ${styleText('cyan', String(defaultValue))}`)
59
+ return defaultValue
60
+ }
61
+ const result = await prompt()
62
+ if (clack.isCancel(result)) cancelAndExit()
63
+ return result as T
64
+ }
65
+
66
+ try {
67
+ // Check/create package.json — detect package manager once after the block
68
+ if (!hasPackageJson(cwd)) {
69
+ if (!yes) {
70
+ const shouldInit = await clack.confirm({
71
+ message: 'No package.json found. Would you like to create one?',
72
+ initialValue: true,
73
+ })
74
+
75
+ if (clack.isCancel(shouldInit) || !shouldInit) {
76
+ cancelAndExit()
77
+ }
78
+ }
79
+
80
+ const packageManager = detectPackageManager(cwd)
81
+ const spinner = clack.spinner()
82
+ spinner.start(`Initializing package.json with ${packageManager.name}`)
83
+ await initPackageJson(cwd, packageManager)
84
+ spinner.stop(`Created package.json with ${packageManager.name}`)
85
+ }
86
+
87
+ const packageManager = detectPackageManager(cwd)
88
+ if (hasPackageJson(cwd)) {
89
+ clack.log.info(`Detected package manager: ${styleText('cyan', packageManager.name)}`)
90
+ }
91
+
92
+ // Prompt for OpenAPI spec path
93
+ const inputPath = await resolveOrPrompt(inputFlag, initDefaults.inputPath, 'Using input path', () =>
94
+ clack.text({
95
+ message: 'Where is your OpenAPI specification located?',
96
+ placeholder: initDefaults.inputPath,
97
+ defaultValue: initDefaults.inputPath,
98
+ validate: (value) => {
99
+ if (!value) return 'Input path is required'
100
+ },
101
+ }),
102
+ )
103
+
104
+ // Prompt for output directory
105
+ const outputPath = await resolveOrPrompt(outputFlag, initDefaults.outputPath, 'Using output path', () =>
106
+ clack.text({
107
+ message: 'Where should the generated files be output?',
108
+ placeholder: initDefaults.outputPath,
109
+ defaultValue: initDefaults.outputPath,
110
+ validate: (value) => {
111
+ if (!value) return 'Output path is required'
112
+ },
113
+ }),
114
+ )
115
+
116
+ // Plugin selection
117
+ const defaultPlugins = availablePlugins.filter((p) => (initDefaults.plugins as readonly string[]).includes(p.value))
118
+ const pluginLabel = (plugins: PluginOption[]) => styleText('cyan', plugins.map((p) => p.label).join(', '))
119
+
120
+ let selectedPlugins: PluginOption[]
121
+ if (pluginsFlag) {
122
+ const requested = pluginsFlag
123
+ .split(',')
124
+ .map((v) => v.trim())
125
+ .filter(Boolean)
126
+ selectedPlugins = availablePlugins.filter((p) => requested.includes(p.value))
127
+ if (selectedPlugins.length === 0) {
128
+ selectedPlugins = defaultPlugins
129
+ clack.log.warn(`No valid plugins found in --plugins value; falling back to default: ${pluginLabel(defaultPlugins)}`)
130
+ } else {
131
+ clack.log.info(`Using plugins: ${pluginLabel(selectedPlugins)}`)
132
+ }
133
+ } else if (yes) {
134
+ selectedPlugins = defaultPlugins
135
+ clack.log.info(`Using plugins: ${pluginLabel(defaultPlugins)}`)
136
+ } else {
137
+ const values = await clack.multiselect({
138
+ message: 'Select plugins to use:',
139
+ options: availablePlugins.map(({ value, label, hint }) => ({ value, label, hint })),
140
+ initialValues: [...initDefaults.plugins],
141
+ required: true,
142
+ })
143
+ if (clack.isCancel(values)) cancelAndExit()
144
+ selectedPlugins = availablePlugins.filter((p) => (values as string[]).includes(p.value))
145
+ }
146
+
147
+ // Install packages
148
+ const packagesToInstall = ['kubb', ...selectedPlugins.map((p) => p.packageName)]
149
+
150
+ const spinner = clack.spinner()
151
+ spinner.start(`Installing ${packagesToInstall.length} packages with ${packageManager.name}`)
152
+
153
+ try {
154
+ await installPackages(packagesToInstall, packageManager, cwd)
155
+ spinner.stop(`Installed ${packagesToInstall.length} packages`)
156
+ } catch (error) {
157
+ spinner.stop('Installation failed')
158
+ throw error
159
+ }
160
+
161
+ // Generate config file
162
+ const configSpinner = clack.spinner()
163
+ configSpinner.start(`Creating ${KUBB_CONFIG_FILENAME}`)
164
+
165
+ const configContent = generateConfigFile({ selectedPlugins, inputPath, outputPath })
166
+ const configPath = path.join(cwd, KUBB_CONFIG_FILENAME)
167
+
168
+ if (fs.existsSync(configPath)) {
169
+ configSpinner.stop(`${KUBB_CONFIG_FILENAME} already exists`)
170
+
171
+ if (!yes) {
172
+ const shouldOverwrite = await clack.confirm({
173
+ message: `${KUBB_CONFIG_FILENAME} already exists. Overwrite?`,
174
+ initialValue: false,
175
+ })
176
+
177
+ if (clack.isCancel(shouldOverwrite) || !shouldOverwrite) {
178
+ cancelAndExit('Keeping existing configuration. Packages have been installed.')
179
+ }
180
+ }
181
+
182
+ configSpinner.start(`Overwriting ${KUBB_CONFIG_FILENAME}`)
183
+ }
184
+
185
+ await fs.promises.writeFile(configPath, configContent, 'utf-8')
186
+
187
+ configSpinner.stop(`Created ${KUBB_CONFIG_FILENAME}`)
188
+
189
+ clack.outro(
190
+ styleText('green', '✓ All set!') +
191
+ '\n\n' +
192
+ styleText('dim', 'Next steps:') +
193
+ '\n' +
194
+ styleText('cyan', ` 1. Make sure your OpenAPI spec is at: ${inputPath}`) +
195
+ '\n' +
196
+ styleText('cyan', ' 2. Generate code with: npx kubb generate') +
197
+ '\n' +
198
+ styleText('cyan', ' Or start a stream server with: npx kubb agent start') +
199
+ '\n' +
200
+ styleText('cyan', ` 3. Find generated files in: ${outputPath}`) +
201
+ '\n\n' +
202
+ styleText('dim', `Using ${packageManager.name} • Kubb v${version}`),
203
+ )
204
+ } catch (error) {
205
+ clack.log.error(styleText('red', 'An error occurred during initialization'))
206
+ if (error instanceof Error) {
207
+ clack.log.error(error.message)
208
+ }
209
+ process.exit(1)
210
+ }
211
+ }
@@ -1,12 +1,19 @@
1
1
  import fs from 'node:fs'
2
2
  import path from 'node:path'
3
+ import process from 'node:process'
3
4
  import type { PackageManagerInfo, PackageManagerName } from '@internals/utils'
4
5
  import { spawnAsync } from '@internals/utils'
5
6
 
7
+ /**
8
+ * Returns `true` when a `package.json` exists at `cwd`.
9
+ */
6
10
  export function hasPackageJson(cwd: string = process.cwd()): boolean {
7
11
  return fs.existsSync(path.join(cwd, 'package.json'))
8
12
  }
9
13
 
14
+ /**
15
+ * Initializes a new `package.json` at `cwd` using the detected package manager.
16
+ */
10
17
  export async function initPackageJson(cwd: string, packageManager: PackageManagerInfo): Promise<void> {
11
18
  const commands: Record<PackageManagerName, string[]> = {
12
19
  npm: ['init', '-y'],
@@ -18,6 +25,9 @@ export async function initPackageJson(cwd: string, packageManager: PackageManage
18
25
  await spawnAsync(packageManager.name, commands[packageManager.name], { cwd })
19
26
  }
20
27
 
28
+ /**
29
+ * Installs the given packages at `cwd` using the detected package manager.
30
+ */
21
31
  export async function installPackages(packages: string[], packageManager: PackageManagerInfo, cwd: string = process.cwd()): Promise<void> {
22
32
  await spawnAsync(packageManager.name, [...packageManager.installCommand, ...packages], { cwd })
23
33
  }
@@ -0,0 +1,55 @@
1
+ import process from 'node:process'
2
+ import { styleText } from 'node:util'
3
+ import { getErrorMessage } from '@internals/utils'
4
+ import type * as McpModule from '@kubb/mcp'
5
+ import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
6
+
7
+ type McpOptions = {
8
+ /**
9
+ * Current `@kubb/cli` version string, used for the telemetry payload.
10
+ */
11
+ version: string
12
+ /**
13
+ * TCP port for the HTTP MCP server. When `undefined`, the server uses stdio transport.
14
+ */
15
+ port?: string
16
+ /**
17
+ * Hostname to bind to when running in HTTP mode.
18
+ *
19
+ * @default 'localhost'
20
+ */
21
+ host?: string
22
+ }
23
+
24
+ /**
25
+ * Starts the Kubb MCP server using `@kubb/mcp`.
26
+ * Exits the process with code 1 if `@kubb/mcp` is not installed.
27
+ */
28
+ export async function run({ version, port, host }: McpOptions): Promise<void> {
29
+ let mod: typeof McpModule
30
+ try {
31
+ mod = (await import('@kubb/mcp')) as typeof McpModule
32
+ } catch (_e) {
33
+ console.error(styleText('red', 'The @kubb/mcp package is not installed.'))
34
+ console.error('')
35
+ console.error('Install it with:')
36
+ console.error(styleText('cyan', ' npm install @kubb/mcp'))
37
+ console.error(styleText('cyan', ' # or'))
38
+ console.error(styleText('cyan', ' pnpm install @kubb/mcp'))
39
+ console.error('')
40
+ process.exit(1)
41
+ }
42
+
43
+ const { run: startMcpServer } = mod
44
+ const hrStart = process.hrtime()
45
+ const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'mcp', kubbVersion: version, hrStart, status }))
46
+ try {
47
+ console.log(styleText('cyan', '⏳ Starting MCP server...'))
48
+ console.warn(styleText('yellow', 'This feature is still under development, use with caution'))
49
+ await startMcpServer(undefined, { port: port !== undefined ? Number(port) : undefined, host })
50
+ await report('success')
51
+ } catch (error) {
52
+ await report('failed')
53
+ console.error(getErrorMessage(error))
54
+ }
55
+ }
@@ -0,0 +1,63 @@
1
+ import process from 'node:process'
2
+ import { styleText } from 'node:util'
3
+ import { getErrorMessage } from '@internals/utils'
4
+ import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
5
+
6
+ type ValidateOptions = {
7
+ /**
8
+ * Path or URL to the OpenAPI/Swagger file to validate.
9
+ */
10
+ input: string
11
+ /**
12
+ * Current `@kubb/cli` version string, used for the telemetry payload.
13
+ */
14
+ version: string
15
+ }
16
+
17
+ type ValidateModule = typeof import('@kubb/adapter-oas')
18
+ type ValidateDependencies = {
19
+ /**
20
+ * Loads `@kubb/adapter-oas`. Injected so tests can substitute a mock.
21
+ */
22
+ loadValidateModule: () => Promise<ValidateModule>
23
+ }
24
+
25
+ /**
26
+ * Dynamically loads `@kubb/adapter-oas` for OpenAPI validation.
27
+ */
28
+ export function loadValidateModule(): Promise<ValidateModule> {
29
+ return import('@kubb/adapter-oas') as Promise<ValidateModule>
30
+ }
31
+
32
+ /**
33
+ * Validates an OpenAPI/Swagger file at `input` using `@kubb/adapter-oas`.
34
+ * Exits the process with code 1 on validation failure or missing dependency.
35
+ */
36
+ export async function run({ input, version }: ValidateOptions, dependencies: ValidateDependencies = { loadValidateModule }): Promise<void> {
37
+ const hrStart = process.hrtime()
38
+ const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'validate', kubbVersion: version, hrStart, status }))
39
+ try {
40
+ const { adapterOas } = await dependencies.loadValidateModule()
41
+ const adapter = adapterOas()
42
+ if (!adapter.validate) {
43
+ throw new Error('The loaded adapter does not support validation.')
44
+ }
45
+ await adapter.validate(input, { throwOnError: true })
46
+ await report('success')
47
+ console.log('✅ Validation success')
48
+ } catch (error) {
49
+ await report('failed')
50
+ if (error instanceof Error && /@kubb\/adapter-oas/.test(error.message)) {
51
+ console.error(styleText('red', 'The @kubb/adapter-oas package is not installed.'))
52
+ console.error('')
53
+ console.error('Install it with:')
54
+ console.error(styleText('cyan', ' npm install @kubb/adapter-oas'))
55
+ console.error(styleText('cyan', ' # or'))
56
+ console.error(styleText('cyan', ' pnpm install @kubb/adapter-oas'))
57
+ console.error('')
58
+ }
59
+ console.error('❌ Validation failed')
60
+ console.error(getErrorMessage(error))
61
+ process.exit(1)
62
+ }
63
+ }
@@ -2,7 +2,7 @@ import { randomBytes } from 'node:crypto'
2
2
  import os from 'node:os'
3
3
  import process from 'node:process'
4
4
  import { executeIfOnline, isCIEnvironment } from '@internals/utils'
5
- import { OTLP_ENDPOINT } from '../constants.ts'
5
+ import { OTLP_ENDPOINT } from './constants.ts'
6
6
 
7
7
  // OpenTelemetry OTLP JSON types
8
8
  // https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto
@@ -96,8 +96,17 @@ type OtlpExportTraceServiceRequest = {
96
96
  resourceSpans: OtlpResourceSpans[]
97
97
  }
98
98
 
99
+ /**
100
+ * Anonymous plugin name and options snapshot sent with each telemetry event.
101
+ */
99
102
  export type TelemetryPlugin = {
103
+ /**
104
+ * Plugin name as registered in the Kubb config, e.g. `'@kubb/plugin-ts'`.
105
+ */
100
106
  name: string
107
+ /**
108
+ * anonymized plugin options snapshot — values are included but cannot be traced back to the user.
109
+ */
101
110
  options: Record<string, unknown>
102
111
  }
103
112
 
@@ -114,16 +123,14 @@ type TelemetryEvent = {
114
123
  }
115
124
 
116
125
  /**
117
- * Detect whether the current process is running inside a CI environment.
118
- * Delegates to the canonical isCIEnvironment() from envDetection.
126
+ * Returns `true` when the current process runs inside a CI environment.
119
127
  */
120
128
  export function isCi(): boolean {
121
129
  return isCIEnvironment()
122
130
  }
123
131
 
124
132
  /**
125
- * Check if telemetry is disabled via DO_NOT_TRACK or KUBB_DISABLE_TELEMETRY.
126
- * Respects the standard DO_NOT_TRACK convention used across development tools.
133
+ * Returns `true` when telemetry is disabled via `DO_NOT_TRACK` or `KUBB_DISABLE_TELEMETRY`.
127
134
  */
128
135
  export function isTelemetryDisabled(): boolean {
129
136
  return (
@@ -1,56 +0,0 @@
1
- import "./chunk--u3MIqq1.js";
2
- import { n as defineCommand } from "./define-Ctii4bel.js";
3
- import { t as version } from "./package-DBU5ii-k.js";
4
- import { s as agentDefaults } from "./constants-DmPrkaz8.js";
5
- //#endregion
6
- //#region src/commands/agent.ts
7
- const command = defineCommand({
8
- name: "agent",
9
- description: "Manage the Kubb Agent server",
10
- subCommands: [defineCommand({
11
- name: "start",
12
- description: "Start the Agent server",
13
- options: {
14
- config: {
15
- type: "string",
16
- description: "Path to the Kubb config",
17
- short: "c"
18
- },
19
- port: {
20
- type: "string",
21
- description: `Port for the server (default: ${agentDefaults.port})`,
22
- short: "p"
23
- },
24
- host: {
25
- type: "string",
26
- description: "Host for the server",
27
- default: agentDefaults.host
28
- },
29
- "allow-write": {
30
- type: "boolean",
31
- description: "Allow writing generated files to the filesystem. When not set, no files are written and the config patch is not persisted.",
32
- default: false
33
- },
34
- "allow-all": {
35
- type: "boolean",
36
- description: "Grant all permissions (implies --allow-write).",
37
- default: false
38
- }
39
- },
40
- async run({ values }) {
41
- const { runAgentStart } = await import("./agent-IP0eLV3C.js");
42
- await runAgentStart({
43
- port: values.port !== void 0 ? values.port : void 0,
44
- host: values.host,
45
- configPath: values.config,
46
- allowWrite: values["allow-write"],
47
- allowAll: values["allow-all"],
48
- version
49
- });
50
- }
51
- })]
52
- });
53
- //#endregion
54
- export { command };
55
-
56
- //# sourceMappingURL=agent-BcUEl9yB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent-BcUEl9yB.js","names":["command","startCommand"],"sources":["../src/commands/agent/start.ts","../src/commands/agent.ts"],"sourcesContent":["import { defineCommand } from '@internals/utils'\nimport { version } from '../../../package.json'\nimport { agentDefaults } from '../../constants.ts'\n\nexport const command = defineCommand({\n name: 'start',\n description: 'Start the Agent server',\n options: {\n config: {\n type: 'string',\n description: 'Path to the Kubb config',\n short: 'c',\n },\n port: {\n type: 'string',\n description: `Port for the server (default: ${agentDefaults.port})`,\n short: 'p',\n },\n host: {\n type: 'string',\n description: 'Host for the server',\n default: agentDefaults.host,\n },\n 'allow-write': {\n type: 'boolean',\n description: 'Allow writing generated files to the filesystem. When not set, no files are written and the config patch is not persisted.',\n default: false,\n },\n 'allow-all': {\n type: 'boolean',\n description: 'Grant all permissions (implies --allow-write).',\n default: false,\n },\n },\n async run({ values }) {\n const { runAgentStart } = await import('../../runners/agent.ts')\n\n await runAgentStart({\n port: values.port !== undefined ? values.port : undefined,\n host: values.host,\n configPath: values.config,\n allowWrite: values['allow-write'],\n allowAll: values['allow-all'],\n version,\n })\n },\n})\n","import { defineCommand } from '@internals/utils'\nimport { command as startCommand } from './agent/start.ts'\n\nexport const command = defineCommand({\n name: 'agent',\n description: 'Manage the Kubb Agent server',\n subCommands: [startCommand],\n})\n"],"mappings":";;;;;;ACGA,MAAa,UAAU,cAAc;CACnC,MAAM;CACN,aAAa;CACb,aAAa,CDFQ,cAAc;EACnC,MAAM;EACN,aAAa;EACb,SAAS;GACP,QAAQ;IACN,MAAM;IACN,aAAa;IACb,OAAO;IACR;GACD,MAAM;IACJ,MAAM;IACN,aAAa,iCAAiC,cAAc,KAAK;IACjE,OAAO;IACR;GACD,MAAM;IACJ,MAAM;IACN,aAAa;IACb,SAAS,cAAc;IACxB;GACD,eAAe;IACb,MAAM;IACN,aAAa;IACb,SAAS;IACV;GACD,aAAa;IACX,MAAM;IACN,aAAa;IACb,SAAS;IACV;GACF;EACD,MAAM,IAAI,EAAE,UAAU;GACpB,MAAM,EAAE,kBAAkB,MAAM,OAAO;AAEvC,SAAM,cAAc;IAClB,MAAM,OAAO,SAAS,KAAA,IAAY,OAAO,OAAO,KAAA;IAChD,MAAM,OAAO;IACb,YAAY,OAAO;IACnB,YAAY,OAAO;IACnB,UAAU,OAAO;IACjB;IACD,CAAC;;EAEL,CCxCeC,CAAa;CAC5B,CAAC"}