@griddo/cx 11.9.17-rc.1 → 11.10.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 (254) hide show
  1. package/README.md +13 -240
  2. package/build/commands/end-render.d.ts +0 -1
  3. package/build/commands/end-render.js +31 -0
  4. package/build/commands/end-render.js.map +7 -0
  5. package/build/commands/prepare-assets-directory.js +9 -0
  6. package/build/commands/prepare-assets-directory.js.map +7 -0
  7. package/build/commands/prepare-domains-render.js +40 -0
  8. package/build/commands/prepare-domains-render.js.map +7 -0
  9. package/build/commands/reset-render.d.ts +0 -1
  10. package/build/commands/reset-render.js +31 -0
  11. package/build/commands/reset-render.js.map +7 -0
  12. package/build/commands/single-domain-upload-search-content.d.ts +1 -0
  13. package/build/commands/start-render.d.ts +0 -1
  14. package/build/commands/start-render.js +66 -0
  15. package/build/commands/start-render.js.map +7 -0
  16. package/build/commands/upload-search-content.d.ts +0 -1
  17. package/build/commands/upload-search-content.js +32 -0
  18. package/build/commands/upload-search-content.js.map +7 -0
  19. package/build/core/GriddoLog.d.ts +16 -0
  20. package/build/{utils/health-checks.d.ts → core/check-env-health.d.ts} +4 -2
  21. package/build/core/db-class.d.ts +11 -0
  22. package/build/core/db.d.ts +4 -0
  23. package/build/core/dist-rollback.d.ts +11 -0
  24. package/build/core/errors.d.ts +26 -0
  25. package/build/core/fs.d.ts +69 -0
  26. package/build/core/life-cycle.d.ts +26 -0
  27. package/build/core/logger.d.ts +18 -0
  28. package/build/core/objects.d.ts +11 -0
  29. package/build/core/print-logos.d.ts +5 -0
  30. package/build/index.d.ts +10 -29
  31. package/build/index.js +404 -73
  32. package/build/react/DynamicScript/index.d.ts +4 -0
  33. package/build/react/GriddoFavicon/index.d.ts +4 -0
  34. package/build/react/GriddoIntegrations/index.d.ts +3 -4
  35. package/build/react/GriddoIntegrations/utils.d.ts +7 -6
  36. package/build/react/GriddoOpenGraph/index.d.ts +10 -0
  37. package/build/react/index.d.ts +3 -2
  38. package/build/react/index.js +1 -3
  39. package/build/{utils → services}/api.d.ts +1 -1
  40. package/build/services/auth.d.ts +2 -5
  41. package/build/services/domains.d.ts +3 -4
  42. package/build/services/manage-sites.d.ts +22 -0
  43. package/build/services/manage-store.d.ts +32 -0
  44. package/build/services/navigation.d.ts +16 -16
  45. package/build/{utils → services}/pages.d.ts +3 -3
  46. package/build/services/reference-fields.d.ts +3 -3
  47. package/build/services/render-artifacts.d.ts +6 -0
  48. package/build/services/render.d.ts +70 -0
  49. package/build/services/robots.d.ts +2 -19
  50. package/build/services/sitemaps.d.ts +5 -0
  51. package/build/services/sites.d.ts +8 -5
  52. package/build/services/store.d.ts +10 -1
  53. package/build/shared/context.d.ts +36 -0
  54. package/build/shared/envs.d.ts +17 -0
  55. package/build/{errors/errors-data.d.ts → shared/errors.d.ts} +5 -3
  56. package/build/shared/npm-modules/brush.d.ts +18 -0
  57. package/build/shared/npm-modules/find-up-simple.d.ts +34 -0
  58. package/build/shared/npm-modules/pkg-dir.d.ts +7 -0
  59. package/build/shared/npm-modules/xml-parser.d.ts +4 -0
  60. package/build/{types → shared/types}/api.d.ts +18 -18
  61. package/build/{types → shared/types}/global.d.ts +15 -16
  62. package/build/{types → shared/types}/navigation.d.ts +5 -5
  63. package/build/{types → shared/types}/pages.d.ts +9 -9
  64. package/build/shared/types/render.d.ts +56 -0
  65. package/build/{types → shared/types}/sites.d.ts +18 -19
  66. package/build/shared/types.d.ts +15 -0
  67. package/build/ssg-adapters/gatsby/actions/clean.d.ts +3 -0
  68. package/build/ssg-adapters/gatsby/actions/close.d.ts +3 -0
  69. package/build/ssg-adapters/gatsby/actions/data.d.ts +2 -0
  70. package/build/ssg-adapters/gatsby/actions/healthCheck.d.ts +2 -0
  71. package/build/ssg-adapters/gatsby/actions/init.d.ts +2 -0
  72. package/build/ssg-adapters/gatsby/actions/logs.d.ts +3 -0
  73. package/build/ssg-adapters/gatsby/actions/meta.d.ts +2 -0
  74. package/build/ssg-adapters/gatsby/actions/prepare.d.ts +2 -0
  75. package/build/ssg-adapters/gatsby/actions/relocation.d.ts +2 -0
  76. package/build/ssg-adapters/gatsby/actions/restore.d.ts +3 -0
  77. package/build/ssg-adapters/gatsby/actions/ssg.d.ts +3 -0
  78. package/build/ssg-adapters/gatsby/actions/sync.d.ts +3 -0
  79. package/build/ssg-adapters/gatsby/index.d.ts +9 -0
  80. package/build/ssg-adapters/gatsby/shared/artifacts.d.ts +4 -0
  81. package/build/ssg-adapters/gatsby/shared/diff-assets.d.ts +15 -0
  82. package/build/ssg-adapters/gatsby/shared/extract-assets.d.ts +7 -0
  83. package/build/ssg-adapters/gatsby/shared/gatsby-build.d.ts +7 -0
  84. package/build/ssg-adapters/gatsby/shared/render-rollback.d.ts +18 -0
  85. package/build/ssg-adapters/gatsby/shared/sync-render.d.ts +26 -0
  86. package/build/ssg-adapters/gatsby/shared/types.d.ts +34 -0
  87. package/cli.mjs +231 -0
  88. package/exporter/build-esbuild.noop +42 -0
  89. package/exporter/build.sh +16 -24
  90. package/exporter/commands/README.md +142 -0
  91. package/exporter/commands/end-render.ts +53 -87
  92. package/exporter/commands/prepare-assets-directory.ts +35 -0
  93. package/exporter/commands/prepare-domains-render.ts +150 -33
  94. package/exporter/commands/reset-render.ts +13 -8
  95. package/exporter/commands/single-domain-upload-search-content.ts +206 -0
  96. package/exporter/commands/start-render.ts +14 -65
  97. package/exporter/commands/upload-search-content.ts +204 -26
  98. package/exporter/core/GriddoLog.ts +45 -0
  99. package/exporter/core/check-env-health.ts +203 -0
  100. package/exporter/core/db-class.ts +54 -0
  101. package/exporter/core/db.ts +33 -0
  102. package/exporter/core/dist-rollback.ts +49 -0
  103. package/exporter/core/errors.ts +93 -0
  104. package/exporter/core/fs.ts +385 -0
  105. package/exporter/{utils → core}/images.ts +1 -6
  106. package/exporter/{utils → core}/instance.ts +9 -13
  107. package/exporter/core/life-cycle.ts +73 -0
  108. package/exporter/core/logger.ts +137 -0
  109. package/exporter/core/objects.ts +37 -0
  110. package/exporter/core/print-logos.ts +21 -0
  111. package/exporter/index.ts +14 -56
  112. package/exporter/react/DynamicScript/index.tsx +33 -0
  113. package/exporter/react/{Favicon → GriddoFavicon}/index.tsx +3 -9
  114. package/exporter/react/GriddoIntegrations/index.tsx +17 -23
  115. package/exporter/react/GriddoIntegrations/utils.ts +24 -12
  116. package/exporter/react/GriddoOpenGraph/index.tsx +39 -0
  117. package/exporter/react/index.tsx +3 -9
  118. package/exporter/services/api.ts +306 -0
  119. package/exporter/services/auth.ts +8 -10
  120. package/exporter/services/domains.ts +23 -8
  121. package/exporter/services/manage-sites.ts +116 -0
  122. package/exporter/services/manage-store.ts +173 -0
  123. package/exporter/services/navigation.ts +12 -18
  124. package/exporter/{utils → services}/pages.ts +27 -92
  125. package/exporter/services/reference-fields.ts +14 -32
  126. package/exporter/services/render-artifacts.ts +44 -0
  127. package/exporter/services/render.ts +229 -0
  128. package/exporter/services/robots.ts +33 -61
  129. package/exporter/services/sitemaps.ts +129 -0
  130. package/exporter/services/sites.ts +40 -28
  131. package/exporter/services/store.ts +354 -321
  132. package/exporter/shared/context.ts +49 -0
  133. package/exporter/{constants → shared}/endpoints.ts +12 -11
  134. package/exporter/shared/envs.ts +58 -0
  135. package/exporter/{errors/errors-data.ts → shared/errors.ts} +24 -14
  136. package/exporter/shared/npm-modules/README.md +36 -0
  137. package/exporter/shared/npm-modules/brush.ts +34 -0
  138. package/exporter/shared/npm-modules/find-up-simple.ts +100 -0
  139. package/exporter/shared/npm-modules/pkg-dir.ts +17 -0
  140. package/exporter/shared/npm-modules/xml-parser.ts +57 -0
  141. package/exporter/{types → shared/types}/api.ts +40 -41
  142. package/exporter/{types → shared/types}/global.ts +17 -21
  143. package/exporter/{types → shared/types}/navigation.ts +3 -3
  144. package/exporter/{types → shared/types}/pages.ts +10 -11
  145. package/exporter/shared/types/render.ts +65 -0
  146. package/exporter/{types → shared/types}/sites.ts +18 -19
  147. package/exporter/shared/types.ts +15 -0
  148. package/exporter/ssg-adapters/gatsby/actions/clean.ts +26 -0
  149. package/exporter/ssg-adapters/gatsby/actions/close.ts +17 -0
  150. package/exporter/ssg-adapters/gatsby/actions/data.ts +22 -0
  151. package/exporter/ssg-adapters/gatsby/actions/healthCheck.ts +10 -0
  152. package/exporter/ssg-adapters/gatsby/actions/init.ts +12 -0
  153. package/exporter/ssg-adapters/gatsby/actions/logs.ts +10 -0
  154. package/exporter/ssg-adapters/gatsby/actions/meta.ts +13 -0
  155. package/exporter/ssg-adapters/gatsby/actions/prepare.ts +9 -0
  156. package/exporter/ssg-adapters/gatsby/actions/relocation.ts +15 -0
  157. package/exporter/ssg-adapters/gatsby/actions/restore.ts +21 -0
  158. package/exporter/ssg-adapters/gatsby/actions/ssg.ts +12 -0
  159. package/exporter/ssg-adapters/gatsby/actions/sync.ts +65 -0
  160. package/exporter/ssg-adapters/gatsby/index.ts +117 -0
  161. package/exporter/ssg-adapters/gatsby/shared/artifacts.ts +17 -0
  162. package/exporter/ssg-adapters/gatsby/shared/diff-assets.ts +128 -0
  163. package/exporter/ssg-adapters/gatsby/shared/extract-assets.ts +75 -0
  164. package/exporter/ssg-adapters/gatsby/shared/gatsby-build.ts +58 -0
  165. package/exporter/ssg-adapters/gatsby/shared/render-rollback.ts +33 -0
  166. package/exporter/ssg-adapters/gatsby/shared/sync-render.ts +298 -0
  167. package/exporter/ssg-adapters/gatsby/shared/types.ts +35 -0
  168. package/gatsby-browser.tsx +41 -58
  169. package/gatsby-config.ts +10 -17
  170. package/gatsby-node.ts +20 -79
  171. package/gatsby-ssr.tsx +2 -1
  172. package/package.json +41 -78
  173. package/plugins/gatsby-plugin-svgr-loader/gatsby-node.js +55 -0
  174. package/plugins/gatsby-plugin-svgr-loader/package.json +8 -0
  175. package/src/components/Head.tsx +28 -73
  176. package/src/components/template.tsx +6 -29
  177. package/src/gatsby-node-utils.ts +81 -2
  178. package/src/html.tsx +2 -11
  179. package/src/types.ts +3 -3
  180. package/tsconfig.commands.json +36 -0
  181. package/tsconfig.exporter.json +21 -0
  182. package/tsconfig.json +5 -3
  183. package/build/adapters/gatsby/index.d.ts +0 -4
  184. package/build/adapters/gatsby/utils.d.ts +0 -26
  185. package/build/artifacts/index.d.ts +0 -6
  186. package/build/constants/envs.d.ts +0 -37
  187. package/build/constants/index.d.ts +0 -57
  188. package/build/end-render.js +0 -74
  189. package/build/end-render.js.map +0 -7
  190. package/build/errors/index.d.ts +0 -15
  191. package/build/index.js.map +0 -7
  192. package/build/prepare-domains-render.js +0 -73
  193. package/build/prepare-domains-render.js.map +0 -7
  194. package/build/react/Favicon/index.d.ts +0 -5
  195. package/build/registers/api.d.ts +0 -9
  196. package/build/registers/gatsby.d.ts +0 -9
  197. package/build/registers/index.d.ts +0 -3
  198. package/build/reset-render.js +0 -74
  199. package/build/reset-render.js.map +0 -7
  200. package/build/services/register.d.ts +0 -36
  201. package/build/services/settings.d.ts +0 -4
  202. package/build/start-render.js +0 -100
  203. package/build/start-render.js.map +0 -7
  204. package/build/upload-search-content.js +0 -74
  205. package/build/upload-search-content.js.map +0 -7
  206. package/build/utils/alerts.d.ts +0 -3
  207. package/build/utils/cache.d.ts +0 -35
  208. package/build/utils/core-utils.d.ts +0 -107
  209. package/build/utils/create-build-data.d.ts +0 -8
  210. package/build/utils/domains.d.ts +0 -13
  211. package/build/utils/folders.d.ts +0 -53
  212. package/build/utils/loggin.d.ts +0 -51
  213. package/build/utils/render.d.ts +0 -13
  214. package/build/utils/searches.d.ts +0 -15
  215. package/build/utils/sites.d.ts +0 -31
  216. package/build/utils/store.d.ts +0 -81
  217. package/cx.config.d.ts +0 -5
  218. package/cx.config.js +0 -36
  219. package/exporter/adapters/gatsby/index.ts +0 -182
  220. package/exporter/adapters/gatsby/utils.ts +0 -186
  221. package/exporter/artifacts/README.md +0 -34
  222. package/exporter/artifacts/index.ts +0 -33
  223. package/exporter/commands/move-assets.ts +0 -11
  224. package/exporter/constants/envs.ts +0 -94
  225. package/exporter/constants/index.ts +0 -129
  226. package/exporter/errors/index.ts +0 -40
  227. package/exporter/registers/api.ts +0 -14
  228. package/exporter/registers/gatsby.ts +0 -14
  229. package/exporter/registers/index.ts +0 -4
  230. package/exporter/services/register.ts +0 -113
  231. package/exporter/services/settings.ts +0 -17
  232. package/exporter/utils/alerts.ts +0 -29
  233. package/exporter/utils/api.ts +0 -243
  234. package/exporter/utils/cache.ts +0 -142
  235. package/exporter/utils/core-utils.ts +0 -458
  236. package/exporter/utils/create-build-data.ts +0 -17
  237. package/exporter/utils/domains.ts +0 -39
  238. package/exporter/utils/folders.ts +0 -320
  239. package/exporter/utils/health-checks.ts +0 -64
  240. package/exporter/utils/loggin.ts +0 -184
  241. package/exporter/utils/render.ts +0 -71
  242. package/exporter/utils/searches.ts +0 -156
  243. package/exporter/utils/sites.ts +0 -312
  244. package/exporter/utils/store.ts +0 -314
  245. package/src/README.md +0 -7
  246. package/start-render.js +0 -7
  247. /package/build/commands/{move-assets.d.ts → prepare-assets-directory.d.ts} +0 -0
  248. /package/build/{utils → core}/images.d.ts +0 -0
  249. /package/build/{utils → core}/instance.d.ts +0 -0
  250. /package/build/react/{Favicon → GriddoFavicon}/utils.d.ts +0 -0
  251. /package/build/{constants → shared}/endpoints.d.ts +0 -0
  252. /package/build/{types → shared/types}/templates.d.ts +0 -0
  253. /package/exporter/react/{Favicon → GriddoFavicon}/utils.ts +0 -0
  254. /package/exporter/{types → shared/types}/templates.ts +0 -0
@@ -1,29 +0,0 @@
1
- import type { GriddoAlertRegisterProps } from "@griddo/core";
2
-
3
- import axios from "axios";
4
-
5
- import { endpoints } from "../constants";
6
-
7
- // Esta función está duplicada de core de manera intencionada por si esta recibe
8
- // cambios necesitados solo por CX.
9
- // Nota: Sí estamos reutilizando el type.
10
- async function insertAlert({
11
- area,
12
- description,
13
- fullData,
14
- instantNotification = false,
15
- level,
16
- }: Omit<GriddoAlertRegisterProps, "publicApiUrl">) {
17
- const url = endpoints.ALERT;
18
- const body = { level, area, description, fullData, instantNotification };
19
-
20
- try {
21
- await axios.post(url, body, {
22
- headers: { "Content-Type": "application/json", Connection: "close" },
23
- });
24
- } catch (error) {
25
- console.error("Error creating Griddo alert:", error);
26
- }
27
- }
28
-
29
- export { insertAlert };
@@ -1,243 +0,0 @@
1
- import type {
2
- APIRequest,
3
- APIResponses,
4
- GetAPI,
5
- PostAPI,
6
- PutAPI,
7
- ShowApiErrorOptions,
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
-
15
- import { saveCache, searchCacheData } from "./cache";
16
- import { delay, getSafeSiteId, msToSec } from "./core-utils";
17
- 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
-
24
- // Envs
25
- const {
26
- env: { RETRY_WAIT_SECONDS = "4", RETRY_ATTEMPTS = "4" },
27
- } = process;
28
-
29
- /**
30
- * Make a GET/PUT/POST request to the Griddo API.
31
- *
32
- * @template T Response Type returned.
33
- * @returns {Promise<T>} A promise that is resolved with the data from the API response.
34
- *
35
- * @example
36
- * const response = await requestAPI<Site>(
37
- * { endpoint: "...", cacheKey: "...", ... },
38
- * "get",
39
- * "..."
40
- * );
41
- */
42
- async function requestAPI<T extends APIResponses>(
43
- props: APIRequest,
44
- method: Method,
45
- appendToLog = "",
46
- ): Promise<T> {
47
- const {
48
- endpoint,
49
- body,
50
- cacheKey = "",
51
- attempt = 1,
52
- headers,
53
- useApiCacheDir = true,
54
- } = props;
55
- const cacheOptions = { endpoint, body, headers, cacheKey };
56
-
57
- // Cache
58
- if (cacheKey && useApiCacheDir) {
59
- const start = new Date();
60
- const cacheData = searchCacheData<T>(cacheOptions);
61
-
62
- if (cacheData) {
63
- const siteId = getSafeSiteId(cacheData);
64
- 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
- );
69
- return cacheData;
70
- }
71
- }
72
-
73
- // Network
74
- try {
75
- 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
- });
85
-
86
- const siteId = getSafeSiteId(data);
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
- );
92
-
93
- 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
- }
107
- }
108
-
109
- return data;
110
- } 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
- }
117
-
118
- if (attempt > parseInt(RETRY_ATTEMPTS)) {
119
- console.log(`
120
- Max attempts ${RETRY_ATTEMPTS} reached
121
- --------------------------------------
122
- - ${method.toUpperCase()} ${endpoint}
123
- - BODY: ${JSON.stringify(body)}
124
- - HEADERS: ${JSON.stringify(headers)}
125
- - RESPONSE: ${error.response?.status} ${JSON.stringify(error.response?.data)}
126
- --------------------------------------
127
- `);
128
-
129
- console.log(JSON.stringify(error, null, 2));
130
- process.exit(1);
131
- }
132
-
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
- showApiError(error, {
140
- callInfo: { endpoint, body },
141
- });
142
-
143
- console.warn(`Waiting for retry: ${method}`, endpoint);
144
-
145
- await delay(parseInt(RETRY_WAIT_SECONDS) * 1000);
146
-
147
- return requestAPI<T>(
148
- {
149
- endpoint,
150
- body,
151
- headers,
152
- cacheKey,
153
- attempt: attempt + 1,
154
- },
155
- method,
156
- appendToLog,
157
- );
158
- }
159
- }
160
-
161
- /**
162
- * Make a GET request to the Griddo API.
163
- *
164
- * @template T Response Type returned.
165
- * @returns A promise that is resolved with the data from the API response.
166
- */
167
- async function getApi<T extends APIResponses>(props: GetAPI) {
168
- return requestAPI<T>(props, "get");
169
- }
170
-
171
- /**
172
- * Make a PUT request to the Griddo API.
173
- *
174
- * @template T Response Type returned.
175
- * @returns A promise that is resolved with the data from the API response.
176
- */
177
- async function putApi<T extends APIResponses>(props: PutAPI) {
178
- return requestAPI<T>(props, "put");
179
- }
180
-
181
- /**
182
- * Make a POST request to the Griddo API.
183
- *
184
- * @template T Response Type returned.
185
- * @returns A promise that is resolved with the data from the API response.
186
- */
187
- async function postApi<T extends APIResponses>(props: PostAPI) {
188
- const { endpoint, body, headers } = props;
189
- const referenceFieldBodyParams =
190
- endpoint.endsWith("/distributor") &&
191
- `# ReferenceField body: ${JSON.stringify(body)} lang: ${JSON.stringify(
192
- headers?.lang,
193
- )}`;
194
-
195
- return requestAPI<T>(props, "post", referenceFieldBodyParams || "");
196
- }
197
-
198
- /**
199
- * Shows an API error through the terminal.
200
- */
201
- function showApiError(error: AxiosError, options: ShowApiErrorOptions) {
202
- const { response, message, stack } = error;
203
- const { callInfo } = options;
204
- const { status, statusText, data } = response || {};
205
- const callInfoArray = [];
206
-
207
- for (const item of Object.keys(callInfo) as Array<keyof typeof callInfo>) {
208
- callInfoArray.push(
209
- `${item}: ${
210
- typeof callInfo[item] === "object"
211
- ? JSON.stringify(callInfo[item])
212
- : callInfo[item]
213
- }`,
214
- );
215
- }
216
-
217
- // Compose the errors output
218
- const callInfoStr = callInfoArray.join("\n");
219
- const apiResponseStr = response
220
- ? `Code: ${status} - ${statusText}\nResponse: ${JSON.stringify(data)}`
221
- : "";
222
- const errorDetailsStr = `${message}\n${stack}`;
223
-
224
- // Print the error
225
- console.warn(
226
- kleur.red(`
227
- =============
228
-
229
- { Call info }
230
- ${callInfoStr}
231
-
232
- { API Response }
233
- ${apiResponseStr}
234
-
235
- { Error details }
236
- ${errorDetailsStr}
237
-
238
- =============
239
- `),
240
- );
241
- }
242
-
243
- export { getApi as get, postApi as post, putApi as put };
@@ -1,142 +0,0 @@
1
- import type { Petition } from "../types/global";
2
- import type { HashSites, SiteHash } from "../types/sites";
3
-
4
- import crypto from "node:crypto";
5
- import fs from "node:fs";
6
- import path from "node:path";
7
-
8
- import fsx from "fs-extra";
9
-
10
- import { getConfig } from "./core-utils";
11
-
12
- const config = getConfig();
13
-
14
- /**
15
- * Creates an `apiCache` dir to store pages fetched from them API.
16
- */
17
- function createAPICacheDir() {
18
- const { __cx } = config.paths();
19
- const apiCacheDir = path.join(__cx, "apiCache");
20
-
21
- if (!fs.existsSync(apiCacheDir)) {
22
- fs.mkdirSync(apiCacheDir);
23
- }
24
-
25
- console.info("Cache initialized");
26
- }
27
-
28
- /**
29
- * Generate a filename with a hash using a Petition object
30
- *
31
- * @todo Merge with createSha256
32
- * @param petition An object
33
- */
34
- function generateFilenameWithHash(petition: Petition) {
35
- const { __cx } = config.paths();
36
- const apiCacheDir = path.join(__cx, "apiCache");
37
-
38
- const hashSum = crypto.createHash("sha256");
39
- hashSum.update(JSON.stringify(petition));
40
-
41
- return `${apiCacheDir}/${hashSum.digest("hex")}`;
42
- }
43
-
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
- /**
59
- * Save a file using a hash name.
60
- *
61
- * @param petition An object.
62
- * @param content Content to be saved.
63
- */
64
- function saveCache<T>(petition: Petition, content: T) {
65
- const stringContent =
66
- typeof content === "string" ? content : JSON.stringify(content);
67
- const filename = generateFilenameWithHash(petition);
68
- const filepath = path.dirname(filename);
69
- if (!fs.existsSync(filepath)) {
70
- fs.mkdirSync(filepath, { recursive: true });
71
- }
72
- fs.writeFileSync(filename, stringContent, "utf8");
73
- }
74
-
75
- /**
76
- * Search in the `apiCache` dir for a file using the petition as hash generator.
77
- * Return the file content if found or null if not.
78
- *
79
- * @param petition An object
80
- */
81
- function searchCacheData<T>(petition: Petition) {
82
- try {
83
- const file = generateFilenameWithHash(petition);
84
- const jsonData = fsx.readJSONSync(file, {
85
- encoding: "utf-8",
86
- });
87
- return jsonData as T;
88
- } catch {
89
- return null;
90
- }
91
- }
92
-
93
- /**
94
- * Get site hashes from the file as an object
95
- */
96
- function getHashSites(): HashSites {
97
- const { __cx } = config.paths();
98
- const apiCacheDir = path.join(__cx, "apiCache");
99
- const siteHasFilename = `${apiCacheDir}/siteHash.json`;
100
-
101
- try {
102
- const jsonData = fsx.readJSONSync(siteHasFilename, {
103
- encoding: "utf-8",
104
- });
105
- return jsonData || {};
106
- } catch {
107
- return {};
108
- }
109
- }
110
-
111
- /**
112
- * Update (write) the site hash file.
113
- *
114
- * @param siteId The id of the site.
115
- * @param siteHash The has of the site.
116
- */
117
- function updatedSiteHash(siteId: number, siteHash: SiteHash) {
118
- const allHash = getHashSites();
119
- const lastHash = allHash[siteId];
120
- const currentHash = siteHash || lastHash || new Date().valueOf();
121
-
122
- const { __cx } = config.paths();
123
- const apiCacheDir = path.join(__cx, "apiCache");
124
- const siteHasFilename = `${apiCacheDir}/siteHash.json`;
125
-
126
- if (currentHash !== lastHash) {
127
- allHash[siteId] = currentHash;
128
- fs.writeFileSync(siteHasFilename, JSON.stringify(allHash), {
129
- encoding: "utf-8",
130
- });
131
- }
132
-
133
- return currentHash.toString();
134
- }
135
-
136
- export {
137
- createAPICacheDir,
138
- createSha256,
139
- saveCache,
140
- searchCacheData,
141
- updatedSiteHash,
142
- };