@griddo/cx 11.10.11-rc.0 → 11.10.11
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.
- package/build/commands/end-render.js +1 -1
- package/build/commands/end-render.js.map +2 -2
- package/build/commands/prepare-assets-directory.js +1 -1
- package/build/commands/prepare-assets-directory.js.map +2 -2
- package/build/commands/prepare-domains-render.js +4 -4
- package/build/commands/prepare-domains-render.js.map +2 -2
- package/build/commands/reset-render.js +1 -1
- package/build/commands/reset-render.js.map +2 -2
- package/build/commands/start-render.js +1 -1
- package/build/commands/start-render.js.map +2 -2
- package/build/commands/upload-search-content.js +11 -11
- package/build/commands/upload-search-content.js.map +2 -2
- package/build/index.js +2 -2
- package/package.json +2 -2
|
@@ -5,7 +5,7 @@ ${o}
|
|
|
5
5
|
${f}
|
|
6
6
|
|
|
7
7
|
${d.red("stack")}
|
|
8
|
-
${JSON.stringify(e,null,2)}`),new S(e)}async function de(r){try{await r()}catch(e){e instanceof S?i.error("Internal Griddo RenderError"):e instanceof Error?i.error(e.message):i.error(`An unexpected error occurred ${e}`);try{let o=await u(),{root:n}=o.paths;o.needsRollbackOnError?(i.info("Cleaning exports dir..."),i.verbose(`Deleting ${ce.default.join(n,"exports")}...`),await ae(o.currentRenderingDomain)):i.info("No rollback needed, skipping...")}catch{i.info("Early render stage, no db.json created yet...")}let t=await u();throw t.domains[t.currentRenderingDomain].isRendering=!1,t.domains[t.currentRenderingDomain].renderMode=$.ERROR,await C(t),e}}var g=process.env.GRIDDO_API_URL,Ge=process.env.GRIDDO_PUBLIC_API_URL,Ur=`${g}/ai/embeddings`,Mr=`${Ge}/alert`,Hr=`${g}/domains`,ke=`${g}/sites/all`,je=`${g}/page`,pe=`${g}/login_check`,Jr=`${g}/debug/reset-render`,Wr=`${g}/domains/robots`,Kr=`${g}/search`,Yr=`${g}/settings`,Ue=`${g}/site/`,fe=[Ue,"/build/end"];var le={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:"11.10.11
|
|
8
|
+
${JSON.stringify(e,null,2)}`),new S(e)}async function de(r){try{await r()}catch(e){e instanceof S?i.error("Internal Griddo RenderError"):e instanceof Error?i.error(e.message):i.error(`An unexpected error occurred ${e}`);try{let o=await u(),{root:n}=o.paths;o.needsRollbackOnError?(i.info("Cleaning exports dir..."),i.verbose(`Deleting ${ce.default.join(n,"exports")}...`),await ae(o.currentRenderingDomain)):i.info("No rollback needed, skipping...")}catch{i.info("Early render stage, no db.json created yet...")}let t=await u();throw t.domains[t.currentRenderingDomain].isRendering=!1,t.domains[t.currentRenderingDomain].renderMode=$.ERROR,await C(t),e}}var g=process.env.GRIDDO_API_URL,Ge=process.env.GRIDDO_PUBLIC_API_URL,Ur=`${g}/ai/embeddings`,Mr=`${Ge}/alert`,Hr=`${g}/domains`,ke=`${g}/sites/all`,je=`${g}/page`,pe=`${g}/login_check`,Jr=`${g}/debug/reset-render`,Wr=`${g}/domains/robots`,Kr=`${g}/search`,Yr=`${g}/settings`,Ue=`${g}/site/`,fe=[Ue,"/build/end"];var le={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:"11.10.11",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:"cbfc6265bef5216b8f34bef05fc6f122826c1dd8"};var N={"x-application-id":"griddo-cx","x-client-version":le.version,"x-client-name":"CX"};var M=class{headers;async login(){try{let e=await fetch(pe,{method:"POST",headers:Object.assign({},N,{"Content-Type":"application/json",Connection:"close"}),body:JSON.stringify({username:ee,password:re})});if(!e.ok)throw new Error("Error while login in the API");let{token:t}=await e.json();return this.headers={Authorization:`bearer ${t}`,"Cache-Control":"no-store"},this.headers}catch(e){w(ie,e)}}},O=new M;var F=c(require("node:path"));async function me(r){let e=await u();if(!e.domains[r])throw new Error(d.red(`[!] Error: Domain ${r} not found in DB`));if(!e.domains[r].renderMode)throw new Error(d.red(`[!] Error: Render mode not found for domain ${r}`));return{renderMode:e.domains[r].renderMode,reason:e.domains[r].renderModeReason}}async function T(r){let{domain:e,dbFilePath:t}=r||{},n=(await u(t)).paths;return{__root:n.root,__cache:F.default.join(n.cxCache,e||""),__components:n.components,__cx:n.cx,__sites:n.exportsDir,__exports:F.default.join(n.exportsDir,e||""),__exports_backup:F.default.join(n.exportsDirBackup,e||""),__ssg:n.ssg,__exports_dist:F.default.join(n.exportsDir,e||"","dist")}}async function ue(){let r=await u();return{griddoVersion:r.griddoVersion,buildReportFileName:r.buildReportFileName}}var Ee=c(require("node:crypto")),G=c(require("node:fs/promises")),J=c(require("node:path"));var he=c(require("node:fs/promises"));var b=[],ge=null,P=null,He=te;var Je=!B;function H(r){Je||(b.push(r.toString()),b.length>=He&&We().catch(e=>{i.error("Background log flush failed:",e)}))}async function We(){if(P&&await P,b.length===0||!ge)return;P=(async()=>{let e=[...b];b.length=0;try{await he.default.appendFile(ge,`${e.join(`
|
|
9
9
|
`)}
|
|
10
10
|
`)}catch(t){b.unshift(...e),i.error("Error flushing logs:",t)}})();try{await P}finally{P=null}}var{env:Ke}=process,{RETRY_WAIT_SECONDS:Ye="4",RETRY_ATTEMPTS:ye="4"}=Ke;async function we(r,e,t=""){let{endpoint:o,body:n,cacheKey:a="",attempt:p=1,headers:f,useApiCacheDir:m=!0,logToFile:_=!0}=r,I={endpoint:o,body:n,headers:f,cacheKey:a};if(a&&m){let A=new Date,l=await Ze(I);if(l){if(_){let h=De(l),x=h?`site: ${h}`:"",v=Re(Date.now()-A.getTime());H(`${e} (cache) ${x} ${o} - ${v}s ${t}`)}return l}}try{let A=new Date,l={method:e.toUpperCase(),headers:Object.assign({},N,f,O.headers)};e.toLowerCase()!=="get"&&n&&(l.body=JSON.stringify(n),l.headers||(l.headers={}),l.headers["Content-Type"]="application/json");let h=await fetch(o,l);if(!h.ok){if(h.status===404)return null;throw new Error(`HTTP ${h.status}: ${h.statusText}`)}let x=await h.json();if(_){let v=De(x),xe=v?`site: ${v}`:"",$e=Re(Date.now()-A.getTime());H(`${e} (fetch) ${xe} ${o} - ${$e}s ${t}`)}return m&&await Xe(I,x),x}catch(A){let l=A;if(p>parseInt(ye))throw i.log(`
|
|
11
11
|
Max attempts ${ye} reached
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../exporter/commands/end-render.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/shared/endpoints.ts", "../../package.json", "../../exporter/shared/headers.ts", "../../exporter/services/auth.ts", "../../exporter/services/render.ts", "../../exporter/services/api.ts", "../../exporter/core/logger.ts", "../../exporter/services/sites.ts"],
|
|
4
|
-
"sourcesContent": ["import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { throwError, withErrorHandler } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { AuthService } from \"../services/auth\";\nimport {\n\tgetRenderMetadataFromDB,\n\tgetRenderModeFromDB,\n\tgetRenderPathsHydratedWithDomainFromDB,\n} from \"../services/render\";\nimport { endSiteRender } from \"../services/sites\";\nimport { ArtifactError } from \"../shared/errors\";\nimport { RENDER_MODE, type Report } from \"../shared/types/render\";\n\nasync function getRenderReport(options: {\n\tdomain: string;\n\texportsSiteDir: string;\n\tbuildReportFileName: string;\n}) {\n\tconst { buildReportFileName, domain, exportsSiteDir } = options;\n\tconst buildReportFile = path.resolve(exportsSiteDir, domain, \"dist\", buildReportFileName);\n\n\tif (!(await pathExists(buildReportFile))) {\n\t\tGriddoLog.info(`Build report file \"${buildReportFile}\" not found.`);\n\t\tthrowError(ArtifactError);\n\t}\n\n\treturn JSON.parse(await fsp.readFile(buildReportFile, \"utf-8\")) as Report;\n}\n\nasync function endRender() {\n\tconst { buildReportFileName } = await getRenderMetadataFromDB();\n\tconst { __sites } = await getRenderPathsHydratedWithDomainFromDB();\n\n\tawait AuthService.login();\n\n\tconst [domain] = process.argv.slice(2);\n\n\tconst { renderMode, reason } = await getRenderModeFromDB(domain);\n\tif (renderMode === RENDER_MODE.IDLE) {\n\t\tGriddoLog.info(\n\t\t\t`(From Current Render) [${domain}]: Skipping end-render as it is marked as IDLE with the reason ${reason}.`,\n\t\t);\n\t\treturn;\n\t}\n\n\tconst report = await getRenderReport({\n\t\tdomain,\n\t\texportsSiteDir: __sites,\n\t\tbuildReportFileName,\n\t});\n\n\tGriddoLog.info(`Sending ending call to ${domain} sites`);\n\n\tfor (const site of report.sites) {\n\t\tsite.publishHashes = [...new Set(site.publishHashes)];\n\t\tsite.unpublishHashes = [...new Set(site.unpublishHashes)];\n\n\t\tconst { siteId, ...body } = site;\n\t\tGriddoLog.info(`Site (${siteId})`);\n\t\tawait endSiteRender(siteId, body);\n\t}\n}\n\nasync function main() {\n\tawait endRender();\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\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);\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_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", "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// 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\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.11-rc.0\",\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\": \"e3fdee4be8b2129da8b54ca6a9fc7e6bddc2ad80\"\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", "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\tconst currentCommit = execSync(\"git rev-parse HEAD\").toString().trim();\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", "import type {\n\tAPIRequest,\n\tAPIResponses,\n\tGetAPI,\n\tPostAPI,\n\tPutAPI,\n\tShowApiErrorOptions,\n} from \"../shared/types/api\";\nimport type { Petition } from \"../shared/types/global\";\n\nimport crypto from \"node:crypto\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { RenderError } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { addLogToBuffer } from \"../core/logger\";\nimport { DEFAULT_HEADERS } from \"../shared/headers\";\nimport { brush } from \"../shared/npm-modules/brush\";\nimport { AuthService } from \"./auth\";\nimport { getRenderPathsHydratedWithDomainFromDB } from \"./render\";\n\n// Envs\nconst { env } = process;\nconst { RETRY_WAIT_SECONDS = \"4\", RETRY_ATTEMPTS = \"4\" } = env;\n\n/**\n * Make a GET/PUT/POST request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns {Promise<T>} A promise that is resolved with the data from the API response.\n *\n * @example\n *\tconst response = await requestAPI<Site>(\n *\t\t{ endpoint: \"...\", cacheKey: \"...\", ... },\n *\t\t\"get\",\n *\t\t\"...\"\n *\t);\n */\nasync function requestAPI<T extends APIResponses>(\n\tprops: APIRequest,\n\tmethod: string,\n\tappendToLog = \"\",\n): Promise<T> {\n\tconst {\n\t\tendpoint,\n\t\tbody,\n\t\tcacheKey = \"\",\n\t\tattempt = 1,\n\t\theaders,\n\t\tuseApiCacheDir = true,\n\t\tlogToFile = true,\n\t} = props;\n\tconst cacheOptions = { endpoint, body, headers, cacheKey };\n\n\t// Cache\n\tif (cacheKey && useApiCacheDir) {\n\t\tconst start = new Date();\n\t\tconst cacheData = await searchCacheData<T>(cacheOptions);\n\n\t\tif (cacheData) {\n\t\t\tif (logToFile) {\n\t\t\t\tconst siteId = getSafeSiteId(cacheData);\n\t\t\t\tconst siteIdMsg = siteId ? `site: ${siteId}` : \"\";\n\t\t\t\tconst duration = msToSec(Date.now() - start.getTime());\n\t\t\t\taddLogToBuffer(`${method} (cache) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`);\n\t\t\t}\n\t\t\treturn cacheData;\n\t\t}\n\t}\n\n\t// Network\n\ttry {\n\t\tconst start = new Date();\n\n\t\t// Prepare fetch options\n\t\tconst fetchOptions: RequestInit = {\n\t\t\tmethod: method.toUpperCase(),\n\t\t\theaders: Object.assign({}, DEFAULT_HEADERS, headers, AuthService.headers) as Record<\n\t\t\t\tstring,\n\t\t\t\tstring\n\t\t\t>,\n\t\t};\n\n\t\t// Add body for non-GET requests\n\t\tif (method.toLowerCase() !== \"get\" && body) {\n\t\t\tfetchOptions.body = JSON.stringify(body);\n\t\t\tif (!fetchOptions.headers) fetchOptions.headers = {};\n\t\t\t(fetchOptions.headers as Record<string, string>)[\"Content-Type\"] = \"application/json\";\n\t\t}\n\n\t\tconst response = await fetch(endpoint, fetchOptions);\n\n\t\t// Handle non-2xx responses\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 404) {\n\t\t\t\t// @ts-expect-error page maybe will be 404\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tthrow new Error(`HTTP ${response.status}: ${response.statusText}`);\n\t\t}\n\n\t\tconst data: T = await response.json();\n\n\t\tif (logToFile) {\n\t\t\tconst siteId = getSafeSiteId(data);\n\t\t\tconst siteIdMsg = siteId ? `site: ${siteId}` : \"\";\n\t\t\tconst duration = msToSec(Date.now() - start.getTime());\n\t\t\taddLogToBuffer(`${method} (fetch) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`);\n\t\t}\n\n\t\tif (useApiCacheDir) {\n\t\t\tawait saveCache(cacheOptions, data);\n\t\t}\n\n\t\treturn data;\n\t} catch (e) {\n\t\tconst error = e as Error;\n\n\t\tif (attempt > parseInt(RETRY_ATTEMPTS)) {\n\t\t\tGriddoLog.log(`\nMax attempts ${RETRY_ATTEMPTS} reached\n--------------------------------------\n- ${method.toUpperCase()} ${endpoint}\n- BODY: ${JSON.stringify(body)}\n- HEADERS: ${JSON.stringify(headers)}\n- ERROR: ${error.message}\n--------------------------------------\n`);\n\t\t\tthrow new RenderError(error);\n\t\t}\n\n\t\tshowApiError(error, {\n\t\t\tcallInfo: { endpoint, body },\n\t\t});\n\n\t\tGriddoLog.warn(`Waiting for retry: ${method}`, endpoint);\n\n\t\tawait delay(parseInt(RETRY_WAIT_SECONDS) * 1000);\n\n\t\treturn requestAPI<T>(\n\t\t\t{\n\t\t\t\tendpoint,\n\t\t\t\tbody,\n\t\t\t\theaders,\n\t\t\t\tcacheKey,\n\t\t\t\tattempt: attempt + 1,\n\t\t\t},\n\t\t\tmethod,\n\t\t\tappendToLog,\n\t\t);\n\t}\n}\n\n/**\n * Make a GET request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns A promise that is resolved with the data from the API response.\n */\nasync function getApi<T extends APIResponses>(props: GetAPI) {\n\treturn requestAPI<T>(props, \"get\");\n}\n\n/**\n * Make a PUT request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns A promise that is resolved with the data from the API response.\n */\nasync function putApi<T extends APIResponses>(props: PutAPI) {\n\treturn requestAPI<T>(props, \"put\");\n}\n\n/**\n * Make a POST request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns A promise that is resolved with the data from the API response.\n */\nasync function postApi<T extends APIResponses>(props: PostAPI) {\n\tconst { endpoint, body, headers } = props;\n\tconst referenceFieldBodyParams =\n\t\tendpoint.endsWith(\"/distributor\") &&\n\t\t`# ReferenceField body: ${JSON.stringify(body)} lang: ${JSON.stringify(headers?.lang)}`;\n\n\treturn requestAPI<T>(props, \"post\", referenceFieldBodyParams || \"\");\n}\n\n/**\n * Shows an API error through the terminal.\n */\nfunction showApiError(error: Error, options: ShowApiErrorOptions) {\n\tconst { message, stack } = error;\n\tconst { callInfo } = options;\n\tconst callInfoArray = [];\n\n\tfor (const item of Object.keys(callInfo) as (keyof typeof callInfo)[]) {\n\t\tcallInfoArray.push(\n\t\t\t`${item}: ${\n\t\t\t\ttypeof callInfo[item] === \"object\" ? JSON.stringify(callInfo[item]) : callInfo[item]\n\t\t\t}`,\n\t\t);\n\t}\n\n\t// Compose the errors output\n\tconst callInfoStr = callInfoArray.join(\"\\n\");\n\tconst errorDetailsStr = `${message}\\n${stack}`;\n\n\t// Print the error\n\tGriddoLog.warn(\n\t\tbrush.red(`\n=============\n\n{ Call info }\n${callInfoStr}\n\n{ Error details }\n${errorDetailsStr}\n\n=============\n`),\n\t);\n}\n\n/**\n * Return a siteID from a response object if exist\n * @param response A response object\n */\nfunction getSafeSiteId(response: APIResponses) {\n\tif (typeof response !== \"object\" || response === null || Array.isArray(response)) {\n\t\treturn undefined;\n\t}\n\n\treturn \"site\" in response && response.site ? response.site : undefined;\n}\n\n/**\n * Custom delay using the \"promise hack\",\n *\n * @param ms Amount of miliseconds to be delayed\n */\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((res) => setTimeout(res, ms));\n}\n\n/**\n * Converts milliseconds to seconds with a fixed number of decimals.\n *\n * @param ms The number in milliseconds.\n * @param fixed The amount of fixed decimals.\n * @returns The converted number in seconds with the fixed number of decimals.\n */\nfunction msToSec(ms: number, decimals = 3): number {\n\treturn Number.parseFloat((ms / 1000).toFixed(decimals));\n}\n\n/**\n * Generate a filename with a hash using a Petition object\n * @param petition An object\n */\nasync function generateFilenameWithHash(petition: Petition) {\n\tconst { __root } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst apiCacheDir = path.join(__root, \"apiCache\");\n\n\tconst hashSum = crypto.createHash(\"sha256\");\n\thashSum.update(JSON.stringify(petition));\n\n\treturn `${apiCacheDir}/${hashSum.digest(\"hex\")}`;\n}\n\n/**\n * Save a file using a hash name.\n *\n * @param petition An object.\n * @param content Content to be saved.\n */\nasync function saveCache<T>(petition: Petition, content: T) {\n\tconst stringContent = typeof content === \"string\" ? content : JSON.stringify(content);\n\tconst filename = await generateFilenameWithHash(petition);\n\tconst filepath = path.dirname(filename);\n\n\tif (!(await pathExists(filepath))) {\n\t\tawait fsp.mkdir(filepath, { recursive: true });\n\t}\n\n\tawait fsp.writeFile(filename, stringContent, \"utf8\");\n}\n\n/**\n * Search in the `apiCache` dir for a file using the petition as hash generator.\n * Return the file content if found or null if not.\n *\n * @param petition An object\n */\nasync function searchCacheData<T>(petition: Petition) {\n\ttry {\n\t\tconst file = await generateFilenameWithHash(petition);\n\t\tconst fileContent = await fsp.readFile(file, \"utf8\");\n\t\tconst jsonData = JSON.parse(fileContent) as T;\n\n\t\treturn jsonData;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport { getApi as get, postApi as post, putApi as put };\n", "import type { RenderDB } from \"../shared/types/render\";\n\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { GRIDDO_BUILD_LOGS, GRIDDO_BUILD_LOGS_BUFFER_SIZE } from \"../shared/envs\";\nimport { readDB } from \"./db\";\nimport { GriddoLog } from \"./GriddoLog\";\n\nconst logBuffer: string[] = [];\nlet logFilePath: string | null = null;\nlet flushPromise: Promise<void> | null = null;\nconst LOG_BUFFER_FLUSH_THRESHOLD = GRIDDO_BUILD_LOGS_BUFFER_SIZE;\nconst LOG_FILENAME = \"render-detail-log.txt\";\nconst LOG_TO_FILE_IS_DISABLED = !GRIDDO_BUILD_LOGS;\n\nlet dbData: RenderDB | null = null;\n\n// Universal data cache for this module...\nasync function getDBData() {\n\tif (!dbData) {\n\t\tdbData = await readDB();\n\t}\n\treturn dbData;\n}\n\nasync function initializeLogFile() {\n\tif (LOG_TO_FILE_IS_DISABLED) {\n\t\treturn;\n\t}\n\n\tconst data = await getDBData();\n\tlogFilePath = path.join(data.paths.root, LOG_FILENAME);\n\n\tawait fsp.rm(logFilePath, { force: true });\n}\n\nfunction addLogToBuffer(lineContent: string) {\n\tif (LOG_TO_FILE_IS_DISABLED) {\n\t\treturn;\n\t}\n\n\tlogBuffer.push(lineContent.toString());\n\n\tif (logBuffer.length >= LOG_BUFFER_FLUSH_THRESHOLD) {\n\t\t// Fire-and-forget flush to avoid blocking the main thread.\n\t\tflushLogsToFile().catch((error) => {\n\t\t\tGriddoLog.error(\"Background log flush failed:\", error);\n\t\t});\n\t}\n}\n\n/**\n * Vuelca el contenido del buffer de logs al archivo de logs en disco.\n * Si el buffer est\u00E1 vac\u00EDo, ya se est\u00E1 volcando, o no hay ruta de archivo, no hace nada.\n * Si ocurre un error al escribir, los logs se reinsertan al buffer para reintentar en el siguiente flush.\n */\nasync function flushLogsToFile() {\n\t// Si ya hay un volcado en curso, espera a que termine.\n\tif (flushPromise) {\n\t\tawait flushPromise;\n\t}\n\n\tif (logBuffer.length === 0 || !logFilePath) {\n\t\treturn;\n\t}\n\n\tconst performFlush = async () => {\n\t\tconst logsToFlush = [...logBuffer];\n\t\tlogBuffer.length = 0;\n\n\t\ttry {\n\t\t\tawait fsp.appendFile(logFilePath!, `${logsToFlush.join(\"\\n\")}\\n`);\n\t\t} catch (error) {\n\t\t\tlogBuffer.unshift(...logsToFlush);\n\t\t\tGriddoLog.error(\"Error flushing logs:\", error);\n\t\t\t// No relanzamos el error para no detener el \"fire-and-forget\"\n\t\t}\n\t};\n\n\tflushPromise = performFlush();\n\n\ttry {\n\t\tawait flushPromise;\n\t} finally {\n\t\tflushPromise = null;\n\t}\n}\n\n/**\n * Copia el archivo de log detallado de renderizado (\"render-detail-log.txt\")\n * desde el directorio ra\u00EDz del proyecto al directorio de logs del dominio en exports,\n * usando una marca de tiempo en el nombre de destino.\n * Si el archivo no existe, ignora el error salvo que sea distinto de ENOENT.\n *\n * @param domain - Nombre del dominio para el que se guarda el log.\n */\nasync function saveDetailRenderLog(domain: string) {\n\tawait flushLogsToFile();\n\n\tconst data = await getDBData();\n\n\tconst dateString = getFormattedDateTime();\n\tconst debugDir = path.join(data.paths.exportsDir, domain, \"logs\");\n\n\tawait fsp.mkdir(debugDir, { recursive: true });\n\n\tconst src = path.join(data.paths.root, LOG_FILENAME);\n\tconst dst = path.join(debugDir, `${dateString}-${LOG_FILENAME}`);\n\n\t// Move log to exports\n\ttry {\n\t\tawait fsp.cp(src, dst);\n\t} catch (error) {\n\t\t// It's possible the file doesn't exist if GRIDDO_BUILD_LOGS is false\n\t\t// or if no logs were ever added.\n\t\tif (error instanceof Error && \"code\" in error && error.code !== \"ENOENT\") {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nfunction getFormattedDateTime() {\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\n\tconst hours = String(now.getHours()).padStart(2, \"0\");\n\tconst minutes = String(now.getMinutes()).padStart(2, \"0\");\n\tconst seconds = String(now.getSeconds()).padStart(2, \"0\");\n\n\t// Formato recomendado para ordenaci\u00F3n de archivos: YYYY-MM-DD_HH-mm-ss\n\treturn `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;\n}\n\nexport { addLogToBuffer, flushLogsToFile, initializeLogFile, saveDetailRenderLog };\n", "import type { Core } from \"@griddo/core\";\nimport type {\n\tAllSitesReponse,\n\tEndPageInfoResponse,\n\tEndSiteRenderBody,\n\tLanguagesResponse,\n\tPageResponse,\n\tReferenceFieldBody,\n\tReferenceFieldResponse,\n\tSitemapAPIResponse,\n\tSocialsResponse,\n\tStartPageRenderResponse,\n} from \"../shared/types/api\";\nimport type { Site } from \"../shared/types/sites\";\n\nimport {\n\tBUILD_END,\n\tBUILD_START,\n\tGET_ALL,\n\tGET_PAGE,\n\tGET_REFERENCE_FIELD_DATA,\n\tGET_SITEMAP,\n\tINFO,\n\tLANGUAGES,\n\tSOCIALS,\n} from \"../shared/endpoints\";\nimport { get, post } from \"./api\";\n\n/**\n * Get a list of site objects.\n */\nasync function getAllSites(domain: string) {\n\treturn get<AllSitesReponse>({\n\t\tendpoint: `${GET_ALL}?domainSlug=${domain}`,\n\t});\n}\n\n/**\n * Get a list of site objects from a domain.\n */\nasync function getAllSitesFromDomain(domain: string) {\n\tconst allSites = await get<AllSitesReponse>({ endpoint: GET_ALL });\n\n\tif (allSites.length) {\n\t\tfor (const site of allSites) {\n\t\t\tconst { items } = await getSiteLanguages(site.id);\n\n\t\t\t// A\u00F1adimos la prop domains con el dominio \"cocinado\" con los\n\t\t\t// idiomas y teniendo en cuenta solo el dominio actual.\n\t\t\tsite.domains = items\n\t\t\t\t.filter(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\titem.domain && (item.domain.slug === domain || item.domain.slug === `/${domain}`),\n\t\t\t\t)\n\t\t\t\t.map((item) => ({ [item.id]: `${item.domain.slug}${item.path}` }));\n\t\t}\n\t}\n\n\treturn allSites.filter((site) => site.domains.length > 0);\n}\n\n/**\n * Fetch a page object from API.\n */\nasync function getPage(id: number, cacheKey: string) {\n\treturn get<PageResponse>({\n\t\tendpoint: `${GET_PAGE}/${id}`,\n\t\tcacheKey,\n\t});\n}\n\n/**\n * Get site info\n */\nasync function getSiteInfo(id: number, cacheKey = \"\") {\n\tconst [prefix, suffix] = INFO;\n\n\treturn get<Site>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tcacheKey,\n\t});\n}\n\nasync function getSiteLanguages(id: number, cacheKey = \"\") {\n\tconst [prefix, suffix] = LANGUAGES;\n\n\treturn get<LanguagesResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tcacheKey,\n\t});\n}\n\nasync function startSiteRender(id: number) {\n\tconst [prefix, suffix] = BUILD_START;\n\n\treturn get<StartPageRenderResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t});\n}\n\n/**\n * Send the end signal to API for a render site.\n */\nasync function endSiteRender(id: number, body: EndSiteRenderBody) {\n\tconst [prefix, suffix] = BUILD_END;\n\n\tawait post<EndPageInfoResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tbody,\n\t\tuseApiCacheDir: false,\n\t\tlogToFile: false,\n\t});\n}\n\nasync function getReferenceFieldSiteData(\n\tpage: Core.Page,\n\tbody: ReferenceFieldBody,\n\tcacheKey: string,\n\tdataSiteId?: number,\n\tdataLangID?: number,\n) {\n\tconst [prefix, suffix] = GET_REFERENCE_FIELD_DATA;\n\tconst site = dataSiteId || page.site;\n\tconst lang = dataLangID || page.language;\n\n\treturn post<ReferenceFieldResponse>({\n\t\tendpoint: `${prefix}${site}${suffix}`,\n\t\tbody,\n\t\theaders: { lang },\n\t\tcacheKey,\n\t});\n}\n\nasync function getSitemap(options: { siteId: number; headers?: Record<string, string> }) {\n\tconst { siteId, headers } = options;\n\tconst [prefix, suffix] = GET_SITEMAP;\n\n\treturn get<SitemapAPIResponse>({\n\t\tendpoint: `${prefix}${siteId}${suffix}`,\n\t\theaders,\n\t});\n}\n\nasync function getSiteSocials(id: number, cacheKey = \"\") {\n\tconst [prefix, suffix] = SOCIALS;\n\n\treturn get<SocialsResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tcacheKey,\n\t});\n}\n\nexport {\n\tendSiteRender,\n\tgetAllSites,\n\tgetAllSitesFromDomain,\n\tgetPage,\n\tgetReferenceFieldSiteData,\n\tgetSiteInfo,\n\tgetSiteLanguages,\n\tgetSitemap,\n\tgetSiteSocials,\n\tstartSiteRender,\n};\n"],
|
|
5
|
-
"mappings": "oeAAA,IAAAA,GAAgB,+BAChBC,GAAiB,wBCCjB,IAAAC,GAAiB,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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AAE,OAAAC,EAAQ,GAAGC,CAAK,EAAIF,EAC5Bd,EAAU,KAAK,SAASe,CAAM,GAAG,EACjC,MAAME,GAAcF,EAAQC,CAAI,CACjC,CACD,CAEA,eAAeE,IAAO,CACrB,MAAMd,GAAU,CACjB,CAEAe,GAAiBD,EAAI",
|
|
4
|
+
"sourcesContent": ["import fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { throwError, withErrorHandler } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { AuthService } from \"../services/auth\";\nimport {\n\tgetRenderMetadataFromDB,\n\tgetRenderModeFromDB,\n\tgetRenderPathsHydratedWithDomainFromDB,\n} from \"../services/render\";\nimport { endSiteRender } from \"../services/sites\";\nimport { ArtifactError } from \"../shared/errors\";\nimport { RENDER_MODE, type Report } from \"../shared/types/render\";\n\nasync function getRenderReport(options: {\n\tdomain: string;\n\texportsSiteDir: string;\n\tbuildReportFileName: string;\n}) {\n\tconst { buildReportFileName, domain, exportsSiteDir } = options;\n\tconst buildReportFile = path.resolve(exportsSiteDir, domain, \"dist\", buildReportFileName);\n\n\tif (!(await pathExists(buildReportFile))) {\n\t\tGriddoLog.info(`Build report file \"${buildReportFile}\" not found.`);\n\t\tthrowError(ArtifactError);\n\t}\n\n\treturn JSON.parse(await fsp.readFile(buildReportFile, \"utf-8\")) as Report;\n}\n\nasync function endRender() {\n\tconst { buildReportFileName } = await getRenderMetadataFromDB();\n\tconst { __sites } = await getRenderPathsHydratedWithDomainFromDB();\n\n\tawait AuthService.login();\n\n\tconst [domain] = process.argv.slice(2);\n\n\tconst { renderMode, reason } = await getRenderModeFromDB(domain);\n\tif (renderMode === RENDER_MODE.IDLE) {\n\t\tGriddoLog.info(\n\t\t\t`(From Current Render) [${domain}]: Skipping end-render as it is marked as IDLE with the reason ${reason}.`,\n\t\t);\n\t\treturn;\n\t}\n\n\tconst report = await getRenderReport({\n\t\tdomain,\n\t\texportsSiteDir: __sites,\n\t\tbuildReportFileName,\n\t});\n\n\tGriddoLog.info(`Sending ending call to ${domain} sites`);\n\n\tfor (const site of report.sites) {\n\t\tsite.publishHashes = [...new Set(site.publishHashes)];\n\t\tsite.unpublishHashes = [...new Set(site.unpublishHashes)];\n\n\t\tconst { siteId, ...body } = site;\n\t\tGriddoLog.info(`Site (${siteId})`);\n\t\tawait endSiteRender(siteId, body);\n\t}\n}\n\nasync function main() {\n\tawait endRender();\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\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);\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_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", "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// 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\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.11\",\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\": \"cbfc6265bef5216b8f34bef05fc6f122826c1dd8\"\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", "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\tconst currentCommit = execSync(\"git rev-parse HEAD\").toString().trim();\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", "import type {\n\tAPIRequest,\n\tAPIResponses,\n\tGetAPI,\n\tPostAPI,\n\tPutAPI,\n\tShowApiErrorOptions,\n} from \"../shared/types/api\";\nimport type { Petition } from \"../shared/types/global\";\n\nimport crypto from \"node:crypto\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { RenderError } from \"../core/errors\";\nimport { pathExists } from \"../core/fs\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { addLogToBuffer } from \"../core/logger\";\nimport { DEFAULT_HEADERS } from \"../shared/headers\";\nimport { brush } from \"../shared/npm-modules/brush\";\nimport { AuthService } from \"./auth\";\nimport { getRenderPathsHydratedWithDomainFromDB } from \"./render\";\n\n// Envs\nconst { env } = process;\nconst { RETRY_WAIT_SECONDS = \"4\", RETRY_ATTEMPTS = \"4\" } = env;\n\n/**\n * Make a GET/PUT/POST request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns {Promise<T>} A promise that is resolved with the data from the API response.\n *\n * @example\n *\tconst response = await requestAPI<Site>(\n *\t\t{ endpoint: \"...\", cacheKey: \"...\", ... },\n *\t\t\"get\",\n *\t\t\"...\"\n *\t);\n */\nasync function requestAPI<T extends APIResponses>(\n\tprops: APIRequest,\n\tmethod: string,\n\tappendToLog = \"\",\n): Promise<T> {\n\tconst {\n\t\tendpoint,\n\t\tbody,\n\t\tcacheKey = \"\",\n\t\tattempt = 1,\n\t\theaders,\n\t\tuseApiCacheDir = true,\n\t\tlogToFile = true,\n\t} = props;\n\tconst cacheOptions = { endpoint, body, headers, cacheKey };\n\n\t// Cache\n\tif (cacheKey && useApiCacheDir) {\n\t\tconst start = new Date();\n\t\tconst cacheData = await searchCacheData<T>(cacheOptions);\n\n\t\tif (cacheData) {\n\t\t\tif (logToFile) {\n\t\t\t\tconst siteId = getSafeSiteId(cacheData);\n\t\t\t\tconst siteIdMsg = siteId ? `site: ${siteId}` : \"\";\n\t\t\t\tconst duration = msToSec(Date.now() - start.getTime());\n\t\t\t\taddLogToBuffer(`${method} (cache) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`);\n\t\t\t}\n\t\t\treturn cacheData;\n\t\t}\n\t}\n\n\t// Network\n\ttry {\n\t\tconst start = new Date();\n\n\t\t// Prepare fetch options\n\t\tconst fetchOptions: RequestInit = {\n\t\t\tmethod: method.toUpperCase(),\n\t\t\theaders: Object.assign({}, DEFAULT_HEADERS, headers, AuthService.headers) as Record<\n\t\t\t\tstring,\n\t\t\t\tstring\n\t\t\t>,\n\t\t};\n\n\t\t// Add body for non-GET requests\n\t\tif (method.toLowerCase() !== \"get\" && body) {\n\t\t\tfetchOptions.body = JSON.stringify(body);\n\t\t\tif (!fetchOptions.headers) fetchOptions.headers = {};\n\t\t\t(fetchOptions.headers as Record<string, string>)[\"Content-Type\"] = \"application/json\";\n\t\t}\n\n\t\tconst response = await fetch(endpoint, fetchOptions);\n\n\t\t// Handle non-2xx responses\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 404) {\n\t\t\t\t// @ts-expect-error page maybe will be 404\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tthrow new Error(`HTTP ${response.status}: ${response.statusText}`);\n\t\t}\n\n\t\tconst data: T = await response.json();\n\n\t\tif (logToFile) {\n\t\t\tconst siteId = getSafeSiteId(data);\n\t\t\tconst siteIdMsg = siteId ? `site: ${siteId}` : \"\";\n\t\t\tconst duration = msToSec(Date.now() - start.getTime());\n\t\t\taddLogToBuffer(`${method} (fetch) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`);\n\t\t}\n\n\t\tif (useApiCacheDir) {\n\t\t\tawait saveCache(cacheOptions, data);\n\t\t}\n\n\t\treturn data;\n\t} catch (e) {\n\t\tconst error = e as Error;\n\n\t\tif (attempt > parseInt(RETRY_ATTEMPTS)) {\n\t\t\tGriddoLog.log(`\nMax attempts ${RETRY_ATTEMPTS} reached\n--------------------------------------\n- ${method.toUpperCase()} ${endpoint}\n- BODY: ${JSON.stringify(body)}\n- HEADERS: ${JSON.stringify(headers)}\n- ERROR: ${error.message}\n--------------------------------------\n`);\n\t\t\tthrow new RenderError(error);\n\t\t}\n\n\t\tshowApiError(error, {\n\t\t\tcallInfo: { endpoint, body },\n\t\t});\n\n\t\tGriddoLog.warn(`Waiting for retry: ${method}`, endpoint);\n\n\t\tawait delay(parseInt(RETRY_WAIT_SECONDS) * 1000);\n\n\t\treturn requestAPI<T>(\n\t\t\t{\n\t\t\t\tendpoint,\n\t\t\t\tbody,\n\t\t\t\theaders,\n\t\t\t\tcacheKey,\n\t\t\t\tattempt: attempt + 1,\n\t\t\t},\n\t\t\tmethod,\n\t\t\tappendToLog,\n\t\t);\n\t}\n}\n\n/**\n * Make a GET request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns A promise that is resolved with the data from the API response.\n */\nasync function getApi<T extends APIResponses>(props: GetAPI) {\n\treturn requestAPI<T>(props, \"get\");\n}\n\n/**\n * Make a PUT request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns A promise that is resolved with the data from the API response.\n */\nasync function putApi<T extends APIResponses>(props: PutAPI) {\n\treturn requestAPI<T>(props, \"put\");\n}\n\n/**\n * Make a POST request to the Griddo API.\n *\n * @template T Response Type returned.\n * @returns A promise that is resolved with the data from the API response.\n */\nasync function postApi<T extends APIResponses>(props: PostAPI) {\n\tconst { endpoint, body, headers } = props;\n\tconst referenceFieldBodyParams =\n\t\tendpoint.endsWith(\"/distributor\") &&\n\t\t`# ReferenceField body: ${JSON.stringify(body)} lang: ${JSON.stringify(headers?.lang)}`;\n\n\treturn requestAPI<T>(props, \"post\", referenceFieldBodyParams || \"\");\n}\n\n/**\n * Shows an API error through the terminal.\n */\nfunction showApiError(error: Error, options: ShowApiErrorOptions) {\n\tconst { message, stack } = error;\n\tconst { callInfo } = options;\n\tconst callInfoArray = [];\n\n\tfor (const item of Object.keys(callInfo) as (keyof typeof callInfo)[]) {\n\t\tcallInfoArray.push(\n\t\t\t`${item}: ${\n\t\t\t\ttypeof callInfo[item] === \"object\" ? JSON.stringify(callInfo[item]) : callInfo[item]\n\t\t\t}`,\n\t\t);\n\t}\n\n\t// Compose the errors output\n\tconst callInfoStr = callInfoArray.join(\"\\n\");\n\tconst errorDetailsStr = `${message}\\n${stack}`;\n\n\t// Print the error\n\tGriddoLog.warn(\n\t\tbrush.red(`\n=============\n\n{ Call info }\n${callInfoStr}\n\n{ Error details }\n${errorDetailsStr}\n\n=============\n`),\n\t);\n}\n\n/**\n * Return a siteID from a response object if exist\n * @param response A response object\n */\nfunction getSafeSiteId(response: APIResponses) {\n\tif (typeof response !== \"object\" || response === null || Array.isArray(response)) {\n\t\treturn undefined;\n\t}\n\n\treturn \"site\" in response && response.site ? response.site : undefined;\n}\n\n/**\n * Custom delay using the \"promise hack\",\n *\n * @param ms Amount of miliseconds to be delayed\n */\nfunction delay(ms: number): Promise<void> {\n\treturn new Promise((res) => setTimeout(res, ms));\n}\n\n/**\n * Converts milliseconds to seconds with a fixed number of decimals.\n *\n * @param ms The number in milliseconds.\n * @param fixed The amount of fixed decimals.\n * @returns The converted number in seconds with the fixed number of decimals.\n */\nfunction msToSec(ms: number, decimals = 3): number {\n\treturn Number.parseFloat((ms / 1000).toFixed(decimals));\n}\n\n/**\n * Generate a filename with a hash using a Petition object\n * @param petition An object\n */\nasync function generateFilenameWithHash(petition: Petition) {\n\tconst { __root } = await getRenderPathsHydratedWithDomainFromDB();\n\tconst apiCacheDir = path.join(__root, \"apiCache\");\n\n\tconst hashSum = crypto.createHash(\"sha256\");\n\thashSum.update(JSON.stringify(petition));\n\n\treturn `${apiCacheDir}/${hashSum.digest(\"hex\")}`;\n}\n\n/**\n * Save a file using a hash name.\n *\n * @param petition An object.\n * @param content Content to be saved.\n */\nasync function saveCache<T>(petition: Petition, content: T) {\n\tconst stringContent = typeof content === \"string\" ? content : JSON.stringify(content);\n\tconst filename = await generateFilenameWithHash(petition);\n\tconst filepath = path.dirname(filename);\n\n\tif (!(await pathExists(filepath))) {\n\t\tawait fsp.mkdir(filepath, { recursive: true });\n\t}\n\n\tawait fsp.writeFile(filename, stringContent, \"utf8\");\n}\n\n/**\n * Search in the `apiCache` dir for a file using the petition as hash generator.\n * Return the file content if found or null if not.\n *\n * @param petition An object\n */\nasync function searchCacheData<T>(petition: Petition) {\n\ttry {\n\t\tconst file = await generateFilenameWithHash(petition);\n\t\tconst fileContent = await fsp.readFile(file, \"utf8\");\n\t\tconst jsonData = JSON.parse(fileContent) as T;\n\n\t\treturn jsonData;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport { getApi as get, postApi as post, putApi as put };\n", "import type { RenderDB } from \"../shared/types/render\";\n\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { GRIDDO_BUILD_LOGS, GRIDDO_BUILD_LOGS_BUFFER_SIZE } from \"../shared/envs\";\nimport { readDB } from \"./db\";\nimport { GriddoLog } from \"./GriddoLog\";\n\nconst logBuffer: string[] = [];\nlet logFilePath: string | null = null;\nlet flushPromise: Promise<void> | null = null;\nconst LOG_BUFFER_FLUSH_THRESHOLD = GRIDDO_BUILD_LOGS_BUFFER_SIZE;\nconst LOG_FILENAME = \"render-detail-log.txt\";\nconst LOG_TO_FILE_IS_DISABLED = !GRIDDO_BUILD_LOGS;\n\nlet dbData: RenderDB | null = null;\n\n// Universal data cache for this module...\nasync function getDBData() {\n\tif (!dbData) {\n\t\tdbData = await readDB();\n\t}\n\treturn dbData;\n}\n\nasync function initializeLogFile() {\n\tif (LOG_TO_FILE_IS_DISABLED) {\n\t\treturn;\n\t}\n\n\tconst data = await getDBData();\n\tlogFilePath = path.join(data.paths.root, LOG_FILENAME);\n\n\tawait fsp.rm(logFilePath, { force: true });\n}\n\nfunction addLogToBuffer(lineContent: string) {\n\tif (LOG_TO_FILE_IS_DISABLED) {\n\t\treturn;\n\t}\n\n\tlogBuffer.push(lineContent.toString());\n\n\tif (logBuffer.length >= LOG_BUFFER_FLUSH_THRESHOLD) {\n\t\t// Fire-and-forget flush to avoid blocking the main thread.\n\t\tflushLogsToFile().catch((error) => {\n\t\t\tGriddoLog.error(\"Background log flush failed:\", error);\n\t\t});\n\t}\n}\n\n/**\n * Vuelca el contenido del buffer de logs al archivo de logs en disco.\n * Si el buffer est\u00E1 vac\u00EDo, ya se est\u00E1 volcando, o no hay ruta de archivo, no hace nada.\n * Si ocurre un error al escribir, los logs se reinsertan al buffer para reintentar en el siguiente flush.\n */\nasync function flushLogsToFile() {\n\t// Si ya hay un volcado en curso, espera a que termine.\n\tif (flushPromise) {\n\t\tawait flushPromise;\n\t}\n\n\tif (logBuffer.length === 0 || !logFilePath) {\n\t\treturn;\n\t}\n\n\tconst performFlush = async () => {\n\t\tconst logsToFlush = [...logBuffer];\n\t\tlogBuffer.length = 0;\n\n\t\ttry {\n\t\t\tawait fsp.appendFile(logFilePath!, `${logsToFlush.join(\"\\n\")}\\n`);\n\t\t} catch (error) {\n\t\t\tlogBuffer.unshift(...logsToFlush);\n\t\t\tGriddoLog.error(\"Error flushing logs:\", error);\n\t\t\t// No relanzamos el error para no detener el \"fire-and-forget\"\n\t\t}\n\t};\n\n\tflushPromise = performFlush();\n\n\ttry {\n\t\tawait flushPromise;\n\t} finally {\n\t\tflushPromise = null;\n\t}\n}\n\n/**\n * Copia el archivo de log detallado de renderizado (\"render-detail-log.txt\")\n * desde el directorio ra\u00EDz del proyecto al directorio de logs del dominio en exports,\n * usando una marca de tiempo en el nombre de destino.\n * Si el archivo no existe, ignora el error salvo que sea distinto de ENOENT.\n *\n * @param domain - Nombre del dominio para el que se guarda el log.\n */\nasync function saveDetailRenderLog(domain: string) {\n\tawait flushLogsToFile();\n\n\tconst data = await getDBData();\n\n\tconst dateString = getFormattedDateTime();\n\tconst debugDir = path.join(data.paths.exportsDir, domain, \"logs\");\n\n\tawait fsp.mkdir(debugDir, { recursive: true });\n\n\tconst src = path.join(data.paths.root, LOG_FILENAME);\n\tconst dst = path.join(debugDir, `${dateString}-${LOG_FILENAME}`);\n\n\t// Move log to exports\n\ttry {\n\t\tawait fsp.cp(src, dst);\n\t} catch (error) {\n\t\t// It's possible the file doesn't exist if GRIDDO_BUILD_LOGS is false\n\t\t// or if no logs were ever added.\n\t\tif (error instanceof Error && \"code\" in error && error.code !== \"ENOENT\") {\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nfunction getFormattedDateTime() {\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\n\tconst hours = String(now.getHours()).padStart(2, \"0\");\n\tconst minutes = String(now.getMinutes()).padStart(2, \"0\");\n\tconst seconds = String(now.getSeconds()).padStart(2, \"0\");\n\n\t// Formato recomendado para ordenaci\u00F3n de archivos: YYYY-MM-DD_HH-mm-ss\n\treturn `${year}-${month}-${day}_${hours}-${minutes}-${seconds}`;\n}\n\nexport { addLogToBuffer, flushLogsToFile, initializeLogFile, saveDetailRenderLog };\n", "import type { Core } from \"@griddo/core\";\nimport type {\n\tAllSitesReponse,\n\tEndPageInfoResponse,\n\tEndSiteRenderBody,\n\tLanguagesResponse,\n\tPageResponse,\n\tReferenceFieldBody,\n\tReferenceFieldResponse,\n\tSitemapAPIResponse,\n\tSocialsResponse,\n\tStartPageRenderResponse,\n} from \"../shared/types/api\";\nimport type { Site } from \"../shared/types/sites\";\n\nimport {\n\tBUILD_END,\n\tBUILD_START,\n\tGET_ALL,\n\tGET_PAGE,\n\tGET_REFERENCE_FIELD_DATA,\n\tGET_SITEMAP,\n\tINFO,\n\tLANGUAGES,\n\tSOCIALS,\n} from \"../shared/endpoints\";\nimport { get, post } from \"./api\";\n\n/**\n * Get a list of site objects.\n */\nasync function getAllSites(domain: string) {\n\treturn get<AllSitesReponse>({\n\t\tendpoint: `${GET_ALL}?domainSlug=${domain}`,\n\t});\n}\n\n/**\n * Get a list of site objects from a domain.\n */\nasync function getAllSitesFromDomain(domain: string) {\n\tconst allSites = await get<AllSitesReponse>({ endpoint: GET_ALL });\n\n\tif (allSites.length) {\n\t\tfor (const site of allSites) {\n\t\t\tconst { items } = await getSiteLanguages(site.id);\n\n\t\t\t// A\u00F1adimos la prop domains con el dominio \"cocinado\" con los\n\t\t\t// idiomas y teniendo en cuenta solo el dominio actual.\n\t\t\tsite.domains = items\n\t\t\t\t.filter(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\titem.domain && (item.domain.slug === domain || item.domain.slug === `/${domain}`),\n\t\t\t\t)\n\t\t\t\t.map((item) => ({ [item.id]: `${item.domain.slug}${item.path}` }));\n\t\t}\n\t}\n\n\treturn allSites.filter((site) => site.domains.length > 0);\n}\n\n/**\n * Fetch a page object from API.\n */\nasync function getPage(id: number, cacheKey: string) {\n\treturn get<PageResponse>({\n\t\tendpoint: `${GET_PAGE}/${id}`,\n\t\tcacheKey,\n\t});\n}\n\n/**\n * Get site info\n */\nasync function getSiteInfo(id: number, cacheKey = \"\") {\n\tconst [prefix, suffix] = INFO;\n\n\treturn get<Site>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tcacheKey,\n\t});\n}\n\nasync function getSiteLanguages(id: number, cacheKey = \"\") {\n\tconst [prefix, suffix] = LANGUAGES;\n\n\treturn get<LanguagesResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tcacheKey,\n\t});\n}\n\nasync function startSiteRender(id: number) {\n\tconst [prefix, suffix] = BUILD_START;\n\n\treturn get<StartPageRenderResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t});\n}\n\n/**\n * Send the end signal to API for a render site.\n */\nasync function endSiteRender(id: number, body: EndSiteRenderBody) {\n\tconst [prefix, suffix] = BUILD_END;\n\n\tawait post<EndPageInfoResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tbody,\n\t\tuseApiCacheDir: false,\n\t\tlogToFile: false,\n\t});\n}\n\nasync function getReferenceFieldSiteData(\n\tpage: Core.Page,\n\tbody: ReferenceFieldBody,\n\tcacheKey: string,\n\tdataSiteId?: number,\n\tdataLangID?: number,\n) {\n\tconst [prefix, suffix] = GET_REFERENCE_FIELD_DATA;\n\tconst site = dataSiteId || page.site;\n\tconst lang = dataLangID || page.language;\n\n\treturn post<ReferenceFieldResponse>({\n\t\tendpoint: `${prefix}${site}${suffix}`,\n\t\tbody,\n\t\theaders: { lang },\n\t\tcacheKey,\n\t});\n}\n\nasync function getSitemap(options: { siteId: number; headers?: Record<string, string> }) {\n\tconst { siteId, headers } = options;\n\tconst [prefix, suffix] = GET_SITEMAP;\n\n\treturn get<SitemapAPIResponse>({\n\t\tendpoint: `${prefix}${siteId}${suffix}`,\n\t\theaders,\n\t});\n}\n\nasync function getSiteSocials(id: number, cacheKey = \"\") {\n\tconst [prefix, suffix] = SOCIALS;\n\n\treturn get<SocialsResponse>({\n\t\tendpoint: `${prefix}${id}${suffix}`,\n\t\tcacheKey,\n\t});\n}\n\nexport {\n\tendSiteRender,\n\tgetAllSites,\n\tgetAllSitesFromDomain,\n\tgetPage,\n\tgetReferenceFieldSiteData,\n\tgetSiteInfo,\n\tgetSiteLanguages,\n\tgetSitemap,\n\tgetSiteSocials,\n\tstartSiteRender,\n};\n"],
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EI,EAAWC,CAAa,GAGlB,KAAK,MAAM,MAAM,GAAAC,QAAI,SAASN,EAAiB,OAAO,CAAC,CAC/D,CAEA,eAAeO,IAAY,CAC1B,GAAM,CAAE,oBAAAV,CAAoB,EAAI,MAAMW,GAAwB,EACxD,CAAE,QAAAC,CAAQ,EAAI,MAAMC,EAAuC,EAEjE,MAAMC,EAAY,MAAM,EAExB,GAAM,CAACb,CAAM,EAAI,QAAQ,KAAK,MAAM,CAAC,EAE/B,CAAE,WAAAc,EAAY,OAAAC,CAAO,EAAI,MAAMC,GAAoBhB,CAAM,EAC/D,GAAIc,IAAeG,EAAY,KAAM,CACpCZ,EAAU,KACT,0BAA0BL,CAAM,kEAAkEe,CAAM,GACzG,EACA,MACD,CAEA,IAAMG,EAAS,MAAMrB,GAAgB,CACpC,OAAAG,EACA,eAAgBW,EAChB,oBAAAZ,CACD,CAAC,EAEDM,EAAU,KAAK,0BAA0BL,CAAM,QAAQ,EAEvD,QAAWmB,KAAQD,EAAO,MAAO,CAChCC,EAAK,cAAgB,CAAC,GAAG,IAAI,IAAIA,EAAK,aAAa,CAAC,EACpDA,EAAK,gBAAkB,CAAC,GAAG,IAAI,IAAIA,EAAK,eAAe,CAAC,EAExD,GAAM,CAAE,OAAAC,EAAQ,GAAGC,CAAK,EAAIF,EAC5Bd,EAAU,KAAK,SAASe,CAAM,GAAG,EACjC,MAAME,GAAcF,EAAQC,CAAI,CACjC,CACD,CAEA,eAAeE,IAAO,CACrB,MAAMd,GAAU,CACjB,CAEAe,GAAiBD,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", "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", "ArtifactError", "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", "GRIDDO_API_URL", "GRIDDO_PUBLIC_API_URL", "AI_EMBEDDINGS", "ALERT", "DOMAINS", "GET_ALL", "GET_PAGE", "LOGIN", "RESET_RENDER", "ROBOTS", "SEARCH", "SETTINGS", "SITE_URI", "BUILD_END", "package_default", "DEFAULT_HEADERS", "package_default", "AuthService", "response", "LOGIN", "DEFAULT_HEADERS", "GRIDDO_BOT_USER", "GRIDDO_BOT_PASSWORD", "token", "throwError", "LoginError", "authService", "import_node_path", "getRenderModeFromDB", "domain", "db", "readDB", "brush", "getRenderPathsHydratedWithDomainFromDB", "options", "dbFilePath", "paths", "path", "getRenderMetadataFromDB", "import_node_crypto", "import_promises", "import_node_path", "import_promises", "logBuffer", "logFilePath", "flushPromise", "LOG_BUFFER_FLUSH_THRESHOLD", "GRIDDO_BUILD_LOGS_BUFFER_SIZE", "LOG_TO_FILE_IS_DISABLED", "GRIDDO_BUILD_LOGS", "addLogToBuffer", "lineContent", "LOG_TO_FILE_IS_DISABLED", "logBuffer", "LOG_BUFFER_FLUSH_THRESHOLD", "flushLogsToFile", "error", "GriddoLog", "flushPromise", "logFilePath", "logsToFlush", "fsp", "env", "RETRY_WAIT_SECONDS", "RETRY_ATTEMPTS", "requestAPI", "props", "method", "appendToLog", "endpoint", "body", "cacheKey", "attempt", "headers", "useApiCacheDir", "logToFile", "cacheOptions", "start", "cacheData", "searchCacheData", "siteId", "getSafeSiteId", "siteIdMsg", "duration", "msToSec", "addLogToBuffer", "fetchOptions", "DEFAULT_HEADERS", "authService", "response", "data", "saveCache", "e", "error", "GriddoLog", "RenderError", "showApiError", "delay", "postApi", "props", "endpoint", "body", "headers", "referenceFieldBodyParams", "requestAPI", "showApiError", "error", "options", "message", "stack", "callInfo", "callInfoArray", "item", "callInfoStr", "errorDetailsStr", "GriddoLog", "brush", "getSafeSiteId", "response", "delay", "ms", "res", "msToSec", "decimals", "generateFilenameWithHash", "petition", "__root", "getRenderPathsHydratedWithDomainFromDB", "apiCacheDir", "path", "hashSum", "crypto", "saveCache", "content", "stringContent", "filename", "filepath", "pathExists", "fsp", "searchCacheData", "file", "fileContent", "endSiteRender", "id", "body", "prefix", "suffix", "BUILD_END", "postApi", "getRenderReport", "options", "buildReportFileName", "domain", "exportsSiteDir", "buildReportFile", "path", "pathExists", "GriddoLog", "throwError", "ArtifactError", "fsp", "endRender", "getRenderMetadataFromDB", "__sites", "getRenderPathsHydratedWithDomainFromDB", "authService", "renderMode", "reason", "getRenderModeFromDB", "RENDER_MODE", "report", "site", "siteId", "body", "endSiteRender", "main", "withErrorHandler"]
|
|
7
7
|
}
|
|
@@ -5,5 +5,5 @@ ${i}
|
|
|
5
5
|
${_}
|
|
6
6
|
|
|
7
7
|
${a.red("stack")}
|
|
8
|
-
${JSON.stringify(e,null,2)}`),new b(e)}async function X(r){try{await r()}catch(e){e instanceof b?o.error("Internal Griddo RenderError"):e instanceof Error?o.error(e.message):o.error(`An unexpected error occurred ${e}`);try{let i=await m(),{root:n}=i.paths;i.needsRollbackOnError?(o.info("Cleaning exports dir..."),o.verbose(`Deleting ${q.default.join(n,"exports")}...`),await Y(i.currentRenderingDomain)):o.info("No rollback needed, skipping...")}catch{o.info("Early render stage, no db.json created yet...")}let t=await m();throw t.domains[t.currentRenderingDomain].isRendering=!1,t.domains[t.currentRenderingDomain].renderMode=h.ERROR,await R(t),e}}var y=c(require("node:path"));var d=process.env.GRIDDO_API_URL,me=process.env.GRIDDO_PUBLIC_API_URL,nr=`${d}/ai/embeddings`,ir=`${me}/alert`,sr=`${d}/domains`,ar=`${d}/sites/all`,cr=`${d}/page`,Z=`${d}/login_check`,dr=`${d}/debug/reset-render`,pr=`${d}/domains/robots`,mr=`${d}/search`,lr=`${d}/settings`,fr=`${d}/site/`;var z={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:"11.10.11
|
|
8
|
+
${JSON.stringify(e,null,2)}`),new b(e)}async function X(r){try{await r()}catch(e){e instanceof b?o.error("Internal Griddo RenderError"):e instanceof Error?o.error(e.message):o.error(`An unexpected error occurred ${e}`);try{let i=await m(),{root:n}=i.paths;i.needsRollbackOnError?(o.info("Cleaning exports dir..."),o.verbose(`Deleting ${q.default.join(n,"exports")}...`),await Y(i.currentRenderingDomain)):o.info("No rollback needed, skipping...")}catch{o.info("Early render stage, no db.json created yet...")}let t=await m();throw t.domains[t.currentRenderingDomain].isRendering=!1,t.domains[t.currentRenderingDomain].renderMode=h.ERROR,await R(t),e}}var y=c(require("node:path"));var d=process.env.GRIDDO_API_URL,me=process.env.GRIDDO_PUBLIC_API_URL,nr=`${d}/ai/embeddings`,ir=`${me}/alert`,sr=`${d}/domains`,ar=`${d}/sites/all`,cr=`${d}/page`,Z=`${d}/login_check`,dr=`${d}/debug/reset-render`,pr=`${d}/domains/robots`,mr=`${d}/search`,lr=`${d}/settings`,fr=`${d}/site/`;var z={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:"11.10.11",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:"cbfc6265bef5216b8f34bef05fc6f122826c1dd8"};var Q={"x-application-id":"griddo-cx","x-client-version":z.version,"x-client-name":"CX"};var x=class{headers;async login(){try{let e=await fetch(Z,{method:"POST",headers:Object.assign({},Q,{"Content-Type":"application/json",Connection:"close"}),body:JSON.stringify({username:U,password:M})});if(!e.ok)throw new Error("Error while login in the API");let{token:t}=await e.json();return this.headers={Authorization:`bearer ${t}`,"Cache-Control":"no-store"},this.headers}catch(e){D(K,e)}}},fe=new x;async function ee(r){let e=await m();if(!e.domains[r])throw new Error(a.red(`[!] Error: Domain ${r} not found in DB`));if(!e.domains[r].renderMode)throw new Error(a.red(`[!] Error: Render mode not found for domain ${r}`));return{renderMode:e.domains[r].renderMode,reason:e.domains[r].renderModeReason}}async function O(r){let{domain:e,dbFilePath:t}=r||{},n=(await m(t)).paths;return{__root:n.root,__cache:y.default.join(n.cxCache,e||""),__components:n.components,__cx:n.cx,__sites:n.exportsDir,__exports:y.default.join(n.exportsDir,e||""),__exports_backup:y.default.join(n.exportsDirBackup,e||""),__ssg:n.ssg,__exports_dist:y.default.join(n.exportsDir,e||"","dist")}}async function ue(){let[r]=process.argv.slice(2),{renderMode:e}=await ee(r);if(e===h.IDLE)return;let{__exports:t}=await O({domain:r}),i=v.default.join(t,"assets"),n=v.default.join(t,r);await g(i)?(await A.default.rm(n,{force:!0,recursive:!0}),await A.default.rename(i,n)):o.warn("Assets directory not found")}async function ge(){await ue()}X(ge);
|
|
9
9
|
//# sourceMappingURL=prepare-assets-directory.js.map
|