# All files / src/html includePanelProcessor.ts

87.86% Statements 152/173
75% Branches 42/56
100% Functions 12/12
87.86% Lines 152/173

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
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    4057x
    7x
    7x

    7x
    7x
    7x
    7x

    7x
    7x
    7x

    7x

    7x

    218x
    2x
    1x

    1x

    1x

    1x

    1x
    1x

    216x

    219x
    219x

    219x

    219x

    219x

    219x
    1x

    218x

    218x
    218x

    219x
    219x

    219x

    7x

    4x
    4x
    4x

    112x
    118x

    112x
    112x
    112x
    112x
    112x
    112x

    116x

    1x
    1x

    116x

    7x

    116x
    1x
    1x
    1x
    1x

    115x

    115x

    115x
    115x
    115x
    2x

    113x
    113x
    113x

    113x

    113x

    113x

    113x

    113x
    113x
    113x

    113x
    8x
    8x
    8x
    8x
    5x
    5x

    1x
    1x

    5x
    1x
    1x

    1x

    1x

    1x
    1x

    8x
    1x

    1x

    1x
    7x
    1x

    1x

    113x
    1x

    113x
    113x
    113x
    113x
    111x
    111x

    111x
    1x
    1x
    1x
    1x

    112x
    112x
    112x

    7x

    110x
    5x

    105x
    1x
    1x
    1x
    1x

    104x

    104x
    1x
    1x

    1x
    1x

    103x
    103x

    103x

    103x

    103x
    103x
    103x

    103x
    1x
    1x

    1x
    1x

    1x

    1x

    1x

    102x

    102x
    101x

    101x
    1x
    1x
    1x
    1x

    101x
    101x

    101x

    101x

     import cheerio from 'cheerio';
    import path from 'path';
    import parse from 'url-parse';

    import has from 'lodash/has';
    import isEmpty from 'lodash/isEmpty';
    import { createErrorNode, createSlotTemplateNode } from './elements';
    import CyclicReferenceError from '../errors/CyclicReferenceError';

    import * as fsUtil from '../utils/fsUtil';
    import * as logger from '../utils/logger';
    import * as urlUtil from '../utils/urlUtil';
    import type { Context } from './Context';
    import type { PageSources } from '../Page/PageSources';
    import type { VariableProcessor } from '../variables/VariableProcessor';
    import { MbNode, NodeOrText } from '../utils/node';
    import { SiteLinkManager } from './SiteLinkManager';

    require('../patches/htmlparser2');

    const _ = { has, isEmpty };

    /*
     * Common panel and include helper functions
     */

    /**
     * Returns a boolean representing whether the file specified exists.
     */
    function _checkAndWarnFileExists(element: MbNode, context: Context, actualFilePath: string,
                                     pageSources: PageSources, isOptional = false) {
      if (!fsUtil.fileExists(actualFilePath)) {
        if (isOptional) {
          return false;
        }

        pageSources.missingIncludeSrc.push({
          from: context.cwf,
          to: actualFilePath,
        });
        const error = new Error(
          `No such file: ${actualFilePath}\nMissing reference in ${context.cwf}`);
        logger.error(error.message);

        createErrorNode(element, error);
        return false;
      }

      return true;
    }

    function _getBoilerplateFilePath(element: MbNode, filePath: string, config: Record<string, any>) {
      const isBoilerplate = _.has(element.attribs, 'boilerplate');
      Iif (isBoilerplate) {
        element.attribs.boilerplate = element.attribs.boilerplate || path.basename(filePath);

        return urlUtil.calculateBoilerplateFilePath(element.attribs.boilerplate, filePath, config);
      }

      return undefined;
    }

    /**
     * Retrieves several flags and file paths from the src attribute specified in the element.
     */
    function _getSrcFlagsAndFilePaths(element: MbNode, config: Record<string, any>) {
      const isUrl = urlUtil.isUrl(element.attribs.src);

      // We do this even if the src is not a url to get the hash, if any
      const includeSrc = parse(element.attribs.src);

      let filePath;
      if (isUrl) {
        filePath = element.attribs.src;
      } else {
        const includePath = decodeURIComponent(includeSrc.pathname).replace(/\\/g, path.sep);

        /*
         If the src starts with the baseUrl (or simply '/' if there is no baseUrl specified),
         get the relative path from the rootPath first,
         then use it to resolve the absolute path of the referenced file on the filesystem.
         */
        const relativePathToFile = path.posix.relative(`${config.baseUrl}/`, includePath);
        filePath = path.resolve(config.rootPath, relativePathToFile);
      }

      const boilerplateFilePath = _getBoilerplateFilePath(element, filePath, config);
      const actualFilePath = boilerplateFilePath || filePath;

      return {
        isUrl,
        hash: includeSrc.hash,
        filePath,
        actualFilePath,
      };
    }

    /*
     * Panels
     */

    /**
     * PreProcesses panels with a src attribute specified.
     * Replaces the panel with an error node if the src is invalid.
     * Otherwise, sets the fragment attribute of the panel as parsed from the src,
     * and adds the appropriate include.
     */
    export function processPanelSrc(node: MbNode, context: Context, pageSources: PageSources,
                                    config: Record<string, any>): Context {
      const hasSrc = _.has(node.attribs, 'src');
      if (!hasSrc) {
        return context;
      }

      const {
        isUrl,
        hash,
        filePath,
        actualFilePath,
        // We can typecast here as we have checked for src above.
      } = _getSrcFlagsAndFilePaths(node, config);

      const fileExists = _checkAndWarnFileExists(node, context, actualFilePath, pageSources);
      Iif (!fileExists) {
        return context;
      }

      Iif (!isUrl && hash) {
        node.attribs.fragment = hash.substring(1);
      }

      const { fragment } = node.attribs;
      const relativePath = fsUtil.setExtension(path.relative(config.rootPath, filePath), '._include_.html');
      const fullResourcePath = path.posix.join(`${config.baseUrl}/`, fsUtil.ensurePosix(relativePath));
      node.attribs.src = fragment ? `${fullResourcePath}#${fragment}` : fullResourcePath;

      delete node.attribs.boilerplate;

      pageSources.dynamicIncludeSrc.push({
        from: context.cwf,
        to: actualFilePath,
        asIfTo: filePath,
      });

      return context;
    }

    /*
     * Includes
     */

    function _deleteIncludeAttributes(node: MbNode) {
      // Delete variable attributes in include tags as they are no longer needed
      // e.g. '<include var-title="..." var-xx="..." />'
      Object.keys(node.attribs).forEach((attribute) => {
        Iif (attribute.startsWith('var-')) {
          delete node.attribs[attribute];
        }
      });

      delete node.attribs.boilerplate;
      delete node.attribs.src;
      delete node.attribs.inline;
      delete node.attribs.trim;
      delete node.attribs.optional;
      delete node.attribs.omitFrontmatter;
    }

    function buildGetNextFootnodeNumber() {
      let footnoteNumber = 0;
      function getFootnoteNumber() {
        footnoteNumber += 1;
        return footnoteNumber;
      }
      return getFootnoteNumber;
    }

    /**
     * PreProcesses includes.
     * Replaces it with an error node if the specified src is invalid,
     * or an empty node if the src is invalid but optional.
     */
    export function processInclude(node: MbNode, context: Context, pageSources: PageSources,
                                   variableProcessor: VariableProcessor, renderMd: (text: string) => string,
                                   renderMdInline: (text: string) => string,
                                   config: Record<string, any>, siteLinkManager: SiteLinkManager,
                                   getNextFootnodeNumber: () => number = buildGetNextFootnodeNumber()): Context {
      if (_.isEmpty(node.attribs.src)) {
        const error = new Error(`Empty src attribute in include in: ${context.cwf}`);
        logger.error(error.message);
        cheerio(node).replaceWith(createErrorNode(node, error));
        return context;
      }

      const {
        isUrl,
        hash,
        filePath,
        actualFilePath,
        // We can typecast here as we have checked for src above.
      } = _getSrcFlagsAndFilePaths(node, config);

      // No need to process url contents
      Iif (isUrl) {
        _deleteIncludeAttributes(node);
        return context;
      }

      const isOptional = _.has(node.attribs, 'optional');
      const fileExists = _checkAndWarnFileExists(node, context, actualFilePath, pageSources, isOptional);
      if (!fileExists) {
        return context;
      }

      const isInline = _.has(node.attribs, 'inline');
      const isTrim = _.has(node.attribs, 'trim');
      const shouldOmitFrontmatter = _.has(node.attribs, 'omitFrontmatter');

      node.name = isInline ? 'span' : 'div';

      pageSources.staticIncludeSrc.push({
        from: context.cwf,
        to: actualFilePath,
      });

      const {
        nunjucksProcessed,
        childContext,
      } = variableProcessor.renderIncludeFile(actualFilePath, pageSources, node, context, filePath);

      Iif (nunjucksProcessed.trim() === '') {
        const warning = `Empty file included in ${context.cwf}:\n`
            + `File: ${actualFilePath} is empty or contains only whitespace`;
        logger.warn(warning);
      }

      let actualContent = nunjucksProcessed;
      if (fsUtil.isMarkdownFileExt(path.extname(actualFilePath))) {
        actualContent = isInline
          ? renderMdInline(actualContent)
          : renderMd(actualContent);
      }

      // Process sources with or without hash, retrieving and appending
      // the appropriate children to a wrapped include element
      if (hash) {
        const $ = cheerio.load(actualContent);
        const actualContentOrNull = $(hash).html();
        actualContent = actualContentOrNull || '';
        if (actualContent !== '') {
          const hashNode = $(hash);
          const footnodeHrefs = hashNode.find('a[aria-describedby="footnote-label"]')
            .map(function (this: any) {
              $(this).text(`[${getNextFootnodeNumber()}]`);
              return $(this).attr('href');
            })
            .get();
          if (footnodeHrefs.length > 0) {
            const tempFootnotes = $('<mb-temp-footnotes></mb-temp-footnotes>');
            footnodeHrefs.forEach((href) => {
              // substring function called to remove the # from the href
              const listItem = $('<li></li>').attr('id', href.substring(1))
                .addClass('footnote-item')
                .html($(`${href}.footnote-item`).html()!);
              tempFootnotes.append(listItem);
            });
            hashNode.append(tempFootnotes);
            actualContent = hashNode.html()!;
          }
        }

        if (actualContentOrNull === null && !isOptional) {
          const error = new Error(`No such segment '${hash}' in file: ${actualFilePath}\n`
           + `Missing reference in ${context.cwf}`);
          logger.error(error.message);

          actualContent = cheerio.html(createErrorNode(node, error));
        } else if (actualContentOrNull === '') {
          const warning = `Empty reference in ${context.cwf}:\n`
              + `Segment '${hash}' in file: ${actualFilePath} is empty`;
          logger.warn(warning);
        }
      }

      if (isTrim) {
        actualContent = actualContent.trim();
      }
      const $includeEl = cheerio(node);
      $includeEl.empty();
      $includeEl.append(actualContent);
      if (node.children && node.children.length > 0) {
        childContext.addCwfToCallstack(context.cwf);
        childContext.processingOptions.omitFrontmatter = shouldOmitFrontmatter;

        if (childContext.hasExceededMaxCallstackSize()) {
          const error = new CyclicReferenceError(childContext.callStack);
          logger.error(error.message);
          cheerio(node).replaceWith(createErrorNode(node, error));
          return context;
        }
      }

      _deleteIncludeAttributes(node);
      siteLinkManager.maintainHashesForInclude(node, context.cwf);
      return childContext;
    }

    /**
     * PreProcesses popovers with the src attribute.
     * Replaces it with an error node if the specified src is invalid.
     * Else, appends the content to the node.
     */
    export function processPopoverSrc(node: MbNode, context: Context, pageSources: PageSources,
                                      variableProcessor: VariableProcessor, renderMd: (text: string) => string,
                                      config: Record<string, any>): Context {
      if (!_.has(node.attribs, 'src')) {
        return context;
      }

      if (_.isEmpty(node.attribs.src)) {
        const error = new Error(`Empty src attribute in popover in: ${context.cwf}`);
        logger.error(error.message);
        cheerio(node).replaceWith(createErrorNode(node, error));
        return context;
      }

      const {
        isUrl,
        hash,
        filePath,
        actualFilePath,
        // We can typecast here as we have checked for src above.
      } = _getSrcFlagsAndFilePaths(node, config);

      // No need to process url contents
      if (isUrl) {
        const error = new Error('URLs are not allowed in the \'src\' attribute');
        logger.error(`${error.message}
          File: ${context.cwf}
          URL provided: ${node.attribs.src}

          Please check the \`src\` attribute in the popover element.
          Ensure it doesn't contain a URL (e.g., "http://www.example.com").`);
        cheerio(node).replaceWith(createErrorNode(node, error));
        return context;
      }

      const fileExists = _checkAndWarnFileExists(node, context, actualFilePath, pageSources);
      Iif (!fileExists) {
        return context;
      }

      pageSources.staticIncludeSrc.push({
        from: context.cwf,
        to: actualFilePath,
      });

      const {
        nunjucksProcessed,
        childContext,
      } = variableProcessor.renderIncludeFile(actualFilePath, pageSources, node, context, filePath);

      let actualContent = nunjucksProcessed;
      if (fsUtil.isMarkdownFileExt(path.extname(actualFilePath))) {
        actualContent = renderMd(actualContent);
      }

      // Process sources with or without hash, retrieving and appending
      // the appropriate children to a wrapped include element
      if (hash) {
        const $ = cheerio.load(actualContent);
        actualContent = $(hash).html() || '';

        if (actualContent === '') {
          const error = new Error(`No such segment '${hash}' in file: ${actualFilePath}\n`
            + `Missing reference in ${context.cwf}`);
          logger.error(error.message);

          cheerio(node).replaceWith(createErrorNode(node, error));

          return context;
        }
      }

      actualContent = actualContent.trim();

      if (node.children.length > 0) {
        childContext.addCwfToCallstack(context.cwf);

        if (childContext.hasExceededMaxCallstackSize()) {
          const error = new CyclicReferenceError(childContext.callStack);
          logger.error(error.message);
          cheerio(node).replaceWith(createErrorNode(node, error));
          return context;
        }
      }

      const attributeSlotElement: NodeOrText[] = createSlotTemplateNode('content', actualContent);
      node.children = node.children ? attributeSlotElement.concat(node.children) : attributeSlotElement;

      delete node.attribs.src;

      return childContext;
    }