@griddo/cx 11.2.8 → 11.2.9

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.
@@ -28,7 +28,7 @@ function deleteSentinelRenderFile() {
28
28
  fs.unlinkSync(renderSentinelFile);
29
29
  }
30
30
 
31
- function isValidRenderProcessOrThrow() {
31
+ function isValidRender() {
32
32
  const { __cx } = config.paths();
33
33
  const renderSentinelFile = path.join(__cx, ".render-sentinel");
34
34
  if (!fs.existsSync(renderSentinelFile)) {
@@ -36,14 +36,6 @@ function isValidRenderProcessOrThrow() {
36
36
  }
37
37
  }
38
38
 
39
- function initRender() {
40
- createSentinelRenderFile();
41
- }
42
-
43
- function finishRender() {
44
- return undefined;
45
- }
46
-
47
39
  /**
48
40
  * Send the default registers through Griddo alerts.
49
41
  */
@@ -74,9 +66,6 @@ function sendGriddoDefaultAlerts() {
74
66
  export {
75
67
  createSentinelRenderFile,
76
68
  deleteSentinelRenderFile,
77
- finishRender,
78
- initRender,
79
- isValidRenderProcessOrThrow,
80
- sendGriddoDefaultAlerts
69
+ isValidRender,
70
+ sendGriddoDefaultAlerts,
81
71
  };
82
-
@@ -12,7 +12,7 @@ import { getBuildMetadata } from "./store";
12
12
  import { AuthService } from "../services/auth";
13
13
  import {
14
14
  endSiteRender,
15
- getAllSitesFromDomain,
15
+ getAllSites,
16
16
  getSiteInfo,
17
17
  getSiteLanguages,
18
18
  getSitemap,
@@ -26,19 +26,56 @@ const config = getConfig();
26
26
  * Check the instance sites and returns site prepared to be published and unpublished.
27
27
  */
28
28
  async function getSitesToRender(domain: string) {
29
- const allSites = await getAllSitesFromDomain(domain);
29
+ console.info(`API URL ${envs.GRIDDO_API_URL as string}`);
30
+
31
+ // Login to API
32
+ await AuthService.login();
33
+
34
+ // Get all sites. An array of Site
35
+ const allSites = await getAllSites(domain);
36
+
37
+ // Filter the array of sites to get only the ones to build/render
38
+ const validSites = envs.GRIDDO_RENDER_ALL_SITES
39
+ ? allSites.filter(
40
+ (site) =>
41
+ !envs.GRIDDO_RENDER_SITE || site.id === envs.GRIDDO_RENDER_SITE,
42
+ )
43
+ : allSites.filter((site) =>
44
+ envs.GRIDDO_RENDER_SITE
45
+ ? site.id === envs.GRIDDO_RENDER_SITE
46
+ : !!site.shouldBeUpdated,
47
+ );
48
+
49
+ // If there are valid sites...
50
+ // En este paso se añade al objeto `Site` la información de los dominios
51
+ // utilizando los idiomas.
52
+ if (validSites.length) {
53
+ for (const site of validSites) {
54
+ const { items } = await getSiteLanguages(site.id);
55
+
56
+ // Añadimos la prop domains con el dominio "cocinado" con los
57
+ // idiomas y teniendo en cuenta solo el dominio actual.
58
+ site.domains = items
59
+ .filter(
60
+ (item) =>
61
+ item.domain &&
62
+ (item.domain.slug === domain || item.domain.slug === `/${domain}`),
63
+ )
64
+ .map((item) => ({ [item.id]: `${item.domain.slug}${item.path}` }));
65
+ }
66
+ }
30
67
 
31
68
  // Save sites object to publish
32
- const sitesToPublish = allSites.filter((site) => {
33
- return envs.GRIDDO_RENDER_SITE
69
+ const sitesToPublish = validSites.filter((site) =>
70
+ envs.GRIDDO_RENDER_SITE
34
71
  ? site.id === envs.GRIDDO_RENDER_SITE
35
- : !!site.isPublished;
36
- });
72
+ : !!site.isPublished,
73
+ );
37
74
 
38
75
  // Save sites object to unpublish
39
- const sitesToUnpublish = allSites.filter((site) => {
40
- return !site.isPublished && site.shouldBeUpdated;
41
- });
76
+ const sitesToUnpublish = validSites.filter(
77
+ (site) => !site.isPublished && site.shouldBeUpdated,
78
+ );
42
79
 
43
80
  return {
44
81
  sitesToPublish,
@@ -21,7 +21,9 @@ const config = getConfig();
21
21
  *
22
22
  * @param domain - The domain to get the pages from.
23
23
  */
24
- function getBuildPagesFromCachedStore<PageType extends GriddoPageObject>(domain: string) {
24
+ function getBuildPagesFromCachedStore<PageType extends GriddoPageObject>(
25
+ domain: string,
26
+ ) {
25
27
  const { __cache } = config.paths(domain);
26
28
  return getBuildPagesFromStore<PageType>({
27
29
  basePath: path.join(__cache, "store"),
@@ -45,7 +47,9 @@ function* getBuildPagesFromStore<PageType extends GriddoPageObject>(args?: {
45
47
  const { __cx } = config.paths();
46
48
  const pagesDirPath = basePath || path.join(__cx, "store");
47
49
 
48
- const jsonFilePaths = walkStore(pagesDirPath).filter((file) => path.extname(file) === ".json");
50
+ const jsonFilePaths = walkStore(pagesDirPath).filter(
51
+ (file) => path.extname(file) === ".json",
52
+ );
49
53
 
50
54
  for (const filePath of jsonFilePaths) {
51
55
  try {
@@ -77,7 +81,9 @@ function getBuildPagesPath() {
77
81
  const { __cx } = config.paths();
78
82
 
79
83
  const PAGES_DIR = path.join(__cx, "store");
80
- const PAGE_FILES = walk(PAGES_DIR).filter((file) => path.extname(file) === ".json");
84
+ const PAGE_FILES = walk(PAGES_DIR).filter(
85
+ (file) => path.extname(file) === ".json",
86
+ );
81
87
 
82
88
  return PAGE_FILES;
83
89
  }
@@ -98,21 +104,6 @@ async function getBuildMetadata(): Promise<BuildMetaData> {
98
104
  };
99
105
  }
100
106
 
101
- /**
102
- * Creates an `store` dir to store pages transformed by createStore
103
- */
104
- function createStoreDir() {
105
- const { __cx } = config.paths();
106
- const storeDir = path.join(__cx, "store");
107
-
108
- if (!fs.existsSync(storeDir)) {
109
- fs.mkdirSync(storeDir);
110
- fs.mkdirSync(path.join(storeDir, "metadata"));
111
- }
112
-
113
- console.info("Store initialized");
114
- }
115
-
116
107
  /**
117
108
  * Write render info into a file.
118
109
  * @param renderInfo - Data that will be saved related to the render process.
@@ -120,7 +111,10 @@ function createStoreDir() {
120
111
  function saveRenderInfoInStore(renderInfo: RenderInfo) {
121
112
  const { __cx } = config.paths();
122
113
 
123
- fs.writeFileSync(path.join(__cx, "render-metadata.json"), JSON.stringify(renderInfo));
114
+ fs.writeFileSync(
115
+ path.join(__cx, "render-metadata.json"),
116
+ JSON.stringify(renderInfo),
117
+ );
124
118
  }
125
119
 
126
120
  /**
@@ -180,14 +174,17 @@ function getPageInStoreDir(basePath: string): Array<number> {
180
174
  * Save the pages into the file system.
181
175
  * @param pages - An array of Griddo page objects to be saved.
182
176
  */
183
- function savePagesInStore(siteFolderName: string, pages: Array<GriddoPageObject>) {
177
+ function saveSitePagesInStore(
178
+ siteDirName: string,
179
+ pages: Array<GriddoPageObject>,
180
+ ) {
184
181
  const { __cx } = config.paths();
185
182
 
186
183
  try {
187
184
  for (const page of pages) {
188
185
  removeProperties(page, ["editorID", "parentEditorID"]);
189
186
  const filename = `${page.context.page.id}.json`;
190
- const filePath = path.join(__cx, "store", siteFolderName, filename);
187
+ const filePath = path.join(__cx, "store", siteDirName, filename);
191
188
  fsx.writeJSONSync(filePath, page);
192
189
  }
193
190
  } catch (error) {
@@ -196,156 +193,44 @@ function savePagesInStore(siteFolderName: string, pages: Array<GriddoPageObject>
196
193
  }
197
194
 
198
195
  /**
199
- * Remove files from dir.
200
- * @param filenames - An array of ids representing file page names.
196
+ * Removes JSON files from the specified site directory based on the provided arrays of page numbers.
197
+ * For each number in the arrays, a corresponding file with the format `<number>.json` is removed if it exists.
198
+ *
199
+ * WARNING: This function may end up handling large arrays, so don't be tempted
200
+ * to refactor it to use something cool like the spread operator and make a
201
+ * single array, etc..
202
+ *
203
+ * @param siteDirName - The name of the site directory containing the pages.
204
+ * @param pageIdsArray - A two-dimensional array where each inner array contains numbers representing page files to be removed.
201
205
  */
202
- function removeSitePagesFromStore(siteDirName: string, filenames: Array<number>) {
206
+ function removeSitePagesFromStore(
207
+ siteDirName: string,
208
+ pageIdsArray: Array<Array<number>>,
209
+ ) {
203
210
  const { __cx } = config.paths();
204
211
 
205
- if (filenames.length === 0) {
206
- return;
207
- }
208
-
209
- for (const filename of filenames) {
210
- const filePath = path.join(__cx, "store", siteDirName, `${filename}.json`);
211
- try {
212
- fs.unlinkSync(filePath);
213
- } catch (error) {
214
- console.log(error);
215
- throw new Error(`Error removing file ${filename}`);
212
+ const processPageIdsArray = (pageIds: Array<number>) => {
213
+ for (const filename of pageIds) {
214
+ const filePath = path.join(
215
+ __cx,
216
+ "store",
217
+ siteDirName,
218
+ `${filename}.json`,
219
+ );
220
+ try {
221
+ if (fs.existsSync(filePath)) {
222
+ fs.unlinkSync(filePath);
223
+ verboseLog(`Removed file: ${filePath}`);
224
+ }
225
+ } catch (error) {
226
+ console.log(error);
227
+ throw new Error(`Error removing file ${filename}`);
228
+ }
216
229
  }
217
- }
218
- }
219
-
220
- /**
221
- * Returns pages that need to be created or deleted for a site in the store based on the provided arguments.
222
- * @param sitePages - Properties for page retrieval.
223
- * @param props.storeDir - Absolute path of the Griddo store.
224
- * @param props.pages - Exhaustive array of all pages in the site.
225
- * @param props.validPagesIds - Array of valid pages in the site.
226
- * @param props.changedPages - Array of pages that have been modified in the site.
227
- * @returns - An object containing the pages to be created and deleted in the site.
228
- */
229
- async function getSitePagesToCreateOrDelete(sitePages: {
230
- sitesToPublish: Array<Site>;
231
- validPagesIds: Array<number>;
232
- changedPages: Array<number>;
233
- siteDirName: string;
234
- }) {
235
- const { __cx } = config.paths();
236
- const storeDir = path.join(__cx, "store");
237
- const { changedPages, validPagesIds, siteDirName } = sitePages;
238
-
239
- // Array<ids> de las páginas que están físicamente en el store en el
240
- // site actual del bucle.
241
- const siteDirStorePath = path.join(storeDir, siteDirName);
242
- const pagesInStore = getPageInStoreDir(siteDirStorePath);
243
-
244
- // Array<ids> que están el `validPagesIds` pero no están por algún
245
- // motivo en el store. Se incluyen porque deben ser creadas.
246
- const pagesMissingInStore = validPagesIds.filter((page) => !pagesInStore.includes(page));
247
-
248
- // Array<ids> para enviar al store, que son las que han cambiado y
249
- // las missings.
250
- const pagesToStore = pagesMissingInStore.concat(changedPages);
251
-
252
- // Array<ids> de las páginas que han sido eliminadas para quitarlas
253
- // físicamente de la carpeta store.
254
- const pagesToDeleteFromStore = pagesInStore.filter((page) => {
255
- // Las que no estén en validPages
256
- return !validPagesIds.includes(page);
257
- });
258
-
259
- // 1 - Elimina del array final las páginas borradas.
260
- // 2 - Elimina las posibles páginas (ids) duplicadas. (new Set)
261
- const pagesToWriteToStore = Array.from(new Set(pagesToStore)).filter(
262
- (page) => !pagesToDeleteFromStore.includes(page),
263
- );
264
-
265
- return {
266
- pagesInStore,
267
- pagesMissingInStore,
268
- pagesToDeleteFromStore: [
269
- ...pagesToDeleteFromStore,
270
- // ...pagesFromInvalidSites,
271
- ],
272
- pagesToWriteToStore,
273
- };
274
- }
275
-
276
- /**
277
- * Returns pages that need to be created or deleted for a site in the store based on the provided arguments.
278
- * @param sitePages - Properties for page retrieval.
279
- * @param props.storeDir - Absolute path of the Griddo store.
280
- * @param props.pages - Exhaustive array of all pages in the site.
281
- * @param props.validPagesIds - Array of valid pages in the site.
282
- * @param props.changedPages - Array of pages that have been modified in the site.
283
- * @returns - An object containing the pages to be created and deleted in the site.
284
- */
285
- async function getSitePagesToCreateOrDeleteCached(sitePages: {
286
- sitesToPublish: Array<Site>;
287
- validPagesIds: Array<number>;
288
- changedPages: Array<number>;
289
- siteDirName: string;
290
- domain: string;
291
- }) {
292
- const { changedPages, validPagesIds, siteDirName, domain } = sitePages;
293
-
294
- const { __cache } = config.paths(domain);
295
- const storeDir = path.join(__cache, "store");
296
-
297
- // Array<ids> de las páginas que están físicamente en el store en el
298
- // site actual del bucle.
299
- const siteDirStorePath = path.join(storeDir, siteDirName);
300
- const pagesInStore = getPageInStoreDir(siteDirStorePath);
301
-
302
- // Array<ids> que están el `validPagesIds` pero no están por algún
303
- // motivo en el store. Se incluyen porque deben ser creadas.
304
- const pagesMissingInStore = validPagesIds.filter((page) => !pagesInStore.includes(page));
305
-
306
- // Array<ids> para enviar al store, que son las que han cambiado y
307
- // las missings.
308
- const pagesToStore = pagesMissingInStore.concat(changedPages);
309
-
310
- // Array<ids> de las páginas que han sido eliminadas para quitarlas
311
- // físicamente de la carpeta store.
312
- const pagesToDeleteFromStore = pagesInStore.filter((page) => {
313
- // Las que no estén en validPages
314
- return !validPagesIds.includes(page);
315
- });
316
-
317
- // 1 - Elimina del array final las páginas borradas.
318
- // 2 - Elimina las posibles páginas (ids) duplicadas. (new Set)
319
- const pagesToWriteToStore = Array.from(new Set(pagesToStore)).filter(
320
- (page) => !pagesToDeleteFromStore.includes(page),
321
- );
322
-
323
- return {
324
- pagesInStore,
325
- pagesMissingInStore,
326
- pagesToDeleteFromStore: [
327
- ...pagesToDeleteFromStore,
328
- // ...pagesFromInvalidSites,
329
- ],
330
- pagesToWriteToStore,
331
230
  };
332
- }
333
231
 
334
- /**
335
- * Removes sites from store that are not in `sitesToPublish` array.
336
- */
337
- function deleteZombieSitesFoldersFromStore(sitesToPublish: Array<Site>) {
338
- const { __cx } = getConfig().paths();
339
- const storeDir = path.join(__cx, "store");
340
- const siteDirs = fs.readdirSync(storeDir, { withFileTypes: true });
341
- const siteIds = sitesToPublish.map((site) => `${site.id}`);
342
- for (const dir of siteDirs) {
343
- if (dir.isDirectory() && !siteIds.includes(dir.name)) {
344
- fs.rmSync(path.join(storeDir, dir.name), {
345
- force: true,
346
- recursive: true,
347
- });
348
- }
232
+ for (const pageIds of pageIdsArray) {
233
+ processPageIdsArray(pageIds);
349
234
  }
350
235
  }
351
236
 
@@ -358,7 +243,9 @@ function removeOrphanSites(sitesToPublish: Array<Site>, domain: string) {
358
243
  const { __cx } = getConfig().paths(domain);
359
244
  const currentSitesInStore = fs.readdirSync(path.join(__cx, "store"));
360
245
  const sitesFromAPI = sitesToPublish.map(({ id }) => `${id}`);
361
- const sitesToDelete = currentSitesInStore.filter((site) => !sitesFromAPI.includes(site));
246
+ const sitesToDelete = currentSitesInStore.filter(
247
+ (site) => !sitesFromAPI.includes(site),
248
+ );
362
249
 
363
250
  for (const site of sitesToDelete) {
364
251
  fs.rmSync(path.join(__cx, "store", site), { recursive: true, force: true });
@@ -366,18 +253,55 @@ function removeOrphanSites(sitesToPublish: Array<Site>, domain: string) {
366
253
  }
367
254
  }
368
255
 
256
+ /**
257
+ * Returns the list of `activePages` pages that do not currently exist in a
258
+ * site's store (probably due to a failed render).
259
+ */
260
+ function getMissingPublishedPagesInStore(
261
+ siteName: string,
262
+ activePages: Array<number>,
263
+ ) {
264
+ const { __cx } = config.paths();
265
+ const pagesInStore = getPageInStoreDir(path.join(__cx, "store", siteName));
266
+ const missingActivePages: Array<number> = [];
267
+ for (const activePage of activePages) {
268
+ if (!pagesInStore.includes(activePage)) {
269
+ missingActivePages.push(activePage);
270
+ }
271
+ }
272
+ return missingActivePages;
273
+ }
274
+
275
+ /**
276
+ * Get pages that are not active anymore but are in the store.
277
+ */
278
+ function getZombiePagesInStore(siteDir: string, pages: Array<number>) {
279
+ const { __cx } = getConfig().paths();
280
+ const storeDir = path.join(__cx, "store", siteDir);
281
+ const sitePages = fs.readdirSync(storeDir);
282
+
283
+ let zombiePages: Array<number> = [];
284
+ for (const pageFileName of sitePages) {
285
+ const pageFileNameWithoutExtension = pageFileName.split(".")[0];
286
+ const pageId = Number.parseInt(pageFileNameWithoutExtension);
287
+ if (!pages.includes(pageId)) {
288
+ zombiePages.push(pageId);
289
+ }
290
+ }
291
+
292
+ return zombiePages;
293
+ }
294
+
369
295
  export {
370
- createStoreDir,
371
- deleteZombieSitesFoldersFromStore,
372
296
  getBuildMetadata,
373
297
  getBuildPagesFromCachedStore,
374
298
  getBuildPagesFromStore,
375
299
  getBuildPagesPath,
300
+ getMissingPublishedPagesInStore,
376
301
  getPageInStoreDir,
377
- getSitePagesToCreateOrDelete,
378
- getSitePagesToCreateOrDeleteCached,
302
+ getZombiePagesInStore,
379
303
  removeOrphanSites,
380
304
  removeSitePagesFromStore,
381
- savePagesInStore,
305
+ saveSitePagesInStore,
382
306
  saveRenderInfoInStore,
383
307
  };
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.2.8",
4
+ "version": "11.2.9",
5
5
  "authors": [
6
6
  "Álvaro Sánchez' <alvaro.sanches@secuoyas.com>",
7
7
  "Diego M. Béjar <diego.bejar@secuoyas.com>",
@@ -38,9 +38,9 @@
38
38
  "build": "sh ./exporter/build.sh",
39
39
  "build:debug": "sh ./exporter/build.sh --debug",
40
40
  "// TESTS": "",
41
- "test": "tsx ./__tests__/utils/tests-health.ts && jest --verbose",
42
- "test:create-render-fixtures": "tsx ./__tests__/utils/create-fixtures.ts",
43
- "test:remove-render-fixtures": "tsx ./__tests__/utils/remove-fixtures.ts",
41
+ "test": "NODE_OPTIONS='--import tsx' env-cmd node --test ./__tests__/*",
42
+ "test:create-render-fixtures": "env-cmd tsx ./__tests__/utils/create-fixtures.ts",
43
+ "test:remove-render-fixtures": "env-cmd tsx ./__tests__/utils/remove-fixtures.ts",
44
44
  "// INFRA SCRIPTS": "",
45
45
  "upload-search-content": "node ./build/upload-search-content.js",
46
46
  "complete-render": "node ./build/end-render.js",
@@ -65,7 +65,7 @@
65
65
  "@babel/preset-env": "7.26.0",
66
66
  "@babel/preset-react": "7.26.3",
67
67
  "@babel/preset-typescript": "7.26.0",
68
- "@griddo/core": "11.2.8",
68
+ "@griddo/core": "11.2.9",
69
69
  "@svgr/webpack": "5.5.0",
70
70
  "axios": "1.7.9",
71
71
  "babel-loader": "9.2.1",
@@ -90,7 +90,6 @@
90
90
  "@types/cheerio": "0.22.35",
91
91
  "@types/eslint": "8.56.10",
92
92
  "@types/fs-extra": "11.0.4",
93
- "@types/jest": "29.5.14",
94
93
  "@types/node": "20.17.10",
95
94
  "@types/webpack": "5.28.5",
96
95
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -103,9 +102,7 @@
103
102
  "eslint-plugin-react-hooks": "^4.6.0",
104
103
  "eslint-plugin-testing-library": "^6.2.0",
105
104
  "globals": "^16.0.0",
106
- "jest": "29.7.0",
107
- "prettier": "3.4.2",
108
- "ts-jest": "29.2.5"
105
+ "prettier": "3.4.2"
109
106
  },
110
107
  "peerDependencies": {
111
108
  "@types/react": ">=18 <19",
@@ -133,5 +130,5 @@
133
130
  "publishConfig": {
134
131
  "access": "public"
135
132
  },
136
- "gitHead": "058e6737daf99b0f3651067d326446e7747a0403"
133
+ "gitHead": "7ccf2bdd0e654a539eb8fadc4a419152d7623b66"
137
134
  }
@@ -1,7 +0,0 @@
1
- /**
2
- * Spawn a new node process to upload the domain content.
3
- * @note This proccess can not access to the custom Griddo `process.env` so it
4
- * needs variables passed to it via the `env` prop
5
- */
6
- declare function publishDomain(domain: string): string;
7
- export { publishDomain };
@@ -1,29 +0,0 @@
1
- import { spawn } from "node:child_process";
2
-
3
- import dotenv from "dotenv";
4
-
5
- import { getConfig } from "./core-utils";
6
-
7
- dotenv.config();
8
-
9
- /**
10
- * Spawn a new node process to upload the domain content.
11
- * @note This proccess can not access to the custom Griddo `process.env` so it
12
- * needs variables passed to it via the `env` prop
13
- */
14
- function publishDomain(domain: string) {
15
- return domain;
16
- // const config = getConfig();
17
- // const { __exports_dist } = config.paths(domain);
18
- // const command = spawn("aws-scyn", [".", "bucket"], {
19
- // cwd: __exports_dist,
20
- // stdio: ["ignore", "inherit", "ignore"],
21
- // shell: true,
22
- // });
23
-
24
- // command.on("error", (error) => {
25
- // console.error("Error in publishDomain:", error);
26
- // });
27
- }
28
-
29
- export { publishDomain };