@elisra-devops/docgen-data-provider 1.106.0 → 1.107.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,6 +27,54 @@ type DocTypeBranchConfig = {
27
27
  fallbackStart?: any;
28
28
  };
29
29
 
30
+ type HistoricalQueryListItem = {
31
+ id: string;
32
+ queryName: string;
33
+ path: string;
34
+ };
35
+
36
+ type HistoricalWorkItemSnapshot = {
37
+ id: number;
38
+ workItemType: string;
39
+ title: string;
40
+ state: string;
41
+ areaPath: string;
42
+ iterationPath: string;
43
+ versionId: number | null;
44
+ versionTimestamp: string;
45
+ description: string;
46
+ steps: string;
47
+ testPhase: string;
48
+ relatedLinkCount: number;
49
+ workItemUrl: string;
50
+ };
51
+
52
+ type HistoricalSnapshotResult = {
53
+ queryId: string;
54
+ queryName: string;
55
+ asOf: string;
56
+ total: number;
57
+ rows: HistoricalWorkItemSnapshot[];
58
+ snapshotMap: Map<number, HistoricalWorkItemSnapshot>;
59
+ };
60
+
61
+ const HISTORICAL_WIT_API_VERSIONS: Array<string | null> = ['7.1', '5.1', null];
62
+ const HISTORICAL_BATCH_MAX_IDS = 200;
63
+ const HISTORICAL_WORK_ITEM_FIELDS = [
64
+ 'System.Id',
65
+ 'System.WorkItemType',
66
+ 'System.Title',
67
+ 'System.State',
68
+ 'System.AreaPath',
69
+ 'System.IterationPath',
70
+ 'System.Rev',
71
+ 'System.ChangedDate',
72
+ 'System.Description',
73
+ 'Microsoft.VSTS.TCM.Steps',
74
+ 'Elisra.TestPhase',
75
+ 'Custom.TestPhase',
76
+ ];
77
+
30
78
  /** Default fields fetched per work item in tree/flat query parsing. */
31
79
  const WI_DEFAULT_FIELDS =
32
80
  'System.Description,System.Title,Microsoft.VSTS.TCM.ReproSteps,Microsoft.VSTS.CMMI.Symptom';
@@ -191,12 +239,21 @@ export default class TicketsDataProvider {
191
239
  * @param docType document type
192
240
  * @returns
193
241
  */
242
+ private normalizeSharedQueriesPath(path: string): string {
243
+ const raw = String(path || '').trim();
244
+ if (!raw) return '';
245
+ const normalized = raw.toLowerCase();
246
+ if (normalized === 'shared' || normalized === 'shared queries') return '';
247
+ return raw;
248
+ }
249
+
194
250
  async GetSharedQueries(project: string, path: string, docType: string = ''): Promise<any> {
195
251
  let url;
196
252
  try {
197
- if (path === '')
253
+ const normalizedPath = this.normalizeSharedQueriesPath(path);
254
+ if (normalizedPath === '')
198
255
  url = `${this.orgUrl}${project}/_apis/wit/queries/Shared%20Queries?$depth=2&$expand=all`;
199
- else url = `${this.orgUrl}${project}/_apis/wit/queries/${path}?$depth=2&$expand=all`;
256
+ else url = `${this.orgUrl}${project}/_apis/wit/queries/${normalizedPath}?$depth=2&$expand=all`;
200
257
  let queries: any = await TFSServices.getItemContent(url, this.token);
201
258
  logger.debug(`doctype: ${docType}`);
202
259
  const normalizedDocType = (docType || '').toLowerCase();
@@ -404,6 +461,13 @@ export default class TicketsDataProvider {
404
461
  knownBugsQueryTree: knownBugsFetch?.result ?? null,
405
462
  };
406
463
  }
464
+ case 'historical-query':
465
+ case 'historical': {
466
+ const { tree1 } = await this.structureAllQueryPath(queriesWithChildren);
467
+ return {
468
+ historicalQueryTree: tree1 ? [tree1] : [],
469
+ };
470
+ }
407
471
  default:
408
472
  break;
409
473
  }
@@ -1490,6 +1554,597 @@ export default class TicketsDataProvider {
1490
1554
  return await this.GetQueryResultsByWiqlHref(wiql.href, project);
1491
1555
  }
1492
1556
 
1557
+ private normalizeHistoricalAsOf(value: string): string {
1558
+ const raw = String(value || '').trim();
1559
+ if (!raw) {
1560
+ throw new Error('asOf date-time is required');
1561
+ }
1562
+ const parsed = new Date(raw);
1563
+ if (Number.isNaN(parsed.getTime())) {
1564
+ throw new Error(`Invalid date-time value: ${raw}`);
1565
+ }
1566
+ return parsed.toISOString();
1567
+ }
1568
+
1569
+ private normalizeHistoricalCompareValue(value: unknown): string {
1570
+ if (value == null) {
1571
+ return '';
1572
+ }
1573
+ if (typeof value === 'string') {
1574
+ return value.replace(/\s+/g, ' ').trim();
1575
+ }
1576
+ if (Array.isArray(value)) {
1577
+ return value
1578
+ .map((item) => this.normalizeHistoricalCompareValue(item))
1579
+ .filter((item) => item !== '')
1580
+ .sort((a, b) => a.localeCompare(b))
1581
+ .join('; ');
1582
+ }
1583
+ if (typeof value === 'object') {
1584
+ const fallback = value as Record<string, unknown>;
1585
+ if (typeof fallback.displayName === 'string') {
1586
+ return this.normalizeHistoricalCompareValue(fallback.displayName);
1587
+ }
1588
+ if (typeof fallback.name === 'string') {
1589
+ return this.normalizeHistoricalCompareValue(fallback.name);
1590
+ }
1591
+ return this.normalizeHistoricalCompareValue(JSON.stringify(value));
1592
+ }
1593
+ return String(value).trim();
1594
+ }
1595
+
1596
+ private normalizeTestPhaseValue(value: unknown): string {
1597
+ const rendered = this.normalizeHistoricalCompareValue(value);
1598
+ if (!rendered) {
1599
+ return '';
1600
+ }
1601
+ const parts = rendered
1602
+ .split(/[;,]/)
1603
+ .map((part) => part.trim())
1604
+ .filter((part) => part.length > 0);
1605
+ if (parts.length <= 1) {
1606
+ return rendered;
1607
+ }
1608
+ const unique = Array.from(new Set(parts));
1609
+ unique.sort((a, b) => a.localeCompare(b));
1610
+ return unique.join('; ');
1611
+ }
1612
+
1613
+ private isTestCaseType(workItemType: string): boolean {
1614
+ const normalized = String(workItemType || '').trim().toLowerCase();
1615
+ return normalized === 'test case' || normalized === 'testcase';
1616
+ }
1617
+
1618
+ private toHistoricalRevision(value: unknown): number | null {
1619
+ const n = Number(value);
1620
+ if (!Number.isFinite(n)) {
1621
+ return null;
1622
+ }
1623
+ return n;
1624
+ }
1625
+
1626
+ private extractHistoricalWorkItemIds(queryResult: any): number[] {
1627
+ const ids = new Set<number>();
1628
+
1629
+ const pushId = (candidate: unknown) => {
1630
+ const n = Number(candidate);
1631
+ if (Number.isFinite(n)) {
1632
+ ids.add(n);
1633
+ }
1634
+ };
1635
+
1636
+ const workItems = Array.isArray(queryResult?.workItems) ? queryResult.workItems : [];
1637
+ for (const workItem of workItems) {
1638
+ pushId(workItem?.id);
1639
+ }
1640
+
1641
+ const workItemRelations = Array.isArray(queryResult?.workItemRelations)
1642
+ ? queryResult.workItemRelations
1643
+ : [];
1644
+ for (const relation of workItemRelations) {
1645
+ pushId(relation?.source?.id);
1646
+ pushId(relation?.target?.id);
1647
+ }
1648
+
1649
+ return Array.from(ids.values()).sort((a, b) => a - b);
1650
+ }
1651
+
1652
+ private appendAsOfToWiql(wiql: string, asOfIso: string): string {
1653
+ const raw = String(wiql || '').trim();
1654
+ if (!raw) {
1655
+ return '';
1656
+ }
1657
+ const withoutAsOf = raw.replace(/\s+ASOF\s+'[^']*'/i, '');
1658
+ return `${withoutAsOf} ASOF '${asOfIso}'`;
1659
+ }
1660
+
1661
+ private appendApiVersion(url: string, apiVersion: string | null): string {
1662
+ if (!apiVersion) {
1663
+ return url;
1664
+ }
1665
+ const separator = url.includes('?') ? '&' : '?';
1666
+ return `${url}${separator}api-version=${encodeURIComponent(apiVersion)}`;
1667
+ }
1668
+
1669
+ private shouldRetryHistoricalWithLowerVersion(error: any): boolean {
1670
+ const status = Number(error?.response?.status || 0);
1671
+ if (status === 401 || status === 403) {
1672
+ return false;
1673
+ }
1674
+ if (status >= 500) {
1675
+ return true;
1676
+ }
1677
+ if ([400, 404, 405, 406, 410].includes(status)) {
1678
+ return true;
1679
+ }
1680
+ const message = String(error?.response?.data?.message || error?.message || '');
1681
+ return /api[- ]?version/i.test(message);
1682
+ }
1683
+
1684
+ private async withHistoricalApiVersionFallback<T>(
1685
+ operation: string,
1686
+ task: (apiVersion: string | null) => Promise<T>,
1687
+ ): Promise<{ apiVersion: string | null; result: T }> {
1688
+ let lastError: any = null;
1689
+ for (const apiVersion of HISTORICAL_WIT_API_VERSIONS) {
1690
+ try {
1691
+ const result = await task(apiVersion);
1692
+ return { apiVersion, result };
1693
+ } catch (error: any) {
1694
+ lastError = error;
1695
+ const status = Number(error?.response?.status || 0);
1696
+ const apiVersionLabel = apiVersion || 'default';
1697
+ logger.warn(
1698
+ `[${operation}] failed with api-version=${apiVersionLabel}${status ? ` (status ${status})` : ''}`,
1699
+ );
1700
+ if (
1701
+ !this.shouldRetryHistoricalWithLowerVersion(error) ||
1702
+ apiVersion === HISTORICAL_WIT_API_VERSIONS[HISTORICAL_WIT_API_VERSIONS.length - 1]
1703
+ ) {
1704
+ throw error;
1705
+ }
1706
+ }
1707
+ }
1708
+ throw lastError || new Error(`[${operation}] Failed to execute historical request`);
1709
+ }
1710
+
1711
+ private chunkHistoricalWorkItemIds(ids: number[]): number[][] {
1712
+ const chunks: number[][] = [];
1713
+ for (let i = 0; i < ids.length; i += HISTORICAL_BATCH_MAX_IDS) {
1714
+ chunks.push(ids.slice(i, i + HISTORICAL_BATCH_MAX_IDS));
1715
+ }
1716
+ return chunks;
1717
+ }
1718
+
1719
+ private normalizeHistoricalQueryPath(path: string): string {
1720
+ const rawPath = String(path || '').trim();
1721
+ const normalizedRoot = rawPath.toLowerCase();
1722
+ if (
1723
+ rawPath === '' ||
1724
+ normalizedRoot === 'shared' ||
1725
+ normalizedRoot === 'shared queries'
1726
+ ) {
1727
+ return 'Shared%20Queries';
1728
+ }
1729
+
1730
+ const segments = rawPath
1731
+ .replace(/\\/g, '/')
1732
+ .split('/')
1733
+ .filter((segment) => segment.trim() !== '')
1734
+ .map((segment) => {
1735
+ try {
1736
+ return encodeURIComponent(decodeURIComponent(segment));
1737
+ } catch (error) {
1738
+ return encodeURIComponent(segment);
1739
+ }
1740
+ });
1741
+ return segments.join('/');
1742
+ }
1743
+
1744
+ private normalizeHistoricalQueryRoot(root: any): any {
1745
+ if (!root) return root;
1746
+ if (Array.isArray(root?.children) || typeof root?.isFolder === 'boolean') {
1747
+ return root;
1748
+ }
1749
+ if (Array.isArray(root?.value)) {
1750
+ return {
1751
+ id: 'root',
1752
+ name: 'Shared Queries',
1753
+ isFolder: true,
1754
+ children: root.value,
1755
+ };
1756
+ }
1757
+ return root;
1758
+ }
1759
+
1760
+ private async fetchHistoricalWorkItemsBatch(
1761
+ project: string,
1762
+ ids: number[],
1763
+ asOf: string,
1764
+ apiVersion: string | null,
1765
+ ): Promise<any[]> {
1766
+ const workItemsBatchUrl = this.appendApiVersion(
1767
+ `${this.orgUrl}${project}/_apis/wit/workitemsbatch`,
1768
+ apiVersion,
1769
+ );
1770
+ const idChunks = this.chunkHistoricalWorkItemIds(ids);
1771
+ try {
1772
+ const batchResponses = await Promise.all(
1773
+ idChunks.map((idChunk) =>
1774
+ this.limit(() =>
1775
+ TFSServices.getItemContent(workItemsBatchUrl, this.token, 'post', {
1776
+ ids: idChunk,
1777
+ asOf,
1778
+ $expand: 'Relations',
1779
+ fields: HISTORICAL_WORK_ITEM_FIELDS,
1780
+ }),
1781
+ ),
1782
+ ),
1783
+ );
1784
+ return batchResponses.flatMap((batch) => (Array.isArray(batch?.value) ? batch.value : []));
1785
+ } catch (error: any) {
1786
+ logger.warn(
1787
+ `[historical-workitems] workitemsbatch failed${
1788
+ apiVersion ? ` (api-version=${apiVersion})` : ''
1789
+ }, falling back to per-item retrieval: ${error?.message || error}`,
1790
+ );
1791
+ const asOfParam = encodeURIComponent(asOf);
1792
+ const responses = await Promise.all(
1793
+ ids.map((id) =>
1794
+ this.limit(() => {
1795
+ const itemUrl = this.appendApiVersion(
1796
+ `${this.orgUrl}${project}/_apis/wit/workitems/${id}?$expand=Relations&asOf=${asOfParam}`,
1797
+ apiVersion,
1798
+ );
1799
+ return TFSServices.getItemContent(itemUrl, this.token);
1800
+ }),
1801
+ ),
1802
+ );
1803
+ return responses.filter((item) => item && typeof item === 'object');
1804
+ }
1805
+ }
1806
+
1807
+ private async executeHistoricalQueryAtAsOf(
1808
+ project: string,
1809
+ queryId: string,
1810
+ asOfIso: string,
1811
+ ): Promise<{ queryDefinition: any; queryResult: any; apiVersion: string | null }> {
1812
+ const { apiVersion, result } = await this.withHistoricalApiVersionFallback(
1813
+ 'historical-query-execution',
1814
+ async (resolvedApiVersion) => {
1815
+ const queryDefUrl = this.appendApiVersion(
1816
+ `${this.orgUrl}${project}/_apis/wit/queries/${encodeURIComponent(queryId)}?$expand=all`,
1817
+ resolvedApiVersion,
1818
+ );
1819
+ const queryDefinition = await TFSServices.getItemContent(queryDefUrl, this.token);
1820
+
1821
+ const wiqlText = String(queryDefinition?.wiql || '').trim();
1822
+ let queryResult: any = null;
1823
+ try {
1824
+ if (!wiqlText) {
1825
+ throw new Error(`Could not resolve WIQL text for query ${queryId}`);
1826
+ }
1827
+ const wiqlWithAsOf = this.appendAsOfToWiql(wiqlText, asOfIso);
1828
+ if (!wiqlWithAsOf) {
1829
+ throw new Error(`Could not build WIQL for historical query ${queryId}`);
1830
+ }
1831
+ const executeUrl = this.appendApiVersion(
1832
+ `${this.orgUrl}${project}/_apis/wit/wiql?$top=2147483646&timePrecision=true`,
1833
+ resolvedApiVersion,
1834
+ );
1835
+ queryResult = await TFSServices.getItemContent(executeUrl, this.token, 'post', {
1836
+ query: wiqlWithAsOf,
1837
+ });
1838
+ } catch (inlineWiqlError: any) {
1839
+ logger.warn(
1840
+ `[historical-query-execution] inline WIQL failed for query ${queryId}${
1841
+ resolvedApiVersion ? ` (api-version=${resolvedApiVersion})` : ''
1842
+ }, trying WIQL-by-id fallback: ${inlineWiqlError?.message || inlineWiqlError}`,
1843
+ );
1844
+ const executeByIdUrl = this.appendApiVersion(
1845
+ `${this.orgUrl}${project}/_apis/wit/wiql/${encodeURIComponent(
1846
+ queryId,
1847
+ )}?$top=2147483646&timePrecision=true&asOf=${encodeURIComponent(asOfIso)}`,
1848
+ resolvedApiVersion,
1849
+ );
1850
+ queryResult = await TFSServices.getItemContent(executeByIdUrl, this.token);
1851
+ }
1852
+ return { queryDefinition, queryResult };
1853
+ },
1854
+ );
1855
+ return { ...result, apiVersion };
1856
+ }
1857
+
1858
+ private toHistoricalWorkItemSnapshot(project: string, workItem: any): HistoricalWorkItemSnapshot {
1859
+ const fields = (workItem?.fields || {}) as Record<string, unknown>;
1860
+ const id = Number(workItem?.id || fields['System.Id'] || 0);
1861
+ const workItemType = this.normalizeHistoricalCompareValue(fields['System.WorkItemType']);
1862
+ const testPhaseRaw =
1863
+ fields['Elisra.TestPhase'] ??
1864
+ fields['Custom.TestPhase'] ??
1865
+ fields['Elisra.Testphase'] ??
1866
+ fields['Custom.Testphase'];
1867
+ const relatedLinkCount = Array.isArray(workItem?.relations) ? workItem.relations.length : 0;
1868
+
1869
+ return {
1870
+ id,
1871
+ workItemType,
1872
+ title: this.normalizeHistoricalCompareValue(fields['System.Title']),
1873
+ state: this.normalizeHistoricalCompareValue(fields['System.State']),
1874
+ areaPath: this.normalizeHistoricalCompareValue(fields['System.AreaPath']),
1875
+ iterationPath: this.normalizeHistoricalCompareValue(fields['System.IterationPath']),
1876
+ versionId: this.toHistoricalRevision(workItem?.rev ?? fields['System.Rev']),
1877
+ versionTimestamp: this.normalizeHistoricalCompareValue(fields['System.ChangedDate']),
1878
+ description: this.normalizeHistoricalCompareValue(fields['System.Description']),
1879
+ steps: this.normalizeHistoricalCompareValue(fields['Microsoft.VSTS.TCM.Steps']),
1880
+ testPhase: this.normalizeTestPhaseValue(testPhaseRaw),
1881
+ relatedLinkCount,
1882
+ workItemUrl: `${this.orgUrl}${project}/_workitems/edit/${id}`,
1883
+ };
1884
+ }
1885
+
1886
+ private async getHistoricalSnapshot(
1887
+ project: string,
1888
+ queryId: string,
1889
+ asOfInput: string,
1890
+ ): Promise<HistoricalSnapshotResult> {
1891
+ const asOf = this.normalizeHistoricalAsOf(asOfInput);
1892
+ const { queryDefinition, queryResult, apiVersion } = await this.executeHistoricalQueryAtAsOf(
1893
+ project,
1894
+ queryId,
1895
+ asOf,
1896
+ );
1897
+ const ids = this.extractHistoricalWorkItemIds(queryResult);
1898
+
1899
+ if (ids.length === 0) {
1900
+ return {
1901
+ queryId,
1902
+ queryName: String(queryDefinition?.name || queryId),
1903
+ asOf,
1904
+ total: 0,
1905
+ rows: [],
1906
+ snapshotMap: new Map<number, HistoricalWorkItemSnapshot>(),
1907
+ };
1908
+ }
1909
+
1910
+ const values = await this.fetchHistoricalWorkItemsBatch(project, ids, asOf, apiVersion);
1911
+ const rows = values
1912
+ .map((workItem: any) => this.toHistoricalWorkItemSnapshot(project, workItem))
1913
+ .sort((a: HistoricalWorkItemSnapshot, b: HistoricalWorkItemSnapshot) => a.id - b.id);
1914
+ const snapshotMap = new Map<number, HistoricalWorkItemSnapshot>();
1915
+ for (const row of rows) {
1916
+ snapshotMap.set(row.id, row);
1917
+ }
1918
+
1919
+ return {
1920
+ queryId,
1921
+ queryName: String(queryDefinition?.name || queryId),
1922
+ asOf,
1923
+ total: rows.length,
1924
+ rows,
1925
+ snapshotMap,
1926
+ };
1927
+ }
1928
+
1929
+ private collectHistoricalQueries(root: any, parentPath = ''): HistoricalQueryListItem[] {
1930
+ const items: HistoricalQueryListItem[] = [];
1931
+ if (!root) {
1932
+ return items;
1933
+ }
1934
+
1935
+ const name = String(root?.name || '').trim();
1936
+ const currentPath = parentPath && name ? `${parentPath}/${name}` : name || parentPath;
1937
+
1938
+ if (!root?.isFolder) {
1939
+ const id = String(root?.id || '').trim();
1940
+ if (id) {
1941
+ items.push({
1942
+ id,
1943
+ queryName: name || id,
1944
+ path: parentPath || 'Shared Queries',
1945
+ });
1946
+ }
1947
+ return items;
1948
+ }
1949
+
1950
+ const children = Array.isArray(root?.children) ? root.children : [];
1951
+ for (const child of children) {
1952
+ items.push(...this.collectHistoricalQueries(child, currentPath || 'Shared Queries'));
1953
+ }
1954
+ return items;
1955
+ }
1956
+
1957
+ /**
1958
+ * Returns a flat list of shared queries for historical/as-of execution.
1959
+ */
1960
+ async GetHistoricalQueries(project: string, path: string = 'shared'): Promise<HistoricalQueryListItem[]> {
1961
+ const normalizedPath = this.normalizeHistoricalQueryPath(path);
1962
+ // Azure DevOps WIT query tree endpoint enforces $depth range 0..2.
1963
+ const depth = 2;
1964
+ const { result: root } = await this.withHistoricalApiVersionFallback('historical-queries-list', (apiVersion) => {
1965
+ const url = this.appendApiVersion(
1966
+ `${this.orgUrl}${project}/_apis/wit/queries/${normalizedPath}?$depth=${depth}&$expand=all`,
1967
+ apiVersion,
1968
+ );
1969
+ return TFSServices.getItemContent(url, this.token);
1970
+ });
1971
+ const normalizedRoot = this.normalizeHistoricalQueryRoot(root);
1972
+ const items = this.collectHistoricalQueries(normalizedRoot).filter((query) => query.id !== '');
1973
+ items.sort((a, b) => {
1974
+ const byPath = a.path.localeCompare(b.path);
1975
+ if (byPath !== 0) return byPath;
1976
+ return a.queryName.localeCompare(b.queryName);
1977
+ });
1978
+ return items;
1979
+ }
1980
+
1981
+ /**
1982
+ * Runs a shared query as-of a specific date-time and returns a flat work-item table snapshot.
1983
+ */
1984
+ async GetHistoricalQueryResults(queryId: string, project: string, asOfInput: string): Promise<any> {
1985
+ const snapshot = await this.getHistoricalSnapshot(project, queryId, asOfInput);
1986
+ return {
1987
+ queryId: snapshot.queryId,
1988
+ queryName: snapshot.queryName,
1989
+ asOf: snapshot.asOf,
1990
+ total: snapshot.total,
1991
+ rows: snapshot.rows.map((row) => ({
1992
+ id: row.id,
1993
+ workItemType: row.workItemType,
1994
+ title: row.title,
1995
+ state: row.state,
1996
+ areaPath: row.areaPath,
1997
+ iterationPath: row.iterationPath,
1998
+ versionId: row.versionId,
1999
+ versionTimestamp: row.versionTimestamp,
2000
+ workItemUrl: row.workItemUrl,
2001
+ })),
2002
+ };
2003
+ }
2004
+
2005
+ /**
2006
+ * Compares a shared query between two date-time baselines using the feature's noise-control fields.
2007
+ */
2008
+ async CompareHistoricalQueryResults(
2009
+ queryId: string,
2010
+ project: string,
2011
+ baselineAsOfInput: string,
2012
+ compareToAsOfInput: string,
2013
+ ): Promise<any> {
2014
+ const [baseline, compareTo] = await Promise.all([
2015
+ this.getHistoricalSnapshot(project, queryId, baselineAsOfInput),
2016
+ this.getHistoricalSnapshot(project, queryId, compareToAsOfInput),
2017
+ ]);
2018
+
2019
+ const allIds = new Set<number>([
2020
+ ...Array.from(baseline.snapshotMap.keys()),
2021
+ ...Array.from(compareTo.snapshotMap.keys()),
2022
+ ]);
2023
+ const sortedIds = Array.from(allIds.values()).sort((a, b) => a - b);
2024
+
2025
+ const rows = sortedIds.map((id) => {
2026
+ const baselineRow = baseline.snapshotMap.get(id) || null;
2027
+ const compareToRow = compareTo.snapshotMap.get(id) || null;
2028
+ const workItemType = compareToRow?.workItemType || baselineRow?.workItemType || '';
2029
+ const isTestCase = this.isTestCaseType(workItemType);
2030
+
2031
+ if (baselineRow && !compareToRow) {
2032
+ return {
2033
+ id,
2034
+ workItemType,
2035
+ title: baselineRow.title,
2036
+ baselineRevisionId: baselineRow.versionId,
2037
+ compareToRevisionId: null,
2038
+ compareStatus: 'Deleted',
2039
+ changedFields: [],
2040
+ differences: [],
2041
+ workItemUrl: baselineRow.workItemUrl,
2042
+ };
2043
+ }
2044
+
2045
+ if (!baselineRow && compareToRow) {
2046
+ return {
2047
+ id,
2048
+ workItemType,
2049
+ title: compareToRow.title,
2050
+ baselineRevisionId: null,
2051
+ compareToRevisionId: compareToRow.versionId,
2052
+ compareStatus: 'Added',
2053
+ changedFields: [],
2054
+ differences: [],
2055
+ workItemUrl: compareToRow.workItemUrl,
2056
+ };
2057
+ }
2058
+
2059
+ const safeBaseline = baselineRow as HistoricalWorkItemSnapshot;
2060
+ const safeCompareTo = compareToRow as HistoricalWorkItemSnapshot;
2061
+ const changedFields: string[] = [];
2062
+
2063
+ if (safeBaseline.description !== safeCompareTo.description) {
2064
+ changedFields.push('Description');
2065
+ }
2066
+ if (safeBaseline.title !== safeCompareTo.title) {
2067
+ changedFields.push('Title');
2068
+ }
2069
+ if (safeBaseline.state !== safeCompareTo.state) {
2070
+ changedFields.push('State');
2071
+ }
2072
+ if (isTestCase && safeBaseline.steps !== safeCompareTo.steps) {
2073
+ changedFields.push('Steps');
2074
+ }
2075
+ if (safeBaseline.testPhase !== safeCompareTo.testPhase) {
2076
+ changedFields.push('Test Phase');
2077
+ }
2078
+ if (isTestCase && safeBaseline.relatedLinkCount !== safeCompareTo.relatedLinkCount) {
2079
+ changedFields.push('Related Link Count');
2080
+ }
2081
+
2082
+ const differences = changedFields.map((field) => {
2083
+ switch (field) {
2084
+ case 'Description':
2085
+ return { field, baseline: safeBaseline.description, compareTo: safeCompareTo.description };
2086
+ case 'Title':
2087
+ return { field, baseline: safeBaseline.title, compareTo: safeCompareTo.title };
2088
+ case 'State':
2089
+ return { field, baseline: safeBaseline.state, compareTo: safeCompareTo.state };
2090
+ case 'Steps':
2091
+ return { field, baseline: safeBaseline.steps, compareTo: safeCompareTo.steps };
2092
+ case 'Test Phase':
2093
+ return { field, baseline: safeBaseline.testPhase, compareTo: safeCompareTo.testPhase };
2094
+ case 'Related Link Count':
2095
+ return {
2096
+ field,
2097
+ baseline: String(safeBaseline.relatedLinkCount),
2098
+ compareTo: String(safeCompareTo.relatedLinkCount),
2099
+ };
2100
+ default:
2101
+ return { field, baseline: '', compareTo: '' };
2102
+ }
2103
+ });
2104
+
2105
+ return {
2106
+ id,
2107
+ workItemType,
2108
+ title: safeCompareTo.title || safeBaseline.title,
2109
+ baselineRevisionId: safeBaseline.versionId,
2110
+ compareToRevisionId: safeCompareTo.versionId,
2111
+ compareStatus: changedFields.length > 0 ? 'Changed' : 'No changes',
2112
+ changedFields,
2113
+ differences,
2114
+ workItemUrl: safeCompareTo.workItemUrl || safeBaseline.workItemUrl,
2115
+ };
2116
+ });
2117
+
2118
+ const summary = rows.reduce(
2119
+ (acc, row) => {
2120
+ if (row.compareStatus === 'Added') acc.addedCount += 1;
2121
+ else if (row.compareStatus === 'Deleted') acc.deletedCount += 1;
2122
+ else if (row.compareStatus === 'Changed') acc.changedCount += 1;
2123
+ else acc.noChangeCount += 1;
2124
+ return acc;
2125
+ },
2126
+ { addedCount: 0, deletedCount: 0, changedCount: 0, noChangeCount: 0 },
2127
+ );
2128
+
2129
+ return {
2130
+ queryId,
2131
+ queryName: compareTo.queryName || baseline.queryName || queryId,
2132
+ baseline: {
2133
+ asOf: baseline.asOf,
2134
+ total: baseline.total,
2135
+ },
2136
+ compareTo: {
2137
+ asOf: compareTo.asOf,
2138
+ total: compareTo.total,
2139
+ },
2140
+ summary: {
2141
+ ...summary,
2142
+ updatedCount: summary.changedCount,
2143
+ },
2144
+ rows,
2145
+ };
2146
+ }
2147
+
1493
2148
  async PopulateWorkItemsByIds(workItemsArray: any[] = [], projectName: string = ''): Promise<any[]> {
1494
2149
  let url = `${this.orgUrl}${projectName}/_apis/wit/workitemsbatch`;
1495
2150
  let res: any[] = [];