bajo 0.3.10 → 1.0.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.
Files changed (163) hide show
  1. package/README.md +127 -26
  2. package/bajoI18N/resource/id.json +31 -0
  3. package/boot/class/app.js +69 -0
  4. package/boot/class/bajo-core/helper/attach-method.js +30 -0
  5. package/boot/{boot-order.js → class/bajo-core/helper/boot-order.js} +10 -10
  6. package/boot/class/bajo-core/helper/boot-plugins.js +19 -0
  7. package/boot/class/bajo-core/helper/build-config.js +61 -0
  8. package/boot/class/bajo-core/helper/build-plugins.js +26 -0
  9. package/boot/class/bajo-core/helper/collect-config-handlers.js +21 -0
  10. package/boot/{exit-handler.js → class/bajo-core/helper/exit-handler.js} +10 -16
  11. package/boot/class/bajo-core/helper/run-as-applet.js +26 -0
  12. package/boot/class/bajo-core/method/arrange-array.js +18 -0
  13. package/boot/class/bajo-core/method/break-ns-path-from-file.js +24 -0
  14. package/boot/class/bajo-core/method/break-ns-path.js +29 -0
  15. package/boot/class/bajo-core/method/build-collections.js +46 -0
  16. package/boot/class/bajo-core/method/call-handler.js +29 -0
  17. package/boot/{helper → class/bajo-core/method}/defaults-deep.js +1 -1
  18. package/boot/class/bajo-core/method/each-plugins.js +55 -0
  19. package/boot/class/bajo-core/method/envs.js +7 -0
  20. package/boot/{helper → class/bajo-core/method}/generate-id.js +4 -0
  21. package/boot/{helper → class/bajo-core/method}/get-global-module-dir.js +5 -6
  22. package/boot/class/bajo-core/method/get-method.js +10 -0
  23. package/boot/{helper → class/bajo-core/method}/get-module-dir.js +3 -4
  24. package/boot/{helper → class/bajo-core/method}/get-plugin-data-dir.js +2 -3
  25. package/boot/class/bajo-core/method/get-plugin-file.js +18 -0
  26. package/boot/class/bajo-core/method/get-plugin.js +23 -0
  27. package/boot/{helper → class/bajo-core/method}/import-module.js +4 -10
  28. package/boot/{helper → class/bajo-core/method}/import-pkg.js +9 -3
  29. package/boot/class/bajo-core/method/includes.js +13 -0
  30. package/boot/class/bajo-core/method/is-class.js +7 -0
  31. package/boot/{helper → class/bajo-core/method}/is-log-in-range.js +1 -1
  32. package/boot/{helper → class/bajo-core/method}/is-valid-app.js +2 -2
  33. package/boot/class/bajo-core/method/join.js +15 -0
  34. package/boot/class/bajo-core/method/log-levels.js +9 -0
  35. package/boot/class/bajo-core/method/num-unit.js +9 -0
  36. package/boot/{helper → class/bajo-core/method}/parse-object.js +24 -8
  37. package/boot/class/bajo-core/method/read-config.js +48 -0
  38. package/boot/{helper → class/bajo-core/method}/read-json.js +2 -2
  39. package/boot/class/bajo-core/method/run-hook.js +26 -0
  40. package/boot/{helper → class/bajo-core/method}/save-as-download.js +2 -2
  41. package/boot/class/bajo-core/method/slice-string.js +13 -0
  42. package/boot/class/bajo-core/method/titleize.js +23 -0
  43. package/boot/class/bajo-core.js +30 -0
  44. package/boot/class/bajo-plugin/helper/attach-method.js +14 -0
  45. package/boot/class/bajo-plugin/helper/build-config.js +10 -0
  46. package/boot/class/bajo-plugin/helper/check-clash.js +16 -0
  47. package/boot/class/bajo-plugin/helper/check-dependency.js +37 -0
  48. package/boot/class/bajo-plugin/helper/collect-exit-handlers.js +14 -0
  49. package/boot/class/bajo-plugin/helper/collect-hooks.js +29 -0
  50. package/boot/class/bajo-plugin/helper/run.js +20 -0
  51. package/boot/class/bajo-plugin.js +78 -0
  52. package/boot/class/error.js +59 -0
  53. package/boot/class/log.js +67 -0
  54. package/boot/class/plugin.js +51 -0
  55. package/boot/class/print.js +103 -0
  56. package/boot/index.js +4 -51
  57. package/boot/lib/create-method.js +30 -0
  58. package/boot/{helper → lib}/current-loc.js +1 -1
  59. package/boot/lib/get-global-module-path.js +189 -0
  60. package/boot/lib/omitted-plugin-keys.js +1 -1
  61. package/boot/lib/parse-args-argv.js +8 -11
  62. package/boot/lib/parse-env.js +7 -6
  63. package/boot/lib/read-all-configs.js +36 -0
  64. package/boot/lib/translate.js +18 -0
  65. package/docs/ecosystem.md +55 -0
  66. package/docs/hook.md +11 -0
  67. package/package.json +54 -56
  68. package/test/{helper-isSet.js → method/isSet.js} +6 -4
  69. package/waibuStatic/virtual.json +7 -0
  70. package/boot/attach-helper.js +0 -40
  71. package/boot/build-config.js +0 -99
  72. package/boot/create-scope.js +0 -36
  73. package/boot/helper/break-ns-path.js +0 -20
  74. package/boot/helper/build-collections.js +0 -43
  75. package/boot/helper/build-name.js +0 -17
  76. package/boot/helper/call-helper-or-handler.js +0 -15
  77. package/boot/helper/dump.js +0 -14
  78. package/boot/helper/each-plugins.js +0 -106
  79. package/boot/helper/envs.js +0 -14
  80. package/boot/helper/error.js +0 -77
  81. package/boot/helper/fatal.js +0 -13
  82. package/boot/helper/get-config.js +0 -19
  83. package/boot/helper/get-helper.js +0 -12
  84. package/boot/helper/get-item-by-name.js +0 -26
  85. package/boot/helper/get-plugin-file.js +0 -16
  86. package/boot/helper/get-plugin-name.js +0 -39
  87. package/boot/helper/get-plugin.js +0 -14
  88. package/boot/helper/join.js +0 -11
  89. package/boot/helper/log-levels.js +0 -19
  90. package/boot/helper/read-config.js +0 -48
  91. package/boot/helper/resolve-tpl-path.js +0 -15
  92. package/boot/helper/run-hook.js +0 -49
  93. package/boot/helper/spinner.js +0 -9
  94. package/boot/helper/start-plugin.js +0 -7
  95. package/boot/helper/titleize.js +0 -14
  96. package/boot/lib/build-helper.js +0 -60
  97. package/boot/lib/logger.js +0 -76
  98. package/boot/lib/print.js +0 -138
  99. package/boot/plugins/attach-helper.js +0 -20
  100. package/boot/plugins/build-config.js +0 -68
  101. package/boot/plugins/check-clash.js +0 -18
  102. package/boot/plugins/check-dependency.js +0 -37
  103. package/boot/plugins/collect-config-handlers.js +0 -22
  104. package/boot/plugins/collect-exit-handlers.js +0 -18
  105. package/boot/plugins/collect-hooks.js +0 -34
  106. package/boot/plugins/extend-config.js +0 -21
  107. package/boot/plugins/index.js +0 -27
  108. package/boot/plugins/run.js +0 -26
  109. package/boot/run-tool.js +0 -41
  110. package/docs/boot_build-config.js.html +0 -75
  111. package/docs/boot_create-scope.js.html +0 -25
  112. package/docs/boot_index.js.html +0 -43
  113. package/docs/data/search.json +0 -1
  114. package/docs/fonts/Inconsolata-Regular.ttf +0 -0
  115. package/docs/fonts/OpenSans-Regular.ttf +0 -0
  116. package/docs/fonts/WorkSans-Bold.ttf +0 -0
  117. package/docs/helper_emit.js.html +0 -18
  118. package/docs/helper_envs.js.html +0 -16
  119. package/docs/helper_error.js.html +0 -25
  120. package/docs/helper_get-bajo.js.html +0 -42
  121. package/docs/helper_index.js.html +0 -39
  122. package/docs/helper_log-levels.js.html +0 -20
  123. package/docs/helper_set-hook.js.html +0 -38
  124. package/docs/helper_walk-bajos.js.html +0 -51
  125. package/docs/index.html +0 -16
  126. package/docs/module-boot.html +0 -3
  127. package/docs/module-boot_buildConfig.html +0 -3
  128. package/docs/module-boot_createScope.html +0 -3
  129. package/docs/module-helper.html +0 -7
  130. package/docs/module-helper_setHook.html +0 -4
  131. package/docs/module-helper_walkBajos.html +0 -6
  132. package/docs/scripts/core.js +0 -655
  133. package/docs/scripts/core.min.js +0 -23
  134. package/docs/scripts/resize.js +0 -90
  135. package/docs/scripts/search.js +0 -265
  136. package/docs/scripts/search.min.js +0 -6
  137. package/docs/scripts/third-party/Apache-License-2.0.txt +0 -202
  138. package/docs/scripts/third-party/fuse.js +0 -9
  139. package/docs/scripts/third-party/hljs-line-num-original.js +0 -369
  140. package/docs/scripts/third-party/hljs-line-num.js +0 -1
  141. package/docs/scripts/third-party/hljs-original.js +0 -5171
  142. package/docs/scripts/third-party/hljs.js +0 -1
  143. package/docs/scripts/third-party/popper.js +0 -5
  144. package/docs/scripts/third-party/tippy.js +0 -1
  145. package/docs/scripts/third-party/tocbot.js +0 -672
  146. package/docs/scripts/third-party/tocbot.min.js +0 -1
  147. package/docs/styles/clean-jsdoc-theme-base.css +0 -975
  148. package/docs/styles/clean-jsdoc-theme-dark.css +0 -407
  149. package/docs/styles/clean-jsdoc-theme-light.css +0 -388
  150. package/docs/styles/clean-jsdoc-theme.min.css +0 -1
  151. package/test/helper-error.js +0 -25
  152. package/test/helper-pathResolve.js +0 -28
  153. /package/boot/{helper → class/bajo-core/method}/get-key-by-value.js +0 -0
  154. /package/boot/{helper → class/bajo-core/method}/is-empty-dir.js +0 -0
  155. /package/boot/{helper → class/bajo-core/method}/is-set.js +0 -0
  156. /package/boot/{helper → class/bajo-core/method}/is-valid-plugin.js +0 -0
  157. /package/boot/{helper → class/bajo-core/method}/paginate.js +0 -0
  158. /package/boot/{helper → class/bajo-core/method}/pascal-case.js +0 -0
  159. /package/boot/{helper → class/bajo-core/method}/pick.js +0 -0
  160. /package/boot/{helper → class/bajo-core/method}/resolve-path.js +0 -0
  161. /package/boot/{helper → class/bajo-core/method}/round.js +0 -0
  162. /package/boot/{helper → class/bajo-core/method}/sec-to-hms.js +0 -0
  163. /package/boot/{helper → class/bajo-core/method}/white-space.js +0 -0
@@ -1,15 +0,0 @@
1
- import { trim } from 'lodash-es'
2
- import fs from 'fs-extra'
3
-
4
- function resolveTplPath (name, baseTpl, extTpl = '') {
5
- const { getConfig, breakNsPath } = this.bajo.helper
6
- const [ns, path] = breakNsPath(name)
7
- const cfgNs = getConfig(ns, { full: true })
8
- const cfgApp = getConfig('app', { full: true })
9
- let file = `${cfgNs.dir.pkg}/${baseTpl}/${trim(path, '/')}${extTpl}`
10
- const override = `${cfgApp.dir.pkg}/${baseTpl}/override/${ns}/${trim(path, '/')}${extTpl}`
11
- if (fs.existsSync(override)) file = override
12
- return file
13
- }
14
-
15
- export default resolveTplPath
@@ -1,49 +0,0 @@
1
- import { filter, isEmpty, orderBy, pullAt } from 'lodash-es'
2
-
3
- /**
4
- * @module helper/runHook
5
- */
6
-
7
- /**
8
- * Set hook defined by parameter ```hookName```. Hook name should be in this following format:
9
- * ```<namespace>:<identifier>``` - where namespace is a valid Bajo name and
10
- * identifier is a unique string set by Bajo developer to identify a hook inside a Bajo
11
- *
12
- * @instance
13
- * @async
14
- * @param {string} hookName - Hook's name
15
- *
16
- * @example
17
- * const { runHook } = this.bajo.helper
18
- * await runHook('myBajo:afterStartApp')
19
- */
20
-
21
- async function runHook (hookName, ...args) {
22
- // const { log } = this.bajo.helper
23
- // log.trace('Run hook: %s', hookName)
24
- const [ns, path] = (hookName ?? '').split(':')
25
- let fns = filter(this.bajo.hooks, { ns, path })
26
- if (isEmpty(fns)) return
27
- fns = orderBy(fns, ['level'])
28
- const results = []
29
- const removed = []
30
- for (const i in fns) {
31
- const fn = fns[i]
32
- /*
33
- if (config.log.report.includes(id)) {
34
- log.trace({ args }, 'Call hook: %s', id)
35
- }
36
- */
37
- const res = await fn.handler.call(this, ...args)
38
- results.push({
39
- hook: hookName,
40
- resp: res
41
- })
42
- if (path.startsWith('once')) removed.push(i)
43
- }
44
- if (removed.length > 0) pullAt(this.bajo.hooks, removed)
45
-
46
- return results
47
- }
48
-
49
- export default runHook
@@ -1,9 +0,0 @@
1
- import { Print } from '../lib/print.js'
2
-
3
- function spinner (options) {
4
- const print = new Print(options)
5
- print.setScope(this)
6
- return print
7
- }
8
-
9
- export default spinner
@@ -1,7 +0,0 @@
1
- async function startPlugin (name, ...args) {
2
- const { importModule } = this.bajo.helper
3
- const start = await importModule(`${name}:/bajo/start.js`)
4
- await start.call(this, ...args)
5
- }
6
-
7
- export default startPlugin
@@ -1,14 +0,0 @@
1
- import { words, upperFirst, map, isFunction, concat, uniq } from 'lodash-es'
2
-
3
- const defIgnores = ['or', 'and', 'of', 'with']
4
-
5
- function titleize (text, { transformer, ignores = [] } = {}) {
6
- return map(words(text), t => {
7
- if (isFunction(transformer)) return transformer.call(this, t)
8
- ignores = uniq(concat(ignores, defIgnores))
9
- if (ignores.includes(t)) return t
10
- return upperFirst(t)
11
- }).join(' ')
12
- }
13
-
14
- export default titleize
@@ -1,60 +0,0 @@
1
- import fastGlob from 'fast-glob'
2
- import path from 'path'
3
- import { camelCase, isFunction, isPlainObject, forOwn } from 'lodash-es'
4
- import resolvePath from '../helper/resolve-path.js'
5
- import importModule from '../helper/import-module.js'
6
- import readJson from '../helper/read-json.js'
7
-
8
- function stackInfo (name, ...args) {
9
- const { log, callsites } = this.bajo.helper
10
- const config = this.bajo.config
11
- if (config.env === 'prod') return
12
- if (!config.log.report.includes(`helper:${name}`)) return
13
- const info = callsites()[2]
14
- const file = info.getFileName()
15
- const line = info.getLineNumber()
16
- log.trace({ line, file, args }, 'Call helper: %s()', name)
17
- }
18
-
19
- const wrapFn = function (name, handler, bind) {
20
- return (...args) => {
21
- stackInfo.call(this, name, ...args)
22
- if (bind) return handler.call(this, ...args)
23
- return handler(...args)
24
- }
25
- }
26
-
27
- const wrapAsyncFn = function (name, handler, bind) {
28
- return async (...args) => {
29
- stackInfo.call(this, name, ...args)
30
- if (bind) return await handler.call(this, ...args)
31
- return await handler(...args)
32
- }
33
- }
34
-
35
- export default async function (dir, pkg = 'bajo') {
36
- dir = resolvePath(dir)
37
- const files = await fastGlob([`!${dir}/**/_*.{js,json}`, `${dir}/**/*.{js,json}`])
38
- const helper = {}
39
- for (const f of files) {
40
- const ext = path.extname(f)
41
- const base = f.replace(dir, '').replace(ext, '')
42
- const name = camelCase(base)
43
- const fnName = pkg + '.' + name
44
- let mod
45
- if (ext === '.json') mod = readJson(f)
46
- else mod = await importModule(f)
47
- if (isFunction(mod)) {
48
- if (mod.constructor.name === 'AsyncFunction') mod = wrapAsyncFn.call(this, fnName, mod, true)
49
- else mod = wrapFn.call(this, fnName, mod, true)
50
- } else if (isPlainObject(mod)) {
51
- if (!mod.exec) { // mod.exec offer unbind, nacked function people can band to anything else later
52
- forOwn(mod, (v, k) => {
53
- if (isFunction(v)) mod[k] = v.bind(this)
54
- })
55
- }
56
- }
57
- helper[name] = mod
58
- }
59
- return helper
60
- }
@@ -1,76 +0,0 @@
1
- import os from 'os'
2
- import { isEmpty, without, merge, upperFirst, isPlainObject } from 'lodash-es'
3
- // import pretty from 'prettyjson'
4
- import getPluginName from '../helper/get-plugin-name.js'
5
- import levels from '../helper/log-levels.js'
6
- import isLogInRange from '../helper/is-log-in-range.js'
7
- import dayjs from 'dayjs'
8
-
9
- /*
10
- const prettyOpts = {
11
- noAlign: true,
12
- defaultIndentation: 2,
13
- renderUndefined: true
14
- }
15
- */
16
-
17
- class Log {
18
- constructor (scope) {
19
- this.scope = scope
20
- this.config = scope.bajo.config
21
- this.bajoLog = this.config.log.logger ?? 'bajoLogger'
22
- this.format = 'YYYY-MM-DDTHH:mm:ss.SSS[Z]'
23
- }
24
-
25
- isExtLogger () {
26
- return this.scope[this.bajoLog] && this.scope[this.bajoLog].logger
27
- }
28
-
29
- child () {
30
- if (this.isExtLogger()) return this.scope[this.bajoLog].logger.child()
31
- return this.scope
32
- }
33
-
34
- formatMsg (level, params) {
35
- const { print } = this.scope.bajo.helper
36
- let opts = {}
37
- if (isPlainObject(params.slice(-1)[0])) opts = params.pop()
38
- if (this.config.log.level === 'silent') return
39
- if (!isLogInRange.call(this.scope, level)) return
40
- let [data, msg, ...args] = params
41
- if (typeof data === 'string') {
42
- args.unshift(msg)
43
- msg = data
44
- data = null
45
- }
46
- args = without(args, undefined)
47
- const pkg = opts.pkg ?? getPluginName.call(this.scope, 3)
48
- msg = print.__(`[%s] ${msg}`, pkg, ...args)
49
- if (this.scope[this.bajoLog] && this.scope[this.bajoLog].logger) {
50
- this.scope[this.bajoLog].logger[level](data, msg, ...args)
51
- } else {
52
- let text
53
- const dt = new Date()
54
- if (this.config.env === 'prod') {
55
- const json = { level: levels[level], time: dt.valueOf(), pid: process.pid, hostname: os.hostname() }
56
- if (!isEmpty(data)) merge(json, data)
57
- merge(json, { msg })
58
- text = JSON.stringify(json)
59
- } else {
60
- text = `[${dayjs(dt).utc(true).format(this.format)}] ${upperFirst(level)}: ${msg}`
61
- if (!isEmpty(data)) text += '\n' + JSON.stringify(data)
62
- }
63
- console.log(text)
64
- }
65
- }
66
- }
67
-
68
- Object.keys(levels).forEach(level => {
69
- Log.prototype[level] = function (...params) {
70
- this.formatMsg(level, params)
71
- }
72
- })
73
-
74
- export default function logger () {
75
- return new Log(this)
76
- }
package/boot/lib/print.js DELETED
@@ -1,138 +0,0 @@
1
- import Sprintf from 'sprintf-js'
2
- import ora from 'ora'
3
- import { isPlainObject, get } from 'lodash-es'
4
- import defaultsDeep from '../helper/defaults-deep.js'
5
-
6
- const { sprintf } = Sprintf
7
-
8
- export class Print {
9
- constructor (opts = {}) {
10
- this.opts = opts
11
- this.startTime = null
12
- }
13
-
14
- setOpts (args = []) {
15
- const { getConfig } = this.scope.bajo.helper
16
- const config = getConfig()
17
- let opts = {}
18
- if (isPlainObject(args.slice(-1)[0])) opts = args.pop()
19
- this.opts.isLog = !config.tool
20
- if (this.opts.isLog) this.opts.isEnabled = false
21
- this.opts.isSilent = !!(config.silent || this.opts.isSilent)
22
- this.opts = defaultsDeep(opts, this.opts)
23
- }
24
-
25
- setScope (scope) {
26
- this.scope = scope
27
- const { dayjs } = this.scope.bajo.helper
28
- this.startTime = dayjs()
29
- this.setOpts()
30
- this.ora = ora(this.opts)
31
- }
32
-
33
- setText (text, ...args) {
34
- const { dayjs } = this.scope.bajo.helper
35
- text = this.__(text, ...args)
36
- this.setOpts(args)
37
- const prefixes = []
38
- const texts = []
39
- if (this.opts.showDatetime) prefixes.push('[' + dayjs().toISOString() + ']')
40
- if (this.opts.showCounter) texts.push('[' + this.getElapsed() + ']')
41
- if (prefixes.length > 0) this.ora.prefixText = this.ora.prefixText + prefixes.join(' ')
42
- if (texts.length > 0) text = texts.join(' ') + ' ' + text
43
- if (this.opts.isLog) this.info(text, ...args)
44
- else this.ora.text = text
45
- return this
46
- }
47
-
48
- __ (text, ...args) {
49
- if (text) {
50
- const i18n = get(this, 'scope.bajoI18N.instance')
51
- if (i18n) {
52
- if (isPlainObject(args[0])) text = i18n.t(text, args[0])
53
- else text = i18n.t(text, { ns: this.ns, postProcess: 'sprintf', sprintf: args })
54
- } else text = sprintf(text, ...args)
55
- }
56
- return text
57
- }
58
-
59
- getElapsed (unit = 'hms') {
60
- const { dayjs, secToHms } = this.scope.bajo.helper
61
- const u = unit === 'hms' ? 'second' : unit
62
- const elapsed = dayjs().diff(this.startTime, u)
63
- return unit === 'hms' ? secToHms(elapsed) : elapsed
64
- }
65
-
66
- start (text, ...args) {
67
- this.setOpts(args)
68
- if (this.opts.isLog) {
69
- this.ora.start()
70
- this.info(text, ...args)
71
- return this
72
- }
73
- this.setText(text, ...args)
74
- this.ora.start()
75
- return this
76
- }
77
-
78
- stop () {
79
- this.ora.stop()
80
- return this
81
- }
82
-
83
- succeed (text, ...args) {
84
- const { log } = this.scope.bajo.helper
85
- if (this.opts.isLog) return log.debug(text, ...args)
86
- this.setText(text, ...args)
87
- this.ora.succeed()
88
- return this
89
- }
90
-
91
- fail (text, ...args) {
92
- const { log } = this.scope.bajo.helper
93
- if (this.opts.isLog) return log.error(text, ...args)
94
- this.setText(text, ...args)
95
- this.ora.fail()
96
- return this
97
- }
98
-
99
- warn (text, ...args) {
100
- const { log } = this.scope.bajo.helper
101
- if (this.opts.isLog) return log.warn(text, ...args)
102
- this.setText(text, ...args)
103
- this.ora.warn()
104
- return this
105
- }
106
-
107
- info (text, ...args) {
108
- const { log } = this.scope.bajo.helper
109
- if (this.opts.isLog) return log.debug(text, ...args)
110
- this.setText(text, ...args)
111
- this.ora.info()
112
- return this
113
- }
114
-
115
- clear () {
116
- this.ora.clear()
117
- return this
118
- }
119
-
120
- render () {
121
- this.ora.render()
122
- return this
123
- }
124
-
125
- fatal (text, ...args) {
126
- const { log } = this.scope.bajo.helper
127
- if (this.opts.isLog) return log.fatal(text, ...args)
128
- this.setText(text, ...args)
129
- this.ora.fail()
130
- process.kill(process.pid, 'SIGINT')
131
- }
132
- }
133
-
134
- export default function (options) {
135
- const print = new Print(options)
136
- print.setScope(this)
137
- return print
138
- }
@@ -1,20 +0,0 @@
1
- import buildHelper from '../lib/build-helper.js'
2
- import { keys } from 'lodash-es'
3
-
4
- async function runner (plugin, pkg) {
5
- const { log, freeze } = this.bajo.helper
6
- const dir = pkg === 'app' ? (this.bajo.config.dir.base + '/app') : this.bajo.helper.getModuleDir(pkg)
7
- this[plugin].helper = await buildHelper.call(this, `${dir}/bajo/helper`, pkg)
8
- freeze(this[plugin].helper, true)
9
- log.trace('Attach helper: %s (%d)', plugin, keys(this[plugin].helper).length)
10
- }
11
-
12
- async function attachHelper () {
13
- const { log, eachPlugins } = this.bajo.helper
14
- log.debug('Attach helpers')
15
- await eachPlugins(async function ({ plugin, pkg }) {
16
- await runner.call(this, plugin, pkg)
17
- })
18
- }
19
-
20
- export default attachHelper
@@ -1,68 +0,0 @@
1
- import { camelCase, pick, isString, omit } from 'lodash-es'
2
- import fs from 'fs-extra'
3
- import omittedPluginKeys from '../lib/omitted-plugin-keys.js'
4
- import titleize from '../helper/titleize.js'
5
-
6
- export async function readAllConfigs (base, name) {
7
- const { readConfig, getConfig } = this.bajo.helper
8
- const config = getConfig()
9
- let cfg = {}
10
- try {
11
- cfg = await readConfig(`${base}-${config.env}.*`)
12
- } catch (err) {
13
- if (['BAJO_CONFIG_NO_PARSER'].includes(err.code)) throw err
14
- if (['BAJO_CONFIG_FILE_NOT_FOUND'].includes(err.code)) {
15
- try {
16
- cfg = await readConfig(`${base}.*`)
17
- } catch (err) {
18
- if (!['BAJO_CONFIG_FILE_NOT_FOUND'].includes(err.code)) throw err
19
- }
20
- }
21
- }
22
- cfg.name = name
23
- return cfg
24
- }
25
-
26
- async function runner (pkg, { argv, env }) {
27
- const { log, getConfig, getModuleDir, readConfig, error, readJson, defaultsDeep } = this.bajo.helper
28
- const config = getConfig()
29
- const name = camelCase(pkg)
30
- log.trace('Read configuration: %s', name)
31
- const dir = pkg === 'app' ? (config.dir.base + '/app') : getModuleDir(pkg)
32
- if (pkg !== 'app' && !fs.existsSync(`${dir}/bajo`)) throw error('Package \'%s\' isn\'t a valid Bajo package', pkg, { code: 'BAJO_INVALID_PACKAGE' })
33
- let cfg = await readAllConfigs.call(this, `${dir}/bajo/config`, name)
34
- cfg.dir = {
35
- pkg: dir,
36
- data: `${config.dir.data}/plugins/${name}`
37
- }
38
- const pkgJson = await readJson(`${dir + (pkg === 'app' ? '/..' : '')}/package.json`)
39
- cfg.pkg = pick(pkgJson,
40
- ['name', 'version', 'description', 'author', 'license', 'homepage'])
41
- if (cfg.name === 'app') {
42
- cfg.alias = 'app'
43
- cfg.title = 'Application'
44
- } else if (!isString(cfg.alias)) cfg.alias = pkg.slice(0, 5) === 'bajo-' ? pkg.slice(5).toLowerCase() : pkg // fix. can't be overriden
45
- cfg.title = cfg.title ?? titleize.call(this, cfg.alias)
46
- // merge with config from datadir
47
- try {
48
- const altCfg = await readConfig(`${config.dir.data}/config/${cfg.name}.*`)
49
- cfg = defaultsDeep({}, omit(altCfg, omittedPluginKeys), cfg)
50
- } catch (err) {}
51
- const envArgv = defaultsDeep({}, omit(env[cfg.name] ?? {}, omittedPluginKeys) ?? {}, omit(argv[cfg.name] ?? {}, omittedPluginKeys) ?? {})
52
- cfg = defaultsDeep({}, envArgv ?? {}, cfg ?? {})
53
- cfg.dependencies = cfg.dependencies ?? []
54
- if (isString(cfg.dependencies)) cfg.dependencies = [cfg.dependencies]
55
- if (!this[name]) this[name] = {}
56
- this[name].config = cfg
57
- }
58
-
59
- async function buildConfig ({ argv, env }) {
60
- const { log, freeze } = this.bajo.helper
61
- log.debug('Read configurations')
62
- for (const pkg of this.bajo.config.plugins) {
63
- await runner.call(this, pkg, { argv, env })
64
- }
65
- freeze(this.bajo.config)
66
- }
67
-
68
- export default buildConfig
@@ -1,18 +0,0 @@
1
- import { find } from 'lodash-es'
2
- import error from '../helper/error.js'
3
-
4
- async function checkAlias () {
5
- const { log, eachPlugins } = this.bajo.helper
6
- log.debug('Checking alias & name clashes')
7
- const refs = []
8
- await eachPlugins(async function ({ plugin, pkg, alias }) {
9
- let item = find(refs, { plugin })
10
- if (item) throw error('Plugin name clash: \'%s (%s)\' with \'%s (%s)\'', plugin, pkg, item.plugin, item.pkg, { code: 'BAJO_NAME_CLASH' })
11
- item = find(refs, { alias })
12
- if (item) throw error('Plugin alias clash: \'%s (%s)\' with \'%s (%s)\'', alias, pkg, item.alias, item.pkg, { code: 'BAJO_ALIAS_CLASH' })
13
- refs.push({ plugin, alias, pkg })
14
- })
15
- this.bajo.pluginRefs = refs
16
- }
17
-
18
- export default checkAlias
@@ -1,37 +0,0 @@
1
- import { reduce, map, trim, keys, intersection, each, camelCase, get } from 'lodash-es'
2
- import semver from 'semver'
3
-
4
- async function runner ({ plugin, pkg, dependencies }) {
5
- const { log, getConfig, error, join } = this.bajo.helper
6
- log.trace('Checking dependencies: %s', plugin)
7
- const config = getConfig()
8
- const odep = reduce(dependencies, (o, k) => {
9
- const item = map(k.split('@'), m => trim(m))
10
- o[item[0]] = item[1]
11
- return o
12
- }, {})
13
- const deps = keys(odep)
14
- if (deps.length > 0) {
15
- if (intersection(config.plugins, deps).length !== deps.length) {
16
- throw error('Dependency for \'%s\' unfulfilled: %s', pkg, join(deps), { code: 'BAJO_DEPENDENCY' })
17
- }
18
- each(deps, d => {
19
- if (!odep[d]) return
20
- const ver = get(this[camelCase(d)], 'config.pkg.version')
21
- if (!ver) return
22
- if (!semver.satisfies(ver, odep[d])) {
23
- throw error('Semver check \'%s\' against \'%s\' failed', pkg, `${d}@${odep[d]}`, { code: 'BAJO_DEPENDENCY_SEMVER' })
24
- }
25
- })
26
- }
27
- }
28
-
29
- async function checkDependency () {
30
- const { log, eachPlugins } = this.bajo.helper
31
- log.debug('Checking dependencies')
32
- await eachPlugins(async function ({ plugin, pkg, dependencies }) {
33
- await runner.call(this, { plugin, pkg, dependencies })
34
- })
35
- }
36
-
37
- export default checkDependency
@@ -1,22 +0,0 @@
1
- import { isFunction, isPlainObject, map } from 'lodash-es'
2
-
3
- async function collectConfigHandlers (pkg) {
4
- const { getModuleDir, importModule, log, join } = this.bajo.helper
5
- for (const pkg of this.bajo.config.plugins) {
6
- let dir
7
- try {
8
- dir = getModuleDir(pkg)
9
- } catch (err) {}
10
- if (!dir) continue
11
- const file = `${dir}/bajo/extend/read-config.js`
12
- let mod = await importModule(file)
13
- if (!mod) continue
14
- if (isFunction(mod)) mod = await mod.call(this)
15
- if (isPlainObject(mod)) mod = [mod]
16
- this.bajo.configHandlers.concat(mod)
17
- }
18
- const exts = map(this.bajo.configHandlers, 'ext')
19
- log.trace('Config handlers: %s', join(exts))
20
- }
21
-
22
- export default collectConfigHandlers
@@ -1,18 +0,0 @@
1
- import {} from 'lodash-es'
2
-
3
- async function collectExitHandlers () {
4
- const { importModule, log, eachPlugins, getConfig, print, join } = this.bajo.helper
5
- const config = getConfig()
6
- if (!config.exitHandler) return
7
- this.bajo.exitHandler = this.bajo.exitHandler ?? {}
8
- const names = []
9
- await eachPlugins(async function ({ plugin, dir }) {
10
- const mod = await importModule(`${dir}/bajo/exit.js`)
11
- if (!mod) return undefined
12
- this.bajo.exitHandler[plugin] = mod
13
- names.push(plugin)
14
- })
15
- log.trace('Exit handlers: %s', names.length === 0 ? print.__('none') : join(names))
16
- }
17
-
18
- export default collectExitHandlers
@@ -1,34 +0,0 @@
1
- import { map, camelCase, merge, forOwn, groupBy } from 'lodash-es'
2
-
3
- async function collectHooks () {
4
- const { eachPlugins, log, runHook, isLogInRange, importModule } = this.bajo.helper
5
- this.bajo.hooks = this.bajo.hooks ?? []
6
- log.debug('Collect hooks')
7
- // collects
8
- await eachPlugins(async function ({ plugin, dir, file }) {
9
- const hookName = (file.slice(dir.length + 1) ?? '').split('/')[1]
10
- let [ns, path] = hookName.replace('.js', '').split('@')
11
- if (!path) {
12
- path = ns
13
- ns = plugin
14
- }
15
- path = camelCase(path)
16
- ns = map(ns.split('.'), (n, i) => i === 1 ? n : camelCase(n)).join('.')
17
- const mod = await importModule(file, { asHandler: true })
18
- if (!mod) return undefined
19
- merge(mod, { ns, path })
20
- this.bajo.hooks.push(mod)
21
- }, { glob: 'hook/**/*.js', insideBajo: true })
22
- await runHook('bajo:afterCollectHooks')
23
- // for log trace purpose only
24
- if (!isLogInRange('trace')) return
25
- const items = groupBy(this.bajo.hooks, 'ns')
26
- forOwn(items, (v, k) => {
27
- const hooks = groupBy(v, 'path')
28
- forOwn(hooks, (v1, k1) => {
29
- log.trace('Collect hook: %s:%s (%d)', k, k1, v1.length)
30
- })
31
- })
32
- }
33
-
34
- export default collectHooks
@@ -1,21 +0,0 @@
1
- import { isArray, each, isPlainObject, has, merge, concat } from 'lodash-es'
2
- import { readAllConfigs } from './build-config.js'
3
-
4
- async function extendConfig () {
5
- const { eachPlugins } = this.bajo.helper
6
- await eachPlugins(async function (opts) {
7
- if (!opts.cfg.mergeProps) return undefined
8
- await eachPlugins(async function ({ dir, plugin }) {
9
- const cfg = await readAllConfigs.call(this, `${dir}/${opts.plugin}/config`, opts.plugin)
10
- each(opts.cfg.mergeProps, p => {
11
- if (!has(cfg, p)) return undefined
12
- if (isArray(opts.cfg[p])) this[opts.plugin].config[p] = concat(opts.cfg[p], cfg[p])
13
- else if (isPlainObject(opts.cfg[p])) this[opts.plugin].config[p] = merge(opts.cfg[p], cfg[p])
14
- else this[opts.plugin].config[p] = cfg[p]
15
- })
16
- })
17
- delete this[opts.plugin].config.mergeProps
18
- })
19
- }
20
-
21
- export default extendConfig
@@ -1,27 +0,0 @@
1
- import buildConfig from './build-config.js'
2
- import extendConfig from './extend-config.js'
3
- import checkDependency from './check-dependency.js'
4
- import checkClash from './check-clash.js'
5
- import attachHelper from './attach-helper.js'
6
- import collectHooks from './collect-hooks.js'
7
- import run from './run.js'
8
- import collectConfigHandlers from './collect-config-handlers.js'
9
- import collectExitHandlers from './collect-exit-handlers.js'
10
- import parseArgsArgv from '../lib/parse-args-argv.js'
11
- import parseEnv from '../lib/parse-env.js'
12
-
13
- async function bootBajos () {
14
- const { argv } = await parseArgsArgv({ useParser: true }) ?? {}
15
- const env = parseEnv() ?? {}
16
- await collectConfigHandlers.call(this)
17
- await buildConfig.call(this, { argv, env })
18
- await extendConfig.call(this)
19
- await checkClash.call(this)
20
- await checkDependency.call(this)
21
- await attachHelper.call(this)
22
- await collectHooks.call(this)
23
- await run.call(this)
24
- await collectExitHandlers.call(this)
25
- }
26
-
27
- export default bootBajos
@@ -1,26 +0,0 @@
1
- import { set, get, camelCase, upperFirst, map } from 'lodash-es'
2
-
3
- async function run () {
4
- const { runHook, log, eachPlugins, importModule, freeze, getConfig, print, join } = this.bajo.helper
5
- const config = getConfig()
6
- const methods = ['init']
7
- if (!get(config, 'tool')) methods.push('start')
8
- for (const f of methods) {
9
- await runHook(`bajo:${camelCase(`before ${f} all plugins`)}`)
10
- await eachPlugins(async function ({ plugin, dir }) {
11
- const mod = await importModule(`${dir}/bajo/${f}.js`)
12
- if (mod) {
13
- log.debug('%s: %s', print.__(upperFirst(f)), plugin)
14
- await runHook(`bajo:${camelCase(`before ${f} ${plugin}`)}`)
15
- await mod.call(this)
16
- await runHook(`bajo:${camelCase(`after ${f} ${plugin}`)}`)
17
- }
18
- if (f === 'init') freeze(this[plugin].config)
19
- set(this, `${plugin}.state.${f}`, true)
20
- })
21
- await runHook(`bajo:${camelCase(`after ${f} all plugins`)}`)
22
- }
23
- log.debug('Loaded plugins: %s', join(map(config.plugins, b => camelCase(b))))
24
- }
25
-
26
- export default run