UNPKG

@vaadin/hilla-file-router

Version:

Hilla file-based router

74 lines 2.7 kB
import { mkdir, readFile, writeFile } from "node:fs/promises"; import applyLayouts from "./applyLayouts.js"; import collectRoutesFromFS from "./collectRoutesFromFS.js"; import createRoutesFromMeta from "./createRoutesFromMeta.js"; import createViewConfigJson from "./createViewConfigJson.js"; /** * Generates a file conditionally. If the file already exists and its content is the same as the * given data, the file will not be overwritten. It is useful to avoid unnecessary server * reboot during development. * * @param url - The URL of the file to generate. * @param data - The data to write to the file. * @param forceWrite - true to force writing the file even if there are no changes * @returns true if the file was written, false otherwise. */ async function generateRuntimeFile(url, data, forceWrite) { await mkdir(new URL("./", url), { recursive: true }); let shouldWrite = forceWrite ?? false; if (!forceWrite) { let contents; try { contents = await readFile(url, "utf-8"); } catch (e) { if (!(e != null && typeof e === "object" && "code" in e && e.code === "ENOENT")) { throw e; } } shouldWrite = contents !== data; } if (shouldWrite) { await writeFile(url, data, "utf-8"); } return shouldWrite; } /** * Collects all file-based routes from the given directory, and based on them generates two files * described by {@link RuntimeFileUrls} type. * @param viewsDir - The directory that contains file-based routes (views). * @param urls - The URLs of the files to generate. * @param extensions - The list of extensions that will be collected as routes. * @param logger - The Vite logger instance. * @param debug - true to debug */ export async function generateRuntimeFiles(viewsDir, urls, extensions, logger, debug) { let routeMeta; try { routeMeta = await collectRoutesFromFS(viewsDir, { extensions, logger }); } catch (e) { if (e instanceof Error && "code" in e && e.code === "ENOENT") { routeMeta = []; } else { throw e; } } if (debug) { logger.info("Collected file-based routes"); } routeMeta = await applyLayouts(routeMeta, urls.layouts); const viewConfigJson = await createViewConfigJson(routeMeta); const runtimeRoutesCode = createRoutesFromMeta(routeMeta, viewConfigJson, urls); const jsonWritten = await generateRuntimeFile(urls.json, JSON.stringify(viewConfigJson, null, 2)); if (debug) { logger.info(`Frontend route list is generated: ${String(urls.json)}`); } const codeWritten = await generateRuntimeFile(urls.code, runtimeRoutesCode, jsonWritten); if (debug) { logger.info(`File Route module is generated: ${String(urls.code)}`); } return codeWritten; } //# sourceMappingURL=./generateRuntimeFiles.js.map