serve-markdown-it-lib
v1.0.5
Published
Shared utility library for serve-markdown-it
Downloads
6
Maintainers
Readme
serve-markdown-it-lib
Shared utility library for sermit
Installation
yarn add serve-markdown-it-lib
Developing
yarn gen-readme // update README.md
yarn docs // update DOCUMENTATION.md
yarn test // lint & mocha
yarn update-deps // bump all deps
Release History
See CHANGELOG.md for more information.
License
Distributed under the MIT license. See LICENSE.md for more information.
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
API Reference
The standalone JSDoc reference can be found in DOCUMENTATION.md
Modules
Classes
Functions
Typedefs
serve-markdown-it-lib
Shared utility library for the serve-markdown-it utility and supported templates, plugins, and other extensions. Provides general utilities (@see requireDynamicModule), and methods to render template (@see serve-markdown-it-template-default) assets and SCSS stylesheets.
See: serve-markdown-it
License: MIT
PathDoesNotExistError ⇐ Error
Error thrown when a path does not exist.
Kind: global class
Extends: Error
Todo
- [ ] colorize stack trace if
color
enabled.
- PathDoesNotExistError ⇐ Error
new PathDoesNotExistError(path, [fsError], [color], [message], [stack])
Create a new PathDoesNotExistError object.
| Param | Type | Description | | --- | --- | --- | | path | string | path that does not exist. | | [fsError] | string | Error | original native error or native message. | | [color] | boolean | enables colorized message. | | [message] | string | error message override | | [stack] | Array.<string> | stack trace override |
Example
const err = new PathDoesNotExistError('/some/path')
console.log(`non-existent path: ${err.path}`)
console.log(`non-existent path parts: ${err.parts}`)
console.log(`non-existent path dir name: ${err.dirname}`)
console.log(`non-existent path base name: ${err.basename}`)
console.log(`non-existent path extension: ${err.extname}`)
console.error(err.stack)
pathDoesNotExistError.path ⇒ string
Get the non-existent path.
Kind: instance property of PathDoesNotExistError
Returns: string - path - path supplied to error.
pathDoesNotExistError.parts ⇒ Array.<string>
Get the non-existent path parts.
Kind: instance property of PathDoesNotExistError
Returns: Array.<string> - pathParts - path split by system path seperator.
pathDoesNotExistError.color ⇒ boolean
Get the color setting.
Kind: instance property of PathDoesNotExistError
Returns: boolean - color - indicates if the error message will be
colorized
pathDoesNotExistError.fsError ⇒ Error
Get the original FS error object.
Kind: instance property of PathDoesNotExistError
Returns: Error - fsError
PathDoesNotExistError.message(path, [fsError], [color]) ⇒ string
Generate a messsage for PathDoesNotExistError.
Kind: static method of PathDoesNotExistError
Returns: string - message - error message
| Param | Type | Default | Description | | --- | --- | --- | --- | | path | string | | path that does not exist. | | [fsError] | string | Error | | original native error or native message. | | [color] | boolean | true | colorizes message. |
Example
const message = PathDoesNotExistError.genMessage('/some/path')
console.log(message)
renderAssets(params) ⇒ Promise
Renders a map of { [dest]: src }
path pairs representing static assets,
either files or folders.
Kind: global function
Returns: Promise - p
| Param | Type | Description |
| --- | --- | --- |
| params | object | params. |
| params.assets | object | asset dest paths key'ed by src path. Source paths starting with ~
are assumed module paths, and loaded via requireDynamicModule. |
| params.srcPath | string | absolute path to asset src folder. |
| params.buildPath | string | absolute path to asset build folder. |
| [params.requirePath] | string | path to directory containing node_modules
; used to resolve module assets, not passed to require.resolve
! |
| [params.quiet] | boolean | if false, progress is logged to the. console. |
| [params.dry] | boolean | if true, progress is logged but not files are modified. |
Example (rendering assets to `public/`)
renderAssets({
dry: true,
quiet: false,
requirePath: path.join(__dirname, '../'),
buildPath: path.join(__dirname, '../public'),
srcPath: path.join(__dirname, '../res/assets'),
assets: {
fonts: 'fonts', // asset folder
'css/highlightjs': '~highlight.js/styles' // module folder
}
})
renderStyles(params) ⇒ Promise
Renders a map of { [dest]: src }
path pairs representing SCSS stylesheets.
Kind: global function
Returns: Promise - p - resolves to array of rendered CSS stylesheets
| Param | Type | Description |
| --- | --- | --- |
| params | object | params. |
| params.styles | object | scss stylesheet dest paths key'ed by src path. |
| params.includePaths | Array.<string> | array of absolute include paths to resolve @import
statements. |
| params.srcPath | string | absolute path to scss src folder. |
| params.buildPath | string | absolute path to scss build folder. |
| [params.quiet] | boolean | if false, progress is logged to the. console. |
| [params.dry] | boolean | if true, progress is logged but not files are modified. |
Example (rendering styles to `public/css`)
renderStyles({
dry: true,
quiet: false,
requirePath: path.join(__dirname, '../'),
buildPath: path.join(__dirname, '../public/css'),
srcPath: path.join(__dirname, '../res/styles'),
styles: {
'index.css': 'index.scss'
}
})
explodePath(params) ⇒ Array.<strings>
Generates an array of paths from '/' up to the provided path.
Kind: global function
Returns: Array.<strings> - paths
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| params | object | | params |
| params.fromPath | string | | path to explode. |
| [params.directory] | boolean | | indicates basePath
is a directory; if not provided, the path is checked to resolve directory/file. |
| [params.prefix] | string | "''" | prefix for all generated paths. |
| [params.suffix] | string | "''" | suffix for all generated paths. |
| [params.paths] | Array.<Array> | [] | target array to append generated paths too |
Example
await explodePath(__dirname, { prefix: '/', suffix: 'node_modules' })
const module = require.resolve(moduleName, { paths: searchPaths })
fsStat(path, [returnError]) ⇒ Promise
Safe wrapper for fs.stat
with returns null
or Error
on failure instead
of throwing.
Kind: global function
Returns: Promise - p - resolves to Stats
, null
, or Error
object on
failure.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| path | string | | path to pass to fs.stat
|
| [returnError] | boolean | false | if true, Error
object is returned on failure instead of null
. |
Example
const _isNull = require('lodash/isNull')
const _isError = require('lodash/isError')
info = await statPath('/some/path')
if (_isNull(info)) {
console.log('path does not exist')
} else {
console.log('path stats: ', JSON.stringify(info))
}
info = await statPath('/some/path', true)
if (_isError(info)) {
console.error(info.stack)
} else {
console.log('path stats: ', JSON.stringify(info))
}
getGitIgnore(config) ⇒ ignore
Attempts to load any .gitignore
file in the configured content root
and returns a configured instance of ignore.
Kind: global function
Returns: ignore - ignore
| Param | Type | Description |
| --- | --- | --- |
| config | Config | configuration data, with basePath
set. |
Example (load `.gitignore` and filter paths)
const nodes = {}
const ig = await getGitIgnore(config)
const allNodes = await fs.readdir(srcPath, { withFileTypes: true })
allNodes
.filter(n => n.isFile() || n.isDirectory())
.forEach((n) => { nodes[n.name] = n })
const visibleNodes = excludeGitIgnore
? ig.filter(_keys(nodes)).map(n => nodes[n])
: _keys(nodes).map(n => nodes[n])
// do something with visibleNodes array...
getLogger(scope) ⇒ Signale
Creates a new scoped signale logger instance.
Kind: global function
Returns: Signale - l
| Param | Type | Description | | --- | --- | --- | | scope | string | scope |
Example
const l = getLogger('template:render-md')
getRelativePath(absPath, config) ⇒ string
Converts the provided absolute path to a path relative to the configured
content root, with a /
prefix for linking in rendered HTML.
Kind: global function
Returns: string - relPath
| Param | Type | Description | | --- | --- | --- | | absPath | string | absolute path | | config | Config | config |
Example
const { state } = config
const { template } = state
const { genRawSrcMarkdown } = template
const relPath = getRelativePath('/home/user/markdown-it/README.md', config)
await genRawSrcMarkdown({ relPath, ...genData })
logModuleResolved(moduleName, modulePath, [params])
Logs successful module resolution.
Kind: global function
| Param | Type | Default | Description | | --- | --- | --- | --- | | moduleName | string | | name of module. | | modulePath | string | | path to module. | | [params] | object | {} | optional params | | [params.logger] | Signale | | signale logger instance, defaults to plain unscoped logger. | | [params.lType] | string | "'debug'" | signale logger type to use. | | [params.loaded] | boolean | | indicates if module was loaded or only the path was resolved. | | [params.color] | boolean | | enables colorized output. |
Example (log module resolution)
logModuleResolved('serve-markdown-it', process.cwd(), { color: false })
resolveGlobal(moduleName, [params]) ⇒ string | null
Safe wrapper around external:resolve-global that returns null
on
failure instead of throwing.
Kind: global function
Returns: string | null - globalModulePath
| Param | Type | Description | | --- | --- | --- | | moduleName | string | module to resolve globally. | | [params] | object | optional params | | [params.prefix] | string | resolved path prefix | | [params.suffix] | string | resolved path suffix |
Example
const modulePath = resolveGlobal('serve-markdown-it')
requireModule(moduleName, config, [load]) ⇒ object | function | string
Attempts to resolve a module by name from the configured basePath
,
searching every directory up from it, along with the local node_modules
folder. Call with load
false
to get the module path.
If the module cannot be resolved by walking the path, an attempt is made to load it from the global module path.
Kind: global function
Returns: object | function | string - module
Throws:
- Error fails if the module is not resolved.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| moduleName | string | | name of module passed to require.resolve
. |
| config | Config | | configuration, with basePath
set. |
| [load] | boolean | true | if false, the resolved module path is returned instead of the loaded module. |
Example (load `markdown-it` anchor plugin)
const parserPlugin = requireModule('markdown-it-anchor', config)
resolveModule(moduleName, [paths]) ⇒ null | string
Safe wrapper around require.resolve
that retuns null
on failure instead
of throwing an error.
Kind: global function
Returns: null | string - modulePath - null on failure.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| moduleName | string | | name of module to resolve path to. |
| [paths] | null | Array.<string> | [] | paths to attempt resolve from; passed through _uniq
. |
Example (resolve from cwd)
const modulePath = resolveModule('serve-markdown-it-lib', [process.cwd()])
if (_isEmpty(modulePath)) {
return
}
const module = require(modulePath)
readAsset(config, assetPath) ⇒ AssetData
Attempts to read a template asset from disk.
Kind: global function
Returns: AssetData - data
| Param | Type | Description |
| --- | --- | --- |
| config | Config | configuration, with basePath
set. |
| assetPath | string | relative to template public
folder. |
Example (read and serve template asset)
const serveAsset = async (ctx, url, config) => {
try {
const { type, src } = await readAsset(config, url)
ctx.body = src
ctx.type = type
ctx.renderType = 'asset'
return true
} catch (e) {
return false
}
}
AssetData : object
Kind: global typedef
Properties
| Name | Type | Description | | --- | --- | --- | | src | Buffer | asset contents | | type | string | mime type, defaults to 'text/plain' if not resolved. |