All files / backend/src/services/workspace workspace-service.ts

13.61% Statements 87/639
9.24% Branches 32/346
16.66% Functions 15/90
14.73% Lines 84/570

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 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656                                                                                                                                                                                                                                                                                        10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x             2x             13x                                                                                                               9x 9x 9x 9x             9x 9x                                                 2x 2x     2x 2x                           7x     7x 7x 7x     7x 7x         7x 7x                                                                                                                                                                                                                                                                                                                                                                                                                     7x 7x 7x 7x 7x 7x 7x     7x 7x   7x                                                                                 4x 5x     4x 4x   4x 4x         4x 4x       4x           4x             4x 4x       7x 7x     7x 7x   7x 7x                 7x       7x   7x     4x                                                     2x 4x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     2x 2x 2x 2x     2x               2x 2x   2x   2x 2x 2x 2x     2x               2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       2x                                                                                                                                              
/**
 * Workspace Service
 *
 * Manages workspace operations including:
 * - Configuration management
 * - Content operations (singles, collections, data files)
 * - Build and serve operations
 * - File operations and bundle management
 * - Image operations and thumbnails
 */
 
import path from 'path';
import { glob } from 'glob';
import fs from 'fs-extra';
import fssimple from 'fs';
import fm from 'front-matter';
import { promisify } from 'util';
import type { WorkspaceConfigProvider, ParseInfo } from './workspace-config-provider.js';
import type { FormatProviderResolver } from '../../utils/format-provider-resolver.js';
import type { FormatProvider, ParsedContent } from '../../utils/format-providers/types.js';
import { isContentFile, SUPPORTED_CONTENT_EXTENSIONS } from '../../utils/content-formats.js';
import type { PathHelper } from '../../utils/path-helper.js';
import { recurForceRemove } from '../../utils/file-dir-utils.js';
import { createThumbnailJob } from '../../jobs/index.js';
import { BuildActionService, type BuildActionResult } from '../../build-actions/index.js';
import { SITE_CATEGORIES } from '../../logging/index.js';
import type { CollectionConfig, ExtraBuildConfig, BuildConfig, ServeConfig } from '@quiqr/types';
import { frontMatterContentSchema } from '@quiqr/types';
import type { WorkspaceConfig } from './workspace-config-validator.js';
import type { AppConfig } from '../../config/app-config.js';
import type { AppState } from '../../config/app-state.js';
import type { AppContainer } from '../../config/container.js';
import type { ProviderFactory } from '../../ssg-providers/provider-factory.js';
import type { SSGDevServer, SSGServerConfig, SSGBuildConfig } from '../../ssg-providers/types.js';
import { WindowAdapter, OutputConsole, ScreenshotWindowManager, ShellAdapter } from '../../adapters/types.js';
import { isValidToString } from '../../sync/embgit-sync-base.js';
 
/**
 * Dependencies required by WorkspaceService
 */
export interface WorkspaceServiceDependencies {
  workspaceConfigProvider: WorkspaceConfigProvider;
  formatProviderResolver: FormatProviderResolver;
  pathHelper: PathHelper;
  appConfig: AppConfig;
  appState: AppState;
  providerFactory: ProviderFactory;
  windowAdapter: WindowAdapter;
  shellAdapter: ShellAdapter;
  outputConsole: OutputConsole;
  screenshotWindowManager: ScreenshotWindowManager;
  buildActionService: BuildActionService;
  container: AppContainer;
}
 
/**
 * Collection item metadata
 */
export interface CollectionItem {
  key: string;
  label: string;
  sortval?: string | null;
}
 
/**
 * Resource file in a content bundle
 */
export interface ResourceFile {
  src: string;
  __deleted?: boolean;
}
 
/**
 * Build action configuration
 */
export interface BuildActionConfig {
  key: string;
  execute: string;
}
 
/**
 * Collection item creation result
 */
export interface CollectionItemCreateResult {
  key?: string;
  unavailableReason?: 'already-exists';
}
 
/**
 * Collection item rename result
 */
export interface CollectionItemRenameResult {
  renamed: boolean;
  item?: CollectionItem;
}
 
/**
 * Collection item copy result
 */
export interface CollectionItemCopyResult {
  copied: boolean;
  item?: CollectionItem;
}
 
/**
 * Hugo language configuration
 */
export interface HugoLanguage {
  lang: string;
  source: string;
}
 
/**
 * WorkspaceService - Main service for workspace operations
 */
export class WorkspaceService {
  private workspacePath: string;
  private workspaceKey: string;
  private siteKey: string;
  private workspaceConfigProvider: WorkspaceConfigProvider;
  private formatProviderResolver: FormatProviderResolver;
  private pathHelper: PathHelper;
  private appConfig: AppConfig;
  private appState: AppState;
  private providerFactory: ProviderFactory;
  private windowAdapter: WindowAdapter;
  private shellAdapter: ShellAdapter;
  private outputConsole: OutputConsole;
  private screenshotWindowManager: ScreenshotWindowManager;
  private buildActionService: BuildActionService;
  private container: AppContainer;
  private currentDevServer?: SSGDevServer;
  private currentSSGType?: string;
 
  constructor(
    workspacePath: string,
    workspaceKey: string,
    siteKey: string,
    dependencies: WorkspaceServiceDependencies
  ) {
    this.workspacePath = workspacePath;
    this.workspaceKey = workspaceKey;
    this.siteKey = siteKey;
    this.workspaceConfigProvider = dependencies.workspaceConfigProvider;
    this.formatProviderResolver = dependencies.formatProviderResolver;
    this.pathHelper = dependencies.pathHelper;
    this.appConfig = dependencies.appConfig;
    this.appState = dependencies.appState;
    this.providerFactory = dependencies.providerFactory;
    this.windowAdapter = dependencies.windowAdapter;
    this.shellAdapter = dependencies.shellAdapter;
    this.outputConsole = dependencies.outputConsole;
    this.screenshotWindowManager = dependencies.screenshotWindowManager;
    this.buildActionService = dependencies.buildActionService;
    this.container = dependencies.container;
  }
 
  /**
   * Get the workspace path
   */
  getWorkspacePath(): string {
    return this.workspacePath;
  }
 
  /**
   * Get the workspace configurations data to be used by the client
   */
  async getConfigurationsData(): Promise<WorkspaceConfig> {
    return this.workspaceConfigProvider.readOrCreateMinimalModelConfig(
      this.workspacePath,
      this.workspaceKey
    );
  }
 
  /**
   * Clear configurations data cache
   */
  clearConfigurationsDataCache(): void {
    this.workspaceConfigProvider.clearCache();
  }
 
  /**
   * Get creator message from workspace
   */
  async getCreatorMessage(): Promise<string> {
    const indexPath = path.join(this.workspacePath, 'quiqr', 'home', 'index.md');
    try {
      if (fs.existsSync(indexPath)) {
        const data = await fs.readFile(indexPath, 'utf8');
        const obj = await this._smartParse(indexPath, ['md'], data);
        // TODO: probably move this validation to when we parse the data
        if (typeof obj === 'object' && obj !== null && 'mainContent' in obj && isValidToString(obj.mainContent)) {
          return obj.mainContent.toString();
        } else {
          return data;
        }
      }
    } catch (err) {
      console.error(err);
      console.error('error checking');
    }
    return '';
  }
 
  /**
   * Get model parse info
   */
  async getModelParseInfo(): Promise<ParseInfo> {
    await this.workspaceConfigProvider.readOrCreateMinimalModelConfig(
      this.workspacePath,
      this.workspaceKey
    );
    return this.workspaceConfigProvider.getModelParseInfo();
  }
 
  /**
   * Smart resolve format provider for a file
   */
  private async _smartResolveFormatProvider(
    filePath: string,
    fallbacks?: string[]
  ): Promise<FormatProvider | undefined> {
    let formatProvider: FormatProvider | undefined;
 
    if (isContentFile(filePath)) {
      Eif (fs.existsSync(filePath)) {
        const resolved = await this.formatProviderResolver.resolveForMdFilePromise(filePath);
        Eif (resolved) formatProvider = resolved;
      }
    } else E{
      const resolved = this.formatProviderResolver.resolveForFilePath(filePath);
      if (resolved) formatProvider = resolved;
    }
 
    Eif (formatProvider) {
      return formatProvider;
    }
 
    if (fallbacks) {
      for (let i = 0; i < fallbacks.length; i++) {
        if (fallbacks[i]) {
          const resolved = this.formatProviderResolver.resolveForExtension(fallbacks[i]);
          if (resolved) {
            return resolved;
          }
        }
      }
    }
 
    return undefined;
  }
 
  /**
   * Smart dump object to string using appropriate format provider
   */
  private async _smartDump(
    filePath: string,
    formatFallbacks: string[],
    obj: ParsedContent
  ): Promise<string> {
    let formatProvider = await this._smartResolveFormatProvider(filePath, formatFallbacks);
    Iif (formatProvider === undefined || formatProvider === null) {
      formatProvider = this.formatProviderResolver.getDefaultFormat();
    }
    if (isContentFile(filePath)) {
      return formatProvider.dumpContent(obj);
    } else E{
      return formatProvider.dump(obj);
    }
  }
 
  /**
   * Smart parse string to object using appropriate format provider
   */
  private async _smartParse(
    filePath: string,
    formatFallbacks: string[],
    str: string
  ): Promise<ParsedContent | unknown> {
    Iif (!str || str.length === 0 || !/\S/.test(str)) {
      return {};
    }
    Eif (isContentFile(filePath)) {
      Eif (formatFallbacks) {
        formatFallbacks.push('yaml');
      }
    }
    const formatProvider = await this._smartResolveFormatProvider(filePath, formatFallbacks);
    Iif (formatProvider === undefined) {
      console.log('formatprovider undefined');
      return {};
    }
 
    if (isContentFile(filePath)) {
      return formatProvider.parseFromMdFileString(str);
    } else E{
      return formatProvider.parse(str);
    }
  }
 
  /**
   * Get a single content item
   */
  async getSingle(singleKey: string, fileOverride?: string): Promise<unknown> {
    const config = await this.getConfigurationsData();
 
    const single = config.singles.find((x) => x.key === singleKey);
    if (single == null) throw new Error('Could not find single.');
    
    if (!single.file && !fileOverride) {
      throw new Error(`Single '${singleKey}' has no file configured`);
    }
 
    let fileLastPath = single.file || '';
 
    if (typeof fileOverride === 'string' && fileOverride.length > 0) {
      fileLastPath = fileOverride;
    }
 
    const filePath = path.join(this.workspacePath, fileLastPath);
 
    if (fs.existsSync(filePath)) {
      const data = await fs.readFile(filePath, 'utf8');
 
      let obj = await this._smartParse(
        filePath,
        [path.extname(single.file || fileLastPath).replace('.', '')],
        data
      );
 
      if (typeof single.pullOuterRootKey === 'string') {
        const newObj: Record<string, unknown> = {};
        newObj[single.pullOuterRootKey] = obj;
        obj = newObj;
      }
 
      return obj;
    } else {
      return {};
    }
  }
 
  /**
   * Get the folder containing a single
   */
  async getSingleFolder(singleKey: string): Promise<string> {
    const config = await this.getConfigurationsData();
    const single = config.singles.find((x) => x.key === singleKey);
    if (single == null) throw new Error('Could not find single.');
    if (!single.file) throw new Error(`Single '${singleKey}' has no file configured`);
    const filePath = path.join(this.workspacePath, single.file);
 
    const directory = path.dirname(filePath);
 
    if (fs.existsSync(directory)) {
      return directory;
    } else {
      return '';
    }
  }
 
  /**
   * Open a single in external editor
   */
  async openSingleInEditor(singleKey: string): Promise<void> {
    const config = await this.getConfigurationsData();
    const single = config.singles.find((x) => x.key === singleKey);
    if (single == null) throw new Error('Could not find single.');
    if (!single.file) throw new Error(`Single '${singleKey}' has no file configured`);
    const filePath = path.join(this.workspacePath, single.file);
    await this.shellAdapter.openPath(filePath);
  }
 
  /**
   * Update a single content item
   */
  async updateSingle(singleKey: string, document: Record<string, unknown>): Promise<unknown> {
    const config = await this.getConfigurationsData();
    const single = config.singles.find((x) => x.key === singleKey);
    if (single == null) throw new Error('Could not find single.');
    if (!single.file) throw new Error(`Single '${singleKey}' has no file configured`);
    const filePath = path.join(this.workspacePath, single.file);
 
    // Log update start
    this.container.logger.infoSite(
      this.siteKey,
      this.workspaceKey,
      SITE_CATEGORIES.CONTENT,
      'Single document update started',
      { singleKey, filePath }
    );
 
    try {
      const directory = path.dirname(filePath);
 
      if (!fs.existsSync(directory)) fs.mkdirSync(directory); // ensure directory existence
 
      let documentClone = JSON.parse(JSON.stringify(document));
 
      if (typeof single.pullOuterRootKey === 'string') {
        documentClone = documentClone[single.pullOuterRootKey];
      }
 
      this._stripNonDocumentData(documentClone);
 
      const stringData = await this._smartDump(
        filePath,
        [path.extname(single.file).replace('.', '')],
        documentClone
      );
      fs.writeFileSync(filePath, stringData);
 
      // Log success
      this.container.logger.infoSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.CONTENT,
        'Single document updated',
        { singleKey, filePath }
      );
 
      return document;
    } catch (error) {
      // Log error
      this.container.logger.errorSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.CONTENT,
        'Single document update failed',
        { 
          singleKey, 
          filePath, 
          error: error instanceof Error ? error.message : String(error) 
        }
      );
      throw error;
    }
  }
 
  /**
   * Get files from an absolute path
   */
  async getFilesFromAbsolutePath(filePath: string): Promise<ResourceFile[]> {
    const directory = path.join(this.workspacePath, filePath);
 
    const globExp = '*';
    const allFiles = await glob(globExp, {
      nodir: true,
      absolute: false,
      cwd: directory,
    });
 
    const expression = `_?index[.](${SUPPORTED_CONTENT_EXTENSIONS.join('|')})$`;
    const pageOrSectionIndexReg = new RegExp(expression);
    const filtered = allFiles.filter((x) => !pageOrSectionIndexReg.test(x));
 
    const merged = filtered.map((src) => ({ src }));
 
    return merged;
  }
 
  /**
   * Get resources from content bundle
   */
  async getResourcesFromContent(
    filePath: string,
    currentResources: ResourceFile[] = [],
    targetPath: string | null = null
  ): Promise<ResourceFile[]> {
    filePath = path.normalize(filePath);
    const directory = path.dirname(filePath);
 
    let globExp = '*';
    if (targetPath) {
      globExp = targetPath + '/*';
    }
 
    const allFiles = await glob(globExp, {
      nodir: true,
      absolute: false,
      cwd: directory,
    });
 
    const expression = `_?index[.](${SUPPORTED_CONTENT_EXTENSIONS.join('|')})$`;
    const pageOrSectionIndexReg = new RegExp(expression);
    const filtered = allFiles.filter((x) => !pageOrSectionIndexReg.test(x));
 
    const merged = filtered.map((src) => {
      return Object.assign({ src }, currentResources.find((r) => r.src === src));
    });
    return merged;
  }
 
  /**
   * Get a collection item
   */
  async getCollectionItem(collectionKey: string, collectionItemKey: string): Promise<unknown> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    Iif (collection == null) throw new Error('Could not find collection.');
    const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
    if (await fs.exists(filePath)) {
      const stats = await fs.stat(filePath);
      Iif (stats.isDirectory()) {
        throw new Error(`EISDIR: illegal operation on a directory, read: ${filePath}`);
      }
      const data = await fs.readFile(filePath, { encoding: 'utf8' });
      const obj = await this._smartParse(filePath, [collection.extension], data);
 
      return obj;
    } else E{
      return undefined;
    }
  }
 
  /**
   * Create a new collection item
   */
  async createCollectionItemKey(
    collectionKey: string,
    collectionItemKey: string,
    itemTitle: string
  ): Promise<CollectionItemCreateResult> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
    let filePath: string;
    let returnedKey: string;
    if (collection.folder.startsWith('content')) {
      returnedKey = path.join(collectionItemKey, 'index.' + collection.extension);
      filePath = path.join(this.workspacePath, collection.folder, returnedKey);
    } else {
      returnedKey = collectionItemKey + '.' + collection.extension;
      filePath = path.join(this.workspacePath, collection.folder, returnedKey);
    }
    if (fs.existsSync(filePath)) return { unavailableReason: 'already-exists' };
 
    await fs.ensureDir(path.dirname(filePath));
    const stringData = await this._smartDump(filePath, [collection.dataformat], {
      title: itemTitle,
    });
    await fs.writeFile(filePath, stringData, { encoding: 'utf8' });
 
    return { key: returnedKey.replace(/\\/g, '/') };
  }
 
  /**
   * List collection items
   */
  async listCollectionItems(collectionKey: string): Promise<CollectionItem[]> {
    const collection = (await this.getConfigurationsData()).collections.find(
      (x) => x.key === collectionKey
    );
 
    Iif (collection == null) throw new Error('Could not find collection.');
    const folder = path.join(this.workspacePath, collection.folder).replace(/\\/g, '/');
 
    const supportedContentExt = ['md', 'html', 'markdown', 'qmd'];
    if (
      collection.folder.startsWith('content') ||
      supportedContentExt.indexOf(collection.extension) !== -1
    ) {
      // WHEN WE WANT TO IGNORE _index.md front pages
      let subDirStars = '**';
      Iif ('includeSubdirs' in collection && collection.includeSubdirs === false) {
        subDirStars = '';
      }
 
      let globExpression = path.join(
        folder,
        `${subDirStars}/*.{${supportedContentExt.join(',')}}`
      ).replace(/\\/g, '/');
 
      // WHEN WE WANT TO IGNORE _index.md front pages
      Iif ('hideIndex' in collection && collection.hideIndex === true) {
        globExpression = path.join(
          folder,
          `${subDirStars}/!(_index).{${supportedContentExt.join(',')}}`
        ).replace(/\\/g, '/');
      }
 
      const files = await glob(globExpression, {});
      const retFiles = files.map(function (item) {
        // Use path.posix.relative: both `item` (from glob) and `folder` must be
        // normalized to forward slashes and have consistent drive letter case.
        // On Windows: glob returns backslashes and drive letter case may differ
        const normalizedFolder = folder.replace(/^[A-Z]:/, (m) => m.toLowerCase());
        const normalizedItem = item
          .replace(/\\/g, '/')  // Normalize backslashes to forward slashes
          .replace(/^[A-Z]:/, (m) => m.toLowerCase());  // Normalize drive letter case
        const key = path.posix.relative(normalizedFolder, normalizedItem);
        const label = key.replace(/^\/?(.+)\/[^/]+$/, '$1');
 
        let sortval: string | null = null;
        Iif ('sortkey' in collection && collection.sortkey) {
          const data = fssimple.readFileSync(item, 'utf8');
          const rawContent = fm(data);
          const parseResult = frontMatterContentSchema.safeParse(rawContent);
 
          if (parseResult.success && collection.sortkey in parseResult.data.attributes) {
            sortval = String(parseResult.data.attributes[collection.sortkey]);
          }
        } else {
          sortval = label;
        }
 
        // Detect if this is a page bundle (file is named index.md/index.html in a directory)
        const isPageBundle = /\/index\.(md|html|markdown|qmd)$/.test(item);
 
        return { key, label, sortval, isPageBundle };
      });
 
      return retFiles;
    } else E{
      // data folder and everything else
      const globExpression = path.join(
        folder,
        `**/*.{${this.formatProviderResolver.allFormatsExt().join(',')}}`
      ).replace(/\\/g, '/');
 
      const files = await glob(globExpression, {});
      return files.map(function (item) {
        // On Windows: glob returns backslashes and drive letter case may differ
        const normalizedFolder = folder.replace(/^[A-Z]:/, (m) => m.toLowerCase());
        const normalizedItem = item
          .replace(/\\/g, '/')  // Normalize backslashes to forward slashes
          .replace(/^[A-Z]:/, (m) => m.toLowerCase());  // Normalize drive letter case
        const key = path.posix.relative(normalizedFolder, normalizedItem);
        const label = key;
        const sortval = key; // Default sortval to key for data folders
        return { key, label, sortval };
      });
    }
  }
 
  /**
   * Strip non-document data (internal fields starting with __)
   */
  private _stripNonDocumentData(document: Record<string, unknown>): void {
    for (const key in document) {
      Iif (key.startsWith('__')) {
        delete document[key];
      }
    }
  }
 
  /**
   * Rename a collection item
   */
  async renameCollectionItem(
    collectionKey: string,
    collectionItemKey: string,
    collectionItemNewKey: string
  ): Promise<CollectionItemRenameResult> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
    let filePath: string;
    let newFilePath: string;
    let newFileKey: string;
    let newLabel: string;
 
    if (collectionItemKey.includes('.' + collection.extension)) {
      filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
      newFilePath = path.join(
        this.workspacePath,
        collection.folder,
        collectionItemNewKey + '.' + collection.extension
      );
      newFileKey = path.join(collectionItemNewKey + '.' + collection.extension);
      newLabel = collectionItemNewKey + '.' + collection.extension;
    } else {
      filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
      newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey);
      newFileKey = path.join(collectionItemNewKey, 'index.' + collection.extension);
      newLabel = collectionItemNewKey;
    }
 
    if (!fs.existsSync(filePath)) {
      console.log('orig does not exist' + filePath);
    }
    if (fs.existsSync(newFilePath)) {
      console.log('new already  exist' + newFilePath);
      return { renamed: false };
    }
    fs.renameSync(filePath, newFilePath);
    return { renamed: true, item: { key: newFileKey.replace(/\\/g, '/'), label: newLabel } };
  }
 
  /**
   * Copy collection item to another language
   */
  async copyCollectionItemToLang(
    collectionKey: string,
    collectionItemKey: string,
    collectionItemNewKey: string,
    destLangCode: string
  ): Promise<CollectionItemCopyResult> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
 
    let newFilePath: string;
    let newFileKey: string;
    let newLabel: string;
 
    const langs = await this.getHugoConfigLanguages();
 
    const sourcelang = langs.find((lang) => {
      return collection.folder.startsWith(lang.source);
    });
    const destlang = langs.find((lang) => {
      return lang.lang == destLangCode;
    });
 
    if (!sourcelang || !destlang) {
      return { copied: false };
    }
 
    const pathInLang = collection.folder.slice(sourcelang.source.length);
 
    const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
 
    if (collectionItemKey.includes('.' + collection.extension)) {
      newFilePath = path.join(
        this.workspacePath,
        destlang.source,
        pathInLang,
        collectionItemNewKey + '.' + collection.extension
      );
      newFileKey = path.join(collectionItemNewKey + '.' + collection.extension);
      newLabel = collectionItemNewKey + '.' + collection.extension;
    } else {
      newFilePath = path.join(
        this.workspacePath,
        destlang.source,
        pathInLang,
        collectionItemNewKey
      );
      newFileKey = path.join(collectionItemNewKey, 'index.' + collection.extension);
      newLabel = collectionItemNewKey;
    }
 
    if (!fs.existsSync(filePath)) {
      console.log('orig does not exist' + filePath);
      return { copied: false };
    }
    if (fs.existsSync(newFilePath)) {
      console.log('new already  exist' + newFilePath);
      return { copied: false };
    }
 
    fs.copySync(filePath, newFilePath);
    return { copied: true, item: { key: newFileKey.replace(/\\/g, '/'), label: newLabel } };
  }
 
  /**
   * Copy a collection item
   */
  async copyCollectionItem(
    collectionKey: string,
    collectionItemKey: string,
    collectionItemNewKey: string
  ): Promise<CollectionItemCopyResult> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
 
    let filePath: string;
    let newFilePath: string;
    let newFileKey: string;
    let newLabel: string;
 
    if (collectionItemKey.includes('.' + collection.extension)) {
      filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
      newFilePath = path.join(
        this.workspacePath,
        collection.folder,
        collectionItemNewKey + '.' + collection.extension
      );
      newFileKey = path.join(collectionItemNewKey + '.' + collection.extension);
      newLabel = collectionItemNewKey + '.' + collection.extension;
    } else {
      filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
      newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey);
      newFileKey = path.join(collectionItemNewKey, 'index.' + collection.extension);
      newLabel = collectionItemNewKey;
    }
 
    if (!fs.existsSync(filePath)) {
      console.log('orig does not exist' + filePath);
      return { copied: false };
    }
    if (fs.existsSync(newFilePath)) {
      console.log('new already  exist' + newFilePath);
      return { copied: false };
    }
 
    fs.copySync(filePath, newFilePath);
    return { copied: true, item: { key: newFileKey.replace(/\\/g, '/'), label: newLabel } };
  }
 
  /**
   * Delete a collection item
   */
  async deleteCollectionItem(collectionKey: string, collectionItemKey: string): Promise<boolean> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
 
    let filePath = '';
    if (collectionItemKey.endsWith('/index.md')) {
      filePath = path.join(
        this.workspacePath,
        collection.folder,
        collectionItemKey.split('/')[0]
      );
    } else {
      filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
    }
 
    await recurForceRemove(filePath);
 
    return true;
  }
 
  /**
   * Make a collection item into a page bundle
   */
  async makePageBundleCollectionItem(
    collectionKey: string,
    collectionItemKey: string
  ): Promise<boolean> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
    const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
 
    if (fs.existsSync(filePath)) {
      const newdir = path.join(
        this.workspacePath,
        collection.folder,
        collectionItemKey.split('.').slice(0, -1).join('.')
      );
      fs.mkdirSync(newdir);
      fs.renameSync(filePath, path.join(newdir, 'index.md'));
 
      return true;
    }
    return false;
  }
 
  /**
   * Open collection item in external editor
   */
  async openCollectionItemInEditor(
    collectionKey: string,
    collectionItemKey: string
  ): Promise<void> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    if (collection == null) throw new Error('Could not find collection.');
    const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
 
    await this.shellAdapter.openPath(filePath);
  }
 
  /**
   * Get collection by key
   */
  async getCollectionByKey(collectionKey: string): Promise<CollectionConfig> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
 
    if (collection == null) throw new Error('Could not find collection.');
 
    return collection;
  }
 
  /**
   * Build a collection item using a build action
   */
  async buildCollectionItem(
    collectionKey: string,
    collectionItemKey: string,
    buildAction: string
  ): Promise<BuildActionResult> {
    const collection = await this.getCollectionByKey(collectionKey);
    const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
 
    const buildActionDict = collection.build_actions?.find((x) => x.key === buildAction);
    if (!buildActionDict) {
      throw new Error(`Build action ${buildAction} not found in collection ${collectionKey}`);
    }
 
    return this.buildActionService.runAction(
      buildAction,
      buildActionDict.execute,
      filePath,
      this.workspacePath,
      this.siteKey,
      this.workspaceKey
    );
  }
 
  /**
   * Build a single using a build action
   */
  async buildSingle(singleKey: string, buildAction: string): Promise<BuildActionResult> {
    const config = await this.getConfigurationsData();
    const single = config.singles.find((x) => x.key === singleKey);
    if (single == null) throw new Error('Could not find single.');
    if (!single.file) throw new Error(`Single '${singleKey}' has no file configured`);
 
    const filePath = path.join(this.workspacePath, single.file);
 
    const buildActionDict = single.build_actions?.find((x) => x.key === buildAction);
    if (!buildActionDict) {
      throw new Error(`Build action ${buildAction} not found in single ${singleKey}`);
    }
 
    return this.buildActionService.runAction(
      buildAction,
      buildActionDict.execute,
      filePath,
      this.workspacePath,
      this.siteKey,
      this.workspaceKey
    );
  }
 
  /**
   * Update a collection item
   */
  async updateCollectionItem(
    collectionKey: string,
    collectionItemKey: string,
    document: Record<string, unknown>
  ): Promise<Record<string, unknown>> {
    const config = await this.getConfigurationsData();
    const collection = config.collections.find((x) => x.key === collectionKey);
    Iif (collection == null) throw new Error('Could not find collection.');
    const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
 
    // Log update start
    this.container.logger.infoSite(
      this.siteKey,
      this.workspaceKey,
      SITE_CATEGORIES.CONTENT,
      'Collection item update started',
      { collectionKey, collectionItemKey, filePath }
    );
 
    try {
      const directory = path.dirname(filePath);
 
      Iif (!fs.existsSync(directory)) fs.mkdirSync(directory); // ensure directory existence
 
      const documentClone = JSON.parse(JSON.stringify(document));
      this._stripNonDocumentData(documentClone);
      const stringData = await this._smartDump(filePath, [collection.dataformat], documentClone);
      fs.writeFileSync(filePath, stringData);
 
      // Log success
      this.container.logger.infoSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.CONTENT,
        'Collection item updated',
        { collectionKey, collectionItemKey, filePath }
      );
 
      return document;
    } catch (error) {
      // Log error
      this.container.logger.errorSite(
        this.siteKey,
        this.workspaceKey,
        SITE_CATEGORIES.CONTENT,
        'Collection item update failed',
        { 
          collectionKey, 
          collectionItemKey, 
          filePath, 
          error: error instanceof Error ? error.message : String(error) 
        }
      );
      throw error;
    }
  }
 
  /**
   * Copy files into a collection item or single
   */
  async copyFilesIntoCollectionItem(
    collectionKey: string,
    collectionItemKey: string,
    targetPath: string,
    files: string[],
    forceFileName?: string
  ): Promise<string[]> {
    const config = await this.getConfigurationsData();
 
    let filesBasePath = '';
    // When file starts with / use the root of the site directory
    if (targetPath.charAt(0) == '/' || targetPath.charAt(0) == '\\') {
      filesBasePath = path.join(this.workspacePath, targetPath);
    } else {
      if (collectionKey == '') {
        filesBasePath = path.join(await this.getSingleFolder(collectionItemKey), targetPath);
      } else {
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null) throw new Error('Could not find collection.');
 
        // Check if item is already a bundle (has directory separator)
        if (!collectionItemKey.includes('/')) {
          const itemPath = path.join(this.workspacePath, collection.folder, collectionItemKey);
          const bundleDirPath = path.join(
            this.workspacePath,
            collection.folder,
            collectionItemKey.replace(/\.[^.]+$/, '')
          );
 
          // Check if we need to convert to bundle
          if (fs.existsSync(itemPath) && fs.statSync(itemPath).isFile()) {
            // File exists as non-bundle - convert it
            await this.makePageBundleCollectionItem(collectionKey, collectionItemKey);
          }
          // If bundle directory already exists (either just converted or already was converted), update the key
          if (fs.existsSync(bundleDirPath) && fs.statSync(bundleDirPath).isDirectory()) {
            collectionItemKey = collectionItemKey.replace(/\.[^.]+$/, '') + '/index.md';
          }
        }
 
        // Extract the bundle directory from collectionItemKey
        // For bundle items like "project1/index.md", extract "project1"
        let bundleDir = collectionItemKey;
        if (collectionItemKey.includes('/')) {
          // Has directory separator - strip the filename part
          bundleDir = collectionItemKey.replace(/\/[^/]+$/, '');
        } else {
          // No directory separator - strip the file extension (shouldn't happen after auto-convert)
          bundleDir = collectionItemKey.replace(/\.[^.]+$/, '');
        }
 
        const pathFromItemRoot = path.join(bundleDir, targetPath);
        filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot);
      }
    }
 
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
 
      const from = file;
      let to = path.join(filesBasePath, path.basename(file));
 
      if (i == 0 && forceFileName) {
        to = path.join(filesBasePath, forceFileName);
        files[0] = forceFileName;
      }
 
      const toExists = fs.existsSync(to);
      if (toExists) {
        fs.unlinkSync(to);
      }
 
      await fs.copy(from, to);
    }
 
    return files.map((x) => {
      return path.join(targetPath, path.basename(x)).replace(/\\/g, '/');
    });
  }
 
  /**
   * Delete a file from a bundle path.
   * Used when removing files from bundle manager.
   */
  async deleteFileFromBundle(
    collectionKey: string,
    collectionItemKey: string,
    targetPath: string,
    filename: string
  ): Promise<boolean> {
    const config = await this.getConfigurationsData();
 
    let filesBasePath = '';
    // When path starts with / use the root of the site directory
    if (targetPath.charAt(0) === '/' || targetPath.charAt(0) === '\\') {
      filesBasePath = path.join(this.workspacePath, targetPath);
    } else {
      if (collectionKey === '') {
        filesBasePath = path.join(await this.getSingleFolder(collectionItemKey), targetPath);
      } else {
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null) throw new Error('Could not find collection.');
 
        const pathFromItemRoot = path.join(
          collectionItemKey.replace(/\/[^/]+$/, ''),
          targetPath
        );
        filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot);
      }
    }
 
    const filePath = path.join(filesBasePath, filename);
 
    if (fs.existsSync(filePath)) {
      await recurForceRemove(filePath);
      return true;
    }
 
    return false;
  }
 
  /**
   * Upload a file to a bundle path with base64 content.
   * Used by native browser file pickers.
   * Returns the uploaded file path and optionally the new collection item key if converted to bundle.
   */
  async uploadFileToBundlePath(
    collectionKey: string,
    collectionItemKey: string,
    targetPath: string,
    filename: string,
    base64Content: string
  ): Promise<{ uploadedPath: string; newCollectionItemKey?: string }> {
    const config = await this.getConfigurationsData();
    const originalCollectionItemKey = collectionItemKey;
    let wasConverted = false;
 
    let filesBasePath = '';
    // When path starts with / use the root of the site directory
    if (targetPath.charAt(0) === '/' || targetPath.charAt(0) === '\\') {
      filesBasePath = path.join(this.workspacePath, targetPath);
    } else {
      if (collectionKey === '') {
        filesBasePath = path.join(await this.getSingleFolder(collectionItemKey), targetPath);
      } else {
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null) throw new Error('Could not find collection.');
 
        // Check if item is already a bundle (has directory separator)
        if (!collectionItemKey.includes('/')) {
          const itemPath = path.join(this.workspacePath, collection.folder, collectionItemKey);
          const bundleDirPath = path.join(
            this.workspacePath,
            collection.folder,
            collectionItemKey.replace(/\.[^.]+$/, '')
          );
 
          // Check if we need to convert to bundle
          if (fs.existsSync(itemPath) && fs.statSync(itemPath).isFile()) {
            // File exists as non-bundle - convert it
            await this.makePageBundleCollectionItem(collectionKey, collectionItemKey);
            wasConverted = true;
          }
          // If bundle directory already exists (either just converted or already was converted), update the key
          if (fs.existsSync(bundleDirPath) && fs.statSync(bundleDirPath).isDirectory()) {
            collectionItemKey = collectionItemKey.replace(/\.[^.]+$/, '') + '/index.md';
          }
        }
 
        // Extract the bundle directory from collectionItemKey
        // For bundle items like "project1/index.md", extract "project1"
        let bundleDir = collectionItemKey;
        if (collectionItemKey.includes('/')) {
          // Has directory separator - strip the filename part
          bundleDir = collectionItemKey.replace(/\/[^/]+$/, '');
        } else {
          // No directory separator - strip the file extension (shouldn't happen after auto-convert)
          bundleDir = collectionItemKey.replace(/\.[^.]+$/, '');
        }
 
        const pathFromItemRoot = path.join(bundleDir, targetPath);
        filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot);
      }
    }
 
    // Ensure the target directory exists
    await fs.ensureDir(filesBasePath);
 
    const filePath = path.join(filesBasePath, filename);
 
    // If file exists, remove it first
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
 
    // Decode base64 and write file
    const buffer = Buffer.from(base64Content, 'base64');
    await fs.writeFile(filePath, buffer);
 
    // Return the relative path from targetPath and new key if converted
    const result: { uploadedPath: string; newCollectionItemKey?: string } = {
      uploadedPath: path.join(targetPath, filename).replace(/\\/g, '/')
    };
 
    if (wasConverted && collectionItemKey !== originalCollectionItemKey) {
      result.newCollectionItemKey = collectionItemKey;
    }
 
    return result;
  }
 
  /**
   * Check if path exists (promisified)
   */
  private existsPromise(src: string): Promise<boolean> {
    return new Promise((resolve) => {
      fs.exists(src, (exists) => {
        resolve(exists);
      });
    });
  }
 
  /**
   * Remove thumbnail for item image
   */
  async removeThumbnailForItemImage(
    collectionKey: string,
    collectionItemKey: string,
    targetPath: string
  ): Promise<void> {
    let folder: string;
    const itemPath = collectionItemKey.replace(/\/[^/]+$/, '');
    if (collectionKey == '') {
      folder = path.basename(await this.getSingleFolder(collectionItemKey));
    } else {
      const config = await this.getConfigurationsData();
 
      const collection = config.collections.find((x) => x.key === collectionKey);
      if (!collection) {
        throw new Error('Could not find collection.');
      }
      folder = collection.folder;
    }
 
    let thumbSrc = path.join(
      this.workspacePath,
      '.quiqr-cache/thumbs',
      folder,
      itemPath,
      targetPath
    );
    if (targetPath.charAt(0) == '/' || targetPath.charAt(0) == '\\') {
      thumbSrc = path.join(this.workspacePath, '.quiqr-cache/thumbs', targetPath);
    }
 
    const thumbSrcExists = await this.existsPromise(thumbSrc);
    if (thumbSrcExists) {
      fs.remove(thumbSrc);
    }
  }
 
  /**
   * Get files in a bundle
   */
  async getFilesInBundle(
    collectionKey: string,
    collectionItemKey: string,
    targetPath: string,
    extensions?: string[],
    forceFileName?: string
  ): Promise<ResourceFile[] | undefined> {
    const show = false;
    if (show) {
      console.log(forceFileName);
      console.log(extensions);
    }
 
    let files: ResourceFile[] = [];
    let folder: string;
    let filePath: string;
 
    const config = await this.getConfigurationsData();
 
    if (collectionKey == '') {
      const single = config.singles.find((x) => x.key === collectionItemKey);
      if (single == null) throw new Error('Could not find single.');
      if (!single.file) throw new Error(`Single '${collectionItemKey}' has no file configured`);
      filePath = path.join(this.workspacePath, single.file);
    } else {
      const collection = config.collections.find((x) => x.key === collectionKey);
      if (!collection) {
        throw new Error('Could not find collection.');
      }
      folder = collection.folder;
      filePath = path.join(this.workspacePath, folder, collectionItemKey);
    }
 
    if (await fs.exists(filePath)) {
      if (isContentFile(filePath)) {
        files = await this.getResourcesFromContent(filePath, [], targetPath);
      }
      return files;
    }
  }
 
  /**
   * Get thumbnail for collection or single item image
   */
  async getThumbnailForCollectionOrSingleItemImage(
    collectionKey: string,
    itemKey: string,
    targetPath: string
  ): Promise<string> {
    const itemPath = itemKey.replace(/\/[^/]+$/, '');
 
    if (targetPath.charAt(0) == '/' || targetPath.charAt(0) == '\\') {
      return this.getThumbnailForAbsoluteImgPath(
        path.join(this.workspacePath, targetPath),
        targetPath
      );
    } else if (collectionKey == '') {
      return this.getThumbnailForAbsoluteImgPath(
        path.join(await this.getSingleFolder(itemKey), targetPath), // complete path
        targetPath, // targetPath
        path.basename(await this.getSingleFolder(itemKey)), // folder
        itemPath
      );
    } else {
      const config = await this.getConfigurationsData();
      const collection = config.collections.find((x) => x.key === collectionKey);
      if (collection == null) throw new Error('Could not find collection.');
      const folder = collection.folder;
 
      return this.getThumbnailForAbsoluteImgPath(
        path.join(this.workspacePath, collection.folder, itemPath, targetPath), // completePath
        targetPath,
        folder,
        itemPath
      );
    }
  }
 
  /**
   * Get thumbnail for absolute image path
   */
  async getThumbnailForAbsoluteImgPath(
    completePath: string,
    targetPath: string,
    folder: string = '',
    itemPath: string = ''
  ): Promise<string> {
    const srcExists = await this.existsPromise(completePath);
    if (!srcExists) {
      return 'NOT_FOUND';
    }
 
    const thumbSrc = path.join(
      this.workspacePath,
      '.quiqr-cache/thumbs',
      folder,
      itemPath,
      targetPath
    );
    const thumbSrcExists = await this.existsPromise(thumbSrc);
    let ext = path.extname(thumbSrc).replace('.', '').toLowerCase();
 
    if (
      ext === 'png' ||
      ext === 'jpg' ||
      ext === 'jpeg' ||
      ext === 'svg' ||
      ext === 'gif'
    ) {
      if (!thumbSrcExists) {
        try {
          await createThumbnailJob(completePath, thumbSrc);
        } catch {
          return 'NOT_FOUND';
        }
      }
 
      if (ext === 'svg') ext = 'svg+xml';
 
      const mime = `image/${ext}`;
      const buffer = await promisify(fs.readFile)(thumbSrc);
      const base64 = buffer.toString('base64');
 
      return `data:${mime};base64,${base64}`;
    } else {
      return 'NO_IMAGE';
    }
  }
 
  /**
   * Find first match or default in array
   */
  private _findFirstMatchOrDefault(arr: BuildConfig[] | ServeConfig[] | undefined, key: string): BuildConfig | ServeConfig {
    let result;
 
    if (key) {
      result = (arr || []).find((x) => x.key === key);
      if (result) return result;
    }
 
    result = (arr || []).find((x) => x.key === 'default' || x.key === '' || x.key == null);
    if (result) return result;
 
    if (arr !== undefined && arr.length === 1) return arr[0];
 
    if (key) {
      throw new Error(
        `Could not find a config for key "${key}" and a default value was not available.`
      );
    } else {
      throw new Error(`Could not find a default config.`);
    }
  }
 
  /**
   * Set current base URL from SSG config
   */
  async setCurrentBaseUrl(ssgType: string, ssgVersion: string, configFile?: string): Promise<void> {
    // Reset currentBaseUrl
    this.appState.currentBaseUrl = undefined;
 
    try {
      const provider = await this.providerFactory.getProvider(ssgType);
      const configQuerier = provider.createConfigQuerier(this.workspacePath, ssgVersion, configFile);
 
      if (!configQuerier) {
        return; // Provider doesn't support config querying
      }
 
      const lines = await configQuerier.getConfigLines();
      const key = 'baseurl';
      const item = lines.find((element: string) => {
        return element.startsWith(key);
      });
 
      if (item) {
        // TOML
        let currentBaseUrl: string;
        if (item.includes('=')) {
          currentBaseUrl = item.split('=')[1].replace(/"/g, '').trim();
        }
        // YAML
        else {
          currentBaseUrl = item.replace('baseurl:', '').replace(/"/g, '').trim();
        }
        // TODO JSON
        if (currentBaseUrl && currentBaseUrl !== '/') {
          try {
            const url = new URL(currentBaseUrl);
            this.appState.currentBaseUrl = url.pathname;
          } catch {
            // Invalid URL, leave currentBaseUrl as undefined
          }
        }
      }
    } catch (error) {
      // If config querying fails, just leave currentBaseUrl as undefined
      console.warn('Failed to query SSG config for baseURL:', error);
    }
  }
 
  /**
   * Get SSG config languages (Hugo-specific feature)
   */
  async getHugoConfigLanguages(): Promise<HugoLanguage[]> {
    const workspaceDetails = await this.getConfigurationsData();
 
    try {
      let serveConfig: Partial<ServeConfig> | null = null;
      if (workspaceDetails.serve && workspaceDetails.serve.length) {
        serveConfig = this._findFirstMatchOrDefault(workspaceDetails.serve, '');
      } else {
        serveConfig = { config: '' };
      }
 
      const provider = await this.providerFactory.getProvider(workspaceDetails.ssgType);
      const configQuerier = provider.createConfigQuerier(
        this.workspacePath,
        workspaceDetails.ssgVersion,
        serveConfig.config
      );
 
      if (!configQuerier) {
        return []; // Provider doesn't support config querying
      }
 
      const config = await configQuerier.getConfig();
 
      if (!config.mounts) {
        return [];
      }
 
      // config.mounts can be either an array or an object with a mounts property
      // TODO: fix this weirdness with the mounts??
      const mountsArray = Array.isArray(config.mounts)
        ? config.mounts
        : (config.mounts as any).mounts;
 
      if (!Array.isArray(mountsArray)) {
        return [];
      }
 
      const filteredArray = mountsArray.filter((mount: any) => {
        return 'lang' in mount;
      }) as HugoLanguage[];
 
      return filteredArray;
    } catch (error) {
      console.warn('Failed to query SSG config languages:', error);
      return [];
    }
  }
 
  /**
   * Start SSG development server
   * Note: SSG binary must be pre-downloaded by the frontend before calling this method.
   * The frontend coordinates downloads via SSE to show progress to the user.
   */
  async serve(): Promise<void> {
    const workspaceDetails = await this.getConfigurationsData();
    const { ssgType, ssgVersion } = workspaceDetails;
 
    // Verify SSG binary is installed (if required) - frontend is responsible for downloading it first
    const provider = await this.providerFactory.getProvider(ssgType);
    const metadata = provider.getMetadata();
 
    if (metadata.requiresBinary) {
      const ssgBin = this.pathHelper.getSSGBinForVer(ssgType, ssgVersion);
      if (!fs.existsSync(ssgBin)) {
        throw new Error(
          `${metadata.name} version ${ssgVersion} is not installed. ` +
            `Please wait for the download to complete before starting the server.`
        );
      }
    }
 
    // Get serve configuration
    let serveConfig: any;
    if (workspaceDetails.serve && workspaceDetails.serve.length) {
      serveConfig = this._findFirstMatchOrDefault(workspaceDetails.serve, '');
    } else {
      serveConfig = { config: '' };
    }
 
    // Set current base URL
    await this.setCurrentBaseUrl(ssgType, ssgVersion, serveConfig.config);
 
    // Create dev server config
    const serverConfig: SSGServerConfig = {
      workspacePath: this.workspacePath,
      version: ssgVersion,
      configFile: serveConfig.config,
      siteKey: this.siteKey,
      workspaceKey: this.workspaceKey,
    };
 
    // Create and start dev server
    this.currentDevServer = provider.createDevServer(serverConfig);
    this.currentSSGType = ssgType;
 
    try {
      await this.currentDevServer.serve();
 
      // Make screenshot if no screenshots are made already
      const screenshotDir = path.join(
        this.workspacePath,
        'quiqr',
        'etalage',
        'screenshots'
      );
      if (!fs.existsSync(screenshotDir)) {
        console.log('autocreate screenshots');
        this.genereateEtalageImages();
      }
    } catch (error) {
      // Clean up on error
      this.currentDevServer = undefined;
      this.currentSSGType = undefined;
      throw error;
    }
  }
 
  /**
   * Stop the dev server if running
   */
  stopHugoServer(): void {
    Iif (this.currentDevServer) {
      this.currentDevServer.stopIfRunning();
      this.currentDevServer = undefined;
      this.currentSSGType = undefined;
    }
  }
 
  /**
   * Build the SSG site
   */
  async build(buildKey?: string, extraConfig: ExtraBuildConfig = {}): Promise<void> {
    const workspaceDetails = await this.getConfigurationsData();
    const { ssgType, ssgVersion } = workspaceDetails;
 
    // Get build configuration
    let buildConfig: any;
    if (workspaceDetails.build && workspaceDetails.build.length) {
      buildConfig = this._findFirstMatchOrDefault(workspaceDetails.build, buildKey || '');
    } else {
      buildConfig = { config: '' };
    }
 
    const destination = path.join(this.pathHelper.getBuildDir(this.workspacePath), 'public');
 
    // Create build config
    const builderConfig: SSGBuildConfig = {
      workspacePath: this.workspacePath,
      version: ssgVersion,
      configFile: buildConfig.config,
      destination: destination,
    };
 
    if (extraConfig.overrideBaseURLSwitch) {
      builderConfig.baseUrl = extraConfig.overrideBaseURL;
    }
 
    // Create and execute builder
    const provider = await this.providerFactory.getProvider(ssgType);
    const builder = provider.createBuilder(builderConfig);
 
    await builder.build();
  }
 
  /**
   * Generate etalage (showcase) images
   */
  async genereateEtalageImages(): Promise<void> {
    await recurForceRemove(
      this.pathHelper.workspaceCacheThumbsPath(
        this.workspacePath,
        path.join('quiqr', 'etalage', 'screenshots')
      )
    );
    await recurForceRemove(
      this.pathHelper.workspaceCacheThumbsPath(
        this.workspacePath,
        path.join('quiqr', 'etalage', 'favicon')
      )
    );
 
    const etalageDir = path.join(this.workspacePath, 'quiqr', 'etalage');
    this.screenshotWindowManager.createScreenshotAndFavicon('localhost', 13131, etalageDir);
  }
 
  /**
   * Get the current dev server instance
   */
  getCurrentHugoServer(): SSGDevServer | undefined {
    return this.currentDevServer;
  }
}