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

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 (133) hide show
  1. package/LICENSE +17 -10
  2. package/README.md +45 -77
  3. package/bin/kubb.js +9 -3
  4. package/dist/Telemetry-CfPP7MYq.cjs +321 -0
  5. package/dist/Telemetry-CfPP7MYq.cjs.map +1 -0
  6. package/dist/Telemetry-uAr3lK_-.js +284 -0
  7. package/dist/Telemetry-uAr3lK_-.js.map +1 -0
  8. package/dist/{define-Bdn8j5VM.cjs → defineCommand-Bo3yZTWI.cjs} +3 -21
  9. package/dist/defineCommand-Bo3yZTWI.cjs.map +1 -0
  10. package/dist/{define-m_fp-Aqm.js → defineCommand-DMEeqliP.js} +4 -16
  11. package/dist/defineCommand-DMEeqliP.js.map +1 -0
  12. package/dist/{errors-CINO1EIv.js → errors-Dc_d7BfX.js} +2 -2
  13. package/dist/{errors-CINO1EIv.js.map → errors-Dc_d7BfX.js.map} +1 -1
  14. package/dist/{errors-CLCjoSg0.cjs → errors-gxFK0vrp.cjs} +2 -2
  15. package/dist/{errors-CLCjoSg0.cjs.map → errors-gxFK0vrp.cjs.map} +1 -1
  16. package/dist/{generate-BY-juRdH.js → generate-BdxIouwm.js} +21 -16
  17. package/dist/generate-BdxIouwm.js.map +1 -0
  18. package/dist/{generate-Bod9YCbF.cjs → generate-tRupKbnI.cjs} +21 -16
  19. package/dist/generate-tRupKbnI.cjs.map +1 -0
  20. package/dist/index.cjs +34 -81
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.ts +6 -1
  23. package/dist/index.js +34 -81
  24. package/dist/index.js.map +1 -1
  25. package/dist/{init-Cs3Fp6nN.js → init-D_9I495E.js} +5 -5
  26. package/dist/{init-Cs3Fp6nN.js.map → init-D_9I495E.js.map} +1 -1
  27. package/dist/{init-BIkZU6mB.cjs → init-XlS3aia7.cjs} +6 -6
  28. package/dist/{init-BIkZU6mB.cjs.map → init-XlS3aia7.cjs.map} +1 -1
  29. package/dist/mcp-BlKi3z04.js +21 -0
  30. package/dist/mcp-BlKi3z04.js.map +1 -0
  31. package/dist/mcp-DSo5Ccwz.cjs +21 -0
  32. package/dist/mcp-DSo5Ccwz.cjs.map +1 -0
  33. package/dist/package-CsDaFmfZ.js +6 -0
  34. package/dist/package-CsDaFmfZ.js.map +1 -0
  35. package/dist/{package-DrUndPET.cjs → package-HWZRLSO4.cjs} +2 -2
  36. package/dist/package-HWZRLSO4.cjs.map +1 -0
  37. package/dist/{chunk-BvFE5Tac.js → rolldown-runtime-C0LytTxp.js} +0 -1
  38. package/dist/{run-YsoCk5we.cjs → run-AYlRjIX5.cjs} +136 -98
  39. package/dist/run-AYlRjIX5.cjs.map +1 -0
  40. package/dist/run-BM1t8CSM.cjs +33 -0
  41. package/dist/run-BM1t8CSM.cjs.map +1 -0
  42. package/dist/run-BlFVmIJl.js +32 -0
  43. package/dist/run-BlFVmIJl.js.map +1 -0
  44. package/dist/{run-CQbj3ley.cjs → run-CBc896in.cjs} +6 -6
  45. package/dist/run-CBc896in.cjs.map +1 -0
  46. package/dist/{run-CF97BWVa.js → run-D9mQoQHA.js} +123 -85
  47. package/dist/run-D9mQoQHA.js.map +1 -0
  48. package/dist/{run-CCZ24VKk.js → run-D_dWNFhX.js} +5 -5
  49. package/dist/run-D_dWNFhX.js.map +1 -0
  50. package/dist/run-DwylXpzM.cjs +1380 -0
  51. package/dist/run-DwylXpzM.cjs.map +1 -0
  52. package/dist/run-KlHwxNTr.js +1377 -0
  53. package/dist/run-KlHwxNTr.js.map +1 -0
  54. package/dist/tools-CZT9wSA6.cjs +175 -0
  55. package/dist/tools-CZT9wSA6.cjs.map +1 -0
  56. package/dist/tools-D0UogMU3.js +152 -0
  57. package/dist/tools-D0UogMU3.js.map +1 -0
  58. package/dist/{validate-Bfpf_UIh.cjs → validate-3gu3yglv.cjs} +6 -6
  59. package/dist/{validate-Bfpf_UIh.cjs.map → validate-3gu3yglv.cjs.map} +1 -1
  60. package/dist/{validate-lbUkWQ5o.js → validate-DBqdV14W.js} +5 -5
  61. package/dist/{validate-lbUkWQ5o.js.map → validate-DBqdV14W.js.map} +1 -1
  62. package/package.json +13 -25
  63. package/dist/agent-DN7o8nlE.js +0 -68
  64. package/dist/agent-DN7o8nlE.js.map +0 -1
  65. package/dist/agent-Fm9_8BBH.cjs +0 -70
  66. package/dist/agent-Fm9_8BBH.cjs.map +0 -1
  67. package/dist/constants-B2JTeRBb.js +0 -42
  68. package/dist/constants-B2JTeRBb.js.map +0 -1
  69. package/dist/constants-BINTA5VZ.cjs +0 -77
  70. package/dist/constants-BINTA5VZ.cjs.map +0 -1
  71. package/dist/constants-BYGmiFs0.cjs +0 -139
  72. package/dist/constants-BYGmiFs0.cjs.map +0 -1
  73. package/dist/constants-DSJ-Xrbv.js +0 -116
  74. package/dist/constants-DSJ-Xrbv.js.map +0 -1
  75. package/dist/define-Bdn8j5VM.cjs.map +0 -1
  76. package/dist/define-m_fp-Aqm.js.map +0 -1
  77. package/dist/generate-BY-juRdH.js.map +0 -1
  78. package/dist/generate-Bod9YCbF.cjs.map +0 -1
  79. package/dist/mcp-BSNulBcC.js +0 -39
  80. package/dist/mcp-BSNulBcC.js.map +0 -1
  81. package/dist/mcp-DcSrFhhP.cjs +0 -39
  82. package/dist/mcp-DcSrFhhP.cjs.map +0 -1
  83. package/dist/package-D5wmvFl4.js +0 -6
  84. package/dist/package-D5wmvFl4.js.map +0 -1
  85. package/dist/package-DrUndPET.cjs.map +0 -1
  86. package/dist/run-BAJubgdA.js +0 -1735
  87. package/dist/run-BAJubgdA.js.map +0 -1
  88. package/dist/run-BzpYYOQs.js +0 -121
  89. package/dist/run-BzpYYOQs.js.map +0 -1
  90. package/dist/run-CCZ24VKk.js.map +0 -1
  91. package/dist/run-CF97BWVa.js.map +0 -1
  92. package/dist/run-CQbj3ley.cjs.map +0 -1
  93. package/dist/run-CqKd6JNc.cjs +0 -1738
  94. package/dist/run-CqKd6JNc.cjs.map +0 -1
  95. package/dist/run-D0hmRpHy.js +0 -49
  96. package/dist/run-D0hmRpHy.js.map +0 -1
  97. package/dist/run-DwdAwnLG.cjs +0 -125
  98. package/dist/run-DwdAwnLG.cjs.map +0 -1
  99. package/dist/run-Lr0Ctnu0.cjs +0 -50
  100. package/dist/run-Lr0Ctnu0.cjs.map +0 -1
  101. package/dist/run-YsoCk5we.cjs.map +0 -1
  102. package/dist/shell-475fQKaX.cjs +0 -62
  103. package/dist/shell-475fQKaX.cjs.map +0 -1
  104. package/dist/shell-CN6DNqeC.js +0 -51
  105. package/dist/shell-CN6DNqeC.js.map +0 -1
  106. package/dist/telemetry-B2iWkY5e.cjs +0 -280
  107. package/dist/telemetry-B2iWkY5e.cjs.map +0 -1
  108. package/dist/telemetry-BkektVz6.js +0 -243
  109. package/dist/telemetry-BkektVz6.js.map +0 -1
  110. package/src/commands/agent/start.ts +0 -50
  111. package/src/commands/agent.ts +0 -10
  112. package/src/commands/generate.ts +0 -59
  113. package/src/commands/init.ts +0 -51
  114. package/src/commands/mcp.ts +0 -36
  115. package/src/commands/validate.ts +0 -22
  116. package/src/constants.ts +0 -48
  117. package/src/index.ts +0 -45
  118. package/src/loggers/clackLogger.ts +0 -460
  119. package/src/loggers/fileSystemLogger.ts +0 -148
  120. package/src/loggers/githubActionsLogger.ts +0 -367
  121. package/src/loggers/plainLogger.ts +0 -243
  122. package/src/loggers/types.ts +0 -7
  123. package/src/loggers/utils.ts +0 -252
  124. package/src/runners/agent/run.ts +0 -113
  125. package/src/runners/agent/utils.ts +0 -98
  126. package/src/runners/generate/run.ts +0 -276
  127. package/src/runners/generate/utils.ts +0 -209
  128. package/src/runners/init/run.ts +0 -211
  129. package/src/runners/init/utils.ts +0 -33
  130. package/src/runners/mcp/run.ts +0 -55
  131. package/src/runners/validate/run.ts +0 -63
  132. package/src/telemetry.ts +0 -280
  133. /package/dist/{chunk-ByKO4r7w.cjs → rolldown-runtime-Bx3C2hgW.cjs} +0 -0
@@ -1,252 +0,0 @@
1
- import path from 'node:path'
2
- import { styleText } from 'node:util'
3
- import { canUseTTY, formatHrtime, isGitHubActions, randomCliColor } from '@internals/utils'
4
- import type { Config, Logger, LoggerContext, LoggerOptions, Plugin } from '@kubb/core'
5
- import { logLevel as logLevelMap } from '@kubb/core'
6
- import { SUMMARY_MAX_BAR_LENGTH, SUMMARY_TIME_SCALE_DIVISOR } from '../constants.ts'
7
- import { clackLogger } from './clackLogger.ts'
8
- import { fileSystemLogger } from './fileSystemLogger.ts'
9
- import { githubActionsLogger } from './githubActionsLogger.ts'
10
- import { plainLogger } from './plainLogger.ts'
11
- import type { LoggerType } from './types.ts'
12
-
13
- /**
14
- * Output sink for a hook subprocess, controlling how streamed lines and exit output are forwarded.
15
- */
16
- type HookOutputSink = {
17
- /**
18
- * Called for each streamed stdout line while the hook runs.
19
- */
20
- onLine?: (line: string) => void
21
- /**
22
- * Called with stderr content after the hook exits with a non-zero code.
23
- */
24
- onStderr?: (text: string) => void
25
- /**
26
- * Called with stdout content after the hook exits with a non-zero code.
27
- */
28
- onStdout?: (text: string) => void
29
- }
30
-
31
- /**
32
- * Output sink combined with stream control for a hook subprocess.
33
- */
34
- export type HookSinkOptions = HookOutputSink & {
35
- /**
36
- * When `true`, streams process output line-by-line via `onLine`.
37
- *
38
- * @default false
39
- */
40
- stream?: boolean
41
- }
42
-
43
- /**
44
- * Factory called once per hook command to build the output sink and streaming flag.
45
- * The function should set up any logger UI (e.g., spinner) and return callbacks that forward subprocess output to it.
46
- */
47
- export type HookSinkFactory = (commandWithArgs: string) => HookSinkOptions | undefined
48
-
49
- /**
50
- * Logger variant that may return a {@link HookSinkFactory} from `install`.
51
- * The factory is forwarded to hook execution so the logger controls subprocess output routing.
52
- */
53
- type CLILogger = Logger<LoggerOptions, HookSinkFactory | void>
54
-
55
- /**
56
- * Optionally prefix a message with a [HH:MM:SS] timestamp when logLevel >= verbose.
57
- * Shared across all logger adapters to avoid duplication.
58
- */
59
- export function formatMessage(message: string, logLevel: number): string {
60
- if (logLevel >= logLevelMap.verbose) {
61
- const timestamp = new Date().toLocaleTimeString('en-US', {
62
- hour12: false,
63
- hour: '2-digit',
64
- minute: '2-digit',
65
- second: '2-digit',
66
- })
67
- return `${styleText('dim', `[${timestamp}]`)} ${message}`
68
- }
69
- return message
70
- }
71
-
72
- type ProgressState = {
73
- /**
74
- * Total number of plugins scheduled for this generation run.
75
- */
76
- totalPlugins: number
77
- /**
78
- * Number of plugins that have finished without error.
79
- */
80
- completedPlugins: number
81
- /**
82
- * Number of plugins that exited with an error.
83
- */
84
- failedPlugins: number
85
- /**
86
- * Total number of files expected to be written.
87
- */
88
- totalFiles: number
89
- /**
90
- * Number of files written so far.
91
- */
92
- processedFiles: number
93
- /**
94
- * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
95
- */
96
- hrStart: [number, number]
97
- }
98
-
99
- /**
100
- * Build the progress summary line shared by clack and GitHub Actions loggers.
101
- * Returns null when there is nothing to display.
102
- */
103
- export function buildProgressLine(state: ProgressState): string | null {
104
- const parts: string[] = []
105
- const duration = formatHrtime(state.hrStart)
106
-
107
- if (state.totalPlugins > 0) {
108
- const pluginStr =
109
- state.failedPlugins > 0
110
- ? `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins} ${styleText('red', `(${state.failedPlugins} failed)`)}`
111
- : `Plugins ${styleText('green', state.completedPlugins.toString())}/${state.totalPlugins}`
112
- parts.push(pluginStr)
113
- }
114
-
115
- if (state.totalFiles > 0) {
116
- parts.push(`Files ${styleText('green', state.processedFiles.toString())}/${state.totalFiles}`)
117
- }
118
-
119
- if (parts.length === 0) {
120
- return null
121
- }
122
-
123
- parts.push(`${styleText('green', duration)} elapsed`)
124
- return parts.join(styleText('dim', ' | '))
125
- }
126
-
127
- /**
128
- * Join a command and its optional args into a single display string.
129
- * e.g. ("prettier", ["--write", "."]) → "prettier --write ."
130
- */
131
- export function formatCommandWithArgs(command: string, args?: readonly string[]): string {
132
- return args?.length ? `${command} ${args.join(' ')}` : command
133
- }
134
-
135
- function detectLogger(): LoggerType {
136
- if (isGitHubActions()) {
137
- return 'github-actions'
138
- }
139
- if (canUseTTY()) {
140
- return 'clack'
141
- }
142
- return 'plain'
143
- }
144
-
145
- const logMapper: Record<LoggerType, CLILogger> = {
146
- clack: clackLogger,
147
- plain: plainLogger,
148
- 'github-actions': githubActionsLogger,
149
- }
150
-
151
- export async function setupLogger(context: LoggerContext, { logLevel }: LoggerOptions): Promise<HookSinkFactory | undefined> {
152
- const type = detectLogger()
153
-
154
- const logger = logMapper[type]
155
-
156
- if (!logger) {
157
- throw new Error(`Unknown adapter type: ${type}`)
158
- }
159
-
160
- const makeSink = await logger.install(context, { logLevel })
161
-
162
- if (logLevel >= logLevelMap.debug) {
163
- await fileSystemLogger.install(context, { logLevel })
164
- }
165
-
166
- return typeof makeSink === 'function' ? makeSink : undefined
167
- }
168
-
169
- type SummaryProps = {
170
- /**
171
- * Set of plugins that failed during this generation run, each with its error.
172
- */
173
- failedPlugins: Set<{ plugin: Plugin; error: Error }>
174
- /**
175
- * Overall generation status used to choose success or failure formatting.
176
- */
177
- status: 'success' | 'failed'
178
- /**
179
- * `process.hrtime()` snapshot taken at the start of generation, used to compute elapsed time.
180
- */
181
- hrStart: [number, number]
182
- /**
183
- * Total number of files written during this generation run.
184
- */
185
- filesCreated: number
186
- /**
187
- * Resolved Kubb config for this generation entry, used to read plugin count and output path.
188
- */
189
- config: Config
190
- /**
191
- * Per-plugin timing map (plugin name → duration in ms). When provided, a timing bar chart is appended.
192
- */
193
- pluginTimings?: Map<string, number>
194
- }
195
-
196
- /**
197
- * Builds the generation summary lines rendered in the end-of-run box.
198
- * Returns an array of styled strings, one per summary row.
199
- */
200
- export function getSummary({ failedPlugins, filesCreated, status, hrStart, config, pluginTimings }: SummaryProps): string[] {
201
- const duration = formatHrtime(hrStart)
202
-
203
- const pluginsCount = config.plugins?.length ?? 0
204
- const successCount = pluginsCount - failedPlugins.size
205
-
206
- const meta = {
207
- plugins:
208
- status === 'success'
209
- ? `${styleText('green', `${successCount} successful`)}, ${pluginsCount} total`
210
- : `${styleText('green', `${successCount} successful`)}, ${styleText('red', `${failedPlugins.size} failed`)}, ${pluginsCount} total`,
211
- pluginsFailed: status === 'failed' ? [...failedPlugins].map(({ plugin }) => randomCliColor(plugin.name)).join(', ') : undefined,
212
- filesCreated,
213
- time: styleText('green', duration),
214
- output: path.resolve(config.root, config.output.path),
215
- } as const
216
-
217
- const labels = {
218
- plugins: 'Plugins:',
219
- failed: 'Failed:',
220
- generated: 'Generated:',
221
- pluginTimings: 'Plugin Timings:',
222
- output: 'Output:',
223
- }
224
- const maxLength = Math.max(0, ...[...Object.values(labels), ...(pluginTimings ? Array.from(pluginTimings.keys()) : [])].map((s) => s.length))
225
-
226
- const summaryLines: string[] = []
227
- summaryLines.push(`${labels.plugins.padEnd(maxLength + 2)} ${meta.plugins}`)
228
-
229
- if (meta.pluginsFailed) {
230
- summaryLines.push(`${labels.failed.padEnd(maxLength + 2)} ${meta.pluginsFailed}`)
231
- }
232
-
233
- summaryLines.push(`${labels.generated.padEnd(maxLength + 2)} ${meta.filesCreated} files in ${meta.time}`)
234
-
235
- if (pluginTimings && pluginTimings.size > 0) {
236
- const sortedTimings = Array.from(pluginTimings.entries()).sort((a, b) => b[1] - a[1])
237
-
238
- summaryLines.push(`${labels.pluginTimings}`)
239
-
240
- sortedTimings.forEach(([name, time]) => {
241
- const timeStr = time >= 1000 ? `${(time / 1000).toFixed(2)}s` : `${Math.round(time)}ms`
242
- const barLength = Math.min(Math.ceil(time / SUMMARY_TIME_SCALE_DIVISOR), SUMMARY_MAX_BAR_LENGTH)
243
- const bar = styleText('dim', '█'.repeat(barLength))
244
-
245
- summaryLines.push(`${styleText('dim', '•')} ${name.padEnd(maxLength + 1)}${bar} ${timeStr}`)
246
- })
247
- }
248
-
249
- summaryLines.push(`${labels.output.padEnd(maxLength + 2)} ${meta.output}`)
250
-
251
- return summaryLines
252
- }
@@ -1,113 +0,0 @@
1
- import { createRequire } from 'node:module'
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 { spawnAsync, getErrorMessage } from '@internals/utils'
7
- import { agentDefaults } from '../../constants.ts'
8
- import { buildTelemetryEvent, sendTelemetry } from '../../telemetry.ts'
9
- import { isPortAvailable, resolveAgentStartEnvironment } from './utils.ts'
10
-
11
- type AgentStartOptions = {
12
- /**
13
- * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
14
- */
15
- port: string | undefined
16
- /**
17
- * Hostname the HTTP server binds to.
18
- *
19
- * @default 'localhost'
20
- */
21
- host: string
22
- /**
23
- * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
24
- */
25
- configPath: string | undefined
26
- /**
27
- * Grants the agent permission to write generated files to the filesystem.
28
- */
29
- allowWrite: boolean
30
- /**
31
- * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
32
- */
33
- allowAll: boolean
34
- /**
35
- * Current `@kubb/cli` version string, used for the telemetry payload.
36
- */
37
- version: string
38
- }
39
-
40
- /**
41
- * Spawns the Kubb Agent HTTP server as a Node.js subprocess.
42
- * Resolves config from CLI flags and environment variables, validates the port, and exits with code 1 on failure.
43
- */
44
- export async function run({ port, host, configPath, allowWrite, allowAll, version }: AgentStartOptions): Promise<void> {
45
- const hrStart = process.hrtime()
46
- const report = (status: 'success' | 'failed') => sendTelemetry(buildTelemetryEvent({ command: 'agent', kubbVersion: version, hrStart, status }))
47
-
48
- try {
49
- // Load .env file into process.env using Node.js built-in (v20.12.0+)
50
- try {
51
- process.loadEnvFile()
52
- } catch {
53
- // .env file may not exist; ignore
54
- }
55
-
56
- // Resolve the @kubb/agent package path — createRequire is CJS/ESM compatible (import.meta.resolve is ESM-only)
57
- const require = createRequire(import.meta.url)
58
- let agentPkgPath: string
59
- try {
60
- agentPkgPath = require.resolve('@kubb/agent/package.json')
61
- } catch (_e) {
62
- console.error(styleText('red', 'The @kubb/agent package is not installed.'))
63
- console.error('')
64
- console.error('Install it with:')
65
- console.error(styleText('cyan', ' npm install @kubb/agent'))
66
- console.error(styleText('cyan', ' # or'))
67
- console.error(styleText('cyan', ' pnpm install @kubb/agent'))
68
- console.error('')
69
- process.exit(1)
70
- }
71
- const agentDir = path.dirname(agentPkgPath)
72
- const serverPath = path.join(agentDir, agentDefaults.serverEntryPath)
73
-
74
- const resolvedEnv = resolveAgentStartEnvironment({
75
- port,
76
- host,
77
- configPath,
78
- allowWrite,
79
- allowAll,
80
- })
81
- const numericPort = Number(resolvedEnv.port)
82
-
83
- if (!Number.isInteger(numericPort) || numericPort <= 0) {
84
- throw new Error(`Invalid port "${resolvedEnv.port}". Provide a positive integer with --port or PORT.`)
85
- }
86
-
87
- clack.log.step(styleText('cyan', 'Starting agent server...'))
88
- clack.log.info(styleText('dim', `Config: ${resolvedEnv.agentConfigPath}`))
89
- clack.log.info(styleText('dim', `Host: ${resolvedEnv.host}`))
90
- clack.log.info(styleText('dim', `Port: ${resolvedEnv.port}`))
91
- if (!resolvedEnv.allowWrite && !resolvedEnv.allowAll) {
92
- clack.log.warn(styleText('yellow', 'Filesystem writes disabled. Use --allow-write or --allow-all to enable.'))
93
- }
94
-
95
- if (!(await isPortAvailable(numericPort, resolvedEnv.host))) {
96
- clack.log.error(styleText('red', `Port ${resolvedEnv.port} is already in use. Stop the existing process or choose a different port with --port.`))
97
- process.exit(1)
98
- }
99
-
100
- // Spawns the server as a detached background process so the CLI can exit independently.
101
- await spawnAsync('node', [serverPath], {
102
- env: resolvedEnv.env,
103
- cwd: process.cwd(),
104
- })
105
-
106
- await report('success')
107
- } catch (error) {
108
- await report('failed')
109
- clack.log.error(styleText('red', 'Failed to start agent server'))
110
- clack.log.error(getErrorMessage(error))
111
- process.exit(1)
112
- }
113
- }
@@ -1,98 +0,0 @@
1
- import net from 'node:net'
2
- import path from 'node:path'
3
- import process from 'node:process'
4
- import { agentDefaults } from '../../constants.ts'
5
-
6
- type AgentStartEnvironmentInput = {
7
- /**
8
- * TCP port for the HTTP server. When `undefined`, falls back to `PORT` env var or the default (`3000`).
9
- */
10
- port: string | undefined
11
- /**
12
- * Hostname the HTTP server binds to.
13
- */
14
- host: string
15
- /**
16
- * Explicit path to the Kubb config file. When `undefined`, falls back to `KUBB_AGENT_CONFIG` or the default filename.
17
- */
18
- configPath: string | undefined
19
- /**
20
- * Grants the agent permission to write generated files to the filesystem.
21
- */
22
- allowWrite: boolean
23
- /**
24
- * Grants all agent permissions, including filesystem writes. Implies `allowWrite`.
25
- */
26
- allowAll: boolean
27
- }
28
-
29
- type ResolvedAgentStartEnvironment = {
30
- /**
31
- * Final port string after merging CLI flag, `PORT` env var, and the default.
32
- */
33
- port: string
34
- /**
35
- * Final hostname after merging CLI flag, `HOST` env var, and the default.
36
- */
37
- host: string
38
- /**
39
- * Effective write-permission flag, accounting for `allowAll` and `KUBB_AGENT_ALLOW_WRITE`.
40
- */
41
- allowWrite: boolean
42
- /**
43
- * Effective all-permissions flag, accounting for `KUBB_AGENT_ALLOW_ALL`.
44
- */
45
- allowAll: boolean
46
- /**
47
- * Absolute path to the Kubb config file passed to the agent subprocess.
48
- */
49
- agentConfigPath: string
50
- /**
51
- * Merged `process.env` object with all resolved agent environment variables applied.
52
- */
53
- env: NodeJS.ProcessEnv
54
- }
55
-
56
- /**
57
- * Resolves the environment passed to the detached agent process using CLI values first, then environment values, then CLI defaults.
58
- */
59
- export function resolveAgentStartEnvironment({ port, host, configPath, allowWrite, allowAll }: AgentStartEnvironmentInput): ResolvedAgentStartEnvironment {
60
- const resolvedPort = port ?? process.env.PORT ?? agentDefaults.port
61
- const resolvedHost = host !== agentDefaults.host ? host : (process.env.HOST ?? agentDefaults.host)
62
- const resolvedAllowAll = allowAll || process.env.KUBB_AGENT_ALLOW_ALL === 'true'
63
- const resolvedAllowWrite = resolvedAllowAll || allowWrite || process.env.KUBB_AGENT_ALLOW_WRITE === 'true'
64
- const agentRoot = process.env.KUBB_AGENT_ROOT ?? process.cwd()
65
- const agentConfigPath = path.resolve(process.cwd(), configPath || process.env.KUBB_AGENT_CONFIG || agentDefaults.configFile)
66
-
67
- return {
68
- port: resolvedPort,
69
- host: resolvedHost,
70
- allowWrite: resolvedAllowWrite,
71
- allowAll: resolvedAllowAll,
72
- agentConfigPath,
73
- env: {
74
- ...process.env,
75
- PORT: resolvedPort,
76
- HOST: resolvedHost,
77
- KUBB_AGENT_ROOT: agentRoot,
78
- KUBB_AGENT_CONFIG: agentConfigPath,
79
- KUBB_AGENT_ALLOW_WRITE: String(resolvedAllowWrite),
80
- KUBB_AGENT_ALLOW_ALL: String(resolvedAllowAll),
81
- KUBB_AGENT_TOKEN: process.env.KUBB_AGENT_TOKEN,
82
- KUBB_AGENT_RETRY_TIMEOUT: process.env.KUBB_AGENT_RETRY_TIMEOUT ?? agentDefaults.retryTimeout,
83
- KUBB_STUDIO_URL: process.env.KUBB_STUDIO_URL ?? agentDefaults.studioUrl,
84
- },
85
- }
86
- }
87
-
88
- export function isPortAvailable(port: number, host: string): Promise<boolean> {
89
- return new Promise((resolve) => {
90
- const server = net.createServer()
91
- server.once('error', () => resolve(false))
92
- server.once('listening', () => {
93
- server.close()
94
- resolve(true)
95
- })
96
- server.listen(port, host)
97
- })
98
- }