1 import fs from "fs/promises"
2 import { File, parse, ParseResult, traverse } from "../babel"
3 import { logger } from "../logger"
4 import {
5 generateHash,
6 getConfigObjectProperties,
7 getParserOptions,
8 } from "../utils"
9 import { getWidgetFilesFromSources } from "./helpers"
10
11 export async function generateWidgetHash(
12 sources: Set<string>
13 ): Promise<string> {
14 const files = await getWidgetFilesFromSources(sources)
15 const contents = await Promise.all(files.map(getWidgetContents))
16 const totalContent = contents
17 .flatMap(({ config, defaultExport }) => [config, defaultExport])
18 .filter(Boolean)
19 .join("")
20
21 return generateHash(totalContent)
22 }
23
24 async function getWidgetContents(
25 file: string
26 ): Promise<{ config: string | null; defaultExport: string | null }> {
27 const code = await fs.readFile(file, "utf-8")
28 let ast: ParseResult<File>
29
30 try {
31 ast = parse(code, getParserOptions(file))
32 } catch (e) {
33 logger.error(
34 `An error occurred while parsing the file. Due to the error we cannot validate whether the widget has changed. If your changes aren't correctly reflected try restarting the dev server.`,
35 {
36 file,
37 error: e,
38 }
39 )
40 return { config: null, defaultExport: null }
41 }
42
43 let configContent: string | null = null
44 let defaultExportContent: string | null = null
45
46 traverse(ast, {
47 ExportNamedDeclaration(path) {
48 const properties = getConfigObjectProperties(path)
49 if (properties) {
50 configContent = code.slice(path.node.start!, path.node.end!)
51 }
52 },
53 ExportDefaultDeclaration(path) {
54 defaultExportContent = code.slice(path.node.start!, path.node.end!)
55 },
56 })
57
58 return { config: configContent, defaultExport: defaultExportContent }
59 }