# All files / src/html includePanelProcessor.ts

55.33% Statements 83/150
48% Branches 24/50
100% Functions 8/8
55.33% Lines 83/150

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
    3609x
    9x
    9x

    9x
    9x
    9x
    9x

    9x
    9x
    9x

    9x

    9x

    226x
    2x
    2x

    224x

    226x
    226x

    226x

    226x

    226x

    226x

    226x

    226x
    226x

    226x
    226x

    226x

    9x

    8x
    8x
    8x

    222x
    234x

    222x
    222x
    222x
    222x
    222x
    222x

    9x

    226x

    226x

    226x

    226x
    226x
    226x
    2x

    224x
    224x
    224x

    224x

    224x

    224x

    224x
    224x
    224x

    224x
    14x
    14x
    14x

    14x
    2x

    2x

    2x

    224x
    2x

    224x
    224x
    224x

    224x
    220x
    220x

    220x
    2x
    2x
    2x
    2x

    222x

    222x

    9x

    4x
    4x

     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';

    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);

        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;
      Iif (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;
    }

    /**
     * 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>): Context {
      Iif (_.isEmpty(node.attribs.src)) {
        const error = new Error(`Empty src attribute in include in: ${context.cwf}`);
        logger.error(error);
        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);

      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 (actualContentOrNull === null && !isOptional) {
          const error = new Error(`No such segment '${hash}' in file: ${actualFilePath}\n`
           + `Missing reference in ${context.cwf}`);
          logger.error(error);

          actualContent = cheerio.html(createErrorNode(node, error));
        }
      }

      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);
          cheerio(node).replaceWith(createErrorNode(node, error));
          return context;
        }
      }

      _deleteIncludeAttributes(node);

      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;
      }

      Iif (_.isEmpty(node.attribs.src)) {
        const error = new Error(`Empty src attribute in include in: ${context.cwf}`);
        logger.error(error);
        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) {
        const error = new Error('URLs are not allowed in the \'src\' attribute');
        logger.error(error);
        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;
      Iif (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
      Iif (hash) {
        const $ = cheerio.load(actualContent);
        actualContent = $(hash).html() || '';

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

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

          return context;
        }
      }

      actualContent = actualContent.trim();

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

        Iif (childContext.hasExceededMaxCallstackSize()) {
          const error = new CyclicReferenceError(childContext.callStack);
          logger.error(error);
          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;
    }