All files / src/plugins Plugin.ts

86.04% Statements 37/43
75% Branches 9/12
84.61% Functions 11/13
88.09% Lines 37/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166                          11x   11x                                                                           24x           24x   24x     24x 24x         40x 10x                               18x 18x   18x 18x       18x 18x   18x   18x 18x         18x       18x             36x 36x   36x 18x 18x 18x     36x           36x             64x     64x       224x 56x     168x       224x 168x     56x       24x      
import path from 'path';
import { createRequire } from 'module';
import fs from 'fs-extra';
import cheerio from 'cheerio';
 
import _ from 'lodash';
import * as logger from '../utils/logger.js';
import * as urlUtil from '../utils/urlUtil.js';
import type { NodeProcessorConfig } from '../html/NodeProcessor.js';
import { NodeOrText } from '../utils/node.js';
 
import '../patches/htmlparser2.js';
 
const require = createRequire(import.meta.url);
 
const PLUGIN_OUTPUT_SITE_ASSET_FOLDER_NAME = 'plugins';
 
export type PluginContext = Record<string, any>;
 
export type FrontMatter = Record<string, any>;
 
type TagConfigAttributes = {
  name: string,
  isRelative: boolean,
  isSourceFile: boolean
};
 
export type TagConfigs = {
  isSpecial?: boolean,
  attributes?: TagConfigAttributes[],
  isCustomElement?: boolean,
};
 
/**
 * Wrapper class around a loaded plugin module
 */
export class Plugin {
  pluginName: string;
  plugin: {
    beforeSiteGenerate: (...args: any[]) => any;
    getLinks: (pluginContext?: PluginContext, frontmatter?: FrontMatter, content?: string) => string[];
    getScripts: (pluginContext?: PluginContext, frontmatter?: FrontMatter, content?: string) => string[];
    postRender: (pluginContext: PluginContext, frontmatter: FrontMatter, content: string) => string;
    processNode: (pluginContext: PluginContext, node: NodeOrText, config?: NodeProcessorConfig) => string;
    postProcessNode: (pluginContext: PluginContext, node: NodeOrText, config?: NodeProcessorConfig) => string;
    tagConfig: Record<string, TagConfigs>;
  };
 
  pluginOptions: PluginContext;
  pluginAbsolutePath: string;
  pluginAssetOutputPath: string;
 
  constructor(pluginName: string, pluginPath: string, pluginOptions: PluginContext, siteOutputPath: string) {
    this.pluginName = pluginName;
 
    /**
     * The plugin module
     */
    // eslint-disable-next-line import/no-dynamic-require
    this.plugin = require(pluginPath);
 
    this.pluginOptions = pluginOptions || {};
 
    // For resolving plugin asset source paths later
    this.pluginAbsolutePath = path.dirname(pluginPath);
    this.pluginAssetOutputPath = path.join(siteOutputPath, PLUGIN_OUTPUT_SITE_ASSET_FOLDER_NAME,
                                           path.basename(pluginPath, path.extname(pluginPath)));
  }
 
  executeBeforeSiteGenerate() {
    if (this.plugin.beforeSiteGenerate) {
      this.plugin.beforeSiteGenerate(this.pluginOptions);
    }
  }
 
  /**
   * Resolves a resource specified as an attribute in a html asset tag
   * (eg. '<script>' or '<link>') provided by a plugin, and copies said asset
   * into the plugin's asset output folder.
   * Does nothing if the resource is a url.
   * @param assetElementHtml The asset element html, as a string, such as '<script src="...">'
   * @param tagName The name of the resource tag
   * @param attrName The attribute name where the resource is specified in the tag
   * @param baseUrl baseUrl of the site
   * @return String html of the element, with the attribute's asset resolved
   */
  _getResolvedAssetElement(assetElementHtml: string, tagName: string, attrName: string, baseUrl: string) {
    const $ = cheerio.load(assetElementHtml);
    const el = $(`${tagName}[${attrName}]`);
 
    el.attr(attrName, (_i: any, assetPath: any): string => {
      Iif (!assetPath || !_.isString(assetPath) || urlUtil.isUrl(assetPath)) {
        return assetPath;
      }
 
      const srcPath = path.resolve(this.pluginAbsolutePath, assetPath);
      const srcBaseName = path.basename(srcPath);
 
      fs.ensureDir(this.pluginAssetOutputPath)
        .then(() => {
          const outputPath = path.join(this.pluginAssetOutputPath, srcBaseName);
          fs.copySync(srcPath, outputPath, { overwrite: false });
        })
        .catch(err => logger.error(
          `Failed to copy asset ${assetPath} for plugin ${this.pluginName}\n${err}`));
 
      return path.posix.join(`${baseUrl}/`, PLUGIN_OUTPUT_SITE_ASSET_FOLDER_NAME,
                             this.pluginName, srcBaseName);
    });
 
    return $.html();
  }
 
  /**
   * Collect page content inserted by plugins
   */
  getPageNjkLinksAndScripts(frontmatter: FrontMatter, content: string, baseUrl: string) {
    let links: string[] = [];
    let scripts: string[] = [];
 
    if (this.plugin.getLinks) {
      const pluginLinks = this.plugin.getLinks(this.pluginOptions, frontmatter, content);
      links = pluginLinks.map(
        (linkHtml: string) => this._getResolvedAssetElement(linkHtml, 'link', 'href', baseUrl));
    }
 
    Iif (this.plugin.getScripts) {
      const pluginScripts = this.plugin.getScripts(this.pluginOptions, frontmatter, content);
      scripts = pluginScripts.map((scriptHtml: string) => this._getResolvedAssetElement(scriptHtml, 'script',
                                                                                        'src', baseUrl));
    }
 
    return {
      links,
      scripts,
    };
  }
 
  postRender(frontmatter: FrontMatter, content: string) {
    Iif (this.plugin.postRender) {
      return this.plugin.postRender(this.pluginOptions, frontmatter, content);
    }
    return content;
  }
 
  processNode(node: NodeOrText, config: NodeProcessorConfig) {
    if (!this.plugin.processNode) {
      return;
    }
 
    this.plugin.processNode(this.pluginOptions, node, config);
  }
 
  postProcessNode(node: NodeOrText, config: NodeProcessorConfig) {
    if (!this.plugin.postProcessNode) {
      return;
    }
 
    this.plugin.postProcessNode(this.pluginOptions, node, config);
  }
 
  getTagConfig() {
    return this.plugin.tagConfig;
  }
}