aboutsummaryrefslogtreecommitdiff
path: root/scripts/apidocs/output/diff-index.ts
blob: f32c5dfe7817295fb607aaf3bbbf1961e7444e27 (plain)
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
import { createHash } from 'node:crypto';
import { writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { RawApiDocsPage } from '../processing/class';
import type { RawApiDocsMethod } from '../processing/method';
import { FILE_PATH_PUBLIC } from '../utils/paths';

export const FILE_NAME_DOCS_DIFF_INDEX = 'api-diff-index.json';
export const FILE_PATH_DOCS_DIFF_INDEX = resolve(
  FILE_PATH_PUBLIC,
  FILE_NAME_DOCS_DIFF_INDEX
);

/**
 * The diff hashes for the entire api.
 */
export interface ApiDiffHashes {
  /**
   * The pages with their diff hashes.
   */
  [pages: string]: ApiPageDiffHashes;
}

/**
 * The diff hashes for a single api doc page.
 */
export interface ApiPageDiffHashes {
  /**
   * The checksum of the entire page.
   */
  pageHash: string;
  /**
   * The checksum of the method by name.
   */
  [method: string]: string;
}

/**
 * Writes the api diff index to the correct location.
 *
 * @param pages The pages to write into the index.
 */
export function writeDiffIndex(pages: RawApiDocsPage[]): void {
  const diffIndex: ApiDiffHashes = Object.fromEntries(
    pages.map((page) => [page.title, pageDiffHashes(page)])
  );
  writeFileSync(FILE_PATH_DOCS_DIFF_INDEX, JSON.stringify(diffIndex));
}

function pageDiffHashes(page: RawApiDocsPage): ApiPageDiffHashes {
  return {
    pageHash: diffHash({
      ...page,
      methods: undefined,
    } satisfies Partial<RawApiDocsPage>),
    ...Object.fromEntries(
      page.methods.map((method) => [method.name, methodDiffHash(method)])
    ),
  };
}

/**
 * Creates a diff hash for the given method by removing the line number from the source path.
 *
 * @param method The method to create a hash for.
 */
function methodDiffHash(method: RawApiDocsMethod): string {
  return diffHash({
    ...method,
    source: method.source.filePath,
  } satisfies Record<keyof RawApiDocsMethod, unknown>);
}

/**
 * Creates a diff hash for the given object.
 *
 * @param object The object to create a hash for.
 */
function diffHash(object: unknown): string {
  return createHash('md5').update(JSON.stringify(object)).digest('hex');
}