@nocobase/cli 2.1.0-alpha.26 → 2.1.0-alpha.28

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 (52) hide show
  1. package/README.md +24 -0
  2. package/README.zh-CN.md +4 -0
  3. package/dist/commands/app/down.js +2 -3
  4. package/dist/commands/app/logs.js +2 -2
  5. package/dist/commands/app/upgrade.js +114 -128
  6. package/dist/commands/config/delete.js +30 -0
  7. package/dist/commands/config/get.js +29 -0
  8. package/dist/commands/config/index.js +20 -0
  9. package/dist/commands/config/list.js +29 -0
  10. package/dist/commands/config/set.js +35 -0
  11. package/dist/commands/db/check.js +238 -0
  12. package/dist/commands/db/logs.js +2 -2
  13. package/dist/commands/db/shared.js +6 -5
  14. package/dist/commands/env/info.js +6 -2
  15. package/dist/commands/env/shared.js +1 -1
  16. package/dist/commands/init.js +0 -1
  17. package/dist/commands/install.js +87 -35
  18. package/dist/commands/license/activate.js +357 -0
  19. package/dist/commands/license/env.js +94 -0
  20. package/dist/commands/license/generate-id.js +107 -0
  21. package/dist/commands/license/id.js +52 -0
  22. package/dist/commands/license/index.js +20 -0
  23. package/dist/commands/license/plugins/clean.js +98 -0
  24. package/dist/commands/license/plugins/index.js +20 -0
  25. package/dist/commands/license/plugins/list.js +50 -0
  26. package/dist/commands/license/plugins/shared.js +325 -0
  27. package/dist/commands/license/plugins/sync.js +267 -0
  28. package/dist/commands/license/shared.js +414 -0
  29. package/dist/commands/license/status.js +50 -0
  30. package/dist/lib/api-client.js +74 -3
  31. package/dist/lib/app-managed-resources.js +10 -6
  32. package/dist/lib/app-runtime.js +29 -11
  33. package/dist/lib/auth-store.js +36 -68
  34. package/dist/lib/build-config.js +8 -0
  35. package/dist/lib/builtin-db.js +86 -0
  36. package/dist/lib/cli-config.js +176 -0
  37. package/dist/lib/cli-home.js +6 -21
  38. package/dist/lib/db-connection-check.js +178 -0
  39. package/dist/lib/env-config.js +7 -0
  40. package/dist/lib/generated-command.js +23 -3
  41. package/dist/lib/plugin-storage.js +127 -0
  42. package/dist/lib/prompt-validators.js +4 -4
  43. package/dist/lib/run-npm.js +53 -0
  44. package/dist/lib/runtime-env-vars.js +32 -0
  45. package/dist/lib/runtime-generator.js +89 -10
  46. package/dist/lib/self-manager.js +57 -2
  47. package/dist/lib/skills-manager.js +2 -2
  48. package/dist/lib/startup-update.js +85 -7
  49. package/dist/locale/en-US.json +16 -13
  50. package/dist/locale/zh-CN.json +16 -13
  51. package/nocobase-ctl.config.json +82 -0
  52. package/package.json +16 -4
@@ -0,0 +1,50 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import { Command, Flags } from '@oclif/core';
10
+ import { ensureInstanceId, licenseEnvFlag, licenseJsonFlag, requireLicenseRuntime } from './shared.js';
11
+ export default class LicenseStatus extends Command {
12
+ static summary = 'Show commercial license status for the selected env';
13
+ static description = 'Inspect the selected env and show the current commercial licensing status. Use `--doctor` for extra diagnostic checks once the license backend wiring is implemented.';
14
+ static examples = [
15
+ '<%= config.bin %> <%= command.id %>',
16
+ '<%= config.bin %> <%= command.id %> --env app1',
17
+ '<%= config.bin %> <%= command.id %> --env app1 --doctor',
18
+ '<%= config.bin %> <%= command.id %> --env app1 --json',
19
+ ];
20
+ static flags = {
21
+ env: licenseEnvFlag,
22
+ json: licenseJsonFlag,
23
+ doctor: Flags.boolean({
24
+ description: 'Run extra diagnostic checks and suggestions',
25
+ default: false,
26
+ }),
27
+ };
28
+ async run() {
29
+ const { flags } = await this.parse(LicenseStatus);
30
+ const runtime = await requireLicenseRuntime(flags.env);
31
+ const payload = {
32
+ ok: true,
33
+ env: runtime.envName,
34
+ kind: runtime.kind,
35
+ instanceId: await ensureInstanceId(runtime),
36
+ licensed: false,
37
+ doctor: Boolean(flags.doctor),
38
+ implemented: false,
39
+ message: 'Commercial license status is not implemented yet in the new CLI.',
40
+ };
41
+ if (flags.json) {
42
+ this.log(JSON.stringify(payload, null, 2));
43
+ return;
44
+ }
45
+ this.log(`License status for env "${runtime.envName}": not implemented yet`);
46
+ if (flags.doctor) {
47
+ this.log('Diagnostic checks for commercial licensing are not implemented yet in the new CLI.');
48
+ }
49
+ }
50
+ }
@@ -6,7 +6,19 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
+ /**
10
+ * This file is part of the NocoBase (R) project.
11
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
12
+ * Authors: NocoBase Team.
13
+ *
14
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
15
+ * For more information, please refer to: https://www.nocobase.com/agreement.
16
+ */
17
+ import { createWriteStream } from 'node:fs';
9
18
  import { promises as fs } from 'node:fs';
19
+ import { basename, dirname } from 'node:path';
20
+ import { Readable } from 'node:stream';
21
+ import { pipeline } from 'node:stream/promises';
10
22
  import { resolveServerRequestTarget } from './env-auth.js';
11
23
  import { fetchWithPreservedAuthRedirect } from './http-request.js';
12
24
  const CLI_REQUEST_SOURCE_HEADER = 'x-request-source';
@@ -43,6 +55,20 @@ async function parseResponse(response) {
43
55
  data,
44
56
  };
45
57
  }
58
+ async function parseBinaryResponse(response, outputPath) {
59
+ if (response.ok && response.body) {
60
+ await fs.mkdir(dirname(outputPath), { recursive: true }).catch(() => undefined);
61
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(outputPath));
62
+ return {
63
+ ok: response.ok,
64
+ status: response.status,
65
+ data: {
66
+ output: outputPath,
67
+ },
68
+ };
69
+ }
70
+ return parseResponse(response);
71
+ }
46
72
  function parseScalarValue(value, type) {
47
73
  if (value === undefined) {
48
74
  return undefined;
@@ -105,6 +131,9 @@ function parseBodyFieldValue(rawValue, parameter) {
105
131
  return parseScalarValue(rawValue, parameter.type);
106
132
  }
107
133
  export async function parseBody(flags, operation) {
134
+ if (operation.requestContentType === 'multipart/form-data') {
135
+ return undefined;
136
+ }
108
137
  const inlineBody = flags.body;
109
138
  const bodyFile = flags['body-file'];
110
139
  const bodyParameters = operation.parameters.filter((parameter) => parameter.in === 'body');
@@ -143,6 +172,39 @@ export async function parseBody(flags, operation) {
143
172
  }
144
173
  return undefined;
145
174
  }
175
+ async function createMultipartBody(flags, operation) {
176
+ const bodyParameters = operation.parameters.filter((parameter) => parameter.in === 'body');
177
+ const formData = new FormData();
178
+ let hasValues = false;
179
+ for (const parameter of bodyParameters) {
180
+ const rawValue = flags[parameter.flagName];
181
+ const hasValue = hasParameterValue(flags, parameter);
182
+ if (parameter.required && !hasValue) {
183
+ throw new Error(`Missing required body field --${parameter.flagName}`);
184
+ }
185
+ if (!hasValue) {
186
+ continue;
187
+ }
188
+ if (parameter.isFile) {
189
+ const filePath = String(rawValue);
190
+ const content = await fs.readFile(filePath);
191
+ const arrayBuffer = content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength);
192
+ formData.append(parameter.name, new Blob([arrayBuffer]), basename(filePath));
193
+ hasValues = true;
194
+ continue;
195
+ }
196
+ const value = parseBodyFieldValue(rawValue, parameter);
197
+ if (value === undefined) {
198
+ continue;
199
+ }
200
+ formData.append(parameter.name, typeof value === 'object' ? JSON.stringify(value) : String(value));
201
+ hasValues = true;
202
+ }
203
+ if (!hasValues && operation.bodyRequired) {
204
+ throw new Error('Missing multipart request body.');
205
+ }
206
+ return hasValues ? formData : undefined;
207
+ }
146
208
  export async function executeApiRequest(options) {
147
209
  const { baseUrl, token } = await resolveServerRequestTarget(options);
148
210
  const headers = new Headers();
@@ -190,8 +252,10 @@ export async function executeApiRequest(options) {
190
252
  continue;
191
253
  }
192
254
  }
193
- const body = await parseBody(options.flags, options.operation);
194
- if (body !== undefined) {
255
+ const body = options.operation.requestContentType === 'multipart/form-data'
256
+ ? await createMultipartBody(options.flags, options.operation)
257
+ : await parseBody(options.flags, options.operation);
258
+ if (body !== undefined && options.operation.requestContentType !== 'multipart/form-data') {
195
259
  headers.set('content-type', 'application/json');
196
260
  }
197
261
  const url = new URL(`${normalizeBaseUrl(baseUrl)}${requestPath}`);
@@ -199,8 +263,15 @@ export async function executeApiRequest(options) {
199
263
  const response = await fetchWithPreservedAuthRedirect(url.toString(), {
200
264
  method: options.operation.method.toUpperCase(),
201
265
  headers,
202
- body: body === undefined ? undefined : JSON.stringify(body),
266
+ body: body === undefined ? undefined : body instanceof FormData ? body : JSON.stringify(body),
203
267
  });
268
+ if (options.operation.responseType === 'binary') {
269
+ const outputPath = options.flags.output;
270
+ if (!outputPath) {
271
+ throw new Error('Missing required output path --output');
272
+ }
273
+ return parseBinaryResponse(response, outputPath);
274
+ }
204
275
  return parseResponse(response);
205
276
  }
206
277
  export async function executeRawApiRequest(options) {
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { mkdir, readdir } from 'node:fs/promises';
10
10
  import { dockerContainerExists, startDockerContainer } from './app-runtime.js';
11
+ import { deriveBuiltinDbConnection, resolveBuiltinDbConnection } from './builtin-db.js';
11
12
  import { resolveConfiguredEnvPath } from './cli-home.js';
12
13
  import { commandSucceeds, run } from './run-npm.js';
13
14
  import Install from '../commands/install.js';
@@ -92,9 +93,10 @@ export function buildSavedDockerRunArgs(runtime) {
92
93
  : trimValue(runtime.env.appPort);
93
94
  const appKey = trimValue(config.appKey);
94
95
  const timeZone = trimValue(config.timezone) || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
95
- const dbDialect = trimValue(config.dbDialect);
96
- const dbHost = trimValue(config.dbHost);
97
- const dbPort = trimValue(config.dbPort);
96
+ const builtinDbConnection = config.builtinDb ? deriveBuiltinDbConnection(runtime) : undefined;
97
+ const dbDialect = builtinDbConnection?.dbDialect || trimValue(config.dbDialect);
98
+ const dbHost = builtinDbConnection?.dbHost || trimValue(config.dbHost);
99
+ const dbPort = builtinDbConnection?.dbPort || trimValue(config.dbPort);
98
100
  const dbDatabase = trimValue(config.dbDatabase);
99
101
  const dbUser = trimValue(config.dbUser);
100
102
  const dbPassword = trimValue(config.dbPassword);
@@ -178,14 +180,16 @@ export async function ensureBuiltinDbReady(runtime, options) {
178
180
  if (!config.builtinDb) {
179
181
  return;
180
182
  }
183
+ const builtinDbConnection = await resolveBuiltinDbConnection(runtime);
181
184
  const plan = Install.buildBuiltinDbPlan({
182
185
  envName: runtime.envName,
183
186
  workspaceName: runtime.workspaceName,
187
+ dockerContainerPrefix: runtime.dockerContainerPrefix,
184
188
  storagePath: config.storagePath,
185
189
  source: runtime.source,
186
- dbDialect: config.dbDialect,
187
- dbHost: config.dbHost,
188
- dbPort: config.dbPort,
190
+ dbDialect: builtinDbConnection.dbDialect,
191
+ dbHost: builtinDbConnection.dbHost,
192
+ dbPort: builtinDbConnection.dbPort,
189
193
  dbDatabase: config.dbDatabase,
190
194
  dbUser: config.dbUser,
191
195
  dbPassword: config.dbPassword,
@@ -9,7 +9,9 @@
9
9
  import path from 'node:path';
10
10
  import { resolveEnvKind } from './auth-store.js';
11
11
  import { getEnv, loadAuthConfig } from './auth-store.js';
12
+ import { DEFAULT_DOCKER_CONTAINER_PREFIX, DEFAULT_DOCKER_NETWORK, getEffectiveCliConfigValue, } from './cli-config.js';
12
13
  import { commandOutput, commandSucceeds, run, runNocoBaseCommand } from './run-npm.js';
14
+ import { buildRuntimeEnvVars } from './runtime-env-vars.js';
13
15
  const DOCKER_APP_WORKDIR = '/app/nocobase';
14
16
  function sanitizeDockerResourceName(value) {
15
17
  const normalized = value
@@ -23,14 +25,24 @@ function sanitizeDockerResourceName(value) {
23
25
  export function defaultWorkspaceName(cwd = process.cwd()) {
24
26
  return sanitizeDockerResourceName(`nb-${path.basename(cwd)}`);
25
27
  }
26
- export function buildDockerAppContainerName(envName, workspaceName) {
27
- const workspace = workspaceName?.trim() || defaultWorkspaceName();
28
- return sanitizeDockerResourceName(`${workspace}-${envName}-app`);
28
+ export function defaultDockerContainerPrefix(cwd = process.cwd()) {
29
+ const configured = String(DEFAULT_DOCKER_CONTAINER_PREFIX ?? '').trim();
30
+ if (configured) {
31
+ return sanitizeDockerResourceName(configured);
32
+ }
33
+ return defaultWorkspaceName(cwd);
34
+ }
35
+ export function defaultDockerNetworkName() {
36
+ return sanitizeDockerResourceName(DEFAULT_DOCKER_NETWORK);
37
+ }
38
+ export function buildDockerAppContainerName(envName, containerPrefix) {
39
+ const prefix = containerPrefix?.trim() || defaultDockerContainerPrefix();
40
+ return sanitizeDockerResourceName(`${prefix}-${envName}-app`);
29
41
  }
30
- export function buildDockerDbContainerName(envName, dbDialect, workspaceName) {
31
- const workspace = workspaceName?.trim() || defaultWorkspaceName();
42
+ export function buildDockerDbContainerName(envName, dbDialect, containerPrefix) {
43
+ const prefix = containerPrefix?.trim() || defaultDockerContainerPrefix();
32
44
  const dialect = dbDialect.trim() || 'postgres';
33
- return sanitizeDockerResourceName(`${workspace}-${envName}-${dialect}`);
45
+ return sanitizeDockerResourceName(`${prefix}-${envName}-${dialect}`);
34
46
  }
35
47
  function normalizeEnvSource(env) {
36
48
  const source = String(env.config.source ?? '').trim();
@@ -51,7 +63,8 @@ export async function resolveManagedAppRuntime(envName) {
51
63
  }
52
64
  const resolvedName = env.name || envName?.trim() || config.currentEnv || 'default';
53
65
  const source = normalizeEnvSource(env);
54
- const workspaceName = config.name?.trim() || defaultWorkspaceName();
66
+ const dockerNetworkName = sanitizeDockerResourceName(getEffectiveCliConfigValue(config, 'docker.network') || defaultDockerNetworkName());
67
+ const dockerContainerPrefix = sanitizeDockerResourceName(getEffectiveCliConfigValue(config, 'docker.container-prefix') || defaultDockerContainerPrefix());
55
68
  const kind = env.kind ?? resolveEnvKind(env.config);
56
69
  if (kind === 'docker') {
57
70
  return {
@@ -59,8 +72,10 @@ export async function resolveManagedAppRuntime(envName) {
59
72
  env,
60
73
  envName: resolvedName,
61
74
  source: 'docker',
62
- workspaceName,
63
- containerName: buildDockerAppContainerName(resolvedName, workspaceName),
75
+ dockerNetworkName,
76
+ dockerContainerPrefix,
77
+ workspaceName: dockerNetworkName,
78
+ containerName: buildDockerAppContainerName(resolvedName, dockerContainerPrefix),
64
79
  };
65
80
  }
66
81
  if (kind === 'local') {
@@ -70,7 +85,9 @@ export async function resolveManagedAppRuntime(envName) {
70
85
  envName: resolvedName,
71
86
  source: source === 'git' ? 'git' : source === 'npm' ? 'npm' : 'local',
72
87
  projectRoot: env.appRootPath,
73
- workspaceName,
88
+ dockerNetworkName,
89
+ dockerContainerPrefix,
90
+ workspaceName: dockerNetworkName,
74
91
  };
75
92
  }
76
93
  if (kind === 'ssh') {
@@ -99,9 +116,10 @@ export function formatMissingManagedAppEnvMessage(envName) {
99
116
  return 'No NocoBase env is configured yet. Run `nb init` to create one first.';
100
117
  }
101
118
  export async function runLocalNocoBaseCommand(runtime, args, options) {
119
+ const envVars = await buildRuntimeEnvVars(runtime);
102
120
  await runNocoBaseCommand(args, {
103
121
  cwd: runtime.projectRoot,
104
- env: runtime.env.envVars,
122
+ env: envVars,
105
123
  stdio: options?.stdio,
106
124
  });
107
125
  }
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { promises as fs } from 'node:fs';
10
10
  import path from 'node:path';
11
- import { NB_CLI_ROOT_ENV, resolveCliHomeDir, resolveConfiguredEnvPath, resolveDefaultConfigScope, resolveEnvRelativePath, } from './cli-home.js';
11
+ import { resolveCliHomeDir, resolveConfiguredEnvPath, resolveEnvRelativePath, } from './cli-home.js';
12
12
  function normalizeStoredEnvKind(value) {
13
13
  const kind = String(value ?? '').trim();
14
14
  if (kind === 'remote') {
@@ -68,8 +68,22 @@ function normalizeEnvConfigEntry(entry) {
68
68
  };
69
69
  }
70
70
  function normalizeAuthConfig(config) {
71
+ const settings = config.settings ?? {};
71
72
  return {
72
73
  name: config.name || config.dockerResourcePrefix,
74
+ settings: {
75
+ ...(settings.license?.pkgUrl ? { license: { pkgUrl: normalizeOptionalString(settings.license.pkgUrl) } } : {}),
76
+ ...(settings.docker?.network || settings.docker?.containerPrefix
77
+ ? {
78
+ docker: {
79
+ ...(settings.docker?.network ? { network: normalizeOptionalString(settings.docker.network) } : {}),
80
+ ...(settings.docker?.containerPrefix
81
+ ? { containerPrefix: normalizeOptionalString(settings.docker.containerPrefix) }
82
+ : {}),
83
+ },
84
+ }
85
+ : {}),
86
+ },
73
87
  currentEnv: config.currentEnv || 'default',
74
88
  envs: Object.fromEntries(Object.entries(config.envs || {}).map(([envName, entry]) => [envName, normalizeEnvConfigEntry(entry) ?? {}])),
75
89
  };
@@ -83,48 +97,21 @@ function createDefaultConfig() {
83
97
  envs: {},
84
98
  };
85
99
  }
86
- function hasConfiguredEnvs(config) {
87
- return Object.keys(config.envs).length > 0;
88
- }
89
- function shouldFallbackToLegacyProjectScope(options = {}) {
90
- const requestedScope = options.scope ?? resolveDefaultConfigScope();
91
- if (requestedScope !== 'global') {
92
- return false;
93
- }
94
- return !process.env[NB_CLI_ROOT_ENV];
95
- }
96
- async function loadExactAuthConfig(options = {}) {
100
+ async function readStoredAuthConfig(filePath) {
97
101
  try {
98
- const content = await fs.readFile(getConfigFile(options), 'utf8');
102
+ const content = await fs.readFile(filePath, 'utf8');
99
103
  const parsed = JSON.parse(content);
100
104
  return normalizeAuthConfig(parsed);
101
105
  }
102
106
  catch (_error) {
103
- return createDefaultConfig();
107
+ return undefined;
104
108
  }
105
109
  }
106
- async function resolveEnvStorageScope(envName, options = {}) {
107
- const requestedScope = options.scope ?? resolveDefaultConfigScope();
108
- if (requestedScope !== 'global') {
109
- return { ...options, scope: requestedScope };
110
- }
111
- const globalConfig = await loadExactAuthConfig({ scope: 'global' });
112
- if (globalConfig.envs[envName]) {
113
- return { ...options, scope: 'global' };
114
- }
115
- const projectConfig = await loadExactAuthConfig({ scope: 'project' });
116
- if (projectConfig.envs[envName]) {
117
- return { ...options, scope: 'project' };
118
- }
119
- return { ...options, scope: 'global' };
110
+ export async function loadExactAuthConfig(options = {}) {
111
+ return (await readStoredAuthConfig(getConfigFile(options))) ?? createDefaultConfig();
120
112
  }
121
113
  export async function loadAuthConfig(options = {}) {
122
- const config = await loadExactAuthConfig(options);
123
- if (!shouldFallbackToLegacyProjectScope(options) || hasConfiguredEnvs(config)) {
124
- return config;
125
- }
126
- const legacyProjectConfig = await loadExactAuthConfig({ scope: 'project' });
127
- return hasConfiguredEnvs(legacyProjectConfig) ? legacyProjectConfig : config;
114
+ return await loadExactAuthConfig(options);
128
115
  }
129
116
  export async function saveAuthConfig(config, options = {}) {
130
117
  const filePath = getConfigFile(options);
@@ -143,24 +130,12 @@ export async function getCurrentEnvName(options = {}) {
143
130
  return config.currentEnv || 'default';
144
131
  }
145
132
  export async function setCurrentEnv(envName, options = {}) {
146
- const writeOptions = await resolveEnvStorageScope(envName, options);
147
- const config = await loadExactAuthConfig(writeOptions);
133
+ const config = await loadExactAuthConfig(options);
148
134
  if (!config.envs[envName]) {
149
135
  throw new Error(`Env "${envName}" is not configured`);
150
136
  }
151
137
  config.currentEnv = envName;
152
- await saveAuthConfig(config, writeOptions);
153
- }
154
- export async function ensureWorkspaceName(defaultName, options = {}) {
155
- const config = await loadExactAuthConfig(options);
156
- const existing = config.name?.trim();
157
- if (existing) {
158
- return existing;
159
- }
160
- const next = defaultName.trim();
161
- config.name = next;
162
138
  await saveAuthConfig(config, options);
163
- return next;
164
139
  }
165
140
  export class Env {
166
141
  config;
@@ -220,8 +195,13 @@ export class Env {
220
195
  put('APP_KEY', this.config.appKey);
221
196
  put('TZ', this.config.timezone);
222
197
  put('DB_DIALECT', this.config.dbDialect);
223
- put('DB_HOST', this.config.dbHost);
224
- put('DB_PORT', this.config.dbPort);
198
+ if (!this.config.builtinDb) {
199
+ put('DB_HOST', this.config.dbHost);
200
+ put('DB_PORT', this.config.dbPort);
201
+ }
202
+ else if (String(this.config.source ?? '').trim() !== 'docker') {
203
+ put('DB_PORT', this.config.dbPort);
204
+ }
225
205
  put('DB_DATABASE', this.config.dbDatabase);
226
206
  put('DB_USER', this.config.dbUser);
227
207
  put('DB_PASSWORD', this.config.dbPassword);
@@ -234,16 +214,7 @@ export async function getEnv(envName, options = {}) {
234
214
  const resolved = envName?.trim() || config.currentEnv || 'default';
235
215
  const envConfig = config.envs[resolved];
236
216
  if (!envConfig) {
237
- if (!shouldFallbackToLegacyProjectScope(loadOptions)) {
238
- return undefined;
239
- }
240
- const legacyProjectConfig = await loadExactAuthConfig({ scope: 'project' });
241
- const legacyResolved = envName?.trim() || legacyProjectConfig.currentEnv || 'default';
242
- const legacyEnvConfig = legacyProjectConfig.envs[legacyResolved];
243
- if (!legacyEnvConfig) {
244
- return undefined;
245
- }
246
- return new Env({ ...(normalizeEnvConfigEntry(legacyEnvConfig) ?? {}), name: legacyResolved });
217
+ return undefined;
247
218
  }
248
219
  return new Env({ ...(normalizeEnvConfigEntry(envConfig) ?? {}), name: resolved });
249
220
  }
@@ -269,12 +240,11 @@ function areAuthConfigsEquivalent(left, right) {
269
240
  return false;
270
241
  }
271
242
  async function writeEnv(envName, updater, options = {}) {
272
- const writeOptions = await resolveEnvStorageScope(envName, options);
273
- const config = await loadExactAuthConfig(writeOptions);
243
+ const config = await loadExactAuthConfig(options);
274
244
  const previous = config.envs[envName];
275
245
  config.envs[envName] = updater(previous);
276
246
  config.currentEnv = envName;
277
- await saveAuthConfig(config, writeOptions);
247
+ await saveAuthConfig(config, options);
278
248
  }
279
249
  export async function upsertEnv(envName, config, options = {}) {
280
250
  await writeEnv(envName, (previous) => {
@@ -330,19 +300,17 @@ export async function setEnvOauthSession(envName, auth, options = {}) {
330
300
  }), options);
331
301
  }
332
302
  export async function setEnvRuntime(envName, runtime, options = {}) {
333
- const writeOptions = await resolveEnvStorageScope(envName, options);
334
- const config = await loadExactAuthConfig(writeOptions);
303
+ const config = await loadExactAuthConfig(options);
335
304
  const current = config.envs[envName] ?? {};
336
305
  config.envs[envName] = {
337
306
  ...current,
338
307
  runtime,
339
308
  };
340
309
  config.currentEnv = envName;
341
- await saveAuthConfig(config, writeOptions);
310
+ await saveAuthConfig(config, options);
342
311
  }
343
312
  export async function removeEnv(envName, options = {}) {
344
- const writeOptions = await resolveEnvStorageScope(envName, options);
345
- const config = await loadExactAuthConfig(writeOptions);
313
+ const config = await loadExactAuthConfig(options);
346
314
  if (!config.envs[envName]) {
347
315
  throw new Error(`Env "${envName}" is not configured`);
348
316
  }
@@ -351,7 +319,7 @@ export async function removeEnv(envName, options = {}) {
351
319
  const nextEnv = Object.keys(config.envs).sort()[0];
352
320
  config.currentEnv = nextEnv ?? 'default';
353
321
  }
354
- await saveAuthConfig(config, writeOptions);
322
+ await saveAuthConfig(config, options);
355
323
  return {
356
324
  removed: envName,
357
325
  currentEnv: config.currentEnv || 'default',
@@ -1,3 +1,11 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
1
9
  import { promises as fs } from 'node:fs';
2
10
  export async function loadBuildConfig(filePath) {
3
11
  try {
@@ -0,0 +1,86 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+ import { buildDockerDbContainerName } from './app-runtime.js';
10
+ import { commandOutput } from './run-npm.js';
11
+ function trimValue(value) {
12
+ return String(value ?? '').trim();
13
+ }
14
+ export function defaultBuiltinDbPortForDialect(value) {
15
+ const dialect = trimValue(value) || 'postgres';
16
+ switch (dialect) {
17
+ case 'mysql':
18
+ case 'mariadb':
19
+ return '3306';
20
+ case 'kingbase':
21
+ return '54321';
22
+ case 'postgres':
23
+ default:
24
+ return '5432';
25
+ }
26
+ }
27
+ export function resolveBuiltinDbContainerName(runtime, dbDialect) {
28
+ const dialect = trimValue(dbDialect ?? runtime.env.config.dbDialect) || 'postgres';
29
+ return buildDockerDbContainerName(runtime.envName, dialect, runtime.dockerContainerPrefix || runtime.workspaceName);
30
+ }
31
+ export function deriveBuiltinDbConnection(runtime, overrides = {}) {
32
+ const dbDialect = trimValue(overrides.dbDialect ?? runtime.env.config.dbDialect) || 'postgres';
33
+ const containerName = resolveBuiltinDbContainerName(runtime, dbDialect);
34
+ const networkName = trimValue(runtime.dockerNetworkName || runtime.workspaceName) || undefined;
35
+ if (runtime.source === 'docker') {
36
+ return {
37
+ builtinDb: true,
38
+ dbDialect,
39
+ dbHost: containerName,
40
+ dbPort: defaultBuiltinDbPortForDialect(dbDialect),
41
+ containerName,
42
+ networkName,
43
+ };
44
+ }
45
+ const dbPort = trimValue(overrides.dbPort ?? runtime.env.config.dbPort) || defaultBuiltinDbPortForDialect(dbDialect);
46
+ return {
47
+ builtinDb: true,
48
+ dbDialect,
49
+ dbHost: '127.0.0.1',
50
+ dbPort,
51
+ containerName,
52
+ networkName,
53
+ };
54
+ }
55
+ export async function resolveBuiltinDbConnection(runtime) {
56
+ const derived = deriveBuiltinDbConnection(runtime);
57
+ if (runtime.source === 'docker') {
58
+ return derived;
59
+ }
60
+ const mappedPort = await inspectBuiltinDbPublishedPort(derived.containerName, derived.dbDialect);
61
+ if (mappedPort) {
62
+ return {
63
+ ...derived,
64
+ dbPort: mappedPort,
65
+ };
66
+ }
67
+ return derived;
68
+ }
69
+ async function inspectBuiltinDbPublishedPort(containerName, dbDialect) {
70
+ const containerPort = defaultBuiltinDbPortForDialect(dbDialect);
71
+ try {
72
+ const output = await commandOutput('docker', [
73
+ 'inspect',
74
+ '--format',
75
+ `{{with index .NetworkSettings.Ports "${containerPort}/tcp"}}{{(index . 0).HostPort}}{{end}}`,
76
+ containerName,
77
+ ], {
78
+ errorName: 'docker inspect',
79
+ });
80
+ const hostPort = trimValue(output);
81
+ return hostPort || undefined;
82
+ }
83
+ catch {
84
+ return undefined;
85
+ }
86
+ }