@nocobase/plugin-multi-app-manager 0.9.1-alpha.2 → 0.9.2-alpha.2

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.
@@ -0,0 +1,290 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.PluginMultiAppManager = void 0;
7
+ function _database() {
8
+ const data = _interopRequireDefault(require("@nocobase/database"));
9
+ _database = function _database() {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _server() {
15
+ const data = require("@nocobase/server");
16
+ _server = function _server() {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _lodash() {
22
+ const data = _interopRequireDefault(require("lodash"));
23
+ _lodash = function _lodash() {
24
+ return data;
25
+ };
26
+ return data;
27
+ }
28
+ function path() {
29
+ const data = _interopRequireWildcard(require("path"));
30
+ path = function path() {
31
+ return data;
32
+ };
33
+ return data;
34
+ }
35
+ var _application = require("./models/application");
36
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
37
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
38
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
39
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
40
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
41
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
42
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
43
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
44
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
45
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
46
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
47
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
48
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
49
+ const defaultDbCreator = /*#__PURE__*/function () {
50
+ var _ref = _asyncToGenerator(function* (app) {
51
+ const databaseOptions = app.options.database;
52
+ const host = databaseOptions.host,
53
+ port = databaseOptions.port,
54
+ username = databaseOptions.username,
55
+ password = databaseOptions.password,
56
+ dialect = databaseOptions.dialect,
57
+ database = databaseOptions.database;
58
+ if (dialect === 'mysql') {
59
+ const mysql = require('mysql2/promise');
60
+ const connection = yield mysql.createConnection({
61
+ host,
62
+ port,
63
+ user: username,
64
+ password
65
+ });
66
+ yield connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
67
+ yield connection.close();
68
+ }
69
+ if (dialect === 'postgres') {
70
+ const _require = require('pg'),
71
+ Client = _require.Client;
72
+ const client = new Client({
73
+ host,
74
+ port,
75
+ user: username,
76
+ password,
77
+ database: 'postgres'
78
+ });
79
+ yield client.connect();
80
+ try {
81
+ yield client.query(`CREATE DATABASE "${database}"`);
82
+ } catch (e) {}
83
+ yield client.end();
84
+ }
85
+ });
86
+ return function defaultDbCreator(_x) {
87
+ return _ref.apply(this, arguments);
88
+ };
89
+ }();
90
+ const defaultAppOptionsFactory = (appName, mainApp) => {
91
+ const rawDatabaseOptions = PluginMultiAppManager.getDatabaseConfig(mainApp);
92
+ if (rawDatabaseOptions.dialect === 'sqlite') {
93
+ const mainAppStorage = rawDatabaseOptions.storage;
94
+ if (mainAppStorage !== ':memory:') {
95
+ const mainStorageDir = path().dirname(mainAppStorage);
96
+ rawDatabaseOptions.storage = path().join(mainStorageDir, `${appName}.sqlite`);
97
+ }
98
+ } else {
99
+ rawDatabaseOptions.database = appName;
100
+ }
101
+ return {
102
+ database: _objectSpread(_objectSpread({}, rawDatabaseOptions), {}, {
103
+ tablePrefix: ''
104
+ }),
105
+ plugins: ['nocobase'],
106
+ resourcer: {
107
+ prefix: '/api'
108
+ }
109
+ };
110
+ };
111
+ class PluginMultiAppManager extends _server().Plugin {
112
+ constructor(...args) {
113
+ super(...args);
114
+ this.appDbCreator = defaultDbCreator;
115
+ this.appOptionsFactory = defaultAppOptionsFactory;
116
+ }
117
+ setAppOptionsFactory(factory) {
118
+ this.appOptionsFactory = factory;
119
+ }
120
+ setAppDbCreator(appDbCreator) {
121
+ this.appDbCreator = appDbCreator;
122
+ }
123
+ static getDatabaseConfig(app) {
124
+ const oldConfig = app.options.database instanceof _database().default ? app.options.database.options : app.options.database;
125
+ return _lodash().default.cloneDeep(_lodash().default.omit(oldConfig, ['migrator']));
126
+ }
127
+ beforeLoad() {
128
+ this.db.registerModels({
129
+ ApplicationModel: _application.ApplicationModel
130
+ });
131
+ }
132
+ load() {
133
+ var _this = this;
134
+ return _asyncToGenerator(function* () {
135
+ _this.app.appManager.setAppSelector( /*#__PURE__*/function () {
136
+ var _ref2 = _asyncToGenerator(function* (req) {
137
+ if (req.headers['x-app']) {
138
+ return req.headers['x-app'];
139
+ }
140
+ if (req.headers['x-hostname']) {
141
+ const repository = _this.db.getRepository('applications');
142
+ if (!repository) {
143
+ return null;
144
+ }
145
+ const appInstance = yield repository.findOne({
146
+ filter: {
147
+ cname: req.headers['x-hostname']
148
+ }
149
+ });
150
+ if (appInstance) {
151
+ return appInstance.name;
152
+ }
153
+ }
154
+ return null;
155
+ });
156
+ return function (_x2) {
157
+ return _ref2.apply(this, arguments);
158
+ };
159
+ }());
160
+ yield _this.db.import({
161
+ directory: (0, path().resolve)(__dirname, 'collections')
162
+ });
163
+ // after application created
164
+ _this.db.on('applications.afterCreateWithAssociations', /*#__PURE__*/function () {
165
+ var _ref3 = _asyncToGenerator(function* (model, options) {
166
+ const transaction = options.transaction;
167
+ const subApp = model.registerToMainApp(_this.app, {
168
+ appOptionsFactory: _this.appOptionsFactory
169
+ });
170
+ // create database
171
+ yield _this.appDbCreator(subApp, transaction);
172
+ // reload subApp plugin
173
+ yield subApp.reload();
174
+ // sync subApp collections
175
+ yield subApp.db.sync();
176
+ // install subApp
177
+ yield subApp.install();
178
+ yield subApp.reload();
179
+ });
180
+ return function (_x3, _x4) {
181
+ return _ref3.apply(this, arguments);
182
+ };
183
+ }());
184
+ _this.db.on('applications.afterDestroy', /*#__PURE__*/function () {
185
+ var _ref4 = _asyncToGenerator(function* (model) {
186
+ yield _this.app.appManager.removeApplication(model.get('name'));
187
+ });
188
+ return function (_x5) {
189
+ return _ref4.apply(this, arguments);
190
+ };
191
+ }());
192
+ // lazy load application
193
+ // if application not in appManager, load it from database
194
+ _this.app.on('beforeGetApplication', /*#__PURE__*/function () {
195
+ var _ref5 = _asyncToGenerator(function* ({
196
+ appManager,
197
+ name,
198
+ options
199
+ }) {
200
+ if (appManager.applications.has(name)) {
201
+ return;
202
+ }
203
+ const applicationRecord = yield _this.app.db.getRepository('applications').findOne({
204
+ filter: {
205
+ name
206
+ }
207
+ });
208
+ if (!applicationRecord) {
209
+ return;
210
+ }
211
+ const subApp = yield applicationRecord.registerToMainApp(_this.app, {
212
+ appOptionsFactory: _this.appOptionsFactory
213
+ });
214
+ // must skip load on upgrade
215
+ if (!(options === null || options === void 0 ? void 0 : options.upgrading)) {
216
+ yield subApp.load();
217
+ }
218
+ });
219
+ return function (_x6) {
220
+ return _ref5.apply(this, arguments);
221
+ };
222
+ }());
223
+ _this.app.on('afterUpgrade', /*#__PURE__*/function () {
224
+ var _ref6 = _asyncToGenerator(function* (app, options) {
225
+ const cliArgs = options === null || options === void 0 ? void 0 : options.cliArgs;
226
+ const repository = _this.db.getRepository('applications');
227
+ const instances = yield repository.find();
228
+ var _iterator = _createForOfIteratorHelper(instances),
229
+ _step;
230
+ try {
231
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
232
+ const instance = _step.value;
233
+ const subApp = yield _this.app.appManager.getApplication(instance.name, {
234
+ upgrading: true
235
+ });
236
+ try {
237
+ console.log(`${instance.name}: upgrading...`);
238
+ yield subApp.upgrade({
239
+ cliArgs
240
+ });
241
+ yield subApp.stop({
242
+ cliArgs
243
+ });
244
+ } catch (error) {
245
+ console.log(`${instance.name}: upgrade failed`);
246
+ _this.app.logger.error(error);
247
+ console.error(error);
248
+ }
249
+ }
250
+ } catch (err) {
251
+ _iterator.e(err);
252
+ } finally {
253
+ _iterator.f();
254
+ }
255
+ });
256
+ return function (_x7, _x8) {
257
+ return _ref6.apply(this, arguments);
258
+ };
259
+ }());
260
+ _this.app.resourcer.registerActionHandlers({
261
+ 'applications:listPinned': function () {
262
+ var _applicationsListPinned = _asyncToGenerator(function* (ctx, next) {
263
+ const items = yield _this.db.getRepository('applications').find({
264
+ filter: {
265
+ pinned: true
266
+ }
267
+ });
268
+ ctx.body = items;
269
+ });
270
+ function applicationsListPinned(_x9, _x10) {
271
+ return _applicationsListPinned.apply(this, arguments);
272
+ }
273
+ return applicationsListPinned;
274
+ }()
275
+ });
276
+ _this.app.acl.allow('applications', 'listPinned', 'loggedIn');
277
+ _this.app.acl.registerSnippet({
278
+ name: `
279
+ pm.$;
280
+ {
281
+ this.name;
282
+ }
283
+ .
284
+ applications`,
285
+ actions: ['applications:*']
286
+ });
287
+ })();
288
+ }
289
+ }
290
+ exports.PluginMultiAppManager = PluginMultiAppManager;
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@nocobase/plugin-multi-app-manager",
3
- "version": "0.9.1-alpha.2",
3
+ "version": "0.9.2-alpha.2",
4
4
  "description": "",
5
5
  "license": "AGPL-3.0",
6
6
  "main": "./lib/index.js",
7
7
  "types": "./lib/index.d.ts",
8
8
  "dependencies": {
9
- "@nocobase/server": "0.9.1-alpha.2"
9
+ "@nocobase/server": "0.9.2-alpha.2"
10
10
  },
11
- "gitHead": "d588a68eca4feed4642a4cb317301011266fe5c9"
11
+ "gitHead": "1a0de6908b2b1854bdf434fcafa8909cb65bb8a3"
12
12
  }
package/server.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ // @ts-nocheck
2
+ export * from './lib/server';
3
+ export { default } from './lib/server';
4
+
package/server.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
4
+
5
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
6
+
7
+ var _index = _interopRequireWildcard(require("./lib/server"));
8
+
9
+ Object.defineProperty(exports, "__esModule", {
10
+ value: true
11
+ });
12
+ var _exportNames = {};
13
+ Object.defineProperty(exports, "default", {
14
+ enumerable: true,
15
+ get: function get() {
16
+ return _index.default;
17
+ }
18
+ });
19
+
20
+ Object.keys(_index).forEach(function (key) {
21
+ if (key === "default" || key === "__esModule") return;
22
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
23
+ if (key in exports && exports[key] === _index[key]) return;
24
+ Object.defineProperty(exports, key, {
25
+ enumerable: true,
26
+ get: function get() {
27
+ return _index[key];
28
+ }
29
+ });
30
+ });
@@ -1,94 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.ApplicationModel = void 0;
7
-
8
- function _database() {
9
- const data = require("@nocobase/database");
10
-
11
- _database = function _database() {
12
- return data;
13
- };
14
-
15
- return data;
16
- }
17
-
18
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
19
-
20
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
21
-
22
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
23
-
24
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
25
-
26
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
27
-
28
- class ApplicationModel extends _database().Model {
29
- static handleAppStart(mainApp, app, options) {
30
- return _asyncToGenerator(function* () {
31
- yield mainApp.emitAsync('beforeSubAppLoad', {
32
- mainApp,
33
- subApp: app
34
- });
35
- yield app.load();
36
-
37
- if (!(yield app.isInstalled())) {
38
- yield app.db.sync();
39
- yield app.install(); // emit an event on mainApp
40
- // current if you add listener on subApp through `subApp.on('afterInstall')` , it will be clear after subApp installed
41
-
42
- yield mainApp.emitAsync('afterSubAppInstalled', {
43
- mainApp,
44
- subApp: app
45
- });
46
- }
47
-
48
- yield app.start();
49
- })();
50
- }
51
-
52
- registerToMainApp(mainApp, options) {
53
- var _this = this;
54
-
55
- return _asyncToGenerator(function* () {
56
- const appName = _this.get('name');
57
-
58
- const appOptions = _this.get('options') || {};
59
- const AppModel = _this.constructor;
60
- const app = mainApp.appManager.createApplication(appName, _objectSpread(_objectSpread(_objectSpread({}, options.appOptionsFactory(appName, mainApp)), appOptions), {}, {
61
- name: appName
62
- }));
63
- const isInstalled = yield _asyncToGenerator(function* () {
64
- try {
65
- return yield app.isInstalled();
66
- } catch (e) {
67
- if (e.message.includes('does not exist') || e.message.includes('Unknown database')) {
68
- return false;
69
- }
70
-
71
- throw e;
72
- }
73
- })();
74
-
75
- if (!isInstalled) {
76
- yield options.dbCreator(app);
77
- }
78
-
79
- yield AppModel.handleAppStart(mainApp, app, options);
80
- yield AppModel.update({
81
- status: 'running'
82
- }, {
83
- transaction: options.transaction,
84
- where: {
85
- [AppModel.primaryKeyAttribute]: _this.get(AppModel.primaryKeyAttribute)
86
- },
87
- hooks: false
88
- });
89
- })();
90
- }
91
-
92
- }
93
-
94
- exports.ApplicationModel = ApplicationModel;
package/lib/server.js DELETED
@@ -1,250 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.PluginMultiAppManager = void 0;
7
-
8
- function _server() {
9
- const data = require("@nocobase/server");
10
-
11
- _server = function _server() {
12
- return data;
13
- };
14
-
15
- return data;
16
- }
17
-
18
- function path() {
19
- const data = _interopRequireWildcard(require("path"));
20
-
21
- path = function path() {
22
- return data;
23
- };
24
-
25
- return data;
26
- }
27
-
28
- var _application = require("./models/application");
29
-
30
- function _database() {
31
- const data = _interopRequireDefault(require("@nocobase/database"));
32
-
33
- _database = function _database() {
34
- return data;
35
- };
36
-
37
- return data;
38
- }
39
-
40
- function _lodash() {
41
- const data = _interopRequireDefault(require("lodash"));
42
-
43
- _lodash = function _lodash() {
44
- return data;
45
- };
46
-
47
- return data;
48
- }
49
-
50
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
51
-
52
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
53
-
54
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
55
-
56
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
57
-
58
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
59
-
60
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
61
-
62
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
63
-
64
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
65
-
66
- const defaultDbCreator = /*#__PURE__*/function () {
67
- var _ref = _asyncToGenerator(function* (app) {
68
- const databaseOptions = app.options.database;
69
- const host = databaseOptions.host,
70
- port = databaseOptions.port,
71
- username = databaseOptions.username,
72
- password = databaseOptions.password,
73
- dialect = databaseOptions.dialect,
74
- database = databaseOptions.database;
75
-
76
- if (dialect === 'mysql') {
77
- const mysql = require('mysql2/promise');
78
-
79
- const connection = yield mysql.createConnection({
80
- host,
81
- port,
82
- user: username,
83
- password
84
- });
85
- yield connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
86
- yield connection.close();
87
- }
88
-
89
- if (dialect === 'postgres') {
90
- const _require = require('pg'),
91
- Client = _require.Client;
92
-
93
- const client = new Client({
94
- host,
95
- port,
96
- user: username,
97
- password,
98
- database: 'postgres'
99
- });
100
- yield client.connect();
101
-
102
- try {
103
- yield client.query(`CREATE DATABASE "${database}"`);
104
- } catch (e) {}
105
-
106
- yield client.end();
107
- }
108
- });
109
-
110
- return function defaultDbCreator(_x) {
111
- return _ref.apply(this, arguments);
112
- };
113
- }();
114
-
115
- const defaultAppOptionsFactory = (appName, mainApp) => {
116
- const rawDatabaseOptions = PluginMultiAppManager.getDatabaseConfig(mainApp);
117
-
118
- if (rawDatabaseOptions.dialect === 'sqlite') {
119
- const mainAppStorage = rawDatabaseOptions.storage;
120
-
121
- if (mainAppStorage !== ':memory:') {
122
- const mainStorageDir = path().dirname(mainAppStorage);
123
- rawDatabaseOptions.storage = path().join(mainStorageDir, `${appName}.sqlite`);
124
- }
125
- } else {
126
- rawDatabaseOptions.database = appName;
127
- }
128
-
129
- return {
130
- database: _objectSpread(_objectSpread({}, rawDatabaseOptions), {}, {
131
- tablePrefix: ''
132
- }),
133
- plugins: ['nocobase'],
134
- resourcer: {
135
- prefix: '/api'
136
- }
137
- };
138
- };
139
-
140
- class PluginMultiAppManager extends _server().Plugin {
141
- constructor(...args) {
142
- super(...args);
143
- this.appDbCreator = defaultDbCreator;
144
- this.appOptionsFactory = defaultAppOptionsFactory;
145
- }
146
-
147
- setAppOptionsFactory(factory) {
148
- this.appOptionsFactory = factory;
149
- }
150
-
151
- setAppDbCreator(appDbCreator) {
152
- this.appDbCreator = appDbCreator;
153
- }
154
-
155
- static getDatabaseConfig(app) {
156
- const oldConfig = app.options.database instanceof _database().default ? app.options.database.options : app.options.database;
157
- return _lodash().default.cloneDeep(_lodash().default.omit(oldConfig, ['migrator']));
158
- }
159
-
160
- install(options) {
161
- var _this = this;
162
-
163
- return _asyncToGenerator(function* () {
164
- const repo = _this.db.getRepository('collections');
165
-
166
- if (repo) {
167
- yield repo.db2cm('applications');
168
- }
169
- })();
170
- }
171
-
172
- beforeLoad() {
173
- this.app.appManager.setAppSelector(req => {
174
- return req.headers['x-app'] || null;
175
- });
176
- }
177
-
178
- load() {
179
- var _this2 = this;
180
-
181
- return _asyncToGenerator(function* () {
182
- _this2.db.registerModels({
183
- ApplicationModel: _application.ApplicationModel
184
- });
185
-
186
- yield _this2.db.import({
187
- directory: (0, path().resolve)(__dirname, 'collections')
188
- });
189
-
190
- _this2.db.on('applications.afterCreateWithAssociations', /*#__PURE__*/function () {
191
- var _ref2 = _asyncToGenerator(function* (model, options) {
192
- const transaction = options.transaction;
193
- yield model.registerToMainApp(_this2.app, {
194
- transaction,
195
- dbCreator: _this2.appDbCreator,
196
- appOptionsFactory: _this2.appOptionsFactory
197
- });
198
- });
199
-
200
- return function (_x2, _x3) {
201
- return _ref2.apply(this, arguments);
202
- };
203
- }());
204
-
205
- _this2.db.on('applications.afterDestroy', /*#__PURE__*/function () {
206
- var _ref3 = _asyncToGenerator(function* (model) {
207
- yield _this2.app.appManager.removeApplication(model.get('name'));
208
- });
209
-
210
- return function (_x4) {
211
- return _ref3.apply(this, arguments);
212
- };
213
- }());
214
-
215
- _this2.app.appManager.on('beforeGetApplication', /*#__PURE__*/function () {
216
- var _ref4 = _asyncToGenerator(function* ({
217
- appManager,
218
- name
219
- }) {
220
- if (!appManager.applications.has(name)) {
221
- const existsApplication = yield _this2.app.db.getRepository('applications').findOne({
222
- filter: {
223
- name
224
- }
225
- });
226
-
227
- if (existsApplication) {
228
- yield existsApplication.registerToMainApp(_this2.app, {
229
- dbCreator: _this2.appDbCreator,
230
- appOptionsFactory: _this2.appOptionsFactory
231
- });
232
- }
233
- }
234
- });
235
-
236
- return function (_x5) {
237
- return _ref4.apply(this, arguments);
238
- };
239
- }());
240
-
241
- _this2.app.acl.registerSnippet({
242
- name: `pm.${_this2.name}.applications`,
243
- actions: ['applications:*']
244
- });
245
- })();
246
- }
247
-
248
- }
249
-
250
- exports.PluginMultiAppManager = PluginMultiAppManager;