zoho-sites-dev-cli 0.0.0-stage → 1.0.1

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 (53) hide show
  1. package/README.md +396 -2
  2. package/bin/zoho-sites-dev-cli.js +108 -0
  3. package/config/default.json +26 -0
  4. package/index.js +6 -0
  5. package/package.json +55 -4
  6. package/src/commands/auth.js +125 -0
  7. package/src/commands/create.js +175 -0
  8. package/src/commands/deploy.js +409 -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 +449 -0
  13. package/src/commands/install.js +90 -0
  14. package/src/commands/login.js +253 -0
  15. package/src/commands/pull.js +41 -0
  16. package/src/commands/serve.js +163 -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 +164 -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 +54 -0
  29. package/src/locales/en.json +216 -0
  30. package/src/services/devServer.js +583 -0
  31. package/src/services/oauthService.js +796 -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/cliName.js +35 -0
  46. package/src/utils/configUtil.js +67 -0
  47. package/src/utils/httpUtil.js +351 -0
  48. package/src/utils/i18n.js +222 -0
  49. package/src/utils/loadingUtil.js +190 -0
  50. package/src/utils/secureConfig.js +75 -0
  51. package/src/utils/secureStorage.js +230 -0
  52. package/src/utils/templateLoader.js +89 -0
  53. package/src/utils/urlUtil.js +372 -0
@@ -0,0 +1,125 @@
1
+ const SecureStorage = require('../utils/secureStorage.js');
2
+ const OAuthService = require('../services/oauthService.js');
3
+ const {i18n} = require('../utils/i18n.js');
4
+ const chalk = require('chalk');
5
+
6
+ // Logout command
7
+ async function logout() {
8
+ const storage = new SecureStorage();
9
+
10
+ try {
11
+ const isLoggedIn = await storage.isLoggedIn();
12
+
13
+ if (!isLoggedIn) {
14
+ i18n.warning('commands.auth.notLoggedIn');
15
+ return;
16
+ }
17
+
18
+ const currentUser = await storage.getCurrentUser();
19
+ const success = await storage.clearAuthData();
20
+
21
+ if (success) {
22
+ i18n.success('commands.auth.logoutSuccess', { name: currentUser.user_name });
23
+ } else {
24
+ i18n.error('commands.auth.logoutFailed');
25
+ }
26
+ } catch (error) {
27
+ i18n.error('commands.auth.logoutFailed', { error: error.message });
28
+ }
29
+ }
30
+
31
+ // Who am I command - show current user info
32
+ async function whoami() {
33
+ const oauthService = new OAuthService();
34
+
35
+ try {
36
+ const authData = await oauthService.getValidAuthData();
37
+
38
+ if (!authData || !authData.access_token) {
39
+ i18n.warning('commands.auth.notLoggedIn');
40
+ i18n.info('commands.auth.loginToAuthenticate');
41
+ return;
42
+ }
43
+
44
+ if (!authData) {
45
+ i18n.error('commands.auth.authenticationDataNotFound');
46
+ return;
47
+ }
48
+
49
+ i18n.info('commands.auth.currentUserInformation');
50
+ i18n.success('commands.auth.name', { name: authData.user_name });
51
+ i18n.success('commands.auth.email', { email: authData.email });
52
+ i18n.success('commands.auth.environment', { environment: authData.environment });
53
+
54
+ if (authData.organization) {
55
+ i18n.success('commands.auth.organization', { organization: authData.organization });
56
+ }
57
+
58
+ if (authData.api_domain) {
59
+ i18n.info('commands.auth.apiDomain', { apiDomain: authData.api_domain });
60
+ }
61
+
62
+ if (authData.user_id) {
63
+ i18n.gray('commands.auth.userId', { userId: authData.user_id });
64
+ }
65
+
66
+ if (authData.permissions) {
67
+ i18n.info('commands.auth.permissions', { permissions: authData.permissions.join(', ') });
68
+ }
69
+
70
+ if (authData.last_login) {
71
+ i18n.gray('commands.auth.lastLogin', { lastLogin: new Date(authData.last_login).toLocaleString() });
72
+ }
73
+
74
+ if (authData.expires_at) {
75
+ const expiresAt = new Date(authData.expires_at);
76
+ const now = new Date();
77
+ if (expiresAt - now <= 0) {
78
+ i18n.error('commands.auth.tokenExpired');
79
+ i18n.info('commands.auth.loginToReauthenticate');
80
+ }
81
+ }
82
+
83
+ } catch (error) {
84
+ i18n.error('commands.auth.failedToGetUserInfo', { error: error.message });
85
+ }
86
+ }
87
+
88
+ // Status command - check authentication status
89
+ async function status() {
90
+ const storage = new SecureStorage();
91
+
92
+ try {
93
+ const isLoggedIn = await storage.isLoggedIn();
94
+
95
+ i18n.info('commands.auth.authenticationStatus');
96
+
97
+ if (isLoggedIn) {
98
+ const currentUser = await storage.getCurrentUser();
99
+ i18n.success('commands.auth.authenticated');
100
+ i18n.info('commands.auth.user', { user: currentUser.user_name, email: currentUser.email });
101
+ i18n.info('commands.auth.environment', { environment: currentUser.environment });
102
+
103
+ const authData = await storage.getAuthData();
104
+ if (authData.expires_at) {
105
+ const expiresAt = new Date(authData.expires_at);
106
+ const now = new Date();
107
+ const timeUntilExpiry = expiresAt - now;
108
+
109
+ if (timeUntilExpiry > 0) {
110
+ const hours = Math.floor(timeUntilExpiry / (1000 * 60 * 60));
111
+ const minutes = Math.floor((timeUntilExpiry % (1000 * 60 * 60)) / (1000 * 60));
112
+ i18n.success('commands.auth.tokenValidFor', { hours: hours, minutes: minutes });
113
+ }
114
+ }
115
+ } else {
116
+ i18n.error('commands.auth.notAuthenticated');
117
+ i18n.info('commands.auth.loginToAuthenticate');
118
+ }
119
+
120
+ } catch (error) {
121
+ i18n.error('commands.auth.failedToCheckStatus', { error: error.message });
122
+ }
123
+ }
124
+
125
+ module.exports = { logout, whoami, status };
@@ -0,0 +1,175 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { i18n } = require('../utils/i18n.js');
4
+ const { templateLoader } = require('../utils/templateLoader.js');
5
+ const { getNamespace } = require('../utils/configUtil.js');
6
+
7
+ /**
8
+ * Convert kebab-case or snake_case to camelCase (lowercase first letter)
9
+ * @param {string} input - Input string in kebab-case or snake_case
10
+ * @returns {string} - Converted string in camelCase
11
+ */
12
+ function toCamelCase(input) {
13
+ if (!input) return input;
14
+
15
+ // If input doesn't contain hyphens or underscores, keep first letter lowercase
16
+ if (!input.includes('-') && !input.includes('_')) {
17
+ return input.charAt(0).toLowerCase() + input.slice(1);
18
+ }
19
+
20
+ // Split by hyphens or underscores and capitalize each part, then lowercase first letter
21
+ const parts = input
22
+ .split(/[-_]/)
23
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
24
+
25
+ // Lowercase the first character of the first part
26
+ if (parts.length > 0) {
27
+ parts[0] = parts[0].charAt(0).toLowerCase() + parts[0].slice(1);
28
+ }
29
+
30
+ return parts.join('');
31
+ }
32
+
33
+ /**
34
+ * Create a new component with the specified name
35
+ * @param {string} componentName - Name of the component to create
36
+ */
37
+ function create(componentName) {
38
+ if (!componentName) {
39
+ i18n.error('commands.create.componentNameRequired');
40
+ return;
41
+ }
42
+
43
+ // Validate component name
44
+ if (!isValidComponentName(componentName)) {
45
+ i18n.error('commands.create.invalidComponentName', { componentName });
46
+ return;
47
+ }
48
+
49
+ try {
50
+ i18n.info('commands.create.title');
51
+ i18n.info('commands.create.creating', { componentName });
52
+
53
+ // Check if we're in a ZS project directory
54
+ const hasConfig = checkProjectConfig();
55
+ if (!hasConfig) {
56
+ i18n.error('commands.create.noConfigFound');
57
+ i18n.info('commands.create.configHint');
58
+ return;
59
+ }
60
+
61
+ // Create component directory (keep original name for directory)
62
+ const componentDir = path.join(process.cwd(), componentName);
63
+
64
+ if (fs.existsSync(componentDir)) {
65
+ i18n.error('commands.create.directoryExists', { componentName });
66
+ return;
67
+ }
68
+
69
+ // Create the component folder
70
+ fs.mkdirSync(componentDir, { recursive: true });
71
+ i18n.success('commands.create.directoryCreated', { componentName });
72
+
73
+ // Get namespace from config
74
+ const namespace = getNamespace();
75
+
76
+ const namespacedComponentName = `${namespace}_${componentName}`;
77
+
78
+ const templateData = {
79
+ componentName: componentName,
80
+ componentNameCamel: toCamelCase(componentName),
81
+ namespacedComponentName: namespacedComponentName,
82
+ namespace: namespace,
83
+ author: process.env.USER || process.env.USERNAME || 'ZS Developer',
84
+ authorEmail: process.env.EMAIL || 'developer@example.com',
85
+ createdDate: new Date().toISOString().split('T')[0]
86
+ };
87
+
88
+ // Create component files from templates
89
+ const files = [
90
+ { template: 'component/index.js', filename: 'index.js' },
91
+ { template: 'component/fields.json', filename: 'fields.json' },
92
+ { template: 'component/meta.json', filename: 'meta.json' },
93
+ { template: 'component/styles.css', filename: 'styles.css' },
94
+ { template: 'component/llm.md', filename: 'llm.md' }
95
+ ];
96
+
97
+ for (const file of files) {
98
+ const content = templateLoader.renderTemplate(file.template, templateData);
99
+ const filePath = path.join(componentDir, file.filename);
100
+
101
+ fs.writeFileSync(filePath, content, 'utf8');
102
+ i18n.success('commands.create.fileCreated', { filename: file.filename });
103
+ }
104
+
105
+ i18n.success('commands.create.componentCreated', { componentName });
106
+ i18n.info('commands.create.nextSteps', { componentName });
107
+
108
+ } catch (error) {
109
+ i18n.error('commands.create.creationFailed', { error: error.message });
110
+
111
+ // Clean up on error - remove partially created directory
112
+ const componentDir = path.join(process.cwd(), componentName);
113
+ if (fs.existsSync(componentDir)) {
114
+ try {
115
+ fs.rmSync(componentDir, { recursive: true, force: true });
116
+ i18n.info('commands.create.cleanupCompleted');
117
+ } catch (cleanupError) {
118
+ i18n.warning('commands.create.cleanupFailed', { error: cleanupError.message });
119
+ }
120
+ }
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Check if we're in a ZS project directory by looking for config files
126
+ * @returns {boolean} - True if config file exists, false otherwise
127
+ */
128
+ function checkProjectConfig() {
129
+ const configFiles = [
130
+ '.zs',
131
+ '.zs.json',
132
+ 'zs.config.js',
133
+ 'zs.config.json',
134
+ 'package.json' // Check if it's a Node.js project with ZS dependencies
135
+ ];
136
+
137
+ for (const configFile of configFiles) {
138
+ const configPath = path.join(process.cwd(), configFile);
139
+ if (fs.existsSync(configPath)) {
140
+ // If it's package.json, check if it has ZS-related dependencies
141
+ if (configFile === 'package.json') {
142
+ try {
143
+ const packageContent = fs.readFileSync(configPath, 'utf8');
144
+ const packageJson = JSON.parse(packageContent);
145
+ const hasZSDeps = packageJson.dependencies &&
146
+ (packageJson.dependencies['zs-cli'] ||
147
+ packageJson.dependencies['@zs/core'] ||
148
+ packageJson.devDependencies?.['zs-cli'] ||
149
+ packageJson.devDependencies?.['@zs/core']);
150
+ if (hasZSDeps) return true;
151
+ } catch (error) {
152
+ // Ignore parsing errors and continue checking other files
153
+ }
154
+ } else {
155
+ return true;
156
+ }
157
+ }
158
+ }
159
+
160
+ return false;
161
+ }
162
+
163
+ /**
164
+ * Validate component name
165
+ * @param {string} name - Component name to validate
166
+ * @returns {boolean} - True if valid, false otherwise
167
+ */
168
+ function isValidComponentName(name) {
169
+ // Component name should be alphanumeric with optional hyphens/underscores
170
+ // Should start with a letter, and be between 3-50 characters
171
+ const regex = /^[a-zA-Z][a-zA-Z0-9_-]{2,49}$/;
172
+ return regex.test(name);
173
+ }
174
+
175
+ module.exports = { create };
@@ -0,0 +1,409 @@
1
+ const { promises: fs } = require("fs");
2
+ const { createWriteStream, createReadStream } = require("fs");
3
+ const path = require("path");
4
+ const os = require("os");
5
+ const archiver = require("archiver");
6
+ const FormData = require("form-data");
7
+ const { i18n } = require("../utils/i18n.js");
8
+ const { POST, isAuthenticated } = require("../utils/httpUtil.js");
9
+ const { UrlUtil } = require("../utils/urlUtil.js");
10
+ const {
11
+ WEBPACK_OVERRIDES_FILE,
12
+ TAILWIND_CONFIG_FILE,
13
+ TAILWIND_CONFIG_CJS,
14
+ POSTCSS_CONFIG_FILE
15
+ } = require("../config/constants.js");
16
+ const { readProjectConfig, getNamespace } = require("../utils/configUtil.js");
17
+ const SecureStorage = require("../utils/secureStorage.js");
18
+
19
+ /**
20
+ * Create a temporary directory for deployment
21
+ * @returns {Promise<string>} Path to temp directory
22
+ */
23
+ async function createTempDir() {
24
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "zs-deploy-"));
25
+ if (typeof fs.chmod === "function") {
26
+ await fs.chmod(tempDir, 0o700);
27
+ }
28
+ return tempDir;
29
+ }
30
+
31
+ /**
32
+ * Copy components to temporary directory
33
+ * @param {string} tempDir - Path to temporary directory
34
+ * @returns {Promise<void>}
35
+ */
36
+ async function copyComponentsToTemp(tempDir) {
37
+ // Read current directory
38
+ const entries = await fs.readdir(".", { withFileTypes: true });
39
+
40
+ // Directories to exclude from deployment
41
+ const excludeDirs = [
42
+ 'node_modules',
43
+ '.git',
44
+ '.vscode',
45
+ '.idea',
46
+ 'temp',
47
+ 'dist',
48
+ 'build',
49
+ 'coverage',
50
+ '.nyc_output'
51
+ ];
52
+
53
+ // Filter for directories (potential components) - exclude common non-component dirs
54
+ const componentDirs = entries.filter(
55
+ (entry) => entry.isDirectory() &&
56
+ !entry.name.startsWith(".") &&
57
+ !excludeDirs.includes(entry.name)
58
+ );
59
+
60
+ if (componentDirs.length === 0) {
61
+ throw new Error("No components found in current directory");
62
+ }
63
+
64
+ // Copy each component directory
65
+ for (const dir of componentDirs) {
66
+ const sourcePath = path.join(".", dir.name);
67
+ const targetPath = path.join(tempDir, dir.name);
68
+
69
+ await fs.cp(sourcePath, targetPath, { recursive: true });
70
+ i18n.info("commands.deploy.copiedComponent", { name: dir.name });
71
+ }
72
+
73
+ return componentDirs.length;
74
+ }
75
+
76
+ /**
77
+ * Copy package.json to temporary directory if it exists
78
+ * @param {string} tempDir - Path to temporary directory
79
+ * @returns {Promise<boolean>} Whether the file was copied
80
+ */
81
+ async function copyPackageJsonToTemp(tempDir) {
82
+ const packageJsonPath = path.join(".", "package.json");
83
+
84
+ try {
85
+ await fs.access(packageJsonPath);
86
+ const targetPath = path.join(tempDir, "package.json");
87
+ await fs.copyFile(packageJsonPath, targetPath);
88
+ i18n.info("commands.deploy.copiedPackageJson");
89
+ return true;
90
+ } catch (error) {
91
+ // File doesn't exist, which is fine
92
+ i18n.info("commands.deploy.noPackageJson");
93
+ return false;
94
+ }
95
+ }
96
+
97
+
98
+ /**
99
+ * Copy webpack overrides file to temporary directory if it exists
100
+ * @param {string} tempDir - Path to temporary directory
101
+ * @returns {Promise<boolean>} Whether the file was copied
102
+ */
103
+ async function copyWebpackOverrides(tempDir) {
104
+ const overridesPath = path.join(".", WEBPACK_OVERRIDES_FILE);
105
+
106
+ try {
107
+ await fs.access(overridesPath);
108
+ const targetPath = path.join(tempDir, WEBPACK_OVERRIDES_FILE);
109
+ await fs.copyFile(overridesPath, targetPath);
110
+ i18n.info("commands.deploy.copiedWebpackOverrides", { file: WEBPACK_OVERRIDES_FILE });
111
+ return true;
112
+ } catch (error) {
113
+ // File doesn't exist, which is fine
114
+ i18n.info("commands.deploy.noWebpackOverrides", { file: WEBPACK_OVERRIDES_FILE });
115
+ return false;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Copy Tailwind and PostCSS config files to temporary directory if they exist
121
+ * (required for Tailwind build during server-side bundle; SDK provides tailwindcss)
122
+ * @param {string} tempDir - Path to temporary directory
123
+ */
124
+ async function copyTailwindAndPostcssConfig(tempDir) {
125
+ const configFiles = [
126
+ { src: TAILWIND_CONFIG_FILE, key: "tailwind" },
127
+ { src: TAILWIND_CONFIG_CJS, key: "tailwindCjs" },
128
+ { src: POSTCSS_CONFIG_FILE, key: "postcss" }
129
+ ];
130
+ for (const { src } of configFiles) {
131
+ const srcPath = path.join(".", src);
132
+ try {
133
+ await fs.access(srcPath);
134
+ const targetPath = path.join(tempDir, src);
135
+ await fs.copyFile(srcPath, targetPath);
136
+ i18n.info("commands.deploy.copiedConfig", { file: src });
137
+ } catch (_) {
138
+ // File doesn't exist, which is fine
139
+ }
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Create zip file from temporary directory
145
+ * @param {string} tempDir - Path to temporary directory
146
+ * @param {string} [customZipPath] - Optional path for zip file (e.g. for generate-zip)
147
+ * @returns {Promise<string>} Path to zip file
148
+ */
149
+ async function createZipFile(tempDir, customZipPath) {
150
+ const zipPath = customZipPath || path.join(tempDir, "components.zip");
151
+ const resolvedZipPath = path.resolve(zipPath);
152
+ const streamOptions = customZipPath
153
+ ? {}
154
+ : { flags: "wx", mode: 0o600 };
155
+
156
+ return new Promise((resolve, reject) => {
157
+ let settled = false;
158
+ const output = createWriteStream(zipPath, streamOptions);
159
+ const archive = archiver("zip", {
160
+ zlib: { level: 9 }, // Maximum compression
161
+ });
162
+
163
+ const fail = (err) => {
164
+ if (settled) return;
165
+ settled = true;
166
+ archive.abort();
167
+ reject(err);
168
+ };
169
+
170
+ output.on("close", () => {
171
+ if (settled) return;
172
+ settled = true;
173
+ i18n.info("commands.deploy.zipCreated", { size: archive.pointer() });
174
+ resolve(zipPath);
175
+ });
176
+
177
+ output.on("error", fail);
178
+
179
+ archive.on("error", fail);
180
+
181
+ archive.pipe(output);
182
+ // Server expects a single top-level directory in the zip (e.g. widgets/).
183
+ // Use 'widgets' so entries are widgets/assets/, widgets/event/, etc.
184
+ // Exclude the output zip itself since temporary archives live inside tempDir.
185
+ archive.directory(tempDir, "widgets", (entry) => {
186
+ if (path.resolve(tempDir, entry.name) === resolvedZipPath) {
187
+ return false;
188
+ }
189
+ return entry;
190
+ });
191
+ archive.finalize();
192
+ });
193
+ }
194
+
195
+ /**
196
+ * Get siteId from project configuration
197
+ * @returns {string|null} Site ID or null if not found
198
+ */
199
+ function getSiteIdFromConfig() {
200
+ try {
201
+ const config = readProjectConfig();
202
+ // Try siteId first, then asoid as fallback
203
+ return config.siteId || config.asoid || null;
204
+ } catch (error) {
205
+ return null;
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Upload zip file to API
211
+ * @param {string} zipPath - Path to zip file
212
+ * @param {string} environment - Environment to deploy to (csez, localzoho, usdc)
213
+ * @returns {Promise<Object>} Upload response from server
214
+ */
215
+ async function uploadComponents(zipPath, environment) {
216
+ // Get siteId from config
217
+ const siteId = getSiteIdFromConfig();
218
+ if (!siteId) {
219
+ throw new Error("Site ID not found in project configuration. Please ensure your .zs file contains siteId or asoid.");
220
+ }
221
+
222
+ // Get namespace from config
223
+ const namespace = getNamespace();
224
+ if (!namespace) {
225
+ throw new Error("Namespace not found in project configuration. Please ensure your .zs file contains namespace.");
226
+ }
227
+
228
+ // Validate environment
229
+ if (!UrlUtil.isValidEnvironment(environment)) {
230
+ throw new Error(`Invalid environment: ${environment}. Valid options are: ${UrlUtil.getValidEnvironmentIds().join(", ")}`);
231
+ }
232
+
233
+ // Get site (DC) domain URL — use async resolution so DEV (user-provided URL) works
234
+ const baseUrl = await UrlUtil.resolveSiteDomain(environment);
235
+ const endpoint = UrlUtil.getApiEndpoint("WIDGETS.UPLOAD");
236
+ const url = `${baseUrl}/${endpoint}?namespace=${encodeURIComponent(namespace)}`;
237
+
238
+ i18n.info("commands.deploy.deployingToEnvironment", { environment, siteId });
239
+
240
+ // Create FormData and append zip file
241
+ const formData = new FormData();
242
+ formData.append("widgets", createReadStream(zipPath), {
243
+ filename: "widgets.zip",
244
+ contentType: "application/zip",
245
+ });
246
+
247
+ // Upload and capture response
248
+ const response = await POST(url, formData, {
249
+ // Don't set Content-Type header - let form-data set it with boundary
250
+ // Large uploads can take time; extend timeout and allow large bodies
251
+ timeout: 15 * 60 * 1000, // 15 minutes
252
+ maxContentLength: Infinity,
253
+ maxBodyLength: Infinity,
254
+ headers: {
255
+ "Content-Type": "multipart/form-data",
256
+ },
257
+ }, i18n.t('commands.deploy.uploading'));
258
+
259
+ return response;
260
+ }
261
+
262
+ /**
263
+ * Get environment from various sources with priority
264
+ * @param {string} providedEnvironment - Environment provided via CLI option
265
+ * @returns {Promise<string>} Environment to use
266
+ */
267
+ async function getDeploymentEnvironment(providedEnvironment) {
268
+ // Priority 1: Environment provided via CLI option
269
+ if (providedEnvironment) {
270
+ if (!UrlUtil.isValidEnvironment(providedEnvironment)) {
271
+ throw new Error(`Invalid environment: ${providedEnvironment}. Valid options are: ${UrlUtil.getValidEnvironmentIds().join(", ")}`);
272
+ }
273
+ return providedEnvironment;
274
+ }
275
+
276
+ // Priority 2: Environment from .zs config file
277
+ try {
278
+ const config = readProjectConfig();
279
+ if (config.environment && UrlUtil.isValidEnvironment(config.environment)) {
280
+ return config.environment;
281
+ }
282
+ } catch (error) {
283
+ // Config file might not exist or might not have environment
284
+ }
285
+
286
+ // Priority 3: Environment from SecureStorage (auth data)
287
+ const environment = await UrlUtil.getEnvironment();
288
+ if (environment) {
289
+ return environment;
290
+ }
291
+
292
+ // Default: throw error if no environment found
293
+ throw new Error("No environment specified. Please provide an environment using --env option, or ensure your .zs file contains an environment field, or login with an environment.");
294
+ }
295
+
296
+ /**
297
+ * Cleanup temporary files
298
+ * @param {string} tempDir - Temporary directory path
299
+ * @param {string} zipPath - Zip file path
300
+ */
301
+ async function cleanup(tempDir, zipPath) {
302
+ try {
303
+ // Remove zip file first (it normally lives inside tempDir)
304
+ if (zipPath) {
305
+ try {
306
+ await fs.unlink(zipPath);
307
+ } catch (err) {
308
+ if (err.code !== "ENOENT") {
309
+ throw err;
310
+ }
311
+ }
312
+ }
313
+
314
+ // Remove temp directory
315
+ if (tempDir) {
316
+ await fs.rm(tempDir, { recursive: true, force: true });
317
+ }
318
+
319
+ i18n.info("commands.deploy.cleanupComplete");
320
+ } catch (error) {
321
+ i18n.warning("commands.deploy.cleanupFailed", { error: error.message });
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Main deploy command function
327
+ * @param {Object} options - Command options
328
+ * @param {string} options.env - Environment to deploy to (csez, localzoho, usdc)
329
+ */
330
+ async function deploy(options = {}) {
331
+ let tempDir = null;
332
+ let zipPath = null;
333
+
334
+ try {
335
+ // Check if user is authenticated
336
+ const authenticated = await isAuthenticated();
337
+ if (!authenticated) {
338
+ i18n.error("commands.deploy.notAuthenticated");
339
+ i18n.info("commands.deploy.pleaseLogin");
340
+ return;
341
+ }
342
+
343
+ i18n.info("commands.deploy.starting");
344
+
345
+ // Get deployment environment
346
+ const environment = await getDeploymentEnvironment(options.env);
347
+ i18n.info("commands.deploy.usingEnvironment", { environment });
348
+
349
+ // Create temp directory
350
+ tempDir = await createTempDir();
351
+ i18n.info("commands.deploy.tempDirCreated");
352
+
353
+ // Copy components
354
+ const componentCount = await copyComponentsToTemp(tempDir);
355
+ i18n.success("commands.deploy.componentsCopied", { count: componentCount });
356
+
357
+ // Copy package.json if it exists
358
+ await copyPackageJsonToTemp(tempDir);
359
+
360
+ // Copy webpack overrides file if it exists
361
+ await copyWebpackOverrides(tempDir);
362
+
363
+ // Copy Tailwind and PostCSS config if present (for Tailwind build on server)
364
+ await copyTailwindAndPostcssConfig(tempDir);
365
+
366
+ // Create zip file
367
+ zipPath = await createZipFile(tempDir);
368
+
369
+ // Upload components
370
+ i18n.info("commands.deploy.uploading");
371
+ const uploadResponse = await uploadComponents(zipPath, environment);
372
+
373
+ // Check if upload was successful
374
+ if (uploadResponse) {
375
+ i18n.success("commands.deploy.uploadComplete");
376
+ } else {
377
+ i18n.warning("commands.deploy.uploadNoResponse");
378
+ }
379
+ } catch (error) {
380
+ i18n.error("commands.deploy.error", { error: error.message });
381
+
382
+ if (error.response?.status === 401) {
383
+ i18n.info("commands.deploy.authenticationRequired");
384
+ } else if (error.response?.status === 403) {
385
+ i18n.info("commands.deploy.permissionDenied");
386
+ }
387
+ } finally {
388
+ // Always cleanup temp files
389
+ await cleanup(tempDir, zipPath);
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Build deployment zip (same contents as deploy). Used by deploy and generate-zip.
395
+ * @param {Object} [options] - Options
396
+ * @param {string} [options.outputZipPath] - If set, write zip to this path (for generate-zip)
397
+ * @returns {Promise<{ tempDir: string, zipPath: string }>}
398
+ */
399
+ async function buildDeployZip(options = {}) {
400
+ const tempDir = await createTempDir();
401
+ await copyComponentsToTemp(tempDir);
402
+ await copyPackageJsonToTemp(tempDir);
403
+ await copyWebpackOverrides(tempDir);
404
+ await copyTailwindAndPostcssConfig(tempDir);
405
+ const zipPath = await createZipFile(tempDir, options.outputZipPath);
406
+ return { tempDir, zipPath };
407
+ }
408
+
409
+ module.exports = { deploy, buildDeployZip, createTempDir, copyComponentsToTemp, copyPackageJsonToTemp, copyWebpackOverrides, copyTailwindAndPostcssConfig, createZipFile, cleanup };