@griddo/cx 11.10.11 → 11.10.12-rc.0
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
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var Be=Object.create;var V=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var ke=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Le(e))!je.call(r,n)&&n!==t&&V(r,n,{get:()=>e[n],enumerable:!(o=Ge(e,n))||o.enumerable});return r};var d=(r,e,t)=>(t=r!=null?Be(Ne(r)):{},ke(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r));var j=d(require("node:fs/promises")),A=d(require("node:path"));var he=d(require("node:path"));var Ue="\x1B[0m",X={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m"},
|
|
1
|
+
"use strict";var Be=Object.create;var V=Object.defineProperty;var Ge=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty;var ke=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Le(e))!je.call(r,n)&&n!==t&&V(r,n,{get:()=>e[n],enumerable:!(o=Ge(e,n))||o.enumerable});return r};var d=(r,e,t)=>(t=r!=null?Be(Ne(r)):{},ke(e||!r||!r.__esModule?V(t,"default",{value:r,enumerable:!0}):t,r));var j=d(require("node:fs/promises")),A=d(require("node:path"));var he=d(require("node:path"));var Ue="\x1B[0m",X={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m"},f={};for(let r in X){let e=r;f[e]=t=>`${X[e]}${t}${Ue}`}var k={FROM_SCRATCH:"FROM_SCRATCH",INCREMENTAL:"INCREMENTAL",IDLE:"IDLE",ERROR:"ERROR",COMPLETED:"COMPLETED"};var M=d(require("node:fs/promises")),B=d(require("node:path"));var te=d(require("node:path"));var z=d(require("node:fs"));var _=d(require("node:path")),Q=d(require("node:process")),ee=require("node:url"),Z=r=>r instanceof URL?(0,ee.fileURLToPath)(r):r;function re(r,e={}){let{cwd:t=Q.default.cwd(),type:o="file",stopAt:n}=e,a=_.default.resolve(Z(t)??""),{root:m}=_.default.parse(a),l=n?_.default.resolve(a,Z(n)):m,c=_.default.isAbsolute(r);for(;;){let u=c?r:_.default.join(a,r);try{let D=z.default.statSync(u,{throwIfNoEntry:!1});if(o==="file"&&D?.isFile()||o==="directory"&&D?.isDirectory())return u}catch{}if(a===l||a===m)break;a=_.default.dirname(a)}}function oe(r){let{cwd:e}=r||{},t=re("package.json",{cwd:e});return t&&te.default.dirname(t)}var{env:s}=process;function R(r){if(!r)return!1;switch(r.trim().toLowerCase()){case"1":case"true":case"yes":case"y":case"on":return!0;default:return!1}}var hr=s.GRIDDO_API_URL||s.API_URL,yr=s.GRIDDO_PUBLIC_API_URL||s.PUBLIC_API_URL,ne=s.botEmail||s.GRIDDO_BOT_USER,ie=s.botPassword||s.GRIDDO_BOT_PASSWORD,Dr=Number.parseInt(s.GRIDDO_API_CONCURRENCY_COUNT||"10"),wr=R(s.GRIDDO_SKIP_BUILD_CHECKS),F=R(s.GRIDDO_BUILD_LOGS),se=Number.parseInt(s.GRIDDO_BUILD_LOGS_BUFFER_SIZE||"500"),Er=R(s.GRIDDO_SSG_VERBOSE_LOGS),U=R(s.GRIDDO_SEARCH_FEATURE),Rr=s.GRIDDO_ASSET_PREFIX||s.ASSET_PREFIX,br=s.GRIDDO_REACT_APP_INSTANCE||s.REACT_APP_INSTANCE,ae=R(s.GRIDDO_AI_EMBEDDINGS),ce=R(s.GRIDDO_VERBOSE_LOGS),Sr=R(s.GRIDDO_USE_DIST_BACKUP),Ir=R(s.GRIDDO_SSG_BUNDLE_ANALYZER);var i=class r{constructor(){}static verbose(...e){ce&&console.log(f.yellow("verbose"),f.dim(e.join(" ")))}static build(...e){F&&r.log(...e)}static info(...e){console.log(`${f.blue("info")} ${e.join(" ")}`)}static success(...e){console.log(`${f.green("success")} ${e.join(" ")}`)}static error(...e){console.error(`${f.red("error")} ${e.join(" ")}`)}static warn(...e){console.warn(`${f.yellow("warn")} ${e.join(" ")}`)}static log(...e){console.log(...e)}};var Me=oe({cwd:B.default.resolve(__dirname,"../../..")})||"",He=B.default.join(Me,".griddo/cache"),de=B.default.join(He,"db.json");async function w(r=""){let e=r||de;try{return JSON.parse(await M.default.readFile(e,"utf-8"))}catch(t){throw i.error(`Failed to read DB file at ${e}:`,t),t}}async function G(r,e=""){let t=e||de;try{await M.default.writeFile(t,JSON.stringify(r,null," "))}catch(o){throw i.error(`Failed to write DB file at ${t}:`,o),o}}var H=d(require("node:fs/promises")),b=d(require("node:path"));var ue=d(require("node:fs/promises"));var pe={error:"LoginError",message:"There was a problem logging in to the API",expected:"This happens if the API is currently not working or the credentials are incorrect."},le={error:"NoDomainsFoundError",message:"No domains were found in this instance. The process cannot continue.",expected:"This may happen if the API is not functioning, or the site is not properly configured, or the domains are not registered.",hint:"You can contact the instance administrator."};var fe={error:"ReadFromStoreError",message:"There was an error reading a file to the Store directory",hint:"There may be an issue such as permissions preventing the file from being read."};var me={error:"UploadSearchError",message:"There was an error uploading content to API for search",hint:"This happens if the API is currently not working or the credentials are incorrect."};async function E(r){try{return await ue.default.access(r),!0}catch{return!1}}async function ge(r){let e=await w(),{exportsDir:t,exportsDirBackup:o}=e.paths;i.info(`Cleaning exports dir for the domain ${r}`),i.verbose(`Deleting ${b.default.join(t,r)}...`),await H.default.rm(b.default.join(t,r),{recursive:!0,force:!0}),await E(b.default.join(o,r))?(await H.default.cp(b.default.join(o,r),b.default.join(t,r),{recursive:!0}),i.info(`export-backup dir for the domain ${r} found. Restoring before exit...`),i.verbose(`Copying ${b.default.join(o,r)} -> ${b.default.join(t,r)}...`)):i.info("No export-backup found, skipping rollback. Next render will create a new exports dir from scratch...")}var T=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e)),this.name="InternalCXError",this.stack=e instanceof Error?e.stack:""}};function h(r,e){let{error:t,message:o,expected:n,hint:a}=r,m=i.log(f.red(`[ ${t} ]`)),l=[n,a].filter(Boolean).join(`
|
|
2
2
|
`);throw i.log(`
|
|
3
3
|
${m}
|
|
4
4
|
${o}
|
|
5
|
-
${
|
|
5
|
+
${l}
|
|
6
6
|
|
|
7
|
-
${
|
|
7
|
+
${f.red("stack")}
|
|
8
8
|
${JSON.stringify(e,null,2)}`),new T(e)}async function ye(r){try{await r()}catch(e){e instanceof T?i.error("Internal Griddo RenderError"):e instanceof Error?i.error(e.message):i.error(`An unexpected error occurred ${e}`);try{let o=await w(),{root:n}=o.paths;o.needsRollbackOnError?(i.info("Cleaning exports dir..."),i.verbose(`Deleting ${he.default.join(n,"exports")}...`),await ge(o.currentRenderingDomain)):i.info("No rollback needed, skipping...")}catch{i.info("Early render stage, no db.json created yet...")}let t=await w();throw t.domains[t.currentRenderingDomain].isRendering=!1,t.domains[t.currentRenderingDomain].renderMode=k.ERROR,await G(t),e}}var Te=d(require("node:crypto")),N=d(require("node:fs/promises")),K=d(require("node:path"));var we=d(require("node:fs/promises"));var O=[],De=null,P=null,Je=se;var We=!F;function J(r){We||(O.push(r.toString()),O.length>=Je&&Ke().catch(e=>{i.error("Background log flush failed:",e)}))}async function Ke(){if(P&&await P,O.length===0||!De)return;P=(async()=>{let e=[...O];O.length=0;try{await we.default.appendFile(De,`${e.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`)}catch(t){O.unshift(...e),i.error("Error flushing logs:",t)}})();try{await P}finally{P=null}}var Ee={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:"11.10.
|
|
10
|
+
`)}catch(t){O.unshift(...e),i.error("Error flushing logs:",t)}})();try{await P}finally{P=null}}var Ee={name:"@griddo/cx",description:"Griddo SSG based on Gatsby",version:"11.10.12-rc.0",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:"114a2b713bcf8b762705c3d492269600d4c95509"};var L={"x-application-id":"griddo-cx","x-client-version":Ee.version,"x-client-name":"CX"};var y=process.env.GRIDDO_API_URL,qe=process.env.GRIDDO_PUBLIC_API_URL,Re=`${y}/ai/embeddings`,rt=`${qe}/alert`,be=`${y}/domains`,tt=`${y}/sites/all`,ot=`${y}/page`,Se=`${y}/login_check`,nt=`${y}/debug/reset-render`,it=`${y}/domains/robots`,Ie=`${y}/search`,st=`${y}/settings`,at=`${y}/site/`;var W=class{headers;async login(){try{let e=await fetch(Se,{method:"POST",headers:Object.assign({},L,{"Content-Type":"application/json",Connection:"close"}),body:JSON.stringify({username:ne,password:ie})});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){h(pe,e)}}},C=new W;var v=d(require("node:path"));async function $(r){let{domain:e,dbFilePath:t}=r||{},n=(await w(t)).paths;return{__root:n.root,__cache:v.default.join(n.cxCache,e||""),__components:n.components,__cx:n.cx,__sites:n.exportsDir,__exports:v.default.join(n.exportsDir,e||""),__exports_backup:v.default.join(n.exportsDirBackup,e||""),__ssg:n.ssg,__exports_dist:v.default.join(n.exportsDir,e||"","dist")}}var{env:Ve}=process,{RETRY_WAIT_SECONDS:Xe="4",RETRY_ATTEMPTS:_e="4"}=Ve;async function Y(r,e,t=""){let{endpoint:o,body:n,cacheKey:a="",attempt:m=1,headers:l,useApiCacheDir:c=!0,logToFile:u=!0}=r,D={endpoint:o,body:n,headers:l,cacheKey:a};if(a&&c){let S=new Date,p=await er(D);if(p){if(u){let g=Ae(p),I=g?`site: ${g}`:"",x=xe(Date.now()-S.getTime());J(`${e} (cache) ${I} ${o} - ${x}s ${t}`)}return p}}try{let S=new Date,p={method:e.toUpperCase(),headers:Object.assign({},L,l,C.headers)};e.toLowerCase()!=="get"&&n&&(p.body=JSON.stringify(n),p.headers||(p.headers={}),p.headers["Content-Type"]="application/json");let g=await fetch(o,p);if(!g.ok){if(g.status===404)return null;throw new Error(`HTTP ${g.status}: ${g.statusText}`)}let I=await g.json();if(u){let x=Ae(I),ve=x?`site: ${x}`:"",Fe=xe(Date.now()-S.getTime());J(`${e} (fetch) ${ve} ${o} - ${Fe}s ${t}`)}return c&&await Qe(D,I),I}catch(S){let p=S;if(m>parseInt(_e))throw i.log(`
|
|
11
11
|
Max attempts ${_e} reached
|
|
12
12
|
--------------------------------------
|
|
13
13
|
- ${e.toUpperCase()} ${o}
|
|
14
14
|
- BODY: ${JSON.stringify(n)}
|
|
15
|
-
- HEADERS: ${JSON.stringify(
|
|
15
|
+
- HEADERS: ${JSON.stringify(l)}
|
|
16
16
|
- ERROR: ${p.message}
|
|
17
17
|
--------------------------------------
|
|
18
|
-
`),new T(p);return Ze(p,{callInfo:{endpoint:o,body:n}}),i.warn(`Waiting for retry: ${e}`,o),await ze(parseInt(Xe)*1e3),Y({endpoint:o,body:n,headers:
|
|
19
|
-
`),
|
|
20
|
-
${o}`;i.warn(
|
|
18
|
+
`),new T(p);return Ze(p,{callInfo:{endpoint:o,body:n}}),i.warn(`Waiting for retry: ${e}`,o),await ze(parseInt(Xe)*1e3),Y({endpoint:o,body:n,headers:l,cacheKey:a,attempt:m+1},e,t)}}async function Oe(r){return Y(r,"get")}async function q(r){let{endpoint:e,body:t,headers:o}=r,n=e.endsWith("/distributor")&&`# ReferenceField body: ${JSON.stringify(t)} lang: ${JSON.stringify(o?.lang)}`;return Y(r,"post",n||"")}function Ze(r,e){let{message:t,stack:o}=r,{callInfo:n}=e,a=[];for(let c of Object.keys(n))a.push(`${c}: ${typeof n[c]=="object"?JSON.stringify(n[c]):n[c]}`);let m=a.join(`
|
|
19
|
+
`),l=`${t}
|
|
20
|
+
${o}`;i.warn(f.red(`
|
|
21
21
|
=============
|
|
22
22
|
|
|
23
23
|
{ Call info }
|
|
24
24
|
${m}
|
|
25
25
|
|
|
26
26
|
{ Error details }
|
|
27
|
-
${
|
|
27
|
+
${l}
|
|
28
28
|
|
|
29
29
|
=============
|
|
30
|
-
`))}function Ae(r){if(!(typeof r!="object"||r===null||Array.isArray(r)))return"site"in r&&r.site?r.site:void 0}function ze(r){return new Promise(e=>setTimeout(e,r))}function xe(r,e=3){return Number.parseFloat((r/1e3).toFixed(e))}async function Pe(r){let{__root:e}=await $(),t=K.default.join(e,"apiCache"),o=Te.default.createHash("sha256");return o.update(JSON.stringify(r)),`${t}/${o.digest("hex")}`}async function Qe(r,e){let t=typeof e=="string"?e:JSON.stringify(e),o=await Pe(r),n=K.default.dirname(o);await E(n)||await N.default.mkdir(n,{recursive:!0}),await N.default.writeFile(o,t,"utf8")}async function er(r){try{let e=await Pe(r),t=await N.default.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}async function Ce(){let r=await Oe({endpoint:be,useApiCacheDir:!1});r.length||h(
|
|
31
|
-
`)}async function*$e(r){let e=await j.default.opendir(r);for await(let t of e)t.isDirectory()?yield*$e(A.default.join(r,t.name)):t.isFile()&&A.default.extname(t.name)===".json"&&t.name.includes("page-data")&&(yield A.default.join(r,t.name))}async function*nr(r){let e=$e(r);for await(let t of e)try{let o=await j.default.readFile(t,"utf8"),n=JSON.parse(o);n.path&&(yield n)}catch(o){h(
|
|
30
|
+
`))}function Ae(r){if(!(typeof r!="object"||r===null||Array.isArray(r)))return"site"in r&&r.site?r.site:void 0}function ze(r){return new Promise(e=>setTimeout(e,r))}function xe(r,e=3){return Number.parseFloat((r/1e3).toFixed(e))}async function Pe(r){let{__root:e}=await $(),t=K.default.join(e,"apiCache"),o=Te.default.createHash("sha256");return o.update(JSON.stringify(r)),`${t}/${o.digest("hex")}`}async function Qe(r,e){let t=typeof e=="string"?e:JSON.stringify(e),o=await Pe(r),n=K.default.dirname(o);await E(n)||await N.default.mkdir(n,{recursive:!0}),await N.default.writeFile(o,t,"utf8")}async function er(r){try{let e=await Pe(r),t=await N.default.readFile(e,"utf8");return JSON.parse(t)}catch{return null}}async function Ce(){let r=await Oe({endpoint:be,useApiCacheDir:!1});r.length||h(le),i.verbose(`getting domains names (${r.length})`);let e=r.filter(({slug:t})=>!!t).map(({slug:t})=>t.replace("/",""));return[...new Set(e)]}async function rr(r){let{title:e,description:t,image:o,pageId:n,languageId:a,siteId:m,url:l,content:c,template:u}=r;return await q({endpoint:Ie,body:{title:e,description:t,image:o,pageId:n,languageId:a,siteId:m,url:l,template:u,content:c},useApiCacheDir:!1,logToFile:!1})}function tr(r){let e=["meta","link","style","script","noscript","nav","header","footer"],t=new RegExp(`<(${e.join("|")})\\b[^>]*>.*?<\\/\\1>`,"gis"),o=r.replace(t,"");return o=o.replace(/<[^>]+>/g," "),o=o.replace(/\s+/g," ").trim(),o}async function or(r){let{htmlContentDir:e,jsonContentDir:t}=r;if(!await E(t)||!await E(e)){i.info("Skipping uploading content to the search endpoint because it has not exported sites.");return}let o=nr(t),n=0;for await(let a of o){let{result:m}=a,{pageContext:l}=m,{page:c,openGraph:u,pageMetadata:D}=l,{compose:S}=c.fullPath,p=A.default.resolve(`${e}/${S}/index.html`),g=await j.default.readFile(p,"utf-8"),I={siteId:c.site,pageId:c.id,title:D?.title||u?.title,languageId:c.language,url:c.fullUrl,template:c.template.templateType||c.templateId,description:D?.description||u?.description,image:u.image,content:tr(g)};try{await rr(I)}catch(x){h(me,x)}i.verbose(`Uploaded content of: ${c.fullUrl}`),n++}i.info(`Uploaded ${n} pages.
|
|
31
|
+
`)}async function*$e(r){let e=await j.default.opendir(r);for await(let t of e)t.isDirectory()?yield*$e(A.default.join(r,t.name)):t.isFile()&&A.default.extname(t.name)===".json"&&t.name.includes("page-data")&&(yield A.default.join(r,t.name))}async function*nr(r){let e=$e(r);for await(let t of e)try{let o=await j.default.readFile(t,"utf8"),n=JSON.parse(o);n.path&&(yield n)}catch(o){h(fe,o)}}async function ir(r){let{__exports:e}=await $({domain:r});return{htmlContentDir:A.default.join(e,"dist"),jsonContentDir:A.default.join(e,"dist","page-data")}}async function sr(){if(U){let r=await Ce();for(let e of r){let{htmlContentDir:t,jsonContentDir:o}=await ir(e);i.info(`Uploading search content for ${e}`),await or({htmlContentDir:t,jsonContentDir:o})}}}async function ar(){U&&ae&&(i.info("Triggering AI embeddings..."),await q({endpoint:Re,useApiCacheDir:!1}))}async function cr(){await C.login(),await sr(),await ar()}ye(cr);
|
|
32
32
|
//# sourceMappingURL=upload-search-content.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../exporter/commands/upload-search-content.ts", "../../exporter/core/errors.ts", "../../exporter/shared/npm-modules/brush.ts", "../../exporter/shared/types/render.ts", "../../exporter/core/db.ts", "../../exporter/shared/npm-modules/pkg-dir.ts", "../../exporter/shared/npm-modules/find-up-simple.ts", "../../exporter/shared/envs.ts", "../../exporter/core/GriddoLog.ts", "../../exporter/core/dist-rollback.ts", "../../exporter/core/fs.ts", "../../exporter/shared/errors.ts", "../../exporter/services/api.ts", "../../exporter/core/logger.ts", "../../package.json", "../../exporter/shared/headers.ts", "../../exporter/shared/endpoints.ts", "../../exporter/services/auth.ts", "../../exporter/services/render.ts", "../../exporter/services/domains.ts"],
|
|
4
|
-
"sourcesContent": ["import type { PostSearchInfoResponse } from \"../shared/types/api\";\nimport type { AIEmbeddingsResponse, PostSearchInfoProps } from \"../shared/types/global\";\nimport type { GatsbyPageData } from \"../ssg-adapters/gatsby/shared/types\";\n\nimport 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 { post } from \"../services/api\";\nimport { AuthService } from \"../services/auth\";\nimport { getInstanceDomains } from \"../services/domains\";\nimport { getRenderPathsHydratedWithDomainFromDB } from \"../services/render\";\nimport { AI_EMBEDDINGS, SEARCH } from \"../shared/endpoints\";\nimport { GRIDDO_AI_EMBEDDINGS, GRIDDO_SEARCH_FEATURE } from \"../shared/envs\";\nimport { ReadFromStoreError, UploadSearchError } from \"../shared/errors\";\n\n/**\n * Save in the BBDD the content of a page parsed without HTML tags.\n *\n * @param props Object with parts of the final page object to be saved in the BBDD.\n */\nasync function postSearchInfo(props: PostSearchInfoProps) {\n\tconst { title, description, image, pageId, languageId, siteId, url, content, template } = props;\n\n\tconst response = await post<PostSearchInfoResponse>({\n\t\tendpoint: SEARCH,\n\t\tbody: {\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\timage,\n\t\t\tpageId,\n\t\t\tlanguageId,\n\t\t\tsiteId,\n\t\t\turl,\n\t\t\ttemplate,\n\t\t\tcontent,\n\t\t},\n\t\tuseApiCacheDir: false,\n\t\tlogToFile: false,\n\t});\n\n\treturn response;\n}\n\nfunction prepareHTMLContentForSearch(content: string): string {\n\t// 1. Remove script, style, and other unwanted block tags and their content.\n\t// The regex looks for <tag...>...</tag> where tag is one of the specified ones.\n\tconst tagsToRemove = [\"meta\", \"link\", \"style\", \"script\", \"noscript\", \"nav\", \"header\", \"footer\"];\n\tconst removeTagsRegex = new RegExp(`<(${tagsToRemove.join(\"|\")})\\\\b[^>]*>.*?<\\\\/\\\\1>`, \"gis\");\n\tlet processedContent = content.replace(removeTagsRegex, \"\");\n\n\t// 2. Strip all remaining HTML tags.\n\tprocessedContent = processedContent.replace(/<[^>]+>/g, \" \");\n\n\t// 3. Normalize whitespace: replace multiple spaces/newlines with a single space and trim.\n\tprocessedContent = processedContent.replace(/\\s+/g, \" \").trim();\n\n\treturn processedContent;\n}\n\n/**\n * Function that search in the `/public` dir the content info of the pages and\n * send it to the search table in the ddbb using the API.\n * @todo Utilizar la carpeta page-data en lugar de la carpeta store puesto que\n * esta ya no es persistente.\n */\nasync function uploadRenderedSearchContentToAPI(options: {\n\thtmlContentDir: string;\n\tjsonContentDir: string;\n}) {\n\tconst { htmlContentDir, jsonContentDir } = options;\n\n\tif (!(await pathExists(jsonContentDir)) || !(await pathExists(htmlContentDir))) {\n\t\tGriddoLog.info(\n\t\t\t`Skipping uploading content to the search endpoint because it has not exported sites.`,\n\t\t);\n\n\t\treturn;\n\t}\n\n\t// Get pages from gatsby page-data dir\n\tconst gatsbyPageDataPages = getPageDataPagesFromExports(jsonContentDir);\n\n\tlet pagesUploadedCounter = 0;\n\tfor await (const pageData of gatsbyPageDataPages) {\n\t\tconst { result } = pageData;\n\t\tconst { pageContext } = result;\n\t\tconst { page, openGraph, pageMetadata } = pageContext;\n\n\t\tconst { compose } = page.fullPath;\n\n\t\tconst htmlPath = path.resolve(`${htmlContentDir}/${compose}/index.html`);\n\t\tconst htmlContent = await fsp.readFile(htmlPath, \"utf-8\");\n\n\t\tconst pageObject: PostSearchInfoProps = {\n\t\t\tsiteId: page.site,\n\t\t\tpageId: page.id,\n\t\t\t// `pageMetadata.title` has already a fallback `metatitle ||\n\t\t\t// pageTitle` so probably `title` never will be take the\n\t\t\t// `openGraph?.title` value. Only when the `metatitle` and\n\t\t\t// `pageTitle` are empty.\n\t\t\ttitle: pageMetadata?.title || openGraph?.title,\n\t\t\tlanguageId: page.language,\n\t\t\turl: page.fullUrl,\n\t\t\ttemplate: page.template.templateType || page.templateId,\n\t\t\tdescription: pageMetadata?.description || openGraph?.description,\n\t\t\timage: openGraph.image,\n\t\t\tcontent: prepareHTMLContentForSearch(htmlContent),\n\t\t};\n\n\t\ttry {\n\t\t\tawait postSearchInfo(pageObject);\n\t\t} catch (error) {\n\t\t\tthrowError(UploadSearchError, error);\n\t\t}\n\n\t\tGriddoLog.verbose(`Uploaded content of: ${page.fullUrl}`);\n\t\tpagesUploadedCounter++;\n\t}\n\n\tGriddoLog.info(`Uploaded ${pagesUploadedCounter} pages.\\n`);\n}\n\n/**\n * Walk recursively in a basePath and return an array of pages with json\n * extension with the full absolute path and the path includes \"page-data\".\n *\n * @param basePath The path to walk recursively.\n * @returns An array of pages with json extension with the full absolute path\n * and the path includes \"page-data\".\n */\nasync function* walkRecursively(basePath: string): AsyncGenerator<string> {\n\tconst filesHandle = await fsp.opendir(basePath);\n\n\tfor await (const fileDirent of filesHandle) {\n\t\tif (fileDirent.isDirectory()) {\n\t\t\tyield* walkRecursively(path.join(basePath, fileDirent.name));\n\t\t} else if (\n\t\t\tfileDirent.isFile() &&\n\t\t\tpath.extname(fileDirent.name) === \".json\" &&\n\t\t\tfileDirent.name.includes(\"page-data\")\n\t\t) {\n\t\t\tyield path.join(basePath, fileDirent.name);\n\t\t}\n\t}\n}\n\n/**\n * Walk recursively in a basePath and return an array of pages with json\n * extension with the full absolute path and the path includes \"page-data\".\n *\n * @param basePath The path to walk recursively.\n * @returns An array of pages with json extension with the full absolute path\n * and the path includes \"page-data\".\n */\nasync function* getPageDataPagesFromExports<PageType extends GatsbyPageData>(\n\tbasePath: string,\n): AsyncGenerator<PageType> {\n\tconst jsonFiles = walkRecursively(basePath);\n\n\tfor await (const filePath of jsonFiles) {\n\t\ttry {\n\t\t\tconst fileContent = await fsp.readFile(filePath, \"utf8\");\n\t\t\tconst page = JSON.parse(fileContent) as PageType;\n\n\t\t\tif (page.path) {\n\t\t\t\tyield page;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrowError(ReadFromStoreError, error);\n\t\t}\n\t}\n}\n\nasync function getContentDirectories(domain: string) {\n\tconst { __exports } = await getRenderPathsHydratedWithDomainFromDB({ domain });\n\n\treturn {\n\t\thtmlContentDir: path.join(__exports, \"dist\"),\n\t\tjsonContentDir: path.join(__exports, \"dist\", \"page-data\"),\n\t};\n}\n\nasync function uploadSearchContent() {\n\tif (GRIDDO_SEARCH_FEATURE) {\n\t\tconst domains = await getInstanceDomains();\n\t\tfor (const domain of domains) {\n\t\t\tconst { htmlContentDir, jsonContentDir } = await getContentDirectories(domain);\n\n\t\t\tGriddoLog.info(`Uploading search content for ${domain}`);\n\t\t\tawait uploadRenderedSearchContentToAPI({\n\t\t\t\thtmlContentDir,\n\t\t\t\tjsonContentDir,\n\t\t\t});\n\t\t}\n\t}\n}\n\nasync function aiEmbeddings() {\n\tif (GRIDDO_SEARCH_FEATURE && GRIDDO_AI_EMBEDDINGS) {\n\t\tGriddoLog.info(`Triggering AI embeddings...`);\n\t\tawait post<AIEmbeddingsResponse>({\n\t\t\tendpoint: AI_EMBEDDINGS,\n\t\t\tuseApiCacheDir: false,\n\t\t});\n\t}\n}\n\nasync function main() {\n\tawait AuthService.login();\n\tawait uploadSearchContent();\n\tawait aiEmbeddings();\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", "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", "{\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", "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", "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 { Domains } from \"../shared/types/global\";\n\nimport { throwError } from \"../core/errors\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { DOMAINS } from \"../shared/endpoints\";\nimport { NoDomainsFoundError } from \"../shared/errors\";\nimport { get } from \"./api\";\n\n/**\n * Return an array of domains name (string) of the current instance.\n */\nasync function getInstanceDomains() {\n\tconst domains = await get<Domains>({\n\t\tendpoint: DOMAINS,\n\t\tuseApiCacheDir: false,\n\t});\n\n\tif (!domains.length) {\n\t\tthrowError(NoDomainsFoundError);\n\t}\n\n\tGriddoLog.verbose(`getting domains names (${domains.length})`);\n\n\tconst filteredDomains = domains\n\t\t.filter(({ slug }) => !!slug)\n\t\t.map(({ slug }) => slug.replace(\"/\", \"\"));\n\n\treturn [...new Set(filteredDomains)];\n}\n\nexport { getInstanceDomains };\n"],
|
|
5
|
-
"mappings": "oeAIA,IAAAA,EAAgB,+BAChBC,EAAiB,wBCHjB,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,EAA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BF,EAAI",
|
|
4
|
+
"sourcesContent": ["import type { PostSearchInfoResponse } from \"../shared/types/api\";\nimport type { AIEmbeddingsResponse, PostSearchInfoProps } from \"../shared/types/global\";\nimport type { GatsbyPageData } from \"../ssg-adapters/gatsby/shared/types\";\n\nimport 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 { post } from \"../services/api\";\nimport { AuthService } from \"../services/auth\";\nimport { getInstanceDomains } from \"../services/domains\";\nimport { getRenderPathsHydratedWithDomainFromDB } from \"../services/render\";\nimport { AI_EMBEDDINGS, SEARCH } from \"../shared/endpoints\";\nimport { GRIDDO_AI_EMBEDDINGS, GRIDDO_SEARCH_FEATURE } from \"../shared/envs\";\nimport { ReadFromStoreError, UploadSearchError } from \"../shared/errors\";\n\n/**\n * Save in the BBDD the content of a page parsed without HTML tags.\n *\n * @param props Object with parts of the final page object to be saved in the BBDD.\n */\nasync function postSearchInfo(props: PostSearchInfoProps) {\n\tconst { title, description, image, pageId, languageId, siteId, url, content, template } = props;\n\n\tconst response = await post<PostSearchInfoResponse>({\n\t\tendpoint: SEARCH,\n\t\tbody: {\n\t\t\ttitle,\n\t\t\tdescription,\n\t\t\timage,\n\t\t\tpageId,\n\t\t\tlanguageId,\n\t\t\tsiteId,\n\t\t\turl,\n\t\t\ttemplate,\n\t\t\tcontent,\n\t\t},\n\t\tuseApiCacheDir: false,\n\t\tlogToFile: false,\n\t});\n\n\treturn response;\n}\n\nfunction prepareHTMLContentForSearch(content: string): string {\n\t// 1. Remove script, style, and other unwanted block tags and their content.\n\t// The regex looks for <tag...>...</tag> where tag is one of the specified ones.\n\tconst tagsToRemove = [\"meta\", \"link\", \"style\", \"script\", \"noscript\", \"nav\", \"header\", \"footer\"];\n\tconst removeTagsRegex = new RegExp(`<(${tagsToRemove.join(\"|\")})\\\\b[^>]*>.*?<\\\\/\\\\1>`, \"gis\");\n\tlet processedContent = content.replace(removeTagsRegex, \"\");\n\n\t// 2. Strip all remaining HTML tags.\n\tprocessedContent = processedContent.replace(/<[^>]+>/g, \" \");\n\n\t// 3. Normalize whitespace: replace multiple spaces/newlines with a single space and trim.\n\tprocessedContent = processedContent.replace(/\\s+/g, \" \").trim();\n\n\treturn processedContent;\n}\n\n/**\n * Function that search in the `/public` dir the content info of the pages and\n * send it to the search table in the ddbb using the API.\n * @todo Utilizar la carpeta page-data en lugar de la carpeta store puesto que\n * esta ya no es persistente.\n */\nasync function uploadRenderedSearchContentToAPI(options: {\n\thtmlContentDir: string;\n\tjsonContentDir: string;\n}) {\n\tconst { htmlContentDir, jsonContentDir } = options;\n\n\tif (!(await pathExists(jsonContentDir)) || !(await pathExists(htmlContentDir))) {\n\t\tGriddoLog.info(\n\t\t\t`Skipping uploading content to the search endpoint because it has not exported sites.`,\n\t\t);\n\n\t\treturn;\n\t}\n\n\t// Get pages from gatsby page-data dir\n\tconst gatsbyPageDataPages = getPageDataPagesFromExports(jsonContentDir);\n\n\tlet pagesUploadedCounter = 0;\n\tfor await (const pageData of gatsbyPageDataPages) {\n\t\tconst { result } = pageData;\n\t\tconst { pageContext } = result;\n\t\tconst { page, openGraph, pageMetadata } = pageContext;\n\n\t\tconst { compose } = page.fullPath;\n\n\t\tconst htmlPath = path.resolve(`${htmlContentDir}/${compose}/index.html`);\n\t\tconst htmlContent = await fsp.readFile(htmlPath, \"utf-8\");\n\n\t\tconst pageObject: PostSearchInfoProps = {\n\t\t\tsiteId: page.site,\n\t\t\tpageId: page.id,\n\t\t\t// `pageMetadata.title` has already a fallback `metatitle ||\n\t\t\t// pageTitle` so probably `title` never will be take the\n\t\t\t// `openGraph?.title` value. Only when the `metatitle` and\n\t\t\t// `pageTitle` are empty.\n\t\t\ttitle: pageMetadata?.title || openGraph?.title,\n\t\t\tlanguageId: page.language,\n\t\t\turl: page.fullUrl,\n\t\t\ttemplate: page.template.templateType || page.templateId,\n\t\t\tdescription: pageMetadata?.description || openGraph?.description,\n\t\t\timage: openGraph.image,\n\t\t\tcontent: prepareHTMLContentForSearch(htmlContent),\n\t\t};\n\n\t\ttry {\n\t\t\tawait postSearchInfo(pageObject);\n\t\t} catch (error) {\n\t\t\tthrowError(UploadSearchError, error);\n\t\t}\n\n\t\tGriddoLog.verbose(`Uploaded content of: ${page.fullUrl}`);\n\t\tpagesUploadedCounter++;\n\t}\n\n\tGriddoLog.info(`Uploaded ${pagesUploadedCounter} pages.\\n`);\n}\n\n/**\n * Walk recursively in a basePath and return an array of pages with json\n * extension with the full absolute path and the path includes \"page-data\".\n *\n * @param basePath The path to walk recursively.\n * @returns An array of pages with json extension with the full absolute path\n * and the path includes \"page-data\".\n */\nasync function* walkRecursively(basePath: string): AsyncGenerator<string> {\n\tconst filesHandle = await fsp.opendir(basePath);\n\n\tfor await (const fileDirent of filesHandle) {\n\t\tif (fileDirent.isDirectory()) {\n\t\t\tyield* walkRecursively(path.join(basePath, fileDirent.name));\n\t\t} else if (\n\t\t\tfileDirent.isFile() &&\n\t\t\tpath.extname(fileDirent.name) === \".json\" &&\n\t\t\tfileDirent.name.includes(\"page-data\")\n\t\t) {\n\t\t\tyield path.join(basePath, fileDirent.name);\n\t\t}\n\t}\n}\n\n/**\n * Walk recursively in a basePath and return an array of pages with json\n * extension with the full absolute path and the path includes \"page-data\".\n *\n * @param basePath The path to walk recursively.\n * @returns An array of pages with json extension with the full absolute path\n * and the path includes \"page-data\".\n */\nasync function* getPageDataPagesFromExports<PageType extends GatsbyPageData>(\n\tbasePath: string,\n): AsyncGenerator<PageType> {\n\tconst jsonFiles = walkRecursively(basePath);\n\n\tfor await (const filePath of jsonFiles) {\n\t\ttry {\n\t\t\tconst fileContent = await fsp.readFile(filePath, \"utf8\");\n\t\t\tconst page = JSON.parse(fileContent) as PageType;\n\n\t\t\tif (page.path) {\n\t\t\t\tyield page;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrowError(ReadFromStoreError, error);\n\t\t}\n\t}\n}\n\nasync function getContentDirectories(domain: string) {\n\tconst { __exports } = await getRenderPathsHydratedWithDomainFromDB({ domain });\n\n\treturn {\n\t\thtmlContentDir: path.join(__exports, \"dist\"),\n\t\tjsonContentDir: path.join(__exports, \"dist\", \"page-data\"),\n\t};\n}\n\nasync function uploadSearchContent() {\n\tif (GRIDDO_SEARCH_FEATURE) {\n\t\tconst domains = await getInstanceDomains();\n\t\tfor (const domain of domains) {\n\t\t\tconst { htmlContentDir, jsonContentDir } = await getContentDirectories(domain);\n\n\t\t\tGriddoLog.info(`Uploading search content for ${domain}`);\n\t\t\tawait uploadRenderedSearchContentToAPI({\n\t\t\t\thtmlContentDir,\n\t\t\t\tjsonContentDir,\n\t\t\t});\n\t\t}\n\t}\n}\n\nasync function aiEmbeddings() {\n\tif (GRIDDO_SEARCH_FEATURE && GRIDDO_AI_EMBEDDINGS) {\n\t\tGriddoLog.info(`Triggering AI embeddings...`);\n\t\tawait post<AIEmbeddingsResponse>({\n\t\t\tendpoint: AI_EMBEDDINGS,\n\t\t\tuseApiCacheDir: false,\n\t\t});\n\t}\n}\n\nasync function main() {\n\tawait AuthService.login();\n\tawait uploadSearchContent();\n\tawait aiEmbeddings();\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", "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", "{\n\t\"name\": \"@griddo/cx\",\n\t\"description\": \"Griddo SSG based on Gatsby\",\n\t\"version\": \"11.10.12-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\": \"114a2b713bcf8b762705c3d492269600d4c95509\"\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", "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", "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 { Domains } from \"../shared/types/global\";\n\nimport { throwError } from \"../core/errors\";\nimport { GriddoLog } from \"../core/GriddoLog\";\nimport { DOMAINS } from \"../shared/endpoints\";\nimport { NoDomainsFoundError } from \"../shared/errors\";\nimport { get } from \"./api\";\n\n/**\n * Return an array of domains name (string) of the current instance.\n */\nasync function getInstanceDomains() {\n\tconst domains = await get<Domains>({\n\t\tendpoint: DOMAINS,\n\t\tuseApiCacheDir: false,\n\t});\n\n\tif (!domains.length) {\n\t\tthrowError(NoDomainsFoundError);\n\t}\n\n\tGriddoLog.verbose(`getting domains names (${domains.length})`);\n\n\tconst filteredDomains = domains\n\t\t.filter(({ slug }) => !!slug)\n\t\t.map(({ slug }) => slug.replace(\"/\", \"\"));\n\n\treturn [...new Set(filteredDomains)];\n}\n\nexport { getInstanceDomains };\n"],
|
|
5
|
+
"mappings": "oeAIA,IAAAA,EAAgB,+BAChBC,EAAiB,wBCHjB,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,GAAG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AI,IAAM,SAClCA,EAAW,KAAK,SAAS,WAAW,IAEpC,MAAM,EAAAV,QAAK,KAAKQ,EAAUE,EAAW,IAAI,EAG5C,CAUA,eAAgBpB,GACfkB,EAC2B,CAC3B,IAAMG,EAAYJ,GAAgBC,CAAQ,EAE1C,cAAiBI,KAAYD,EAC5B,GAAI,CACH,IAAME,EAAc,MAAM,EAAAX,QAAI,SAASU,EAAU,MAAM,EACjDjB,EAAO,KAAK,MAAMkB,CAAW,EAE/BlB,EAAK,OACR,MAAMA,EAER,OAASS,EAAO,CACfC,EAAWS,GAAoBV,CAAK,CACrC,CAEF,CAEA,eAAeW,GAAsBC,EAAgB,CACpD,GAAM,CAAE,UAAAC,CAAU,EAAI,MAAMC,EAAuC,CAAE,OAAAF,CAAO,CAAC,EAE7E,MAAO,CACN,eAAgB,EAAAhB,QAAK,KAAKiB,EAAW,MAAM,EAC3C,eAAgB,EAAAjB,QAAK,KAAKiB,EAAW,OAAQ,WAAW,CACzD,CACD,CAEA,eAAeE,IAAsB,CACpC,GAAIC,EAAuB,CAC1B,IAAMC,EAAU,MAAMC,GAAmB,EACzC,QAAWN,KAAUK,EAAS,CAC7B,GAAM,CAAE,eAAApC,EAAgB,eAAAC,CAAe,EAAI,MAAM6B,GAAsBC,CAAM,EAE7E5B,EAAU,KAAK,gCAAgC4B,CAAM,EAAE,EACvD,MAAMjC,GAAiC,CACtC,eAAAE,EACA,eAAAC,CACD,CAAC,CACF,CACD,CACD,CAEA,eAAeqC,IAAe,CACzBH,GAAyBI,KAC5BpC,EAAU,KAAK,6BAA6B,EAC5C,MAAMX,EAA2B,CAChC,SAAUgD,GACV,eAAgB,EACjB,CAAC,EAEH,CAEA,eAAeC,IAAO,CACrB,MAAMC,EAAY,MAAM,EACxB,MAAMR,GAAoB,EAC1B,MAAMI,GAAa,CACpB,CAEAK,GAAiBF,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", "LoginError", "NoDomainsFoundError", "ReadFromStoreError", "UploadSearchError", "pathExists", "dir", "fsp", "distRollback", "domain", "data", "readDB", "exportsDir", "exportsDirBackup", "GriddoLog", "path", "fsp", "pathExists", "RenderError", "originalError", "throwError", "options", "stack", "error", "message", "expected", "hint", "errorColor", "GriddoLog", "brush", "extraText", "withErrorHandler", "fn", "data", "readDB", "root", "path", "distRollback", "RENDER_MODE", "writeDB", "import_node_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", "package_default", "DEFAULT_HEADERS", "package_default", "GRIDDO_API_URL", "GRIDDO_PUBLIC_API_URL", "AI_EMBEDDINGS", "ALERT", "DOMAINS", "GET_ALL", "GET_PAGE", "LOGIN", "RESET_RENDER", "ROBOTS", "SEARCH", "SETTINGS", "SITE_URI", "AuthService", "response", "LOGIN", "DEFAULT_HEADERS", "GRIDDO_BOT_USER", "GRIDDO_BOT_PASSWORD", "token", "throwError", "LoginError", "authService", "import_node_path", "getRenderPathsHydratedWithDomainFromDB", "options", "domain", "dbFilePath", "paths", "readDB", "path", "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", "getApi", "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", "getInstanceDomains", "domains", "getApi", "DOMAINS", "throwError", "NoDomainsFoundError", "GriddoLog", "filteredDomains", "slug", "postSearchInfo", "props", "title", "description", "image", "pageId", "languageId", "siteId", "url", "content", "template", "postApi", "SEARCH", "prepareHTMLContentForSearch", "tagsToRemove", "removeTagsRegex", "processedContent", "uploadRenderedSearchContentToAPI", "options", "htmlContentDir", "jsonContentDir", "pathExists", "GriddoLog", "gatsbyPageDataPages", "getPageDataPagesFromExports", "pagesUploadedCounter", "pageData", "result", "pageContext", "page", "openGraph", "pageMetadata", "compose", "htmlPath", "path", "htmlContent", "fsp", "pageObject", "error", "throwError", "UploadSearchError", "walkRecursively", "basePath", "filesHandle", "fileDirent", "jsonFiles", "filePath", "fileContent", "ReadFromStoreError", "getContentDirectories", "domain", "__exports", "getRenderPathsHydratedWithDomainFromDB", "uploadSearchContent", "GRIDDO_SEARCH_FEATURE", "domains", "getInstanceDomains", "aiEmbeddings", "GRIDDO_AI_EMBEDDINGS", "AI_EMBEDDINGS", "main", "authService", "withErrorHandler"]
|
|
7
7
|
}
|
package/build/index.js
CHANGED
|
@@ -349,7 +349,7 @@ var SITE_URI = `${GRIDDO_API_URL2}/site/`;
|
|
|
349
349
|
var package_default = {
|
|
350
350
|
name: "@griddo/cx",
|
|
351
351
|
description: "Griddo SSG based on Gatsby",
|
|
352
|
-
version: "11.10.
|
|
352
|
+
version: "11.10.12-rc.0",
|
|
353
353
|
authors: [
|
|
354
354
|
"Hisco <francis.vega@griddo.io>"
|
|
355
355
|
],
|
|
@@ -442,7 +442,7 @@ var package_default = {
|
|
|
442
442
|
publishConfig: {
|
|
443
443
|
access: "public"
|
|
444
444
|
},
|
|
445
|
-
gitHead: "
|
|
445
|
+
gitHead: "114a2b713bcf8b762705c3d492269600d4c95509"
|
|
446
446
|
};
|
|
447
447
|
|
|
448
448
|
// exporter/shared/headers.ts
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@griddo/cx",
|
|
3
3
|
"description": "Griddo SSG based on Gatsby",
|
|
4
|
-
"version": "11.10.
|
|
4
|
+
"version": "11.10.12-rc.0",
|
|
5
5
|
"authors": [
|
|
6
6
|
"Hisco <francis.vega@griddo.io>"
|
|
7
7
|
],
|
|
@@ -94,5 +94,5 @@
|
|
|
94
94
|
"publishConfig": {
|
|
95
95
|
"access": "public"
|
|
96
96
|
},
|
|
97
|
-
"gitHead": "
|
|
97
|
+
"gitHead": "114a2b713bcf8b762705c3d492269600d4c95509"
|
|
98
98
|
}
|