@nocobase/cli 2.1.0-alpha.26 → 2.1.0-alpha.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/README.zh-CN.md +4 -0
- package/dist/commands/app/down.js +2 -3
- package/dist/commands/app/upgrade.js +112 -128
- package/dist/commands/config/delete.js +30 -0
- package/dist/commands/config/get.js +29 -0
- package/dist/commands/config/index.js +20 -0
- package/dist/commands/config/list.js +29 -0
- package/dist/commands/config/set.js +35 -0
- package/dist/commands/db/check.js +230 -0
- package/dist/commands/db/shared.js +1 -1
- package/dist/commands/env/shared.js +1 -1
- package/dist/commands/init.js +0 -1
- package/dist/commands/install.js +87 -35
- package/dist/commands/license/activate.js +357 -0
- package/dist/commands/license/env.js +94 -0
- package/dist/commands/license/generate-id.js +107 -0
- package/dist/commands/license/id.js +52 -0
- package/dist/commands/license/index.js +20 -0
- package/dist/commands/license/plugins/clean.js +98 -0
- package/dist/commands/license/plugins/index.js +20 -0
- package/dist/commands/license/plugins/list.js +50 -0
- package/dist/commands/license/plugins/shared.js +325 -0
- package/dist/commands/license/plugins/sync.js +267 -0
- package/dist/commands/license/shared.js +411 -0
- package/dist/commands/license/status.js +50 -0
- package/dist/lib/api-client.js +74 -3
- package/dist/lib/app-runtime.js +26 -10
- package/dist/lib/auth-store.js +29 -66
- package/dist/lib/build-config.js +8 -0
- package/dist/lib/cli-config.js +176 -0
- package/dist/lib/cli-home.js +6 -21
- package/dist/lib/db-connection-check.js +178 -0
- package/dist/lib/generated-command.js +23 -3
- package/dist/lib/plugin-storage.js +127 -0
- package/dist/lib/prompt-validators.js +4 -4
- package/dist/lib/runtime-generator.js +89 -10
- package/dist/lib/self-manager.js +57 -2
- package/dist/lib/startup-update.js +85 -7
- package/dist/locale/en-US.json +16 -13
- package/dist/locale/zh-CN.json +16 -13
- package/nocobase-ctl.config.json +82 -0
- package/package.json +16 -4
|
@@ -0,0 +1,178 @@
|
|
|
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 { translateCli } from "./cli-locale.js";
|
|
10
|
+
import { validateTcpPort } from "./prompt-validators.js";
|
|
11
|
+
const DB_CONNECTION_TIMEOUT_MS = 5_000;
|
|
12
|
+
const externalDbValidationCache = new Map();
|
|
13
|
+
function trimPromptValue(value) {
|
|
14
|
+
return String(value ?? '').trim();
|
|
15
|
+
}
|
|
16
|
+
export function readExternalDbConnectionConfig(values) {
|
|
17
|
+
const builtinDb = values.builtinDb === undefined ? true : Boolean(values.builtinDb);
|
|
18
|
+
if (builtinDb) {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
const dialect = trimPromptValue(values.dbDialect || 'postgres');
|
|
22
|
+
if (dialect !== 'postgres' && dialect !== 'kingbase' && dialect !== 'mysql' && dialect !== 'mariadb') {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
const host = trimPromptValue(values.dbHost);
|
|
26
|
+
const portText = trimPromptValue(values.dbPort);
|
|
27
|
+
const database = trimPromptValue(values.dbDatabase);
|
|
28
|
+
const user = trimPromptValue(values.dbUser);
|
|
29
|
+
const password = String(values.dbPassword ?? '');
|
|
30
|
+
if (!host || !portText || !database || !user || !password) {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
if (validateTcpPort(portText)) {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
dialect,
|
|
38
|
+
host,
|
|
39
|
+
port: Number.parseInt(portText, 10),
|
|
40
|
+
database,
|
|
41
|
+
user,
|
|
42
|
+
password,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export function formatDbCheckAddress(config) {
|
|
46
|
+
return `${config.host}:${config.port}/${config.database}`;
|
|
47
|
+
}
|
|
48
|
+
function buildValidationCacheKey(config) {
|
|
49
|
+
return JSON.stringify(config);
|
|
50
|
+
}
|
|
51
|
+
function formatDbConnectionError(config, error) {
|
|
52
|
+
const maybeError = error;
|
|
53
|
+
const code = String(maybeError?.code ?? '').trim().toUpperCase();
|
|
54
|
+
const errno = typeof maybeError?.errno === 'number' ? maybeError.errno : undefined;
|
|
55
|
+
const rawMessage = String(maybeError?.message || maybeError?.sqlMessage || error || '').trim();
|
|
56
|
+
if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EHOSTUNREACH' || code === 'ECONNRESET') {
|
|
57
|
+
return translateCli('validators.dbConnection.unreachable', {
|
|
58
|
+
host: config.host,
|
|
59
|
+
port: config.port,
|
|
60
|
+
details: rawMessage,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (code === 'ETIMEDOUT') {
|
|
64
|
+
return translateCli('validators.dbConnection.timeout', {
|
|
65
|
+
host: config.host,
|
|
66
|
+
port: config.port,
|
|
67
|
+
seconds: Math.ceil(DB_CONNECTION_TIMEOUT_MS / 1000),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
if (code === '28P01' || code === '28000' || code === 'ER_ACCESS_DENIED_ERROR' || errno === 1045) {
|
|
71
|
+
return translateCli('validators.dbConnection.authenticationFailed', {
|
|
72
|
+
user: config.user,
|
|
73
|
+
database: config.database,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
if (code === '3D000' || code === 'ER_BAD_DB_ERROR' || errno === 1049) {
|
|
77
|
+
return translateCli('validators.dbConnection.databaseNotFound', {
|
|
78
|
+
database: config.database,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return translateCli('validators.dbConnection.connectionFailed', {
|
|
82
|
+
details: rawMessage || code || String(error),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async function checkPostgresFamilyConnection(config) {
|
|
86
|
+
const { default: pg } = await import('pg');
|
|
87
|
+
const client = new pg.Client({
|
|
88
|
+
host: config.host,
|
|
89
|
+
port: config.port,
|
|
90
|
+
user: config.user,
|
|
91
|
+
password: config.password,
|
|
92
|
+
database: config.database,
|
|
93
|
+
connectionTimeoutMillis: DB_CONNECTION_TIMEOUT_MS,
|
|
94
|
+
});
|
|
95
|
+
try {
|
|
96
|
+
await client.connect();
|
|
97
|
+
await client.query('SELECT 1');
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
await Promise.resolve(client.end()).catch(() => undefined);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
async function checkMysqlConnection(config) {
|
|
104
|
+
const { default: mysql } = await import('mysql2/promise');
|
|
105
|
+
const connection = await mysql.createConnection({
|
|
106
|
+
host: config.host,
|
|
107
|
+
port: config.port,
|
|
108
|
+
user: config.user,
|
|
109
|
+
password: config.password,
|
|
110
|
+
database: config.database,
|
|
111
|
+
connectTimeout: DB_CONNECTION_TIMEOUT_MS,
|
|
112
|
+
});
|
|
113
|
+
try {
|
|
114
|
+
await connection.query('SELECT 1');
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
await Promise.resolve(connection.end()).catch(() => undefined);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function checkMariaDbConnection(config) {
|
|
121
|
+
const { default: mariadb } = await import('mariadb');
|
|
122
|
+
const connection = await mariadb.createConnection({
|
|
123
|
+
host: config.host,
|
|
124
|
+
port: config.port,
|
|
125
|
+
user: config.user,
|
|
126
|
+
password: config.password,
|
|
127
|
+
database: config.database,
|
|
128
|
+
connectTimeout: DB_CONNECTION_TIMEOUT_MS,
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
await connection.query('SELECT 1');
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
await Promise.resolve(connection.end()).catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
async function performExternalDbConnectionCheck(config) {
|
|
138
|
+
try {
|
|
139
|
+
switch (config.dialect) {
|
|
140
|
+
case 'postgres':
|
|
141
|
+
case 'kingbase': {
|
|
142
|
+
await checkPostgresFamilyConnection(config);
|
|
143
|
+
return undefined;
|
|
144
|
+
}
|
|
145
|
+
case 'mysql': {
|
|
146
|
+
await checkMysqlConnection(config);
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
case 'mariadb': {
|
|
150
|
+
await checkMariaDbConnection(config);
|
|
151
|
+
return undefined;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
return formatDbConnectionError(config, error);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
export async function checkExternalDbConnection(config) {
|
|
160
|
+
const cacheKey = buildValidationCacheKey(config);
|
|
161
|
+
const cached = externalDbValidationCache.get(cacheKey);
|
|
162
|
+
if (cached) {
|
|
163
|
+
return await cached;
|
|
164
|
+
}
|
|
165
|
+
const pending = performExternalDbConnectionCheck(config);
|
|
166
|
+
externalDbValidationCache.set(cacheKey, pending);
|
|
167
|
+
return await pending;
|
|
168
|
+
}
|
|
169
|
+
export async function validateExternalDbConfig(values) {
|
|
170
|
+
const config = readExternalDbConnectionConfig(values);
|
|
171
|
+
if (!config) {
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
174
|
+
return await checkExternalDbConnection(config);
|
|
175
|
+
}
|
|
176
|
+
export function clearExternalDbValidationCache() {
|
|
177
|
+
externalDbValidationCache.clear();
|
|
178
|
+
}
|
|
@@ -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
|
/**
|
|
2
10
|
* This file is part of the NocoBase (R) project.
|
|
3
11
|
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
@@ -12,7 +20,10 @@ import { applyPostProcessor } from './post-processors.js';
|
|
|
12
20
|
import { registerPostProcessors } from '../post-processors/index.js';
|
|
13
21
|
function buildParameterFlag(parameter, options) {
|
|
14
22
|
const hints = [parameter.in];
|
|
15
|
-
if (parameter.
|
|
23
|
+
if (parameter.isFile) {
|
|
24
|
+
hints.push('file path');
|
|
25
|
+
}
|
|
26
|
+
else if (parameter.type === 'object' || parameter.type === 'array' || parameter.jsonEncoded) {
|
|
16
27
|
hints.push('JSON');
|
|
17
28
|
}
|
|
18
29
|
else if (parameter.isArray) {
|
|
@@ -67,10 +78,10 @@ export function createGeneratedFlags(operation) {
|
|
|
67
78
|
// Body flags are an alternative authoring path to --body/--body-file.
|
|
68
79
|
// Enforce required body semantics later in parseBody(), after we know
|
|
69
80
|
// which input mode the user chose.
|
|
70
|
-
required: parameter.in === 'body' ? false : parameter.required,
|
|
81
|
+
required: parameter.in === 'body' && !parameter.isFile ? false : parameter.required,
|
|
71
82
|
});
|
|
72
83
|
}
|
|
73
|
-
if (operation.hasBody) {
|
|
84
|
+
if (operation.hasBody && operation.requestContentType !== 'multipart/form-data') {
|
|
74
85
|
flags.body = Flags.string({
|
|
75
86
|
description: 'Full JSON request body string. Do not combine with body field flags.',
|
|
76
87
|
helpGroup: 'Raw JSON Body',
|
|
@@ -82,6 +93,13 @@ export function createGeneratedFlags(operation) {
|
|
|
82
93
|
exclusive: ['body'],
|
|
83
94
|
});
|
|
84
95
|
}
|
|
96
|
+
if (operation.responseType === 'binary') {
|
|
97
|
+
flags.output = Flags.string({
|
|
98
|
+
description: 'Path where the downloaded response should be written.',
|
|
99
|
+
helpGroup: 'Output',
|
|
100
|
+
required: true,
|
|
101
|
+
});
|
|
102
|
+
}
|
|
85
103
|
flags['api-base-url'] = Flags.string({
|
|
86
104
|
description: 'NocoBase API base URL, for example http://localhost:13000/api',
|
|
87
105
|
helpGroup: 'Global',
|
|
@@ -132,6 +150,8 @@ export class GeneratedApiCommand extends Command {
|
|
|
132
150
|
parameters: ctor.operation.parameters,
|
|
133
151
|
hasBody: ctor.operation.hasBody,
|
|
134
152
|
bodyRequired: ctor.operation.bodyRequired,
|
|
153
|
+
requestContentType: ctor.operation.requestContentType,
|
|
154
|
+
responseType: ctor.operation.responseType,
|
|
135
155
|
},
|
|
136
156
|
});
|
|
137
157
|
if (!response.ok) {
|
|
@@ -0,0 +1,127 @@
|
|
|
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 path from 'node:path';
|
|
10
|
+
import { access, lstat, mkdir, readdir, readlink, realpath, rm, stat, symlink } from 'node:fs/promises';
|
|
11
|
+
async function pathExists(target) {
|
|
12
|
+
try {
|
|
13
|
+
await access(target);
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export function resolvePluginStoragePath(storagePath) {
|
|
21
|
+
const root = String(storagePath ?? process.env.STORAGE_PATH ?? '').trim();
|
|
22
|
+
if (root) {
|
|
23
|
+
return path.join(path.isAbsolute(root) ? root : path.resolve(process.cwd(), root), 'plugins');
|
|
24
|
+
}
|
|
25
|
+
const configured = String(process.env.PLUGIN_STORAGE_PATH ?? '').trim();
|
|
26
|
+
if (configured) {
|
|
27
|
+
return path.isAbsolute(configured) ? configured : path.resolve(process.cwd(), configured);
|
|
28
|
+
}
|
|
29
|
+
return path.resolve(process.cwd(), 'storage', 'plugins');
|
|
30
|
+
}
|
|
31
|
+
async function getStoragePluginNames(target) {
|
|
32
|
+
const plugins = [];
|
|
33
|
+
const items = await readdir(target);
|
|
34
|
+
for (const item of items) {
|
|
35
|
+
const itemPath = path.resolve(target, item);
|
|
36
|
+
if (item.startsWith('@')) {
|
|
37
|
+
const statResult = await stat(itemPath);
|
|
38
|
+
if (!statResult.isDirectory()) {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const children = await getStoragePluginNames(itemPath);
|
|
42
|
+
plugins.push(...children.map((child) => `${item}/${child}`));
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (await pathExists(path.resolve(itemPath, 'package.json'))) {
|
|
46
|
+
plugins.push(item);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return plugins;
|
|
50
|
+
}
|
|
51
|
+
async function ensureOrgDirectory(nodeModulesPath, pluginName) {
|
|
52
|
+
if (!pluginName.startsWith('@')) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const [orgName] = pluginName.split('/');
|
|
56
|
+
await mkdir(path.resolve(nodeModulesPath, orgName), { recursive: true });
|
|
57
|
+
}
|
|
58
|
+
async function isSymlinkValid(linkPath, targetPath) {
|
|
59
|
+
try {
|
|
60
|
+
if (await pathExists(linkPath)) {
|
|
61
|
+
const realPath = await realpath(linkPath);
|
|
62
|
+
return realPath === targetPath;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
async function createStoragePluginSymlink(storagePluginsPath, nodeModulesPath, pluginName) {
|
|
71
|
+
const targetPath = path.resolve(storagePluginsPath, pluginName);
|
|
72
|
+
if (!(await pathExists(targetPath))) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
await ensureOrgDirectory(nodeModulesPath, pluginName);
|
|
76
|
+
const linkPath = path.resolve(nodeModulesPath, pluginName);
|
|
77
|
+
if (await isSymlinkValid(linkPath, targetPath)) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
await rm(linkPath, { recursive: true, force: true });
|
|
81
|
+
await symlink(targetPath, linkPath, 'dir');
|
|
82
|
+
}
|
|
83
|
+
export async function createStoragePluginsSymlink(storagePath, nodeModulesPath = String(process.env.NODE_MODULES_PATH ?? '').trim()) {
|
|
84
|
+
if (!nodeModulesPath) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const storagePluginsPath = resolvePluginStoragePath(storagePath);
|
|
88
|
+
if (!(await pathExists(storagePluginsPath))) {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const pluginNames = await getStoragePluginNames(storagePluginsPath);
|
|
92
|
+
await Promise.all(pluginNames.map(async (pluginName) => await createStoragePluginSymlink(storagePluginsPath, nodeModulesPath, pluginName)));
|
|
93
|
+
}
|
|
94
|
+
export async function removeStoragePluginSymlink(pluginName, storagePath, nodeModulesPath = String(process.env.NODE_MODULES_PATH ?? '').trim()) {
|
|
95
|
+
if (!nodeModulesPath) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
const storagePluginsPath = resolvePluginStoragePath(storagePath);
|
|
99
|
+
const targetPath = path.resolve(storagePluginsPath, pluginName);
|
|
100
|
+
const linkPath = path.resolve(nodeModulesPath, pluginName);
|
|
101
|
+
if (!(await pathExists(linkPath))) {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
let statResult;
|
|
105
|
+
try {
|
|
106
|
+
statResult = await lstat(linkPath);
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
if (!statResult.isSymbolicLink()) {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
let resolvedLinkTarget = '';
|
|
115
|
+
try {
|
|
116
|
+
const linkTarget = await readlink(linkPath);
|
|
117
|
+
resolvedLinkTarget = path.resolve(path.dirname(linkPath), linkTarget);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
if (resolvedLinkTarget !== targetPath) {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
await rm(linkPath, { recursive: true, force: true });
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
@@ -173,13 +173,13 @@ export async function validateAvailableTcpPort(value) {
|
|
|
173
173
|
return formatError;
|
|
174
174
|
}
|
|
175
175
|
const port = parseTcpPort(raw);
|
|
176
|
-
const available = await canListenOnTcpPort(port);
|
|
177
|
-
if (!available) {
|
|
178
|
-
return translateCli('validators.tcpPort.alreadyInUse', { port });
|
|
179
|
-
}
|
|
180
176
|
const dockerPorts = await getDockerPublishedTcpPorts();
|
|
181
177
|
if (dockerPorts.has(port)) {
|
|
182
178
|
return translateCli('validators.tcpPort.alreadyInUseByDocker', { port });
|
|
183
179
|
}
|
|
180
|
+
const available = await canListenOnTcpPort(port);
|
|
181
|
+
if (!available) {
|
|
182
|
+
return translateCli('validators.tcpPort.alreadyInUse', { port });
|
|
183
|
+
}
|
|
184
184
|
return undefined;
|
|
185
185
|
}
|
|
@@ -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
|
/**
|
|
2
10
|
* This file is part of the NocoBase (R) project.
|
|
3
11
|
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
@@ -60,12 +68,59 @@ function toGeneratedParameter(parameter, usedFlagNames) {
|
|
|
60
68
|
required: parameter.required,
|
|
61
69
|
description: parameter.description,
|
|
62
70
|
type: inferParameterType(parameter.schema),
|
|
71
|
+
format: parameter.schema?.format,
|
|
63
72
|
isArray: parameter.schema?.type === 'array',
|
|
73
|
+
isFile: parameter.schema?.type === 'string' && parameter.schema?.format === 'binary',
|
|
64
74
|
};
|
|
65
75
|
}
|
|
66
76
|
function getJsonRequestSchema(requestBody) {
|
|
67
77
|
return requestBody?.content?.['application/json']?.schema;
|
|
68
78
|
}
|
|
79
|
+
function getMultipartRequestSchema(requestBody) {
|
|
80
|
+
return requestBody?.content?.['multipart/form-data']?.schema;
|
|
81
|
+
}
|
|
82
|
+
function getRequestContentType(requestBody) {
|
|
83
|
+
if (!requestBody || '$ref' in requestBody) {
|
|
84
|
+
return undefined;
|
|
85
|
+
}
|
|
86
|
+
if (requestBody.content?.['multipart/form-data']) {
|
|
87
|
+
return 'multipart/form-data';
|
|
88
|
+
}
|
|
89
|
+
if (requestBody.content?.['application/json']) {
|
|
90
|
+
return 'application/json';
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
function getRequestSchema(requestBody) {
|
|
95
|
+
return getMultipartRequestSchema(requestBody) ?? getJsonRequestSchema(requestBody);
|
|
96
|
+
}
|
|
97
|
+
function isBinarySchema(schema) {
|
|
98
|
+
if (!schema || typeof schema !== 'object') {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
if (schema.type === 'string' && schema.format === 'binary') {
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
return [...(schema.oneOf ?? []), ...(schema.anyOf ?? []), ...(schema.allOf ?? [])].some(isBinarySchema);
|
|
105
|
+
}
|
|
106
|
+
function getResponseType(operation) {
|
|
107
|
+
for (const response of Object.values(operation.responses ?? {})) {
|
|
108
|
+
const content = response?.content ?? {};
|
|
109
|
+
const mediaTypes = Object.keys(content);
|
|
110
|
+
const hasJson = mediaTypes.some((mediaType) => mediaType.includes('json'));
|
|
111
|
+
if (hasJson) {
|
|
112
|
+
return 'json';
|
|
113
|
+
}
|
|
114
|
+
const hasBinary = mediaTypes.some((mediaType) => {
|
|
115
|
+
const schema = content[mediaType]?.schema;
|
|
116
|
+
return mediaType === 'application/octet-stream' || mediaType.includes('zip') || isBinarySchema(schema);
|
|
117
|
+
});
|
|
118
|
+
if (hasBinary) {
|
|
119
|
+
return 'binary';
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
69
124
|
function normalizeCompositeSchema(schema) {
|
|
70
125
|
if (!schema || typeof schema !== 'object') {
|
|
71
126
|
return schema;
|
|
@@ -139,7 +194,7 @@ function describeSchemaShape(schema, options = {}) {
|
|
|
139
194
|
return type;
|
|
140
195
|
}
|
|
141
196
|
function extractBodyParameters(requestBody, usedFlagNames) {
|
|
142
|
-
const schema =
|
|
197
|
+
const schema = getRequestSchema(requestBody);
|
|
143
198
|
const properties = normalizeCompositeSchema(schema)?.properties;
|
|
144
199
|
const required = new Set(normalizeCompositeSchema(schema)?.required ?? []);
|
|
145
200
|
return Object.entries(properties ?? {}).map(([name, propertySchema]) => ({
|
|
@@ -149,7 +204,9 @@ function extractBodyParameters(requestBody, usedFlagNames) {
|
|
|
149
204
|
required: required.has(name),
|
|
150
205
|
description: propertySchema.description,
|
|
151
206
|
type: inferParameterType(propertySchema),
|
|
207
|
+
format: propertySchema.format,
|
|
152
208
|
isArray: propertySchema.type === 'array',
|
|
209
|
+
isFile: propertySchema.type === 'string' && propertySchema.format === 'binary',
|
|
153
210
|
jsonEncoded: propertySchema.type === 'object' || propertySchema.type === 'array',
|
|
154
211
|
jsonShape: describeSchemaShape(propertySchema),
|
|
155
212
|
}));
|
|
@@ -179,6 +236,9 @@ function formatFlagExample(parameter) {
|
|
|
179
236
|
if (parameter.type === 'boolean') {
|
|
180
237
|
return `--${parameter.flagName}`;
|
|
181
238
|
}
|
|
239
|
+
if (parameter.isFile) {
|
|
240
|
+
return `--${parameter.flagName} <path>`;
|
|
241
|
+
}
|
|
182
242
|
if (parameter.type === 'object' || parameter.jsonEncoded) {
|
|
183
243
|
if (parameter.type === 'array' || parameter.isArray) {
|
|
184
244
|
return `--${parameter.flagName} '[]'`;
|
|
@@ -216,12 +276,13 @@ export function buildExamples(commandId, operation) {
|
|
|
216
276
|
const requiredParameters = operation.parameters.filter((parameter) => parameter.required);
|
|
217
277
|
const requiredFlags = requiredParameters.map(formatFlagExample);
|
|
218
278
|
const requiredNonBodyFlags = requiredParameters.filter((parameter) => parameter.in !== 'body').map(formatFlagExample);
|
|
219
|
-
const
|
|
279
|
+
const outputFlag = operation.responseType === 'binary' ? ' --output <path>' : '';
|
|
280
|
+
const examples = [`nb api ${commandId}${requiredFlags.length ? ` ${requiredFlags.join(' ')}` : ''}${outputFlag}`];
|
|
220
281
|
const firstOptional = operation.parameters.find((parameter) => !parameter.required);
|
|
221
282
|
if (firstOptional) {
|
|
222
|
-
examples.push(`${examples[0]} ${formatFlagExample(firstOptional)}
|
|
283
|
+
examples.push(`${examples[0]} ${formatFlagExample(firstOptional)}`.trim());
|
|
223
284
|
}
|
|
224
|
-
if (operation.hasBody) {
|
|
285
|
+
if (operation.hasBody && operation.requestContentType !== 'multipart/form-data') {
|
|
225
286
|
const prefix = `nb api ${commandId}${requiredNonBodyFlags.length ? ` ${requiredNonBodyFlags.join(' ')}` : ''}`;
|
|
226
287
|
examples.push(`${prefix} --body '${buildSampleBody(operation.parameters)}'`);
|
|
227
288
|
}
|
|
@@ -248,9 +309,17 @@ function buildDescription(operation) {
|
|
|
248
309
|
}
|
|
249
310
|
if (operation.hasBody) {
|
|
250
311
|
const bodyFlags = operation.parameters.filter((parameter) => parameter.in === 'body').map((parameter) => `--${parameter.flagName}`);
|
|
251
|
-
|
|
252
|
-
? `Request body:
|
|
253
|
-
|
|
312
|
+
if (operation.requestContentType === 'multipart/form-data') {
|
|
313
|
+
sections.push(bodyFlags.length ? `Request body: multipart form fields (${bodyFlags.join(', ')}).` : 'Request body: multipart form data.');
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
sections.push(bodyFlags.length
|
|
317
|
+
? `Request body: use body field flags (${bodyFlags.join(', ')}) or pass raw JSON via \`--body\` / \`--body-file\`.`
|
|
318
|
+
: 'Request body: JSON via `--body` or `--body-file`.');
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (operation.responseType === 'binary') {
|
|
322
|
+
sections.push('Response body: binary download written to `--output`.');
|
|
254
323
|
}
|
|
255
324
|
return sections.join('\n\n');
|
|
256
325
|
}
|
|
@@ -357,6 +426,8 @@ export async function generateRuntime(document, configFile, baseUrl) {
|
|
|
357
426
|
const bodyParameters = extractBodyParameters(operation.requestBody, usedFlagNames);
|
|
358
427
|
const allParameters = [...parameters, ...bodyParameters];
|
|
359
428
|
const hasBody = Boolean(operation.requestBody && !('$ref' in operation.requestBody));
|
|
429
|
+
const requestContentType = getRequestContentType(operation.requestBody);
|
|
430
|
+
const responseType = getResponseType(operation);
|
|
360
431
|
const moduleDisplayName = moduleConfig.name ?? moduleKey;
|
|
361
432
|
const moduleDescription = moduleConfig.description;
|
|
362
433
|
const resourceDisplayName = resourceConfig?.name ?? resourceKey;
|
|
@@ -366,9 +437,11 @@ export async function generateRuntime(document, configFile, baseUrl) {
|
|
|
366
437
|
description: operation.description,
|
|
367
438
|
});
|
|
368
439
|
const resourceSegments = toResourceSegments(pathTemplate);
|
|
369
|
-
const mappedResourceSegments = resourceSegments.length && resourceConfig?.
|
|
370
|
-
? [
|
|
371
|
-
: resourceSegments
|
|
440
|
+
const mappedResourceSegments = resourceSegments.length && resourceConfig?.segments?.length
|
|
441
|
+
? [...resourceConfig.segments.map(toKebabCase), ...resourceSegments.slice(1)]
|
|
442
|
+
: resourceSegments.length && resourceConfig?.name
|
|
443
|
+
? [toKebabCase(resourceConfig.name), ...resourceSegments.slice(1)]
|
|
444
|
+
: resourceSegments;
|
|
372
445
|
const segments = [
|
|
373
446
|
...(resourceConfig?.topLevel ? [] : [toKebabCase(moduleDisplayName)]),
|
|
374
447
|
...mappedResourceSegments,
|
|
@@ -397,15 +470,21 @@ export async function generateRuntime(document, configFile, baseUrl) {
|
|
|
397
470
|
tags: operation.tags,
|
|
398
471
|
description: operationText.description,
|
|
399
472
|
hasBody,
|
|
473
|
+
requestContentType,
|
|
474
|
+
responseType,
|
|
400
475
|
parameters: allParameters,
|
|
401
476
|
}),
|
|
402
477
|
examples: buildExamples(segments.join(' '), {
|
|
403
478
|
parameters: allParameters,
|
|
404
479
|
hasBody,
|
|
480
|
+
requestContentType,
|
|
481
|
+
responseType,
|
|
405
482
|
}),
|
|
406
483
|
parameters: allParameters,
|
|
407
484
|
hasBody,
|
|
408
485
|
bodyRequired: operation.requestBody && !('$ref' in operation.requestBody) ? operation.requestBody.required : undefined,
|
|
486
|
+
requestContentType,
|
|
487
|
+
responseType,
|
|
409
488
|
});
|
|
410
489
|
}
|
|
411
490
|
const schemaHash = createHash('sha1').update(JSON.stringify(document)).digest('hex').slice(0, 8);
|
package/dist/lib/self-manager.js
CHANGED
|
@@ -7,11 +7,14 @@
|
|
|
7
7
|
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
8
|
*/
|
|
9
9
|
import fs from 'node:fs';
|
|
10
|
+
import fsp from 'node:fs/promises';
|
|
10
11
|
import path from 'node:path';
|
|
11
12
|
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { resolveCliHomeDir } from './cli-home.js';
|
|
12
14
|
import { commandOutput, run } from './run-npm.js';
|
|
13
15
|
const DEFAULT_PACKAGE_NAME = '@nocobase/cli';
|
|
14
16
|
const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
17
|
+
const INSTALL_METHOD_CACHE_FILE = 'self-install-methods.json';
|
|
15
18
|
function normalizePath(value) {
|
|
16
19
|
return path.resolve(value);
|
|
17
20
|
}
|
|
@@ -115,6 +118,38 @@ function detectInstallMethod(packageRoot, globalPrefix) {
|
|
|
115
118
|
}
|
|
116
119
|
return 'unknown';
|
|
117
120
|
}
|
|
121
|
+
function getInstallMethodCacheFile() {
|
|
122
|
+
return path.join(resolveCliHomeDir('global'), INSTALL_METHOD_CACHE_FILE);
|
|
123
|
+
}
|
|
124
|
+
function getInstallMethodCacheKey(packageRoot) {
|
|
125
|
+
return normalizePath(path.join(packageRoot, 'bin', 'run.js'));
|
|
126
|
+
}
|
|
127
|
+
async function readInstallMethodCache() {
|
|
128
|
+
try {
|
|
129
|
+
const raw = await fsp.readFile(getInstallMethodCacheFile(), 'utf8');
|
|
130
|
+
return JSON.parse(raw);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return {};
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function writeInstallMethodCache(state) {
|
|
137
|
+
const filePath = getInstallMethodCacheFile();
|
|
138
|
+
await fsp.mkdir(path.dirname(filePath), { recursive: true });
|
|
139
|
+
await fsp.writeFile(filePath, JSON.stringify(state, null, 2));
|
|
140
|
+
}
|
|
141
|
+
async function readCachedInstallMethod(packageRoot) {
|
|
142
|
+
const state = await readInstallMethodCache();
|
|
143
|
+
return state.entries?.[getInstallMethodCacheKey(packageRoot)];
|
|
144
|
+
}
|
|
145
|
+
async function writeCachedInstallMethod(packageRoot, entry) {
|
|
146
|
+
const state = await readInstallMethodCache();
|
|
147
|
+
const entries = {
|
|
148
|
+
...(state.entries ?? {}),
|
|
149
|
+
[getInstallMethodCacheKey(packageRoot)]: entry,
|
|
150
|
+
};
|
|
151
|
+
await writeInstallMethodCache({ entries });
|
|
152
|
+
}
|
|
118
153
|
async function readGlobalPrefix(commandOutputFn) {
|
|
119
154
|
try {
|
|
120
155
|
return (await commandOutputFn('npm', ['prefix', '-g'], {
|
|
@@ -177,14 +212,34 @@ export function formatSelfUpdateUnavailableMessage(status) {
|
|
|
177
212
|
export function getSelfUpdatePackageSpec(status) {
|
|
178
213
|
return `${status.packageName}@${status.channel}`;
|
|
179
214
|
}
|
|
215
|
+
export async function inspectSelfInstall(options = {}) {
|
|
216
|
+
const packageRoot = options.packageRoot ? normalizePath(options.packageRoot) : PACKAGE_ROOT;
|
|
217
|
+
const commandOutputFn = options.commandOutputFn ?? commandOutput;
|
|
218
|
+
const cachedInstallMethod = await readCachedInstallMethod(packageRoot);
|
|
219
|
+
const globalPrefix = cachedInstallMethod?.globalPrefix ?? await readGlobalPrefix(commandOutputFn);
|
|
220
|
+
const installMethod = cachedInstallMethod?.installMethod ?? detectInstallMethod(packageRoot, globalPrefix);
|
|
221
|
+
if (!cachedInstallMethod) {
|
|
222
|
+
await writeCachedInstallMethod(packageRoot, {
|
|
223
|
+
installMethod,
|
|
224
|
+
globalPrefix,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
packageRoot,
|
|
229
|
+
installMethod,
|
|
230
|
+
globalPrefix,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
180
233
|
export async function inspectSelfStatus(options = {}) {
|
|
181
234
|
const packageRoot = options.packageRoot ? normalizePath(options.packageRoot) : PACKAGE_ROOT;
|
|
182
235
|
const packageName = options.packageName ?? DEFAULT_PACKAGE_NAME;
|
|
183
236
|
const currentVersion = options.currentVersion ?? readCurrentVersion(packageRoot);
|
|
184
237
|
const channel = options.channel && options.channel !== 'auto' ? options.channel : detectChannel(currentVersion);
|
|
185
238
|
const commandOutputFn = options.commandOutputFn ?? commandOutput;
|
|
186
|
-
const globalPrefix = await
|
|
187
|
-
|
|
239
|
+
const { installMethod, globalPrefix } = await inspectSelfInstall({
|
|
240
|
+
packageRoot,
|
|
241
|
+
commandOutputFn,
|
|
242
|
+
});
|
|
188
243
|
let latestVersion;
|
|
189
244
|
let registryError;
|
|
190
245
|
try {
|