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,253 @@
1
+ const inquirer = require('inquirer');
2
+ const SecureStorage = require('../utils/secureStorage.js');
3
+ const OAuthService = require('../services/oauthService.js');
4
+ const { i18n } = require('../utils/i18n.js');
5
+ const { UrlUtil, PROMPT_MODES } = require('../utils/urlUtil.js');
6
+ const chalk = require('chalk');
7
+
8
+ const environments = UrlUtil.getEnvironmentOptions();
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Step helpers
12
+ // ---------------------------------------------------------------------------
13
+
14
+ async function checkExistingLogin(storage) {
15
+ const isLoggedIn = await storage.isLoggedIn();
16
+ if (!isLoggedIn) return true;
17
+
18
+ const currentUser = await storage.getCurrentUser();
19
+ i18n.warning('commands.login.alreadyLoggedIn', {
20
+ name: currentUser.user_name,
21
+ email: currentUser.email
22
+ });
23
+ i18n.info('commands.login.environment', { environment: currentUser.environment });
24
+
25
+ const { shouldContinue } = await inquirer.prompt([
26
+ {
27
+ type: 'confirm',
28
+ name: 'shouldContinue',
29
+ message: i18n.t('commands.login.alreadyLoggedIn', {
30
+ name: currentUser.user_name,
31
+ email: currentUser.email
32
+ }),
33
+ default: false
34
+ }
35
+ ]);
36
+
37
+ if (!shouldContinue) return false;
38
+
39
+ await storage.clearAuthData();
40
+ i18n.success('commands.login.logoutSuccess');
41
+ return true;
42
+ }
43
+
44
+ /**
45
+ * Prompt user to pick an environment.
46
+ * Depending on the selected environment's `promptMode`, ask for any
47
+ * additional host URLs that are not fixed for the current build audience
48
+ * (Dev 1 / sdk only — Dev 2 / internal and Dev 3 / public never prompt).
49
+ * @returns {{ environmentName: string, authUrl: string, devSiteUrl: string|null, devSiteBuilderUrl: string|null, promptMode: string }}
50
+ */
51
+ async function selectEnvironment() {
52
+ const { environment } = await inquirer.prompt([
53
+ {
54
+ type: 'list',
55
+ name: 'environment',
56
+ message: 'Select your environment:',
57
+ choices: environments.map(env => ({ name: env.name, value: env.value })),
58
+ pageSize: 5
59
+ }
60
+ ]);
61
+
62
+ const selected = environments.find(env => env.value === environment);
63
+ const authUrl = selected.url;
64
+ let devSiteUrl = null;
65
+ let devSiteBuilderUrl = null;
66
+
67
+ // --DEV1-ONLY-PROMPTS-START-- (stripped from the public/release build; see scripts/prepare-dist-package.js)
68
+ if (selected.promptMode === PROMPT_MODES.CSEZ) {
69
+ // Csez (Dev 1 only): auth + site builder are fixed; ask for the host domain.
70
+ const { hostDomainUrl } = await inquirer.prompt([
71
+ {
72
+ type: 'input',
73
+ name: 'hostDomainUrl',
74
+ message: 'Enter your host domain URL (e.g. https://yourhost.csez.zohocorpin.com:8443):',
75
+ default: 'https://yourhost.csez.zohocorpin.com:8443',
76
+ validate: (v) => {
77
+ const trimmed = (v || '').trim();
78
+ if (!trimmed) return 'Host domain URL cannot be empty.';
79
+ try { new URL(trimmed); return true; } catch (_) { return 'Please enter a valid URL.'; }
80
+ },
81
+ filter: (v) => (v || '').trim().replace(/\/$/, '') || 'https://yourhost.csez.zohocorpin.com:8443',
82
+ },
83
+ ]);
84
+ devSiteUrl = hostDomainUrl;
85
+ } else if (selected.promptMode === PROMPT_MODES.LOCALZOHO) {
86
+ // Localzoho (Dev 1 only): auth is fixed; ask for site builder + sites grid URLs.
87
+ const devAnswers = await inquirer.prompt([
88
+ {
89
+ type: 'input',
90
+ name: 'devSiteBuilderUrl',
91
+ message: 'Enter the Site builder url (e.g. https://{siteId}-builder.integv3.localzohositescontent.com/):',
92
+ default: 'https://{siteId}-builder.integv3.localzohositescontent.com/',
93
+ validate: (v) => {
94
+ const trimmed = (v || '').trim();
95
+ if (!trimmed) return 'Site builder URL cannot be empty.';
96
+ try { new URL(trimmed.replace('{siteId}', 'placeholder')); return true; } catch (_) { return 'Please enter a valid URL.'; }
97
+ },
98
+ filter: (v) => (v || '').trim().replace(/\/$/, ''),
99
+ },
100
+ {
101
+ type: 'input',
102
+ name: 'devSiteUrl',
103
+ message: 'Enter the Sites grid url (e.g. https://sites.localzoho.com):',
104
+ default: 'https://sites.localzoho.com',
105
+ validate: (v) => {
106
+ const trimmed = (v || '').trim();
107
+ if (!trimmed) return 'Sites grid URL cannot be empty.';
108
+ try { new URL(trimmed); return true; } catch (_) { return 'Please enter a valid URL.'; }
109
+ },
110
+ filter: (v) => (v || '').trim().replace(/\/$/, '') || 'https://sites.localzoho.com',
111
+ },
112
+ ]);
113
+ devSiteUrl = devAnswers.devSiteUrl;
114
+ devSiteBuilderUrl = devAnswers.devSiteBuilderUrl || null;
115
+ }
116
+ // --DEV1-ONLY-PROMPTS-END--
117
+ // promptMode 'none' -> environment is fully fixed, nothing to ask.
118
+
119
+ i18n.success('commands.login.selectedEnvironment', { environment });
120
+
121
+ return { environmentName: environment, authUrl, devSiteUrl, devSiteBuilderUrl, promptMode: selected.promptMode };
122
+ }
123
+
124
+ async function performOAuthAuthentication(authUrl, environmentName) {
125
+ const oauthService = new OAuthService();
126
+ i18n.info('commands.login.startingAuth');
127
+
128
+ try {
129
+ // Bind the environment-specific OAuth client before opening the browser.
130
+ oauthService.setClientForEnvironment(environmentName);
131
+ const { tokenData, userProfile } = await oauthService.completeAuthentication(authUrl);
132
+ return { tokenData, userProfile, oauthService };
133
+ } catch (oauthError) {
134
+ try { await oauthService.stopServer(); } catch (_) {}
135
+ throw oauthError;
136
+ }
137
+ }
138
+
139
+ function prepareAuthData(tokenData, userProfile, environmentName, authUrl, devSiteUrl, devSiteBuilderUrl, promptMode, oauthService) {
140
+ const expiresIn = tokenData.expires_in || 3600;
141
+ const expiresAt = new Date(Date.now() + expiresIn * 1000).toISOString();
142
+
143
+ return {
144
+ // OAuth tokens
145
+ access_token: tokenData.access_token,
146
+ refresh_token: tokenData.refresh_token,
147
+ token_type: tokenData.token_type || 'Bearer',
148
+ expires_in: tokenData.expires_in,
149
+ expires_at: expiresAt,
150
+ api_domain: tokenData.api_domain || authUrl,
151
+ scope: tokenData.scope || oauthService.scope,
152
+
153
+ // User profile
154
+ user_name: userProfile.Display_Name || userProfile.first_name || userProfile.email?.split('@')[0] || 'User',
155
+ email: userProfile.Email || userProfile.email,
156
+ first_name: userProfile.First_Name || userProfile.first_name,
157
+ last_name: userProfile.Last_Name || userProfile.last_name,
158
+ user_id: userProfile.ZUID || userProfile.id,
159
+ environment: environmentName,
160
+
161
+ // Additional metadata
162
+ timezone: userProfile.Time_Zone,
163
+ locale: userProfile.Locale,
164
+ country: userProfile.Country,
165
+ profile_photo: userProfile.Profile_Photo,
166
+ client_id: tokenData.client_id || oauthService.clientId,
167
+
168
+ // Dev-1-only URL overrides (undefined when promptMode is 'none', omitted by storeAuthData)
169
+ ...(promptMode !== PROMPT_MODES.NONE && {
170
+ dev_auth_url: authUrl,
171
+ dev_site_url: devSiteUrl,
172
+ dev_site_builder_url: devSiteBuilderUrl,
173
+ }),
174
+ };
175
+ }
176
+
177
+ async function storeAndDisplayResults(storage, authData, oauthService) {
178
+ const stored = await storage.storeAuthData(authData);
179
+ if (!stored) {
180
+ i18n.error('commands.login.failedToStore');
181
+ throw new Error('Failed to store authentication data locally');
182
+ }
183
+
184
+ i18n.success('commands.login.loginSuccess');
185
+ i18n.info('commands.login.welcomeUser', { name: authData.user_name });
186
+
187
+ displayUserInfo(authData);
188
+ i18n.gray('commands.login.youCanNowUseTheZSCommandLineInterface');
189
+
190
+ if (oauthService) await oauthService.stopServer();
191
+ return true;
192
+ }
193
+
194
+ function displayUserInfo(authData) {
195
+ i18n.gray('commands.login.email', { email: authData.email });
196
+ i18n.gray('commands.login.environment', { environment: authData.environment });
197
+
198
+ if (authData.dev_site_url || authData.dev_site_builder_url) {
199
+ if (authData.dev_site_url) i18n.gray('commands.login.apiDomain', { apiDomain: authData.dev_site_url });
200
+ if (authData.dev_site_builder_url) i18n.gray('commands.login.apiDomain', { apiDomain: authData.dev_site_builder_url });
201
+ } else if (authData.api_domain) {
202
+ i18n.gray('commands.login.apiDomain', { apiDomain: authData.api_domain });
203
+ }
204
+ }
205
+
206
+ function handleLoginError(error) {
207
+ i18n.error('commands.login.authError', { error: error.message });
208
+ process.exit(1);
209
+ }
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // Main entry point
213
+ // ---------------------------------------------------------------------------
214
+
215
+ async function login() {
216
+ const storage = new SecureStorage();
217
+
218
+ try {
219
+ // 1. Check existing login
220
+ const shouldContinue = await checkExistingLogin(storage);
221
+ if (!shouldContinue) return;
222
+
223
+ // 2. Welcome
224
+ i18n.info('commands.login.welcome');
225
+
226
+ // 3. Environment selection (+ Dev 1 URL prompts if needed)
227
+ const { environmentName, authUrl, devSiteUrl, devSiteBuilderUrl, promptMode } = await selectEnvironment();
228
+
229
+ // 4. OAuth authentication (uses oauth.clients.<environment> credentials)
230
+ const { tokenData, userProfile, oauthService } = await performOAuthAuthentication(
231
+ authUrl,
232
+ environmentName
233
+ );
234
+
235
+ // 5. Prepare auth data
236
+ const authData = prepareAuthData(
237
+ tokenData, userProfile,
238
+ environmentName, authUrl,
239
+ devSiteUrl, devSiteBuilderUrl,
240
+ promptMode,
241
+ oauthService
242
+ );
243
+
244
+ // 6. Persist and display
245
+ await storeAndDisplayResults(storage, authData, oauthService);
246
+
247
+ process.exit(0);
248
+ } catch (error) {
249
+ handleLoginError(error);
250
+ }
251
+ }
252
+
253
+ module.exports = { login };
@@ -0,0 +1,41 @@
1
+ const { i18n } = require('../utils/i18n.js');
2
+ const { GET, isAuthenticated } = require('../utils/httpUtil.js');
3
+ const { UrlUtil } = require('../utils/urlUtil.js');
4
+
5
+ async function pull() {
6
+ i18n.info('commands.pull.title');
7
+ i18n.info('commands.pull.description');
8
+
9
+ try {
10
+ // Check if user is authenticated
11
+ const authenticated = await isAuthenticated();
12
+ if (!authenticated) {
13
+ i18n.error('commands.pull.notAuthenticated');
14
+ i18n.info('commands.pull.pleaseLogin');
15
+ return;
16
+ }
17
+
18
+ // Fetch components list with loading message
19
+ const response = await GET(
20
+ UrlUtil.getSiteBuilderUrl('WIDGETS.LIST'),
21
+ {},
22
+ i18n.t('commands.login.fetchingComponents')
23
+ );
24
+
25
+ // Display success message
26
+ i18n.success('commands.pull.fetchSuccess');
27
+
28
+ } catch (error) {
29
+ i18n.error('commands.pull.fetchError', { error: error.message });
30
+
31
+ if (error.response?.status === 401) {
32
+ i18n.info('commands.pull.authenticationRequired');
33
+ } else if (error.response?.status === 403) {
34
+ i18n.info('commands.pull.permissionDenied');
35
+ } else if (error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED') {
36
+ i18n.info('commands.pull.connectionError');
37
+ }
38
+ }
39
+ }
40
+
41
+ module.exports = { pull };
@@ -0,0 +1,163 @@
1
+ const path = require('path');
2
+ const fs = require('fs');
3
+ const open = require('open');
4
+ const { i18n } = require('../utils/i18n.js');
5
+ const { createWebpackDevServerConfig } = require('../services/devServer.js');
6
+ const { SERVER_CONFIG } = require('../config/constants.js');
7
+ const { UrlUtil } = require('../utils/urlUtil.js');
8
+ const SecureStorage = require('../utils/secureStorage.js');
9
+ const { readProjectConfig } = require('../utils/configUtil.js');
10
+ const { getCliName } = require('../utils/cliName.js');
11
+
12
+ // Load compilers
13
+ const compilerPath = path.resolve(__dirname, '../compilers');
14
+ const cssCompilerPath = path.join(compilerPath, 'css-compiler.js');
15
+
16
+ if (fs.existsSync(cssCompilerPath)) {
17
+ require(cssCompilerPath);
18
+ }
19
+
20
+ /**
21
+ * Check if we're in a ZS project directory
22
+ */
23
+ function isZsProject() {
24
+ return fs.existsSync('.zs');
25
+ }
26
+
27
+ /**
28
+ * Get defaultSiteId from config
29
+ * Supports multiple formats: defaultSiteId, defaultSite.id, or defaultSite (if it's a string)
30
+ */
31
+ function getDefaultSiteId(config) {
32
+ // Check for direct defaultSiteId field
33
+ if (config.defaultSiteId) {
34
+ return config.defaultSiteId;
35
+ }
36
+
37
+ // Check if defaultSite is an object with id property
38
+ if (config.defaultSite && typeof config.defaultSite === 'object' && config.defaultSite.id) {
39
+ return config.defaultSite.id;
40
+ }
41
+
42
+ // Check if defaultSite is a string (the ID itself)
43
+ if (config.defaultSite && typeof config.defaultSite === 'string') {
44
+ return config.defaultSite;
45
+ }
46
+
47
+ // Fallback to siteId or asoid (new app-based .zs uses asoid)
48
+ if (config.siteId) {
49
+ return config.siteId;
50
+ }
51
+ if (config.asoid) {
52
+ return config.asoid;
53
+ }
54
+
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Get environment from config or SecureStorage
60
+ */
61
+ async function getEnvironment(config) {
62
+ // First try to get from config
63
+ if (config.environment) {
64
+ return config.environment;
65
+ }
66
+
67
+ // Fallback to SecureStorage
68
+ try {
69
+ const environment = await SecureStorage.getEnvironment();
70
+ if (environment) {
71
+ return environment;
72
+ }
73
+ } catch (error) {
74
+ // Ignore errors, will throw below
75
+ }
76
+
77
+ throw new Error(`Environment not found in config. Please run "${getCliName()} init" or "${getCliName()} login" to set up the environment.`);
78
+ }
79
+
80
+ /**
81
+ * Start webpack development server
82
+ */
83
+ async function startWebpackDevServer(config, shouldOpenBrowser = true) {
84
+ const PORT = process.env.PORT || SERVER_CONFIG.HTTP_PORT;
85
+ const devServer = createWebpackDevServerConfig(PORT);
86
+
87
+ i18n.info('commands.serve.webpackServerReady', { port: PORT });
88
+ i18n.info('commands.serve.fileWatchingEnabled');
89
+
90
+ // Get defaultSiteId from config
91
+ const defaultSiteId = getDefaultSiteId(config);
92
+ if (!defaultSiteId) {
93
+ throw new Error(`defaultSiteId, siteId, or asoid not found in .zs file. Please ensure your project is properly initialized with '${getCliName()} init'.`);
94
+ }
95
+
96
+ // Get environment from config or SecureStorage
97
+ const environment = await getEnvironment(config);
98
+
99
+ // Get namespace from config
100
+ const namespace = config.namespace;
101
+ if (!namespace) {
102
+ throw new Error('namespace not found in .zs file. Please ensure your project is properly initialized.');
103
+ }
104
+
105
+ // Build site builder URL based on environment
106
+ const siteBuilderDomain = await UrlUtil.resolveSiteBuilderDomain(defaultSiteId, environment);
107
+ const developmentUrl = `${siteBuilderDomain}/zcms/editor/home?isAppBuildMode=true`;
108
+
109
+ if (shouldOpenBrowser) {
110
+ i18n.info('commands.serve.openingDevelopmentUrl', { url: developmentUrl });
111
+ i18n.info('commands.serve.localServerInfo', { port: PORT });
112
+
113
+ try {
114
+ await open(developmentUrl);
115
+ } catch (error) {
116
+ i18n.info('commands.serve.pleaseVisitUrl', { url: developmentUrl });
117
+ }
118
+ } else {
119
+ i18n.info('commands.serve.developmentUrl', { url: developmentUrl });
120
+ i18n.info('commands.serve.localServerInfo', { port: PORT });
121
+ i18n.info('commands.serve.browserNotAutoOpen');
122
+ }
123
+
124
+ return { devServer };
125
+ }
126
+
127
+ /**
128
+ * Main serve command function
129
+ */
130
+ async function serve(options = {}) {
131
+ try {
132
+ // Check if we're in a ZS project
133
+ if (!isZsProject()) {
134
+ i18n.error('commands.serve.notInProject');
135
+ process.exit(1);
136
+ }
137
+
138
+ // Get project configuration (validates namespace / namespaceId)
139
+ const config = readProjectConfig();
140
+ i18n.info('commands.serve.startingServer', { siteName: config.name || 'project' });
141
+
142
+ // Start webpack dev server with browser opening preference
143
+ const shouldOpenBrowser = options.open !== false; // Default to true unless --no-open is used
144
+ const { devServer } = await startWebpackDevServer(config, shouldOpenBrowser);
145
+
146
+ // Handle graceful shutdown
147
+ const shutdown = () => {
148
+ i18n.info('commands.serve.shuttingDownServer');
149
+ devServer.cleanup();
150
+ i18n.success('commands.serve.serverStoppedSuccess');
151
+ process.exit(0);
152
+ };
153
+
154
+ process.on('SIGINT', shutdown);
155
+ process.on('SIGTERM', shutdown);
156
+
157
+ } catch (error) {
158
+ i18n.error('commands.serve.error', { error: error.message });
159
+ process.exit(1);
160
+ }
161
+ }
162
+
163
+ module.exports = { serve };
@@ -0,0 +1,230 @@
1
+ // css-compiler.js - Modern CSS Processing with PostCSS
2
+
3
+ // Load PostCSS and plugins
4
+ const fs = require("fs");
5
+ const postcss = require("postcss");
6
+ const cssnano = require("cssnano");
7
+ const postcssNested = require("postcss-nested");
8
+ const postcssPrefixSelector = require("postcss-prefix-selector");
9
+ const postcssPrefixKeyframe = require("postcss-prefix-keyframe");
10
+ const { createRootSelectorTransformPlugin } = require("./plugins/index.js");
11
+
12
+ /**
13
+ * Custom PostCSS plugin to detect and throw errors for global selectors
14
+ */
15
+ const globalSelectorDetector = () => {
16
+ return {
17
+ postcssPlugin: "global-selector-detector",
18
+ Rule(rule) {
19
+ // Skip @rules (media queries, keyframes, etc.)
20
+ if (rule.parent && rule.parent.type === "atrule") {
21
+ return;
22
+ }
23
+
24
+ // Skip root-level @rules
25
+ if (rule.selector && rule.selector.startsWith("@")) {
26
+ return;
27
+ }
28
+
29
+ // Check for global selectors that should not be allowed (excluding :root)
30
+ const globalSelectors = ["html", "body", "*"];
31
+ const selectors = rule.selector.split(",").map((s) => s.trim());
32
+
33
+ for (const selector of selectors) {
34
+ // Check for exact matches
35
+ if (globalSelectors.includes(selector)) {
36
+ throw new Error(
37
+ `Global selector '${selector}' is not allowed. Use component-specific selectors only.`
38
+ );
39
+ }
40
+
41
+ // Check for selectors that start with global elements
42
+ for (const global of globalSelectors) {
43
+ if (
44
+ selector.startsWith(`${global} `) ||
45
+ selector.startsWith(`${global}.`) ||
46
+ selector.startsWith(`${global}#`)
47
+ ) {
48
+ throw new Error(
49
+ `Global selector '${selector}' is not allowed. Use component-specific selectors only.`
50
+ );
51
+ }
52
+ }
53
+
54
+ // Check for selectors that contain global elements
55
+ for (const global of globalSelectors) {
56
+ if (
57
+ selector.includes(` ${global} `) ||
58
+ selector.includes(` ${global}.`) ||
59
+ selector.includes(` ${global}#`)
60
+ ) {
61
+ throw new Error(
62
+ `Global selector '${selector}' is not allowed. Use component-specific selectors only.`
63
+ );
64
+ }
65
+ }
66
+ }
67
+ }
68
+ };
69
+ };
70
+
71
+ globalSelectorDetector.postcss = true;
72
+
73
+ /**
74
+ * Compiles CSS with PostCSS - prefixing and minification in one pipeline
75
+ * @param {string} input - CSS file path (preferred) or Base64-encoded CSS string (backward compatible)
76
+ * @param {string} name - Component name for prefixing
77
+ * @param {string} namespace - Optional namespace for additional prefixing
78
+ * @param {Object} [options]
79
+ * @param {boolean} [options.isFile=false] - When true, treat input as a file path and read CSS from disk
80
+ * @returns {Promise<string>} - Promise resolving to processed CSS
81
+ */
82
+ async function compileCSS(input, name, namespace = null, options = {}) {
83
+ return new Promise(async (resolve, reject) => {
84
+ try {
85
+ // Check if namespace is required but not provided
86
+ if (!namespace) {
87
+ throw new Error(
88
+ "Namespace is required for CSS compilation. Please provide a namespace parameter."
89
+ );
90
+ }
91
+
92
+ // Resolve input to CSS code
93
+ const decodeBase64 = (value) => {
94
+ try {
95
+ if (typeof atob === "function") {
96
+ return atob(value);
97
+ }
98
+ } catch (_) {
99
+ /* ignore */
100
+ }
101
+ return Buffer.from(value, "base64").toString("utf8");
102
+ };
103
+
104
+ const resolveCssCode = () => {
105
+ // Explicit file mode
106
+ if (options && options.isFile) {
107
+ return fs.readFileSync(input, "utf8");
108
+ }
109
+ // If input points to an existing file, read it
110
+ if (typeof input === "string" && fs.existsSync(input)) {
111
+ return fs.readFileSync(input, "utf8");
112
+ }
113
+ // Backward compatibility: assume Base64 string
114
+ return decodeBase64(input);
115
+ };
116
+
117
+ const cssCode = resolveCssCode();
118
+
119
+ // Create component prefix for :root transformation
120
+ const componentPrefix = namespace
121
+ ? `[data-element-type="${namespace}_${name}"]`
122
+ : `[data-element-type="${name}"]`;
123
+
124
+ // Create PostCSS processor with plugins
125
+ const processor = postcss([
126
+ // 1. Handle nested CSS first
127
+ postcssNested(),
128
+
129
+ // 2. Transform :root selectors to component-specific selectors
130
+ createRootSelectorTransformPlugin(componentPrefix),
131
+
132
+ // 3. Detect and throw errors for global selectors (excluding :root)
133
+ globalSelectorDetector(),
134
+
135
+ // 4. Prefix keyframes with component name and namespace
136
+ postcssPrefixKeyframe({
137
+ prefix: namespace ? `${namespace}-${name}-` : `${name}-`
138
+ }),
139
+
140
+ // 5. Add component prefixing using postcss-prefix-selector
141
+ postcssPrefixSelector({
142
+ prefix: componentPrefix,
143
+ // Skip special selectors that should remain global
144
+ exclude: [
145
+ /^\d+%$/, // Keyframe percentages
146
+ "from",
147
+ "to",
148
+ // Exclude already transformed :root selectors to prevent double prefixing
149
+ new RegExp(
150
+ `^\\[data-element-type="${
151
+ namespace ? `${namespace}_${name}` : name
152
+ }"\\]$`
153
+ )
154
+ ],
155
+ // Ensure quotes are preserved in attribute selectors
156
+ transform(prefix, selector, prefixedSelector) {
157
+ // Ensure attribute selectors maintain quotes
158
+ if (
159
+ prefixedSelector.includes("data-element-type=") &&
160
+ !prefixedSelector.includes('data-element-type="')
161
+ ) {
162
+ return prefixedSelector.replace(
163
+ /data-element-type=([^"\s\]]+)/g,
164
+ 'data-element-type="$1"'
165
+ );
166
+ }
167
+ return prefixedSelector;
168
+ }
169
+ }),
170
+
171
+ // 6. Minify with cssnano (includes autoprefixer and optimization)
172
+ cssnano({
173
+ preset: [
174
+ "default",
175
+ {
176
+ discardComments: { removeAll: true },
177
+ normalizeWhitespace: true,
178
+ colormin: true,
179
+ convertValues: true,
180
+ discardDuplicates: true,
181
+ discardEmpty: true,
182
+ mergeIdents: true,
183
+ mergeLonghand: true,
184
+ mergeRules: true,
185
+ minifyFontValues: true,
186
+ minifyGradients: true,
187
+ minifyParams: true,
188
+ minifySelectors: true,
189
+ normalizeCharset: true,
190
+ normalizeDisplayValues: true,
191
+ normalizePositions: true,
192
+ normalizeRepeatStyle: true,
193
+ normalizeString: true,
194
+ normalizeTimingFunctions: true,
195
+ normalizeUnicode: true,
196
+ normalizeUrl: true,
197
+ orderedValues: true,
198
+ reduceIdents: true,
199
+ reduceInitial: true,
200
+ reduceTransforms: true,
201
+ svgo: true,
202
+ uniqueSelectors: true,
203
+ autoprefixer: {
204
+ browsers: ["> 1%", "last 2 versions", "ie >= 9"],
205
+ add: true,
206
+ remove: true,
207
+ flexbox: "no-2009"
208
+ }
209
+ }
210
+ ]
211
+ })
212
+ ]);
213
+
214
+ // Process the CSS
215
+ const result = await processor.process(cssCode, {
216
+ from: undefined,
217
+ to: undefined,
218
+ map: false
219
+ });
220
+
221
+ const processedCSS = result.css;
222
+
223
+ resolve(processedCSS);
224
+ } catch (error) {
225
+ reject(new Error(`CSS compilation failed for ${name}: ${error.message}`));
226
+ }
227
+ });
228
+ }
229
+
230
+ module.exports = compileCSS;