Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

serve-markdown-it-lib

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

serve-markdown-it-lib

Shared utility library for serve-markdown-it

  • 1.0.5
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
0
decreased by-100%
Maintainers
1
Weekly downloads
 
Created
Source

serve-markdown-it-lib

NPM Version Build Status Downloads Stats

Shared utility library for sermit

Installation

npm badge

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

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

API Reference

The standalone JSDoc reference can be found in DOCUMENTATION.md

Modules

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.

Classes

PathDoesNotExistErrorError

Error thrown when a path does not exist.

Functions

renderAssets(params)Promise

Renders a map of { [dest]: src } path pairs representing static assets, either files or folders.

renderStyles(params)Promise

Renders a map of { [dest]: src } path pairs representing SCSS stylesheets.

explodePath(params)Array.<strings>

Generates an array of paths from '/' up to the provided path.

fsStat(path, [returnError])Promise

Safe wrapper for fs.stat with returns null or Error on failure instead of throwing.

getGitIgnore(config)ignore

Attempts to load any .gitignore file in the configured content root and returns a configured instance of ignore.

getLogger(scope)Signale

Creates a new scoped signale logger instance.

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.

logModuleResolved(moduleName, modulePath, [params])

Logs successful module resolution.

resolveGlobal(moduleName, [params])string | null

Safe wrapper around external:resolve-global that returns null on failure instead of throwing.

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.

resolveModule(moduleName, [paths])null | string

Safe wrapper around require.resolve that retuns null on failure instead of throwing an error.

readAsset(config, assetPath)AssetData

Attempts to read a template asset from disk.

Typedefs

AssetData : object

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.

new PathDoesNotExistError(path, [fsError], [color], [message], [stack])

Create a new PathDoesNotExistError object.

ParamTypeDescription
pathstringpath that does not exist.
[fsError]string | Errororiginal native error or native message.
[color]booleanenables colorized message.
[message]stringerror 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

ParamTypeDefaultDescription
pathstringpath that does not exist.
[fsError]string | Errororiginal native error or native message.
[color]booleantruecolorizes 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

ParamTypeDescription
paramsobjectparams.
params.assetsobjectasset dest paths key'ed by src path. Source paths starting with ~ are assumed module paths, and loaded via requireDynamicModule.
params.srcPathstringabsolute path to asset src folder.
params.buildPathstringabsolute path to asset build folder.
[params.requirePath]stringpath to directory containing node_modules; used to resolve module assets, not passed to require.resolve!
[params.quiet]booleanif false, progress is logged to the. console.
[params.dry]booleanif 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

ParamTypeDescription
paramsobjectparams.
params.stylesobjectscss stylesheet dest paths key'ed by src path.
params.includePathsArray.<string>array of absolute include paths to resolve @import statements.
params.srcPathstringabsolute path to scss src folder.
params.buildPathstringabsolute path to scss build folder.
[params.quiet]booleanif false, progress is logged to the. console.
[params.dry]booleanif 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

ParamTypeDefaultDescription
paramsobjectparams
params.fromPathstringpath to explode.
[params.directory]booleanindicates 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.

ParamTypeDefaultDescription
pathstringpath to pass to fs.stat
[returnError]booleanfalseif 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

ParamTypeDescription
configConfigconfiguration 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

ParamTypeDescription
scopestringscope

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

ParamTypeDescription
absPathstringabsolute path
configConfigconfig

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

ParamTypeDefaultDescription
moduleNamestringname of module.
modulePathstringpath to module.
[params]object{}optional params
[params.logger]Signalesignale logger instance, defaults to plain unscoped logger.
[params.lType]string"'debug'"signale logger type to use.
[params.loaded]booleanindicates if module was loaded or only the path was resolved.
[params.color]booleanenables 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

ParamTypeDescription
moduleNamestringmodule to resolve globally.
[params]objectoptional params
[params.prefix]stringresolved path prefix
[params.suffix]stringresolved 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.
ParamTypeDefaultDescription
moduleNamestringname of module passed to require.resolve.
configConfigconfiguration, with basePath set.
[load]booleantrueif 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.

ParamTypeDefaultDescription
moduleNamestringname 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

ParamTypeDescription
configConfigconfiguration, with basePath set.
assetPathstringrelative 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

NameTypeDescription
srcBufferasset contents
typestringmime type, defaults to 'text/plain' if not resolved.

Keywords

FAQs

Package last updated on 04 Jul 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc