@griddo/cx 11.10.20 → 11.10.21

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../exporter/commands/prepare-assets-directory.ts", "../../exporter/core/errors.ts", "../../exporter/shared/npm-modules/brush.ts", "../../exporter/shared/types/render.ts", "../../exporter/core/db.ts", "../../exporter/shared/npm-modules/pkg-dir.ts", "../../exporter/shared/npm-modules/find-up-simple.ts", "../../exporter/shared/envs.ts", "../../exporter/core/GriddoLog.ts", "../../exporter/core/dist-rollback.ts", "../../exporter/core/fs.ts", "../../exporter/shared/errors.ts", "../../exporter/services/render.ts", "../../exporter/shared/endpoints.ts", "../../package.json", "../../exporter/shared/headers.ts", "../../exporter/services/auth.ts"],
4
- "sourcesContent": ["import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { withErrorHandler } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { getRenderModeFromDB, getRenderPathsHydratedWithDomainFromDB } from \"../services/render\";\nimport { RENDER_MODE } from \"../shared/types/render\";\n\nasync function prepareAssetsDir() {\n\tconst [domain] = process.argv.slice(2);\n\n\tconst { renderMode } = await getRenderModeFromDB(domain);\n\n\tif (renderMode === RENDER_MODE.IDLE) {\n\t\treturn;\n\t}\n\n\tconst { __exports } = await getRenderPathsHydratedWithDomainFromDB({ domain });\n\tconst assetsDir = path.join(__exports, \"assets\");\n\tconst domainAssetsDir = path.join(__exports, domain);\n\n\tif (await pathExists(assetsDir)) {\n\t\tawait fsp.rm(domainAssetsDir, { force: true, recursive: true });\n\t\tawait fsp.rename(assetsDir, domainAssetsDir);\n\t} else {\n\t\tGriddoLog.warn(\"Assets directory not found\");\n\t}\n}\n\nasync function main() {\n\tawait prepareAssetsDir();\n}\n\nwithErrorHandler(main);\n", "import type { ErrorsType } from \"../shared/errors\";\n\nimport path from \"node:path\";\n\nimport { brush } from \"../shared/npm-modules/brush\";\nimport { RENDER_MODE } from \"../shared/types/render\";\nimport { readDB, writeDB } from \"./db\";\nimport { distRollback } from \"./dist-rollback\";\nimport { GriddoLog } from \"./GriddoLog\";\n\nexport type ErrorData = {\n\terror: ErrorsType;\n\tmessage: string;\n\texpected?: string;\n\thint?: string;\n};\n\nexport class RenderError extends Error {\n\tconstructor(originalError?: unknown) {\n\t\tsuper(originalError instanceof Error ? originalError.message : String(originalError));\n\n\t\tthis.name = \"InternalCXError\";\n\t\tthis.stack = originalError instanceof Error ? originalError.stack : \"\";\n\t}\n}\n\n/**\n * Throws an error with the provided error message, expected value, and hint.\n */\nfunction throwError(options: ErrorData, stack?: unknown): never {\n\tconst { error, message, expected, hint } = options;\n\n\tconst errorColor = GriddoLog.log(brush.red(`[ ${error} ]`));\n\tconst extraText = [expected, hint].filter(Boolean).join(\"\\n\");\n\n\tGriddoLog.log(`\n${errorColor}\n${message}\n${extraText}\n\n${brush.red(\"stack\")}\n${JSON.stringify(stack, null, 2)}`);\n\n\tthrow new RenderError(stack);\n}\n\n/**\n * Executes the provided asynchronous function and handles errors that occur during execution.\n *\n * - If an error is thrown, attempts to log the error and, if necessary, rolls back the exports directory.\n * - Updates the render database to set the domain's rendering state to \"ERROR\" if an error occurs.\n *\n * @param fn - The asynchronous function to execute within the error handler.\n * @returns A promise that resolves when the function is executed successfully.\n * @throws RenderError | unknown - Rethrows the original error after handling and database state update.\n */\nasync function withErrorHandler(fn: () => Promise<void>) {\n\ttry {\n\t\tawait fn();\n\t} catch (error) {\n\t\tif (error instanceof RenderError) {\n\t\t\tGriddoLog.error(\"Internal Griddo RenderError\");\n\t\t} else if (error instanceof Error) {\n\t\t\tGriddoLog.error(error.message);\n\t\t} else {\n\t\t\tGriddoLog.error(`An unexpected error occurred ${error}`);\n\t\t}\n\n\t\t// Try to rollback the exports directory if needed\n\t\ttry {\n\t\t\tconst data = await readDB();\n\t\t\tconst { root } = data.paths;\n\t\t\tif (data.needsRollbackOnError) {\n\t\t\t\tGriddoLog.info(\"Cleaning exports dir...\");\n\t\t\t\tGriddoLog.verbose(`Deleting ${path.join(root, \"exports\")}...`);\n\n\t\t\t\tawait distRollback(data.currentRenderingDomain!);\n\t\t\t} else {\n\t\t\t\tGriddoLog.info(\"No rollback needed, skipping...\");\n\t\t\t}\n\t\t} catch (_e) {\n\t\t\tGriddoLog.info(\"Early render stage, no db.json created yet...\");\n\t\t}\n\n\t\tconst data = await readDB();\n\t\tdata.domains[data.currentRenderingDomain!].isRendering = false;\n\t\tdata.domains[data.currentRenderingDomain!].renderMode = RENDER_MODE.ERROR;\n\t\tawait writeDB(data);\n\t\tthrow error;\n\t}\n}\n\nexport { throwError, withErrorHandler };\n", "//\n// Brush adds color to a string|number, it does not print it!\n// Its simple, no log, no chains, just color in a string|number\n// usage:\n// console.log(brush.green(\"sucess!\"))\n//\n\nconst RESET = \"\\x1b[0m\";\nconst CODES = {\n\tblack: \"\\x1b[30m\",\n\tred: \"\\x1b[31m\",\n\tgreen: \"\\x1b[32m\",\n\tyellow: \"\\x1b[33m\",\n\tblue: \"\\x1b[34m\",\n\tmagenta: \"\\x1b[35m\",\n\tcyan: \"\\x1b[36m\",\n\twhite: \"\\x1b[37m\",\n\tgray: \"\\x1b[90m\",\n\tbold: \"\\x1b[1m\",\n\tdim: \"\\x1b[2m\",\n} as const;\n\ntype ColorFunction = (text: string | number) => string;\ntype ColorName = keyof typeof CODES;\ntype Brush = Record<ColorName, ColorFunction>;\n\nconst brush = {} as Brush;\n\nfor (const color in CODES) {\n\tconst key = color as ColorName;\n\tbrush[key] = (text: string | number) => `${CODES[key]}${text}${RESET}`;\n}\n\nexport { brush };\n", "import type { RenderInfo } from \"./global\";\n\nconst RENDER_MODE = {\n\tFROM_SCRATCH: \"FROM_SCRATCH\",\n\tINCREMENTAL: \"INCREMENTAL\",\n\tIDLE: \"IDLE\",\n\tERROR: \"ERROR\",\n\tCOMPLETED: \"COMPLETED\",\n} as const;\n\ntype RenderMode = (typeof RENDER_MODE)[keyof typeof RENDER_MODE];\n\nexport interface RenderModeTuple {\n\trenderMode: RenderMode;\n\treason?: string;\n}\n\ntype DomainLike = string;\n\ntype RenderDB = {\n\tgriddoVersion: string;\n\tbuildReportFileName: string;\n\tsortedDomains: DomainLike[];\n\tneedsRollbackOnError: boolean;\n\tcurrentRenderingDomain: string | null;\n\tcommitHash: string;\n\tcommitMessage: string;\n\tpaths: {\n\t\troot: string;\n\t\tcx: string;\n\t\tssg: string;\n\t\tcxCache: string;\n\t\tcomponents: string;\n\t\texportsDir: string;\n\t\texportsDirBackup: string;\n\t};\n\tdomains: {\n\t\t[key: DomainLike]: {\n\t\t\tid?: number;\n\t\t\trenderMode?: RenderMode;\n\t\t\tshouldBeRendered?: boolean;\n\t\t\tisRendering?: boolean;\n\t\t\trenderInfo?: RenderInfo;\n\t\t\trenderModeReason?: string;\n\t\t};\n\t};\n};\n\ninterface Report {\n\tauthControl:\n\t\t| {\n\t\t\t\tAuthorization: string;\n\t\t\t\t\"Cache-Control\": string;\n\t\t\t\tlang?: string | undefined;\n\t\t }\n\t\t| undefined;\n\tsites: {\n\t\tsiteId: number;\n\t\tpublishHashes: string[];\n\t\tsiteHash: string | null;\n\t\tunpublishHashes: string[];\n\t\tpublishPagesIds: number[];\n\t}[];\n}\n\nexport { RENDER_MODE, type RenderDB, type RenderMode, type Report };\n", "import type { RenderDB } from \"../shared/types/render\";\n\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { pkgDirSync } from \"../shared/npm-modules/pkg-dir\";\nimport { GriddoLog } from \"./GriddoLog\";\n\nconst root = pkgDirSync({ cwd: path.resolve(__dirname, \"../../..\") }) || \"\";\nconst cache = path.join(root, \".griddo/cache\");\nconst dbFilePath = path.join(cache, \"db.json\");\n\nasync function readDB(customDBPath = \"\") {\n\tconst file = customDBPath || dbFilePath;\n\ttry {\n\t\treturn JSON.parse(await fsp.readFile(file, \"utf-8\")) as RenderDB;\n\t} catch (error) {\n\t\tGriddoLog.error(`Failed to read DB file at ${file}:`, error);\n\t\tthrow error;\n\t}\n}\n\nasync function writeDB(renderDB: RenderDB, customDBPath = \"\") {\n\tconst file = customDBPath || dbFilePath;\n\ttry {\n\t\tawait fsp.writeFile(file, JSON.stringify(renderDB, null, \"\\t\"));\n\t} catch (error) {\n\t\tGriddoLog.error(`Failed to write DB file at ${file}:`, error);\n\t\tthrow error;\n\t}\n}\n\nexport { readDB, writeDB };\n", "import path from \"node:path\";\n\nimport { findUp, findUpSync } from \"./find-up-simple\";\n\nasync function pkgDir(options?: { readonly cwd?: string }) {\n\tconst { cwd } = options || {};\n\tconst filePath = await findUp(\"package.json\", { cwd });\n\treturn filePath && path.dirname(filePath);\n}\n\nfunction pkgDirSync(options?: { readonly cwd?: string }) {\n\tconst { cwd } = options || {};\n\tconst filePath = findUpSync(\"package.json\", { cwd });\n\treturn filePath && path.dirname(filePath);\n}\n\nexport { pkgDir, pkgDirSync };\n", "import fs from \"node:fs\";\nimport fsPromises from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Opciones para controlar el comportamiento de la b\u00FAsqueda.\n */\nexport type Options = {\n\t/**\n\tEl directorio desde donde empezar a buscar.\n\t@default process.cwd()\n\t*/\n\treadonly cwd?: URL | string;\n\n\t/**\n\tEl tipo de ruta a buscar.\n\t@default 'file'\n\t*/\n\treadonly type?: \"file\" | \"directory\";\n\n\t/**\n\tUn directorio en el que la b\u00FAsqueda se detiene si no se encuentran coincidencias.\n\t@default El directorio ra\u00EDz del sistema\n\t*/\n\treadonly stopAt?: URL | string;\n};\n\n// Funci\u00F3n auxiliar para convertir una URL en una ruta de archivo de tipo string.\nconst toPath = (urlOrPath: URL | string | undefined): string | undefined =>\n\turlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n\n/**\n * Encuentra un archivo o directorio de forma as\u00EDncrona subiendo por los directorios padre.\n * @param name - El nombre del archivo o directorio a buscar.\n * @param options - Opciones de b\u00FAsqueda.\n * @returns La ruta encontrada o `undefined` si no se pudo encontrar.\n */\nexport async function findUp(name: string, options: Options = {}): Promise<string | undefined> {\n\tconst { cwd = process.cwd(), type = \"file\", stopAt: stopAtOption } = options;\n\n\tlet directory = path.resolve(toPath(cwd) ?? \"\");\n\tconst { root } = path.parse(directory);\n\tconst stopAt = stopAtOption ? path.resolve(directory, toPath(stopAtOption)!) : root;\n\tconst isAbsoluteName = path.isAbsolute(name);\n\n\twhile (true) {\n\t\tconst filePath = isAbsoluteName ? name : path.join(directory, name);\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst stats = await fsPromises.stat(filePath);\n\t\t\tif ((type === \"file\" && stats.isFile()) || (type === \"directory\" && stats.isDirectory())) {\n\t\t\t\treturn filePath;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignora errores (ej. el archivo no existe) y contin\u00FAa la b\u00FAsqueda.\n\t\t}\n\n\t\tif (directory === stopAt || directory === root) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n}\n\n/**\n * Encuentra un archivo o directorio de forma s\u00EDncrona subiendo por los directorios padre.\n * @param name - El nombre del archivo o directorio a buscar.\n * @param options - Opciones de b\u00FAsqueda.\n * @returns La ruta encontrada o `undefined` si no se pudo encontrar.\n */\nexport function findUpSync(name: string, options: Options = {}): string | undefined {\n\tconst { cwd = process.cwd(), type = \"file\", stopAt: stopAtOption } = options;\n\n\tlet directory = path.resolve(toPath(cwd) ?? \"\");\n\tconst { root } = path.parse(directory);\n\tconst stopAt = stopAtOption ? path.resolve(directory, toPath(stopAtOption)!) : root;\n\tconst isAbsoluteName = path.isAbsolute(name);\n\n\twhile (true) {\n\t\tconst filePath = isAbsoluteName ? name : path.join(directory, name);\n\t\ttry {\n\t\t\tconst stats = fs.statSync(filePath, { throwIfNoEntry: false });\n\t\t\tif ((type === \"file\" && stats?.isFile()) || (type === \"directory\" && stats?.isDirectory())) {\n\t\t\t\treturn filePath;\n\t\t\t}\n\t\t} catch {\n\t\t\t// En teor\u00EDa, statSync con `throwIfNoEntry: false` no deber\u00EDa lanzar un error,\n\t\t\t// pero se mantiene por seguridad.\n\t\t}\n\n\t\tif (directory === stopAt || directory === root) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n}\n", "const { env } = process;\n\n/**\n * Returns true/false from string\n */\nfunction envIsTruthy(value?: string): boolean {\n\tif (!value) return false;\n\n\tswitch (value.trim().toLowerCase()) {\n\t\tcase \"1\":\n\t\tcase \"true\":\n\t\tcase \"yes\":\n\t\tcase \"y\":\n\t\tcase \"on\":\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n// Credentials\nconst GRIDDO_API_URL = env.GRIDDO_API_URL || env.API_URL;\nconst GRIDDO_PUBLIC_API_URL = env.GRIDDO_PUBLIC_API_URL || env.PUBLIC_API_URL;\nconst GRIDDO_BOT_USER = env.botEmail || env.GRIDDO_BOT_USER;\nconst GRIDDO_BOT_PASSWORD = env.botPassword || env.GRIDDO_BOT_PASSWORD;\n\n// Rendering\nconst GRIDDO_API_CONCURRENCY_COUNT = Number.parseInt(env.GRIDDO_API_CONCURRENCY_COUNT || \"10\");\nconst GRIDDO_SKIP_BUILD_CHECKS = envIsTruthy(env.GRIDDO_SKIP_BUILD_CHECKS);\nconst GRIDDO_BUILD_LOGS = envIsTruthy(env.GRIDDO_BUILD_LOGS);\nconst GRIDDO_BUILD_LOGS_BUFFER_SIZE = Number.parseInt(env.GRIDDO_BUILD_LOGS_BUFFER_SIZE || \"500\");\nconst GRIDDO_SSG_VERBOSE_LOGS = envIsTruthy(env.GRIDDO_SSG_VERBOSE_LOGS);\nconst GRIDDO_SEARCH_FEATURE = envIsTruthy(env.GRIDDO_SEARCH_FEATURE);\nconst GRIDDO_ASSET_PREFIX = env.GRIDDO_ASSET_PREFIX || env.ASSET_PREFIX;\nconst GRIDDO_REACT_APP_INSTANCE = env.GRIDDO_REACT_APP_INSTANCE || env.REACT_APP_INSTANCE;\nconst GRIDDO_AI_EMBEDDINGS = envIsTruthy(env.GRIDDO_AI_EMBEDDINGS);\nconst GRIDDO_VERBOSE_LOGS = envIsTruthy(env.GRIDDO_VERBOSE_LOGS);\nconst GRIDDO_USE_DIST_BACKUP = envIsTruthy(env.GRIDDO_USE_DIST_BACKUP);\nconst GRIDDO_SSG_BUNDLE_ANALYZER = envIsTruthy(env.GRIDDO_SSG_BUNDLE_ANALYZER);\nconst GRIDDO_RENDER_DISABLE_LLMS_TXT = envIsTruthy(env.GRIDDO_RENDER_DISABLE_LLMS_TXT);\n\nexport {\n\tGRIDDO_AI_EMBEDDINGS,\n\tGRIDDO_API_CONCURRENCY_COUNT,\n\tGRIDDO_API_URL,\n\tGRIDDO_ASSET_PREFIX,\n\tGRIDDO_BOT_PASSWORD,\n\tGRIDDO_BOT_USER,\n\tGRIDDO_BUILD_LOGS,\n\tGRIDDO_BUILD_LOGS_BUFFER_SIZE,\n\tGRIDDO_PUBLIC_API_URL,\n\tGRIDDO_REACT_APP_INSTANCE,\n\tGRIDDO_RENDER_DISABLE_LLMS_TXT,\n\tGRIDDO_SEARCH_FEATURE,\n\tGRIDDO_SKIP_BUILD_CHECKS,\n\tGRIDDO_SSG_BUNDLE_ANALYZER,\n\tGRIDDO_SSG_VERBOSE_LOGS,\n\tGRIDDO_USE_DIST_BACKUP,\n\tGRIDDO_VERBOSE_LOGS,\n};\n", "import { GRIDDO_BUILD_LOGS, GRIDDO_VERBOSE_LOGS } from \"../shared/envs\";\nimport { brush } from \"../shared/npm-modules/brush\";\n\n/**\n * Clase est\u00E1tica para gestionar los logs de la aplicaci\u00F3n.\n * No se puede instanciar, se usa directamente: GriddoLogs.info(\"mensaje\").\n */\nclass GriddoLog {\n\t/** El constructor es privado para prevenir la instanciaci\u00F3n de la clase. */\n\tprivate constructor() {}\n\n\tpublic static verbose(...str: unknown[]): void {\n\t\tif (GRIDDO_VERBOSE_LOGS) {\n\t\t\tconsole.log(brush.yellow(\"verbose\"), brush.dim(str.join(\" \")));\n\t\t}\n\t}\n\n\tpublic static build(...str: unknown[]): void {\n\t\tif (GRIDDO_BUILD_LOGS) {\n\t\t\tGriddoLog.log(...str);\n\t\t}\n\t}\n\n\tpublic static info(...str: unknown[]): void {\n\t\tconsole.log(`${brush.blue(\"info\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static success(...str: unknown[]): void {\n\t\tconsole.log(`${brush.green(\"success\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static error(...str: unknown[]): void {\n\t\tconsole.error(`${brush.red(\"error\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static warn(...str: unknown[]): void {\n\t\tconsole.warn(`${brush.yellow(\"warn\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static log(...args: Parameters<typeof console.log>): void {\n\t\tconsole.log(...args);\n\t}\n}\n\nexport { GriddoLog };\n", "import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { readDB } from \"./db\";\nimport { pathExists } from \"./fs\";\nimport { GriddoLog } from \"./GriddoLog\";\n\n/**\n * Rolls back the exports directory for the given domain.\n *\n * - Deletes the potentially corrupt exports directory for the domain.\n * - If a backup exists, it restores the directory from the backup location.\n * - If no backup is found, it informs that a fresh exports directory will be created on the next render.\n *\n * @param domain The domain for which to rollback the exports directory.\n */\nasync function distRollback(domain: string): Promise<void> {\n\tconst data = await readDB();\n\tconst { exportsDir, exportsDirBackup } = data.paths;\n\n\tGriddoLog.info(`Cleaning exports dir for the domain ${domain}`);\n\tGriddoLog.verbose(`Deleting ${path.join(exportsDir, domain)}...`);\n\n\t// TODO: Probar rsync en lugar de borrar y copiar\n\n\t// 1 - Borrar dist corrupto\n\tawait fsp.rm(path.join(exportsDir, domain), {\n\t\trecursive: true,\n\t\tforce: true,\n\t});\n\n\t// 2 - Si hay backup, restaurar\n\tif (await pathExists(path.join(exportsDirBackup, domain))) {\n\t\tawait fsp.cp(path.join(exportsDirBackup, domain), path.join(exportsDir, domain), {\n\t\t\trecursive: true,\n\t\t});\n\n\t\tGriddoLog.info(`export-backup dir for the domain ${domain} found. Restoring before exit...`);\n\t\tGriddoLog.verbose(\n\t\t\t`Copying ${path.join(exportsDirBackup, domain)} -> ${path.join(exportsDir, domain)}...`,\n\t\t);\n\t} else {\n\t\tGriddoLog.info(\n\t\t\t\"No export-backup found, skipping rollback. Next render will create a new exports dir from scratch...\",\n\t\t);\n\t}\n}\n\nexport { distRollback };\n", "import type { MakeDirectoryOptions } from \"node:fs\";\n\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { ArtifactError } from \"../shared/errors\";\nimport { throwError } from \"./errors\";\nimport { GriddoLog } from \"./GriddoLog\";\n\n/**\n * Remove an empty directory from the basePath recursively.\n * If the directory has only .xml files it will handle as empty too (empty site)\n *\n * @param baseDir - The base directory.\n */\nasync function deleteDisposableSiteDirs(baseDir: string) {\n\tif (!(await pathExists(baseDir))) {\n\t\treturn;\n\t}\n\n\tconst sitesDirs = (await fsp.readdir(baseDir, { withFileTypes: true })).filter((file) =>\n\t\tfile.isDirectory(),\n\t);\n\n\tfor (const siteDir of sitesDirs) {\n\t\tconst sitePath = path.join(baseDir, siteDir.name);\n\t\tif (await siteIsEmpty(sitePath)) {\n\t\t\tawait fsp.rm(sitePath, { recursive: true });\n\t\t}\n\t}\n}\n\n/**\n * Creates multiple artifact directories.\n *\n * @param dirs - An array of directory paths.\n * @param options - Same option as `fs.mkdirSync()`\n */\nasync function mkDirs(dirs: string[], options?: MakeDirectoryOptions) {\n\tfor (const dir of dirs) {\n\t\ttry {\n\t\t\tif (!(await pathExists(dir))) {\n\t\t\t\tawait fsp.mkdir(dir, { recursive: true, ...options });\n\t\t\t\tGriddoLog.verbose(`create directory: ${dir}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\nasync function renamePath(src: string, dst: string) {\n\ttry {\n\t\tif (await pathExists(src)) {\n\t\t\tawait fsp.rename(src, dst);\n\t\t\tGriddoLog.verbose(`rename ${src} to ${dst}`);\n\t\t}\n\t} catch (error) {\n\t\tthrowError(ArtifactError, error);\n\t}\n}\n\n/**\n * Copy multiple directories with backup option.\n *\n * @param src - Source directory.\n * @param dst - Destination directory.\n * @param dirs - Directories to copy.\n * @param options.withBackup - Create a previous backup before copy.\n */\nasync function cpDirs(\n\tsrc: string,\n\tdst: string,\n\tdirs: string[],\n\toptions = {\n\t\twithBackup: false,\n\t},\n) {\n\tconst { withBackup } = options;\n\tfor (const dir of dirs) {\n\t\tconst srcCompose = path.join(src, dir);\n\t\tconst dstCompose = path.join(dst, dir);\n\n\t\t// The dir we want to copy, doesn't exist.\n\t\tif (!(await pathExists(srcCompose))) {\n\t\t\tGriddoLog.info(`(Maybe first render) Source directory does not exist: ${srcCompose}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Create the backup\n\t\tif (withBackup) {\n\t\t\tawait createBackup(dstCompose);\n\t\t\tGriddoLog.verbose(`create backup: ${dstCompose}`);\n\t\t}\n\n\t\t// Copy directory\n\t\ttry {\n\t\t\t// First clean destination\n\t\t\tif (await pathExists(dstCompose)) {\n\t\t\t\tawait fsp.rm(dstCompose, { recursive: true, force: true });\n\t\t\t\tGriddoLog.verbose(`clean destination: ${dstCompose}`);\n\t\t\t}\n\n\t\t\t// Then copy src to dst\n\t\t\tawait fsp.cp(srcCompose, dstCompose, {\n\t\t\t\trecursive: true,\n\t\t\t\tpreserveTimestamps: true,\n\t\t\t});\n\t\t\tGriddoLog.verbose(`copy: ${srcCompose} to ${dstCompose}`);\n\n\t\t\tif (withBackup) {\n\t\t\t\tawait deleteBackup(dstCompose);\n\t\t\t\tGriddoLog.verbose(`delete backup: ${dstCompose}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (withBackup) {\n\t\t\t\tawait restoreBackup(dstCompose);\n\t\t\t\tGriddoLog.verbose(\"Backup has been restored.\");\n\t\t\t}\n\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\n/**\n * Move artifacts between cx-paths\n *\n * @param src - Source directory.\n * @param dst - Destination directory.\n * @param dirs - Directories to move.\n * @param options - Options.\n */\nasync function mvDirs(\n\tsrc: string,\n\tdst: string,\n\tdirs: string[],\n\toptions?: { withBackup?: boolean; override?: boolean },\n) {\n\tconst { override, withBackup } = options || {};\n\n\tfor (const dir of dirs) {\n\t\tconst srcCompose = path.join(src, dir);\n\t\tconst dstCompose = path.join(dst, dir);\n\n\t\tif (!(await pathExists(srcCompose))) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (withBackup) {\n\t\t\tawait createBackup(dstCompose);\n\t\t}\n\n\t\ttry {\n\t\t\t// Clean destination\n\t\t\tif (override && (await pathExists(dstCompose))) {\n\t\t\t\tawait fsp.rm(dstCompose, { recursive: true, force: true });\n\t\t\t}\n\n\t\t\tawait fsp.rename(srcCompose, dstCompose);\n\t\t\tGriddoLog.verbose(`moved: ${srcCompose} to ${dstCompose}`);\n\n\t\t\tif (withBackup) {\n\t\t\t\tawait deleteBackup(dstCompose);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (withBackup) {\n\t\t\t\tawait restoreBackup(dstCompose);\n\t\t\t\tGriddoLog.info(\"Backup has been restored.\");\n\t\t\t}\n\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\n/**\n * Removes multiple artifact directories.\n *\n * @param dirs - An array of directory paths.\n */\nasync function rmDirs(dirs: string[]) {\n\tfor (const dir of dirs) {\n\t\ttry {\n\t\t\tawait fsp.rm(dir, { recursive: true, force: true });\n\t\t\tGriddoLog.verbose(`artifact removed: ${dir}`);\n\t\t} catch (error) {\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\nasync function restoreBackup(src: string, suffix = \"-BACKUP\") {\n\tconst dst = src + suffix;\n\ttry {\n\t\tawait fsp.rename(dst, src);\n\t\tGriddoLog.info(`Backup ${dst} has been restored`);\n\t} catch (_error) {\n\t\tthrow new Error(`Error while delete ${dst} backup`);\n\t}\n}\n\nasync function deleteBackup(src: string, suffix = \"-BACKUP\") {\n\tconst dst = src + suffix;\n\n\tif (!(await pathExists(dst))) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait fsp.rm(dst, { recursive: true, force: true });\n\t\tGriddoLog.verbose(`Backup ${dst} has been deleted`);\n\t} catch (_error) {\n\t\tthrow new Error(`Error while delete ${dst} backup`);\n\t}\n}\n\nasync function createBackup(src: string, suffix = \"-BACKUP\") {\n\tconst dst = src + suffix;\n\n\tif (!(await pathExists(src))) {\n\t\treturn;\n\t}\n\n\tif (await pathExists(dst)) {\n\t\tGriddoLog.warn(`Destination ${dst} already exists`);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait fsp.rename(src, dst);\n\t\tGriddoLog.verbose(`Backup of ${src} has been created in ${dst}`);\n\t} catch (error) {\n\t\tGriddoLog.error(`Error while coping ${src} to ${dst} backup`);\n\t\tthrowError(ArtifactError, error);\n\t}\n}\n\n/**\n * Return true if the site folder is empty or only has xml files. (Recursively)\n */\nasync function siteIsEmpty(sitePath: string) {\n\tconst siteFiles = (\n\t\tawait fsp.readdir(sitePath, {\n\t\t\twithFileTypes: true,\n\t\t\trecursive: true,\n\t\t})\n\t).filter((file) => file.isFile() && !path.basename(file.name).startsWith(\".\"));\n\n\tconst xmlFiles = siteFiles.filter((file) => file.name.endsWith(\".xml\"));\n\n\tif (siteFiles.length === xmlFiles.length) {\n\t\treturn true;\n\t}\n}\n\n/**\n * Delete empty directories from the given directory in a recursive way.\n */\nasync function deleteEmptyDirectories(dirPath: string) {\n\ttry {\n\t\tconst stats = await fsp.stat(dirPath);\n\n\t\t// Si no es un directorio, no hacemos nada\n\t\tif (!stats.isDirectory()) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet filesInDirectory: string[];\n\t\ttry {\n\t\t\tfilesInDirectory = await fsp.readdir(dirPath);\n\t\t} catch (err: any) {\n\t\t\t// Si el directorio no existe o no se puede leer (ej. permisos), lo saltamos.\n\t\t\tif (err.code === \"ENOENT\") {\n\t\t\t\tGriddoLog.warn(`The directory \"${dirPath}\" does not exist, skipping it.`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tGriddoLog.error(`Error al leer el directorio \"${dirPath}\":`, err);\n\t\t\tthrow err; // Re-lanza el error para que sea manejado por el llamador\n\t\t}\n\n\t\t// Recorrer los contenidos del directorio\n\t\tfor (const file of filesInDirectory) {\n\t\t\tconst fullPath = path.join(dirPath, file);\n\t\t\tawait deleteEmptyDirectories(fullPath); // Llamada recursiva s\u00EDncrona\n\t\t}\n\n\t\t// Despu\u00E9s de procesar todos los subdirectorios, verifica si el directorio actual est\u00E1 vac\u00EDo\n\t\tconst remainingFiles = await fsp.readdir(dirPath);\n\n\t\tif (remainingFiles.length === 0) {\n\t\t\ttry {\n\t\t\t\tawait fsp.rmdir(dirPath);\n\t\t\t\tGriddoLog.verbose(`Remove empty directory: ${dirPath}`);\n\t\t\t} catch (err: any) {\n\t\t\t\t// Puede que haya habido un problema de concurrencia o permisos\n\t\t\t\tif (err.code === \"ENOENT\") {\n\t\t\t\t\tGriddoLog.warn(\n\t\t\t\t\t\t`El directorio \"${dirPath}\" ya no existe. Posiblemente fue borrado por otra operaci\u00F3n.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tGriddoLog.error(`Error al borrar el directorio \"${dirPath}\":`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (err: any) {\n\t\tif (err.code === \"ENOENT\") {\n\t\t\t// El directorio ya no existe, no es un error para nosotros en este contexto\n\t\t\tGriddoLog.warn(`The directory \"${dirPath}\" does not exist or has already been processed.`);\n\t\t} else {\n\t\t\tGriddoLog.error(`General error general while processing \"${dirPath}\":`, err);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\nasync function pathExists(dir: string) {\n\ttry {\n\t\tawait fsp.access(dir);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Busca recursivamente archivos que terminen con un sufijo espec\u00EDfico dentro de un directorio.\n * Esta funci\u00F3n es un generador as\u00EDncrono, lo que la hace muy eficiente en uso de memoria.\n *\n * @param dir El directorio base para comenzar la b\u00FAsqueda.\n * @param suffix El sufijo con el que deben terminar los nombres de archivo (ej: 'page-data.json').\n * @returns Un generador as\u00EDncrono que produce la ruta completa de cada archivo encontrado.\n * @throws Si el directorio inicial `dir` no existe o no se puede leer.\n */\nasync function* findFilesBySuffix(dir: string, suffix: string): AsyncGenerator<string> {\n\tconst dirHandle = await fsp.opendir(dir);\n\tfor await (const item of dirHandle) {\n\t\tconst fullPath = path.join(dir, item.name);\n\t\tif (item.isDirectory()) {\n\t\t\t// yield* para encadenar otro generator.\n\t\t\tyield* findFilesBySuffix(fullPath, suffix);\n\t\t} else if (item.isFile() && item.name.endsWith(suffix)) {\n\t\t\tyield fullPath;\n\t\t}\n\t}\n}\n\n/**\n * Walk a directory and returns the JSON file absolute paths with one level of depth.\n * /abs/.../sotre/331/158.json\n * /abs/.../sotre/114/443.json\n * /abs/.../sotre/131/217.json\n * /abs/.../sotre/191/281.json\n */\nasync function* walkStore(storeDir: string): AsyncGenerator<string> {\n\tconst storeDirHandle = await fsp.opendir(storeDir);\n\n\tfor await (const siteDirent of storeDirHandle) {\n\t\tif (siteDirent.isDirectory()) {\n\t\t\tconst siteDirPath = path.join(storeDir, siteDirent.name);\n\t\t\tconst siteDirHandle = await fsp.opendir(siteDirPath);\n\n\t\t\tfor await (const fileDirent of siteDirHandle) {\n\t\t\t\tconst filePath = path.join(siteDirPath, fileDirent.name);\n\n\t\t\t\tif (fileDirent.isFile() && path.extname(filePath) === \".json\") {\n\t\t\t\t\tyield filePath;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport {\n\tcpDirs,\n\tdeleteDisposableSiteDirs,\n\tdeleteEmptyDirectories,\n\tfindFilesBySuffix,\n\tmkDirs,\n\tmvDirs,\n\tpathExists,\n\trenamePath,\n\trmDirs,\n\twalkStore,\n};\n", "/**\n * Do you want to add a new error to the list?\n *\n * 1 - Add the new error type name to the `ErrorsType` union type.\n * 2 - Export a new ErrorData object (or a function that returns one) in this\n * file by completing the `error` (ErrosType) and `message` (string) properties\n * obligatorily.\n */\n\nimport type { SpawnSyncReturns } from \"node:child_process\";\nimport type { ErrorData } from \"../core/errors\";\n\ntype ErrorsType =\n\t| \"ArtifactError\"\n\t| \"BundlesInconsistencyError\"\n\t| \"CheckHealthError\"\n\t| \"ErrorInSSGBuildProcess\"\n\t| \"LifecycleExecutionError\"\n\t| \"LoginError\"\n\t| \"NoDomainsFoundError\"\n\t| \"NoJSConfigFileFound\"\n\t| \"ReadFromStoreError\"\n\t| \"ReferenceFieldSourcesNotFoundError\"\n\t| \"RenderUUIDError\"\n\t| \"UploadSearchError\"\n\t| \"WriteToStoreError\";\n\nconst ArtifactError: ErrorData = {\n\terror: \"ArtifactError\",\n\tmessage: \"There was a problem with an artifact\",\n\texpected:\n\t\t\"An external process may have has modified or deleted one of the artifacts (files and directories).\",\n\thint: \"Have there been any recent deployments? These can delete directories from the current render.\",\n};\n\nconst ErrorInSSGBuildProcess = (command: SpawnSyncReturns<string>): ErrorData => ({\n\terror: \"ErrorInSSGBuildProcess\",\n\tmessage: `Error in SSG build process: ${JSON.stringify(command)}`,\n\texpected: \"This can happen if there was a problem with the SSG build process.\",\n});\n\nconst LifecycleExecutionError = (attempts: number, name: string): ErrorData => ({\n\terror: \"LifecycleExecutionError\",\n\tmessage: `Exceeded maximum retry attempts (${attempts}) for ${name} LifeCycle`,\n});\n\nconst LoginError: ErrorData = {\n\terror: \"LoginError\",\n\tmessage: \"There was a problem logging in to the API\",\n\texpected: \"This happens if the API is currently not working or the credentials are incorrect.\",\n};\n\nconst NoDomainsFoundError: ErrorData = {\n\terror: \"NoDomainsFoundError\",\n\tmessage: \"No domains were found in this instance. The process cannot continue.\",\n\texpected:\n\t\t\"This may happen if the API is not functioning, or the site is not properly configured, or the domains are not registered.\",\n\thint: \"You can contact the instance administrator.\",\n};\n\nconst NoJSConfigFileFound: ErrorData = {\n\terror: \"NoJSConfigFileFound\",\n\tmessage: \"Could not find jsconfig.json or tsconfig.json\",\n\texpected:\n\t\t\"This can happen if the instance is not properly configured with a jsconfig.json or tsconfig.json file.\",\n};\n\nconst ReadFromStoreError: ErrorData = {\n\terror: \"ReadFromStoreError\",\n\tmessage: \"There was an error reading a file to the Store directory\",\n\thint: \"There may be an issue such as permissions preventing the file from being read.\",\n};\n\nconst ReferenceFieldSourcesNotFoundError: ErrorData = {\n\terror: \"ReferenceFieldSourcesNotFoundError\",\n\tmessage: \"The distributor has no sources defined.\",\n\texpected:\n\t\t\"It is expected to have at least one data source in the `sources` property, even if it is empty.\",\n};\n\nconst RenderUUIDError: ErrorData = {\n\terror: \"RenderUUIDError\",\n\tmessage: `Render sentinel file does not exist.\nThe rendering UUID cannot be read safely.\nThere was probably an instance deployment during the render, and files were deleted.\n\nThe files generated in this render will not be published.`,\n};\n\nconst WriteToStoreError: ErrorData = {\n\terror: \"WriteToStoreError\",\n\tmessage: \"There was an error writing a file to the Store directory\",\n\thint: \"There may be an issue such as lack of space or permissions preventing the file from being written.\",\n};\n\nconst UploadSearchError: ErrorData = {\n\terror: \"UploadSearchError\",\n\tmessage: \"There was an error uploading content to API for search\",\n\thint: \"This happens if the API is currently not working or the credentials are incorrect.\",\n};\n\nconst CheckHealthError: ErrorData = {\n\terror: \"CheckHealthError\",\n\tmessage: \"There was a problem with environment vars configuration.\",\n\texpected: \"Some of the required environment variables are not set correctly or are missing\",\n\thint: \"Are the environment variables correctly set?\",\n};\n\nexport {\n\tArtifactError,\n\tCheckHealthError,\n\tErrorInSSGBuildProcess,\n\tLifecycleExecutionError,\n\tLoginError,\n\tNoDomainsFoundError,\n\tNoJSConfigFileFound,\n\tReadFromStoreError,\n\tReferenceFieldSourcesNotFoundError,\n\tRenderUUIDError,\n\tUploadSearchError,\n\tWriteToStoreError,\n\ttype ErrorsType,\n};\n", "import type { RenderModeTuple } from \"../shared/types/render\";\n\nimport { execSync } from \"node:child_process\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { readDB, writeDB } from \"../core/db\";\nimport { throwError } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { RenderUUIDError } from \"../shared/errors\";\nimport { brush } from \"../shared/npm-modules/brush\";\nimport { RENDER_MODE } from \"../shared/types/render\";\nimport { AuthService } from \"./auth\";\nimport { getBuildMetadata } from \"./manage-store\";\n\n/**\n * Creates a sentinel file with the current date and time.\n * This file is used to track later if node_modules/@griddo/cx was cleaned by a\n * npm install coming from a deploy.\n */\nasync function markRenderAsStarted(options: { domain: string; basePath: string }) {\n\tconst { domain } = options;\n\n\tconst db = await readDB();\n\tdb.domains[domain].isRendering = true;\n\tawait writeDB(db);\n\n\t// Creamos un archivo centinela, si al terminar el render este archivo no\n\t// existe es que ha habido un deploy por medio y hay que invalidar el render\n\tconst { __ssg } = await getRenderPathsHydratedWithDomainFromDB();\n\n\tconst renderSentinelFile = path.join(__ssg, `.render-sentinel-${domain}`);\n\tawait fsp.writeFile(renderSentinelFile, new Date().toISOString());\n}\n\nasync function markRenderAsCompleted(domain: string) {\n\tconst db = await readDB();\n\tdb.domains[domain].isRendering = false;\n\tdb.currentRenderingDomain = null;\n\tdb.domains[domain].renderMode = RENDER_MODE.COMPLETED;\n\t// db.domains[domain].shouldBeRendered = false;\n\tawait writeDB(db);\n\n\t// Borramos finalmente el archivo centinela\n\tconst { __ssg } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst renderSentinelFile = path.join(__ssg, `.render-sentinel-${domain}`);\n\tawait fsp.unlink(renderSentinelFile);\n}\n\nasync function assertRenderIsValid(domain: string) {\n\t// Comprobamos que .render-sentinel exista, si no es que un deploy lo borro\n\t// y hay que invalidar el render.\n\tconst { __ssg } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst renderSentinelFile = path.join(__ssg, `.render-sentinel-${domain}`);\n\tif (!(await pathExists(renderSentinelFile))) {\n\t\tthrowError(RenderUUIDError);\n\t}\n}\n\n/**\n * Determines the appropriate render mode for a given domain based on its current state,\n * previous render errors, deployment status, and whether rendering is required.\n *\n * @param options - An object containing:\n * - `domain`: The domain name to resolve the render mode for.\n * - `shouldBeRendered`: A boolean indicating if the domain should be rendered.\n * @returns An object with:\n * - `renderMode`: The resolved render mode (`FROM_SCRATCH`, `INCREMENTAL`, or `IDLE`).\n * - `reason`: A string describing the reason for the chosen render mode.\n *\n * @remarks\n * The function checks for missing exports, previous render errors, new deployments,\n * and whether rendering is necessary to decide the render mode.\n *\n * @todo\n * Improve ifs and reason concatenations...\n */\nasync function resolveDomainRenderMode(options: { domain: string; shouldBeRendered: boolean }) {\n\tconst { domain, shouldBeRendered } = options;\n\n\tconst db = await readDB();\n\n\tconst { __cache, __exports } = await getRenderPathsHydratedWithDomainFromDB({ domain });\n\tconst exportsAreMissing = !(await pathExists(path.join(__exports)));\n\tconst previousRenderFailed = db.domains[domain]?.isRendering;\n\tconst newDeployDetected = await hasNewCommit(__cache);\n\n\tif (exportsAreMissing) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.FROM_SCRATCH,\n\t\t\treason: \"missing exports directory\",\n\t\t};\n\t}\n\n\tif (previousRenderFailed) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.FROM_SCRATCH,\n\t\t\treason: \"error in previous render\",\n\t\t};\n\t}\n\n\tif (newDeployDetected) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.FROM_SCRATCH,\n\t\t\treason: \"new commit hash\",\n\t\t};\n\t}\n\n\tif (!shouldBeRendered) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.IDLE,\n\t\t\treason: \"no activity\",\n\t\t};\n\t}\n\n\treturn {\n\t\trenderMode: RENDER_MODE.INCREMENTAL,\n\t\treason: \"has changes\",\n\t};\n}\n\nasync function hasNewCommit(basePath: string): Promise<boolean> {\n\tconst commitFile = path.join(basePath, \"commit\");\n\tconst currentCommit = execSync(\"git rev-parse HEAD\").toString().trim();\n\n\tif (await pathExists(commitFile)) {\n\t\tconst savedCommit = (await fsp.readFile(commitFile, \"utf-8\")).trim();\n\t\tif (savedCommit === currentCommit) {\n\t\t\treturn false; // No hay nuevo commit\n\t\t}\n\n\t\treturn true;\n\t}\n\n\treturn true;\n}\n\nasync function updateCommitFile(options: { basePath: string }) {\n\tconst { basePath } = options;\n\t// We use the commit saved at the beginning of the render, not the current\n\t// machine commit, thus avoiding problems if there is a deployment during\n\t// the render\n\tconst db = await readDB();\n\tconst currentCommit = db.commitHash;\n\tawait fsp.writeFile(path.join(basePath, \"commit\"), currentCommit);\n}\n\nasync function getRenderModeFromDB(domain: string): Promise<RenderModeTuple> {\n\tconst db = await readDB();\n\n\tif (!db.domains[domain]) {\n\t\tthrow new Error(brush.red(`[!] Error: Domain ${domain} not found in DB`));\n\t}\n\n\tif (!db.domains[domain].renderMode) {\n\t\tthrow new Error(brush.red(`[!] Error: Render mode not found for domain ${domain}`));\n\t}\n\n\treturn {\n\t\trenderMode: db.domains[domain].renderMode,\n\t\treason: db.domains[domain].renderModeReason,\n\t};\n}\n\nasync function getRenderPathsHydratedWithDomainFromDB(options?: {\n\tdomain?: string;\n\tdbFilePath?: string;\n}) {\n\tconst { domain, dbFilePath } = options || {};\n\n\tconst db = await readDB(dbFilePath);\n\tconst paths = db.paths;\n\n\treturn {\n\t\t__root: paths.root,\n\t\t__cache: path.join(paths.cxCache, domain || \"\"),\n\t\t__components: paths.components,\n\t\t__cx: paths.cx,\n\t\t__sites: paths.exportsDir,\n\t\t__exports: path.join(paths.exportsDir, domain || \"\"),\n\t\t__exports_backup: path.join(paths.exportsDirBackup, domain || \"\"),\n\t\t__ssg: paths.ssg,\n\t\t__exports_dist: path.join(paths.exportsDir, domain || \"\", \"dist\"),\n\t};\n}\n\nasync function getRenderMetadataFromDB() {\n\tconst db = await readDB();\n\treturn {\n\t\tgriddoVersion: db.griddoVersion,\n\t\tbuildReportFileName: db.buildReportFileName,\n\t};\n}\n\n/**\n * Save a file with the end of build process to use as `end-render` signal.\n */\nasync function generateBuildReport(domain: string) {\n\tconst authControl = await AuthService.login();\n\n\tconst { __root } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst { buildReportFileName } = await getRenderMetadataFromDB();\n\tconst { buildProcessData } = await getBuildMetadata(domain);\n\n\tconst buildSitesInfo = Object.keys(buildProcessData).map((siteID) => ({\n\t\t...buildProcessData[siteID],\n\t\tsiteId: Number.parseInt(siteID),\n\t}));\n\n\tconst report = {\n\t\tauthControl,\n\t\tsites: buildSitesInfo,\n\t};\n\n\tconst reportFilePath = path.join(__root, \"current-dist\", buildReportFileName);\n\n\tawait fsp.writeFile(reportFilePath, JSON.stringify(report));\n\n\tGriddoLog.verbose(`build report saved in ${reportFilePath}`);\n}\n\nexport {\n\tassertRenderIsValid,\n\tgenerateBuildReport,\n\tgetRenderMetadataFromDB,\n\tgetRenderModeFromDB,\n\tgetRenderPathsHydratedWithDomainFromDB,\n\tmarkRenderAsCompleted,\n\tmarkRenderAsStarted,\n\tresolveDomainRenderMode,\n\tupdateCommitFile,\n};\n", "const GRIDDO_API_URL = process.env.GRIDDO_API_URL;\nconst GRIDDO_PUBLIC_API_URL = process.env.GRIDDO_PUBLIC_API_URL;\n\nconst AI_EMBEDDINGS = `${GRIDDO_API_URL}/ai/embeddings`;\nconst ALERT = `${GRIDDO_PUBLIC_API_URL}/alert`;\nconst DOMAINS = `${GRIDDO_API_URL}/domains`;\nconst GET_ALL = `${GRIDDO_API_URL}/sites/all`;\nconst GET_PAGE = `${GRIDDO_API_URL}/page`;\nconst LOGIN = `${GRIDDO_API_URL}/login_check`;\nconst RESET_RENDER = `${GRIDDO_API_URL}/debug/reset-render`;\nconst ROBOTS = `${GRIDDO_API_URL}/domains/robots`;\nconst SEARCH = `${GRIDDO_API_URL}/search`;\nconst SETTINGS = `${GRIDDO_API_URL}/settings`;\n\n// Domain\nconst DOMAIN_URI = `${GRIDDO_API_URL}/domains/`;\nconst LLMS = [DOMAIN_URI, \"/llms\"];\n\n// Site\nconst SITE_URI = `${GRIDDO_API_URL}/site/`;\nconst BUILD_END = [SITE_URI, \"/build/end\"];\nconst BUILD_START = [SITE_URI, \"/build/start\"];\nconst GET_REFERENCE_FIELD_DATA = [SITE_URI, \"/distributor\"];\nconst GET_SITEMAP = [SITE_URI, \"/sitemap\"];\nconst INFO = [SITE_URI, \"/all\"];\nconst LANGUAGES = [SITE_URI, \"/languages\"];\nconst SOCIALS = [SITE_URI, \"/socials\"];\n\nexport {\n\tAI_EMBEDDINGS,\n\tALERT,\n\tBUILD_END,\n\tBUILD_START,\n\tDOMAINS,\n\tGET_ALL,\n\tGET_PAGE,\n\tGET_REFERENCE_FIELD_DATA,\n\tGET_SITEMAP,\n\tINFO,\n\tLANGUAGES,\n\tLLMS,\n\tLOGIN,\n\tRESET_RENDER,\n\tROBOTS,\n\tSEARCH,\n\tSETTINGS,\n\tSOCIALS,\n};\n", "{\n\t\"name\": \"@griddo/cx\",\n\t\"description\": \"Griddo SSG based on Gatsby\",\n\t\"version\": \"11.10.20\",\n\t\"authors\": [\n\t\t\"Hisco <francis.vega@griddo.io>\"\n\t],\n\t\"license\": \"UNLICENSED\",\n\t\"homepage\": \"https://griddo.io\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/griddo/griddo\"\n\t},\n\t\"bin\": {\n\t\t\"griddo-render\": \"cli.mjs\"\n\t},\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"import\": \"./build/index.js\",\n\t\t\t\"require\": \"./build/index.js\",\n\t\t\t\"types\": \"./build/index.d.ts\"\n\t\t},\n\t\t\"./react\": {\n\t\t\t\"import\": \"./build/react/index.js\",\n\t\t\t\"require\": \"./build/react/index.js\",\n\t\t\t\"types\": \"./build/react/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"// NPM\": \"\",\n\t\t\"prepare\": \"yarn run build\",\n\t\t\"// BUILD\": \"\",\n\t\t\"build\": \"rm -rf build && sh ./exporter/build.sh\",\n\t\t\"build:debug\": \"rm -rf build && sh ./exporter/build.sh --debug\",\n\t\t\"// TESTS\": \"\",\n\t\t\"test\": \"npm run test:compile && npm run test:create-render-fixtures && node --env-file=.env --test ./build/__tests__/* && npm run test:remove-render-fixtures\",\n\t\t\"test-exporter\": \"npm run test:compile && node --env-file=.env --test ./build/__tests__exporter__/\",\n\t\t\"test:create-render-fixtures\": \"node --env-file=.env ./build/__tests__/utils/create-fixtures\",\n\t\t\"test:remove-render-fixtures\": \"node --env-file=.env ./build/__tests__/utils/remove-fixtures\",\n\t\t\"test:compile\": \"tsgo --project tsconfig.tests.json\",\n\t\t\"// INFRA SCRIPTS\": \"\",\n\t\t\"prepare-domains-render\": \"node ./build/commands/prepare-domains-render\",\n\t\t\"start-render\": \"node ./build/commands/start-render\",\n\t\t\"end-render\": \"node ./build/commands/end-render\",\n\t\t\"upload-search-content\": \"node ./build/commands/upload-search-content\",\n\t\t\"reset-render\": \"node ./build/commands/reset-render\",\n\t\t\"// ONLY LOCAL SCRIPTS\": \"\",\n\t\t\"prepare-assets-directory\": \"node ./build/commands/prepare-assets-directory\",\n\t\t\"create-rollback-copy\": \"rm -rf ../../exports-backup && cp -r ../../exports ../../exports-backup\",\n\t\t\"render\": \"npm run build && node --env-file=.env cli.mjs render --root=../..\",\n\t\t\"// LINTER & FORMATTER\": \"\",\n\t\t\"lint\": \"biome check --write\",\n\t\t\"format\": \"biome format --write\",\n\t\t\"flint\": \"npm run lint && npm run format\",\n\t\t\"ts-lint\": \"tsgo --noEmit\",\n\t\t\"watch:ts-lint\": \"tsc --noEmit --watch\"\n\t},\n\t\"dependencies\": {\n\t\t\"gatsby\": \"5.15.0\",\n\t\t\"html-react-parser\": \"^5.2.10\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@biomejs/biome\": \"2.3.4\",\n\t\t\"@types/node\": \"20.19.4\",\n\t\t\"@typescript/native-preview\": \"latest\",\n\t\t\"cheerio\": \"1.1.2\",\n\t\t\"esbuild\": \"0.25.12\",\n\t\t\"p-limit\": \"7.2.0\",\n\t\t\"typescript\": \"5.9.3\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"@griddo/core\": \"11.9.16\",\n\t\t\"react\": \">=18 <19\",\n\t\t\"react-dom\": \">=18 <19\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=20.19\"\n\t},\n\t\"files\": [\n\t\t\"build\",\n\t\t\"exporter\",\n\t\t\"src\",\n\t\t\"gatsby-browser.tsx\",\n\t\t\"gatsby-config.ts\",\n\t\t\"gatsby-node.ts\",\n\t\t\"gatsby-ssr.tsx\",\n\t\t\"global.d.ts\",\n\t\t\"tsconfig.commands.json\",\n\t\t\"tsconfig.exporter.json\",\n\t\t\"tsconfig.json\",\n\t\t\"plugins\",\n\t\t\"cli.mjs\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"gitHead\": \"cc4cb47324099928259991fc63e6a516679c83db\"\n}\n", "import packageJson from \"../../package.json\";\n\nexport const DEFAULT_HEADERS = {\n\t\"x-application-id\": \"griddo-cx\",\n\t\"x-client-version\": packageJson.version,\n\t\"x-client-name\": \"CX\",\n} as const;\n", "import type { AuthHeaders } from \"../shared/types/api\";\n\nimport { throwError } from \"../core/errors\";\nimport { LOGIN } from \"../shared/endpoints\";\nimport { GRIDDO_BOT_PASSWORD, GRIDDO_BOT_USER } from \"../shared/envs\";\nimport { LoginError } from \"../shared/errors\";\nimport { DEFAULT_HEADERS } from \"../shared/headers\";\n\nclass AuthService {\n\theaders: AuthHeaders | undefined;\n\n\tasync login() {\n\t\ttry {\n\t\t\tconst response = await fetch(LOGIN, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: Object.assign({}, DEFAULT_HEADERS, {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tConnection: \"close\",\n\t\t\t\t}),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tusername: GRIDDO_BOT_USER,\n\t\t\t\t\tpassword: GRIDDO_BOT_PASSWORD,\n\t\t\t\t}),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(\"Error while login in the API\");\n\t\t\t}\n\n\t\t\tconst { token } = await response.json();\n\t\t\tthis.headers = {\n\t\t\t\tAuthorization: `bearer ${token}`,\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t};\n\n\t\t\treturn this.headers;\n\t\t} catch (e) {\n\t\t\tthrowError(LoginError, e);\n\t\t}\n\t}\n}\n\nconst authService = new AuthService();\n\nexport { authService as AuthService };\n"],
4
+ "sourcesContent": ["import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { withErrorHandler } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { getRenderModeFromDB, getRenderPathsHydratedWithDomainFromDB } from \"../services/render\";\nimport { RENDER_MODE } from \"../shared/types/render\";\n\nasync function prepareAssetsDir() {\n\tconst [domain] = process.argv.slice(2);\n\n\tconst { renderMode } = await getRenderModeFromDB(domain);\n\n\tif (renderMode === RENDER_MODE.IDLE) {\n\t\treturn;\n\t}\n\n\tconst { __exports } = await getRenderPathsHydratedWithDomainFromDB({ domain });\n\tconst assetsDir = path.join(__exports, \"assets\");\n\tconst domainAssetsDir = path.join(__exports, domain);\n\n\tif (await pathExists(assetsDir)) {\n\t\tawait fsp.rm(domainAssetsDir, { force: true, recursive: true });\n\t\tawait fsp.rename(assetsDir, domainAssetsDir);\n\t} else {\n\t\tGriddoLog.warn(\"Assets directory not found\");\n\t}\n}\n\nasync function main() {\n\tawait prepareAssetsDir();\n}\n\nwithErrorHandler(main);\n", "import type { ErrorsType } from \"../shared/errors\";\n\nimport path from \"node:path\";\n\nimport { brush } from \"../shared/npm-modules/brush\";\nimport { RENDER_MODE } from \"../shared/types/render\";\nimport { readDB, writeDB } from \"./db\";\nimport { distRollback } from \"./dist-rollback\";\nimport { GriddoLog } from \"./GriddoLog\";\n\nexport type ErrorData = {\n\terror: ErrorsType;\n\tmessage: string;\n\texpected?: string;\n\thint?: string;\n};\n\nexport class RenderError extends Error {\n\tconstructor(originalError?: unknown) {\n\t\tsuper(originalError instanceof Error ? originalError.message : String(originalError));\n\n\t\tthis.name = \"InternalCXError\";\n\t\tthis.stack = originalError instanceof Error ? originalError.stack : \"\";\n\t}\n}\n\n/**\n * Throws an error with the provided error message, expected value, and hint.\n */\nfunction throwError(options: ErrorData, stack?: unknown): never {\n\tconst { error, message, expected, hint } = options;\n\n\tconst errorColor = GriddoLog.log(brush.red(`[ ${error} ]`));\n\tconst extraText = [expected, hint].filter(Boolean).join(\"\\n\");\n\n\tGriddoLog.log(`\n${errorColor}\n${message}\n${extraText}\n\n${brush.red(\"stack\")}\n${JSON.stringify(stack, null, 2)}`);\n\n\tthrow new RenderError(stack);\n}\n\n/**\n * Executes the provided asynchronous function and handles errors that occur during execution.\n *\n * - If an error is thrown, attempts to log the error and, if necessary, rolls back the exports directory.\n * - Updates the render database to set the domain's rendering state to \"ERROR\" if an error occurs.\n *\n * @param fn - The asynchronous function to execute within the error handler.\n * @returns A promise that resolves when the function is executed successfully.\n * @throws RenderError | unknown - Rethrows the original error after handling and database state update.\n */\nasync function withErrorHandler(fn: () => Promise<void>) {\n\ttry {\n\t\tawait fn();\n\t} catch (error) {\n\t\tif (error instanceof RenderError) {\n\t\t\tGriddoLog.error(\"Internal Griddo RenderError\");\n\t\t} else if (error instanceof Error) {\n\t\t\tGriddoLog.error(error.message);\n\t\t} else {\n\t\t\tGriddoLog.error(`An unexpected error occurred ${error}`);\n\t\t}\n\n\t\t// Try to rollback the exports directory if needed\n\t\ttry {\n\t\t\tconst data = await readDB();\n\t\t\tconst { root } = data.paths;\n\t\t\tif (data.needsRollbackOnError) {\n\t\t\t\tGriddoLog.info(\"Cleaning exports dir...\");\n\t\t\t\tGriddoLog.verbose(`Deleting ${path.join(root, \"exports\")}...`);\n\n\t\t\t\tawait distRollback(data.currentRenderingDomain!);\n\t\t\t} else {\n\t\t\t\tGriddoLog.info(\"No rollback needed, skipping...\");\n\t\t\t}\n\t\t} catch (_e) {\n\t\t\tGriddoLog.info(\"Early render stage, no db.json created yet...\");\n\t\t}\n\n\t\tconst data = await readDB();\n\t\tdata.domains[data.currentRenderingDomain!].isRendering = false;\n\t\tdata.domains[data.currentRenderingDomain!].renderMode = RENDER_MODE.ERROR;\n\t\tawait writeDB(data);\n\t\tthrow error;\n\t}\n}\n\nexport { throwError, withErrorHandler };\n", "//\n// Brush adds color to a string|number, it does not print it!\n// Its simple, no log, no chains, just color in a string|number\n// usage:\n// console.log(brush.green(\"sucess!\"))\n//\n\nconst RESET = \"\\x1b[0m\";\nconst CODES = {\n\tblack: \"\\x1b[30m\",\n\tred: \"\\x1b[31m\",\n\tgreen: \"\\x1b[32m\",\n\tyellow: \"\\x1b[33m\",\n\tblue: \"\\x1b[34m\",\n\tmagenta: \"\\x1b[35m\",\n\tcyan: \"\\x1b[36m\",\n\twhite: \"\\x1b[37m\",\n\tgray: \"\\x1b[90m\",\n\tbold: \"\\x1b[1m\",\n\tdim: \"\\x1b[2m\",\n} as const;\n\ntype ColorFunction = (text: string | number) => string;\ntype ColorName = keyof typeof CODES;\ntype Brush = Record<ColorName, ColorFunction>;\n\nconst brush = {} as Brush;\n\nfor (const color in CODES) {\n\tconst key = color as ColorName;\n\tbrush[key] = (text: string | number) => `${CODES[key]}${text}${RESET}`;\n}\n\nexport { brush };\n", "import type { RenderInfo } from \"./global\";\n\nconst RENDER_MODE = {\n\tFROM_SCRATCH: \"FROM_SCRATCH\",\n\tINCREMENTAL: \"INCREMENTAL\",\n\tIDLE: \"IDLE\",\n\tERROR: \"ERROR\",\n\tCOMPLETED: \"COMPLETED\",\n} as const;\n\ntype RenderMode = (typeof RENDER_MODE)[keyof typeof RENDER_MODE];\n\nexport interface RenderModeTuple {\n\trenderMode: RenderMode;\n\treason?: string;\n}\n\ntype DomainLike = string;\n\ntype RenderDB = {\n\tgriddoVersion: string;\n\tbuildReportFileName: string;\n\tsortedDomains: DomainLike[];\n\tneedsRollbackOnError: boolean;\n\tcurrentRenderingDomain: string | null;\n\tcommitHash: string;\n\tcommitMessage: string;\n\tpaths: {\n\t\troot: string;\n\t\tcx: string;\n\t\tssg: string;\n\t\tcxCache: string;\n\t\tcomponents: string;\n\t\texportsDir: string;\n\t\texportsDirBackup: string;\n\t};\n\tdomains: {\n\t\t[key: DomainLike]: {\n\t\t\tid?: number;\n\t\t\trenderMode?: RenderMode;\n\t\t\tshouldBeRendered?: boolean;\n\t\t\tisRendering?: boolean;\n\t\t\trenderInfo?: RenderInfo;\n\t\t\trenderModeReason?: string;\n\t\t};\n\t};\n};\n\ninterface Report {\n\tauthControl:\n\t\t| {\n\t\t\t\tAuthorization: string;\n\t\t\t\t\"Cache-Control\": string;\n\t\t\t\tlang?: string | undefined;\n\t\t }\n\t\t| undefined;\n\tsites: {\n\t\tsiteId: number;\n\t\tpublishHashes: string[];\n\t\tsiteHash: string | null;\n\t\tunpublishHashes: string[];\n\t\tpublishPagesIds: number[];\n\t}[];\n}\n\nexport { RENDER_MODE, type RenderDB, type RenderMode, type Report };\n", "import type { RenderDB } from \"../shared/types/render\";\n\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { pkgDirSync } from \"../shared/npm-modules/pkg-dir\";\nimport { GriddoLog } from \"./GriddoLog\";\n\nconst root = pkgDirSync({ cwd: path.resolve(__dirname, \"../../..\") }) || \"\";\nconst cache = path.join(root, \".griddo/cache\");\nconst dbFilePath = path.join(cache, \"db.json\");\n\nasync function readDB(customDBPath = \"\") {\n\tconst file = customDBPath || dbFilePath;\n\ttry {\n\t\treturn JSON.parse(await fsp.readFile(file, \"utf-8\")) as RenderDB;\n\t} catch (error) {\n\t\tGriddoLog.error(`Failed to read DB file at ${file}:`, error);\n\t\tthrow error;\n\t}\n}\n\nasync function writeDB(renderDB: RenderDB, customDBPath = \"\") {\n\tconst file = customDBPath || dbFilePath;\n\ttry {\n\t\tawait fsp.writeFile(file, JSON.stringify(renderDB, null, \"\\t\"));\n\t} catch (error) {\n\t\tGriddoLog.error(`Failed to write DB file at ${file}:`, error);\n\t\tthrow error;\n\t}\n}\n\nexport { readDB, writeDB };\n", "import path from \"node:path\";\n\nimport { findUp, findUpSync } from \"./find-up-simple\";\n\nasync function pkgDir(options?: { readonly cwd?: string }) {\n\tconst { cwd } = options || {};\n\tconst filePath = await findUp(\"package.json\", { cwd });\n\treturn filePath && path.dirname(filePath);\n}\n\nfunction pkgDirSync(options?: { readonly cwd?: string }) {\n\tconst { cwd } = options || {};\n\tconst filePath = findUpSync(\"package.json\", { cwd });\n\treturn filePath && path.dirname(filePath);\n}\n\nexport { pkgDir, pkgDirSync };\n", "import fs from \"node:fs\";\nimport fsPromises from \"node:fs/promises\";\nimport path from \"node:path\";\nimport process from \"node:process\";\nimport { fileURLToPath } from \"node:url\";\n\n/**\n * Opciones para controlar el comportamiento de la b\u00FAsqueda.\n */\nexport type Options = {\n\t/**\n\tEl directorio desde donde empezar a buscar.\n\t@default process.cwd()\n\t*/\n\treadonly cwd?: URL | string;\n\n\t/**\n\tEl tipo de ruta a buscar.\n\t@default 'file'\n\t*/\n\treadonly type?: \"file\" | \"directory\";\n\n\t/**\n\tUn directorio en el que la b\u00FAsqueda se detiene si no se encuentran coincidencias.\n\t@default El directorio ra\u00EDz del sistema\n\t*/\n\treadonly stopAt?: URL | string;\n};\n\n// Funci\u00F3n auxiliar para convertir una URL en una ruta de archivo de tipo string.\nconst toPath = (urlOrPath: URL | string | undefined): string | undefined =>\n\turlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;\n\n/**\n * Encuentra un archivo o directorio de forma as\u00EDncrona subiendo por los directorios padre.\n * @param name - El nombre del archivo o directorio a buscar.\n * @param options - Opciones de b\u00FAsqueda.\n * @returns La ruta encontrada o `undefined` si no se pudo encontrar.\n */\nexport async function findUp(name: string, options: Options = {}): Promise<string | undefined> {\n\tconst { cwd = process.cwd(), type = \"file\", stopAt: stopAtOption } = options;\n\n\tlet directory = path.resolve(toPath(cwd) ?? \"\");\n\tconst { root } = path.parse(directory);\n\tconst stopAt = stopAtOption ? path.resolve(directory, toPath(stopAtOption)!) : root;\n\tconst isAbsoluteName = path.isAbsolute(name);\n\n\twhile (true) {\n\t\tconst filePath = isAbsoluteName ? name : path.join(directory, name);\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-await-in-loop\n\t\t\tconst stats = await fsPromises.stat(filePath);\n\t\t\tif ((type === \"file\" && stats.isFile()) || (type === \"directory\" && stats.isDirectory())) {\n\t\t\t\treturn filePath;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignora errores (ej. el archivo no existe) y contin\u00FAa la b\u00FAsqueda.\n\t\t}\n\n\t\tif (directory === stopAt || directory === root) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n}\n\n/**\n * Encuentra un archivo o directorio de forma s\u00EDncrona subiendo por los directorios padre.\n * @param name - El nombre del archivo o directorio a buscar.\n * @param options - Opciones de b\u00FAsqueda.\n * @returns La ruta encontrada o `undefined` si no se pudo encontrar.\n */\nexport function findUpSync(name: string, options: Options = {}): string | undefined {\n\tconst { cwd = process.cwd(), type = \"file\", stopAt: stopAtOption } = options;\n\n\tlet directory = path.resolve(toPath(cwd) ?? \"\");\n\tconst { root } = path.parse(directory);\n\tconst stopAt = stopAtOption ? path.resolve(directory, toPath(stopAtOption)!) : root;\n\tconst isAbsoluteName = path.isAbsolute(name);\n\n\twhile (true) {\n\t\tconst filePath = isAbsoluteName ? name : path.join(directory, name);\n\t\ttry {\n\t\t\tconst stats = fs.statSync(filePath, { throwIfNoEntry: false });\n\t\t\tif ((type === \"file\" && stats?.isFile()) || (type === \"directory\" && stats?.isDirectory())) {\n\t\t\t\treturn filePath;\n\t\t\t}\n\t\t} catch {\n\t\t\t// En teor\u00EDa, statSync con `throwIfNoEntry: false` no deber\u00EDa lanzar un error,\n\t\t\t// pero se mantiene por seguridad.\n\t\t}\n\n\t\tif (directory === stopAt || directory === root) {\n\t\t\tbreak;\n\t\t}\n\n\t\tdirectory = path.dirname(directory);\n\t}\n}\n", "const { env } = process;\n\n/**\n * Returns true/false from string\n */\nfunction envIsTruthy(value?: string): boolean {\n\tif (!value) return false;\n\n\tswitch (value.trim().toLowerCase()) {\n\t\tcase \"1\":\n\t\tcase \"true\":\n\t\tcase \"yes\":\n\t\tcase \"y\":\n\t\tcase \"on\":\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n// Credentials\nconst GRIDDO_API_URL = env.GRIDDO_API_URL || env.API_URL;\nconst GRIDDO_PUBLIC_API_URL = env.GRIDDO_PUBLIC_API_URL || env.PUBLIC_API_URL;\nconst GRIDDO_BOT_USER = env.botEmail || env.GRIDDO_BOT_USER;\nconst GRIDDO_BOT_PASSWORD = env.botPassword || env.GRIDDO_BOT_PASSWORD;\n\n// Rendering\nconst GRIDDO_API_CONCURRENCY_COUNT = Number.parseInt(env.GRIDDO_API_CONCURRENCY_COUNT || \"10\");\nconst GRIDDO_SKIP_BUILD_CHECKS = envIsTruthy(env.GRIDDO_SKIP_BUILD_CHECKS);\nconst GRIDDO_BUILD_LOGS = envIsTruthy(env.GRIDDO_BUILD_LOGS);\nconst GRIDDO_BUILD_LOGS_BUFFER_SIZE = Number.parseInt(env.GRIDDO_BUILD_LOGS_BUFFER_SIZE || \"500\");\nconst GRIDDO_SSG_VERBOSE_LOGS = envIsTruthy(env.GRIDDO_SSG_VERBOSE_LOGS);\nconst GRIDDO_SEARCH_FEATURE = envIsTruthy(env.GRIDDO_SEARCH_FEATURE);\nconst GRIDDO_ASSET_PREFIX = env.GRIDDO_ASSET_PREFIX || env.ASSET_PREFIX;\nconst GRIDDO_REACT_APP_INSTANCE = env.GRIDDO_REACT_APP_INSTANCE || env.REACT_APP_INSTANCE;\nconst GRIDDO_AI_EMBEDDINGS = envIsTruthy(env.GRIDDO_AI_EMBEDDINGS);\nconst GRIDDO_VERBOSE_LOGS = envIsTruthy(env.GRIDDO_VERBOSE_LOGS);\nconst GRIDDO_USE_DIST_BACKUP = envIsTruthy(env.GRIDDO_USE_DIST_BACKUP);\nconst GRIDDO_SSG_BUNDLE_ANALYZER = envIsTruthy(env.GRIDDO_SSG_BUNDLE_ANALYZER);\nconst GRIDDO_RENDER_DISABLE_LLMS_TXT = envIsTruthy(env.GRIDDO_RENDER_DISABLE_LLMS_TXT);\n\nexport {\n\tGRIDDO_AI_EMBEDDINGS,\n\tGRIDDO_API_CONCURRENCY_COUNT,\n\tGRIDDO_API_URL,\n\tGRIDDO_ASSET_PREFIX,\n\tGRIDDO_BOT_PASSWORD,\n\tGRIDDO_BOT_USER,\n\tGRIDDO_BUILD_LOGS,\n\tGRIDDO_BUILD_LOGS_BUFFER_SIZE,\n\tGRIDDO_PUBLIC_API_URL,\n\tGRIDDO_REACT_APP_INSTANCE,\n\tGRIDDO_RENDER_DISABLE_LLMS_TXT,\n\tGRIDDO_SEARCH_FEATURE,\n\tGRIDDO_SKIP_BUILD_CHECKS,\n\tGRIDDO_SSG_BUNDLE_ANALYZER,\n\tGRIDDO_SSG_VERBOSE_LOGS,\n\tGRIDDO_USE_DIST_BACKUP,\n\tGRIDDO_VERBOSE_LOGS,\n};\n", "import { GRIDDO_BUILD_LOGS, GRIDDO_VERBOSE_LOGS } from \"../shared/envs\";\nimport { brush } from \"../shared/npm-modules/brush\";\n\n/**\n * Clase est\u00E1tica para gestionar los logs de la aplicaci\u00F3n.\n * No se puede instanciar, se usa directamente: GriddoLogs.info(\"mensaje\").\n */\nclass GriddoLog {\n\t/** El constructor es privado para prevenir la instanciaci\u00F3n de la clase. */\n\tprivate constructor() {}\n\n\tpublic static verbose(...str: unknown[]): void {\n\t\tif (GRIDDO_VERBOSE_LOGS) {\n\t\t\tconsole.log(brush.yellow(\"verbose\"), brush.dim(str.join(\" \")));\n\t\t}\n\t}\n\n\tpublic static build(...str: unknown[]): void {\n\t\tif (GRIDDO_BUILD_LOGS) {\n\t\t\tGriddoLog.log(...str);\n\t\t}\n\t}\n\n\tpublic static info(...str: unknown[]): void {\n\t\tconsole.log(`${brush.blue(\"info\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static success(...str: unknown[]): void {\n\t\tconsole.log(`${brush.green(\"success\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static error(...str: unknown[]): void {\n\t\tconsole.error(`${brush.red(\"error\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static warn(...str: unknown[]): void {\n\t\tconsole.warn(`${brush.yellow(\"warn\")} ${str.join(\" \")}`);\n\t}\n\n\tpublic static log(...args: Parameters<typeof console.log>): void {\n\t\tconsole.log(...args);\n\t}\n}\n\nexport { GriddoLog };\n", "import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { readDB } from \"./db\";\nimport { pathExists } from \"./fs\";\nimport { GriddoLog } from \"./GriddoLog\";\n\n/**\n * Rolls back the exports directory for the given domain.\n *\n * - Deletes the potentially corrupt exports directory for the domain.\n * - If a backup exists, it restores the directory from the backup location.\n * - If no backup is found, it informs that a fresh exports directory will be created on the next render.\n *\n * @param domain The domain for which to rollback the exports directory.\n */\nasync function distRollback(domain: string): Promise<void> {\n\tconst data = await readDB();\n\tconst { exportsDir, exportsDirBackup } = data.paths;\n\n\tGriddoLog.info(`Cleaning exports dir for the domain ${domain}`);\n\tGriddoLog.verbose(`Deleting ${path.join(exportsDir, domain)}...`);\n\n\t// TODO: Probar rsync en lugar de borrar y copiar\n\n\t// 1 - Borrar dist corrupto\n\tawait fsp.rm(path.join(exportsDir, domain), {\n\t\trecursive: true,\n\t\tforce: true,\n\t});\n\n\t// 2 - Si hay backup, restaurar\n\tif (await pathExists(path.join(exportsDirBackup, domain))) {\n\t\tawait fsp.cp(path.join(exportsDirBackup, domain), path.join(exportsDir, domain), {\n\t\t\trecursive: true,\n\t\t});\n\n\t\tGriddoLog.info(`export-backup dir for the domain ${domain} found. Restoring before exit...`);\n\t\tGriddoLog.verbose(\n\t\t\t`Copying ${path.join(exportsDirBackup, domain)} -> ${path.join(exportsDir, domain)}...`,\n\t\t);\n\t} else {\n\t\tGriddoLog.info(\n\t\t\t\"No export-backup found, skipping rollback. Next render will create a new exports dir from scratch...\",\n\t\t);\n\t}\n}\n\nexport { distRollback };\n", "import type { MakeDirectoryOptions } from \"node:fs\";\n\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { ArtifactError } from \"../shared/errors\";\nimport { throwError } from \"./errors\";\nimport { GriddoLog } from \"./GriddoLog\";\n\n/**\n * Remove an empty directory from the basePath recursively.\n * If the directory has only .xml files it will handle as empty too (empty site)\n *\n * @param baseDir - The base directory.\n */\nasync function deleteDisposableSiteDirs(baseDir: string) {\n\tif (!(await pathExists(baseDir))) {\n\t\treturn;\n\t}\n\n\tconst sitesDirs = (await fsp.readdir(baseDir, { withFileTypes: true })).filter((file) =>\n\t\tfile.isDirectory(),\n\t);\n\n\tfor (const siteDir of sitesDirs) {\n\t\tconst sitePath = path.join(baseDir, siteDir.name);\n\t\tif (await siteIsEmpty(sitePath)) {\n\t\t\tawait fsp.rm(sitePath, { recursive: true });\n\t\t}\n\t}\n}\n\n/**\n * Creates multiple artifact directories.\n *\n * @param dirs - An array of directory paths.\n * @param options - Same option as `fs.mkdirSync()`\n */\nasync function mkDirs(dirs: string[], options?: MakeDirectoryOptions) {\n\tfor (const dir of dirs) {\n\t\ttry {\n\t\t\tif (!(await pathExists(dir))) {\n\t\t\t\tawait fsp.mkdir(dir, { recursive: true, ...options });\n\t\t\t\tGriddoLog.verbose(`create directory: ${dir}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\nasync function renamePath(src: string, dst: string) {\n\ttry {\n\t\tif (await pathExists(src)) {\n\t\t\tawait fsp.rename(src, dst);\n\t\t\tGriddoLog.verbose(`rename ${src} to ${dst}`);\n\t\t}\n\t} catch (error) {\n\t\tthrowError(ArtifactError, error);\n\t}\n}\n\n/**\n * Copy multiple directories with backup option.\n *\n * @param src - Source directory.\n * @param dst - Destination directory.\n * @param dirs - Directories to copy.\n * @param options.withBackup - Create a previous backup before copy.\n */\nasync function cpDirs(\n\tsrc: string,\n\tdst: string,\n\tdirs: string[],\n\toptions = {\n\t\twithBackup: false,\n\t},\n) {\n\tconst { withBackup } = options;\n\tfor (const dir of dirs) {\n\t\tconst srcCompose = path.join(src, dir);\n\t\tconst dstCompose = path.join(dst, dir);\n\n\t\t// The dir we want to copy, doesn't exist.\n\t\tif (!(await pathExists(srcCompose))) {\n\t\t\tGriddoLog.info(`(Maybe first render) Source directory does not exist: ${srcCompose}`);\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Create the backup\n\t\tif (withBackup) {\n\t\t\tawait createBackup(dstCompose);\n\t\t\tGriddoLog.verbose(`create backup: ${dstCompose}`);\n\t\t}\n\n\t\t// Copy directory\n\t\ttry {\n\t\t\t// First clean destination\n\t\t\tif (await pathExists(dstCompose)) {\n\t\t\t\tawait fsp.rm(dstCompose, { recursive: true, force: true });\n\t\t\t\tGriddoLog.verbose(`clean destination: ${dstCompose}`);\n\t\t\t}\n\n\t\t\t// Then copy src to dst\n\t\t\tawait fsp.cp(srcCompose, dstCompose, {\n\t\t\t\trecursive: true,\n\t\t\t\tpreserveTimestamps: true,\n\t\t\t});\n\t\t\tGriddoLog.verbose(`copy: ${srcCompose} to ${dstCompose}`);\n\n\t\t\tif (withBackup) {\n\t\t\t\tawait deleteBackup(dstCompose);\n\t\t\t\tGriddoLog.verbose(`delete backup: ${dstCompose}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (withBackup) {\n\t\t\t\tawait restoreBackup(dstCompose);\n\t\t\t\tGriddoLog.verbose(\"Backup has been restored.\");\n\t\t\t}\n\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\n/**\n * Move artifacts between cx-paths\n *\n * @param src - Source directory.\n * @param dst - Destination directory.\n * @param dirs - Directories to move.\n * @param options - Options.\n */\nasync function mvDirs(\n\tsrc: string,\n\tdst: string,\n\tdirs: string[],\n\toptions?: { withBackup?: boolean; override?: boolean },\n) {\n\tconst { override, withBackup } = options || {};\n\n\tfor (const dir of dirs) {\n\t\tconst srcCompose = path.join(src, dir);\n\t\tconst dstCompose = path.join(dst, dir);\n\n\t\tif (!(await pathExists(srcCompose))) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (withBackup) {\n\t\t\tawait createBackup(dstCompose);\n\t\t}\n\n\t\ttry {\n\t\t\t// Clean destination\n\t\t\tif (override && (await pathExists(dstCompose))) {\n\t\t\t\tawait fsp.rm(dstCompose, { recursive: true, force: true });\n\t\t\t}\n\n\t\t\tawait fsp.rename(srcCompose, dstCompose);\n\t\t\tGriddoLog.verbose(`moved: ${srcCompose} to ${dstCompose}`);\n\n\t\t\tif (withBackup) {\n\t\t\t\tawait deleteBackup(dstCompose);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (withBackup) {\n\t\t\t\tawait restoreBackup(dstCompose);\n\t\t\t\tGriddoLog.info(\"Backup has been restored.\");\n\t\t\t}\n\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\n/**\n * Removes multiple artifact directories.\n *\n * @param dirs - An array of directory paths.\n */\nasync function rmDirs(dirs: string[]) {\n\tfor (const dir of dirs) {\n\t\ttry {\n\t\t\tawait fsp.rm(dir, { recursive: true, force: true });\n\t\t\tGriddoLog.verbose(`artifact removed: ${dir}`);\n\t\t} catch (error) {\n\t\t\tthrowError(ArtifactError, error);\n\t\t}\n\t}\n}\n\nasync function restoreBackup(src: string, suffix = \"-BACKUP\") {\n\tconst dst = src + suffix;\n\ttry {\n\t\tawait fsp.rename(dst, src);\n\t\tGriddoLog.info(`Backup ${dst} has been restored`);\n\t} catch (_error) {\n\t\tthrow new Error(`Error while delete ${dst} backup`);\n\t}\n}\n\nasync function deleteBackup(src: string, suffix = \"-BACKUP\") {\n\tconst dst = src + suffix;\n\n\tif (!(await pathExists(dst))) {\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait fsp.rm(dst, { recursive: true, force: true });\n\t\tGriddoLog.verbose(`Backup ${dst} has been deleted`);\n\t} catch (_error) {\n\t\tthrow new Error(`Error while delete ${dst} backup`);\n\t}\n}\n\nasync function createBackup(src: string, suffix = \"-BACKUP\") {\n\tconst dst = src + suffix;\n\n\tif (!(await pathExists(src))) {\n\t\treturn;\n\t}\n\n\tif (await pathExists(dst)) {\n\t\tGriddoLog.warn(`Destination ${dst} already exists`);\n\t\treturn;\n\t}\n\n\ttry {\n\t\tawait fsp.rename(src, dst);\n\t\tGriddoLog.verbose(`Backup of ${src} has been created in ${dst}`);\n\t} catch (error) {\n\t\tGriddoLog.error(`Error while coping ${src} to ${dst} backup`);\n\t\tthrowError(ArtifactError, error);\n\t}\n}\n\n/**\n * Return true if the site folder is empty or only has xml files. (Recursively)\n */\nasync function siteIsEmpty(sitePath: string) {\n\tconst siteFiles = (\n\t\tawait fsp.readdir(sitePath, {\n\t\t\twithFileTypes: true,\n\t\t\trecursive: true,\n\t\t})\n\t).filter((file) => file.isFile() && !path.basename(file.name).startsWith(\".\"));\n\n\tconst xmlFiles = siteFiles.filter((file) => file.name.endsWith(\".xml\"));\n\n\tif (siteFiles.length === xmlFiles.length) {\n\t\treturn true;\n\t}\n}\n\n/**\n * Delete empty directories from the given directory in a recursive way.\n */\nasync function deleteEmptyDirectories(dirPath: string) {\n\ttry {\n\t\tconst stats = await fsp.stat(dirPath);\n\n\t\t// Si no es un directorio, no hacemos nada\n\t\tif (!stats.isDirectory()) {\n\t\t\treturn;\n\t\t}\n\n\t\tlet filesInDirectory: string[];\n\t\ttry {\n\t\t\tfilesInDirectory = await fsp.readdir(dirPath);\n\t\t} catch (err: any) {\n\t\t\t// Si el directorio no existe o no se puede leer (ej. permisos), lo saltamos.\n\t\t\tif (err.code === \"ENOENT\") {\n\t\t\t\tGriddoLog.warn(`The directory \"${dirPath}\" does not exist, skipping it.`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tGriddoLog.error(`Error al leer el directorio \"${dirPath}\":`, err);\n\t\t\tthrow err; // Re-lanza el error para que sea manejado por el llamador\n\t\t}\n\n\t\t// Recorrer los contenidos del directorio\n\t\tfor (const file of filesInDirectory) {\n\t\t\tconst fullPath = path.join(dirPath, file);\n\t\t\tawait deleteEmptyDirectories(fullPath); // Llamada recursiva s\u00EDncrona\n\t\t}\n\n\t\t// Despu\u00E9s de procesar todos los subdirectorios, verifica si el directorio actual est\u00E1 vac\u00EDo\n\t\tconst remainingFiles = await fsp.readdir(dirPath);\n\n\t\tif (remainingFiles.length === 0) {\n\t\t\ttry {\n\t\t\t\tawait fsp.rmdir(dirPath);\n\t\t\t\tGriddoLog.verbose(`Remove empty directory: ${dirPath}`);\n\t\t\t} catch (err: any) {\n\t\t\t\t// Puede que haya habido un problema de concurrencia o permisos\n\t\t\t\tif (err.code === \"ENOENT\") {\n\t\t\t\t\tGriddoLog.warn(\n\t\t\t\t\t\t`El directorio \"${dirPath}\" ya no existe. Posiblemente fue borrado por otra operaci\u00F3n.`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tGriddoLog.error(`Error al borrar el directorio \"${dirPath}\":`, err);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} catch (err: any) {\n\t\tif (err.code === \"ENOENT\") {\n\t\t\t// El directorio ya no existe, no es un error para nosotros en este contexto\n\t\t\tGriddoLog.warn(`The directory \"${dirPath}\" does not exist or has already been processed.`);\n\t\t} else {\n\t\t\tGriddoLog.error(`General error general while processing \"${dirPath}\":`, err);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\nasync function pathExists(dir: string) {\n\ttry {\n\t\tawait fsp.access(dir);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * Busca recursivamente archivos que terminen con un sufijo espec\u00EDfico dentro de un directorio.\n * Esta funci\u00F3n es un generador as\u00EDncrono, lo que la hace muy eficiente en uso de memoria.\n *\n * @param dir El directorio base para comenzar la b\u00FAsqueda.\n * @param suffix El sufijo con el que deben terminar los nombres de archivo (ej: 'page-data.json').\n * @returns Un generador as\u00EDncrono que produce la ruta completa de cada archivo encontrado.\n * @throws Si el directorio inicial `dir` no existe o no se puede leer.\n */\nasync function* findFilesBySuffix(dir: string, suffix: string): AsyncGenerator<string> {\n\tconst dirHandle = await fsp.opendir(dir);\n\tfor await (const item of dirHandle) {\n\t\tconst fullPath = path.join(dir, item.name);\n\t\tif (item.isDirectory()) {\n\t\t\t// yield* para encadenar otro generator.\n\t\t\tyield* findFilesBySuffix(fullPath, suffix);\n\t\t} else if (item.isFile() && item.name.endsWith(suffix)) {\n\t\t\tyield fullPath;\n\t\t}\n\t}\n}\n\n/**\n * Walk a directory and returns the JSON file absolute paths with one level of depth.\n * /abs/.../sotre/331/158.json\n * /abs/.../sotre/114/443.json\n * /abs/.../sotre/131/217.json\n * /abs/.../sotre/191/281.json\n */\nasync function* walkStore(storeDir: string): AsyncGenerator<string> {\n\tconst storeDirHandle = await fsp.opendir(storeDir);\n\n\tfor await (const siteDirent of storeDirHandle) {\n\t\tif (siteDirent.isDirectory()) {\n\t\t\tconst siteDirPath = path.join(storeDir, siteDirent.name);\n\t\t\tconst siteDirHandle = await fsp.opendir(siteDirPath);\n\n\t\t\tfor await (const fileDirent of siteDirHandle) {\n\t\t\t\tconst filePath = path.join(siteDirPath, fileDirent.name);\n\n\t\t\t\tif (fileDirent.isFile() && path.extname(filePath) === \".json\") {\n\t\t\t\t\tyield filePath;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport {\n\tcpDirs,\n\tdeleteDisposableSiteDirs,\n\tdeleteEmptyDirectories,\n\tfindFilesBySuffix,\n\tmkDirs,\n\tmvDirs,\n\tpathExists,\n\trenamePath,\n\trmDirs,\n\twalkStore,\n};\n", "/**\n * Do you want to add a new error to the list?\n *\n * 1 - Add the new error type name to the `ErrorsType` union type.\n * 2 - Export a new ErrorData object (or a function that returns one) in this\n * file by completing the `error` (ErrosType) and `message` (string) properties\n * obligatorily.\n */\n\nimport type { SpawnSyncReturns } from \"node:child_process\";\nimport type { ErrorData } from \"../core/errors\";\n\ntype ErrorsType =\n\t| \"ArtifactError\"\n\t| \"BundlesInconsistencyError\"\n\t| \"CheckHealthError\"\n\t| \"ErrorInSSGBuildProcess\"\n\t| \"LifecycleExecutionError\"\n\t| \"LoginError\"\n\t| \"NoDomainsFoundError\"\n\t| \"NoJSConfigFileFound\"\n\t| \"ReadFromStoreError\"\n\t| \"ReferenceFieldSourcesNotFoundError\"\n\t| \"RenderUUIDError\"\n\t| \"UploadSearchError\"\n\t| \"WriteToStoreError\";\n\nconst ArtifactError: ErrorData = {\n\terror: \"ArtifactError\",\n\tmessage: \"There was a problem with an artifact\",\n\texpected:\n\t\t\"An external process may have has modified or deleted one of the artifacts (files and directories).\",\n\thint: \"Have there been any recent deployments? These can delete directories from the current render.\",\n};\n\nconst ErrorInSSGBuildProcess = (command: SpawnSyncReturns<string>): ErrorData => ({\n\terror: \"ErrorInSSGBuildProcess\",\n\tmessage: `Error in SSG build process: ${JSON.stringify(command)}`,\n\texpected: \"This can happen if there was a problem with the SSG build process.\",\n});\n\nconst LifecycleExecutionError = (attempts: number, name: string): ErrorData => ({\n\terror: \"LifecycleExecutionError\",\n\tmessage: `Exceeded maximum retry attempts (${attempts}) for ${name} LifeCycle`,\n});\n\nconst LoginError: ErrorData = {\n\terror: \"LoginError\",\n\tmessage: \"There was a problem logging in to the API\",\n\texpected: \"This happens if the API is currently not working or the credentials are incorrect.\",\n};\n\nconst NoDomainsFoundError: ErrorData = {\n\terror: \"NoDomainsFoundError\",\n\tmessage: \"No domains were found in this instance. The process cannot continue.\",\n\texpected:\n\t\t\"This may happen if the API is not functioning, or the site is not properly configured, or the domains are not registered.\",\n\thint: \"You can contact the instance administrator.\",\n};\n\nconst NoJSConfigFileFound: ErrorData = {\n\terror: \"NoJSConfigFileFound\",\n\tmessage: \"Could not find jsconfig.json or tsconfig.json\",\n\texpected:\n\t\t\"This can happen if the instance is not properly configured with a jsconfig.json or tsconfig.json file.\",\n};\n\nconst ReadFromStoreError: ErrorData = {\n\terror: \"ReadFromStoreError\",\n\tmessage: \"There was an error reading a file to the Store directory\",\n\thint: \"There may be an issue such as permissions preventing the file from being read.\",\n};\n\nconst ReferenceFieldSourcesNotFoundError: ErrorData = {\n\terror: \"ReferenceFieldSourcesNotFoundError\",\n\tmessage: \"The distributor has no sources defined.\",\n\texpected:\n\t\t\"It is expected to have at least one data source in the `sources` property, even if it is empty.\",\n};\n\nconst RenderUUIDError: ErrorData = {\n\terror: \"RenderUUIDError\",\n\tmessage: `Render sentinel file does not exist.\nThe rendering UUID cannot be read safely.\nThere was probably an instance deployment during the render, and files were deleted.\n\nThe files generated in this render will not be published.`,\n};\n\nconst WriteToStoreError: ErrorData = {\n\terror: \"WriteToStoreError\",\n\tmessage: \"There was an error writing a file to the Store directory\",\n\thint: \"There may be an issue such as lack of space or permissions preventing the file from being written.\",\n};\n\nconst UploadSearchError: ErrorData = {\n\terror: \"UploadSearchError\",\n\tmessage: \"There was an error uploading content to API for search\",\n\thint: \"This happens if the API is currently not working or the credentials are incorrect.\",\n};\n\nconst CheckHealthError: ErrorData = {\n\terror: \"CheckHealthError\",\n\tmessage: \"There was a problem with environment vars configuration.\",\n\texpected: \"Some of the required environment variables are not set correctly or are missing\",\n\thint: \"Are the environment variables correctly set?\",\n};\n\nexport {\n\tArtifactError,\n\tCheckHealthError,\n\tErrorInSSGBuildProcess,\n\tLifecycleExecutionError,\n\tLoginError,\n\tNoDomainsFoundError,\n\tNoJSConfigFileFound,\n\tReadFromStoreError,\n\tReferenceFieldSourcesNotFoundError,\n\tRenderUUIDError,\n\tUploadSearchError,\n\tWriteToStoreError,\n\ttype ErrorsType,\n};\n", "import type { RenderModeTuple } from \"../shared/types/render\";\n\nimport { execSync } from \"node:child_process\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { readDB, writeDB } from \"../core/db\";\nimport { throwError } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { RenderUUIDError } from \"../shared/errors\";\nimport { brush } from \"../shared/npm-modules/brush\";\nimport { RENDER_MODE } from \"../shared/types/render\";\nimport { AuthService } from \"./auth\";\nimport { getBuildMetadata } from \"./manage-store\";\n\n/**\n * Creates a sentinel file with the current date and time.\n * This file is used to track later if node_modules/@griddo/cx was cleaned by a\n * npm install coming from a deploy.\n */\nasync function markRenderAsStarted(options: { domain: string; basePath: string }) {\n\tconst { domain } = options;\n\n\tconst db = await readDB();\n\tdb.domains[domain].isRendering = true;\n\tawait writeDB(db);\n\n\t// Creamos un archivo centinela, si al terminar el render este archivo no\n\t// existe es que ha habido un deploy por medio y hay que invalidar el render\n\tconst { __ssg } = await getRenderPathsHydratedWithDomainFromDB();\n\n\tconst renderSentinelFile = path.join(__ssg, `.render-sentinel-${domain}`);\n\tawait fsp.writeFile(renderSentinelFile, new Date().toISOString());\n}\n\nasync function markRenderAsCompleted(domain: string) {\n\tconst db = await readDB();\n\tdb.domains[domain].isRendering = false;\n\tdb.currentRenderingDomain = null;\n\tdb.domains[domain].renderMode = RENDER_MODE.COMPLETED;\n\t// db.domains[domain].shouldBeRendered = false;\n\tawait writeDB(db);\n\n\t// Borramos finalmente el archivo centinela\n\tconst { __ssg } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst renderSentinelFile = path.join(__ssg, `.render-sentinel-${domain}`);\n\tawait fsp.unlink(renderSentinelFile);\n}\n\nasync function assertRenderIsValid(domain: string) {\n\t// Comprobamos que .render-sentinel exista, si no es que un deploy lo borro\n\t// y hay que invalidar el render.\n\tconst { __ssg } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst renderSentinelFile = path.join(__ssg, `.render-sentinel-${domain}`);\n\tif (!(await pathExists(renderSentinelFile))) {\n\t\tthrowError(RenderUUIDError);\n\t}\n}\n\n/**\n * Determines the appropriate render mode for a given domain based on its current state,\n * previous render errors, deployment status, and whether rendering is required.\n *\n * @param options - An object containing:\n * - `domain`: The domain name to resolve the render mode for.\n * - `shouldBeRendered`: A boolean indicating if the domain should be rendered.\n * @returns An object with:\n * - `renderMode`: The resolved render mode (`FROM_SCRATCH`, `INCREMENTAL`, or `IDLE`).\n * - `reason`: A string describing the reason for the chosen render mode.\n *\n * @remarks\n * The function checks for missing exports, previous render errors, new deployments,\n * and whether rendering is necessary to decide the render mode.\n *\n * @todo\n * Improve ifs and reason concatenations...\n */\nasync function resolveDomainRenderMode(options: { domain: string; shouldBeRendered: boolean }) {\n\tconst { domain, shouldBeRendered } = options;\n\n\tconst db = await readDB();\n\n\tconst { __cache, __exports } = await getRenderPathsHydratedWithDomainFromDB({ domain });\n\tconst exportsAreMissing = !(await pathExists(path.join(__exports)));\n\tconst previousRenderFailed = db.domains[domain]?.isRendering;\n\tconst newDeployDetected = await hasNewCommit(__cache);\n\n\tif (exportsAreMissing) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.FROM_SCRATCH,\n\t\t\treason: \"missing exports directory\",\n\t\t};\n\t}\n\n\tif (previousRenderFailed) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.FROM_SCRATCH,\n\t\t\treason: \"error in previous render\",\n\t\t};\n\t}\n\n\tif (newDeployDetected) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.FROM_SCRATCH,\n\t\t\treason: \"new commit hash\",\n\t\t};\n\t}\n\n\tif (!shouldBeRendered) {\n\t\treturn {\n\t\t\trenderMode: RENDER_MODE.IDLE,\n\t\t\treason: \"no activity\",\n\t\t};\n\t}\n\n\treturn {\n\t\trenderMode: RENDER_MODE.INCREMENTAL,\n\t\treason: \"has changes\",\n\t};\n}\n\nasync function hasNewCommit(basePath: string): Promise<boolean> {\n\tconst commitFile = path.join(basePath, \"commit\");\n\tconst currentCommit = execSync(\"git rev-parse HEAD\").toString().trim();\n\n\tif (await pathExists(commitFile)) {\n\t\tconst savedCommit = (await fsp.readFile(commitFile, \"utf-8\")).trim();\n\t\tif (savedCommit === currentCommit) {\n\t\t\treturn false; // No hay nuevo commit\n\t\t}\n\n\t\treturn true;\n\t}\n\n\treturn true;\n}\n\nasync function updateCommitFile(options: { basePath: string }) {\n\tconst { basePath } = options;\n\t// We use the commit saved at the beginning of the render, not the current\n\t// machine commit, thus avoiding problems if there is a deployment during\n\t// the render\n\tconst db = await readDB();\n\tconst currentCommit = db.commitHash;\n\tawait fsp.writeFile(path.join(basePath, \"commit\"), currentCommit);\n}\n\nasync function getRenderModeFromDB(domain: string): Promise<RenderModeTuple> {\n\tconst db = await readDB();\n\n\tif (!db.domains[domain]) {\n\t\tthrow new Error(brush.red(`[!] Error: Domain ${domain} not found in DB`));\n\t}\n\n\tif (!db.domains[domain].renderMode) {\n\t\tthrow new Error(brush.red(`[!] Error: Render mode not found for domain ${domain}`));\n\t}\n\n\treturn {\n\t\trenderMode: db.domains[domain].renderMode,\n\t\treason: db.domains[domain].renderModeReason,\n\t};\n}\n\nasync function getRenderPathsHydratedWithDomainFromDB(options?: {\n\tdomain?: string;\n\tdbFilePath?: string;\n}) {\n\tconst { domain, dbFilePath } = options || {};\n\n\tconst db = await readDB(dbFilePath);\n\tconst paths = db.paths;\n\n\treturn {\n\t\t__root: paths.root,\n\t\t__cache: path.join(paths.cxCache, domain || \"\"),\n\t\t__components: paths.components,\n\t\t__cx: paths.cx,\n\t\t__sites: paths.exportsDir,\n\t\t__exports: path.join(paths.exportsDir, domain || \"\"),\n\t\t__exports_backup: path.join(paths.exportsDirBackup, domain || \"\"),\n\t\t__ssg: paths.ssg,\n\t\t__exports_dist: path.join(paths.exportsDir, domain || \"\", \"dist\"),\n\t};\n}\n\nasync function getRenderMetadataFromDB() {\n\tconst db = await readDB();\n\treturn {\n\t\tgriddoVersion: db.griddoVersion,\n\t\tbuildReportFileName: db.buildReportFileName,\n\t};\n}\n\n/**\n * Save a file with the end of build process to use as `end-render` signal.\n */\nasync function generateBuildReport(domain: string) {\n\tconst authControl = await AuthService.login();\n\n\tconst { __root } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst { buildReportFileName } = await getRenderMetadataFromDB();\n\tconst { buildProcessData } = await getBuildMetadata(domain);\n\n\tconst buildSitesInfo = Object.keys(buildProcessData).map((siteID) => ({\n\t\t...buildProcessData[siteID],\n\t\tsiteId: Number.parseInt(siteID),\n\t}));\n\n\tconst report = {\n\t\tauthControl,\n\t\tsites: buildSitesInfo,\n\t};\n\n\tconst reportFilePath = path.join(__root, \"current-dist\", buildReportFileName);\n\n\tawait fsp.writeFile(reportFilePath, JSON.stringify(report));\n\n\tGriddoLog.verbose(`build report saved in ${reportFilePath}`);\n}\n\nexport {\n\tassertRenderIsValid,\n\tgenerateBuildReport,\n\tgetRenderMetadataFromDB,\n\tgetRenderModeFromDB,\n\tgetRenderPathsHydratedWithDomainFromDB,\n\tmarkRenderAsCompleted,\n\tmarkRenderAsStarted,\n\tresolveDomainRenderMode,\n\tupdateCommitFile,\n};\n", "const GRIDDO_API_URL = process.env.GRIDDO_API_URL;\nconst GRIDDO_PUBLIC_API_URL = process.env.GRIDDO_PUBLIC_API_URL;\n\nconst AI_EMBEDDINGS = `${GRIDDO_API_URL}/ai/embeddings`;\nconst ALERT = `${GRIDDO_PUBLIC_API_URL}/alert`;\nconst DOMAINS = `${GRIDDO_API_URL}/domains`;\nconst GET_ALL = `${GRIDDO_API_URL}/sites/all`;\nconst GET_PAGE = `${GRIDDO_API_URL}/page`;\nconst LOGIN = `${GRIDDO_API_URL}/login_check`;\nconst RESET_RENDER = `${GRIDDO_API_URL}/debug/reset-render`;\nconst ROBOTS = `${GRIDDO_API_URL}/domains/robots`;\nconst SEARCH = `${GRIDDO_API_URL}/search`;\nconst SETTINGS = `${GRIDDO_API_URL}/settings`;\n\n// Domain\nconst DOMAIN_URI = `${GRIDDO_API_URL}/domains/`;\nconst LLMS = [DOMAIN_URI, \"/llms\"];\n\n// Site\nconst SITE_URI = `${GRIDDO_API_URL}/site/`;\nconst BUILD_END = [SITE_URI, \"/build/end\"];\nconst BUILD_START = [SITE_URI, \"/build/start\"];\nconst GET_REFERENCE_FIELD_DATA = [SITE_URI, \"/distributor\"];\nconst GET_SITEMAP = [SITE_URI, \"/sitemap\"];\nconst INFO = [SITE_URI, \"/all\"];\nconst LANGUAGES = [SITE_URI, \"/languages\"];\nconst SOCIALS = [SITE_URI, \"/socials\"];\n\nexport {\n\tAI_EMBEDDINGS,\n\tALERT,\n\tBUILD_END,\n\tBUILD_START,\n\tDOMAINS,\n\tGET_ALL,\n\tGET_PAGE,\n\tGET_REFERENCE_FIELD_DATA,\n\tGET_SITEMAP,\n\tINFO,\n\tLANGUAGES,\n\tLLMS,\n\tLOGIN,\n\tRESET_RENDER,\n\tROBOTS,\n\tSEARCH,\n\tSETTINGS,\n\tSOCIALS,\n};\n", "{\n\t\"name\": \"@griddo/cx\",\n\t\"description\": \"Griddo SSG based on Gatsby\",\n\t\"version\": \"11.10.21\",\n\t\"authors\": [\n\t\t\"Hisco <francis.vega@griddo.io>\"\n\t],\n\t\"license\": \"UNLICENSED\",\n\t\"homepage\": \"https://griddo.io\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"https://github.com/griddo/griddo\"\n\t},\n\t\"bin\": {\n\t\t\"griddo-render\": \"cli.mjs\"\n\t},\n\t\"exports\": {\n\t\t\".\": {\n\t\t\t\"import\": \"./build/index.js\",\n\t\t\t\"require\": \"./build/index.js\",\n\t\t\t\"types\": \"./build/index.d.ts\"\n\t\t},\n\t\t\"./react\": {\n\t\t\t\"import\": \"./build/react/index.js\",\n\t\t\t\"require\": \"./build/react/index.js\",\n\t\t\t\"types\": \"./build/react/index.d.ts\"\n\t\t}\n\t},\n\t\"scripts\": {\n\t\t\"// NPM\": \"\",\n\t\t\"prepare\": \"yarn run build\",\n\t\t\"// BUILD\": \"\",\n\t\t\"build\": \"rm -rf build && sh ./exporter/build.sh\",\n\t\t\"build:debug\": \"rm -rf build && sh ./exporter/build.sh --debug\",\n\t\t\"// TESTS\": \"\",\n\t\t\"test\": \"npm run test:compile && npm run test:create-render-fixtures && node --env-file=.env --test ./build/__tests__/* && npm run test:remove-render-fixtures\",\n\t\t\"test-exporter\": \"npm run test:compile && node --env-file=.env --test ./build/__tests__exporter__/\",\n\t\t\"test:create-render-fixtures\": \"node --env-file=.env ./build/__tests__/utils/create-fixtures\",\n\t\t\"test:remove-render-fixtures\": \"node --env-file=.env ./build/__tests__/utils/remove-fixtures\",\n\t\t\"test:compile\": \"tsgo --project tsconfig.tests.json\",\n\t\t\"// INFRA SCRIPTS\": \"\",\n\t\t\"prepare-domains-render\": \"node ./build/commands/prepare-domains-render\",\n\t\t\"start-render\": \"node ./build/commands/start-render\",\n\t\t\"end-render\": \"node ./build/commands/end-render\",\n\t\t\"upload-search-content\": \"node ./build/commands/upload-search-content\",\n\t\t\"reset-render\": \"node ./build/commands/reset-render\",\n\t\t\"// ONLY LOCAL SCRIPTS\": \"\",\n\t\t\"prepare-assets-directory\": \"node ./build/commands/prepare-assets-directory\",\n\t\t\"create-rollback-copy\": \"rm -rf ../../exports-backup && cp -r ../../exports ../../exports-backup\",\n\t\t\"render\": \"npm run build && node --env-file=.env cli.mjs render --root=../..\",\n\t\t\"// LINTER & FORMATTER\": \"\",\n\t\t\"lint\": \"biome check --write\",\n\t\t\"format\": \"biome format --write\",\n\t\t\"flint\": \"npm run lint && npm run format\",\n\t\t\"ts-lint\": \"tsgo --noEmit\",\n\t\t\"watch:ts-lint\": \"tsc --noEmit --watch\"\n\t},\n\t\"dependencies\": {\n\t\t\"gatsby\": \"5.15.0\",\n\t\t\"html-react-parser\": \"^5.2.10\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@biomejs/biome\": \"2.3.4\",\n\t\t\"@types/node\": \"20.19.4\",\n\t\t\"@typescript/native-preview\": \"latest\",\n\t\t\"cheerio\": \"1.1.2\",\n\t\t\"esbuild\": \"0.25.12\",\n\t\t\"p-limit\": \"7.2.0\",\n\t\t\"typescript\": \"5.9.3\"\n\t},\n\t\"peerDependencies\": {\n\t\t\"@griddo/core\": \"11.9.16\",\n\t\t\"react\": \">=18 <19\",\n\t\t\"react-dom\": \">=18 <19\"\n\t},\n\t\"engines\": {\n\t\t\"node\": \">=20.19\"\n\t},\n\t\"files\": [\n\t\t\"build\",\n\t\t\"exporter\",\n\t\t\"src\",\n\t\t\"gatsby-browser.tsx\",\n\t\t\"gatsby-config.ts\",\n\t\t\"gatsby-node.ts\",\n\t\t\"gatsby-ssr.tsx\",\n\t\t\"global.d.ts\",\n\t\t\"tsconfig.commands.json\",\n\t\t\"tsconfig.exporter.json\",\n\t\t\"tsconfig.json\",\n\t\t\"plugins\",\n\t\t\"cli.mjs\"\n\t],\n\t\"publishConfig\": {\n\t\t\"access\": \"public\"\n\t},\n\t\"gitHead\": \"8be1be07411fa9b37c7c64a8d2075635edf24263\"\n}\n", "import packageJson from \"../../package.json\";\n\nexport const DEFAULT_HEADERS = {\n\t\"x-application-id\": \"griddo-cx\",\n\t\"x-client-version\": packageJson.version,\n\t\"x-client-name\": \"CX\",\n} as const;\n", "import type { AuthHeaders } from \"../shared/types/api\";\n\nimport { throwError } from \"../core/errors\";\nimport { LOGIN } from \"../shared/endpoints\";\nimport { GRIDDO_BOT_PASSWORD, GRIDDO_BOT_USER } from \"../shared/envs\";\nimport { LoginError } from \"../shared/errors\";\nimport { DEFAULT_HEADERS } from \"../shared/headers\";\n\nclass AuthService {\n\theaders: AuthHeaders | undefined;\n\n\tasync login() {\n\t\ttry {\n\t\t\tconst response = await fetch(LOGIN, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: Object.assign({}, DEFAULT_HEADERS, {\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tConnection: \"close\",\n\t\t\t\t}),\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tusername: GRIDDO_BOT_USER,\n\t\t\t\t\tpassword: GRIDDO_BOT_PASSWORD,\n\t\t\t\t}),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tthrow new Error(\"Error while login in the API\");\n\t\t\t}\n\n\t\t\tconst { token } = await response.json();\n\t\t\tthis.headers = {\n\t\t\t\tAuthorization: `bearer ${token}`,\n\t\t\t\t\"Cache-Control\": \"no-store\",\n\t\t\t};\n\n\t\t\treturn this.headers;\n\t\t} catch (e) {\n\t\t\tthrowError(LoginError, e);\n\t\t}\n\t}\n}\n\nconst authService = new AuthService();\n\nexport { authService as AuthService };\n"],
5
5
  "mappings": "oeAAA,IAAAA,EAAgB,+BAChBC,EAAiB,wBCCjB,IAAAC,EAAiB,wBCKjB,IAAMC,GAAQ,UACRC,EAAQ,CACb,MAAO,WACP,IAAK,WACL,MAAO,WACP,OAAQ,WACR,KAAM,WACN,QAAS,WACT,KAAM,WACN,MAAO,WACP,KAAM,WACN,KAAM,UACN,IAAK,SACN,EAMMC,EAAQ,CAAC,EAEf,QAAWC,KAASF,EAAO,CAC1B,IAAMG,EAAMD,EACZD,EAAME,CAAG,EAAKC,GAA0B,GAAGJ,EAAMG,CAAG,CAAC,GAAGC,CAAI,GAAGL,EAAK,EACrE,CC7BA,IAAMM,EAAc,CACnB,aAAc,eACd,YAAa,cACb,KAAM,OACN,MAAO,QACP,UAAW,WACZ,ECNA,IAAAC,EAAgB,+BAChBC,EAAiB,wBCHjB,IAAAC,EAAiB,wBCAjB,IAAAC,EAAe,sBAEf,IAAAC,EAAiB,wBACjBC,EAAoB,2BACpBC,EAA8B,oBA0BxBC,EAAUC,GACfA,aAAqB,OAAM,iBAAcA,CAAS,EAAIA,EA0ChD,SAASC,EAAWC,EAAcC,EAAmB,CAAC,EAAuB,CACnF,GAAM,CAAE,IAAAC,EAAM,EAAAC,QAAQ,IAAI,EAAG,KAAAC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IAAeE,EAAY,KAC9B,OAGD,GAAM,CAAE,UAAAC,CAAU,EAAI,MAAMC,EAAuC,CAAE,OAAAL,CAAO,CAAC,EACvEM,EAAY,EAAAC,QAAK,KAAKH,EAAW,QAAQ,EACzCI,EAAkB,EAAAD,QAAK,KAAKH,EAAWJ,CAAM,EAE/C,MAAMS,EAAWH,CAAS,GAC7B,MAAM,EAAAI,QAAI,GAAGF,EAAiB,CAAE,MAAO,GAAM,UAAW,EAAK,CAAC,EAC9D,MAAM,EAAAE,QAAI,OAAOJ,EAAWE,CAAe,GAE3CG,EAAU,KAAK,4BAA4B,CAE7C,CAEA,eAAeC,IAAO,CACrB,MAAMb,GAAiB,CACxB,CAEAc,EAAiBD,EAAI",
6
6
  "names": ["import_promises", "import_node_path", "import_node_path", "RESET", "CODES", "brush", "color", "key", "text", "RENDER_MODE", "import_promises", "import_node_path", "import_node_path", "import_node_fs", "import_node_path", "import_node_process", "import_node_url", "toPath", "urlOrPath", "findUpSync", "name", "options", "cwd", "process", "type", "stopAtOption", "directory", "path", "toPath", "root", "stopAt", "isAbsoluteName", "filePath", "stats", "fs", "pkgDirSync", "options", "cwd", "filePath", "findUpSync", "path", "env", "envIsTruthy", "value", "GRIDDO_API_URL", "GRIDDO_PUBLIC_API_URL", "GRIDDO_BOT_USER", "GRIDDO_BOT_PASSWORD", "GRIDDO_API_CONCURRENCY_COUNT", "GRIDDO_SKIP_BUILD_CHECKS", "GRIDDO_BUILD_LOGS", "GRIDDO_BUILD_LOGS_BUFFER_SIZE", "GRIDDO_SSG_VERBOSE_LOGS", "GRIDDO_SEARCH_FEATURE", "GRIDDO_ASSET_PREFIX", "GRIDDO_REACT_APP_INSTANCE", "GRIDDO_AI_EMBEDDINGS", "GRIDDO_VERBOSE_LOGS", "GRIDDO_USE_DIST_BACKUP", "GRIDDO_SSG_BUNDLE_ANALYZER", "GRIDDO_RENDER_DISABLE_LLMS_TXT", "GriddoLog", "_GriddoLog", "str", "GRIDDO_VERBOSE_LOGS", "brush", "GRIDDO_BUILD_LOGS", "args", "root", "pkgDirSync", "path", "cache", "dbFilePath", "readDB", "customDBPath", "file", "fsp", "error", "GriddoLog", "writeDB", "renderDB", "import_promises", "import_node_path", "import_promises", "LoginError", "pathExists", "dir", "fsp", "distRollback", "domain", "data", "readDB", "exportsDir", "exportsDirBackup", "GriddoLog", "path", "fsp", "pathExists", "RenderError", "originalError", "throwError", "options", "stack", "error", "message", "expected", "hint", "errorColor", "GriddoLog", "brush", "extraText", "withErrorHandler", "fn", "data", "readDB", "root", "path", "distRollback", "RENDER_MODE", "writeDB", "import_node_path", "GRIDDO_API_URL", "GRIDDO_PUBLIC_API_URL", "AI_EMBEDDINGS", "ALERT", "DOMAINS", "GET_ALL", "GET_PAGE", "LOGIN", "RESET_RENDER", "ROBOTS", "SEARCH", "SETTINGS", "DOMAIN_URI", "SITE_URI", "GRIDDO_API_URL", "package_default", "DEFAULT_HEADERS", "package_default", "AuthService", "response", "LOGIN", "DEFAULT_HEADERS", "GRIDDO_BOT_USER", "GRIDDO_BOT_PASSWORD", "token", "throwError", "LoginError", "authService", "getRenderModeFromDB", "domain", "db", "readDB", "brush", "getRenderPathsHydratedWithDomainFromDB", "options", "dbFilePath", "paths", "path", "prepareAssetsDir", "domain", "renderMode", "getRenderModeFromDB", "RENDER_MODE", "__exports", "getRenderPathsHydratedWithDomainFromDB", "assetsDir", "path", "domainAssetsDir", "pathExists", "fsp", "GriddoLog", "main", "withErrorHandler"]
7
7
  }
@@ -1,4 +1,4 @@
1
- "use strict";var Je=Object.create;var re=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var Xe=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of qe(r))!Ye.call(e,n)&&n!==t&&re(e,n,{get:()=>r[n],enumerable:!(o=We(r,n))||o.enumerable});return e};var l=(e,r,t)=>(t=e!=null?Je(Ke(e)):{},Xe(r||!e||!e.__esModule?re(t,"default",{value:e,enumerable:!0}):t,e));var Q=require("node:child_process"),ee=l(require("node:fs/promises")),S=l(require("node:path"));var oe="11.10.20";var ne={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:oe,authors:["Hisco <francis.vega@griddo.io>"],license:"UNLICENSED",homepage:"https://griddo.io",repository:{type:"git",url:"https://github.com/griddo/griddo"},bin:{"griddo-render":"cli.mjs"},exports:{".":{import:"./build/index.js",require:"./build/index.js",types:"./build/index.d.ts"},"./react":{import:"./build/react/index.js",require:"./build/react/index.js",types:"./build/react/index.d.ts"}},scripts:{"// NPM":"",prepare:"yarn run build","// BUILD":"",build:"rm -rf build && sh ./exporter/build.sh","build:debug":"rm -rf build && sh ./exporter/build.sh --debug","// TESTS":"",test:"npm run test:compile && npm run test:create-render-fixtures && node --env-file=.env --test ./build/__tests__/* && npm run test:remove-render-fixtures","test-exporter":"npm run test:compile && node --env-file=.env --test ./build/__tests__exporter__/","test:create-render-fixtures":"node --env-file=.env ./build/__tests__/utils/create-fixtures","test:remove-render-fixtures":"node --env-file=.env ./build/__tests__/utils/remove-fixtures","test:compile":"tsgo --project tsconfig.tests.json","// INFRA SCRIPTS":"","prepare-domains-render":"node ./build/commands/prepare-domains-render","start-render":"node ./build/commands/start-render","end-render":"node ./build/commands/end-render","upload-search-content":"node ./build/commands/upload-search-content","reset-render":"node ./build/commands/reset-render","// ONLY LOCAL SCRIPTS":"","prepare-assets-directory":"node ./build/commands/prepare-assets-directory","create-rollback-copy":"rm -rf ../../exports-backup && cp -r ../../exports ../../exports-backup",render:"npm run build && node --env-file=.env cli.mjs render --root=../..","// LINTER & FORMATTER":"",lint:"biome check --write",format:"biome format --write",flint:"npm run lint && npm run format","ts-lint":"tsgo --noEmit","watch:ts-lint":"tsc --noEmit --watch"},dependencies:{gatsby:"5.15.0","html-react-parser":"^5.2.10"},devDependencies:{"@biomejs/biome":"2.3.4","@types/node":"20.19.4","@typescript/native-preview":"latest",cheerio:"1.1.2",esbuild:"0.25.12","p-limit":"7.2.0",typescript:"5.9.3"},peerDependencies:{"@griddo/core":"11.9.16",react:">=18 <19","react-dom":">=18 <19"},engines:{node:">=20.19"},files:["build","exporter","src","gatsby-browser.tsx","gatsby-config.ts","gatsby-node.ts","gatsby-ssr.tsx","global.d.ts","tsconfig.commands.json","tsconfig.exporter.json","tsconfig.json","plugins","cli.mjs"],publishConfig:{access:"public"},gitHead:"cc4cb47324099928259991fc63e6a516679c83db"};var ie={error:"ArtifactError",message:"There was a problem with an artifact",expected:"An external process may have has modified or deleted one of the artifacts (files and directories).",hint:"Have there been any recent deployments? These can delete directories from the current render."};var se={error:"LoginError",message:"There was a problem logging in to the API",expected:"This happens if the API is currently not working or the credentials are incorrect."},ae={error:"NoDomainsFoundError",message:"No domains were found in this instance. The process cannot continue.",expected:"This may happen if the API is not functioning, or the site is not properly configured, or the domains are not registered.",hint:"You can contact the instance administrator."},ce={error:"NoJSConfigFileFound",message:"Could not find jsconfig.json or tsconfig.json",expected:"This can happen if the instance is not properly configured with a jsconfig.json or tsconfig.json file."};var de={error:"CheckHealthError",message:"There was a problem with environment vars configuration.",expected:"Some of the required environment variables are not set correctly or are missing",hint:"Are the environment variables correctly set?"};var Ze="\x1B[0m",pe={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m"},m={};for(let e in pe){let r=e;m[r]=t=>`${pe[r]}${t}${Ze}`}var A={FROM_SCRATCH:"FROM_SCRATCH",INCREMENTAL:"INCREMENTAL",IDLE:"IDLE",ERROR:"ERROR",COMPLETED:"COMPLETED"};var q=l(require("node:fs/promises")),U=l(require("node:path"));var J=l(require("node:path"));var me=l(require("node:fs")),le=l(require("node:fs/promises")),h=l(require("node:path")),V=l(require("node:process")),fe=require("node:url"),G=e=>e instanceof URL?(0,fe.fileURLToPath)(e):e;async function ue(e,r={}){let{cwd:t=V.default.cwd(),type:o="file",stopAt:n}=r,i=h.default.resolve(G(t)??""),{root:a}=h.default.parse(i),c=n?h.default.resolve(i,G(n)):a,d=h.default.isAbsolute(e);for(;;){let f=d?e:h.default.join(i,e);try{let g=await le.default.stat(f);if(o==="file"&&g.isFile()||o==="directory"&&g.isDirectory())return f}catch{}if(i===c||i===a)break;i=h.default.dirname(i)}}function O(e,r={}){let{cwd:t=V.default.cwd(),type:o="file",stopAt:n}=r,i=h.default.resolve(G(t)??""),{root:a}=h.default.parse(i),c=n?h.default.resolve(i,G(n)):a,d=h.default.isAbsolute(e);for(;;){let f=d?e:h.default.join(i,e);try{let g=me.default.statSync(f,{throwIfNoEntry:!1});if(o==="file"&&g?.isFile()||o==="directory"&&g?.isDirectory())return f}catch{}if(i===c||i===a)break;i=h.default.dirname(i)}}async function W(e){let{cwd:r}=e||{},t=await ue("package.json",{cwd:r});return t&&J.default.dirname(t)}function v(e){let{cwd:r}=e||{},t=O("package.json",{cwd:r});return t&&J.default.dirname(t)}var{env:p}=process;function w(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"y":case"on":return!0;default:return!1}}var kr=p.GRIDDO_API_URL||p.API_URL,Fr=p.GRIDDO_PUBLIC_API_URL||p.PUBLIC_API_URL,ge=p.botEmail||p.GRIDDO_BOT_USER,he=p.botPassword||p.GRIDDO_BOT_PASSWORD,Gr=Number.parseInt(p.GRIDDO_API_CONCURRENCY_COUNT||"10"),De=w(p.GRIDDO_SKIP_BUILD_CHECKS),j=w(p.GRIDDO_BUILD_LOGS),ye=Number.parseInt(p.GRIDDO_BUILD_LOGS_BUFFER_SIZE||"500"),jr=w(p.GRIDDO_SSG_VERBOSE_LOGS),Ur=w(p.GRIDDO_SEARCH_FEATURE),Mr=p.GRIDDO_ASSET_PREFIX||p.ASSET_PREFIX,Hr=p.GRIDDO_REACT_APP_INSTANCE||p.REACT_APP_INSTANCE,Vr=w(p.GRIDDO_AI_EMBEDDINGS),Re=w(p.GRIDDO_VERBOSE_LOGS),Jr=w(p.GRIDDO_USE_DIST_BACKUP),Wr=w(p.GRIDDO_SSG_BUNDLE_ANALYZER),qr=w(p.GRIDDO_RENDER_DISABLE_LLMS_TXT);var s=class e{constructor(){}static verbose(...r){Re&&console.log(m.yellow("verbose"),m.dim(r.join(" ")))}static build(...r){j&&e.log(...r)}static info(...r){console.log(`${m.blue("info")} ${r.join(" ")}`)}static success(...r){console.log(`${m.green("success")} ${r.join(" ")}`)}static error(...r){console.error(`${m.red("error")} ${r.join(" ")}`)}static warn(...r){console.warn(`${m.yellow("warn")} ${r.join(" ")}`)}static log(...r){console.log(...r)}};var ze=v({cwd:U.default.resolve(__dirname,"../../..")})||"",Qe=U.default.join(ze,".griddo/cache"),Ee=U.default.join(Qe,"db.json");async function E(e=""){let r=e||Ee;try{return JSON.parse(await q.default.readFile(r,"utf-8"))}catch(t){throw s.error(`Failed to read DB file at ${r}:`,t),t}}async function P(e,r=""){let t=r||Ee;try{await q.default.writeFile(t,JSON.stringify(e,null," "))}catch(o){throw s.error(`Failed to write DB file at ${t}:`,o),o}}var K=l(require("node:fs/promises"));async function we(e){for(let r of e)try{await K.default.rm(r,{recursive:!0,force:!0}),s.verbose(`artifact removed: ${r}`)}catch(t){D(ie,t)}}async function b(e){try{return await K.default.access(e),!0}catch{return!1}}var C=class extends Error{constructor(r){super(r instanceof Error?r.message:String(r)),this.name="InternalCXError",this.stack=r instanceof Error?r.stack:""}};function D(e,r){let{error:t,message:o,expected:n,hint:i}=e,a=s.log(m.red(`[ ${t} ]`)),c=[n,i].filter(Boolean).join(`
1
+ "use strict";var Je=Object.create;var re=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,Ye=Object.prototype.hasOwnProperty;var Xe=(e,r,t,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of qe(r))!Ye.call(e,n)&&n!==t&&re(e,n,{get:()=>r[n],enumerable:!(o=We(r,n))||o.enumerable});return e};var l=(e,r,t)=>(t=e!=null?Je(Ke(e)):{},Xe(r||!e||!e.__esModule?re(t,"default",{value:e,enumerable:!0}):t,e));var Q=require("node:child_process"),ee=l(require("node:fs/promises")),S=l(require("node:path"));var oe="11.10.21";var ne={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:oe,authors:["Hisco <francis.vega@griddo.io>"],license:"UNLICENSED",homepage:"https://griddo.io",repository:{type:"git",url:"https://github.com/griddo/griddo"},bin:{"griddo-render":"cli.mjs"},exports:{".":{import:"./build/index.js",require:"./build/index.js",types:"./build/index.d.ts"},"./react":{import:"./build/react/index.js",require:"./build/react/index.js",types:"./build/react/index.d.ts"}},scripts:{"// NPM":"",prepare:"yarn run build","// BUILD":"",build:"rm -rf build && sh ./exporter/build.sh","build:debug":"rm -rf build && sh ./exporter/build.sh --debug","// TESTS":"",test:"npm run test:compile && npm run test:create-render-fixtures && node --env-file=.env --test ./build/__tests__/* && npm run test:remove-render-fixtures","test-exporter":"npm run test:compile && node --env-file=.env --test ./build/__tests__exporter__/","test:create-render-fixtures":"node --env-file=.env ./build/__tests__/utils/create-fixtures","test:remove-render-fixtures":"node --env-file=.env ./build/__tests__/utils/remove-fixtures","test:compile":"tsgo --project tsconfig.tests.json","// INFRA SCRIPTS":"","prepare-domains-render":"node ./build/commands/prepare-domains-render","start-render":"node ./build/commands/start-render","end-render":"node ./build/commands/end-render","upload-search-content":"node ./build/commands/upload-search-content","reset-render":"node ./build/commands/reset-render","// ONLY LOCAL SCRIPTS":"","prepare-assets-directory":"node ./build/commands/prepare-assets-directory","create-rollback-copy":"rm -rf ../../exports-backup && cp -r ../../exports ../../exports-backup",render:"npm run build && node --env-file=.env cli.mjs render --root=../..","// LINTER & FORMATTER":"",lint:"biome check --write",format:"biome format --write",flint:"npm run lint && npm run format","ts-lint":"tsgo --noEmit","watch:ts-lint":"tsc --noEmit --watch"},dependencies:{gatsby:"5.15.0","html-react-parser":"^5.2.10"},devDependencies:{"@biomejs/biome":"2.3.4","@types/node":"20.19.4","@typescript/native-preview":"latest",cheerio:"1.1.2",esbuild:"0.25.12","p-limit":"7.2.0",typescript:"5.9.3"},peerDependencies:{"@griddo/core":"11.9.16",react:">=18 <19","react-dom":">=18 <19"},engines:{node:">=20.19"},files:["build","exporter","src","gatsby-browser.tsx","gatsby-config.ts","gatsby-node.ts","gatsby-ssr.tsx","global.d.ts","tsconfig.commands.json","tsconfig.exporter.json","tsconfig.json","plugins","cli.mjs"],publishConfig:{access:"public"},gitHead:"8be1be07411fa9b37c7c64a8d2075635edf24263"};var ie={error:"ArtifactError",message:"There was a problem with an artifact",expected:"An external process may have has modified or deleted one of the artifacts (files and directories).",hint:"Have there been any recent deployments? These can delete directories from the current render."};var se={error:"LoginError",message:"There was a problem logging in to the API",expected:"This happens if the API is currently not working or the credentials are incorrect."},ae={error:"NoDomainsFoundError",message:"No domains were found in this instance. The process cannot continue.",expected:"This may happen if the API is not functioning, or the site is not properly configured, or the domains are not registered.",hint:"You can contact the instance administrator."},ce={error:"NoJSConfigFileFound",message:"Could not find jsconfig.json or tsconfig.json",expected:"This can happen if the instance is not properly configured with a jsconfig.json or tsconfig.json file."};var de={error:"CheckHealthError",message:"There was a problem with environment vars configuration.",expected:"Some of the required environment variables are not set correctly or are missing",hint:"Are the environment variables correctly set?"};var Ze="\x1B[0m",pe={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m"},m={};for(let e in pe){let r=e;m[r]=t=>`${pe[r]}${t}${Ze}`}var A={FROM_SCRATCH:"FROM_SCRATCH",INCREMENTAL:"INCREMENTAL",IDLE:"IDLE",ERROR:"ERROR",COMPLETED:"COMPLETED"};var q=l(require("node:fs/promises")),U=l(require("node:path"));var J=l(require("node:path"));var me=l(require("node:fs")),le=l(require("node:fs/promises")),h=l(require("node:path")),V=l(require("node:process")),fe=require("node:url"),G=e=>e instanceof URL?(0,fe.fileURLToPath)(e):e;async function ue(e,r={}){let{cwd:t=V.default.cwd(),type:o="file",stopAt:n}=r,i=h.default.resolve(G(t)??""),{root:a}=h.default.parse(i),c=n?h.default.resolve(i,G(n)):a,d=h.default.isAbsolute(e);for(;;){let f=d?e:h.default.join(i,e);try{let g=await le.default.stat(f);if(o==="file"&&g.isFile()||o==="directory"&&g.isDirectory())return f}catch{}if(i===c||i===a)break;i=h.default.dirname(i)}}function O(e,r={}){let{cwd:t=V.default.cwd(),type:o="file",stopAt:n}=r,i=h.default.resolve(G(t)??""),{root:a}=h.default.parse(i),c=n?h.default.resolve(i,G(n)):a,d=h.default.isAbsolute(e);for(;;){let f=d?e:h.default.join(i,e);try{let g=me.default.statSync(f,{throwIfNoEntry:!1});if(o==="file"&&g?.isFile()||o==="directory"&&g?.isDirectory())return f}catch{}if(i===c||i===a)break;i=h.default.dirname(i)}}async function W(e){let{cwd:r}=e||{},t=await ue("package.json",{cwd:r});return t&&J.default.dirname(t)}function v(e){let{cwd:r}=e||{},t=O("package.json",{cwd:r});return t&&J.default.dirname(t)}var{env:p}=process;function w(e){if(!e)return!1;switch(e.trim().toLowerCase()){case"1":case"true":case"yes":case"y":case"on":return!0;default:return!1}}var kr=p.GRIDDO_API_URL||p.API_URL,Fr=p.GRIDDO_PUBLIC_API_URL||p.PUBLIC_API_URL,ge=p.botEmail||p.GRIDDO_BOT_USER,he=p.botPassword||p.GRIDDO_BOT_PASSWORD,Gr=Number.parseInt(p.GRIDDO_API_CONCURRENCY_COUNT||"10"),De=w(p.GRIDDO_SKIP_BUILD_CHECKS),j=w(p.GRIDDO_BUILD_LOGS),ye=Number.parseInt(p.GRIDDO_BUILD_LOGS_BUFFER_SIZE||"500"),jr=w(p.GRIDDO_SSG_VERBOSE_LOGS),Ur=w(p.GRIDDO_SEARCH_FEATURE),Mr=p.GRIDDO_ASSET_PREFIX||p.ASSET_PREFIX,Hr=p.GRIDDO_REACT_APP_INSTANCE||p.REACT_APP_INSTANCE,Vr=w(p.GRIDDO_AI_EMBEDDINGS),Re=w(p.GRIDDO_VERBOSE_LOGS),Jr=w(p.GRIDDO_USE_DIST_BACKUP),Wr=w(p.GRIDDO_SSG_BUNDLE_ANALYZER),qr=w(p.GRIDDO_RENDER_DISABLE_LLMS_TXT);var s=class e{constructor(){}static verbose(...r){Re&&console.log(m.yellow("verbose"),m.dim(r.join(" ")))}static build(...r){j&&e.log(...r)}static info(...r){console.log(`${m.blue("info")} ${r.join(" ")}`)}static success(...r){console.log(`${m.green("success")} ${r.join(" ")}`)}static error(...r){console.error(`${m.red("error")} ${r.join(" ")}`)}static warn(...r){console.warn(`${m.yellow("warn")} ${r.join(" ")}`)}static log(...r){console.log(...r)}};var ze=v({cwd:U.default.resolve(__dirname,"../../..")})||"",Qe=U.default.join(ze,".griddo/cache"),Ee=U.default.join(Qe,"db.json");async function E(e=""){let r=e||Ee;try{return JSON.parse(await q.default.readFile(r,"utf-8"))}catch(t){throw s.error(`Failed to read DB file at ${r}:`,t),t}}async function P(e,r=""){let t=r||Ee;try{await q.default.writeFile(t,JSON.stringify(e,null," "))}catch(o){throw s.error(`Failed to write DB file at ${t}:`,o),o}}var K=l(require("node:fs/promises"));async function we(e){for(let r of e)try{await K.default.rm(r,{recursive:!0,force:!0}),s.verbose(`artifact removed: ${r}`)}catch(t){D(ie,t)}}async function b(e){try{return await K.default.access(e),!0}catch{return!1}}var C=class extends Error{constructor(r){super(r instanceof Error?r.message:String(r)),this.name="InternalCXError",this.stack=r instanceof Error?r.stack:""}};function D(e,r){let{error:t,message:o,expected:n,hint:i}=e,a=s.log(m.red(`[ ${t} ]`)),c=[n,i].filter(Boolean).join(`
2
2
  `);throw s.log(`
3
3
  ${a}
4
4
  ${o}