@griddo/cx 11.7.5 → 11.7.6-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.
Files changed (300) hide show
  1. package/README.md +25 -228
  2. package/build/adapters/gatsby/actions/clean.js +10 -0
  3. package/build/adapters/gatsby/actions/clean.js.map +1 -0
  4. package/build/adapters/gatsby/actions/close.js +12 -0
  5. package/build/adapters/gatsby/actions/close.js.map +1 -0
  6. package/build/adapters/gatsby/actions/data.js +18 -0
  7. package/build/adapters/gatsby/actions/data.js.map +1 -0
  8. package/build/adapters/gatsby/actions/healthCheck.js +10 -0
  9. package/build/adapters/gatsby/actions/healthCheck.js.map +1 -0
  10. package/build/adapters/gatsby/actions/init.js +9 -0
  11. package/build/adapters/gatsby/actions/init.js.map +1 -0
  12. package/build/adapters/gatsby/actions/meta.js +14 -0
  13. package/build/adapters/gatsby/actions/meta.js.map +1 -0
  14. package/build/adapters/gatsby/actions/prepare.js +9 -0
  15. package/build/adapters/gatsby/actions/prepare.js.map +1 -0
  16. package/build/adapters/gatsby/actions/relocation.js +15 -0
  17. package/build/adapters/gatsby/actions/relocation.js.map +1 -0
  18. package/build/adapters/gatsby/actions/restore.js +26 -0
  19. package/build/adapters/gatsby/actions/restore.js.map +1 -0
  20. package/build/adapters/gatsby/actions/ssg.js +9 -0
  21. package/build/adapters/gatsby/actions/ssg.js.map +1 -0
  22. package/build/adapters/gatsby/actions/sync.js +50 -0
  23. package/build/adapters/gatsby/actions/sync.js.map +1 -0
  24. package/build/adapters/gatsby/index.js +74 -0
  25. package/build/adapters/gatsby/index.js.map +1 -0
  26. package/build/adapters/gatsby/shared/context.js +25 -0
  27. package/build/adapters/gatsby/shared/context.js.map +1 -0
  28. package/build/adapters/gatsby/shared/extract-assets.js +58 -0
  29. package/build/adapters/gatsby/shared/extract-assets.js.map +1 -0
  30. package/build/adapters/gatsby/shared/gatsby-build.js +49 -0
  31. package/build/adapters/gatsby/shared/gatsby-build.js.map +1 -0
  32. package/build/adapters/gatsby/shared/sync-render.js +208 -0
  33. package/build/adapters/gatsby/shared/sync-render.js.map +1 -0
  34. package/build/adapters/gatsby/shared/types.js +3 -0
  35. package/build/adapters/gatsby/shared/types.js.map +1 -0
  36. package/build/commands/end-render.js +63 -0
  37. package/build/commands/end-render.js.map +1 -0
  38. package/build/commands/prepare-assets-directory.js +32 -0
  39. package/build/commands/prepare-assets-directory.js.map +1 -0
  40. package/build/commands/prepare-domains-render.js +138 -0
  41. package/build/commands/prepare-domains-render.js.map +1 -0
  42. package/build/commands/reset-render.js +22 -0
  43. package/build/commands/reset-render.js.map +1 -0
  44. package/build/commands/start-render.js +35 -0
  45. package/build/commands/start-render.js.map +1 -0
  46. package/build/commands/upload-search-content.js +189 -0
  47. package/build/commands/upload-search-content.js.map +1 -0
  48. package/build/constants/endpoints.js +42 -0
  49. package/build/constants/endpoints.js.map +1 -0
  50. package/build/constants/envs.js +73 -0
  51. package/build/constants/envs.js.map +1 -0
  52. package/build/constants/errors.js +89 -0
  53. package/build/constants/errors.js.map +1 -0
  54. package/build/exporter/adapters/gatsby/actions/clean.d.ts +3 -0
  55. package/build/exporter/adapters/gatsby/actions/close.d.ts +3 -0
  56. package/build/exporter/adapters/gatsby/actions/data.d.ts +2 -0
  57. package/build/exporter/adapters/gatsby/actions/healthCheck.d.ts +2 -0
  58. package/build/exporter/adapters/gatsby/actions/init.d.ts +2 -0
  59. package/build/exporter/adapters/gatsby/actions/meta.d.ts +2 -0
  60. package/build/exporter/adapters/gatsby/actions/prepare.d.ts +2 -0
  61. package/build/exporter/adapters/gatsby/actions/relocation.d.ts +2 -0
  62. package/build/exporter/adapters/gatsby/actions/restore.d.ts +3 -0
  63. package/build/exporter/adapters/gatsby/actions/ssg.d.ts +3 -0
  64. package/build/exporter/adapters/gatsby/actions/sync.d.ts +3 -0
  65. package/build/exporter/adapters/gatsby/index.d.ts +9 -0
  66. package/build/exporter/adapters/gatsby/shared/context.d.ts +38 -0
  67. package/build/exporter/adapters/gatsby/shared/extract-assets.d.ts +7 -0
  68. package/build/exporter/adapters/gatsby/shared/gatsby-build.d.ts +7 -0
  69. package/build/exporter/adapters/gatsby/shared/sync-render.d.ts +36 -0
  70. package/build/exporter/adapters/gatsby/shared/types.d.ts +34 -0
  71. package/build/exporter/commands/start-render.d.ts +2 -0
  72. package/build/exporter/commands/upload-search-content.d.ts +2 -0
  73. package/build/{constants → exporter/constants}/envs.d.ts +1 -7
  74. package/build/{errors/errors-data.d.ts → exporter/constants/errors.d.ts} +5 -3
  75. package/build/{services → exporter/services}/auth.d.ts +1 -1
  76. package/build/exporter/services/db.d.ts +4 -0
  77. package/build/{services → exporter/services}/robots.d.ts +0 -6
  78. package/build/{services → exporter/services}/sites.d.ts +5 -2
  79. package/build/exporter/services/store.d.ts +15 -0
  80. package/build/{types → exporter/types}/api.d.ts +3 -4
  81. package/build/{types → exporter/types}/global.d.ts +6 -6
  82. package/build/{types → exporter/types}/navigation.d.ts +1 -1
  83. package/build/exporter/types/render.d.ts +50 -0
  84. package/build/{types → exporter/types}/sites.d.ts +1 -2
  85. package/build/exporter/utils/artifacts.d.ts +6 -0
  86. package/build/exporter/utils/brush.d.ts +18 -0
  87. package/build/{utils → exporter/utils}/cache.d.ts +7 -12
  88. package/build/{utils/health-checks.d.ts → exporter/utils/check-health.d.ts} +2 -2
  89. package/build/exporter/utils/core-utils.d.ts +77 -0
  90. package/build/{utils → exporter/utils}/domains.d.ts +1 -1
  91. package/build/{errors/index.d.ts → exporter/utils/errors.d.ts} +3 -3
  92. package/build/exporter/utils/folders.d.ts +66 -0
  93. package/build/{utils → exporter/utils}/loggin.d.ts +2 -16
  94. package/build/{utils → exporter/utils}/pages.d.ts +2 -2
  95. package/build/exporter/utils/render.d.ts +49 -0
  96. package/build/{utils → exporter/utils}/sites.d.ts +3 -3
  97. package/build/{utils → exporter/utils}/store.d.ts +10 -38
  98. package/build/services/auth.js +39 -0
  99. package/build/services/auth.js.map +1 -0
  100. package/build/services/db.js +34 -0
  101. package/build/services/db.js.map +1 -0
  102. package/build/services/navigation.js +93 -0
  103. package/build/services/navigation.js.map +1 -0
  104. package/build/services/reference-fields.js +131 -0
  105. package/build/services/reference-fields.js.map +1 -0
  106. package/build/services/robots.js +58 -0
  107. package/build/services/robots.js.map +1 -0
  108. package/build/services/sites.js +109 -0
  109. package/build/services/sites.js.map +1 -0
  110. package/build/services/store.js +282 -0
  111. package/build/services/store.js.map +1 -0
  112. package/build/types/api.js +3 -0
  113. package/build/types/api.js.map +1 -0
  114. package/build/types/global.js +3 -0
  115. package/build/types/global.js.map +1 -0
  116. package/build/types/navigation.js +3 -0
  117. package/build/types/navigation.js.map +1 -0
  118. package/build/types/pages.js +3 -0
  119. package/build/types/pages.js.map +1 -0
  120. package/build/types/render.js +10 -0
  121. package/build/types/render.js.map +1 -0
  122. package/build/types/sites.js +3 -0
  123. package/build/types/sites.js.map +1 -0
  124. package/build/types/templates.js +3 -0
  125. package/build/types/templates.js.map +1 -0
  126. package/build/utils/api.js +161 -0
  127. package/build/utils/api.js.map +1 -0
  128. package/build/utils/artifacts.js +34 -0
  129. package/build/utils/artifacts.js.map +1 -0
  130. package/build/utils/brush.js +30 -0
  131. package/build/utils/brush.js.map +1 -0
  132. package/build/utils/cache.js +106 -0
  133. package/build/utils/cache.js.map +1 -0
  134. package/build/utils/check-health.js +68 -0
  135. package/build/utils/check-health.js.map +1 -0
  136. package/build/utils/core-utils.js +251 -0
  137. package/build/utils/core-utils.js.map +1 -0
  138. package/build/utils/domains.js +37 -0
  139. package/build/utils/domains.js.map +1 -0
  140. package/build/utils/errors.js +30 -0
  141. package/build/utils/errors.js.map +1 -0
  142. package/build/utils/folders.js +339 -0
  143. package/build/utils/folders.js.map +1 -0
  144. package/build/utils/images.js +45 -0
  145. package/build/utils/images.js.map +1 -0
  146. package/build/utils/instance.js +66 -0
  147. package/build/utils/instance.js.map +1 -0
  148. package/build/utils/loggin.js +102 -0
  149. package/build/utils/loggin.js.map +1 -0
  150. package/build/utils/pages.js +359 -0
  151. package/build/utils/pages.js.map +1 -0
  152. package/build/utils/render.js +144 -0
  153. package/build/utils/render.js.map +1 -0
  154. package/build/utils/sites.js +239 -0
  155. package/build/utils/sites.js.map +1 -0
  156. package/build/utils/store.js +193 -0
  157. package/build/utils/store.js.map +1 -0
  158. package/exporter/adapters/gatsby/actions/clean.ts +14 -0
  159. package/exporter/adapters/gatsby/actions/close.ts +17 -0
  160. package/exporter/adapters/gatsby/actions/data.ts +25 -0
  161. package/exporter/adapters/gatsby/actions/healthCheck.ts +10 -0
  162. package/exporter/adapters/gatsby/actions/init.ts +12 -0
  163. package/exporter/adapters/gatsby/actions/meta.ts +18 -0
  164. package/exporter/adapters/gatsby/actions/prepare.ts +9 -0
  165. package/exporter/adapters/gatsby/actions/relocation.ts +15 -0
  166. package/exporter/adapters/gatsby/actions/restore.ts +36 -0
  167. package/exporter/adapters/gatsby/actions/ssg.ts +12 -0
  168. package/exporter/adapters/gatsby/actions/sync.ts +70 -0
  169. package/exporter/adapters/gatsby/index.ts +60 -146
  170. package/exporter/adapters/gatsby/shared/context.ts +50 -0
  171. package/exporter/adapters/gatsby/shared/extract-assets.ts +61 -0
  172. package/exporter/adapters/gatsby/shared/gatsby-build.ts +54 -0
  173. package/exporter/adapters/gatsby/shared/sync-render.ts +294 -0
  174. package/exporter/adapters/gatsby/shared/types.ts +35 -0
  175. package/exporter/build-esbuild.noop +42 -0
  176. package/exporter/build.sh +5 -38
  177. package/exporter/commands/end-render.ts +56 -81
  178. package/exporter/commands/prepare-assets-directory.ts +33 -0
  179. package/exporter/commands/prepare-domains-render.ts +149 -31
  180. package/exporter/commands/reset-render.ts +12 -3
  181. package/exporter/commands/start-render.ts +18 -47
  182. package/exporter/commands/upload-search-content.ts +206 -21
  183. package/exporter/constants/envs.ts +59 -51
  184. package/exporter/{errors/errors-data.ts → constants/errors.ts} +24 -15
  185. package/exporter/services/auth.ts +7 -6
  186. package/exporter/services/db.ts +32 -0
  187. package/exporter/services/navigation.ts +4 -10
  188. package/exporter/services/reference-fields.ts +8 -23
  189. package/exporter/services/robots.ts +8 -15
  190. package/exporter/services/sites.ts +35 -24
  191. package/exporter/services/store.ts +118 -76
  192. package/exporter/types/api.ts +24 -27
  193. package/exporter/types/global.ts +8 -10
  194. package/exporter/types/navigation.ts +1 -1
  195. package/exporter/types/pages.ts +2 -3
  196. package/exporter/types/render.ts +59 -0
  197. package/exporter/types/sites.ts +1 -2
  198. package/exporter/utils/api.ts +46 -82
  199. package/exporter/{artifacts/index.ts → utils/artifacts.ts} +9 -8
  200. package/exporter/utils/brush.ts +34 -0
  201. package/exporter/utils/cache.ts +34 -59
  202. package/exporter/utils/check-health.ts +79 -0
  203. package/exporter/utils/core-utils.ts +86 -247
  204. package/exporter/utils/domains.ts +10 -7
  205. package/exporter/{errors/index.ts → utils/errors.ts} +10 -9
  206. package/exporter/utils/folders.ts +161 -92
  207. package/exporter/utils/images.ts +1 -6
  208. package/exporter/utils/instance.ts +9 -12
  209. package/exporter/utils/loggin.ts +24 -89
  210. package/exporter/utils/pages.ts +23 -88
  211. package/exporter/utils/render.ts +147 -48
  212. package/exporter/utils/sites.ts +67 -77
  213. package/exporter/utils/store.ts +85 -178
  214. package/gatsby-browser.tsx +41 -58
  215. package/gatsby-config.ts +6 -12
  216. package/gatsby-node.ts +30 -89
  217. package/gatsby-ssr.tsx +2 -1
  218. package/package.json +32 -73
  219. package/plugins/gatsby-plugin-svgr-loader/gatsby-node.js +55 -0
  220. package/plugins/gatsby-plugin-svgr-loader/package.json +8 -0
  221. package/{exporter/react → react}/Favicon/index.tsx +1 -7
  222. package/{exporter/react → react}/GriddoIntegrations/index.tsx +6 -14
  223. package/{exporter/react → react}/GriddoIntegrations/utils.ts +4 -9
  224. package/{build/react/index.d.ts → react/index.tsx} +1 -0
  225. package/src/components/Head.tsx +13 -46
  226. package/src/components/template.tsx +8 -30
  227. package/src/gatsby-node-utils.ts +91 -2
  228. package/src/html.tsx +2 -11
  229. package/src/types.ts +5 -5
  230. package/start-render.js +1 -3
  231. package/tsconfig.json +3 -2
  232. package/build/adapters/gatsby/index.d.ts +0 -4
  233. package/build/adapters/gatsby/utils.d.ts +0 -22
  234. package/build/artifacts/index.d.ts +0 -6
  235. package/build/commands/move-assets.d.ts +0 -1
  236. package/build/commands/prepare-domains-render.d.ts +0 -1
  237. package/build/constants/index.d.ts +0 -57
  238. package/build/end-render.js +0 -74
  239. package/build/end-render.js.map +0 -7
  240. package/build/index.d.ts +0 -29
  241. package/build/index.js +0 -73
  242. package/build/index.js.map +0 -7
  243. package/build/prepare-domains-render.js +0 -73
  244. package/build/prepare-domains-render.js.map +0 -7
  245. package/build/react/Favicon/index.d.ts +0 -5
  246. package/build/react/Favicon/utils.d.ts +0 -9
  247. package/build/react/GriddoIntegrations/index.d.ts +0 -20
  248. package/build/react/GriddoIntegrations/utils.d.ts +0 -26
  249. package/build/react/index.js +0 -3
  250. package/build/registers/api.d.ts +0 -9
  251. package/build/registers/gatsby.d.ts +0 -9
  252. package/build/registers/index.d.ts +0 -3
  253. package/build/reset-render.js +0 -74
  254. package/build/reset-render.js.map +0 -7
  255. package/build/services/domains.d.ts +0 -6
  256. package/build/services/register.d.ts +0 -36
  257. package/build/services/settings.d.ts +0 -4
  258. package/build/services/store.d.ts +0 -6
  259. package/build/start-render.js +0 -100
  260. package/build/start-render.js.map +0 -7
  261. package/build/upload-search-content.js +0 -74
  262. package/build/upload-search-content.js.map +0 -7
  263. package/build/utils/alerts.d.ts +0 -3
  264. package/build/utils/core-utils.d.ts +0 -107
  265. package/build/utils/create-build-data.d.ts +0 -8
  266. package/build/utils/folders.d.ts +0 -53
  267. package/build/utils/render.d.ts +0 -13
  268. package/build/utils/searches.d.ts +0 -15
  269. package/cx.config.d.ts +0 -5
  270. package/cx.config.js +0 -36
  271. package/exporter/adapters/gatsby/utils.ts +0 -161
  272. package/exporter/artifacts/README.md +0 -34
  273. package/exporter/commands/move-assets.ts +0 -11
  274. package/exporter/constants/index.ts +0 -129
  275. package/exporter/index.ts +0 -82
  276. package/exporter/react/index.tsx +0 -11
  277. package/exporter/registers/api.ts +0 -14
  278. package/exporter/registers/gatsby.ts +0 -14
  279. package/exporter/registers/index.ts +0 -4
  280. package/exporter/services/domains.ts +0 -16
  281. package/exporter/services/register.ts +0 -113
  282. package/exporter/services/settings.ts +0 -17
  283. package/exporter/utils/alerts.ts +0 -29
  284. package/exporter/utils/create-build-data.ts +0 -17
  285. package/exporter/utils/health-checks.ts +0 -64
  286. package/exporter/utils/searches.ts +0 -179
  287. package/src/README.md +0 -7
  288. package/build/{commands → exporter/commands}/end-render.d.ts +0 -0
  289. package/build/{commands/reset-render.d.ts → exporter/commands/prepare-assets-directory.d.ts} +0 -0
  290. package/build/{commands/start-render.d.ts → exporter/commands/prepare-domains-render.d.ts} +0 -0
  291. package/build/{commands/upload-search-content.d.ts → exporter/commands/reset-render.d.ts} +0 -0
  292. package/build/{constants → exporter/constants}/endpoints.d.ts +0 -0
  293. package/build/{services → exporter/services}/navigation.d.ts +0 -0
  294. package/build/{services → exporter/services}/reference-fields.d.ts +0 -0
  295. package/build/{types → exporter/types}/pages.d.ts +1 -1
  296. /package/build/{types → exporter/types}/templates.d.ts +0 -0
  297. /package/build/{utils → exporter/utils}/api.d.ts +0 -0
  298. /package/build/{utils → exporter/utils}/images.d.ts +0 -0
  299. /package/build/{utils → exporter/utils}/instance.d.ts +0 -0
  300. /package/{exporter/react → react}/Favicon/utils.ts +0 -0
@@ -6,25 +6,16 @@ import type {
6
6
  PutAPI,
7
7
  ShowApiErrorOptions,
8
8
  } from "../types/api";
9
- import type { AxiosError, Method } from "axios";
10
-
11
- import axios from "axios";
12
- import dotenv from "dotenv";
13
- import kleur from "kleur";
14
9
 
10
+ import { AuthService } from "../services/auth";
11
+ import { brush } from "./brush";
15
12
  import { saveCache, searchCacheData } from "./cache";
16
13
  import { delay, getSafeSiteId, msToSec } from "./core-utils";
17
14
  import { buildLog } from "./loggin";
18
- import { envs } from "../constants";
19
- import { apiRegister } from "../registers";
20
- import { AuthService } from "../services/auth";
21
-
22
- dotenv.config();
23
15
 
24
16
  // Envs
25
- const {
26
- env: { RETRY_WAIT_SECONDS = "4", RETRY_ATTEMPTS = "4" },
27
- } = process;
17
+ const { env } = process;
18
+ const { RETRY_WAIT_SECONDS = "4", RETRY_ATTEMPTS = "4" } = env;
28
19
 
29
20
  /**
30
21
  * Make a GET/PUT/POST request to the Griddo API.
@@ -41,31 +32,22 @@ const {
41
32
  */
42
33
  async function requestAPI<T extends APIResponses>(
43
34
  props: APIRequest,
44
- method: Method,
35
+ method: string,
45
36
  appendToLog = "",
46
37
  ): Promise<T> {
47
- const {
48
- endpoint,
49
- body,
50
- cacheKey = "",
51
- attempt = 1,
52
- headers,
53
- useApiCacheDir = true,
54
- } = props;
38
+ const { endpoint, body, cacheKey = "", attempt = 1, headers, useApiCacheDir = true } = props;
55
39
  const cacheOptions = { endpoint, body, headers, cacheKey };
56
40
 
57
41
  // Cache
58
42
  if (cacheKey && useApiCacheDir) {
59
43
  const start = new Date();
60
- const cacheData = searchCacheData<T>(cacheOptions);
44
+ const cacheData = await searchCacheData<T>(cacheOptions);
61
45
 
62
46
  if (cacheData) {
63
47
  const siteId = getSafeSiteId(cacheData);
64
48
  const siteIdMsg = siteId ? `site: ${siteId}` : "";
65
- const duration = msToSec(new Date().getTime() - start.getTime());
66
- buildLog(
67
- `${method} (cache) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`,
68
- );
49
+ const duration = msToSec(Date.now() - start.getTime());
50
+ buildLog(`${method} (cache) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`);
69
51
  return cacheData;
70
52
  }
71
53
  }
@@ -73,47 +55,46 @@ async function requestAPI<T extends APIResponses>(
73
55
  // Network
74
56
  try {
75
57
  const start = new Date();
76
- const {
77
- data,
78
- headers: responseHeaders,
79
- }: { data: T; headers: { "content-length": string } } = await axios({
80
- url: endpoint,
81
- method,
82
- headers: Object.assign({}, headers, AuthService.headers),
83
- data: body,
84
- });
58
+
59
+ // Prepare fetch options
60
+ const fetchOptions: RequestInit = {
61
+ method: method.toUpperCase(),
62
+ headers: Object.assign({}, headers, AuthService.headers) as Record<string, string>,
63
+ };
64
+
65
+ // Add body for non-GET requests
66
+ if (method.toLowerCase() !== "get" && body) {
67
+ fetchOptions.body = JSON.stringify(body);
68
+ if (!fetchOptions.headers) fetchOptions.headers = {};
69
+ (fetchOptions.headers as Record<string, string>)["Content-Type"] = "application/json";
70
+ }
71
+
72
+ const response = await fetch(endpoint, fetchOptions);
73
+
74
+ // Handle non-2xx responses
75
+ if (!response.ok) {
76
+ if (response.status === 404) {
77
+ // @ts-expect-error page maybe will be 404
78
+ return null;
79
+ }
80
+
81
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
82
+ }
83
+
84
+ const data: T = await response.json();
85
85
 
86
86
  const siteId = getSafeSiteId(data);
87
87
  const siteIdMsg = siteId ? `site: ${siteId}` : "";
88
- const duration = msToSec(new Date().getTime() - start.getTime());
89
- buildLog(
90
- `${method} (fetch) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`,
91
- );
88
+ const duration = msToSec(Date.now() - start.getTime());
89
+ buildLog(`${method} (fetch) ${siteIdMsg} ${endpoint} - ${duration}s ${appendToLog}`);
92
90
 
93
91
  if (useApiCacheDir) {
94
- saveCache(cacheOptions, data);
95
- }
96
-
97
- // Only save registers if alerts are enabled
98
- if (envs.GRIDDO_ALERT_FEATURE) {
99
- const responseSize = Number.parseInt(responseHeaders["content-length"]);
100
- if (responseSize > envs.GRIDDO_API_MAX_RESPONSE_SIZE) {
101
- apiRegister.insert("API_RESPONSE_TOO_BIG", {
102
- endpoint,
103
- responseSize,
104
- duration,
105
- });
106
- }
92
+ await saveCache(cacheOptions, data);
107
93
  }
108
94
 
109
95
  return data;
110
96
  } catch (e) {
111
- const error = e as AxiosError;
112
-
113
- if (error.response?.status === 404) {
114
- // @ts-expect-error page maybe will be 404
115
- return null;
116
- }
97
+ const error = e as Error;
117
98
 
118
99
  if (attempt > parseInt(RETRY_ATTEMPTS)) {
119
100
  console.log(`
@@ -122,7 +103,7 @@ Max attempts ${RETRY_ATTEMPTS} reached
122
103
  - ${method.toUpperCase()} ${endpoint}
123
104
  - BODY: ${JSON.stringify(body)}
124
105
  - HEADERS: ${JSON.stringify(headers)}
125
- - RESPONSE: ${error.response?.status} ${JSON.stringify(error.response?.data)}
106
+ - ERROR: ${error.message}
126
107
  --------------------------------------
127
108
  `);
128
109
 
@@ -130,12 +111,6 @@ Max attempts ${RETRY_ATTEMPTS} reached
130
111
  process.exit(1);
131
112
  }
132
113
 
133
- if (!error.response) {
134
- console.log("Unknown error occurred");
135
- console.log(JSON.stringify(error, null, 2));
136
- process.exit(1);
137
- }
138
-
139
114
  showApiError(error, {
140
115
  callInfo: { endpoint, body },
141
116
  });
@@ -188,9 +163,7 @@ async function postApi<T extends APIResponses>(props: PostAPI) {
188
163
  const { endpoint, body, headers } = props;
189
164
  const referenceFieldBodyParams =
190
165
  endpoint.endsWith("/distributor") &&
191
- `# ReferenceField body: ${JSON.stringify(body)} lang: ${JSON.stringify(
192
- headers?.lang,
193
- )}`;
166
+ `# ReferenceField body: ${JSON.stringify(body)} lang: ${JSON.stringify(headers?.lang)}`;
194
167
 
195
168
  return requestAPI<T>(props, "post", referenceFieldBodyParams || "");
196
169
  }
@@ -198,40 +171,31 @@ async function postApi<T extends APIResponses>(props: PostAPI) {
198
171
  /**
199
172
  * Shows an API error through the terminal.
200
173
  */
201
- function showApiError(error: AxiosError, options: ShowApiErrorOptions) {
202
- const { response, message, stack } = error;
174
+ function showApiError(error: Error, options: ShowApiErrorOptions) {
175
+ const { message, stack } = error;
203
176
  const { callInfo } = options;
204
- const { status, statusText, data } = response || {};
205
177
  const callInfoArray = [];
206
178
 
207
179
  for (const item of Object.keys(callInfo) as Array<keyof typeof callInfo>) {
208
180
  callInfoArray.push(
209
181
  `${item}: ${
210
- typeof callInfo[item] === "object"
211
- ? JSON.stringify(callInfo[item])
212
- : callInfo[item]
182
+ typeof callInfo[item] === "object" ? JSON.stringify(callInfo[item]) : callInfo[item]
213
183
  }`,
214
184
  );
215
185
  }
216
186
 
217
187
  // Compose the errors output
218
188
  const callInfoStr = callInfoArray.join("\n");
219
- const apiResponseStr = response
220
- ? `Code: ${status} - ${statusText}\nResponse: ${JSON.stringify(data)}`
221
- : "";
222
189
  const errorDetailsStr = `${message}\n${stack}`;
223
190
 
224
191
  // Print the error
225
192
  console.warn(
226
- kleur.red(`
193
+ brush.red(`
227
194
  =============
228
195
 
229
196
  { Call info }
230
197
  ${callInfoStr}
231
198
 
232
- { API Response }
233
- ${apiResponseStr}
234
-
235
199
  { Error details }
236
200
  ${errorDetailsStr}
237
201
 
@@ -2,14 +2,13 @@ import type { Artifacts } from "../types/global";
2
2
 
3
3
  import path from "node:path";
4
4
 
5
- import { getConfig } from "../utils/core-utils";
5
+ import { getRenderPathsFromDB } from "./render";
6
6
 
7
7
  /**
8
8
  * Returns the artifacts of CX.
9
9
  */
10
- function getCxArtifacts(domain: string): Artifacts {
11
- const config = getConfig();
12
- const { __cx, __exports, __cache } = config.paths(domain);
10
+ async function getCxArtifacts(domain: string): Promise<Artifacts> {
11
+ const { __cx, __exports, __cache } = await getRenderPathsFromDB({ domain });
13
12
 
14
13
  return {
15
14
  initials: [
@@ -21,13 +20,15 @@ function getCxArtifacts(domain: string): Artifacts {
21
20
  disposables: [
22
21
  path.join(__cx, "store"),
23
22
  path.join(__cx, "apiCache"),
24
- path.join(__cx, "render-metadata.json"),
25
23
  path.join(__cx, "dist"),
24
+ path.join(__cx, "dist-restored"),
26
25
  path.join(__cx, "debug"),
26
+ path.join(__cx, "assets"),
27
27
  ],
28
- cacheables: ["apiCache", "store"],
29
- archivables: ["dist", "assets", "debug"],
28
+ cacheables: [],
29
+ archivables: ["dist", "debug", "assets"],
30
+ restaurable: ["dist", "debug"],
30
31
  };
31
32
  }
32
33
 
33
- export default getCxArtifacts;
34
+ export { getCxArtifacts };
@@ -0,0 +1,34 @@
1
+ //
2
+ // Brush adds color to a string|number, it does not print it!
3
+ // Its simple, no log, no chains, just color in a string|number
4
+ // usage:
5
+ // console.log(brush.green("sucess!"))
6
+ //
7
+
8
+ const RESET = "\x1b[0m";
9
+ const CODES = {
10
+ black: "\x1b[30m",
11
+ red: "\x1b[31m",
12
+ green: "\x1b[32m",
13
+ yellow: "\x1b[33m",
14
+ blue: "\x1b[34m",
15
+ magenta: "\x1b[35m",
16
+ cyan: "\x1b[36m",
17
+ white: "\x1b[37m",
18
+ gray: "\x1b[90m",
19
+ bold: "\x1b[1m",
20
+ dim: "\x1b[2m",
21
+ } as const;
22
+
23
+ type ColorFunction = (text: string | number) => string;
24
+ type ColorName = keyof typeof CODES;
25
+ type Brush = Record<ColorName, ColorFunction>;
26
+
27
+ const brush = {} as Brush;
28
+
29
+ for (const color in CODES) {
30
+ const key = color as ColorName;
31
+ brush[key] = (text: string | number) => `${CODES[key]}${text}${RESET}`;
32
+ }
33
+
34
+ export { brush };
@@ -2,24 +2,21 @@ import type { Petition } from "../types/global";
2
2
  import type { HashSites, SiteHash } from "../types/sites";
3
3
 
4
4
  import crypto from "node:crypto";
5
- import fs from "node:fs";
5
+ import fsp from "node:fs/promises";
6
6
  import path from "node:path";
7
7
 
8
- import fsx from "fs-extra";
9
-
10
- import { getConfig } from "./core-utils";
11
-
12
- const config = getConfig();
8
+ import { pathExists } from "../utils/folders";
9
+ import { getRenderPathsFromDB } from "./render";
13
10
 
14
11
  /**
15
12
  * Creates an `apiCache` dir to store pages fetched from them API.
16
13
  */
17
- function createAPICacheDir() {
18
- const { __cx } = config.paths();
19
- const apiCacheDir = path.join(__cx, "apiCache");
14
+ async function createAPICacheDir(options: { basePath: string }) {
15
+ const { basePath } = options;
16
+ const apiCacheDir = path.join(basePath, "apiCache");
20
17
 
21
- if (!fs.existsSync(apiCacheDir)) {
22
- fs.mkdirSync(apiCacheDir);
18
+ if (!(await pathExists(apiCacheDir))) {
19
+ await fsp.mkdir(apiCacheDir);
23
20
  }
24
21
 
25
22
  console.info("Cache initialized");
@@ -27,12 +24,10 @@ function createAPICacheDir() {
27
24
 
28
25
  /**
29
26
  * Generate a filename with a hash using a Petition object
30
- *
31
- * @todo Merge with createSha256
32
27
  * @param petition An object
33
28
  */
34
- function generateFilenameWithHash(petition: Petition) {
35
- const { __cx } = config.paths();
29
+ async function generateFilenameWithHash(petition: Petition) {
30
+ const { __cx } = await getRenderPathsFromDB();
36
31
  const apiCacheDir = path.join(__cx, "apiCache");
37
32
 
38
33
  const hashSum = crypto.createHash("sha256");
@@ -41,35 +36,22 @@ function generateFilenameWithHash(petition: Petition) {
41
36
  return `${apiCacheDir}/${hashSum.digest("hex")}`;
42
37
  }
43
38
 
44
- /**
45
- * Generate a filename with a hash using a string.
46
- *
47
- * @todo Merge with generateFilenameWithHash
48
- * @param data A string to create a sha256 based on.
49
- */
50
- function createSha256(data: string) {
51
- const uniqueString = crypto.randomBytes(16).toString("hex");
52
- const hash = crypto.createHash("sha256");
53
- hash.update(`${data}${uniqueString}`);
54
-
55
- return hash.digest("hex");
56
- }
57
-
58
39
  /**
59
40
  * Save a file using a hash name.
60
41
  *
61
42
  * @param petition An object.
62
43
  * @param content Content to be saved.
63
44
  */
64
- function saveCache<T>(petition: Petition, content: T) {
65
- const stringContent =
66
- typeof content === "string" ? content : JSON.stringify(content);
67
- const filename = generateFilenameWithHash(petition);
45
+ async function saveCache<T>(petition: Petition, content: T) {
46
+ const stringContent = typeof content === "string" ? content : JSON.stringify(content);
47
+ const filename = await generateFilenameWithHash(petition);
68
48
  const filepath = path.dirname(filename);
69
- if (!fs.existsSync(filepath)) {
70
- fs.mkdirSync(filepath, { recursive: true });
49
+
50
+ if (!(await pathExists(filepath))) {
51
+ await fsp.mkdir(filepath, { recursive: true });
71
52
  }
72
- fs.writeFileSync(filename, stringContent, "utf8");
53
+
54
+ await fsp.writeFile(filename, stringContent, "utf8");
73
55
  }
74
56
 
75
57
  /**
@@ -78,13 +60,13 @@ function saveCache<T>(petition: Petition, content: T) {
78
60
  *
79
61
  * @param petition An object
80
62
  */
81
- function searchCacheData<T>(petition: Petition) {
63
+ async function searchCacheData<T>(petition: Petition) {
82
64
  try {
83
- const file = generateFilenameWithHash(petition);
84
- const jsonData = fsx.readJSONSync(file, {
85
- encoding: "utf-8",
86
- });
87
- return jsonData as T;
65
+ const file = await generateFilenameWithHash(petition);
66
+ const fileContent = await fsp.readFile(file, "utf8");
67
+ const jsonData = JSON.parse(fileContent) as T;
68
+
69
+ return jsonData;
88
70
  } catch {
89
71
  return null;
90
72
  }
@@ -93,15 +75,14 @@ function searchCacheData<T>(petition: Petition) {
93
75
  /**
94
76
  * Get site hashes from the file as an object
95
77
  */
96
- function getHashSites(): HashSites {
97
- const { __cx } = config.paths();
78
+ async function getHashSites(): Promise<HashSites> {
79
+ const { __cx } = await getRenderPathsFromDB();
98
80
  const apiCacheDir = path.join(__cx, "apiCache");
99
81
  const siteHasFilename = `${apiCacheDir}/siteHash.json`;
100
82
 
101
83
  try {
102
- const jsonData = fsx.readJSONSync(siteHasFilename, {
103
- encoding: "utf-8",
104
- });
84
+ const fileContent = await fsp.readFile(siteHasFilename, "utf8");
85
+ const jsonData = JSON.parse(fileContent);
105
86
  return jsonData || {};
106
87
  } catch {
107
88
  return {};
@@ -114,18 +95,18 @@ function getHashSites(): HashSites {
114
95
  * @param siteId The id of the site.
115
96
  * @param siteHash The has of the site.
116
97
  */
117
- function updatedSiteHash(siteId: number, siteHash: SiteHash) {
118
- const allHash = getHashSites();
98
+ async function updatedSiteHash(siteId: number, siteHash: SiteHash) {
99
+ const allHash = await getHashSites();
119
100
  const lastHash = allHash[siteId];
120
- const currentHash = siteHash || lastHash || new Date().valueOf();
101
+ const currentHash = siteHash || lastHash || Date.now();
121
102
 
122
- const { __cx } = config.paths();
103
+ const { __cx } = await getRenderPathsFromDB();
123
104
  const apiCacheDir = path.join(__cx, "apiCache");
124
105
  const siteHasFilename = `${apiCacheDir}/siteHash.json`;
125
106
 
126
107
  if (currentHash !== lastHash) {
127
108
  allHash[siteId] = currentHash;
128
- fs.writeFileSync(siteHasFilename, JSON.stringify(allHash), {
109
+ await fsp.writeFile(siteHasFilename, JSON.stringify(allHash), {
129
110
  encoding: "utf-8",
130
111
  });
131
112
  }
@@ -133,10 +114,4 @@ function updatedSiteHash(siteId: number, siteHash: SiteHash) {
133
114
  return currentHash.toString();
134
115
  }
135
116
 
136
- export {
137
- createAPICacheDir,
138
- createSha256,
139
- saveCache,
140
- searchCacheData,
141
- updatedSiteHash,
142
- };
117
+ export { createAPICacheDir, saveCache, searchCacheData, updatedSiteHash };
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { CheckHealthError } from "../constants/errors";
4
+ import { isTruthy } from "./core-utils";
5
+ import { throwError } from "./errors";
6
+
7
+ const GRIDDO_ENVS_VARS: ReadonlyArray<string> = [];
8
+ const GRIDDO_SKIP_BUILD_CHECKS = isTruthy(process.env.GRIDDO_SKIP_BUILD_CHECKS);
9
+
10
+ /**
11
+ * Check if a list of environments variables exist with any value.
12
+ *
13
+ * @todo Also check the value.
14
+ * @param envs An array of environments variables
15
+ * @returns exists with (1) if there are missing envs vars
16
+ */
17
+ function checkEnvsVars(envs: ReadonlyArray<string>) {
18
+ const missingEnvs = envs.filter((envName) => {
19
+ return !process.env[envName];
20
+ });
21
+
22
+ if (missingEnvs.length) {
23
+ const missingEnvsMsg = missingEnvs.join("\n");
24
+ console.error(`Env check failed. These envs vars are missing: \n\n${missingEnvsMsg}`);
25
+
26
+ return false;
27
+ }
28
+
29
+ return true;
30
+ }
31
+
32
+ function checkEnvsVarsAndValues(envs: Array<Record<string, string>>): boolean {
33
+ for (const env of envs) {
34
+ const [key, expected] = Object.entries(env)[0];
35
+ const actual = process.env[key];
36
+
37
+ if (actual !== expected) {
38
+ return false;
39
+ }
40
+ }
41
+ return true;
42
+ }
43
+
44
+ /**
45
+ * Check if the environment is secure to launch a render.
46
+ * If something fails then log an error message and exit from the process.
47
+ * Otherwise just return true.
48
+ */
49
+ export function checkHealth() {
50
+ // Bypass the check using this env var, handy for local renders.
51
+ if (GRIDDO_SKIP_BUILD_CHECKS) {
52
+ console.info("Build health check skipped");
53
+
54
+ return true;
55
+ }
56
+
57
+ // Checklist
58
+ // check if it's setted
59
+ const areRequiredEnvsSet = checkEnvsVars(GRIDDO_ENVS_VARS);
60
+ // check if it's setted and the value
61
+ const areEnvsMatchingExpected = checkEnvsVarsAndValues([
62
+ {
63
+ GRIDDO_RENDER_BY_DOMAINS: "true",
64
+ },
65
+ ]);
66
+
67
+ // Render is safe if...
68
+ const isSafeToRender = areRequiredEnvsSet && areEnvsMatchingExpected;
69
+
70
+ // The environment is suitable for a build-render
71
+ if (isSafeToRender) {
72
+ console.info("\nBuild health check passed\n");
73
+
74
+ return true;
75
+ }
76
+
77
+ // Error
78
+ throwError(CheckHealthError);
79
+ }