@nocobase/cli 2.1.0-alpha.20 → 2.1.0-alpha.21

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.
@@ -9,142 +9,342 @@
9
9
  import { Command, Flags } from '@oclif/core';
10
10
  import * as p from '@clack/prompts';
11
11
  import pc from 'picocolors';
12
+ import { existsSync } from 'node:fs';
13
+ import path from 'node:path';
12
14
  import { stdin as stdinStream, stdout as stdoutStream } from 'node:process';
13
- import { buildEnvAddArgv, InitWizardCancelledError, runInitBrowserWizard, } from "../lib/init-browser-wizard.js";
15
+ import { getEnv, upsertEnv } from "../lib/auth-store.js";
16
+ import { runPromptCatalog, } from "../lib/prompt-catalog.js";
17
+ import { runPromptCatalogWebUI, } from "../lib/prompt-web-ui.js";
18
+ import { validateApiBaseUrl, validateEnvKey } from "../lib/prompt-validators.js";
14
19
  import { run } from "../lib/run-npm.js";
20
+ import Download from "./download.js";
21
+ import EnvAdd from "./env/add.js";
22
+ import Install, { defaultDbPortForDialect } from "./install.js";
23
+ import _ from 'lodash';
24
+ const DEFAULT_INIT_API_BASE_URL = 'http://localhost:13000/api';
25
+ const DEFAULT_INIT_APP_NAME = 'local';
26
+ const DOWNLOAD_OUTPUT_DIR_PROMPT = Download.prompts.outputDir;
27
+ const CONFIG_SCOPE = 'project';
28
+ function withExtraHidden(def, extraHidden) {
29
+ if (def.type === 'run') {
30
+ return def;
31
+ }
32
+ return {
33
+ ...def,
34
+ hidden: (values) => extraHidden(values) || (def.hidden?.(values) ?? false),
35
+ };
36
+ }
37
+ function existingAppOnly(def) {
38
+ return withExtraHidden(def, (values) => values.hasNocobase !== 'yes');
39
+ }
40
+ function newInstallOnly(def) {
41
+ return withExtraHidden(def, (values) => values.hasNocobase !== 'no');
42
+ }
43
+ function downloadInNewInstallOnly(def) {
44
+ return withExtraHidden(def, (values) => values.hasNocobase !== 'no' || values.fetchSource !== true);
45
+ }
46
+ function argvHasToken(argv, tokens) {
47
+ return tokens.some((token) => argv.includes(token));
48
+ }
49
+ function shouldAllowExistingInitEnv() {
50
+ return argvHasToken(process.argv.slice(2), ['--force', '-f']);
51
+ }
52
+ async function validateInitAppName(value) {
53
+ const formatError = validateEnvKey(value);
54
+ if (formatError) {
55
+ return formatError;
56
+ }
57
+ const envName = String(value ?? '').trim();
58
+ if (!envName) {
59
+ return undefined;
60
+ }
61
+ const existingEnv = await getEnv(envName, { scope: 'project' });
62
+ if (existingEnv) {
63
+ if (shouldAllowExistingInitEnv()) {
64
+ return undefined;
65
+ }
66
+ return `Env "${envName}" already exists in this workspace. Choose another app name.`;
67
+ }
68
+ return undefined;
69
+ }
70
+ function highlightInitValidationMessage(message) {
71
+ return message.replace(/Env "([^"]+)"/, (_match, envName) => `Env ${pc.cyan(pc.bold(`"${envName}"`))}`);
72
+ }
73
+ function formatInitValidationMessage(message) {
74
+ if (/"appName" is required/.test(message)) {
75
+ return [
76
+ 'App name is required when prompts are skipped.',
77
+ 'The app name is also the CLI env name. Use `nb init --yes --env <envName>` to continue.',
78
+ ].join('\n');
79
+ }
80
+ return message;
81
+ }
82
+ function formatResumeEnvRequiredMessage() {
83
+ return [
84
+ 'Env name is required when resuming setup.',
85
+ 'App name is also the CLI env name. Use `nb init --resume --env <envName>` to continue.',
86
+ ].join('\n');
87
+ }
15
88
  export default class Init extends Command {
16
- static summary = 'Initialize the NocoBase AI setup environment';
17
- static description = `Initialize the current workspace for NocoBase CLI and agent workflows. You only run nb init; the following runs inside this command (not as separate manual steps):
89
+ static summary = 'Set up NocoBase so coding agents can connect and work with it';
90
+ static description = `Set up NocoBase for coding agents in the current workspace.
18
91
 
19
- 1. Optionally install NocoBase agent skills (\`npx -y skills add nocobase/skills\`)—you are prompted when using a TTY.
20
- 2. If you already have a NocoBase application (anywhere): runs \`nb env add\` only (\`nb install\` is skipped).
21
- 3. If not: runs \`nb install\` only (\`nb env add\` is not run afterward; configure the CLI with \`nb env add\` when you need it).
92
+ \`nb init\` prepares a NocoBase environment that coding agents can use. It supports two setup paths:
22
93
 
23
- Internal ordering: (skills?) (already have an app? env add | install only).
94
+ - Connect an existing NocoBase app and save it as a CLI env.
95
+ - Install a new NocoBase app, then save it as a CLI env.
24
96
 
25
- Use \`-y\` / \`--yes\` to skip init prompts (defaults: install skills, then \`nb install\` only—same as choosing the first option, no existing app). When you choose an existing app in a TTY, \`nb env add\` may still prompt for URL and auth.
97
+ It can also install NocoBase AI coding skills (\`nocobase/skills\`) so agents get the project-specific workflow guidance.
26
98
 
27
- Use \`--ui\` to open a **browser** wizard (local HTTP server; default bind \`0.0.0.0\`, random port). Use \`--ui-host\` / \`--ui-port\` to override. The opened URL uses \`127.0.0.1\` when the bind address is all-interfaces. It can collect \`nb env add\` fields when you link an existing app, so the terminal env wizard is skipped. Cannot be combined with \`--yes\`.`;
99
+ If setup was interrupted earlier, use \`--resume\` with an existing env name to continue from the saved workspace config.
100
+
101
+ Prompt modes:
102
+ - Default: guided prompts in the terminal.
103
+ - \`--ui\`: open the same setup flow in a local browser form.
104
+ - \`-y\`, \`--yes\`: skip prompts. In this mode \`--env <envName>\` is required, and init creates a new local NocoBase app with safe defaults.
105
+
106
+ \`--ui\` cannot be combined with \`--yes\`.`;
28
107
  static examples = [
29
108
  '<%= config.bin %> <%= command.id %>',
109
+ '<%= config.bin %> <%= command.id %> --env app1',
110
+ '<%= config.bin %> <%= command.id %> --env app1 --ui',
30
111
  '<%= config.bin %> <%= command.id %> --ui',
31
- '<%= config.bin %> <%= command.id %> --ui --ui-host 127.0.0.1 --ui-port 3000',
32
- '<%= config.bin %> <%= command.id %> -y',
112
+ '<%= config.bin %> <%= command.id %> --env app1 --yes',
113
+ '<%= config.bin %> <%= command.id %> --env app1 --resume',
114
+ '<%= config.bin %> <%= command.id %> --env app1 --yes --source docker --version alpha',
115
+ '<%= config.bin %> <%= command.id %> --env app1 --yes --source npm --version alpha --app-port 13080',
116
+ '<%= config.bin %> <%= command.id %> --env app1 --yes --source git --version fix/cli-v2',
117
+ '<%= config.bin %> <%= command.id %> --ui --ui-port 3000',
33
118
  ];
119
+ static prompts = {
120
+ appName: {
121
+ type: 'text',
122
+ message: 'App name (also used as the CLI env name)',
123
+ placeholder: DEFAULT_INIT_APP_NAME,
124
+ required: true,
125
+ validate: validateInitAppName,
126
+ },
127
+ hasNocobase: {
128
+ type: 'select',
129
+ variant: 'radio',
130
+ message: 'Do you already have a NocoBase application?',
131
+ options: [
132
+ {
133
+ value: 'no',
134
+ label: "I don't have a NocoBase application yet",
135
+ },
136
+ {
137
+ value: 'yes',
138
+ label: 'I already have a NocoBase application',
139
+ },
140
+ ],
141
+ initialValue: 'no',
142
+ yesInitialValue: 'no',
143
+ required: true,
144
+ },
145
+ installSkills: {
146
+ type: 'boolean',
147
+ message: 'Install NocoBase AI coding skills (nocobase/skills)?',
148
+ initialValue: true,
149
+ yesInitialValue: true,
150
+ },
151
+ apiBaseUrl: existingAppOnly({
152
+ type: 'text',
153
+ message: 'API base URL',
154
+ placeholder: DEFAULT_INIT_API_BASE_URL,
155
+ required: true,
156
+ validate: validateApiBaseUrl,
157
+ }),
158
+ authType: existingAppOnly(EnvAdd.prompts.authType),
159
+ accessToken: existingAppOnly(EnvAdd.prompts.accessToken),
160
+ lang: newInstallOnly(Install.appPrompts.lang),
161
+ appRootPath: newInstallOnly(Install.appPrompts.appRootPath),
162
+ appPort: newInstallOnly(Install.appPrompts.appPort),
163
+ storagePath: newInstallOnly(Install.appPrompts.storagePath),
164
+ fetchSource: newInstallOnly(Install.appPrompts.fetchSource),
165
+ source: downloadInNewInstallOnly(Download.prompts.source),
166
+ version: downloadInNewInstallOnly(Download.prompts.version),
167
+ dockerRegistry: downloadInNewInstallOnly(Download.prompts.dockerRegistry),
168
+ dockerPlatform: downloadInNewInstallOnly(Download.prompts.dockerPlatform),
169
+ dockerSave: downloadInNewInstallOnly(Download.prompts.dockerSave),
170
+ gitUrl: downloadInNewInstallOnly(Download.prompts.gitUrl),
171
+ outputDir: downloadInNewInstallOnly({
172
+ ...DOWNLOAD_OUTPUT_DIR_PROMPT,
173
+ hidden: (values) => {
174
+ const source = String(values.source ?? '').trim();
175
+ if (source === 'npm' || source === 'git') {
176
+ return true;
177
+ }
178
+ return DOWNLOAD_OUTPUT_DIR_PROMPT.hidden?.(values) ?? false;
179
+ },
180
+ initialValue: (values) => {
181
+ const source = String(values.source ?? '').trim();
182
+ if (source === 'npm' || source === 'git') {
183
+ const appRootPath = String(values.appRootPath ?? '').trim();
184
+ if (appRootPath) {
185
+ return appRootPath;
186
+ }
187
+ }
188
+ const initialValue = DOWNLOAD_OUTPUT_DIR_PROMPT.initialValue;
189
+ return typeof initialValue === 'function' ? initialValue(values) : String(initialValue ?? '');
190
+ },
191
+ }),
192
+ npmRegistry: downloadInNewInstallOnly(Download.prompts.npmRegistry),
193
+ replace: downloadInNewInstallOnly(Download.prompts.replace),
194
+ devDependencies: downloadInNewInstallOnly(Download.prompts.devDependencies),
195
+ build: downloadInNewInstallOnly(Download.prompts.build),
196
+ buildDts: downloadInNewInstallOnly(Download.prompts.buildDts),
197
+ builtinDb: newInstallOnly(Install.dbPrompts.builtinDb),
198
+ dbDialect: newInstallOnly(Install.dbPrompts.dbDialect),
199
+ dbHost: newInstallOnly(Install.dbPrompts.dbHost),
200
+ dbPort: newInstallOnly(Install.dbPrompts.dbPort),
201
+ dbDatabase: newInstallOnly(Install.dbPrompts.dbDatabase),
202
+ dbUser: newInstallOnly(Install.dbPrompts.dbUser),
203
+ dbPassword: newInstallOnly(Install.dbPrompts.dbPassword),
204
+ rootUsername: newInstallOnly(Install.rootUserPrompts.rootUsername),
205
+ rootEmail: newInstallOnly(Install.rootUserPrompts.rootEmail),
206
+ rootPassword: newInstallOnly(Install.rootUserPrompts.rootPassword),
207
+ rootNickname: newInstallOnly(Install.rootUserPrompts.rootNickname),
208
+ };
34
209
  static flags = {
35
210
  yes: Flags.boolean({
36
211
  char: 'y',
37
- description: 'Skip all prompts',
212
+ description: 'Skip prompts and create a new local NocoBase app. Requires an app/env name.',
213
+ default: false,
214
+ }),
215
+ env: Flags.string({
216
+ char: 'e',
217
+ description: 'App name / CLI env name for this setup. Required with --yes and --resume',
218
+ }),
219
+ 'install-skills': Flags.boolean({
220
+ description: 'Install NocoBase AI coding skills (`nocobase/skills`) for this workspace',
38
221
  default: false,
39
222
  }),
40
223
  ui: Flags.boolean({
41
- description: 'Open a browser-based setup wizard (local HTTP server; not valid with --yes)',
224
+ description: 'Open the guided setup flow in a local browser form (not valid with --yes)',
42
225
  default: false,
43
226
  }),
44
227
  'ui-host': Flags.string({
45
- description: 'Bind address for the --ui wizard HTTP server (default 0.0.0.0; only with --ui)',
228
+ description: 'Host for the local --ui setup server (default: 127.0.0.1)',
46
229
  }),
47
230
  'ui-port': Flags.integer({
48
- description: 'TCP port for the --ui wizard; 0 = OS-assigned ephemeral port (default 0; only with --ui)',
231
+ description: 'Port for the local --ui setup server; 0 lets the OS choose an available port',
49
232
  min: 0,
50
233
  max: 65535,
51
234
  }),
235
+ ..._.omit(Install.flags, ['yes', 'env']),
52
236
  };
53
237
  async run() {
54
- const { flags } = await this.parse(Init);
55
- if (flags.ui && flags.yes) {
238
+ const parsedResult = await this.parse(Init);
239
+ const flags = parsedResult.flags;
240
+ const normalizedFlags = { ...flags };
241
+ if (normalizedFlags.ui && normalizedFlags.yes) {
56
242
  this.error('--ui cannot be used with --yes.');
57
243
  }
58
- if (!flags.ui &&
59
- (flags['ui-host'] !== undefined || flags['ui-port'] !== undefined)) {
244
+ if (normalizedFlags.ui && normalizedFlags.resume) {
245
+ this.error('--ui cannot be used with --resume.');
246
+ }
247
+ if (!normalizedFlags.ui &&
248
+ (normalizedFlags['ui-host'] !== undefined || normalizedFlags['ui-port'] !== undefined)) {
60
249
  this.error('--ui-host and --ui-port require --ui.');
61
250
  }
62
- const interactive = Boolean(stdinStream.isTTY && stdoutStream.isTTY);
63
- const useBrowserUi = Boolean(flags.ui);
64
- if (useBrowserUi) {
65
- if (interactive) {
66
- p.intro(`${pc.bold('nb init')} ${pc.dim('— browser wizard')}`);
251
+ if (normalizedFlags.resume) {
252
+ const envName = String(normalizedFlags.env ?? '').trim();
253
+ if (!envName) {
254
+ p.log.error(formatResumeEnvRequiredMessage());
255
+ this.exit(1);
67
256
  }
68
- else {
69
- this.log('nb init — browser wizard');
257
+ p.intro('Set Up NocoBase for Coding Agents');
258
+ if (Boolean(normalizedFlags['install-skills'])) {
259
+ try {
260
+ p.log.step('Installing NocoBase agent skills (npx -y skills add nocobase/skills)');
261
+ await run('npx', ['-y', 'skills', 'add', 'nocobase/skills', '-y']);
262
+ }
263
+ catch (error) {
264
+ const message = error instanceof Error ? error.message : String(error);
265
+ p.outro(pc.red(`Skills install failed: ${message}`));
266
+ this.error(message);
267
+ }
70
268
  }
71
- this.log('Your browser should open; complete the form there to continue.');
72
- }
73
- else {
74
- p.intro('Initialize the NocoBase AI setup environment');
75
- }
76
- /** Whether `nb install` / follow-up should avoid terminal prompts (`-y`). */
77
- const skipInstallPrompts = Boolean(flags.yes) || !interactive;
78
- let installSkills = true;
79
- let hasNocobase = false;
80
- /** When set, \`nb env add\` is invoked with these argv (from \`--ui\` form). */
81
- let envAddArgvFromUi;
82
- if (flags.yes) {
83
- p.log.info('Skipping prompts (--yes): will install NocoBase agent skills.');
84
- installSkills = true;
85
- hasNocobase = false;
86
- p.log.info('Skipping prompts (--yes): will run nb install only (same default as "I don\'t have a NocoBase application yet").');
87
- }
88
- else if (useBrowserUi) {
89
269
  try {
90
- const choice = await runInitBrowserWizard((line) => this.log(line), {
91
- bindHost: flags['ui-host']?.trim() || '0.0.0.0',
92
- port: flags['ui-port'] ?? 0,
93
- });
94
- installSkills = choice.installSkills;
95
- hasNocobase = choice.hasNocobase;
96
- if (choice.envAdd) {
97
- envAddArgvFromUi = buildEnvAddArgv(choice.envAdd);
98
- }
270
+ p.log.step(`Resuming setup for env "${envName}" from the saved workspace config`);
271
+ await this.config.runCommand('install', this.buildResumeInstallArgv(normalizedFlags));
99
272
  }
100
273
  catch (error) {
101
- if (error instanceof InitWizardCancelledError) {
102
- if (interactive) {
103
- p.cancel(error.message);
104
- }
105
- else {
106
- this.log(error.message);
107
- }
108
- this.exit(0);
109
- }
110
- throw error;
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ p.outro(pc.red(message));
276
+ this.error(message);
111
277
  }
278
+ p.outro('Workspace init finished.');
279
+ return;
112
280
  }
113
- else if (interactive) {
114
- const skillsAnswer = await p.confirm({
115
- message: 'Install NocoBase agent skills (nocobase/skills) for Cursor / Codex workflows?',
116
- initialValue: true,
117
- });
118
- if (p.isCancel(skillsAnswer)) {
119
- p.cancel('Init cancelled.');
120
- this.exit(0);
121
- }
122
- installSkills = skillsAnswer;
123
- const answer = await p.select({
124
- message: 'Do you already have a NocoBase application?',
125
- options: [
126
- {
127
- value: 'no',
128
- label: "I don't have a NocoBase application yet",
129
- },
130
- {
131
- value: 'yes',
132
- label: 'I already have a NocoBase application',
133
- },
134
- ],
135
- initialValue: 'no',
136
- });
137
- if (p.isCancel(answer)) {
138
- p.cancel('Init cancelled.');
139
- this.exit(0);
140
- }
141
- hasNocobase = answer === 'yes';
281
+ const interactive = Boolean(stdinStream.isTTY && stdoutStream.isTTY);
282
+ const useBrowserUi = Boolean(normalizedFlags.ui);
283
+ let presetValues = this.buildPresetValuesFromFlags(normalizedFlags);
284
+ if (normalizedFlags.yes && !String(presetValues.appName ?? '').trim()) {
285
+ const formatted = formatInitValidationMessage('Non-interactive: "appName" is required; set initialValues.appName, yesInitialValues.appName, yesInitialValue on the block, or initialValue.');
286
+ p.log.error(highlightInitValidationMessage(formatted));
287
+ this.exit(1);
288
+ }
289
+ const appName = String(presetValues.appName ?? '').trim();
290
+ if (useBrowserUi) {
291
+ p.intro('Set Up NocoBase for Coding Agents');
292
+ p.log.info('A local setup form will open in your browser. Submit the form there to continue in this terminal.');
142
293
  }
143
294
  else {
144
- p.log.warn('Non-interactive terminal: will install NocoBase agent skills (skip is not available without a TTY).');
145
- installSkills = true;
146
- hasNocobase = false;
147
- p.log.warn('Non-interactive terminal: assuming you do not already have a NocoBase app (will run nb install only).');
295
+ p.intro('Set Up NocoBase for Coding Agents');
296
+ if (normalizedFlags.yes) {
297
+ p.log.info(`Prompts skipped (--yes). NocoBase will be installed for env "${appName}" using the provided flags and safe defaults.`);
298
+ }
299
+ else if (!interactive) {
300
+ p.log.warn('No interactive terminal detected. NocoBase will be installed using the provided flags and safe defaults.');
301
+ }
302
+ }
303
+ const dynamicInitialValues = await Init.buildDynamicInitialValuesForInstall(normalizedFlags, presetValues);
304
+ if (useBrowserUi) {
305
+ presetValues = await runPromptCatalogWebUI({
306
+ stages: Init.buildWebUiStages(),
307
+ values: {
308
+ ...dynamicInitialValues,
309
+ ...presetValues,
310
+ },
311
+ host: normalizedFlags['ui-host']?.trim() || '127.0.0.1',
312
+ port: normalizedFlags['ui-port'] ?? 0,
313
+ pageTitle: 'Set Up NocoBase for Coding Agents',
314
+ documentHeading: 'Set Up NocoBase for Coding Agents',
315
+ documentHint: 'Connect an existing NocoBase app or install a new one, then save it as an agent-ready CLI environment.',
316
+ onServerStart: ({ host, port, url }) => {
317
+ this.log(`Local setup form ready at ${url} (listening on ${host}:${port}). Submit it in your browser to continue here.`);
318
+ },
319
+ onOpenBrowserError: (url, err) => {
320
+ this.log(`Open this URL in your browser to continue setup: ${url} (${err instanceof Error ? err.message : String(err)})`);
321
+ },
322
+ });
323
+ }
324
+ const results = await runPromptCatalog(Init.prompts, {
325
+ initialValues: dynamicInitialValues,
326
+ values: presetValues,
327
+ yes: normalizedFlags.yes || useBrowserUi || !interactive,
328
+ hooks: {
329
+ onCancel: () => {
330
+ p.cancel('Init cancelled.');
331
+ this.exit(0);
332
+ },
333
+ onMissingNonInteractive: (message) => {
334
+ const formatted = formatInitValidationMessage(message);
335
+ p.log.error(highlightInitValidationMessage(formatted));
336
+ this.exit(1);
337
+ },
338
+ },
339
+ command: this,
340
+ });
341
+ const installSkills = Boolean(results.installSkills);
342
+ const hasNocobase = results.hasNocobase === 'yes';
343
+ const existingEnv = !hasNocobase
344
+ ? await getEnv(String(results.appName ?? '').trim(), { scope: 'project' })
345
+ : undefined;
346
+ if (existingEnv && Boolean(normalizedFlags.force)) {
347
+ p.log.warn(`Reconfiguring existing env ${pc.cyan(pc.bold(`"${existingEnv.name}"`))} in this workspace because ${pc.bold('--force')} was set. The env config will be updated before install starts, then refreshed again after install succeeds.`);
148
348
  }
149
349
  if (installSkills) {
150
350
  try {
@@ -164,16 +364,13 @@ Use \`--ui\` to open a **browser** wizard (local HTTP server; default bind \`0.0
164
364
  // oclif explicit registry keys use `:` (e.g. `env:add`); users still type `nb env add`.
165
365
  if (hasNocobase) {
166
366
  p.log.step('Running nb env add');
167
- if (useBrowserUi && !envAddArgvFromUi) {
168
- this.error('Browser wizard did not supply env add options.');
169
- }
170
- const envArgv = envAddArgvFromUi ??
171
- (interactive ? ['--scope', 'project'] : ['default', '--scope', 'project']);
172
- await this.config.runCommand('env:add', envArgv);
367
+ await this.config.runCommand('env:add', this.buildEnvAddArgv(results));
173
368
  }
174
369
  else {
370
+ p.log.step('Saving the local env config');
371
+ await this.persistManagedEnvConfig(results);
175
372
  p.log.step('Running nb install');
176
- await this.config.runCommand('install', skipInstallPrompts ? ['-e', 'local', '-y'] : []);
373
+ await this.config.runCommand('install', this.buildInstallArgv(results, normalizedFlags));
177
374
  }
178
375
  }
179
376
  catch (error) {
@@ -183,4 +380,400 @@ Use \`--ui\` to open a **browser** wizard (local HTTP server; default bind \`0.0
183
380
  }
184
381
  p.outro('Workspace init finished.');
185
382
  }
383
+ static async buildDynamicInitialValuesForInstall(flags, presetValues) {
384
+ const out = {};
385
+ if (!Object.prototype.hasOwnProperty.call(presetValues, 'appPort')) {
386
+ const appInitialValues = await Install.buildAppPromptInitialValues({
387
+ envName: String(presetValues.appName ?? '').trim(),
388
+ flags: {
389
+ ...flags,
390
+ 'app-root-path': flags['app-root-path'] ?? '',
391
+ 'storage-path': flags['storage-path'] ?? '',
392
+ },
393
+ });
394
+ if (appInitialValues.appPort !== undefined) {
395
+ out.appPort = appInitialValues.appPort;
396
+ }
397
+ }
398
+ const downloadSeed = { ...presetValues };
399
+ if (flags.yes
400
+ && !Object.prototype.hasOwnProperty.call(downloadSeed, 'source')
401
+ && downloadSeed.fetchSource !== false) {
402
+ downloadSeed.source = 'docker';
403
+ }
404
+ const dbInitial = await Install.buildDbPromptInitialValues({
405
+ flags,
406
+ downloadResults: downloadSeed,
407
+ dbPreset: presetValues,
408
+ });
409
+ for (const [key, value] of Object.entries(dbInitial)) {
410
+ if (!Object.prototype.hasOwnProperty.call(presetValues, key)) {
411
+ out[key] = value;
412
+ }
413
+ }
414
+ return out;
415
+ }
416
+ static buildWebUiStages() {
417
+ const c = Init.prompts;
418
+ return [
419
+ {
420
+ sectionTitle: 'Getting started',
421
+ sectionDescription: 'Pick your setup path.',
422
+ catalog: {
423
+ appName: c.appName,
424
+ hasNocobase: c.hasNocobase,
425
+ installSkills: c.installSkills,
426
+ },
427
+ },
428
+ {
429
+ sectionTitle: 'Connect an existing app',
430
+ sectionDescription: 'Add your app connection.',
431
+ catalog: {
432
+ apiBaseUrl: c.apiBaseUrl,
433
+ authType: c.authType,
434
+ accessToken: c.accessToken,
435
+ },
436
+ },
437
+ {
438
+ sectionTitle: 'Create a new app',
439
+ sectionDescription: 'Set project basics.',
440
+ catalog: {
441
+ lang: c.lang,
442
+ appRootPath: c.appRootPath,
443
+ appPort: c.appPort,
444
+ storagePath: c.storagePath,
445
+ fetchSource: c.fetchSource,
446
+ },
447
+ },
448
+ {
449
+ sectionTitle: 'Download app files',
450
+ sectionDescription: 'Choose source and options.',
451
+ catalog: {
452
+ source: c.source,
453
+ version: c.version,
454
+ dockerRegistry: c.dockerRegistry,
455
+ dockerPlatform: c.dockerPlatform,
456
+ dockerSave: c.dockerSave,
457
+ gitUrl: c.gitUrl,
458
+ outputDir: c.outputDir,
459
+ npmRegistry: c.npmRegistry,
460
+ replace: c.replace,
461
+ devDependencies: c.devDependencies,
462
+ build: c.build,
463
+ buildDts: c.buildDts,
464
+ },
465
+ },
466
+ {
467
+ sectionTitle: 'Configure the database',
468
+ sectionDescription: 'Use built-in or custom.',
469
+ catalog: {
470
+ builtinDb: c.builtinDb,
471
+ dbDialect: c.dbDialect,
472
+ dbHost: c.dbHost,
473
+ dbPort: c.dbPort,
474
+ dbDatabase: c.dbDatabase,
475
+ dbUser: c.dbUser,
476
+ dbPassword: c.dbPassword,
477
+ },
478
+ },
479
+ {
480
+ sectionTitle: 'Create an admin account',
481
+ sectionDescription: 'Set up the first admin.',
482
+ catalog: {
483
+ rootUsername: c.rootUsername,
484
+ rootEmail: c.rootEmail,
485
+ rootPassword: c.rootPassword,
486
+ rootNickname: c.rootNickname,
487
+ },
488
+ },
489
+ ];
490
+ }
491
+ buildPresetValuesFromFlags(flags) {
492
+ const preset = {};
493
+ const argv = process.argv.slice(2);
494
+ if (flags.env !== undefined && String(flags.env).trim() !== '') {
495
+ preset.appName = String(flags.env).trim();
496
+ }
497
+ if (flags.lang !== undefined && String(flags.lang).trim() !== '') {
498
+ preset.lang = String(flags.lang).trim();
499
+ }
500
+ if (flags['app-root-path'] !== undefined && String(flags['app-root-path']).trim() !== '') {
501
+ preset.appRootPath = String(flags['app-root-path']).trim();
502
+ }
503
+ if (flags['app-port'] !== undefined && String(flags['app-port']).trim() !== '') {
504
+ preset.appPort = String(flags['app-port']).trim();
505
+ }
506
+ if (flags['storage-path'] !== undefined && String(flags['storage-path']).trim() !== '') {
507
+ preset.storagePath = String(flags['storage-path']).trim();
508
+ }
509
+ if (flags['root-username'] !== undefined) {
510
+ preset.rootUsername = String(flags['root-username'] ?? '').trim();
511
+ }
512
+ if (flags['root-email'] !== undefined) {
513
+ preset.rootEmail = String(flags['root-email'] ?? '').trim();
514
+ }
515
+ if (flags['root-password'] !== undefined) {
516
+ preset.rootPassword = String(flags['root-password'] ?? '');
517
+ }
518
+ if (flags['root-nickname'] !== undefined) {
519
+ preset.rootNickname = String(flags['root-nickname'] ?? '').trim();
520
+ }
521
+ if (flags['db-dialect'] !== undefined && String(flags['db-dialect']).trim() !== '') {
522
+ preset.dbDialect = String(flags['db-dialect']).trim();
523
+ }
524
+ if (flags['db-host'] !== undefined && String(flags['db-host']).trim() !== '') {
525
+ preset.dbHost = String(flags['db-host']).trim();
526
+ }
527
+ if (flags['db-port'] !== undefined && String(flags['db-port']).trim() !== '') {
528
+ preset.dbPort = String(flags['db-port']).trim();
529
+ }
530
+ if (flags['db-database'] !== undefined && String(flags['db-database']).trim() !== '') {
531
+ preset.dbDatabase = String(flags['db-database']).trim();
532
+ }
533
+ if (flags['db-user'] !== undefined && String(flags['db-user']).trim() !== '') {
534
+ preset.dbUser = String(flags['db-user']).trim();
535
+ }
536
+ if (flags['db-password'] !== undefined) {
537
+ preset.dbPassword = String(flags['db-password'] ?? '');
538
+ }
539
+ if (argvHasToken(argv, ['--fetch-source'])) {
540
+ preset.fetchSource = Boolean(flags['fetch-source']);
541
+ }
542
+ if (flags.source !== undefined && String(flags.source).trim() !== '') {
543
+ preset.source = String(flags.source).trim();
544
+ }
545
+ if (flags.version !== undefined) {
546
+ preset.version = String(flags.version).trim() || 'latest';
547
+ }
548
+ if (flags['docker-registry'] !== undefined && String(flags['docker-registry']).trim() !== '') {
549
+ preset.dockerRegistry = String(flags['docker-registry']).trim();
550
+ }
551
+ if (flags['docker-platform'] !== undefined && String(flags['docker-platform']).trim() !== '') {
552
+ preset.dockerPlatform = String(flags['docker-platform']).trim();
553
+ }
554
+ if (flags['output-dir'] !== undefined && String(flags['output-dir']).trim() !== '') {
555
+ preset.outputDir = String(flags['output-dir']).trim();
556
+ }
557
+ if (flags['git-url'] !== undefined && String(flags['git-url']).trim() !== '') {
558
+ preset.gitUrl = String(flags['git-url']).trim();
559
+ }
560
+ if (flags['npm-registry'] !== undefined) {
561
+ preset.npmRegistry = String(flags['npm-registry'] ?? '');
562
+ }
563
+ if (argvHasToken(argv, ['--replace', '-r'])) {
564
+ preset.replace = Boolean(flags.replace);
565
+ }
566
+ if (argvHasToken(argv, ['--dev-dependencies', '--no-dev-dependencies', '-D'])) {
567
+ preset.devDependencies = Boolean(flags['dev-dependencies']);
568
+ }
569
+ if (argvHasToken(argv, ['--docker-save', '--no-docker-save'])) {
570
+ preset.dockerSave = Boolean(flags['docker-save']);
571
+ }
572
+ if (argvHasToken(argv, ['--build', '--no-build'])) {
573
+ preset.build = Boolean(flags.build);
574
+ }
575
+ if (argvHasToken(argv, ['--build-dts', '--no-build-dts'])) {
576
+ preset.buildDts = Boolean(flags['build-dts']);
577
+ }
578
+ if (argvHasToken(argv, ['--builtin-db'])) {
579
+ preset.builtinDb = Boolean(flags['builtin-db']);
580
+ }
581
+ if (argvHasToken(argv, ['--install-skills'])) {
582
+ preset.installSkills = Boolean(flags['install-skills']);
583
+ }
584
+ else if (this.hasAgentsDirInCwd()) {
585
+ preset.installSkills = false;
586
+ }
587
+ return preset;
588
+ }
589
+ hasAgentsDirInCwd() {
590
+ return existsSync(path.resolve(process.cwd(), '.agents'));
591
+ }
592
+ async persistManagedEnvConfig(results) {
593
+ const envName = String(results.appName ?? DEFAULT_INIT_APP_NAME).trim() || DEFAULT_INIT_APP_NAME;
594
+ const appPort = String(results.appPort ?? '').trim();
595
+ const source = String(results.source ?? '').trim();
596
+ const version = String(results.version ?? '').trim();
597
+ const dockerRegistry = String(results.dockerRegistry ?? '').trim();
598
+ const dockerPlatform = String(results.dockerPlatform ?? '').trim();
599
+ const gitUrl = String(results.gitUrl ?? '').trim();
600
+ const npmRegistry = String(results.npmRegistry ?? '').trim();
601
+ const appRootPath = String(results.appRootPath ?? '').trim();
602
+ const storagePath = String(results.storagePath ?? '').trim();
603
+ const dbDialect = String(results.dbDialect ?? '').trim();
604
+ const dbHost = String(results.dbHost ?? '').trim();
605
+ const dbPort = String(results.dbPort ?? '').trim();
606
+ const dbDatabase = String(results.dbDatabase ?? '').trim();
607
+ const dbUser = String(results.dbUser ?? '').trim();
608
+ const dbPassword = String(results.dbPassword ?? '');
609
+ await upsertEnv(envName, {
610
+ ...(appPort ? { baseUrl: `http://127.0.0.1:${appPort}/api` } : {}),
611
+ ...(source ? { source } : {}),
612
+ ...(version ? { downloadVersion: version } : {}),
613
+ ...(dockerRegistry ? { dockerRegistry } : {}),
614
+ ...(dockerPlatform ? { dockerPlatform } : {}),
615
+ ...(gitUrl ? { gitUrl } : {}),
616
+ ...(npmRegistry ? { npmRegistry } : {}),
617
+ ...(appRootPath ? { appRootPath } : {}),
618
+ ...(storagePath ? { storagePath } : {}),
619
+ ...(appPort ? { appPort } : {}),
620
+ ...(results.devDependencies !== undefined ? { devDependencies: Boolean(results.devDependencies) } : {}),
621
+ ...(results.build !== undefined ? { build: Boolean(results.build) } : {}),
622
+ ...(results.buildDts !== undefined ? { buildDts: Boolean(results.buildDts) } : {}),
623
+ ...(results.builtinDb !== undefined ? { builtinDb: Boolean(results.builtinDb) } : {}),
624
+ ...(dbDialect ? { dbDialect } : {}),
625
+ ...(dbHost ? { dbHost } : {}),
626
+ ...(dbPort ? { dbPort } : {}),
627
+ ...(dbDatabase ? { dbDatabase } : {}),
628
+ ...(dbUser ? { dbUser } : {}),
629
+ ...(dbPassword ? { dbPassword } : {}),
630
+ }, { scope: CONFIG_SCOPE });
631
+ }
632
+ buildEnvAddArgv(results) {
633
+ const argv = [String(results.appName ?? DEFAULT_INIT_APP_NAME)];
634
+ argv.push('--no-intro');
635
+ argv.push('--scope', CONFIG_SCOPE);
636
+ argv.push('--api-base-url', String(results.apiBaseUrl ?? DEFAULT_INIT_API_BASE_URL));
637
+ argv.push('--auth-type', String(results.authType ?? 'oauth'));
638
+ if (results.authType === 'token') {
639
+ argv.push('--access-token', String(results.accessToken ?? ''));
640
+ }
641
+ return argv;
642
+ }
643
+ buildInstallArgv(results, flags, options) {
644
+ const argv = ['--no-intro'];
645
+ if (options?.nonInteractive ?? true) {
646
+ argv.unshift('-y');
647
+ }
648
+ const processArgv = process.argv.slice(2);
649
+ const envName = String(results.appName ?? DEFAULT_INIT_APP_NAME).trim() || DEFAULT_INIT_APP_NAME;
650
+ const source = String(results.source ?? '').trim();
651
+ argv.push('--env', envName);
652
+ if (options?.resume) {
653
+ argv.push('--resume');
654
+ }
655
+ const lang = String(results.lang ?? '').trim();
656
+ if (lang) {
657
+ argv.push('--lang', lang);
658
+ }
659
+ const appRootPath = String(results.appRootPath ?? '').trim();
660
+ if (appRootPath) {
661
+ argv.push('--app-root-path', appRootPath);
662
+ }
663
+ const appPort = String(results.appPort ?? '').trim();
664
+ if (appPort && (!flags.yes || argvHasToken(processArgv, ['--app-port']) || appPort !== '13000')) {
665
+ argv.push('--app-port', appPort);
666
+ }
667
+ const storagePath = String(results.storagePath ?? '').trim();
668
+ if (storagePath) {
669
+ argv.push('--storage-path', storagePath);
670
+ }
671
+ if (Boolean(flags.force)) {
672
+ argv.push('--force');
673
+ }
674
+ if (Boolean(results.fetchSource)) {
675
+ argv.push('--fetch-source');
676
+ if (source) {
677
+ argv.push('--source', source);
678
+ }
679
+ const version = String(results.version ?? '').trim();
680
+ if (version) {
681
+ argv.push('--version', version);
682
+ }
683
+ const outputDir = String(results.outputDir ?? '').trim();
684
+ if (outputDir) {
685
+ argv.push('--output-dir', outputDir);
686
+ }
687
+ const gitUrl = String(results.gitUrl ?? '').trim();
688
+ if (gitUrl) {
689
+ argv.push('--git-url', gitUrl);
690
+ }
691
+ const dockerRegistry = String(results.dockerRegistry ?? '').trim();
692
+ if (dockerRegistry) {
693
+ argv.push('--docker-registry', dockerRegistry);
694
+ }
695
+ const dockerPlatform = String(results.dockerPlatform ?? '').trim();
696
+ if (dockerPlatform) {
697
+ argv.push('--docker-platform', dockerPlatform);
698
+ }
699
+ const npmRegistry = String(results.npmRegistry ?? '').trim();
700
+ if (npmRegistry) {
701
+ argv.push('--npm-registry', npmRegistry);
702
+ }
703
+ if (Boolean(results.replace)) {
704
+ argv.push('--replace');
705
+ }
706
+ if (Boolean(results.devDependencies)) {
707
+ argv.push('--dev-dependencies');
708
+ }
709
+ if (Boolean(results.dockerSave)) {
710
+ argv.push('--docker-save');
711
+ }
712
+ if (results.build !== undefined && !Boolean(results.build)) {
713
+ argv.push('--no-build');
714
+ }
715
+ else if (argvHasToken(processArgv, ['--build', '--no-build']) && flags.build === false) {
716
+ argv.push('--no-build');
717
+ }
718
+ if (Boolean(results.buildDts)) {
719
+ argv.push('--build-dts');
720
+ }
721
+ }
722
+ const builtinDb = Boolean(results.builtinDb);
723
+ if (builtinDb) {
724
+ argv.push('--builtin-db');
725
+ }
726
+ const dbDialect = String(results.dbDialect ?? '').trim();
727
+ if (dbDialect) {
728
+ argv.push('--db-dialect', dbDialect);
729
+ }
730
+ const dbHost = String(results.dbHost ?? '').trim();
731
+ if (dbHost) {
732
+ argv.push('--db-host', dbHost);
733
+ }
734
+ const dbPort = String(results.dbPort ?? '').trim();
735
+ const dbPortWasProvided = argvHasToken(processArgv, ['--db-port']);
736
+ const dockerBuiltinDbPortIsHidden = builtinDb && source === 'docker';
737
+ const dbDefaultPort = defaultDbPortForDialect(dbDialect);
738
+ if (dbPort
739
+ && (!dockerBuiltinDbPortIsHidden || dbPortWasProvided)
740
+ && (!flags.yes || dbPortWasProvided || dbPort !== dbDefaultPort)) {
741
+ argv.push('--db-port', dbPort);
742
+ }
743
+ const dbDatabase = String(results.dbDatabase ?? '').trim();
744
+ if (dbDatabase) {
745
+ argv.push('--db-database', dbDatabase);
746
+ }
747
+ const dbUser = String(results.dbUser ?? '').trim();
748
+ if (dbUser) {
749
+ argv.push('--db-user', dbUser);
750
+ }
751
+ const dbPassword = String(results.dbPassword ?? '');
752
+ if (dbPassword) {
753
+ argv.push('--db-password', dbPassword);
754
+ }
755
+ const rootUsername = String(results.rootUsername ?? '').trim();
756
+ if (rootUsername) {
757
+ argv.push('--root-username', rootUsername);
758
+ }
759
+ const rootEmail = String(results.rootEmail ?? '').trim();
760
+ if (rootEmail) {
761
+ argv.push('--root-email', rootEmail);
762
+ }
763
+ const rootPassword = String(results.rootPassword ?? '');
764
+ if (rootPassword) {
765
+ argv.push('--root-password', rootPassword);
766
+ }
767
+ const rootNickname = String(results.rootNickname ?? '').trim();
768
+ if (rootNickname) {
769
+ argv.push('--root-nickname', rootNickname);
770
+ }
771
+ return argv;
772
+ }
773
+ buildResumeInstallArgv(flags) {
774
+ return this.buildInstallArgv(this.buildPresetValuesFromFlags(flags), flags, {
775
+ nonInteractive: Boolean(flags.yes),
776
+ resume: true,
777
+ });
778
+ }
186
779
  }