@griddo/cx 10.6.3 → 10.6.5

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.
Files changed (72) hide show
  1. package/README.md +0 -2
  2. package/build/adapters/gatsby/index.d.ts +1 -1
  3. package/build/build-complete.js +69 -30
  4. package/build/constants/endpoints.d.ts +18 -0
  5. package/build/constants/envs.d.ts +33 -0
  6. package/build/constants/index.d.ts +53 -0
  7. package/build/index.d.ts +4 -3
  8. package/build/index.js +90 -49
  9. package/build/reset-render.js +69 -30
  10. package/build/run-start-render.js +90 -49
  11. package/build/services/settings.d.ts +3 -22
  12. package/build/services/sites.d.ts +34 -36
  13. package/build/start-render.js +90 -49
  14. package/build/types/global.d.ts +1 -1
  15. package/build/upload-search-content.js +70 -31
  16. package/build/utils/core-utils.d.ts +9 -60
  17. package/build/utils/domains.d.ts +5 -1
  18. package/build/utils/loggin.d.ts +49 -0
  19. package/build/utils/render.d.ts +11 -0
  20. package/cx.config.js +3 -4
  21. package/exporter/adapters/gatsby/index.ts +95 -257
  22. package/exporter/adapters/gatsby/utils.ts +11 -10
  23. package/exporter/browser/index.ts +4 -4
  24. package/exporter/constants/endpoints.ts +42 -0
  25. package/exporter/constants/envs.ts +86 -0
  26. package/exporter/constants/index.ts +120 -0
  27. package/exporter/errors/index.ts +2 -2
  28. package/exporter/index.ts +11 -10
  29. package/exporter/react/GriddoIntegrations/index.tsx +3 -3
  30. package/exporter/{build-complete.ts → scripts/build-complete.ts} +4 -4
  31. package/exporter/{reset-render.ts → scripts/reset-render.ts} +3 -3
  32. package/exporter/scripts/start-render.ts +26 -0
  33. package/exporter/{upload-search-content.ts → scripts/upload-search-content.ts} +3 -3
  34. package/exporter/services/auth.ts +7 -5
  35. package/exporter/services/distributors.ts +12 -18
  36. package/exporter/services/domains.ts +2 -12
  37. package/exporter/services/navigation.ts +10 -8
  38. package/exporter/services/robots.ts +2 -6
  39. package/exporter/services/settings.ts +7 -44
  40. package/exporter/services/sites.ts +115 -159
  41. package/exporter/services/store.ts +24 -29
  42. package/exporter/types/api.ts +1 -1
  43. package/exporter/types/global.ts +1 -0
  44. package/exporter/utils/api.ts +11 -10
  45. package/exporter/utils/core-utils.ts +49 -180
  46. package/exporter/utils/domains.ts +21 -3
  47. package/exporter/utils/folders.ts +3 -3
  48. package/exporter/utils/health-checks.ts +4 -4
  49. package/exporter/utils/instance.ts +3 -3
  50. package/exporter/utils/integrations.ts +12 -12
  51. package/exporter/utils/loggin.ts +159 -0
  52. package/exporter/utils/pages.ts +15 -15
  53. package/exporter/utils/render.ts +49 -0
  54. package/exporter/utils/searches.ts +5 -5
  55. package/exporter/utils/sites.ts +42 -48
  56. package/exporter/utils/store.ts +9 -9
  57. package/gatsby-browser.tsx +46 -48
  58. package/gatsby-config.ts +5 -5
  59. package/gatsby-node.ts +7 -7
  60. package/package.json +21 -26
  61. package/src/components/Head.tsx +1 -1
  62. package/src/gatsby-node-utils.ts +1 -1
  63. package/src/utils.ts +1 -1
  64. package/exporter/start-render.ts +0 -18
  65. /package/build/{build-complete.d.ts → scripts/build-complete.d.ts} +0 -0
  66. /package/build/{move-assets.d.ts → scripts/move-assets.d.ts} +0 -0
  67. /package/build/{reset-render.d.ts → scripts/reset-render.d.ts} +0 -0
  68. /package/build/{run-start-render.d.ts → scripts/run-start-render.d.ts} +0 -0
  69. /package/build/{start-render.d.ts → scripts/start-render.d.ts} +0 -0
  70. /package/build/{upload-search-content.d.ts → scripts/upload-search-content.d.ts} +0 -0
  71. /package/exporter/{move-assets.ts → scripts/move-assets.ts} +0 -0
  72. /package/exporter/{run-start-render.ts → scripts/run-start-render.ts} +0 -0
@@ -1,4 +1,3 @@
1
- import type { Adapters } from "../adapters";
2
1
  import type { APIResponses } from "../types/api";
3
2
  import type { CXConfig, LifeCyclesNames } from "../types/global";
4
3
  import type { APIPageObject } from "../types/pages";
@@ -10,33 +9,18 @@ import path from "node:path";
10
9
  import chalk from "chalk";
11
10
  import dotenv from "dotenv";
12
11
  import fsx from "fs-extra";
13
- import gradient from "gradient-string";
14
12
  import pkgDir from "pkg-dir";
15
13
 
16
14
  import { createDirsSync, removeDirsSync } from "./folders";
15
+ import { boxLog, verboseLog } from "./loggin";
16
+ import { envs } from "../constants";
17
17
 
18
18
  dotenv.config();
19
19
 
20
20
  const config = getConfig();
21
21
 
22
- const GRIDDO_DEBUG_LOGS = isTruthy(process.env.GRIDDO_DEBUG_LOGS);
23
- const GRIDDO_BUILD_LOGS = isTruthy(process.env.GRIDDO_BUILD_LOGS);
24
-
25
22
  const instanceRootDir = pkgDir.sync()!; // instance root dir
26
23
 
27
- const attempts = {
28
- clean: JSON.parse(process.env.GRIDDO_CLEAN_LIFECYCLE_MAX_ATTEMPTS || "1"),
29
- prepare: JSON.parse(process.env.GRIDDO_PREPARE_LIFECYCLE_MAX_ATTEMPTS || "1"),
30
- restore: JSON.parse(process.env.GRIDDO_RESTORE_LIFECYCLE_MAX_ATTEMPTS || "1"),
31
- data: JSON.parse(process.env.GRIDDO_DATA_LIFECYCLE_MAX_ATTEMPTS || "1"),
32
- ssg: JSON.parse(process.env.GRIDDO_SSG_LIFECYCLE_MAX_ATTEMPTS || "2"),
33
- relocation: JSON.parse(
34
- process.env.GRIDDO_RELOCATION_LIFECYCLE_MAX_ATTEMPTS || "1"
35
- ),
36
- meta: JSON.parse(process.env.GRIDDO_META_LIFECYCLE_MAX_ATTEMPTS || "4"),
37
- archive: JSON.parse(process.env.GRIDDO_ARCHIVE_LIFECYCLE_MAX_ATTEMPTS || "1"),
38
- };
39
-
40
24
  /**
41
25
  * Returns the configuration file content.
42
26
  *
@@ -67,9 +51,9 @@ async function exporterCreateInitialDirectories(domain: string) {
67
51
  const { __exports, __caches } = config.paths(domain);
68
52
 
69
53
  createDirsSync([__exports]);
70
- verbose("create `exports/sites/<domain>` directory");
54
+ verboseLog("create `exports/sites/<domain>` directory");
71
55
  createDirsSync([__caches]);
72
- verbose("create `caches/<domain>` directory");
56
+ verboseLog("create `caches/<domain>` directory");
73
57
  }
74
58
 
75
59
  /**
@@ -81,21 +65,7 @@ async function exporterCleanDisposableDirectories(domain: string) {
81
65
  const { __cx } = config.paths(domain);
82
66
 
83
67
  removeDirsSync(__cx, ["store", "apiCache", "dist"]);
84
- verbose("clean `store`, `apiCache` and `dist` directories from `__cx`");
85
- }
86
-
87
- /**
88
- * Custom basic logging function controlled by a environment variable.
89
- *
90
- * @param str The string to be logged.
91
- */
92
- function verbose(str: string) {
93
- if (GRIDDO_DEBUG_LOGS) {
94
- console.log(
95
- chalk.hex("#ffff33")("verbose"),
96
- chalk.gray(str.replace(/(\s)\s+/g, "$1").trim())
97
- );
98
- }
68
+ verboseLog("clean `store`, `apiCache` and `dist` directories from `__cx`");
99
69
  }
100
70
 
101
71
  /**
@@ -142,70 +112,6 @@ function walk(dir: string) {
142
112
  return results;
143
113
  }
144
114
 
145
- /**
146
- * Custom log inside a line-box.
147
- *
148
- * @param stringValue The string to be logged.
149
- * @param paddingInline The number of white spaces inside the box at left and right.
150
- * @param paddingBlock The number of white spaces inside the box at top and bottom.
151
- */
152
- function logBox(
153
- stringValue: string,
154
- title = "",
155
- paddingInline = 1,
156
- paddingBlock = 1
157
- ) {
158
- const lines = stringValue
159
- .split("\n") // lines
160
- .map((line) => line.trim()); // remove extra spaces
161
- const windowTitle = title ? ` ${title} ` : "";
162
- const windowTitleLength = title ? windowTitle.length : 0;
163
- const longerContent =
164
- Math.max(...lines.map((l) => l.length)) + paddingInline * 2;
165
- const longerLine = Math.max(longerContent, windowTitleLength);
166
- const paddingBlockString = `│${" ".repeat(longerLine)}│\n`.repeat(
167
- paddingBlock
168
- );
169
- const minWidth = longerLine;
170
- const borderTop = `╭${windowTitle}${"─".repeat(
171
- minWidth - windowTitleLength
172
- )}╮\n`;
173
- const borderBottom = `╰${"─".repeat(minWidth)}╯`;
174
- const content = lines
175
- .map((l) => {
176
- const mr = " ".repeat(longerLine - l.length - paddingInline);
177
- return `│${" ".repeat(paddingInline)}${l}${mr}│\n`;
178
- })
179
- .join("");
180
-
181
- console.log(
182
- `${borderTop}${paddingBlockString}${content}${paddingBlockString}${borderBottom}`
183
- );
184
- }
185
-
186
- /**
187
- * Custom basic logging function controlled by a environment variable.
188
- * Strip double spaces.
189
- *
190
- * @param str The string to be logged.
191
- */
192
- function logInfo(str: string) {
193
- if (GRIDDO_BUILD_LOGS) {
194
- console.info(str.replace(/(\s)\s+/g, "$1").trim());
195
- }
196
- }
197
-
198
- /**
199
- * Internal log
200
- * @param values The values to be logged.
201
- */
202
- function debug(...values: Array<unknown>) {
203
- if (!GRIDDO_DEBUG_LOGS) {
204
- return;
205
- }
206
- console.log(...values);
207
- }
208
-
209
115
  /**
210
116
  * Custom delay using the "promise hack",
211
117
  *
@@ -215,33 +121,6 @@ function delay(ms: number) {
215
121
  return new Promise((res) => setTimeout(res, ms));
216
122
  }
217
123
 
218
- /**
219
- * Return a scale size colors with a number and a measure string (KB by default).
220
- *
221
- * @param size The page size in KB.
222
- * @param measure The measure string to be added in the log.
223
- */
224
- function logPageSize(size: number, measure = "KB") {
225
- const sizeScale = {
226
- low: 50,
227
- mid: 80,
228
- large: 130,
229
- extraLarge: 210,
230
- };
231
-
232
- // Ternary pawa!
233
- const color =
234
- size > sizeScale.large
235
- ? "red"
236
- : size > sizeScale.mid
237
- ? "magenta"
238
- : size > sizeScale.low
239
- ? "blue"
240
- : "green";
241
-
242
- return chalk[color].bold(`${size}${measure}`);
243
- }
244
-
245
124
  /**
246
125
  * Converts milliseconds to seconds with a fixed number of decimals.
247
126
  *
@@ -259,9 +138,9 @@ export function msToSec(ms: number, decimals = 3) {
259
138
  */
260
139
  export function getSafeSiteId(response: APIResponses) {
261
140
  if (typeof response === "string") {
262
- return undefined
141
+ return undefined;
263
142
  }
264
-
143
+
265
144
  return "site" in response && response.site ? response?.site : undefined;
266
145
  }
267
146
 
@@ -290,23 +169,6 @@ function siteList(sites: Array<Site>) {
290
169
  return sites.map(({ name, id }) => `${name} (${id})`).join(", ");
291
170
  }
292
171
 
293
- /**
294
- * Print the great Griddo Exporter logo in ASCII.
295
- */
296
- function printExporterLogo(adapter: Adapters) {
297
- const nodeVersion = process.version;
298
- const { griddoVersion } = config;
299
- const logo = `
300
- ··
301
- ·· Griddo Exporter ${griddoVersion}
302
- ·· Adapter: ${adapter}
303
- ·· Node: ${nodeVersion}
304
- ··
305
- `;
306
-
307
- console.log(gradient.cristal(logo));
308
- }
309
-
310
172
  /**
311
173
  * Remove unused files (old) inside the `apiCache` dir
312
174
  *
@@ -376,12 +238,16 @@ function sanitizeAPICacheDir() {
376
238
  * @returns A promise that resolves with the total execution time in seconds.
377
239
  */
378
240
  async function measureExecutionTime(
379
- ...functions: Array<(...args: Array<unknown>) => unknown | Promise<any>>
241
+ functions: Array<(...args: Array<unknown>) => unknown | Promise<unknown>>,
242
+ delayInMS = 0,
380
243
  ): Promise<number> {
381
244
  const start = process.hrtime();
382
245
 
383
246
  for (const func of functions) {
384
247
  await func();
248
+ if (delayInMS > 0) {
249
+ await delay(delayInMS);
250
+ }
385
251
  }
386
252
 
387
253
  const [seconds, miliseconds] = process.hrtime(start);
@@ -392,7 +258,7 @@ async function measureExecutionTime(
392
258
 
393
259
  function pause(title: string) {
394
260
  const isPauseEnabled = !!JSON.parse(
395
- process.env.GRIDDO_RENDER_BREAKPOINTS_FEATURE || "false"
261
+ process.env.GRIDDO_RENDER_BREAKPOINTS_FEATURE || "false",
396
262
  );
397
263
 
398
264
  if (!isPauseEnabled) {
@@ -401,51 +267,63 @@ function pause(title: string) {
401
267
 
402
268
  return new Promise<void>((resolve) => {
403
269
  console.log("\n");
404
- logBox(`⌛️ ${title}`, "", 1, 0);
270
+ boxLog(`⌛️ ${title}`, "", 1, 0);
405
271
  process.stdin.once("data", () => {
406
272
  resolve();
407
273
  });
408
274
  });
409
275
  }
410
276
 
411
- function startLifeCycle(lifeCyleName: string) {
412
- console.info(`
413
- ${chalk.blue(`info`)} start ${lifeCyleName} life-cycle`);
414
- }
415
-
416
- function successLifeCyle(value: string) {
417
- console.info(`${chalk.green("success")} ${value}`);
418
- }
419
-
420
277
  /**
421
278
  * Executes a life cycle process, which involves executing an array of
422
279
  * functions, printing to the console, and handling errors with optional
423
280
  * retries.
424
281
  *
425
282
  * @async
426
- * @param args - The arguments object.
427
- * @param args.steps - An array of functions to execute.
428
- * @param args.name - The name of the life cycle.
429
- * @param args.attempts=1 - The number of retry attempts allowed in case of errors.
430
- * @param args.bypass - Skip the step functions.
283
+ * @param options - The arguments object.
284
+ * @param options.steps - An array of functions to execute.
285
+ * @param options.delay - Delay between steps functions.
286
+ * @param options.bypass - Skip the step functions.
431
287
  * @returns - A promise that resolves when the life cycle process is completed.
432
288
  */
433
- async function doLifeCycle(args: {
434
- steps: Array<(...args: Array<unknown>) => unknown | Promise<any>>;
435
- name: LifeCyclesNames;
436
- attempts?: number;
437
- }) {
438
- const { steps, name, attempts } = args;
289
+ async function doLifeCycle(
290
+ name: LifeCyclesNames,
291
+ options: {
292
+ steps: Array<(...args: Array<unknown>) => unknown | Promise<any>>;
293
+ delay?: number;
294
+ bypass?: boolean;
295
+ },
296
+ ) {
297
+ const { steps, bypass, delay } = options;
298
+
299
+ if (bypass) {
300
+ return;
301
+ }
302
+
303
+ const attemptsByLifeCycleName: Record<LifeCyclesNames, number> = {
304
+ Archive: envs.GRIDDO_ARCHIVE_LIFECYCLE_MAX_ATTEMPTS,
305
+ Data: envs.GRIDDO_DATA_LIFECYCLE_MAX_ATTEMPTS,
306
+ Meta: envs.GRIDDO_META_LIFECYCLE_MAX_ATTEMPTS,
307
+ Relocation: envs.GRIDDO_RELOCATION_LIFECYCLE_MAX_ATTEMPTS,
308
+ Clean: envs.GRIDDO_CLEAN_LIFECYCLE_MAX_ATTEMPTS,
309
+ Restore: envs.GRIDDO_RESTORE_LIFECYCLE_MAX_ATTEMPTS,
310
+ Prepare: envs.GRIDDO_PREPARE_LIFECYCLE_MAX_ATTEMPTS,
311
+ Close: envs.GRIDDO_CLOSE_LIFECYCLE_MAX_ATTEMPTS,
312
+ SSG: envs.GRIDDO_SSG_LIFECYCLE_MAX_ATTEMPTS,
313
+ HealthCheck: 1,
314
+ __DEBUG__: 1,
315
+ };
439
316
 
440
317
  let trysCount = 0;
441
- const maxTrysAccepted = attempts || 1;
318
+ const maxTrysAccepted = attemptsByLifeCycleName[name] || 1;
442
319
 
443
320
  while (trysCount < maxTrysAccepted) {
444
321
  try {
445
322
  console.info(`\n${chalk.blue(`info`)} start ${name} life-cycle`);
446
- const exeTime = await measureExecutionTime(...steps);
323
+ const exeTime = await measureExecutionTime(steps, delay);
447
324
  console.info(`${chalk.green("success")} ${name} - ${exeTime}s`);
448
325
  // if no errors, go out!! :)
326
+ await pause(`${name} LifeCycle`);
449
327
  break;
450
328
  } catch (error) {
451
329
  const errorString = chalk.bgRed.black(` Error in ${name} LifeCycle `);
@@ -459,7 +337,7 @@ async function doLifeCycle(args: {
459
337
  }
460
338
  if (trysCount === maxTrysAccepted) {
461
339
  throw new Error(
462
- `Exceeded maximum retry attempts (${maxTrysAccepted}) for ${name} LifeCycle`
340
+ `Exceeded maximum retry attempts (${maxTrysAccepted}) for ${name} LifeCycle`,
463
341
  );
464
342
  }
465
343
  }
@@ -484,8 +362,6 @@ function isVersionLowerThan(versionA: string, versionB: string) {
484
362
  }
485
363
 
486
364
  export {
487
- attempts,
488
- debug,
489
365
  delay,
490
366
  doLifeCycle,
491
367
  exporterCleanDisposableDirectories,
@@ -495,17 +371,10 @@ export {
495
371
  isTruthy,
496
372
  isVersionGreaterThan,
497
373
  isVersionLowerThan,
498
- logBox,
499
- logInfo,
500
- logPageSize,
501
374
  measureExecutionTime,
502
375
  pause,
503
- printExporterLogo,
504
376
  removeProperties,
505
377
  sanitizeAPICacheDir,
506
378
  siteList,
507
- startLifeCycle,
508
- successLifeCyle,
509
- verbose,
510
379
  walk,
511
380
  };
@@ -1,9 +1,27 @@
1
1
  import type { Domains } from "../types/global";
2
2
 
3
- import { verbose } from "./core-utils";
3
+ import { verboseLog } from "./loggin";
4
+ import { throwError } from "../errors";
5
+ import { NoDomainsFoundError } from "../errors/errors-data";
4
6
  import { AuthService } from "../services/auth";
5
7
  import { DomainsService } from "../services/domains";
6
8
 
9
+ /**
10
+ * Return an array of domains name (string) of the current instance.
11
+ */
12
+ async function getInstanceDomainsOrThrow() {
13
+ await AuthService.login();
14
+ const domains = await DomainsService.getAll();
15
+
16
+ if (!domains.length) {
17
+ throwError(NoDomainsFoundError);
18
+ }
19
+
20
+ verboseLog(`getting domains names (${domains.length})`);
21
+
22
+ return getDomainSlugs(domains);
23
+ }
24
+
7
25
  /**
8
26
  * Return an array of domains name (string) of the current instance.
9
27
  */
@@ -11,7 +29,7 @@ async function getInstanceDomains() {
11
29
  await AuthService.login();
12
30
  const domains = await DomainsService.getAll();
13
31
 
14
- verbose(`Getting domains slugs (${domains.length})`);
32
+ verboseLog(`Getting domains slugs (${domains.length})`);
15
33
 
16
34
  return getDomainSlugs(domains);
17
35
  }
@@ -30,4 +48,4 @@ function getDomainSlugs(domains: Domains) {
30
48
  return [...new Set(filteredDomains)];
31
49
  }
32
50
 
33
- export { getInstanceDomains };
51
+ export { getInstanceDomains, getInstanceDomainsOrThrow };
@@ -90,7 +90,7 @@ function copyDirsSync(
90
90
  dirs: Array<string>,
91
91
  options = {
92
92
  withBackup: false,
93
- }
93
+ },
94
94
  ) {
95
95
  const { withBackup } = options;
96
96
  for (const dir of dirs) {
@@ -144,7 +144,7 @@ function moveDirsSync(
144
144
  src: string,
145
145
  dst: string,
146
146
  dirs: Array<string>,
147
- options?: { withBackup?: boolean; override?: boolean }
147
+ options?: { withBackup?: boolean; override?: boolean },
148
148
  ) {
149
149
  const { override, withBackup } = options || {};
150
150
 
@@ -255,7 +255,7 @@ async function removeVirtualPagesFromStore() {
255
255
  removePagesFromStore(multiPageFiles);
256
256
  } catch (e) {
257
257
  console.info(
258
- "`store` folder does not exist. Skipping multipage or static list template cleaning."
258
+ "`store` folder does not exist. Skipping multipage or static list template cleaning.",
259
259
  );
260
260
  }
261
261
  }
@@ -1,4 +1,4 @@
1
- import { logBox } from "./core-utils";
1
+ import { boxLog } from "./loggin";
2
2
 
3
3
  const GRIDDO_SKIP_BUILD_CHECKS = process.env.GRIDDO_SKIP_BUILD_CHECKS;
4
4
  const GRIDDO_ENVS_VARS: ReadonlyArray<string> = [];
@@ -30,9 +30,9 @@ function checkRenderHealthOrExit() {
30
30
  }
31
31
 
32
32
  // Error
33
- logBox(
33
+ boxLog(
34
34
  `Error. The environment is not suitable for a build.`,
35
- "Not valid environment"
35
+ "Not valid environment",
36
36
  );
37
37
  process.exit(1);
38
38
  }
@@ -52,7 +52,7 @@ function checkEnvsVars(envs: ReadonlyArray<string>) {
52
52
  if (missingEnvs.length) {
53
53
  const missingEnvsMsg = missingEnvs.join("\n");
54
54
  console.error(
55
- `Env check failed. These envs vars are missing: \n\n${missingEnvsMsg}`
55
+ `Env check failed. These envs vars are missing: \n\n${missingEnvsMsg}`,
56
56
  );
57
57
 
58
58
  return false;
@@ -18,8 +18,8 @@ function resolveComponentsPath(customPath = "") {
18
18
  : path.resolve(
19
19
  pkgDir.sync(__dirname) as string,
20
20
  "../griddo-components",
21
- customPath
22
- );
21
+ customPath,
22
+ );
23
23
  }
24
24
 
25
25
  /**
@@ -65,7 +65,7 @@ function getComponentsLibAliases() {
65
65
  // Por este motivo se puede hacer `... import from "@griddo-instance" en
66
66
  // los packages del monorepo.
67
67
  "@griddo-instance": `${resolveComponentsPath()}/src/index.js`,
68
- }
68
+ },
69
69
  );
70
70
  }
71
71
 
@@ -10,7 +10,7 @@ function isObject(value: unknown) {
10
10
 
11
11
  function filterBodyIntegrationFromPosition(
12
12
  integrations: Array<Core.PageIntegration>,
13
- position: "start" | "end"
13
+ position: "start" | "end",
14
14
  ) {
15
15
  return (
16
16
  integrations
@@ -18,7 +18,7 @@ function filterBodyIntegrationFromPosition(
18
18
  (integration) =>
19
19
  integration.contentBody !== null &&
20
20
  integration.contentBody !== "" &&
21
- integration.contentBodyPosition === position
21
+ integration.contentBodyPosition === position,
22
22
  )
23
23
  .map((integration) => {
24
24
  return { content: integration.contentBody!, type: integration.type };
@@ -32,11 +32,11 @@ function filterHeadIntegrations(integrations: Array<Core.PageIntegration>) {
32
32
  return integrations
33
33
  ?.filter(
34
34
  (integration) =>
35
- (integration.type==='addon' && integration.contentHead !== null && integration.contentHead !== "")
36
- ||
37
- (integration.type === 'analytics')
38
- ||
39
- (integration.type === 'datalayer')
35
+ (integration.type === "addon" &&
36
+ integration.contentHead !== null &&
37
+ integration.contentHead !== "") ||
38
+ integration.type === "analytics" ||
39
+ integration.type === "datalayer",
40
40
  )
41
41
  .map((integration) => {
42
42
  return {
@@ -48,7 +48,7 @@ function filterHeadIntegrations(integrations: Array<Core.PageIntegration>) {
48
48
 
49
49
  export const filterPositionIntegrations = (
50
50
  integrations: Array<Core.PageIntegration>,
51
- position: "head" | "start" | "end"
51
+ position: "head" | "start" | "end",
52
52
  ) => {
53
53
  switch (position) {
54
54
  case "head":
@@ -70,7 +70,7 @@ export function composeAnalytics(
70
70
  };
71
71
  },
72
72
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
73
- generateAutomaticDimensions = (page: Record<string, unknown>) => null
73
+ generateAutomaticDimensions = (page: Record<string, unknown>) => null,
74
74
  ) {
75
75
  const analyticsScript = siteScriptRaw ? siteScriptRaw.trim() : "";
76
76
 
@@ -96,10 +96,10 @@ export function composeAnalytics(
96
96
  dimensionValue?.startsWith(dynamicValuePrefix)
97
97
  ? `${dimensionValue.slice(
98
98
  dynamicValuePrefix.length,
99
- dimensionValue.endsWith(";") ? -1 : dimensionValue.length
100
- )}`
99
+ dimensionValue.endsWith(";") ? -1 : dimensionValue.length,
100
+ )}`
101
101
  : `"${dimensionValue}"`
102
- }`
102
+ }`,
103
103
  );
104
104
  }
105
105
 
@@ -0,0 +1,159 @@
1
+ import type { Adapters } from "../adapters";
2
+
3
+ import kleur from "kleur";
4
+ import { version as reactVersion } from "react";
5
+
6
+ import { getConfig } from "./core-utils";
7
+ import { envs } from "../constants";
8
+
9
+ /**
10
+ * Custom basic logging function controlled by a environment variable.
11
+ *
12
+ * @param str The string to be logged.
13
+ */
14
+ function verboseLog(str: string) {
15
+ if (envs.GRIDDO_VERBOSE_LOGS) {
16
+ console.log(
17
+ kleur.yellow("verbose"),
18
+ kleur.dim(str.replace(/(\s)\s+/g, "$1").trim()),
19
+ );
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Custom log inside a line-box.
25
+ *
26
+ * @param stringValue The string to be logged.
27
+ * @param paddingInline The number of white spaces inside the box at left and right.
28
+ * @param paddingBlock The number of white spaces inside the box at top and bottom.
29
+ */
30
+ function boxLog(
31
+ stringValue: string,
32
+ title = "",
33
+ paddingInline = 1,
34
+ paddingBlock = 1,
35
+ ) {
36
+ const lines = stringValue
37
+ .split("\n") // lines
38
+ .map((line) => line.trim()); // remove extra spaces
39
+ const windowTitle = title ? ` ${title} ` : "";
40
+ const windowTitleLength = title ? windowTitle.length : 0;
41
+ const longerContent =
42
+ Math.max(...lines.map((l) => l.length)) + paddingInline * 2;
43
+ const longerLine = Math.max(longerContent, windowTitleLength);
44
+ const paddingBlockString = `│${" ".repeat(longerLine)}│\n`.repeat(
45
+ paddingBlock,
46
+ );
47
+ const minWidth = longerLine;
48
+ const borderTop = `╭${windowTitle}${"─".repeat(
49
+ minWidth - windowTitleLength,
50
+ )}╮\n`;
51
+ const borderBottom = `╰${"─".repeat(minWidth)}╯`;
52
+ const content = lines
53
+ .map((l) => {
54
+ const mr = " ".repeat(longerLine - l.length - paddingInline);
55
+ return `│${" ".repeat(paddingInline)}${l}${mr}│\n`;
56
+ })
57
+ .join("");
58
+
59
+ console.log(
60
+ `${borderTop}${paddingBlockString}${content}${paddingBlockString}${borderBottom}`,
61
+ );
62
+ }
63
+
64
+ /**
65
+ * Custom basic logging function controlled by a environment variable.
66
+ * Strip double spaces.
67
+ *
68
+ * @param str The string to be logged.
69
+ */
70
+ function buildLog(str: string) {
71
+ if (envs.GRIDDO_BUILD_LOGS) {
72
+ console.info(str.replace(/(\s)\s+/g, "$1").trim());
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Console log with a blue color in the info prefix.
78
+ * @param str The string to be logged.
79
+ */
80
+ function infoLog(str: string) {
81
+ console.info(`${kleur.blue("info")} ${str}`);
82
+ }
83
+
84
+ /**
85
+ * Console log with a green color in the success prefix.
86
+ * @param str The string to be logged.
87
+ */
88
+ function successLog(str: string) {
89
+ console.info(`${kleur.green("success")} ${str}`);
90
+ }
91
+
92
+ /**
93
+ * Internal log
94
+ * @param values The values to be logged.
95
+ */
96
+ function debugLog(...values: Array<unknown>) {
97
+ if (!envs.GRIDDO_DEBUG_LOGS) {
98
+ return;
99
+ }
100
+ console.log(...values);
101
+ }
102
+
103
+ /**
104
+ * Return a scale size colors with a number and a measure string (KB by default).
105
+ *
106
+ * @param size The page size in KB.
107
+ * @param measure The measure string to be added in the log.
108
+ */
109
+ function pageSizeLog(size: number, measure = "KB") {
110
+ const sizeScale = {
111
+ low: 50,
112
+ mid: 80,
113
+ large: 130,
114
+ extraLarge: 210,
115
+ };
116
+
117
+ // Ternary pawa!
118
+ const color =
119
+ size > sizeScale.large
120
+ ? "red"
121
+ : size > sizeScale.mid
122
+ ? "magenta"
123
+ : size > sizeScale.low
124
+ ? "blue"
125
+ : "green";
126
+
127
+ return kleur[color](kleur.bold(`${size}${measure}`));
128
+ }
129
+
130
+ /**
131
+ * Print Griddo, adapter and Node version.
132
+ */
133
+ function printExporterLogo(adapter: Adapters) {
134
+ const config = getConfig();
135
+ const nodeVersion = process.version;
136
+ const { griddoVersion } = config;
137
+ const logo = `
138
+ ··
139
+ ·· Griddo ${griddoVersion}
140
+ ··
141
+ ·· Adapter: ${adapter}
142
+ ·· Node: ${nodeVersion}
143
+ ·· React: ${reactVersion}
144
+ ··
145
+ `;
146
+
147
+ console.log(logo);
148
+ }
149
+
150
+ export {
151
+ boxLog,
152
+ buildLog,
153
+ debugLog,
154
+ infoLog,
155
+ pageSizeLog,
156
+ printExporterLogo,
157
+ successLog,
158
+ verboseLog,
159
+ };