zoho-sites-dev-cli 0.0.0-stage → 1.0.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 (52) hide show
  1. package/README.md +401 -2
  2. package/bin/zoho-sites-dev-cli.js +107 -0
  3. package/config/default.json +18 -0
  4. package/index.js +6 -0
  5. package/package.json +55 -4
  6. package/src/commands/auth.js +136 -0
  7. package/src/commands/create.js +175 -0
  8. package/src/commands/deploy.js +380 -0
  9. package/src/commands/generate-zip.js +49 -0
  10. package/src/commands/index.js +23 -0
  11. package/src/commands/init-tailwind.js +57 -0
  12. package/src/commands/init.js +448 -0
  13. package/src/commands/install.js +89 -0
  14. package/src/commands/login.js +248 -0
  15. package/src/commands/pull.js +41 -0
  16. package/src/commands/serve.js +162 -0
  17. package/src/compilers/css-compiler.js +230 -0
  18. package/src/compilers/css-ignore-loader.js +33 -0
  19. package/src/compilers/plugins/index.js +12 -0
  20. package/src/compilers/plugins/root-selector-transform-plugin.js +79 -0
  21. package/src/compilers/tailwind-compiler.js +102 -0
  22. package/src/compilers/webpack-compiler.js +512 -0
  23. package/src/compilers/webpack-config.js +103 -0
  24. package/src/config/constants.js +125 -0
  25. package/src/config/environments/audiences.js +19 -0
  26. package/src/config/environments/index.js +78 -0
  27. package/src/config/environments/internal.js +72 -0
  28. package/src/config/environments/production.js +39 -0
  29. package/src/locales/en.json +216 -0
  30. package/src/services/devServer.js +489 -0
  31. package/src/services/oauthService.js +672 -0
  32. package/src/templates/component/fields.json +6 -0
  33. package/src/templates/component/index.js +11 -0
  34. package/src/templates/component/llm.md +9 -0
  35. package/src/templates/component/meta.json +9 -0
  36. package/src/templates/component/styles.css +3 -0
  37. package/src/templates/oauth/complete.html +41 -0
  38. package/src/templates/oauth/error.html +69 -0
  39. package/src/templates/oauth/invalid-request.html +58 -0
  40. package/src/templates/oauth/loading.html +80 -0
  41. package/src/templates/oauth/not-found.html +33 -0
  42. package/src/templates/oauth/success.html +70 -0
  43. package/src/templates/oauth/timeout.html +56 -0
  44. package/src/templates/oauth/token-error.html +57 -0
  45. package/src/utils/configUtil.js +66 -0
  46. package/src/utils/httpUtil.js +351 -0
  47. package/src/utils/i18n.js +205 -0
  48. package/src/utils/loadingUtil.js +190 -0
  49. package/src/utils/secureConfig.js +75 -0
  50. package/src/utils/secureStorage.js +230 -0
  51. package/src/utils/templateLoader.js +89 -0
  52. package/src/utils/urlUtil.js +371 -0
@@ -0,0 +1,351 @@
1
+ const axios = require("axios");
2
+ const https = require("https");
3
+ const { readFileSync } = require("fs");
4
+ const { dirname, join } = require("path");
5
+ const SecureStorage = require("./secureStorage.js");
6
+ const { i18n } = require("./i18n.js");
7
+ const OAuthService = require("../services/oauthService.js");
8
+ const { loadingUtil } = require("./loadingUtil.js");
9
+
10
+ // Shared instances for state management
11
+ const defaultTimeout = 30000; // 30 seconds
12
+
13
+ /**
14
+ * Get version from package.json
15
+ * @returns {string} Version string
16
+ */
17
+ function getVersion() {
18
+ try {
19
+ const packageJson = JSON.parse(
20
+ readFileSync(
21
+ join(__dirname, "../../package.json"),
22
+ "utf8"
23
+ )
24
+ );
25
+ return packageJson.version || "1.0.0";
26
+ } catch (error) {
27
+ return "1.0.0";
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Read asoid/siteId from project `.zs` for resource API headers.
33
+ * Returns null when not in a project (login, init before config is written).
34
+ * @returns {string|null}
35
+ */
36
+ function getProjectSiteIdForHeader() {
37
+ try {
38
+ const { readProjectConfig } = require("./configUtil.js");
39
+ const config = readProjectConfig();
40
+ const siteId = config.asoid || config.siteId;
41
+ return siteId ? String(siteId) : null;
42
+ } catch (_) {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Get common headers including authentication and x-site-id when available
49
+ * @returns {Promise<Object>} Headers object
50
+ */
51
+ async function getCommonHeaders() {
52
+ const headers = {
53
+ "Content-Type": "application/json",
54
+ Accept: "application/json",
55
+ "User-Agent": `ZS-CLI/${getVersion()}`,
56
+ };
57
+
58
+ // Add authentication header if user is logged in
59
+ const authHeader = await new OAuthService().getAuthorizationHeader();
60
+ if (authHeader) {
61
+ Object.assign(headers, authHeader);
62
+ }
63
+
64
+ // Resource APIs require the account asoid as x-site-id
65
+ const siteId = getProjectSiteIdForHeader();
66
+ if (siteId) {
67
+ headers["x-site-id"] = siteId;
68
+ }
69
+
70
+ return headers;
71
+ }
72
+
73
+ /**
74
+ * Configure axios with enhanced settings for better compatibility
75
+ * @param {Object} config - Base axios config
76
+ * @returns {Promise<Object>} Enhanced config
77
+ */
78
+ async function enhanceAxiosConfig(config) {
79
+ const enhancedConfig = {
80
+ ...config,
81
+ httpsAgent: undefined,
82
+ proxy: false,
83
+ validateStatus: (status) => status >= 200 && status < 300,
84
+ maxRedirects: 5,
85
+ timeout: config.timeout || defaultTimeout,
86
+ paramsSerializer: (params) => {
87
+ return new URLSearchParams(params).toString();
88
+ },
89
+ };
90
+
91
+ // Handle SSL/TLS issues for local development servers
92
+ const isLocalDevelopment =
93
+ config.url &&
94
+ (config.url.includes(".devzohositescontent.com") ||
95
+ config.url.includes(".csez.zohocorpin.com") ||
96
+ config.url.includes("localhost") ||
97
+ config.url.includes("127.0.0.1"));
98
+
99
+ if (isLocalDevelopment) {
100
+ enhancedConfig.proxy = false;
101
+ enhancedConfig.httpsAgent = new https.Agent({
102
+ rejectUnauthorized: false,
103
+ requestCert: false,
104
+ agent: false,
105
+ checkServerIdentity: () => undefined,
106
+ secureOptions: 0,
107
+ // Honor request-specific timeout (e.g., large uploads)
108
+ timeout: enhancedConfig.timeout,
109
+ keepAlive: true,
110
+ maxSockets: 100,
111
+ });
112
+ enhancedConfig.rejectUnauthorized = false;
113
+ // process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
114
+ }
115
+
116
+ return enhancedConfig;
117
+ }
118
+
119
+ /**
120
+ * Private function: Generic request handler with error handling and loading support
121
+ * @param {Object} config - Axios config object
122
+ * @param {string} loadingMessage - Loading message to display
123
+ * @returns {Promise} Response data
124
+ * @private
125
+ */
126
+ async function _sendRequest(config, loadingMessage = null) {
127
+ let loadingStarted = false;
128
+
129
+ try {
130
+ // Start loading if message provided
131
+ if (loadingMessage) {
132
+ loadingUtil.start(loadingMessage);
133
+ loadingStarted = true;
134
+ }
135
+
136
+ // Enhance config for better compatibility
137
+ const enhancedConfig = await enhanceAxiosConfig(config);
138
+
139
+ // Make the request
140
+ const response = await axios(enhancedConfig);
141
+
142
+ // Stop loading on success
143
+ if (loadingStarted) {
144
+ loadingUtil.stop(
145
+ i18n.t("commands.login.requestSuccessful", { status: response.status })
146
+ );
147
+ }
148
+
149
+ return response.data;
150
+ } catch (error) {
151
+ // Stop loading on error
152
+ if (loadingStarted) {
153
+ loadingUtil.stop(
154
+ i18n.t("commands.login.requestFailed", { error: error.message })
155
+ );
156
+ }
157
+
158
+ // Handle specific HTTP error codes with i18n messages
159
+ if (error.response) {
160
+ const { status, data } = error.response;
161
+
162
+ switch (status) {
163
+ case 401:
164
+ i18n.error("commands.login.authenticationFailed");
165
+ throw new Error(i18n.t("commands.login.authenticationFailed"));
166
+
167
+ case 403:
168
+ i18n.error("commands.login.accessForbidden");
169
+ throw new Error(i18n.t("commands.login.accessForbidden"));
170
+
171
+ case 404:
172
+ i18n.error("commands.login.resourceNotFound");
173
+ throw new Error(i18n.t("commands.login.resourceNotFound"));
174
+
175
+ case 429:
176
+ i18n.error("commands.login.rateLimitExceeded");
177
+ throw new Error(i18n.t("commands.login.rateLimitExceeded"));
178
+
179
+ case 500:
180
+ i18n.error("commands.login.serverError");
181
+ throw new Error(i18n.t("commands.login.serverError"));
182
+
183
+ default:
184
+ i18n.error("commands.login.httpError", {
185
+ status: status,
186
+ data: data,
187
+ });
188
+ throw new Error(
189
+ i18n.t("commands.login.httpError", {
190
+ status: status,
191
+ data: data?.message || error.message,
192
+ })
193
+ );
194
+ }
195
+ } else if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED") {
196
+ i18n.error("commands.login.networkConnectionError");
197
+ throw new Error(i18n.t("commands.login.networkConnectionError"));
198
+ } else if (error.code === "ECONNABORTED") {
199
+ // Axios timeout
200
+ i18n.error("commands.login.requestTimeout");
201
+ throw new Error(i18n.t("commands.login.requestTimeout"));
202
+ }
203
+
204
+ throw error;
205
+ }
206
+ }
207
+
208
+ /**
209
+ * GET request
210
+ * @param {string} url - Request URL
211
+ * @param {Object} options - Request options
212
+ * @param {string} loadingMessage - Loading message to display
213
+ * @returns {Promise} Response data
214
+ */
215
+ async function GET(url, options = {}, loadingMessage = null) {
216
+ const headers = await getCommonHeaders();
217
+ if (options.headers) {
218
+ Object.assign(headers, options.headers);
219
+ }
220
+
221
+ const config = {
222
+ method: "GET",
223
+ url,
224
+ headers,
225
+ params: options.params,
226
+ ...options,
227
+ };
228
+
229
+ const message =
230
+ loadingMessage || loadingUtil.getLoadingMessageFromUrl(url, "GET");
231
+ return _sendRequest(config, message);
232
+ }
233
+
234
+ /**
235
+ * POST request
236
+ * @param {string} url - Request URL
237
+ * @param {Object} data - Request payload
238
+ * @param {Object} options - Request options
239
+ * @param {string} loadingMessage - Loading message to display
240
+ * @returns {Promise} Response data
241
+ */
242
+ async function POST(url, data = null, options = {}, loadingMessage = null) {
243
+ let headers = await getCommonHeaders();
244
+ if (options.headers) {
245
+ Object.assign(headers, options.headers);
246
+ }
247
+ // If sending FormData, let axios set the proper multipart boundary header
248
+ try {
249
+ if (typeof FormData !== 'undefined' && data instanceof FormData) {
250
+ delete headers["Content-Type"]; // allow axios to set multipart/form-data; boundary=...
251
+ delete headers["content-type"]; // case-insensitive safety
252
+ }
253
+ } catch (_) {}
254
+ const config = {
255
+ method: "POST",
256
+ url,
257
+ data,
258
+ params: options.params,
259
+ ...options,
260
+ headers, // Move headers after ...options to prevent overwriting
261
+ };
262
+
263
+ const message =
264
+ loadingMessage || loadingUtil.getLoadingMessageFromUrl(url, "POST");
265
+
266
+ return _sendRequest(config, message);
267
+ }
268
+
269
+ /**
270
+ * PUT request
271
+ * @param {string} url - Request URL
272
+ * @param {Object} data - Request payload
273
+ * @param {Object} options - Request options
274
+ * @param {string} loadingMessage - Loading message to display
275
+ * @returns {Promise} Response data
276
+ */
277
+ async function PUT(url, data = null, options = {}, loadingMessage = null) {
278
+ const headers = await getCommonHeaders();
279
+ if (options.headers) {
280
+ Object.assign(headers, options.headers);
281
+ }
282
+
283
+ const config = {
284
+ method: "PUT",
285
+ url,
286
+ data,
287
+ params: options.params,
288
+ ...options,
289
+ headers, // Move headers after ...options to prevent overwriting
290
+ };
291
+
292
+ const message =
293
+ loadingMessage || loadingUtil.getLoadingMessageFromUrl(url, "PUT");
294
+ return _sendRequest(config, message);
295
+ }
296
+
297
+ /**
298
+ * DELETE request
299
+ * @param {string} url - Request URL
300
+ * @param {Object} options - Request options
301
+ * @param {string} loadingMessage - Loading message to display
302
+ * @returns {Promise} Response data
303
+ */
304
+ async function DELETE(url, options = {}, loadingMessage = null) {
305
+ const headers = await getCommonHeaders();
306
+
307
+ if (options.headers) {
308
+ Object.assign(headers, options.headers);
309
+ }
310
+
311
+
312
+ const config = {
313
+ method: "DELETE",
314
+ url,
315
+ params: options.params,
316
+ ...options,
317
+ headers, // Move headers after ...options to prevent overwriting
318
+ };
319
+
320
+ const message =
321
+ loadingMessage || loadingUtil.getLoadingMessageFromUrl(url, "DELETE");
322
+ return _sendRequest(config, message);
323
+ }
324
+
325
+ /**
326
+ * Check if user is authenticated
327
+ * @returns {Promise<boolean>} True if authenticated
328
+ */
329
+ async function isAuthenticated() {
330
+ return await new OAuthService().isAuthenticated();
331
+ }
332
+
333
+ /**
334
+ * Get current user information
335
+ * @returns {Promise<Object|null>} User data or null
336
+ */
337
+ async function getCurrentUser() {
338
+ return await new SecureStorage().getCurrentUser();
339
+ }
340
+
341
+ // Export for backward compatibility (create a simple object with the same interface)
342
+ const httpUtil = {
343
+ get: GET,
344
+ post: POST,
345
+ put: PUT,
346
+ delete: DELETE,
347
+ isAuthenticated,
348
+ getCurrentUser,
349
+ };
350
+
351
+ module.exports = { GET, POST, PUT, DELETE, isAuthenticated, getCurrentUser, httpUtil };
@@ -0,0 +1,205 @@
1
+ const { readFileSync } = require('fs');
2
+ const { join, dirname } = require('path');
3
+ const chalk = require('chalk');
4
+
5
+ /**
6
+ * I18n utility for internationalization support
7
+ */
8
+ class I18n {
9
+ constructor() {
10
+ this.currentLocale = 'en'; // Default locale
11
+ this.translations = {};
12
+ this.fallbackLocale = 'en';
13
+ this.loadTranslations();
14
+ }
15
+
16
+ /**
17
+ * Load translations for the current locale
18
+ */
19
+ loadTranslations() {
20
+ try {
21
+ const translationPath = join(__dirname, '..', 'locales', `${this.currentLocale}.json`);
22
+ const translationData = readFileSync(translationPath, 'utf8');
23
+ this.translations = JSON.parse(translationData);
24
+ } catch (error) {
25
+ // Silently fallback to default locale if translation file not found
26
+ if (this.currentLocale !== this.fallbackLocale) {
27
+ this.currentLocale = this.fallbackLocale;
28
+ this.loadTranslations();
29
+ }
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Set the current locale
35
+ * @param {string} locale - The locale to set
36
+ */
37
+ setLocale(locale) {
38
+ this.currentLocale = locale;
39
+ this.loadTranslations();
40
+ }
41
+
42
+ /**
43
+ * Get the current locale
44
+ * @returns {string} Current locale
45
+ */
46
+ getLocale() {
47
+ return this.currentLocale;
48
+ }
49
+
50
+ /**
51
+ * Get user locale from SecureStorage
52
+ * @param {Object} secureStorage - SecureStorage instance
53
+ * @returns {string} User's preferred locale
54
+ */
55
+ async getUserLocale(secureStorage) {
56
+ try {
57
+ const userData = await secureStorage.get('user_preferences');
58
+ if (userData && userData.locale) {
59
+ return userData.locale;
60
+ }
61
+ } catch (error) {
62
+ // Ignore error and use default
63
+ }
64
+ return this.fallbackLocale;
65
+ }
66
+
67
+ /**
68
+ * Save user locale to SecureStorage
69
+ * @param {Object} secureStorage - SecureStorage instance
70
+ * @param {string} locale - Locale to save
71
+ */
72
+ async saveUserLocale(secureStorage, locale) {
73
+ try {
74
+ let userData = await secureStorage.get('user_preferences') || {};
75
+ userData.locale = locale;
76
+ await secureStorage.store('user_preferences', userData);
77
+ } catch (error) {
78
+ // Silently fail if locale preference cannot be saved
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Get nested property from object using dot notation
84
+ * @param {Object} obj - Object to search in
85
+ * @param {string} path - Dot notation path
86
+ * @returns {*} Value at path or undefined
87
+ */
88
+ getNestedProperty(obj, path) {
89
+ return path.split('.').reduce((current, key) => current && current[key], obj);
90
+ }
91
+
92
+ /**
93
+ * Get translated text
94
+ * @param {string} key - Translation key in dot notation (e.g., 'commands.login.title')
95
+ * @param {Object|...any} params - Parameters for string formatting (object for named placeholders, or legacy positional args)
96
+ * @returns {string} Translated text
97
+ */
98
+ t(key, params, ...legacyArgs) {
99
+ const translation = this.getNestedProperty(this.translations, key);
100
+
101
+ if (!translation) {
102
+ // Return the key itself as fallback if translation is missing
103
+ return key;
104
+ }
105
+
106
+ // Handle string formatting
107
+ if (params !== undefined) {
108
+ // Check if first parameter is an object (named placeholders)
109
+ if (typeof params === 'object' && params !== null && !Array.isArray(params)) {
110
+ return this.formatStringNamed(translation, params);
111
+ } else {
112
+ // Legacy positional arguments support
113
+ const allArgs = [params, ...legacyArgs];
114
+ return this.formatString(translation, ...allArgs);
115
+ }
116
+ }
117
+
118
+ return translation;
119
+ }
120
+
121
+ /**
122
+ * Format string with named placeholders
123
+ * @param {string} str - String with {name} placeholders
124
+ * @param {Object} params - Object with parameter values
125
+ * @returns {string} Formatted string
126
+ */
127
+ formatStringNamed(str, params) {
128
+ return str.replace(/\{(\w+)\}/g, (match, key) => {
129
+ const value = params[key];
130
+ return value !== undefined ? String(value) : match;
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Format string with positional arguments (legacy support)
136
+ * @param {string} str - String with %s placeholders
137
+ * @param {...any} args - Arguments to replace placeholders
138
+ * @returns {string} Formatted string
139
+ */
140
+ formatString(str, ...args) {
141
+ let index = 0;
142
+ return str.replace(/%s/g, () => {
143
+ const arg = args[index++];
144
+ return arg !== undefined ? String(arg) : '%s';
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Get colored text using chalk
150
+ * @param {string} key - Translation key
151
+ * @param {string} color - Chalk color name
152
+ * @param {Object|...any} params - Parameters for string formatting
153
+ * @returns {string} Colored translated text
154
+ */
155
+ tc(key, color, params, ...legacyArgs) {
156
+ const text = this.t(key, params, ...legacyArgs);
157
+ console.log(chalk[color] ? chalk[color](text) : text);
158
+ }
159
+
160
+ /**
161
+ * Get common icons/emojis
162
+ * @param {string} iconKey - Icon key from common section
163
+ * @returns {string} Icon/emoji
164
+ */
165
+ icon(iconKey) {
166
+ return this.t(`common.${iconKey}`) || iconKey;
167
+ }
168
+
169
+ /**
170
+ * Helper methods for common colored output
171
+ */
172
+ success(key, params, ...legacyArgs) {
173
+ return this.tc(key, 'green', params, ...legacyArgs);
174
+ }
175
+
176
+ error(key, params, ...legacyArgs) {
177
+ return this.tc(key, 'red', params, ...legacyArgs);
178
+ }
179
+
180
+ warning(key, params, ...legacyArgs) {
181
+ return this.tc(key, 'yellow', params, ...legacyArgs);
182
+ }
183
+
184
+ info(key, params, ...legacyArgs) {
185
+ return this.tc(key, 'blue', params, ...legacyArgs);
186
+ }
187
+
188
+ gray(key, params, ...legacyArgs) {
189
+ return this.tc(key, 'gray', params, ...legacyArgs);
190
+ }
191
+
192
+ /**
193
+ * Get available locales
194
+ * @returns {string[]} Array of available locale codes
195
+ */
196
+ getAvailableLocales() {
197
+ // In a real implementation, this would scan the locales directory
198
+ return ['en']; // For now, only English is available
199
+ }
200
+ }
201
+
202
+ // Create singleton instance
203
+ const i18n = new I18n();
204
+
205
+ module.exports = { I18n, i18n };