Plugin Authoring Guide

A custom plugin is a factory that returns hooks:

// pb_pages/_private/my-plugin.ts
module.exports = (config) => ({
  name: 'my-plugin',
  onRequest(ctx) {},                                   // before middleware
  extendContext(ctx) { ctx.hello = () => 'hi' },
  transform({ html, ctx, file }) { return html },      // after each template or layout renders
})

Turn it on in +config.ts:

module.exports = {
  plugins: ['my-plugin'], // pb_pages/_private/my-plugin.ts
}

config

config is the plugin's entry in +config.ts when that entry is an object ({ factory, ...options }), else {}:

module.exports = {
  plugins: [{ factory: require('./_private/banner.ts'), text: 'Beta' }],
}
// pb_pages/_private/banner.ts
module.exports = (config) => ({
  name: 'banner',
  transform({ html }) {
    return html.replace('<body>', `<body><div class="banner">${config.text}</div>`)
  },
})

Hooks

Every hook is optional. Hooks run in the order plugins are listed in +config.ts.

Hook When
name The plugin's name.
onRequest(ctx) At the start of each request, before middleware.
extendContext(ctx) Add members to ctx.
transform({ html, ctx, file }) After each template or layout renders. Return the new HTML.

Example: a context helper

module.exports = () => ({
  name: 'format',
  extendContext(ctx) {
    ctx.formatDate = (d) => new Date(d).toLocaleDateString()
  },
})
<p>Posted <%= ctx.formatDate(data.post.getString('created')) %></p>

Permissions

Custom plugins run with the same permissions as the rest of the app's code. Under a multitenant host, that means the instance's sandbox.