@nocobase/server 1.2.13-alpha → 1.3.0-alpha.20240710084543

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 (124) hide show
  1. package/package.json +14 -14
  2. package/lib/acl/available-action.d.ts +0 -13
  3. package/lib/acl/available-action.js +0 -71
  4. package/lib/acl/index.d.ts +0 -10
  5. package/lib/acl/index.js +0 -46
  6. package/lib/app-command.d.ts +0 -20
  7. package/lib/app-command.js +0 -82
  8. package/lib/app-supervisor.d.ts +0 -69
  9. package/lib/app-supervisor.js +0 -302
  10. package/lib/application.d.ts +0 -345
  11. package/lib/application.js +0 -876
  12. package/lib/cache/index.d.ts +0 -11
  13. package/lib/cache/index.js +0 -44
  14. package/lib/commands/console.d.ts +0 -11
  15. package/lib/commands/console.js +0 -48
  16. package/lib/commands/create-migration.d.ts +0 -11
  17. package/lib/commands/create-migration.js +0 -79
  18. package/lib/commands/db-auth.d.ts +0 -11
  19. package/lib/commands/db-auth.js +0 -38
  20. package/lib/commands/db-clean.d.ts +0 -11
  21. package/lib/commands/db-clean.js +0 -41
  22. package/lib/commands/db-sync.d.ts +0 -11
  23. package/lib/commands/db-sync.js +0 -50
  24. package/lib/commands/destroy.d.ts +0 -11
  25. package/lib/commands/destroy.js +0 -40
  26. package/lib/commands/index.d.ts +0 -10
  27. package/lib/commands/index.js +0 -82
  28. package/lib/commands/install.d.ts +0 -11
  29. package/lib/commands/install.js +0 -43
  30. package/lib/commands/migrator.d.ts +0 -11
  31. package/lib/commands/migrator.js +0 -41
  32. package/lib/commands/pm.d.ts +0 -11
  33. package/lib/commands/pm.js +0 -98
  34. package/lib/commands/refresh.d.ts +0 -11
  35. package/lib/commands/refresh.js +0 -41
  36. package/lib/commands/restart.d.ts +0 -11
  37. package/lib/commands/restart.js +0 -45
  38. package/lib/commands/start.d.ts +0 -11
  39. package/lib/commands/start.js +0 -85
  40. package/lib/commands/stop.d.ts +0 -11
  41. package/lib/commands/stop.js +0 -44
  42. package/lib/commands/upgrade.d.ts +0 -14
  43. package/lib/commands/upgrade.js +0 -39
  44. package/lib/cron/cron-job-manager.d.ts +0 -22
  45. package/lib/cron/cron-job-manager.js +0 -82
  46. package/lib/errors/application-not-install.d.ts +0 -12
  47. package/lib/errors/application-not-install.js +0 -45
  48. package/lib/errors/handler.d.ts +0 -11
  49. package/lib/errors/handler.js +0 -50
  50. package/lib/errors/plugin-command-error.d.ts +0 -10
  51. package/lib/errors/plugin-command-error.js +0 -40
  52. package/lib/errors/plugin-not-exist.d.ts +0 -10
  53. package/lib/errors/plugin-not-exist.js +0 -40
  54. package/lib/gateway/errors.d.ts +0 -30
  55. package/lib/gateway/errors.js +0 -154
  56. package/lib/gateway/index.d.ts +0 -79
  57. package/lib/gateway/index.js +0 -393
  58. package/lib/gateway/ipc-socket-client.d.ts +0 -27
  59. package/lib/gateway/ipc-socket-client.js +0 -110
  60. package/lib/gateway/ipc-socket-server.d.ts +0 -21
  61. package/lib/gateway/ipc-socket-server.js +0 -150
  62. package/lib/gateway/ws-server.d.ts +0 -36
  63. package/lib/gateway/ws-server.js +0 -196
  64. package/lib/helper.d.ts +0 -18
  65. package/lib/helper.js +0 -193
  66. package/lib/helpers/application-version.d.ts +0 -18
  67. package/lib/helpers/application-version.js +0 -88
  68. package/lib/index.d.ts +0 -17
  69. package/lib/index.js +0 -64
  70. package/lib/locale/index.d.ts +0 -9
  71. package/lib/locale/index.js +0 -30
  72. package/lib/locale/locale.d.ts +0 -38
  73. package/lib/locale/locale.js +0 -174
  74. package/lib/locale/resource.d.ts +0 -9
  75. package/lib/locale/resource.js +0 -87
  76. package/lib/main-data-source.d.ts +0 -12
  77. package/lib/main-data-source.js +0 -57
  78. package/lib/middlewares/data-template.d.ts +0 -10
  79. package/lib/middlewares/data-template.js +0 -146
  80. package/lib/middlewares/data-wrapping.d.ts +0 -11
  81. package/lib/middlewares/data-wrapping.js +0 -100
  82. package/lib/middlewares/i18n.d.ts +0 -9
  83. package/lib/middlewares/i18n.js +0 -53
  84. package/lib/middlewares/index.d.ts +0 -10
  85. package/lib/middlewares/index.js +0 -39
  86. package/lib/middlewares/parse-variables.d.ts +0 -9
  87. package/lib/middlewares/parse-variables.js +0 -95
  88. package/lib/middlewares/validate-filter-params.d.ts +0 -9
  89. package/lib/middlewares/validate-filter-params.js +0 -42
  90. package/lib/migration.d.ts +0 -20
  91. package/lib/migration.js +0 -54
  92. package/lib/migrations/20230912193824-package-name-unique.d.ts +0 -14
  93. package/lib/migrations/20230912193824-package-name-unique.js +0 -59
  94. package/lib/migrations/20230912294620-update-pkg.d.ts +0 -14
  95. package/lib/migrations/20230912294620-update-pkg.js +0 -65
  96. package/lib/migrations/20240106082756-update-plugins.d.ts +0 -14
  97. package/lib/migrations/20240106082756-update-plugins.js +0 -51
  98. package/lib/migrations/20240428235620-rename-plugins.d.ts +0 -14
  99. package/lib/migrations/20240428235620-rename-plugins.js +0 -49
  100. package/lib/plugin-manager/clientStaticUtils.d.ts +0 -31
  101. package/lib/plugin-manager/clientStaticUtils.js +0 -129
  102. package/lib/plugin-manager/constants.d.ts +0 -15
  103. package/lib/plugin-manager/constants.js +0 -135
  104. package/lib/plugin-manager/deps.d.ts +0 -10
  105. package/lib/plugin-manager/deps.js +0 -83
  106. package/lib/plugin-manager/index.d.ts +0 -10
  107. package/lib/plugin-manager/index.js +0 -32
  108. package/lib/plugin-manager/middleware.d.ts +0 -10
  109. package/lib/plugin-manager/middleware.js +0 -45
  110. package/lib/plugin-manager/options/collection.d.ts +0 -10
  111. package/lib/plugin-manager/options/collection.js +0 -47
  112. package/lib/plugin-manager/options/resource.d.ts +0 -23
  113. package/lib/plugin-manager/options/resource.js +0 -186
  114. package/lib/plugin-manager/plugin-manager-repository.d.ts +0 -36
  115. package/lib/plugin-manager/plugin-manager-repository.js +0 -158
  116. package/lib/plugin-manager/plugin-manager.d.ts +0 -206
  117. package/lib/plugin-manager/plugin-manager.js +0 -1100
  118. package/lib/plugin-manager/types.d.ts +0 -23
  119. package/lib/plugin-manager/types.js +0 -24
  120. package/lib/plugin-manager/utils.d.ts +0 -115
  121. package/lib/plugin-manager/utils.js +0 -568
  122. package/lib/plugin.d.ts +0 -99
  123. package/lib/plugin.js +0 -228
  124. package/lib/swagger/index.json +0 -1569
@@ -1,1100 +0,0 @@
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
-
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
17
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
18
- var __export = (target, all) => {
19
- for (var name in all)
20
- __defProp(target, name, { get: all[name], enumerable: true });
21
- };
22
- var __copyProps = (to, from, except, desc) => {
23
- if (from && typeof from === "object" || typeof from === "function") {
24
- for (let key of __getOwnPropNames(from))
25
- if (!__hasOwnProp.call(to, key) && key !== except)
26
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
- }
28
- return to;
29
- };
30
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
31
- // If the importer is in node compatibility mode or this is not an ESM
32
- // file that has been converted to a CommonJS file using a Babel-
33
- // compatible transform (i.e. "__esModule" has not been set), then set
34
- // "default" to the CommonJS "module.exports" for node compatibility.
35
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
36
- mod
37
- ));
38
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
39
- var __publicField = (obj, key, value) => {
40
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
41
- return value;
42
- };
43
- var plugin_manager_exports = {};
44
- __export(plugin_manager_exports, {
45
- AddPresetError: () => AddPresetError,
46
- PluginManager: () => PluginManager,
47
- default: () => plugin_manager_default,
48
- sleep: () => sleep
49
- });
50
- module.exports = __toCommonJS(plugin_manager_exports);
51
- var import_topo = __toESM(require("@hapi/topo"));
52
- var import_utils = require("@nocobase/utils");
53
- var import_plugin_symlink = require("@nocobase/utils/plugin-symlink");
54
- var import_execa = __toESM(require("execa"));
55
- var import_fast_glob = __toESM(require("fast-glob"));
56
- var import_fs = __toESM(require("fs"));
57
- var import_lodash = __toESM(require("lodash"));
58
- var import_path = require("path");
59
- var import_helper = require("../helper");
60
- var import_middleware = require("./middleware");
61
- var import_collection = __toESM(require("./options/collection"));
62
- var import_resource = __toESM(require("./options/resource"));
63
- var import_plugin_manager_repository = require("./plugin-manager-repository");
64
- var import_utils2 = require("./utils");
65
- const sleep = /* @__PURE__ */ __name(async (timeout = 0) => {
66
- return new Promise((resolve2) => {
67
- setTimeout(resolve2, timeout);
68
- });
69
- }, "sleep");
70
- const _AddPresetError = class _AddPresetError extends Error {
71
- };
72
- __name(_AddPresetError, "AddPresetError");
73
- let AddPresetError = _AddPresetError;
74
- const _PluginManager = class _PluginManager {
75
- /**
76
- * @internal
77
- */
78
- constructor(options) {
79
- this.options = options;
80
- this.app = options.app;
81
- this.app.db.registerRepositories({
82
- PluginManagerRepository: import_plugin_manager_repository.PluginManagerRepository
83
- });
84
- this.collection = this.app.db.collection(import_collection.default);
85
- this._repository = this.collection.repository;
86
- this._repository.setPluginManager(this);
87
- this.app.resourcer.define(import_resource.default);
88
- this.app.acl.allow("pm", "listEnabled", "public");
89
- this.app.acl.registerSnippet({
90
- name: "pm",
91
- actions: ["pm:*"]
92
- });
93
- this.app.db.addMigrations({
94
- namespace: "core/pm",
95
- directory: (0, import_path.resolve)(__dirname, "../migrations")
96
- });
97
- this.app.resourcer.use(import_middleware.uploadMiddleware);
98
- }
99
- /**
100
- * @internal
101
- */
102
- app;
103
- /**
104
- * @internal
105
- */
106
- collection;
107
- /**
108
- * @internal
109
- */
110
- pluginInstances = /* @__PURE__ */ new Map();
111
- /**
112
- * @internal
113
- */
114
- pluginAliases = /* @__PURE__ */ new Map();
115
- /**
116
- * @internal
117
- */
118
- server;
119
- /**
120
- * @internal
121
- */
122
- _repository;
123
- get repository() {
124
- return this.app.db.getRepository("applicationPlugins");
125
- }
126
- /**
127
- * @internal
128
- */
129
- static async getPackageJson(packageName) {
130
- const file = await import_fs.default.promises.realpath((0, import_path.resolve)(process.env.NODE_MODULES_PATH, packageName, "package.json"));
131
- const data = await import_fs.default.promises.readFile(file, { encoding: "utf-8" });
132
- return JSON.parse(data);
133
- }
134
- /**
135
- * @internal
136
- */
137
- static async getPackageName(name) {
138
- const prefixes = this.getPluginPkgPrefix();
139
- for (const prefix of prefixes) {
140
- const pkg = (0, import_path.resolve)(process.env.NODE_MODULES_PATH, `${prefix}${name}`, "package.json");
141
- const exists = await (0, import_plugin_symlink.fsExists)(pkg);
142
- if (exists) {
143
- return `${prefix}${name}`;
144
- }
145
- }
146
- throw new Error(`${name} plugin does not exist`);
147
- }
148
- /**
149
- * @internal
150
- */
151
- static getPluginPkgPrefix() {
152
- return (process.env.PLUGIN_PACKAGE_PREFIX || "@nocobase/plugin-,@nocobase/preset-,@nocobase/plugin-pro-").split(
153
- ","
154
- );
155
- }
156
- /**
157
- * @internal
158
- */
159
- static async findPackage(name) {
160
- try {
161
- const packageName = this.getPackageName(name);
162
- return packageName;
163
- } catch (error) {
164
- console.log(`\`${name}\` plugin not found locally`);
165
- const prefixes = this.getPluginPkgPrefix();
166
- for (const prefix of prefixes) {
167
- try {
168
- const packageName = `${prefix}${name}`;
169
- console.log(`Try to find ${packageName}`);
170
- await (0, import_execa.default)("npm", ["v", packageName, "versions"]);
171
- console.log(`${packageName} downloading`);
172
- await (0, import_execa.default)("yarn", ["add", packageName, "-W"]);
173
- console.log(`${packageName} downloaded`);
174
- return packageName;
175
- } catch (error2) {
176
- continue;
177
- }
178
- }
179
- }
180
- throw new Error(`No available packages found, ${name} plugin does not exist`);
181
- }
182
- /**
183
- * @internal
184
- */
185
- static clearCache(packageName) {
186
- return;
187
- const packageNamePath = packageName.replace("/", import_path.sep);
188
- Object.keys(require.cache).forEach((key) => {
189
- if (key.includes(packageNamePath)) {
190
- delete require.cache[key];
191
- }
192
- });
193
- }
194
- /**
195
- * @internal
196
- */
197
- static async resolvePlugin(pluginName, isUpgrade = false, isPkg = false) {
198
- if (typeof pluginName === "string") {
199
- const packageName = isPkg ? pluginName : await this.getPackageName(pluginName);
200
- this.clearCache(packageName);
201
- return await (0, import_utils.importModule)(packageName);
202
- } else {
203
- return pluginName;
204
- }
205
- }
206
- static async parseName(nameOrPkg) {
207
- if (this.parsedNames[nameOrPkg]) {
208
- return this.parsedNames[nameOrPkg];
209
- }
210
- if (nameOrPkg.startsWith("@nocobase/plugin-")) {
211
- this.parsedNames[nameOrPkg] = {
212
- packageName: nameOrPkg,
213
- name: nameOrPkg.replace("@nocobase/plugin-", "")
214
- };
215
- return this.parsedNames[nameOrPkg];
216
- }
217
- if (nameOrPkg.startsWith("@nocobase/preset-")) {
218
- this.parsedNames[nameOrPkg] = {
219
- packageName: nameOrPkg,
220
- name: nameOrPkg.replace("@nocobase/preset-", "")
221
- };
222
- return this.parsedNames[nameOrPkg];
223
- }
224
- const exists = /* @__PURE__ */ __name(async (name, isPreset = false) => {
225
- return (0, import_plugin_symlink.fsExists)(
226
- (0, import_path.resolve)(process.env.NODE_MODULES_PATH, `@nocobase/${isPreset ? "preset" : "plugin"}-${name}`, "package.json")
227
- );
228
- }, "exists");
229
- if (await exists(nameOrPkg)) {
230
- this.parsedNames[nameOrPkg] = { name: nameOrPkg, packageName: `@nocobase/plugin-${nameOrPkg}` };
231
- } else if (await exists(nameOrPkg, true)) {
232
- this.parsedNames[nameOrPkg] = { name: nameOrPkg, packageName: `@nocobase/preset-${nameOrPkg}` };
233
- } else {
234
- this.parsedNames[nameOrPkg] = { name: nameOrPkg, packageName: nameOrPkg };
235
- }
236
- return this.parsedNames[nameOrPkg];
237
- }
238
- addPreset(plugin, options = {}) {
239
- if (this.app.loaded) {
240
- throw new AddPresetError("must be added before executing app.load()");
241
- }
242
- if (!this.options.plugins) {
243
- this.options.plugins = [];
244
- }
245
- this.options.plugins.push([plugin, options]);
246
- }
247
- getPlugins() {
248
- return this.app.pm.pluginInstances;
249
- }
250
- getAliases() {
251
- return this.app.pm.pluginAliases.keys();
252
- }
253
- get(name) {
254
- if (typeof name === "string") {
255
- return this.app.pm.pluginAliases.get(name);
256
- }
257
- return this.app.pm.pluginInstances.get(name);
258
- }
259
- has(name) {
260
- if (typeof name === "string") {
261
- return this.app.pm.pluginAliases.has(name);
262
- }
263
- return this.app.pm.pluginInstances.has(name);
264
- }
265
- del(name) {
266
- const instance = this.get(name);
267
- if (instance) {
268
- this.app.pm.pluginAliases.delete(instance.name);
269
- this.app.pm.pluginInstances.delete(instance.constructor);
270
- }
271
- }
272
- /* istanbul ignore next -- @preserve */
273
- async create(pluginName, options) {
274
- const createPlugin = /* @__PURE__ */ __name(async (name2) => {
275
- const pluginDir = (0, import_path.resolve)(process.cwd(), "packages/plugins", name2);
276
- if (options == null ? void 0 : options.forceRecreate) {
277
- await import_fs.default.promises.rm(pluginDir, { recursive: true, force: true });
278
- }
279
- const { PluginGenerator } = require("@nocobase/cli/src/plugin-generator");
280
- const generator = new PluginGenerator({
281
- cwd: process.cwd(),
282
- args: {},
283
- context: {
284
- name: name2
285
- }
286
- });
287
- await generator.run();
288
- }, "createPlugin");
289
- await createPlugin(pluginName);
290
- try {
291
- await this.app.db.auth({ retry: 1 });
292
- const installed = await this.app.isInstalled();
293
- if (!installed) {
294
- console.log(`yarn pm add ${pluginName}`);
295
- return;
296
- }
297
- } catch (error) {
298
- return;
299
- }
300
- this.app.log.info("attempt to add the plugin to the app");
301
- const { name, packageName } = await _PluginManager.parseName(pluginName);
302
- const json = await _PluginManager.getPackageJson(packageName);
303
- this.app.log.info(`add plugin [${packageName}]`, {
304
- name,
305
- packageName,
306
- version: json.version
307
- });
308
- await this.repository.updateOrCreate({
309
- values: {
310
- name,
311
- packageName,
312
- version: json.version
313
- },
314
- filterKeys: ["name"]
315
- });
316
- await sleep(1e3);
317
- await (0, import_helper.tsxRerunning)();
318
- }
319
- async add(plugin, options = {}, insert = false, isUpgrade = false) {
320
- if (!isUpgrade && this.has(plugin)) {
321
- const name = typeof plugin === "string" ? plugin : plugin.name;
322
- this.app.log.warn(`plugin [${name}] added`);
323
- return;
324
- }
325
- if (!options.name && typeof plugin === "string") {
326
- options.name = plugin;
327
- }
328
- try {
329
- if (typeof plugin === "string" && options.name && !options.packageName) {
330
- const packageName = await _PluginManager.getPackageName(options.name);
331
- options["packageName"] = packageName;
332
- }
333
- if (options.packageName) {
334
- const packageJson = await _PluginManager.getPackageJson(options.packageName);
335
- options["packageJson"] = packageJson;
336
- options["version"] = packageJson.version;
337
- }
338
- } catch (error) {
339
- console.error(error);
340
- }
341
- this.app.log.trace(`add plugin [${options.name}]`, {
342
- method: "add",
343
- submodule: "plugin-manager",
344
- name: options.name
345
- });
346
- let P;
347
- try {
348
- P = await _PluginManager.resolvePlugin(options.packageName || plugin, isUpgrade, !!options.packageName);
349
- } catch (error) {
350
- this.app.log.warn("plugin not found", error);
351
- return;
352
- }
353
- const instance = new P((0, import_helper.createAppProxy)(this.app), options);
354
- this.pluginInstances.set(P, instance);
355
- if (options.name) {
356
- this.pluginAliases.set(options.name, instance);
357
- }
358
- if (options.packageName) {
359
- this.pluginAliases.set(options.packageName, instance);
360
- }
361
- if (insert && options.name) {
362
- await this.repository.updateOrCreate({
363
- values: {
364
- ...options
365
- },
366
- filterKeys: ["name"]
367
- });
368
- }
369
- await instance.afterAdd();
370
- }
371
- /**
372
- * @internal
373
- */
374
- async initPlugins() {
375
- await this.initPresetPlugins();
376
- await this.initOtherPlugins();
377
- }
378
- /**
379
- * @internal
380
- */
381
- async loadCommands() {
382
- this.app.log.info("load commands");
383
- const items = await this.repository.find({
384
- filter: {
385
- enabled: true
386
- }
387
- });
388
- const packageNames = items.map((item) => item.packageName);
389
- const source = [];
390
- for (const packageName of packageNames) {
391
- const dirname = await (0, import_utils2.getPluginBasePath)(packageName);
392
- const directory = (0, import_path.join)(dirname, "server/commands/*." + ((0, import_path.basename)(dirname) === "src" ? "ts" : "js"));
393
- source.push(directory.replaceAll(import_path.sep, "/"));
394
- }
395
- for (const plugin of this.options.plugins || []) {
396
- if (typeof plugin === "string") {
397
- const { packageName } = await _PluginManager.parseName(plugin);
398
- const dirname = await (0, import_utils2.getPluginBasePath)(packageName);
399
- const directory = (0, import_path.join)(dirname, "server/commands/*." + ((0, import_path.basename)(dirname) === "src" ? "ts" : "js"));
400
- source.push(directory.replaceAll(import_path.sep, "/"));
401
- }
402
- }
403
- const files = await (0, import_fast_glob.default)(source, {
404
- ignore: ["**/*.d.ts"],
405
- cwd: process.env.NODE_MODULES_PATH
406
- });
407
- for (const file of files) {
408
- const callback = await (0, import_utils.importModule)(file);
409
- callback(this.app);
410
- }
411
- }
412
- async load(options = {}) {
413
- this.app.log.debug("loading plugins...");
414
- this.app.setMaintainingMessage("loading plugins...");
415
- const total = this.pluginInstances.size;
416
- let current = 0;
417
- for (const [P, plugin] of this.getPlugins()) {
418
- if (plugin.state.loaded) {
419
- continue;
420
- }
421
- const name = plugin.name || P.name;
422
- current += 1;
423
- this.app.setMaintainingMessage(`before load plugin [${name}], ${current}/${total}`);
424
- if (!plugin.enabled) {
425
- continue;
426
- }
427
- this.app.logger.trace(`before load plugin [${name}]`, { submodule: "plugin-manager", method: "load", name });
428
- await plugin.beforeLoad();
429
- }
430
- current = 0;
431
- for (const [P, plugin] of this.getPlugins()) {
432
- if (plugin.state.loaded) {
433
- continue;
434
- }
435
- const name = plugin.name || P.name;
436
- current += 1;
437
- this.app.setMaintainingMessage(`load plugin [${name}], ${current}/${total}`);
438
- if (!plugin.enabled) {
439
- continue;
440
- }
441
- await this.app.emitAsync("beforeLoadPlugin", plugin, options);
442
- this.app.logger.trace(`load plugin [${name}] `, { submodule: "plugin-manager", method: "load", name });
443
- await plugin.loadCollections();
444
- await plugin.load();
445
- plugin.state.loaded = true;
446
- await this.app.emitAsync("afterLoadPlugin", plugin, options);
447
- }
448
- this.app.log.debug("plugins loaded");
449
- this.app.setMaintainingMessage("plugins loaded");
450
- }
451
- async install(options = {}) {
452
- this.app.setMaintainingMessage("install plugins...");
453
- const total = this.pluginInstances.size;
454
- let current = 0;
455
- this.app.log.debug("call db.sync()");
456
- await this.app.db.sync();
457
- const toBeUpdated = [];
458
- for (const [P, plugin] of this.getPlugins()) {
459
- if (plugin.state.installing || plugin.state.installed) {
460
- continue;
461
- }
462
- const name = plugin.name || P.name;
463
- current += 1;
464
- if (!plugin.enabled) {
465
- continue;
466
- }
467
- plugin.state.installing = true;
468
- this.app.setMaintainingMessage(`before install plugin [${name}], ${current}/${total}`);
469
- await this.app.emitAsync("beforeInstallPlugin", plugin, options);
470
- this.app.logger.debug(`install plugin [${name}]...`);
471
- await plugin.install(options);
472
- toBeUpdated.push(name);
473
- plugin.state.installing = false;
474
- plugin.state.installed = true;
475
- plugin.installed = true;
476
- this.app.setMaintainingMessage(`after install plugin [${name}], ${current}/${total}`);
477
- await this.app.emitAsync("afterInstallPlugin", plugin, options);
478
- }
479
- await this.repository.update({
480
- filter: {
481
- name: toBeUpdated
482
- },
483
- values: {
484
- installed: true
485
- }
486
- });
487
- }
488
- async enable(nameOrPkg) {
489
- let pluginNames = nameOrPkg;
490
- if (nameOrPkg === "*") {
491
- const items = await this.repository.find();
492
- pluginNames = items.map((item) => item.name);
493
- }
494
- pluginNames = this.sort(pluginNames);
495
- this.app.log.debug(`enabling plugin ${pluginNames.join(",")}`);
496
- this.app.setMaintainingMessage(`enabling plugin ${pluginNames.join(",")}`);
497
- const toBeUpdated = [];
498
- for (const name of pluginNames) {
499
- const { name: pluginName } = await _PluginManager.parseName(name);
500
- console.log("pluginName", pluginName);
501
- const plugin = this.get(pluginName);
502
- if (!plugin) {
503
- throw new Error(`${pluginName} plugin does not exist`);
504
- }
505
- if (plugin.enabled) {
506
- continue;
507
- }
508
- await this.app.emitAsync("beforeEnablePlugin", pluginName);
509
- try {
510
- await plugin.beforeEnable();
511
- plugin.enabled = true;
512
- toBeUpdated.push(pluginName);
513
- } catch (error) {
514
- if (nameOrPkg === "*") {
515
- this.app.log.error(error.message);
516
- } else {
517
- throw error;
518
- }
519
- }
520
- }
521
- if (toBeUpdated.length === 0) {
522
- return;
523
- }
524
- await this.repository.update({
525
- filter: {
526
- name: toBeUpdated
527
- },
528
- values: {
529
- enabled: true
530
- }
531
- });
532
- try {
533
- await this.app.reload();
534
- this.app.log.debug(`syncing database in enable plugin ${toBeUpdated.join(",")}...`);
535
- this.app.setMaintainingMessage(`syncing database in enable plugin ${toBeUpdated.join(",")}...`);
536
- await this.app.db.sync();
537
- for (const pluginName of toBeUpdated) {
538
- const plugin = this.get(pluginName);
539
- if (!plugin.installed) {
540
- this.app.log.debug(`installing plugin ${pluginName}...`);
541
- this.app.setMaintainingMessage(`installing plugin ${pluginName}...`);
542
- await plugin.install();
543
- plugin.installed = true;
544
- }
545
- }
546
- await this.repository.update({
547
- filter: {
548
- name: toBeUpdated
549
- },
550
- values: {
551
- installed: true
552
- }
553
- });
554
- for (const pluginName of toBeUpdated) {
555
- const plugin = this.get(pluginName);
556
- this.app.log.debug(`emit afterEnablePlugin event...`);
557
- await plugin.afterEnable();
558
- await this.app.emitAsync("afterEnablePlugin", pluginName);
559
- this.app.log.debug(`afterEnablePlugin event emitted`);
560
- }
561
- await this.app.tryReloadOrRestart();
562
- } catch (error) {
563
- await this.repository.update({
564
- filter: {
565
- name: toBeUpdated
566
- },
567
- values: {
568
- enabled: false,
569
- installed: false
570
- }
571
- });
572
- await this.app.tryReloadOrRestart({
573
- recover: true
574
- });
575
- throw error;
576
- }
577
- }
578
- async disable(name) {
579
- const pluginNames = import_lodash.default.castArray(name);
580
- this.app.log.debug(`disabling plugin ${pluginNames.join(",")}`);
581
- this.app.setMaintainingMessage(`disabling plugin ${pluginNames.join(",")}`);
582
- const toBeUpdated = [];
583
- for (const name2 of pluginNames) {
584
- const { name: pluginName } = await _PluginManager.parseName(name2);
585
- const plugin = this.get(pluginName);
586
- if (!plugin) {
587
- throw new Error(`${pluginName} plugin does not exist`);
588
- }
589
- if (!plugin.enabled) {
590
- continue;
591
- }
592
- await this.app.emitAsync("beforeDisablePlugin", pluginName);
593
- await plugin.beforeDisable();
594
- plugin.enabled = false;
595
- toBeUpdated.push(pluginName);
596
- }
597
- if (toBeUpdated.length === 0) {
598
- return;
599
- }
600
- await this.repository.update({
601
- filter: {
602
- name: toBeUpdated
603
- },
604
- values: {
605
- enabled: false
606
- }
607
- });
608
- try {
609
- await this.app.tryReloadOrRestart();
610
- for (const pluginName of pluginNames) {
611
- const plugin = this.get(pluginName);
612
- this.app.log.debug(`emit afterDisablePlugin event...`);
613
- await plugin.afterDisable();
614
- await this.app.emitAsync("afterDisablePlugin", pluginName);
615
- this.app.log.debug(`afterDisablePlugin event emitted`);
616
- }
617
- } catch (error) {
618
- await this.repository.update({
619
- filter: {
620
- name: toBeUpdated
621
- },
622
- values: {
623
- enabled: true
624
- }
625
- });
626
- await this.app.tryReloadOrRestart({
627
- recover: true
628
- });
629
- throw error;
630
- }
631
- }
632
- async remove(name, options) {
633
- const names = import_lodash.default.castArray(name);
634
- const pluginNames = [];
635
- const records = [];
636
- for (const nameOrPkg of names) {
637
- const { name: name2, packageName } = await _PluginManager.parseName(nameOrPkg);
638
- pluginNames.push(name2);
639
- records.push({
640
- name: name2,
641
- packageName
642
- });
643
- }
644
- const removeDir = /* @__PURE__ */ __name(async () => {
645
- await Promise.all(
646
- records.map(async (plugin) => {
647
- const dir = (0, import_path.resolve)(process.env.NODE_MODULES_PATH, plugin.packageName);
648
- try {
649
- const realDir = await import_fs.default.promises.realpath(dir);
650
- this.app.log.debug(`rm -rf ${realDir}`);
651
- return import_fs.default.promises.rm(realDir, { force: true, recursive: true });
652
- } catch (error) {
653
- return false;
654
- }
655
- })
656
- );
657
- await (0, import_execa.default)("yarn", ["nocobase", "postinstall"]);
658
- }, "removeDir");
659
- if (options == null ? void 0 : options.force) {
660
- await this.repository.destroy({
661
- filter: {
662
- name: pluginNames
663
- }
664
- });
665
- this.app.log.warn(`force remove plugins ${pluginNames.join(",")}`);
666
- } else {
667
- await this.app.load();
668
- for (const pluginName of pluginNames) {
669
- const plugin = this.get(pluginName);
670
- if (!plugin) {
671
- continue;
672
- }
673
- if (plugin.enabled) {
674
- throw new Error(`plugin is enabled [${pluginName}]`);
675
- }
676
- await plugin.beforeRemove();
677
- }
678
- await this.repository.destroy({
679
- filter: {
680
- name: pluginNames
681
- }
682
- });
683
- const plugins = [];
684
- for (const pluginName of pluginNames) {
685
- const plugin = this.get(pluginName);
686
- if (!plugin) {
687
- continue;
688
- }
689
- plugins.push(plugin);
690
- this.del(pluginName);
691
- await plugin.afterRemove();
692
- }
693
- if (await this.app.isStarted()) {
694
- await this.app.tryReloadOrRestart();
695
- }
696
- }
697
- if (options == null ? void 0 : options.removeDir) {
698
- await removeDir();
699
- }
700
- await (0, import_execa.default)("yarn", ["nocobase", "refresh"], {
701
- env: process.env
702
- });
703
- }
704
- /**
705
- * @internal
706
- */
707
- async addViaCLI(urlOrName, options, emitStartedEvent = true) {
708
- if (Array.isArray(urlOrName)) {
709
- for (const packageName of urlOrName) {
710
- await this.addViaCLI(packageName, import_lodash.default.omit(options, "name"), false);
711
- }
712
- await this.app.emitStartedEvent();
713
- await (0, import_execa.default)("yarn", ["nocobase", "postinstall"]);
714
- return;
715
- }
716
- if ((0, import_utils.isURL)(urlOrName)) {
717
- await this.addByCompressedFileUrl(
718
- {
719
- ...options,
720
- compressedFileUrl: urlOrName
721
- },
722
- emitStartedEvent
723
- );
724
- } else if (await (0, import_plugin_symlink.fsExists)(urlOrName)) {
725
- await this.addByCompressedFileUrl(
726
- {
727
- ...options,
728
- compressedFileUrl: urlOrName
729
- },
730
- emitStartedEvent
731
- );
732
- } else if (options == null ? void 0 : options.registry) {
733
- const { name, packageName } = await _PluginManager.parseName(urlOrName);
734
- options["name"] = name;
735
- await this.addByNpm(
736
- {
737
- ...options,
738
- packageName
739
- },
740
- emitStartedEvent
741
- );
742
- } else {
743
- const { name, packageName } = await _PluginManager.parseName(urlOrName);
744
- const opts = {
745
- ...options,
746
- name,
747
- packageName
748
- };
749
- await this.repository.findOne({ filter: { packageName } });
750
- await this.add(name, opts, true);
751
- }
752
- if (emitStartedEvent) {
753
- await this.app.emitStartedEvent();
754
- await (0, import_execa.default)("yarn", ["nocobase", "postinstall"]);
755
- }
756
- }
757
- /**
758
- * @internal
759
- */
760
- async addByNpm(options, throwError = true) {
761
- let { name = "", registry, packageName, authToken } = options;
762
- name = name.trim();
763
- registry = registry.trim();
764
- packageName = packageName.trim();
765
- authToken = authToken == null ? void 0 : authToken.trim();
766
- const { compressedFileUrl } = await (0, import_utils2.getPluginInfoByNpm)({
767
- packageName,
768
- registry,
769
- authToken
770
- });
771
- return this.addByCompressedFileUrl({ name, compressedFileUrl, registry, authToken, type: "npm" }, throwError);
772
- }
773
- /**
774
- * @internal
775
- */
776
- async addByFile(options, throwError = true) {
777
- const { file, authToken } = options;
778
- const { packageName, tempFile, tempPackageContentDir } = await (0, import_utils2.downloadAndUnzipToTempDir)(file, authToken);
779
- const { name } = await _PluginManager.parseName(packageName);
780
- if (this.has(name)) {
781
- await (0, import_utils2.removeTmpDir)(tempFile, tempPackageContentDir);
782
- if (throwError) {
783
- throw new Error(`plugin name [${name}] already exists`);
784
- } else {
785
- this.app.log.warn(`plugin name [${name}] already exists`);
786
- return;
787
- }
788
- }
789
- await (0, import_utils2.copyTempPackageToStorageAndLinkToNodeModules)(tempFile, tempPackageContentDir, packageName);
790
- return this.add(name, { packageName }, true);
791
- }
792
- /**
793
- * @internal
794
- */
795
- async addByCompressedFileUrl(options, throwError = true) {
796
- const { compressedFileUrl, authToken } = options;
797
- const { packageName, tempFile, tempPackageContentDir } = await (0, import_utils2.downloadAndUnzipToTempDir)(
798
- compressedFileUrl,
799
- authToken
800
- );
801
- const { name } = await _PluginManager.parseName(packageName);
802
- if (this.has(name)) {
803
- await (0, import_utils2.removeTmpDir)(tempFile, tempPackageContentDir);
804
- if (throwError) {
805
- throw new Error(`plugin name [${name}] already exists`);
806
- } else {
807
- this.app.log.warn(`plugin name [${name}] already exists`);
808
- return;
809
- }
810
- }
811
- await (0, import_utils2.copyTempPackageToStorageAndLinkToNodeModules)(tempFile, tempPackageContentDir, packageName);
812
- return this.add(name, { packageName }, true);
813
- }
814
- async update(nameOrPkg, options, emitStartedEvent = true) {
815
- const upgrade = /* @__PURE__ */ __name(async () => {
816
- if (!await this.app.isStarted()) {
817
- this.app.log.debug("app upgrading");
818
- await this.app.runCommand("upgrade");
819
- await (0, import_helper.tsxRerunning)();
820
- await (0, import_execa.default)("yarn", ["nocobase", "pm2-restart"], {
821
- env: process.env
822
- });
823
- return;
824
- }
825
- const file = (0, import_path.resolve)(process.cwd(), "storage/app-upgrading");
826
- await import_fs.default.promises.writeFile(file, "", "utf-8");
827
- await (0, import_helper.tsxRerunning)();
828
- await (0, import_execa.default)("yarn", ["nocobase", "pm2-restart"], {
829
- env: process.env
830
- });
831
- }, "upgrade");
832
- if (Array.isArray(nameOrPkg)) {
833
- for (const name of nameOrPkg) {
834
- await this.update(name, { ...options }, false);
835
- }
836
- return upgrade();
837
- }
838
- const opts = { ...options };
839
- if ((0, import_utils.isURL)(nameOrPkg)) {
840
- opts.compressedFileUrl = nameOrPkg;
841
- } else if (await (0, import_plugin_symlink.fsExists)(nameOrPkg)) {
842
- opts.compressedFileUrl = nameOrPkg;
843
- }
844
- if (opts.compressedFileUrl) {
845
- await this.upgradeByCompressedFileUrl(opts);
846
- } else {
847
- const { name, packageName } = await _PluginManager.parseName(nameOrPkg);
848
- await this.upgradeByNpm({ ...opts, packageName, name });
849
- }
850
- if (emitStartedEvent) {
851
- await upgrade();
852
- }
853
- }
854
- /**
855
- * @internal
856
- */
857
- async upgradeByNpm(values) {
858
- var _a, _b, _c;
859
- const name = values.name;
860
- if (!await this.repository.has(name)) {
861
- throw new Error(`plugin name [${name}] not exists`);
862
- }
863
- if (!values.registry) {
864
- throw new Error(`plugin name [${name}] not installed by npm`);
865
- }
866
- const version = (_a = values.version) == null ? void 0 : _a.trim();
867
- const registry = (_b = values.registry) == null ? void 0 : _b.trim();
868
- const authToken = (_c = values.authToken) == null ? void 0 : _c.trim();
869
- const { compressedFileUrl } = await (0, import_utils2.getPluginInfoByNpm)({
870
- packageName: values.packageName,
871
- registry,
872
- authToken,
873
- version
874
- });
875
- return this.upgradeByCompressedFileUrl({
876
- compressedFileUrl,
877
- name,
878
- version,
879
- registry,
880
- authToken
881
- });
882
- }
883
- /**
884
- * @internal
885
- */
886
- async upgradeByCompressedFileUrl(options) {
887
- const { compressedFileUrl, authToken } = options;
888
- const { packageName, version } = await (0, import_utils2.updatePluginByCompressedFileUrl)({
889
- compressedFileUrl,
890
- authToken,
891
- repository: this.repository
892
- });
893
- const { name } = await _PluginManager.parseName(packageName);
894
- await this.add(name, { name, version, packageName }, true, true);
895
- }
896
- /**
897
- * @internal
898
- */
899
- getNameByPackageName(packageName) {
900
- const prefixes = _PluginManager.getPluginPkgPrefix();
901
- const prefix = prefixes.find((prefix2) => packageName.startsWith(prefix2));
902
- if (!prefix) {
903
- throw new Error(
904
- `package name [${packageName}] invalid, just support ${prefixes.join(
905
- ", "
906
- )}. You can modify process.env.PLUGIN_PACKAGE_PREFIX add more prefix.`
907
- );
908
- }
909
- return packageName.replace(prefix, "");
910
- }
911
- async list(options = {}) {
912
- const { locale = "en-US", isPreset = false } = options;
913
- return Promise.all(
914
- [...this.getPlugins().keys()].map((name) => {
915
- const plugin = this.get(name);
916
- if (!isPreset && plugin.options.isPreset) {
917
- return;
918
- }
919
- return plugin.toJSON({ locale });
920
- }).filter(Boolean)
921
- );
922
- }
923
- /**
924
- * @internal
925
- */
926
- async getNpmVersionList(name) {
927
- const plugin = this.get(name);
928
- const npmInfo = await (0, import_utils2.getNpmInfo)(plugin.options.packageName, plugin.options.registry, plugin.options.authToken);
929
- return Object.keys(npmInfo.versions);
930
- }
931
- /**
932
- * @internal
933
- */
934
- async loadPresetMigrations() {
935
- const migrations = {
936
- beforeLoad: [],
937
- afterSync: [],
938
- afterLoad: []
939
- };
940
- for (const [P, plugin] of this.getPlugins()) {
941
- if (!plugin.isPreset) {
942
- continue;
943
- }
944
- const { beforeLoad, afterSync, afterLoad } = await plugin.loadMigrations();
945
- migrations.beforeLoad.push(...beforeLoad);
946
- migrations.afterSync.push(...afterSync);
947
- migrations.afterLoad.push(...afterLoad);
948
- }
949
- return {
950
- beforeLoad: {
951
- up: async () => {
952
- this.app.log.debug("run preset migrations(beforeLoad)");
953
- const migrator = this.app.db.createMigrator({ migrations: migrations.beforeLoad });
954
- await migrator.up();
955
- }
956
- },
957
- afterSync: {
958
- up: async () => {
959
- this.app.log.debug("run preset migrations(afterSync)");
960
- const migrator = this.app.db.createMigrator({ migrations: migrations.afterSync });
961
- await migrator.up();
962
- }
963
- },
964
- afterLoad: {
965
- up: async () => {
966
- this.app.log.debug("run preset migrations(afterLoad)");
967
- const migrator = this.app.db.createMigrator({ migrations: migrations.afterLoad });
968
- await migrator.up();
969
- }
970
- }
971
- };
972
- }
973
- /**
974
- * @internal
975
- */
976
- async loadOtherMigrations() {
977
- const migrations = {
978
- beforeLoad: [],
979
- afterSync: [],
980
- afterLoad: []
981
- };
982
- for (const [P, plugin] of this.getPlugins()) {
983
- if (plugin.isPreset) {
984
- continue;
985
- }
986
- if (!plugin.enabled) {
987
- continue;
988
- }
989
- const { beforeLoad, afterSync, afterLoad } = await plugin.loadMigrations();
990
- migrations.beforeLoad.push(...beforeLoad);
991
- migrations.afterSync.push(...afterSync);
992
- migrations.afterLoad.push(...afterLoad);
993
- }
994
- return {
995
- beforeLoad: {
996
- up: async () => {
997
- this.app.log.debug("run others migrations(beforeLoad)");
998
- const migrator = this.app.db.createMigrator({ migrations: migrations.beforeLoad });
999
- await migrator.up();
1000
- }
1001
- },
1002
- afterSync: {
1003
- up: async () => {
1004
- this.app.log.debug("run others migrations(afterSync)");
1005
- const migrator = this.app.db.createMigrator({ migrations: migrations.afterSync });
1006
- await migrator.up();
1007
- }
1008
- },
1009
- afterLoad: {
1010
- up: async () => {
1011
- this.app.log.debug("run others migrations(afterLoad)");
1012
- const migrator = this.app.db.createMigrator({ migrations: migrations.afterLoad });
1013
- await migrator.up();
1014
- }
1015
- }
1016
- };
1017
- }
1018
- /**
1019
- * @internal
1020
- */
1021
- async loadPresetPlugins() {
1022
- await this.initPresetPlugins();
1023
- await this.load();
1024
- }
1025
- async upgrade() {
1026
- this.app.log.info("run upgrade");
1027
- const toBeUpdated = [];
1028
- for (const [P, plugin] of this.getPlugins()) {
1029
- if (plugin.state.upgraded) {
1030
- continue;
1031
- }
1032
- if (!plugin.enabled) {
1033
- continue;
1034
- }
1035
- if (!plugin.isPreset && !plugin.installed) {
1036
- this.app.log.info(`install built-in plugin [${plugin.name}]`);
1037
- await plugin.install();
1038
- toBeUpdated.push(plugin.name);
1039
- }
1040
- this.app.log.debug(`upgrade plugin [${plugin.name}]`);
1041
- await plugin.upgrade();
1042
- plugin.state.upgraded = true;
1043
- }
1044
- await this.repository.update({
1045
- filter: {
1046
- name: toBeUpdated
1047
- },
1048
- values: {
1049
- installed: true
1050
- }
1051
- });
1052
- }
1053
- /**
1054
- * @internal
1055
- */
1056
- async initOtherPlugins() {
1057
- if (this["_initOtherPlugins"]) {
1058
- return;
1059
- }
1060
- await this.repository.init();
1061
- this["_initOtherPlugins"] = true;
1062
- }
1063
- /**
1064
- * @internal
1065
- */
1066
- async initPresetPlugins() {
1067
- if (this["_initPresetPlugins"]) {
1068
- return;
1069
- }
1070
- for (const plugin of this.options.plugins) {
1071
- const [p, opts = {}] = Array.isArray(plugin) ? plugin : [plugin];
1072
- await this.add(p, { enabled: true, isPreset: true, ...opts });
1073
- }
1074
- this["_initPresetPlugins"] = true;
1075
- }
1076
- sort(names) {
1077
- var _a, _b, _c;
1078
- const pluginNames = import_lodash.default.castArray(names);
1079
- if (pluginNames.length === 1) {
1080
- return pluginNames;
1081
- }
1082
- const sorter = new import_topo.default.Sorter();
1083
- for (const pluginName of pluginNames) {
1084
- const plugin = this.get(pluginName);
1085
- const peerDependencies = Object.keys(((_b = (_a = plugin.options) == null ? void 0 : _a.packageJson) == null ? void 0 : _b.peerDependencies) || {});
1086
- sorter.add(pluginName, { after: peerDependencies, group: ((_c = plugin.options) == null ? void 0 : _c.packageName) || pluginName });
1087
- }
1088
- return sorter.nodes;
1089
- }
1090
- };
1091
- __name(_PluginManager, "PluginManager");
1092
- __publicField(_PluginManager, "parsedNames", {});
1093
- let PluginManager = _PluginManager;
1094
- var plugin_manager_default = PluginManager;
1095
- // Annotate the CommonJS export names for ESM import in node:
1096
- 0 && (module.exports = {
1097
- AddPresetError,
1098
- PluginManager,
1099
- sleep
1100
- });