All files / src/Site SiteGenerationManager.ts

68.71% Statements 336/489
42.02% Branches 58/138
70.32% Functions 64/91
68.88% Lines 321/466

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 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140                                                            2x 2x   2x   2x   2x 2x   2x 2x                                                                                                     30x 30x 30x 30x 30x     30x 30x 30x     30x 30x     30x 30x     30x       30x 30x       2x 2x 4x             10x 10x 10x                                                                                                           18x 18x 18x 18x             8x 34x 14x   14x 8x 8x   8x             9x                               9x 9x   9x 9x   9x 9x   9x     9x 9x 9x 9x 9x             8x   8x 11x   11x 11x                   11x 11x     11x 11x   11x 11x 15x   15x                     1x 1x 1x 1x                   5x   5x   5x 5x 5x     5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x           5x   5x   5x 5x                       5x 5x 5x     5x                   7x 7x   7x 7x 7x 7x                                                                                               1x       1x 1x 1x   1x 1x 1x 1x 1x                 2x 2x 2x 2x     2x 2x 2x         2x 2x                   2x     2x                         2x       2x 2x 2x 2x   2x 1x     2x                                           2x       2x 2x   2x   2x 2x 2x 2x 2x                       2x                 2x 2x             7x 7x 7x   7x 7x                 7x 7x 7x 7x                                     8x 8x 8x 8x   8x 8x 8x 8x             8x     8x     8x 8x   8x                                                                                         8x 8x               9x   9x                   9x 9x 9x 9x     9x                       8x 9x                   9x                 9x 9x   9x   9x 8x                   7x 7x   7x 7x   7x       7x                                           1x   1x 1x 1x   1x   1x 1x 1x   1x 1x                           1x                   1x   1x 1x       1x   1x 1x               1x 1x       1x     1x 1x 1x 1x 1x                   1x 1x 1x 1x             10x               10x 10x     30x                 30x               30x               30x                   15x 15x   15x           15x 1x     15x 9x                 14x 14x 14x   14x         14x 8x   8x   5x     5x 7x     5x   5x 1x     4x 5x 5x 5x 5x   5x                       5x     4x 5x 5x         5x 5x 5x   5x   5x 5x 5x 5x       5x 5x   5x 5x 5x     5x   3x 3x 3x   6x 6x                     5x 1x 1x     5x   5x 6x   5x   5x 5x   1x 1x 1x   4x 4x           4x 4x   4x 4x           4x 4x   1x 1x         1x       1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x   1x                       1x     1x 2x   1x 1x       1x                             1x 1x 1x 1x 1x                            
import cheerio from 'cheerio';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import walkSync from 'walk-sync';
import * as pagefind from 'pagefind';
 
import { SiteAssetsManager } from './SiteAssetsManager.js';
import { SitePagesManager, AddressablePage } from './SitePagesManager.js';
import { SiteConfig } from './SiteConfig.js';
import { Page } from '../Page/index.js';
import { VariableProcessor } from '../variables/VariableProcessor.js';
import { ExternalManager } from '../External/ExternalManager.js';
import { SiteLinkManager } from '../html/SiteLinkManager.js';
import { PluginManager } from '../plugins/PluginManager.js';
import { sequentialAsyncForEach } from '../utils/async.js';
import { delay } from '../utils/delay.js';
import * as fsUtil from '../utils/fsUtil.js';
import * as logger from '../utils/logger.js';
import {
  SITE_CONFIG_NAME, LAZY_LOADING_SITE_FILE_NAME, _,
  TEMP_FOLDER_NAME, SITE_DATA_NAME, USER_VARIABLES_PATH, TEMPLATE_SITE_ASSET_FOLDER_NAME,
} from './constants.js';
import { LayoutManager } from '../Layout/index.js';
import { LayoutConfig } from '../Layout/Layout.js';
import { ProgressBar } from '../lib/progress/index.js';
import packageJson from '../../package.json' with { type: 'json' };
 
import '../patches/htmlparser2.js';
 
const __filepath = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filepath);
 
const MARKBIND_VERSION = packageJson.version;
 
const MAX_CONCURRENT_PAGE_GENERATION_PROMISES = 4;
 
const LAZY_LOADING_BUILD_TIME_RECOMMENDATION_LIMIT = 30000;
const LAZY_LOADING_REBUILD_TIME_RECOMMENDATION_LIMIT = 5000;
 
const MARKBIND_WEBSITE_URL = 'https://markbind.org/';
const MARKBIND_LINK_HTML = `<a href='${MARKBIND_WEBSITE_URL}'>MarkBind ${MARKBIND_VERSION}</a>`;
 
type PageGenerationTask = {
  mode: string,
  pages: Page[]
};
 
type PageGenerationContext = {
  startTime: Date,
  numPagesGenerated: number,
  numPagesToGenerate: number,
  isCompleted: boolean,
};
 
/**
 * Orchestrates the site generation process.
 * Manages the build lifecycle, variable processing, plugin management,
 * and rebuilding strategies (lazy/background).
 */
export class SiteGenerationManager {
  rootPath: string;
  outputPath: string;
  tempPath: string;
  siteConfig!: SiteConfig;
  siteConfigPath: string;
 
  // Managers
  variableProcessor!: VariableProcessor;
  pluginManager!: PluginManager;
  siteLinkManager!: SiteLinkManager;
  externalManager!: ExternalManager;
  layoutManager!: LayoutManager;
  sitePages!: SitePagesManager;
  siteAssets!: SiteAssetsManager;
 
  // Build state
  forceReload: boolean;
  backgroundBuildMode: string | boolean;
  stopGenerationTimeThreshold: Date;
  postBackgroundBuildFunc: () => void;
  onePagePath: string;
  currentPageViewed: string;
  currentOpenedPages: string[];
  toRebuild: Set<string>;
 
  // Pagefind index state (kept in memory for serve mode for incremental updates)
  pagefindIndex: any;
 
  constructor(rootPath: string, outputPath: string, onePagePath: string, forceReload = false,
              siteConfigPath = SITE_CONFIG_NAME, isDevMode: any, backgroundBuildMode: boolean,
              postBackgroundBuildFunc: () => void) {
    this.rootPath = rootPath;
    this.outputPath = outputPath;
    this.tempPath = path.join(rootPath, TEMP_FOLDER_NAME);
    this.forceReload = forceReload;
    this.siteConfigPath = siteConfigPath;
 
    // Background build properties
    this.backgroundBuildMode = onePagePath && backgroundBuildMode;
    this.stopGenerationTimeThreshold = new Date();
    this.postBackgroundBuildFunc = postBackgroundBuildFunc || (() => {});
 
    // Lazy reload properties
    this.onePagePath = onePagePath;
    this.currentPageViewed = onePagePath
      ? path.resolve(this.rootPath, fsUtil.removeExtension(onePagePath))
      : '';
    this.currentOpenedPages = [];
    this.toRebuild = new Set();
 
    // Pagefind index state (kept in memory for serve mode for incremental updates)
    this.pagefindIndex = null;
  }
 
  configure(siteAssets: SiteAssetsManager, sitePages: SitePagesManager) {
    this.siteAssets = siteAssets;
    this.sitePages = sitePages;
  }
 
  static async rejectHandler(error: unknown, removeFolders: string[]) {
    logger.warn(error);
    try {
      await Promise.all(removeFolders.map(folder => fs.remove(folder)));
    } catch (err) {
      logger.error(`Failed to remove generated files after error!\n${(err as Error).message}`);
    }
  }
 
  beforeSiteGenerate() {
    this.variableProcessor.invalidateCache();
    this.externalManager.reset();
    this.pluginManager.beforeSiteGenerate();
  }
 
  /**
   * Changes the site variable of the current page being viewed, building it if necessary.
   * @param normalizedUrl BaseUrl-less and extension-less url of the page
   * @return Boolean of whether the page needed to be rebuilt
   */
  changeCurrentPage(normalizedUrl: string) {
    this.currentPageViewed = path.join(this.rootPath, normalizedUrl);
 
    Iif (this.toRebuild.has(this.currentPageViewed)) {
      this.beforeSiteGenerate();
      /*
       Lazy loading only builds the page being viewed, but the user may be quick enough
       to trigger multiple page builds before the first one has finished building,
       hence we need to take this into account by using the delayed variant of the method.
       */
      this.rebuildPagesBeingViewed(this.currentPageViewed);
      return true;
    }
 
    return false;
  }
 
  /**
   * Changes the list of current opened pages
   * @param normalizedUrls Collection of normalized url of pages taken from the clients
   * ordered from most-to-least recently opened
   */
  changeCurrentOpenedPages(normalizedUrls: string[]) {
    Iif (!this.onePagePath) {
      return;
    }
 
    const openedPages = normalizedUrls.map(normalizedUrl => path.join(this.rootPath, normalizedUrl));
    this.currentOpenedPages = _.uniq(openedPages);
 
    if (this.currentOpenedPages.length > 0) {
      logger.info('Current opened pages, from most-to-least recent:');
      this.currentOpenedPages.forEach((pagePath, idx) => {
        logger.info(`${idx + 1}. ${fsUtil.ensurePosix(path.relative(this.rootPath, pagePath))}`);
      });
    } else {
      logger.info('No pages are currently opened');
    }
  }
 
  /**
   * Read and stores the site config from site.json, in Site, SitePages and SiteAssets.
   * Overwrite the default base URL if it's specified by the user.
   * @param baseUrl user defined base URL (if exists)
   */
  async readSiteConfig(baseUrl?: string) {
    this.siteConfig = await SiteConfig.readSiteConfig(this.rootPath, this.siteConfigPath, baseUrl);
    this.sitePages.siteConfig = this.siteConfig;
    this.siteAssets.siteConfig = this.siteConfig;
    return this.siteConfig;
  }
 
  /**
   * Collects the base url map in the site/subsites
   */
  collectBaseUrl() {
    const candidates = walkSync(this.rootPath, { directories: false })
      .filter(x => x.endsWith(this.siteConfigPath))
      .map(x => path.resolve(this.rootPath, x));
 
    const baseUrlMap = new Set(candidates.map(candidate => path.dirname(candidate)));
    this.variableProcessor = new VariableProcessor(this.rootPath, baseUrlMap);
    this.sitePages.setBaseUrlMap(baseUrlMap);
 
    this.buildManagers(baseUrlMap);
  }
 
  /**
   * Set up the managers used with the configurations.
   */
  buildManagers(baseUrlMap: Set<string>) {
    const config: LayoutConfig = {
      baseUrlMap,
      baseUrl: this.siteConfig.baseUrl,
      rootPath: this.rootPath,
      outputPath: this.outputPath,
      ignore: this.siteConfig.ignore,
      addressablePagesSource: this.sitePages.addressablePagesSource,
      variableProcessor: this.variableProcessor,
      intrasiteLinkValidation: this.siteConfig.intrasiteLinkValidation,
      codeLineNumbers: this.siteConfig.style.codeLineNumbers,
      plantumlCheck: this.siteConfig.plantumlCheck,
      headerIdMap: {},
      siteLinkManager: this.siteLinkManager,
      pluginManager: this.pluginManager,
      externalManager: this.externalManager,
    };
    this.siteLinkManager = new SiteLinkManager(config);
    config.siteLinkManager = this.siteLinkManager;
 
    this.pluginManager = new PluginManager(config, this.siteConfig.plugins, this.siteConfig.pluginsContext);
    config.pluginManager = this.pluginManager;
 
    this.externalManager = new ExternalManager(config);
    config.externalManager = this.externalManager;
 
    this.layoutManager = new LayoutManager(config);
 
    // Propagate managers to SitePages
    this.sitePages.variableProcessor = this.variableProcessor;
    this.sitePages.pluginManager = this.pluginManager;
    this.sitePages.siteLinkManager = this.siteLinkManager;
    this.sitePages.externalManager = this.externalManager;
    this.sitePages.layoutManager = this.layoutManager;
  }
 
  /**
   * Collects the user defined variables map in the site/subsites
   */
  collectUserDefinedVariablesMap() {
    this.variableProcessor.resetUserDefinedVariablesMap();
 
    this.sitePages.baseUrlMap.forEach((base) => {
      const userDefinedVariablesPath = path.resolve(base, USER_VARIABLES_PATH);
      let content;
      try {
        content = fs.readFileSync(userDefinedVariablesPath, 'utf8');
      } catch (e) {
        content = '';
        logger.warn((e as Error).message);
      }
 
      /*
       We retrieve the baseUrl of the (sub)site by appending the relative to the configured base url
       i.e. We ignore the configured baseUrl of the sub sites.
       */
      const siteRelativePathFromRoot = fsUtil.ensurePosix(path.relative(this.rootPath, base));
      const siteBaseUrl = siteRelativePathFromRoot === ''
        ? this.siteConfig.baseUrl
        : path.posix.join(this.siteConfig.baseUrl || '/', siteRelativePathFromRoot);
      this.variableProcessor.addUserDefinedVariable(base, 'baseUrl', siteBaseUrl);
      this.variableProcessor.addUserDefinedVariable(base, 'MarkBind', MARKBIND_LINK_HTML);
 
      const $ = cheerio.load(content, { decodeEntities: false });
      $('variable,span').each((_index, element) => {
        const name = $(element).attr('name') || $(element).attr('id');
 
        this.variableProcessor.renderAndAddUserDefinedVariable(base, name, $(element).html());
      });
    });
  }
 
  /**
   * Collects the user defined variables map in the site/subsites
   * if there is a change in the variables file
   * @param filePaths array of paths corresponding to files that have changed
   */
  collectUserDefinedVariablesMapIfNeeded(filePaths: string[]) {
    const variablesPath = path.resolve(this.rootPath, USER_VARIABLES_PATH);
    if (filePaths.includes(variablesPath)) {
      this.collectUserDefinedVariablesMap();
      return true;
    }
    return false;
  }
 
  /**
   * Generate the website.
   * @param baseUrl user defined base URL (if exists)
   */
  async generate(baseUrl: string | undefined): Promise<any> {
    const startTime = new Date();
    // Create the .tmp folder for storing intermediate results.
    fs.emptydirSync(this.tempPath);
    // Clean the output folder; create it if not exist.
    fs.emptydirSync(this.outputPath);
    const lazyWebsiteGenerationString = this.onePagePath ? '(lazy) ' : '';
    logger.info(`Website generation ${lazyWebsiteGenerationString}started at ${
      startTime.toLocaleTimeString()}`);
 
    try {
      await this.readSiteConfig(baseUrl);
      this.sitePages.collectAddressablePages();
      this.collectBaseUrl();
      this.collectUserDefinedVariablesMap();
      await this.siteAssets.buildAssets();
      await (this.onePagePath ? this.lazyBuildSourceFiles() : this.buildSourceFiles());
      await this.siteAssets.copyCoreWebAsset();
      await this.siteAssets.copyBootstrapIconsAsset();
      await this.siteAssets.copyBootstrapTheme(false);
      await this.siteAssets.copyFontAwesomeAsset();
      await this.siteAssets.copyOcticonsAsset();
      await this.siteAssets.copyMaterialIconsAsset();
      await this.writeSiteData();
      if (this.siteConfig.enableSearch) {
        let indexingSucceeded: boolean;
        Iif (this.onePagePath) {
          const builtPages = this.sitePages.pages.filter(page =>
            fs.existsSync(page.pageConfig.resultPath),
          );
          indexingSucceeded = await this.updatePagefindIndex(builtPages);
        } else {
          indexingSucceeded = await this.indexSiteWithPagefind();
        }
        this.sitePages.pagefindIndexingSucceeded = indexingSucceeded;
      }
      this.calculateBuildTimeForGenerate(startTime, lazyWebsiteGenerationString);
      Iif (this.backgroundBuildMode) {
        this.backgroundBuildNotViewedFiles();
      }
    } catch (error) {
      await SiteGenerationManager.rejectHandler(error, [this.tempPath, this.outputPath]);
    }
  }
 
  /**
   * Helper function for generate().
   */
  calculateBuildTimeForGenerate(startTime: Date, lazyWebsiteGenerationString: string) {
    const endTime = new Date();
    const totalBuildTime = (endTime.getTime() - startTime.getTime()) / 1000;
    logger.info(`Website generation ${lazyWebsiteGenerationString}complete! Total build time: ${
      totalBuildTime}s`);
 
    Iif (!this.onePagePath && totalBuildTime > LAZY_LOADING_BUILD_TIME_RECOMMENDATION_LIMIT) {
      logger.info('Your site took quite a while to build...'
          + ' Have you considered using markbind serve -o when writing content to speed things up?');
    }
  }
 
  /**
   * Build all pages of the site
   */
  async buildSourceFiles() {
    this.beforeSiteGenerate();
    logger.info('Generating pages...');
 
    try {
      await this.generatePages();
      await fs.remove(this.tempPath);
      logger.info('Pages built');
    } catch (error) {
      await SiteGenerationManager.rejectHandler(error, [this.tempPath, this.outputPath]);
    }
  }
 
  /**
   * Adds all pages except the viewed pages to toRebuild, flagging them for lazy building later.
   */
  async lazyBuildAllPagesNotViewed(viewedPages: string | string[]) {
    const viewedPagesArray = Array.isArray(viewedPages) ? viewedPages : [viewedPages];
    this.sitePages.pages.forEach((page) => {
      const normalizedUrl = fsUtil.removeExtension(page.pageConfig.sourcePath);
      Iif (!viewedPagesArray.some(viewedPage => normalizedUrl === viewedPage)) {
        this.toRebuild.add(normalizedUrl);
      }
    });
  }
 
  /**
   * Only build landing page of the site, building more as the author goes to different links.
   */
  async lazyBuildSourceFiles() {
    this.beforeSiteGenerate();
    logger.info('Generating landing page...');
 
    try {
      await this.generateLandingPage();
      await this.copyLazySourceFiles();
      await fs.remove(this.tempPath);
      await this.lazyBuildAllPagesNotViewed(this.currentPageViewed);
      logger.info('Landing page built, other pages will be built as you navigate to them!');
    } catch (error) {
      await SiteGenerationManager.rejectHandler(error, [this.tempPath, this.outputPath]);
    }
  }
 
  /**
   * Helper function for lazyBuildSourceFiles().
   */
  copyLazySourceFiles() {
    const lazyLoadingSpinnerHtmlFilePath = path.join(__dirname, LAZY_LOADING_SITE_FILE_NAME);
    const outputSpinnerHtmlFilePath = path.join(this.outputPath, LAZY_LOADING_SITE_FILE_NAME);
 
    return fs.copy(lazyLoadingSpinnerHtmlFilePath, outputSpinnerHtmlFilePath);
  }
 
  async _rebuildAffectedSourceFiles(filePaths: string | string[]) {
    Iif (this.backgroundBuildMode) {
      this.stopOngoingBuilds();
    }
 
    const filePathArray = Array.isArray(filePaths) ? filePaths : [filePaths];
    const uniquePaths = _.uniq(filePathArray);
    this.beforeSiteGenerate();
 
    try {
      await this.layoutManager.updateLayouts(filePathArray);
      await this.regenerateAffectedPages(uniquePaths);
      await fs.remove(this.tempPath);
      Iif (this.backgroundBuildMode) {
        this.backgroundBuildNotViewedFiles();
      }
    } catch (error) {
      await SiteGenerationManager.rejectHandler(error, [this.tempPath, this.outputPath]);
    }
  }
 
  async _rebuildPagesBeingViewed(normalizedUrls: string[]) {
    const startTime = new Date();
    const normalizedUrlArray = Array.isArray(normalizedUrls) ? normalizedUrls : [normalizedUrls];
    const uniqueUrls = _.uniq(normalizedUrlArray);
    uniqueUrls.forEach(normalizedUrl => logger.info(
      `Building ${normalizedUrl} as some of its dependencies were changed since the last visit`));
 
    const pagesToRebuild = this.sitePages.pages.filter(page =>
      uniqueUrls.some(pageUrl => fsUtil.removeExtension(page.pageConfig.sourcePath) === pageUrl));
    const pageGenerationTask = {
      mode: 'async',
      pages: pagesToRebuild,
    };
 
    try {
      this._setTimestampVariable();
      await this.runPageGenerationTasks([pageGenerationTask]);
      await this.writeSiteData();
 
      Iif (this.siteConfig.enableSearch && this.pagefindIndex) {
        await this.updatePagefindIndex(pagesToRebuild);
      }
 
      SiteGenerationManager.calculateBuildTimeForRebuildPagesBeingViewed(startTime);
    } catch (err) {
      await SiteGenerationManager.rejectHandler(err, [this.tempPath, this.outputPath]);
    }
 
    await fs.remove(this.tempPath);
  }
 
  /**
   * Helper function for _rebuildPagesBeingViewed().
   */
  static calculateBuildTimeForRebuildPagesBeingViewed(startTime: Date) {
    const endTime = new Date();
    const totalBuildTime = (endTime.getTime() - startTime.getTime()) / 1000;
    return logger.info(`Lazy website regeneration complete! Total build time: ${totalBuildTime}s`);
  }
 
  async _backgroundBuildNotViewedFiles() {
    Iif (this.toRebuild.size === 0) {
      return;
    }
 
    logger.info('Building files that are not viewed in the background...');
    const isCompleted = await this.generatePagesMarkedToRebuild();
    if (isCompleted) {
      logger.info('Background building completed!');
 
      if (this.siteConfig.enableSearch) {
        await this.indexSiteWithPagefind();
      }
 
      this.postBackgroundBuildFunc();
    }
  }
 
  /**
   * Generates pages that are marked to be built/rebuilt.
   * @returns A Promise that resolves once all pages are generated.
   */
  async generatePagesMarkedToRebuild(): Promise<boolean> {
    const pagesToRebuild = this.sitePages.pages.filter((page) => {
      const normalizedUrl = fsUtil.removeExtension(page.pageConfig.sourcePath);
      return this.toRebuild.has(normalizedUrl);
    });
 
    const pageRebuildTask = {
      mode: 'async',
      pages: pagesToRebuild,
    };
    return this.runPageGenerationTasks([pageRebuildTask]);
  }
 
  async _rebuildSourceFiles() {
    Iif (this.backgroundBuildMode) {
      this.stopOngoingBuilds();
    }
 
    logger.info('Pages or site config modified, updating pages...');
    this.beforeSiteGenerate();
 
    this.layoutManager.removeLayouts();
 
    const removedPageFilePaths = this.sitePages.updateAddressablePages();
    try {
      await this.siteAssets.removeAsset(removedPageFilePaths);
      await this.rebuildRequiredPages();
      Iif (this.backgroundBuildMode) {
        this.backgroundBuildNotViewedFiles();
      }
    } catch (error) {
      await SiteGenerationManager.rejectHandler(error, [this.tempPath, this.outputPath]);
    }
  }
 
  /**
   * Helper function for _rebuildSourceFiles().
   */
  async rebuildRequiredPages() {
    Iif (this.onePagePath) {
      this.sitePages
        .mapAddressablePagesToPages(this.sitePages.addressablePages || [], this.sitePages.getFavIconUrl());
 
      await this._rebuildPagesBeingViewed(this.currentOpenedPages);
      await this.lazyBuildAllPagesNotViewed(this.currentOpenedPages);
      return;
    }
 
    logger.warn('Rebuilding all pages...');
    await this.buildSourceFiles();
  }
 
  /**
   * Writes the site data to siteData.json
   * @param verbose Flag to emit logs of the operation
   */
  async writeSiteData(verbose: boolean = true) {
    const siteDataPath = path.join(this.outputPath, SITE_DATA_NAME);
    const siteData = {
      enableSearch: this.siteConfig.enableSearch,
      pages: this.sitePages.pages.filter(page => page.pageConfig.searchable && page.headings)
        .map(page => ({
          src: page.pageConfig.src,
          title: page.title,
          headings: page.headings,
          headingKeywords: page.keywords,
          frontmatterKeywords: page.frontmatter.keywords,
        })),
    };
 
    try {
      await fs.outputJson(siteDataPath, siteData, { spaces: 2 });
      if (verbose) {
        logger.info('Site data built');
      }
    } catch (error) {
      await SiteGenerationManager.rejectHandler(error, [this.tempPath, this.outputPath]);
    }
  }
 
  stopOngoingBuilds() {
    this.stopGenerationTimeThreshold = new Date();
  }
 
  /**
   * Runs the supplied page generation tasks according to the specified mode of each task.
   * A page generation task can be a sequential generation or an asynchronous generation.
   * @param pageGenerationTasks Array of page generation tasks
   * @returns A Promise that resolves to a boolean which indicates whether the generation
   * ran to completion
   */
  async runPageGenerationTasks(pageGenerationTasks: PageGenerationTask[]): Promise<boolean> {
    const pagesCount = pageGenerationTasks.reduce((acc, task) => acc + task.pages.length, 0);
    const progressBar = new ProgressBar(`[:bar] :current / ${pagesCount} pages built`, { total: pagesCount });
    progressBar.render();
    logger.setProgressBar(progressBar);
 
    const startTime = new Date();
    let isCompleted = true;
    await sequentialAsyncForEach(pageGenerationTasks, async (task) => {
      Iif (this.backgroundBuildMode && startTime < this.stopGenerationTimeThreshold) {
        logger.info('Page generation stopped');
        logger.debug('Page generation stopped at generation task queue');
        isCompleted = false;
        return;
      }
 
      Iif (task.mode === 'sequential') {
        isCompleted = await this.generatePagesSequential(task.pages, progressBar);
      } else {
        isCompleted = await this.generatePagesAsyncThrottled(task.pages, progressBar) as boolean;
      }
 
      logger.removeProgressBar();
      this.siteLinkManager.validateAllIntralinks();
    });
    return isCompleted;
  }
 
  /**
   * Generate pages sequentially. That is, the pages are generated
   * one-by-one in order.
   * @param pages Pages to be generated
   * @param progressBar Progress bar of the overall generation process
   * @returns A Promise that resolves to a boolean which indicates whether the generation
   * ran to completion
   */
  async generatePagesSequential(pages: Page[], progressBar: ProgressBar): Promise<boolean> {
    const startTime = new Date();
    let isCompleted = true;
    await sequentialAsyncForEach(pages, async (page) => {
      Iif (this.backgroundBuildMode && startTime < this.stopGenerationTimeThreshold) {
        logger.info('Page generation stopped');
        logger.debug('Page generation stopped at sequential generation');
        isCompleted = false;
        return;
      }
 
      try {
        await page.generate(this.externalManager);
        this.toRebuild.delete(fsUtil.removeExtension(page.pageConfig.sourcePath));
        Iif (this.backgroundBuildMode) {
          await this.writeSiteData(false);
        }
        progressBar.tick();
      } catch (err) {
        throw new Error(`Error while generating ${page.pageConfig.sourcePath}: ${err}`);
      }
    });
    return isCompleted;
  }
 
  /**
   * Creates the supplied pages' page generation promises at a throttled rate.
   * This is done to avoid pushing too many callbacks into the event loop at once. (#1245)
   * @param pages Pages to be generated
   * @param progressBar Progress bar of the overall generation process
   * @returns A Promise that resolves to a boolean which indicates whether the generation
   * ran to completion
   */
  generatePagesAsyncThrottled(pages: Page[], progressBar: ProgressBar): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const context: PageGenerationContext = {
        startTime: new Date(),
        numPagesGenerated: 0,
        numPagesToGenerate: pages.length,
        isCompleted: true,
      };
 
      // Map pages into array of callbacks for delayed execution
      const pageGenerationQueue = pages.map(page => async () => {
        // Pre-generate guard to ensure no newly executed callbacks start on stop
        Iif (this.backgroundBuildMode && context.startTime < this.stopGenerationTimeThreshold) {
          Iif (context.isCompleted) {
            logger.info('Page generation stopped');
            logger.debug('Page generation stopped at asynchronous generation');
            context.isCompleted = false;
            resolve(false);
          }
          return;
        }
 
        try {
          await page.generate(this.externalManager);
          this.toRebuild.delete(fsUtil.removeExtension(page.pageConfig.sourcePath));
          Iif (this.backgroundBuildMode) {
            await this.writeSiteData(false);
          }
          this.generateProgressBarStatus(progressBar, context, pageGenerationQueue, resolve);
        } catch (err) {
          logger.error(err);
          reject(new Error(`Error while generating ${page.pageConfig.sourcePath}`));
        }
      });
 
      /*
       Take the first MAX_CONCURRENT_PAGE_GENERATION_PROMISES callbacks and execute them.
       Whenever a page generation callback resolves,
       it pops the next unprocessed callback off pageGenerationQueue and executes it.
       */
      pageGenerationQueue.splice(0, MAX_CONCURRENT_PAGE_GENERATION_PROMISES)
        .forEach(generatePage => generatePage());
    });
  }
 
  /**
   * Helper function for generatePagesAsyncThrottled().
   */
  generateProgressBarStatus(progressBar: ProgressBar, context: PageGenerationContext,
                            pageGenerationQueue: (() => Promise<void>)[], resolve: ((arg0: boolean) => any)) {
    // Post-generate guard to ensure no new callbacks are executed on stop
    Iif (this.backgroundBuildMode && context.startTime < this.stopGenerationTimeThreshold) {
      Iif (context.isCompleted) {
        logger.info('Page generation stopped');
        logger.debug('Page generation stopped at asynchronous generation');
        context.isCompleted = false;
        resolve(false);
      }
      return;
    }
    progressBar.tick();
    context.numPagesGenerated += 1;
 
    Iif (pageGenerationQueue.length) {
      pageGenerationQueue.pop()!();
    } else if (context.numPagesGenerated === context.numPagesToGenerate) {
      resolve(true);
    }
  }
 
  /**
   * Renders all pages specified in site configuration file to the output folder
   */
  generatePages() {
    // Run MarkBind include and render on each source file.
    // Render the final rendered page to the output folder.
    const addressablePages = this.sitePages.addressablePages || [];
    const faviconUrl = this.sitePages.getFavIconUrl();
 
    this._setTimestampVariable();
    this.sitePages.mapAddressablePagesToPages(addressablePages, faviconUrl);
 
    const pageGenerationTask = {
      mode: 'async',
      pages: this.sitePages.pages,
    };
    return this.runPageGenerationTasks([pageGenerationTask]);
  }
 
  /**
   * Renders only the starting page for lazy loading to the output folder.
   */
  async generateLandingPage() {
    const addressablePages = this.sitePages.addressablePages || [];
    const faviconUrl = this.sitePages.getFavIconUrl();
 
    this._setTimestampVariable();
    this.sitePages.mapAddressablePagesToPages(addressablePages, faviconUrl);
 
    const landingPage = this.sitePages.pages.find(page => page.pageConfig.src === this.onePagePath);
    Iif (!landingPage) {
      throw new Error(`${this.onePagePath} is not specified in the site configuration.`);
    }
 
    await landingPage.generate(this.externalManager);
  }
 
  async regenerateAffectedPages(filePaths: string[]) {
    const startTime = new Date();
 
    const shouldRebuildAllPages = this.collectUserDefinedVariablesMapIfNeeded(filePaths) || this.forceReload;
    if (shouldRebuildAllPages) {
      logger.warn('Rebuilding all pages as variables file was changed, or the --force-reload flag was set');
    }
    this._setTimestampVariable();
 
    let openedPagesToRegenerate: Page[] = [];
    const asyncPagesToRegenerate = this.sitePages.pages.filter((page) => {
      const doFilePathsHaveSourceFiles = filePaths.some(filePath => page.isDependency(filePath));
 
      if (shouldRebuildAllPages || doFilePathsHaveSourceFiles) {
        Iif (this.onePagePath) {
          const normalizedSource = fsUtil.removeExtension(page.pageConfig.sourcePath);
          const openIdx = this.currentOpenedPages.findIndex(pagePath => pagePath === normalizedSource);
          const isRecentlyViewed = openIdx !== -1;
 
          if (!isRecentlyViewed) {
            this.toRebuild.add(normalizedSource);
          } else {
            openedPagesToRegenerate[openIdx] = page;
          }
 
          return false;
        }
 
        return true;
      }
 
      return false;
    });
 
    /*
     * As a side effect of doing assignment to an empty array, some elements might be
     * undefined if it has not been assigned to anything. We filter those out here.
     */
    openedPagesToRegenerate = openedPagesToRegenerate.filter(page => page);
 
    const totalPagesToRegenerate = openedPagesToRegenerate.length + asyncPagesToRegenerate.length;
    Iif (totalPagesToRegenerate === 0) {
      logger.info('No pages needed to be rebuilt');
      return;
    }
    logger.info(`Rebuilding ${totalPagesToRegenerate} pages`);
 
    const pageGenerationTasks = [];
    Iif (openedPagesToRegenerate.length > 0) {
      const recentPagesGenerationTask = {
        mode: 'sequential',
        pages: openedPagesToRegenerate,
      };
      pageGenerationTasks.push(recentPagesGenerationTask);
    }
 
    if (asyncPagesToRegenerate.length > 0) {
      const asyncPagesGenerationTask = {
        mode: 'async',
        pages: asyncPagesToRegenerate,
      };
      pageGenerationTasks.push(asyncPagesGenerationTask);
    }
 
    try {
      await this.runPageGenerationTasks(pageGenerationTasks);
      await this.writeSiteData();
      logger.info('Pages rebuilt');
      this.calculateBuildTimeForRegenerateAffectedPages(startTime);
    } catch (err) {
      await SiteGenerationManager.rejectHandler(err, [this.tempPath, this.outputPath]);
    }
  }
 
  /**
   * Helper function for regenerateAffectedPages().
   */
  calculateBuildTimeForRegenerateAffectedPages(startTime: Date) {
    const endTime = new Date();
    const totalBuildTime = (endTime.getTime() - startTime.getTime()) / 1000;
    logger.info(`Website regeneration complete! Total build time: ${totalBuildTime}s`);
    Iif (!this.onePagePath && totalBuildTime > LAZY_LOADING_REBUILD_TIME_RECOMMENDATION_LIMIT) {
      logger.info('Your pages took quite a while to rebuild...'
          + ' Have you considered using markbind serve -o when writing content to speed things up?');
    }
  }
 
  private _setTimestampVariable() {
    const options: Intl.DateTimeFormatOptions = {
      weekday: 'short',
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      timeZone: this.siteConfig.timeZone,
      timeZoneName: 'short',
    };
    const time = new Date().toLocaleTimeString(this.siteConfig.locale, options);
    this.variableProcessor.addUserDefinedVariableForAllSites('timestamp', time);
  }
 
  rebuildPagesBeingViewed = delay(
    this._rebuildPagesBeingViewed.bind(this) as (args: string[]) => Promise<void>,
    1000,
  );
 
  /**
   * Rebuild pages that are affected by changes in filePaths
   * @param filePaths a single path or an array of paths corresponding to the files that have changed
   */
  rebuildAffectedSourceFiles = delay(
    this._rebuildAffectedSourceFiles.bind(this) as (args: string[]) => Promise<void>,
    1000,
  );
 
  /**
   * Rebuild all pages
   */
  rebuildSourceFiles = delay(
    this._rebuildSourceFiles.bind(this) as (args: string[]) => Promise<void>,
    1000,
  );
 
  /**
   * Builds pages that are yet to build/rebuild in the background
   */
  backgroundBuildNotViewedFiles = delay(
    this._backgroundBuildNotViewedFiles.bind(this) as (args: string[]) => Promise<void>,
    1000,
  );
 
  /**
   * Initializes a new Pagefind index with proper configuration.
   * @returns The created index object
   */
  private async initializePagefindIndex(): Promise<any> {
    const { createIndex } = pagefind;
    const pagefindConfig = this.siteConfig.pagefind || {};
 
    const createIndexOptions: Record<string, unknown> = {
      keepIndexUrl: true,
      verbose: true,
      logfile: 'debug.log',
    };
 
    if (pagefindConfig.exclude_selectors) {
      createIndexOptions.excludeSelectors = pagefindConfig.exclude_selectors;
    }
 
    const { index } = await createIndex(createIndexOptions);
    return index;
  }
 
  /**
  * Indexes all the pages of the site using pagefind.
  * Performs a full rebuild of the search index.
  * @returns true if indexing succeeded and pagefind assets were written, false otherwise.
  */
  async indexSiteWithPagefind(): Promise<boolean> {
    const startTime = new Date();
    logger.info('Creating Pagefind Search Index...');
    try {
      // Clean up existing in-memory index if it exists
      Iif (this.pagefindIndex) {
        await this.pagefindIndex.deleteIndex();
        this.pagefindIndex = null;
      }
 
      const index = await this.initializePagefindIndex();
      const { close } = pagefind;
 
      if (index) {
        // Store index in memory for incremental updates in serve mode
        this.pagefindIndex = index;
 
        // Filter pages that should be indexed (searchable !== false)
        const searchablePages = this.sitePages.pages.filter(
          page => page.pageConfig.searchable,
        );
 
        let totalPageCount = 0;
 
        if (searchablePages.length === 0) {
          logger.info('No pages configured for search indexing');
        } else {
          // Add each searchable page to the index using addHTMLFile
          const indexingResults = await Promise.all(
            searchablePages.map(async (page) => {
              try {
                const content = await fs.readFile(page.pageConfig.resultPath, 'utf8');
                const relativePath = path.relative(this.outputPath, page.pageConfig.resultPath);
 
                return index.addHTMLFile({
                  sourcePath: relativePath,
                  content,
                });
              } catch (error) {
                logger.error(`Failed to index ${page.pageConfig.resultPath}: ${error}`);
                return null;
              }
            }),
          );
 
          // Count successful indexings
          totalPageCount = indexingResults.filter(r => r !== null).length;
 
          // Log any errors from indexing results
          indexingResults.forEach((result) => {
            if (result && result.errors) {
              result.errors.forEach((error: string) => logger.error(error));
            }
          });
        }
 
        const endTime = new Date();
        const totalTime = (endTime.getTime() - startTime.getTime()) / 1000;
        logger.info(`Pagefind indexed ${totalPageCount} pages in ${totalTime}s`);
 
        const pagefindOutputPath = path.join(this.outputPath, TEMPLATE_SITE_ASSET_FOLDER_NAME, 'pagefind');
        // Clear output directory before writing
        await fs.emptyDir(pagefindOutputPath);
        await fs.ensureDir(pagefindOutputPath);
        await index.writeFiles({ outputPath: pagefindOutputPath });
        logger.info(`Pagefind assets written to ${pagefindOutputPath}`);
 
        // Only close the index in build/deploy mode; keep it in memory for serve mode
        // Detect serve mode by checking if postBackgroundBuildFunc has a name (named function = serve)
        const isServeMode = this.postBackgroundBuildFunc.name !== '';
        const shouldClose = !isServeMode;
 
        if (shouldClose) {
          await close();
          this.pagefindIndex = null;
        }
 
        return true;
      }
      logger.error('Pagefind failed to create index');
      await close();
      return false;
    } catch (error) {
      logger.warn(`Pagefind indexing skipped: ${error}`);
      return false;
    }
  }
 
  /**
   * Updates the search index for changed pages only (incremental update).
   * Requires the index to be kept in memory from a prior indexSiteWithPagefind() call.
   * @param pages Array of pages that were modified/added
   * @returns true if update succeeded, false otherwise
   */
  async updatePagefindIndex(pages: Page[]): Promise<boolean> {
    if (!this.pagefindIndex) {
      logger.info('Pagefind index not in memory, auto-creating...');
      this.pagefindIndex = await this.initializePagefindIndex();
    }
 
    const pagefindOutputPath = path.join(this.outputPath, TEMPLATE_SITE_ASSET_FOLDER_NAME, 'pagefind');
 
    try {
      const searchablePages = pages.filter(page => page.pageConfig.searchable);
 
      await Promise.all(searchablePages.map(async (page) => {
        let content;
        try {
          content = await fs.readFile(page.pageConfig.resultPath, 'utf8');
        } catch (err) {
          const pageResultPath = page.pageConfig.resultPath;
          logger.warn(`Skipping index update for ${pageResultPath}: file not built yet`);
          return null;
        }
        const relativePath = path.relative(this.outputPath, page.pageConfig.resultPath);
        return this.pagefindIndex.addHTMLFile({
          sourcePath: relativePath,
          content,
        });
      }));
 
      const { files } = await this.pagefindIndex.getFiles();
      await fs.emptyDir(pagefindOutputPath);
 
      const pagefindFiles: { path: string; content: Uint8Array }[] = files;
      await Promise.all(pagefindFiles.map(async (file) => {
        const filePath = path.join(pagefindOutputPath, file.path);
        await fs.ensureDir(path.dirname(filePath));
        return fs.writeFile(filePath, Buffer.from(file.content));
      }));
 
      logger.info(`Updated Pagefind index for ${searchablePages.length} page(s)`);
      return true;
    } catch (error) {
      logger.error(`Failed to update Pagefind index: ${error}`);
      return false;
    }
  }
 
  async reloadSiteConfig() {
    Iif (this.backgroundBuildMode) {
      this.stopOngoingBuilds();
    }
 
    const oldSiteConfig = this.siteConfig;
    const oldAddressablePages = this.sitePages.addressablePages.slice();
    const oldPagesSrc = oldAddressablePages.map(page => page.src);
    await this.readSiteConfig();
    await this.siteAssets.handleIgnoreReload(oldSiteConfig.ignore);
    await this.handlePageReload(oldAddressablePages, oldPagesSrc, oldSiteConfig);
    await this.siteAssets.handleStyleReload(oldSiteConfig.style);
    Iif (this.backgroundBuildMode) {
      this.backgroundBuildNotViewedFiles();
    }
 
    if (this.siteConfig.enableSearch) {
      const enableSearchToggledOn = !oldSiteConfig.enableSearch && this.siteConfig.enableSearch;
      const pagefindConfigChanged = !_.isEqual(oldSiteConfig.pagefind, this.siteConfig.pagefind);
 
      Iif (enableSearchToggledOn || pagefindConfigChanged) {
        logger.info('Site config change detected, reindexing Pagefind...');
        await this.indexSiteWithPagefind();
      }
    }
  }
 
  /**
   * Handles the rebuilding of modified pages
   */
  async handlePageReload(oldAddressablePages: AddressablePage[], oldPagesSrc: string[],
                         oldSiteConfig: SiteConfig) {
    this.sitePages.collectAddressablePages();
 
    // Comparator for the _differenceWith comparison below
    const isNewPage = (newPage: AddressablePage, oldPage: AddressablePage) =>
      _.isEqual(newPage, oldPage) || newPage.src === oldPage.src;
 
    const addedPages = _.differenceWith(this.sitePages.addressablePages, oldAddressablePages, isNewPage);
    const removedPages = _.differenceWith(oldAddressablePages, this.sitePages.addressablePages, isNewPage)
      .map(filePath => fsUtil.setExtension(filePath.src as string, '.html'));
 
    // Checks if any attributes of site.json requiring a global rebuild are modified
    const isGlobalConfigModified = () => !_.isEqual(oldSiteConfig.faviconPath, this.siteConfig.faviconPath)
        || !_.isEqual(oldSiteConfig.titlePrefix, this.siteConfig.titlePrefix)
        || !_.isEqual(oldSiteConfig.titleSuffix, this.siteConfig.titleSuffix)
        || !_.isEqual(oldSiteConfig.style, this.siteConfig.style)
        || !_.isEqual(oldSiteConfig.externalScripts, this.siteConfig.externalScripts)
        || !_.isEqual(oldSiteConfig.globalOverride, this.siteConfig.globalOverride)
        || !_.isEqual(oldSiteConfig.plugins, this.siteConfig.plugins)
        || !_.isEqual(oldSiteConfig.pluginsContext, this.siteConfig.pluginsContext)
        || !_.isEqual(oldSiteConfig.headingIndexingLevel, this.siteConfig.headingIndexingLevel)
        || !_.isEqual(oldSiteConfig.enableSearch, this.siteConfig.enableSearch)
        || !_.isEqual(oldSiteConfig.timeZone, this.siteConfig.timeZone)
        || !_.isEqual(oldSiteConfig.locale, this.siteConfig.locale)
        || !_.isEqual(oldSiteConfig.intrasiteLinkValidation, this.siteConfig.intrasiteLinkValidation)
        || !_.isEqual(oldSiteConfig.plantumlCheck, this.siteConfig.plantumlCheck);
 
    if (isGlobalConfigModified() || !_.isEmpty(addedPages) || !_.isEmpty(removedPages)) {
      await this.siteAssets.removeAsset(removedPages);
      this.buildManagers(this.sitePages.baseUrlMap);
      await this.rebuildSourceFiles();
      await this.writeSiteData();
    } else E{
      // Get pages with edited attributes but with the same src
      const editedPages = _.differenceWith(
        this.sitePages.addressablePages,
        oldAddressablePages,
        (newPage, oldPage) => _.isEqual(newPage, oldPage) || !oldPagesSrc.includes(newPage.src),
      );
      this.sitePages.updatePages(editedPages);
      const siteConfigDirectory = path.dirname(path.join(this.rootPath, this.siteConfigPath));
      this.regenerateAffectedPages(editedPages.map(page => path.join(siteConfigDirectory, page.src)));
    }
  }
}