bajo 0.3.10 → 1.0.1

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 (162) 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 +3 -4
  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/omitted-plugin-keys.js +1 -1
  60. package/boot/lib/parse-args-argv.js +8 -11
  61. package/boot/lib/parse-env.js +7 -6
  62. package/boot/lib/read-all-configs.js +36 -0
  63. package/boot/lib/translate.js +18 -0
  64. package/docs/ecosystem.md +55 -0
  65. package/docs/hook.md +11 -0
  66. package/package.json +55 -56
  67. package/test/{helper-isSet.js → method/isSet.js} +6 -4
  68. package/waibuStatic/virtual.json +7 -0
  69. package/boot/attach-helper.js +0 -40
  70. package/boot/build-config.js +0 -99
  71. package/boot/create-scope.js +0 -36
  72. package/boot/helper/break-ns-path.js +0 -20
  73. package/boot/helper/build-collections.js +0 -43
  74. package/boot/helper/build-name.js +0 -17
  75. package/boot/helper/call-helper-or-handler.js +0 -15
  76. package/boot/helper/dump.js +0 -14
  77. package/boot/helper/each-plugins.js +0 -106
  78. package/boot/helper/envs.js +0 -14
  79. package/boot/helper/error.js +0 -77
  80. package/boot/helper/fatal.js +0 -13
  81. package/boot/helper/get-config.js +0 -19
  82. package/boot/helper/get-helper.js +0 -12
  83. package/boot/helper/get-item-by-name.js +0 -26
  84. package/boot/helper/get-plugin-file.js +0 -16
  85. package/boot/helper/get-plugin-name.js +0 -39
  86. package/boot/helper/get-plugin.js +0 -14
  87. package/boot/helper/join.js +0 -11
  88. package/boot/helper/log-levels.js +0 -19
  89. package/boot/helper/read-config.js +0 -48
  90. package/boot/helper/resolve-tpl-path.js +0 -15
  91. package/boot/helper/run-hook.js +0 -49
  92. package/boot/helper/spinner.js +0 -9
  93. package/boot/helper/start-plugin.js +0 -7
  94. package/boot/helper/titleize.js +0 -14
  95. package/boot/lib/build-helper.js +0 -60
  96. package/boot/lib/logger.js +0 -76
  97. package/boot/lib/print.js +0 -138
  98. package/boot/plugins/attach-helper.js +0 -20
  99. package/boot/plugins/build-config.js +0 -68
  100. package/boot/plugins/check-clash.js +0 -18
  101. package/boot/plugins/check-dependency.js +0 -37
  102. package/boot/plugins/collect-config-handlers.js +0 -22
  103. package/boot/plugins/collect-exit-handlers.js +0 -18
  104. package/boot/plugins/collect-hooks.js +0 -34
  105. package/boot/plugins/extend-config.js +0 -21
  106. package/boot/plugins/index.js +0 -27
  107. package/boot/plugins/run.js +0 -26
  108. package/boot/run-tool.js +0 -41
  109. package/docs/boot_build-config.js.html +0 -75
  110. package/docs/boot_create-scope.js.html +0 -25
  111. package/docs/boot_index.js.html +0 -43
  112. package/docs/data/search.json +0 -1
  113. package/docs/fonts/Inconsolata-Regular.ttf +0 -0
  114. package/docs/fonts/OpenSans-Regular.ttf +0 -0
  115. package/docs/fonts/WorkSans-Bold.ttf +0 -0
  116. package/docs/helper_emit.js.html +0 -18
  117. package/docs/helper_envs.js.html +0 -16
  118. package/docs/helper_error.js.html +0 -25
  119. package/docs/helper_get-bajo.js.html +0 -42
  120. package/docs/helper_index.js.html +0 -39
  121. package/docs/helper_log-levels.js.html +0 -20
  122. package/docs/helper_set-hook.js.html +0 -38
  123. package/docs/helper_walk-bajos.js.html +0 -51
  124. package/docs/index.html +0 -16
  125. package/docs/module-boot.html +0 -3
  126. package/docs/module-boot_buildConfig.html +0 -3
  127. package/docs/module-boot_createScope.html +0 -3
  128. package/docs/module-helper.html +0 -7
  129. package/docs/module-helper_setHook.html +0 -4
  130. package/docs/module-helper_walkBajos.html +0 -6
  131. package/docs/scripts/core.js +0 -655
  132. package/docs/scripts/core.min.js +0 -23
  133. package/docs/scripts/resize.js +0 -90
  134. package/docs/scripts/search.js +0 -265
  135. package/docs/scripts/search.min.js +0 -6
  136. package/docs/scripts/third-party/Apache-License-2.0.txt +0 -202
  137. package/docs/scripts/third-party/fuse.js +0 -9
  138. package/docs/scripts/third-party/hljs-line-num-original.js +0 -369
  139. package/docs/scripts/third-party/hljs-line-num.js +0 -1
  140. package/docs/scripts/third-party/hljs-original.js +0 -5171
  141. package/docs/scripts/third-party/hljs.js +0 -1
  142. package/docs/scripts/third-party/popper.js +0 -5
  143. package/docs/scripts/third-party/tippy.js +0 -1
  144. package/docs/scripts/third-party/tocbot.js +0 -672
  145. package/docs/scripts/third-party/tocbot.min.js +0 -1
  146. package/docs/styles/clean-jsdoc-theme-base.css +0 -975
  147. package/docs/styles/clean-jsdoc-theme-dark.css +0 -407
  148. package/docs/styles/clean-jsdoc-theme-light.css +0 -388
  149. package/docs/styles/clean-jsdoc-theme.min.css +0 -1
  150. package/test/helper-error.js +0 -25
  151. package/test/helper-pathResolve.js +0 -28
  152. /package/boot/{helper → class/bajo-core/method}/get-key-by-value.js +0 -0
  153. /package/boot/{helper → class/bajo-core/method}/is-empty-dir.js +0 -0
  154. /package/boot/{helper → class/bajo-core/method}/is-set.js +0 -0
  155. /package/boot/{helper → class/bajo-core/method}/is-valid-plugin.js +0 -0
  156. /package/boot/{helper → class/bajo-core/method}/paginate.js +0 -0
  157. /package/boot/{helper → class/bajo-core/method}/pascal-case.js +0 -0
  158. /package/boot/{helper → class/bajo-core/method}/pick.js +0 -0
  159. /package/boot/{helper → class/bajo-core/method}/resolve-path.js +0 -0
  160. /package/boot/{helper → class/bajo-core/method}/round.js +0 -0
  161. /package/boot/{helper → class/bajo-core/method}/sec-to-hms.js +0 -0
  162. /package/boot/{helper → class/bajo-core/method}/white-space.js +0 -0
@@ -1,106 +0,0 @@
1
- import { camelCase, isString, omit, trim } from 'lodash-es'
2
- import fastGlob from 'fast-glob'
3
- import path from 'path'
4
- import omittedPluginKeys from '../lib/omitted-plugin-keys.js'
5
-
6
- async function _eachPlugins (handler, { key = 'name', glob, ns, useBajo } = {}) {
7
- const { getConfig } = this.bajo.helper
8
- const config = getConfig()
9
- const result = {}
10
- const plugins = [...config.plugins]
11
- if (useBajo) plugins.unshift('bajo')
12
- for (const pkg of plugins) {
13
- const plugin = camelCase(pkg)
14
- let cfg = getConfig(plugin, { full: true })
15
- const { alias, dependencies } = cfg
16
- const dir = cfg.dir.pkg
17
- cfg = omit(cfg, omittedPluginKeys)
18
- let r
19
- if (glob) {
20
- const base = `${dir}/${ns}`
21
- let opts = isString(glob) ? { pattern: [glob] } : glob
22
- let pattern = opts.pattern ?? []
23
- if (isString(pattern)) pattern = [pattern]
24
- opts = omit(opts, ['pattern'])
25
- for (const i in pattern) {
26
- if (!path.isAbsolute(pattern[i])) pattern[i] = `${base}/${pattern[i]}`
27
- }
28
- const files = await fastGlob(pattern, opts)
29
- for (const f of files) {
30
- if (path.basename(f)[0] === '_') continue
31
- const resp = await handler.call(this, { plugin, pkg, cfg, alias, file: f, dir: base, dependencies })
32
- if (resp === false) break
33
- else if (resp === undefined) continue
34
- else {
35
- result[plugin] = result[plugin] ?? {}
36
- result[plugin][f] = resp
37
- }
38
- }
39
- } else {
40
- r = await handler.call(this, { plugin, pkg, cfg, dir, alias, dependencies })
41
- if (r === false) break
42
- else if (r === undefined) continue
43
- else result[plugin] = r
44
- }
45
- }
46
- return result
47
- }
48
-
49
- /**
50
- * @module helper/eachPlugins
51
- */
52
-
53
- /**
54
- * Callback function that will be executed while walking through all Bajos
55
- *
56
- * @callback handlerFn
57
- * @async
58
- * @param {Object} argument - Provides information about current Bajo
59
- * @param {string} argument.name - Bajo's name
60
- * @param {string} argument.pkgName - Bajo's package name
61
- * @param {Object} argument.cfg - Bajo's config object
62
- * @returns {Object|boolean|undefined}
63
- */
64
-
65
- /**
66
- * Walk through all plugins and execute the callback handler
67
- *
68
- * @instance
69
- * @async
70
- * @param {function} handlerFn - [The callback]{@link module:helper/eachPlugins~handlerFn}
71
- * @param {Object} [options] - Optional parameter
72
- * @param {string} [options.key=name] - Key of Bajo's config object that will be used as the key of returned object
73
- * @returns {Object} Results from callback execution through all Bajos
74
- *
75
- * @example
76
- * const { eachPlugins } = this.bajo.helper
77
- * await eachPlugins(async function ({ name }) => {
78
- * console.log(name)
79
- * })
80
- */
81
-
82
- async function eachPlugins (handler, options = {}) {
83
- const { getConfig, getPluginName } = this.bajo.helper
84
- if (typeof options === 'string') options = { glob: options }
85
- let { key = 'name', glob, ns, extend, extendHandler, useBajo } = options
86
- if (!extendHandler) extendHandler = handler
87
- ns = ns ?? getPluginName(4)
88
- const result = await _eachPlugins.call(this, handler, { key, glob, ns, useBajo })
89
- if (extend && isString(glob)) {
90
- let nsExtend = ns
91
- if (isString(extend)) nsExtend += '/' + trim(extend, '/')
92
- const cfg = getConfig('app', { full: true })
93
- const ext = `${cfg.dir.pkg}/${nsExtend}/extend/*`
94
- const exts = await fastGlob(ext, { onlyDirectories: true })
95
- for (const e of exts) {
96
- const plugin = path.basename(e)
97
- const files = await fastGlob(`${e}/${glob}`)
98
- for (const file of files) {
99
- await extendHandler.call(this, { file, plugin, dir: e })
100
- }
101
- }
102
- }
103
- return result // TODO: merge with extender
104
- }
105
-
106
- export default eachPlugins
@@ -1,14 +0,0 @@
1
- /**
2
- * Supported environment
3
- *
4
- * @memberof module:helper
5
- * @type Object
6
- * @instance
7
- */
8
-
9
- const envs = {
10
- dev: 'development',
11
- prod: 'production'
12
- }
13
-
14
- export default envs
@@ -1,77 +0,0 @@
1
- import { last, isPlainObject, each, isArray, get, isEmpty, merge } from 'lodash-es'
2
- import getPluginName from './get-plugin-name.js'
3
-
4
- /**
5
- * It's a shortcut to create an instance of Error with message and optional parameter
6
- * in a single line
7
- *
8
- * @memberof helper
9
- * @type Object
10
- * @instance
11
- * @param {string} msg - String that will be used as error message
12
- * @param {options} [options] - Optional parameter
13
- * @param {string} [options.code] - Error code
14
- * @returns {error} Instance of Error
15
- */
16
-
17
- Error.stackTraceLimit = 15
18
-
19
- function formatErrorDetails (value, ns) {
20
- const { print } = this.bajo.helper
21
- const result = {}
22
- each(value, (v, i) => {
23
- if (!v.context) {
24
- v.error = print.__(v.error, { ns })
25
- return undefined
26
- }
27
- v.context.message = v.message
28
- if (v.type === 'any.only') v.context.ref = print.__(`field.${get(v, 'context.valids.0.key')}`, { ns })
29
- const field = get(v, 'context.key')
30
- const val = get(v, 'context.value')
31
- value[i] = {
32
- field,
33
- error: print.__(`validation.${v.type}`, v.context, { ns }),
34
- value: val
35
- }
36
- })
37
- return result
38
- }
39
-
40
- function error (msg = 'Internal server error', ...args) {
41
- const { print } = this.bajo.helper
42
- let payload = last(args)
43
- let ns
44
- if (isPlainObject(payload)) {
45
- payload = args.pop()
46
- ns = payload.ns
47
- }
48
- if (!ns) ns = getPluginName.call(this, 3)
49
- const orgMsg = msg
50
- args.push({ ns })
51
- const message = print.__(msg, ...args)
52
- let err
53
- if (isPlainObject(payload) && payload.class) err = payload.class(message)
54
- else err = Error(message)
55
- const stacks = err.stack.split('\n')
56
- stacks.splice(1, 1) // this file
57
- if (stacks[1].includes('/helper/fatal.js')) stacks.splice(1, 1) // if it goes to fatal.js
58
- stacks.splice(1, 1) // for buildHelper.js
59
- err.stack = stacks.join('\n')
60
- if (isPlainObject(payload)) {
61
- delete payload.class
62
- delete payload.ns
63
- const values = {}
64
- for (const key in payload) {
65
- const value = payload[key]
66
- if (key === 'details' && isArray(value) && orgMsg === 'Validation Error') {
67
- const result = formatErrorDetails.call(this, value, ns)
68
- if (result) merge(values, result)
69
- }
70
- err[key] = value
71
- }
72
- if (!isEmpty(values)) err.values = values
73
- }
74
- return err
75
- }
76
-
77
- export default error
@@ -1,13 +0,0 @@
1
- import getPluginName from './get-plugin-name.js'
2
-
3
- function fatal (...args) {
4
- const { error } = this.bajo.helper
5
- const ns = getPluginName.call(this, 3)
6
- args.push({ ns })
7
- const [msg, ...params] = args
8
- const err = error(msg, ...params)
9
- console.error(err)
10
- process.kill(process.pid, 'SIGINT')
11
- }
12
-
13
- export default fatal
@@ -1,19 +0,0 @@
1
- import { isEmpty, isPlainObject, cloneDeep, omit, find } from 'lodash-es'
2
- import omittedPluginKeys from '../lib/omitted-plugin-keys.js'
3
-
4
- function getConfig (name, options = {}) {
5
- const { full, clone } = options
6
- if (name === 'bajo' || isEmpty(name)) return this.bajo.config
7
- if (this[name] && isPlainObject(this[name].config) && this[name].config.name === name) {
8
- const cfg = clone ? cloneDeep(this[name].config) : this[name].config
9
- return full ? cfg : omit(cfg, omittedPluginKeys)
10
- }
11
- const ref = find(this.bajo.pluginRefs ?? [], { alias: name })
12
- if (ref) {
13
- const cfg = clone ? cloneDeep(this[ref.plugin].config) : this[ref.plugin].config
14
- return full ? cfg : omit(cfg, omittedPluginKeys)
15
- }
16
- return {}
17
- }
18
-
19
- export default getConfig
@@ -1,12 +0,0 @@
1
- import { get } from 'lodash-es'
2
- import error from './error.js'
3
- import breakNsPath from './break-ns-path.js'
4
-
5
- function getHelper (name = '', thrown = true) {
6
- const [plugin, method] = breakNsPath.call(this, name)
7
- const helper = get(this, `${plugin}.helper.${method}`)
8
- if (helper) return helper
9
- if (thrown) throw error.call(this, 'Can\'t find helper named \'%s\'', name)
10
- }
11
-
12
- export default getHelper
@@ -1,26 +0,0 @@
1
- import path from 'path'
2
-
3
- async function getItemByName (name) {
4
- const { resolvePath, getConfig, readConfig, error } = this.bajo.helper
5
- const config = getConfig()
6
- const [type, ...paths] = name.split(':')
7
- let result
8
- switch (type) {
9
- case 'config': {
10
- let file = paths.join(':')
11
- if (!path.isAbsolute(file)) file = resolvePath(`${config.dir.data}/config/${file}`)
12
- result = await readConfig(file)
13
- break
14
- }
15
- case 'helper': {
16
- const [ns, fn] = paths.join(':').split('.')
17
- if (!(ns && fn)) throw error('Unknown helper \'%s.%s\'', ns, fn, { code: 'BAJO_UNKNOWN_HELPER' })
18
- result = this[ns].helper[fn]
19
- break
20
- }
21
- default: throw error('Unsupported type \'%s\'', type, { code: 'BAJO_UNSUPPORTED_TYPE' })
22
- }
23
- return result
24
- }
25
-
26
- export default getItemByName
@@ -1,16 +0,0 @@
1
- import { get } from 'lodash-es'
2
- import breakNsPath from './break-ns-path.js'
3
-
4
- function getPluginFile (file) {
5
- if (!get(this, 'bajo.helper')) return file
6
- if (file.includes(':')) {
7
- const [plugin, path] = breakNsPath.call(this, file)
8
- if (plugin !== 'file' && this && this[plugin] && plugin.length > 1) {
9
- const dir = get(this[plugin], 'config.dir.pkg')
10
- file = `${dir}${path}`
11
- }
12
- }
13
- return file
14
- }
15
-
16
- export default getPluginFile
@@ -1,39 +0,0 @@
1
- import { isString, isNumber, each, camelCase } from 'lodash-es'
2
- import callsites from 'callsites'
3
- import error from './error.js'
4
- import resolvePath from './resolve-path.js'
5
-
6
- /**
7
- * Get the right Bajo name inside your app or plugins/Bajos. If parameter ```fname```
8
- * is not provided, it will be set to the actual file this function is called.
9
- *
10
- * @memberof helper
11
- * @instance
12
- * @param {string} [fname] - File name (relative/absolute)
13
- * @throws Will throw if Bajo name coldn't be resolved
14
- * @returns {string} Bajo name
15
- */
16
-
17
- function getPluginName (fname) {
18
- const config = this.bajo.config
19
- let file
20
- if (isString(fname)) file = fname
21
- else file = callsites()[isNumber(fname) ? fname : 2].getFileName()
22
- if (!file) throw error('Can\'t resolve bajo named \'%s\', sorry!', fname, { code: 'BAJO_UNABLE_TO_RESOLVE_BAJO_NAME' })
23
- file = resolvePath(file)
24
- let match
25
- each(config.plugins, b => {
26
- if (file.includes('/bajo/boot/')) {
27
- match = 'bajo'
28
- return false
29
- }
30
- if (file.includes('/' + b + '/')) {
31
- match = b
32
- return false
33
- }
34
- })
35
- if (match) return camelCase(match)
36
- return 'bajo'
37
- }
38
-
39
- export default getPluginName
@@ -1,14 +0,0 @@
1
- import { find } from 'lodash-es'
2
-
3
- function getPlugin (name) {
4
- const { error } = this.bajo.helper
5
- if (!this[name]) {
6
- // alias?
7
- const ref = find(this.bajo.pluginRefs ?? [], { alias: name })
8
- if (!ref) throw error('\'%s\' is not loaded', name)
9
- name = ref.plugin
10
- }
11
- return this[name]
12
- }
13
-
14
- export default getPlugin
@@ -1,11 +0,0 @@
1
- import { isPlainObject } from 'lodash-es'
2
- import isSet from './is-set.js'
3
-
4
- const join = (array, sep) => {
5
- if (isSet(sep) && !isPlainObject(sep)) return array.join(sep)
6
- const { separator = ', ', joiner = 'and' } = sep ?? {}
7
- const last = (array.pop() ?? '').trim()
8
- return array.map(a => (a + '').trim()).join(separator) + ` ${joiner} ${last}`
9
- }
10
-
11
- export default join
@@ -1,19 +0,0 @@
1
- /**
2
- * Supported logger levels including its level priority
3
- *
4
- * @memberof module:helper
5
- * @type Object
6
- * @instance
7
- */
8
-
9
- const logLevels = {
10
- trace: 10,
11
- debug: 20,
12
- info: 30,
13
- warn: 40,
14
- error: 50,
15
- fatal: 60,
16
- silent: 99
17
- }
18
-
19
- export default logLevels
@@ -1,48 +0,0 @@
1
- import path from 'path'
2
- import resolvePath from './resolve-path.js'
3
- import getPluginFile from './get-plugin-file.js'
4
- import readJson from './read-json.js'
5
- import parseObject from './parse-object.js'
6
- import { find, map, isEmpty } from 'lodash-es'
7
- import error from './error.js'
8
- import fg from 'fast-glob'
9
-
10
- async function readConfig (file, { pattern, globOptions = {}, ignoreError, defValue = {} } = {}) {
11
- file = resolvePath(getPluginFile.call(this, file))
12
- let ext = path.extname(file)
13
- const fname = path.dirname(file) + '/' + path.basename(file, ext)
14
- ext = ext.toLowerCase()
15
- if (['.mjs', '.js'].includes(ext)) {
16
- const { handler } = find(this.bajo.configHandlers, { ext })
17
- return parseObject(await handler.call(this, file))
18
- }
19
- if (ext === '.json') return await readJson(file)
20
- if (!['', '.*'].includes(ext)) {
21
- const item = find(this.bajo.configHandlers, { ext })
22
- if (!item) {
23
- if (!ignoreError) throw error.call(this, 'Can\'t parse \'%s\'', file, { code: 'BAJO_CONFIG_NO_PARSER' })
24
- return parseObject(defValue)
25
- }
26
- return parseObject(item.handler.call(this, file))
27
- }
28
- const item = pattern ?? `${fname}.{${map(map(this.bajo.configHandlers, 'ext'), k => k.slice(1)).join(',')}}`
29
- const files = await fg(item, globOptions)
30
- if (files.length === 0) {
31
- if (!ignoreError) throw error.call(this, 'No config file found', { code: 'BAJO_CONFIG_FILE_NOT_FOUND' })
32
- return parseObject(defValue)
33
- }
34
- let config = defValue
35
- for (const f of files) {
36
- const ext = path.extname(f).toLowerCase()
37
- const item = find(this.bajo.configHandlers, { ext })
38
- if (!item) {
39
- if (!ignoreError) throw error.call(this, 'Can\'t parse \'%s\'', f, { code: 'BAJO_CONFIG_NO_PARSER' })
40
- continue
41
- }
42
- config = await item.handler.call(this, f)
43
- if (!isEmpty(config)) break
44
- }
45
- return parseObject(config)
46
- }
47
-
48
- export default readConfig
@@ -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
- }