Bajo

The Core. The main engine. The one and only plugin that control app's boot process and making sure all other plugins working nicely.

Constructor

new Bajo(app)

Parameters:
NameTypeDescription
appApp

App instance. Usefull to call app method inside a plugin

Members

config :Object

Config object

Type:
  • Object
See
  • config

Methods

breakNsPath(name, checkNsopt) → {TNsPathResult}

Break name to its namespace & path infos

Parameters:
NameTypeAttributesDefaultDescription
nameTNsPathPairs | string

Name to break

checkNsboolean<optional>
true

If true (default), namespace will be checked for its validity

Returns:
Type: 
TNsPathResult

(async) buildCollections(options) → {Array.<Object>}

Method to transform config's array or object into an array of collection.

Parameters:
NameTypeDescription
optionsObject

Options

Properties
NameTypeAttributesDefaultDescription
nsstring<optional>

Namespace. If not provided, defaults to bajo

handlerfunction<optional>

Handler to call while building the collection item

dupChecksArray.<string><optional>
[]

Array of keys to check for duplicates

containerstring

Key used as container name

useDefaultNameboolean<optional>
true

If true (default) and name key is not provided, returned collection will be named default

Returns:

The collection

Type: 
Array.<Object>

buildNsPath(optionsopt) → {TNsPathPairs}

Build ns/path pairs

Parameters:
NameTypeAttributesDefaultDescription
optionsobject<optional>
{}

Options object

Properties
NameTypeAttributesDefaultDescription
nsstring<optional>
''

Namespace

subNsstring<optional>

Sub namespace

subSubNsstring<optional>

Sub sub namespace

pathstring<optional>

Path

Returns:
  • Ns/path pairs
Type: 
TNsPathPairs

(async) callHandler(name, …argsopt) → {any}

Calling any plugin's method by its name:

  • If name is a string, the corresponding plugin's method will be called with passed args as its parameters
  • If name is a plugin instance, this will be used as the scope instead. The first args is now the handler name and the rest are its parameters
  • If name is a function, this function will be run under scope with the remaining args
  • If name is an object and has handler key in it, this function handler will be instead
Parameters:
NameTypeAttributesDescription
nameTNsPathPairs | Object | function

Method's name, function handler, plain object or plugin instance

argsany<optional>
<repeatable>

One or more arguments passed as parameter to the handler

Returns:

Returned value

Type: 
any

(async) eachPlugins(handler, optionsopt) → {any}

This function iterates through all loaded plugins and call the provided handler scoped as the running plugin. And an object with the following key serves as its parameter:

  • file: file matched the glob pattern
  • dir: plugin's base directory
Parameters:
NameTypeAttributesDefaultDescription
handlerfunction

Function handler. Can be an async function. Scoped to the running plugin

optionsstring | Object<optional>
{}

Options. If a string is provided, it serves as the glob pattern, otherwise:

Properties
NameTypeAttributesDefaultDescription
globstring | Array.<string><optional>

Glob pattern. If provided,

useBajoboolean<optional>
false

If true, add bajo to the running plugins too

prefixstring<optional>
''

Prepend glob pattern with prefix

noUnderscoreboolean<optional>
true

If true (default), matched file with name starts with underscore is ignored

returnItemsany<optional>

If true, each value of returned handler call will be saved as an object with running plugin name as its keys

Returns:
Type: 
any

findDeep(item, paths) → {string}

Find item deep in paths

Parameters:
NameTypeDescription
itemstring

Item to find

pathsArray

Array of path to look for

Returns:
Type: 
string

format(value, typeopt, optionsopt) → {string}

Format value

Parameters:
NameTypeAttributesDefaultDescription
valueany

Value to format

typestring<optional>

Data type to use. See TBajoDataType for acceptable values. If not provided, return the untouched value

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
emptyValuestring<optional>
''

Empty value to use if function resulted empty. Defaults to the one from your config

withUnitboolean<optional>
true

Return with its unit appended

langstring<optional>

Format value according to this language. Defaults to the one you set in config

latitudestring<optional>

If Bajo Spatial is loaded and data type is a double or float, then format it as latitude in degree, minute, second

longitudestring<optional>

If Bajo Spatial is loaded and data type is a double or float, then format it as longitude in degree, minute, second

Returns:

Formatted value

Type: 
string

formatByType(type, value, dataTypeopt, optionsopt) → {Array|string}

Format value by type

Parameters:
NameTypeAttributesDefaultDescription
typestring

Format type. See TBajoFormatType for acceptable values

valueany

Value to format

dataTypestring<optional>

Value's data type. See TBajoDataType for acceptable values

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
withUnitboolean<optional>
true

Return with its unit appended

langstring<optional>

Format value according to this language. Defaults to the one you set in config

Returns:

Return string if withUnit is true. Otherwise is an array of [value, unit, separator]

Type: 
Array | string

freeze(obj, shallowopt)

Freeze object

Parameters:
NameTypeAttributesDefaultDescription
objObject

Object to freeze

shallowboolean<optional>
false

If false (default), deep freeze object

generateId(optionsopt) → {string|Object}

Generate unique random characters that can be used as ID. Use nanoid under the hood

Parameters:
NameTypeAttributesDefaultDescription
optionsboolean | string | Object<optional>
{}

Options. If set to true or alpha, it will generate alphaphet only characters. If set to int, it will generate integer only characters. Otherwise:

Properties
NameTypeAttributesDefaultDescription
patternstring<optional>

Character pattern to use. Defaults to all available alphanumeric characters

lengthnumber<optional>
13

Length of resulted characters

casestring<optional>

If set to lower to use lower cased pattern only. For upper cased pattern, set it to upper

returnInstanceboolean<optional>

Set to true to return nanoid instance instead of string

Returns:

Return string or instance of nanoid

Type: 
string | Object

getGlobalModuleDir(pkgNameopt, silentopt) → {string}

Get NPM global module directory

Parameters:
NameTypeAttributesDefaultDescription
pkgNamestring<optional>

If provided, return this package global directory. Otherwise the npm global module directory

silentboolean<optional>
true

Set to false to throw exception in case of error. Otherwise silently returns undefined

Returns:
Type: 
string

getMethod(name, thrownopt) → {function}

Get class method by name

Parameters:
NameTypeAttributesDefaultDescription
namestring

Name in format ns:methodName

thrownboolean<optional>
true

If true (default), throw exceptiom in case of error

Returns:

Class method

Type: 
function

getModuleDir(pkgName, base) → {string}

Get module directory, locally and globally

Parameters:
NameTypeDescription
pkgNamestring

Package name to find

basestring

Provide base name if pkgName is a module under base's package name

Returns:

Return absolute package directory

Type: 
string

getPlugin(name, silentopt) → {Object}

Get plugin by name

Parameters:
NameTypeAttributesDescription
namestring

Plugin name/namespace or alias

silentboolean<optional>

If true, silently return undefined even on error

Returns:

Plugin object

Type: 
Object

getPluginDataDir(name, ensureDiropt) → {string}

Get plugin data directory

Parameters:
NameTypeAttributesDefaultDescription
namestring

Plugin name (namespace) or alias

ensureDirboolean<optional>
true

Set true (default) to ensure directory is existed

Returns:
Type: 
string

getPluginFile(file) → {string}

Resolve file path from:

  • local/absolute file
  • TNsPath (myPlugin:/path/to/file.txt)
Parameters:
NameTypeDescription
filestring

File path, see above for supported types

Returns:

Resolved file path

Type: 
string

getUnitFormat(optionsopt) → {TBajoFormatResult}

Get unit format

Parameters:
NameTypeAttributesDefaultDescription
optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDescription
langstring<optional>

Language to use. Defaults to the one you set in config

unitSysstring<optional>

Unit system to use. Defaults to language's unit system or metric if unspecified

Returns:
  • Returned value
Type: 
TBajoFormatResult

(async) importModule()

Import file/module from any loaded plugins.

Method proxy from module:Lib.importModule

(async) importPkg(…pkgs) → {Object|Array}

Import one or more packages belongs to a plugin.

If the last arguments passed is an object, this object serves as options object:

  • returnDefault: should return package's default export. Defaults to true
  • throwNotFound: should throw if package is not found. Defaults to false
  • noCache: always use fresh import. Defaults to false
  • asObject: see below. Defaults to false

Return value:

  • if options.asObject is true (default false), return as object with package's names as it's keys
  • Otherwise depends on how many parameters are provided, it should return the named package or an array of packages

Example: you want to import delay and chalk from bajo plugin because you want to use it in your code

const { importPkg } from this.app.bajo
const [delay, chalk] = await importPkg('bajo:delay', 'bajo:chalk')

await delay(1000)
...
Parameters:
NameTypeAttributesDescription
pkgsTNsPathPairs<repeatable>

One or more packages in format {ns}:{packageName}

Returns:

See above

Type: 
Object | Array

(async) isEmptyDir(dir, filterFn) → {boolean}

Check whether a directory is empty or not. More info please check here.

Parameters:
NameTypeDescription
dirstring | TNsPathPairs

Directory to check

filterFnfunction

Filter function to filter out files that cause false positives.

Returns:
Type: 
boolean

isLogInRange(level) → {boolean}

Check whether log level is within log's app current level

Parameters:
NameTypeDescription
levelstring

Level to check. See TLogLevels for more

Returns:
Type: 
boolean

isValidApp(dir, returnPkgopt) → {boolean|Object}

Check whether directory is a valid Bajo app

Parameters:
NameTypeAttributesDescription
dirstring

Directory to check

returnPkgboolean<optional>

Set true to return its package.json content

Returns:
Type: 
boolean | Object

isValidPlugin(dir, returnPkgopt) → {boolean|Object}

Check whether directory is a valid Bajo plugin

Parameters:
NameTypeAttributesDescription
dirstring

Directory to check

returnPkgboolean<optional>

Set true to return its package.json content

Returns:
Type: 
boolean | Object

join(array, options) → {string}

Human friendly join array of items.

Parameters:
NameTypeDescription
arrayArray.<any>

Array to join

optionsstring | Object

If provided and is a string, it will be used as separator

Properties
NameTypeAttributesDefaultDescription
separatorstring<optional>
', '

Separator to use

lastSeparatorstring<optional>
and

Text to use as the last separator

Returns:
Type: 
string

numUnit(valueopt, defUnitopt) → {string}

Return its numeric portion of a value

Parameters:
NameTypeAttributesDefaultDescription
valuestring<optional>
''

Value to get its numeric portion

defUnitstring<optional>
''

Default unit if value doesn't have one

Returns:
Type: 
string

parseDt(dt) → {Object}

Parse datetime string as Javascript date object. Please visit dayjs for valid formats and more infos

Parameters:
NameTypeDescription
dtstring

Datetime string

Returns:

Javascript date object

Type: 
Object

parseDur(dur) → {number}

Parse duration to its millisecond value. Use ms under the hood

Parameters:
NameTypeDescription
durnumber | string

If string is given, parse this to its millisecond value. Otherwise returns as is

See
Returns:
Type: 
number

parseObject(input, optionsopt) → {Object}

Parse an object and optionally normalize its values recursively. Use https://github.com/ladjs/dotenv-parse-variables to parse values, so please have a visit to know how it works

If options.parseValue is true, any key ends with Dur and Dt will also be parsed as millisecond and Javascript date time accordingly.

Parameters:
NameTypeAttributesDefaultDescription
inputObject | string

If string is given, parse it first using JSON.parse

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
silentboolean<optional>
true

If true (default), exception are not thrown and silently ignored

parseValueboolean<optional>
false

If true, values will be parsed & normalized

langstring<optional>

If provided, use this language instead of the one in config

Returns:
Type: 
Object

(async) readAllConfigs(path) → {Object}

Read all config files by path

Parameters:
NameTypeDescription
pathstring

Base path to start looking config files

Returns:
Type: 
Object

(async) readConfig(file, optionsopt) → {Object}

Read and parse file as config object. Supported types: .js and .json. More supports can be added using plugin. bajo-config gives you additional supports for .yml, .yaml and .toml file

If file extension is .*, it will be auto detected and parsed accordingly

Parameters:
NameTypeAttributesDefaultDescription
filestring

File to read and parse

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
ignoreErrorboolean<optional>

Any exception will be silently discarded

nsstring<optional>

If given, use this as the scope

patternstring<optional>

If given and auto detection is on (extension is .*), it will be used for instead the default one

globOptionsObject<optional>
{}

fast-glob options

defValueObject<optional>
{}

Default value to use if value returned empty

optsObject<optional>
{}

Parser setting

Returns:
Type: 
Object

readJson(file, thrownNotFoundopt) → {Object}

Read and parse json file

Parameters:
NameTypeAttributesDefaultDescription
filestring

File to read

thrownNotFoundboolean<optional>
false

If true, silently ignore if file is not found

Returns:
Type: 
Object

resolvePath(file, asFileUrlopt) → {string}

Resolve file name to filesystem's path. Windows path separator \ is normalized to Unix's /

Parameters:
NameTypeAttributesDefaultDescription
filestring

File to resolve

asFileUrlboolean<optional>
false

Return as file URL format file:///<name>

Returns:
Type: 
string

(async) runHook(hookName, …argsopt) → {Array}

Run named hook/event

Parameters:
NameTypeAttributesDescription
hookNameTNsPathPairs
argsany<optional>
<repeatable>

Argument passed to the hook function

Returns:

Array of hook execution results

Type: 
Array

(async) saveAsDownload(file, item, printSavedopt) → {string}

Save item as file in Bajo's download directory. That is a directory inside your Bajo plugin's data directory.

If file exists already, file will automatically be renamed incrementally.

Parameters:
NameTypeAttributesDefaultDescription
filestring

File name

itemObject

Item to save

printSavedboolean<optional>
true

Print info on screen

Returns:

Full file path

Type: 
string