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,49 @@
1
+ const path = require("path");
2
+ const { promises: fs } = require("fs");
3
+ const { i18n } = require("../utils/i18n.js");
4
+ const { buildDeployZip } = require("./deploy.js");
5
+
6
+ /**
7
+ * Generate deployment zip (same contents as zs deploy) and write to a file.
8
+ * Use this to produce a zip for the server team to verify (e.g. content-type, structure).
9
+ * @param {Object} options - Command options
10
+ * @param {string} [options.output] - Output path for the zip file (default: ./widgets.zip in cwd)
11
+ */
12
+ async function generateZip(options = {}) {
13
+ const cwd = process.cwd();
14
+ const outputPath = options.output
15
+ ? path.resolve(cwd, options.output)
16
+ : path.join(cwd, "widgets.zip");
17
+
18
+ let tempDir = null;
19
+
20
+ try {
21
+ i18n.info("commands.generateZip.starting");
22
+
23
+ const { tempDir: dir, zipPath } = await buildDeployZip({
24
+ outputZipPath: outputPath
25
+ });
26
+ tempDir = dir;
27
+
28
+ // Remove only the temp directory; keep the zip at outputPath
29
+ if (tempDir) {
30
+ await fs.rm(tempDir, { recursive: true, force: true });
31
+ }
32
+
33
+ const stats = await fs.stat(outputPath);
34
+ i18n.success("commands.generateZip.done", {
35
+ path: outputPath,
36
+ size: stats.size
37
+ });
38
+ i18n.info("commands.generateZip.shareHint");
39
+ } catch (error) {
40
+ if (tempDir) {
41
+ try {
42
+ await fs.rm(tempDir, { recursive: true, force: true });
43
+ } catch (_) {}
44
+ }
45
+ i18n.error("commands.generateZip.error", { error: error.message });
46
+ }
47
+ }
48
+
49
+ module.exports = { generateZip };
@@ -0,0 +1,23 @@
1
+ // Export all commands
2
+ const { login } = require('./login.js');
3
+ const { logout, whoami, status } = require('./auth.js');
4
+ const { init } = require('./init.js');
5
+ const { initTailwind } = require('./init-tailwind.js');
6
+ const { pull } = require('./pull.js');
7
+ const { create } = require('./create.js');
8
+ const { serve } = require('./serve.js');
9
+ const { install } = require('./install.js');
10
+
11
+
12
+ module.exports = {
13
+ login,
14
+ logout,
15
+ whoami,
16
+ status,
17
+ init,
18
+ initTailwind,
19
+ pull,
20
+ create,
21
+ serve,
22
+ install
23
+ };
@@ -0,0 +1,57 @@
1
+ const { promises: fs } = require("fs");
2
+ const { join } = require("path");
3
+ const { i18n } = require("../utils/i18n.js");
4
+ const {
5
+ CONFIG_FILE_NAME,
6
+ TAILWIND_CONFIG_FILE
7
+ } = require("../config/constants.js");
8
+
9
+ const TAILWIND_CONFIG_CONTENT = `/** @type {import('tailwindcss').Config} */
10
+ module.exports = {
11
+ content: [
12
+ "./*/index.js",
13
+ "./*/**/*.js",
14
+ "./*/**/*.jsx",
15
+ "./*/styles.css"
16
+ ],
17
+ theme: {
18
+ extend: {}
19
+ },
20
+ plugins: []
21
+ };
22
+ `;
23
+
24
+ /**
25
+ * Initialize Tailwind CSS in the current ZS project by creating tailwind.config.js.
26
+ * Run from project root (where .zs exists). Tailwind is built by the SDK at compile time.
27
+ */
28
+ async function initTailwind() {
29
+ try {
30
+ const cwd = process.cwd();
31
+ const configPath = join(cwd, CONFIG_FILE_NAME);
32
+ const tailwindConfigPath = join(cwd, TAILWIND_CONFIG_FILE);
33
+
34
+ try {
35
+ await fs.access(configPath);
36
+ } catch {
37
+ i18n.error("commands.initTailwind.notInProject");
38
+ process.exit(1);
39
+ }
40
+
41
+ try {
42
+ await fs.access(tailwindConfigPath);
43
+ i18n.info("commands.initTailwind.alreadyExists");
44
+ return;
45
+ } catch {
46
+ // File does not exist, create it
47
+ }
48
+
49
+ await fs.writeFile(tailwindConfigPath, TAILWIND_CONFIG_CONTENT, "utf8");
50
+ i18n.success("commands.initTailwind.created");
51
+ } catch (error) {
52
+ i18n.error("commands.initTailwind.error", { error: error.message });
53
+ process.exit(1);
54
+ }
55
+ }
56
+
57
+ module.exports = { initTailwind };
@@ -0,0 +1,449 @@
1
+ const inquirer = require("inquirer");
2
+ const { promises: fs } = require("fs");
3
+ const { join, dirname, parse } = require("path");
4
+ const { i18n } = require("../utils/i18n.js");
5
+ const { UrlUtil } = require("../utils/urlUtil.js");
6
+ const { GET, POST, isAuthenticated } = require("../utils/httpUtil.js");
7
+ const {
8
+ CONFIG_FILE_NAME,
9
+ WEBPACK_OVERRIDES_FILE
10
+ } = require("../config/constants.js");
11
+ const SecureStorage = require("../utils/secureStorage.js");
12
+ const { getCliName } = require("../utils/cliName.js");
13
+
14
+ const WORKSPACES_PARENT_PATH = "/__workspaces";
15
+ const WORKSPACE_RESOURCE_TYPE = "/__conf/devhub_workspace";
16
+ const APP_RESOURCE_TYPE = "/__conf/apps";
17
+
18
+ /**
19
+ * Build headers for resource APIs (workspaces/apps query).
20
+ * @param {string} asoid - Account asoid from /api/v3/account
21
+ * @returns {{ headers: { "x-site-id": string } }}
22
+ */
23
+ function buildSiteIdHeaders(asoid) {
24
+ return {
25
+ headers: {
26
+ "x-site-id": String(asoid),
27
+ },
28
+ };
29
+ }
30
+
31
+ /**
32
+ * Extract asoid from /api/v3/account response.
33
+ * @param {Object} response
34
+ * @returns {string}
35
+ */
36
+ function parseAccountAsoid(response) {
37
+ const asoid =
38
+ response?.asoid ||
39
+ response?.account?.asoid ||
40
+ response?.data?.asoid ||
41
+ response?.account_data?.asoid;
42
+
43
+ if (!asoid) {
44
+ throw new Error(
45
+ "Could not determine asoid from account API response. Please ensure your account is provisioned."
46
+ );
47
+ }
48
+
49
+ return String(asoid);
50
+ }
51
+
52
+ /**
53
+ * Fetch current user account asoid via GET /api/v3/account.
54
+ * This asoid is required as x-site-id for subsequent resource API calls.
55
+ * @returns {Promise<string>}
56
+ */
57
+ async function fetchAccountAsoid() {
58
+ i18n.info("commands.init.fetchingAccount");
59
+ await assertAuthenticated();
60
+
61
+ const response = await GET(
62
+ await UrlUtil.getSitesUrl("ACCOUNT.GET"),
63
+ {},
64
+ i18n.t("commands.init.fetchingAccount")
65
+ );
66
+
67
+ const asoid = parseAccountAsoid(response);
68
+ i18n.success("commands.init.foundAccountAsoid", { asoid });
69
+ return asoid;
70
+ }
71
+
72
+ /**
73
+ * Prevent running `zs init` inside an existing ZS project.
74
+ * The presence of a `.zs` file in the current directory or any parent directory
75
+ * indicates an existing project; we should refuse to create a new one.
76
+ */
77
+ async function assertNotInExistingProject() {
78
+ const markerFileName = CONFIG_FILE_NAME; // typically ".zs"
79
+ let currentDir = process.cwd();
80
+ const rootDir = parse(currentDir).root;
81
+
82
+ while (true) {
83
+ const markerPath = join(currentDir, markerFileName);
84
+ let markerExists = false;
85
+
86
+ try {
87
+ await fs.access(markerPath);
88
+ markerExists = true;
89
+ } catch (error) {
90
+ // ENOENT/ENOTDIR => marker not present; continue scanning upwards.
91
+ if (!error || (error.code !== "ENOENT" && error.code !== "ENOTDIR")) {
92
+ // Unexpected errors (e.g. permission issues): fail fast to avoid
93
+ // accidentally overwriting or creating a project in a bad state.
94
+ throw error;
95
+ }
96
+ }
97
+
98
+ if (markerExists) {
99
+ throw new Error(i18n.t("commands.init.alreadyInProject"));
100
+ }
101
+
102
+ if (currentDir === rootDir) break;
103
+ const parentDir = dirname(currentDir);
104
+ if (!parentDir || parentDir === currentDir) break;
105
+ currentDir = parentDir;
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Ensure the user is authenticated before making API calls.
111
+ */
112
+ async function assertAuthenticated() {
113
+ const authenticated = await isAuthenticated();
114
+ if (!authenticated) {
115
+ throw new Error(
116
+ `Authentication required. Please run \`${getCliName()} login\` to authenticate before initializing a project.`
117
+ );
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Build the shared query payload for the resources/query API.
123
+ * @param {string} parentPath
124
+ * @param {string} resourceType
125
+ * @param {boolean} [sortAsc=true]
126
+ * @returns {Object}
127
+ */
128
+ function buildQueryPayload(parentPath, resourceType, sortAsc = true) {
129
+ return {
130
+ parent_path: parentPath,
131
+ resource_types: [resourceType],
132
+ skip: 0,
133
+ limit: 100,
134
+ sort_columns: [{ field_name: "created_time", is_asc: sortAsc }],
135
+ };
136
+ }
137
+
138
+ /**
139
+ * Parse resource_data.data from a query_resource response.
140
+ * @param {Object} response
141
+ * @param {string} label - Human-readable label for error messages
142
+ * @returns {Array}
143
+ */
144
+ function parseQueryResourceResponse(response, label) {
145
+ if (response.status_code !== "0") {
146
+ throw new Error(
147
+ response.status_message || `Unexpected response from ${label} API`
148
+ );
149
+ }
150
+
151
+ const data = response.resource_data?.data;
152
+ if (!data || !Array.isArray(data)) {
153
+ throw new Error(`Unexpected response format from ${label} API`);
154
+ }
155
+
156
+ return data;
157
+ }
158
+
159
+ /**
160
+ * Fetch available workspaces via POST /api/v3/resources/query.
161
+ * @param {string} asoid - Account asoid for x-site-id header
162
+ * @returns {Promise<Array>} Normalized workspace objects
163
+ */
164
+ async function fetchWorkspaces(asoid) {
165
+ i18n.info("commands.init.fetchingWorkspaces");
166
+ await assertAuthenticated();
167
+
168
+ const response = await POST(
169
+ await UrlUtil.getSitesUrl("NAMESPACES.QUERY"),
170
+ buildQueryPayload(WORKSPACES_PARENT_PATH, WORKSPACE_RESOURCE_TYPE, true),
171
+ buildSiteIdHeaders(asoid),
172
+ i18n.t("commands.init.fetchingWorkspaces")
173
+ );
174
+
175
+ const workspaces = parseQueryResourceResponse(response, "workspaces").map(
176
+ (ws) => ({
177
+ name: ws.resource_name || ws.name,
178
+ resourceUrl: ws.resource_url,
179
+ resourcePath: ws.resource_path,
180
+ resourceId: ws.resource_id,
181
+ createdTime: ws.created_time,
182
+ })
183
+ );
184
+
185
+ if (workspaces.length === 0) {
186
+ throw new Error(
187
+ `No workspaces found. Please create a workspace in the Zoho Sites dashboard before running '${getCliName()} init'.`
188
+ );
189
+ }
190
+
191
+ i18n.success("commands.init.foundWorkspaces", { count: workspaces.length });
192
+ return workspaces;
193
+ }
194
+
195
+ /**
196
+ * Fetch apps for a workspace via POST /api/v3/resources/query.
197
+ * @param {Object} workspace - Selected workspace (uses resourceUrl for parent_path)
198
+ * @param {string} asoid - Account asoid for x-site-id header
199
+ * @returns {Promise<Array>} Normalized app objects
200
+ */
201
+ async function fetchAppsForWorkspace(workspace, asoid) {
202
+ i18n.info("commands.init.fetchingApps");
203
+ await assertAuthenticated();
204
+
205
+ const parentPath = `${WORKSPACES_PARENT_PATH}/${workspace.resourceUrl}`;
206
+ const response = await POST(
207
+ await UrlUtil.getSitesUrl("NAMESPACES.QUERY"),
208
+ buildQueryPayload(parentPath, APP_RESOURCE_TYPE, false),
209
+ buildSiteIdHeaders(asoid),
210
+ i18n.t("commands.init.fetchingApps")
211
+ );
212
+
213
+ const apps = parseQueryResourceResponse(response, "apps").map((app) => ({
214
+ name: app.app_name || app.resource_name || app.name,
215
+ namespace: app.namespace || app.resource_url,
216
+ defaultSite: app.defaultSite,
217
+ resourcePath: app.resource_path,
218
+ resourceId: app.resource_id,
219
+ createdTime: app.created_time,
220
+ workspace: workspace.name,
221
+ workspaceUrl: workspace.resourceUrl,
222
+ }));
223
+
224
+ if (apps.length === 0) {
225
+ throw new Error(
226
+ `No apps found in workspace "${workspace.name}". Please create an app in the Zoho Sites dashboard before running '${getCliName()} init'.`
227
+ );
228
+ }
229
+
230
+ i18n.success("commands.init.foundApps", { count: apps.length });
231
+ return apps;
232
+ }
233
+
234
+ /**
235
+ * Prompt user to select a workspace or auto-select if only one exists.
236
+ * @param {Array} workspaces
237
+ * @returns {Promise<Object>}
238
+ */
239
+ async function selectWorkspaceFromUser(workspaces) {
240
+ if (workspaces.length === 1) {
241
+ const selected = workspaces[0];
242
+ i18n.info("commands.init.usingWorkspace", { workspace: selected.name });
243
+ return selected;
244
+ }
245
+
246
+ const choices = workspaces.map((ws) => ({
247
+ name: i18n.t("commands.init.workspaceChoiceLabel", {
248
+ name: ws.name,
249
+ url: ws.resourceUrl,
250
+ }),
251
+ value: ws,
252
+ }));
253
+
254
+ const { selectedWorkspace } = await inquirer.prompt([
255
+ {
256
+ type: "list",
257
+ name: "selectedWorkspace",
258
+ message: i18n.t("commands.init.selectWorkspaceMessage"),
259
+ choices,
260
+ },
261
+ ]);
262
+
263
+ i18n.success("commands.init.selectedWorkspace", {
264
+ workspace: selectedWorkspace.name,
265
+ });
266
+ return selectedWorkspace;
267
+ }
268
+
269
+ /**
270
+ * Prompt user to select an app or auto-select if only one exists.
271
+ * @param {Array} apps
272
+ * @returns {Promise<Object>}
273
+ */
274
+ async function selectAppFromUser(apps) {
275
+ if (apps.length === 1) {
276
+ const selected = apps[0];
277
+ i18n.info("commands.init.usingApp", { app: selected.name });
278
+ return selected;
279
+ }
280
+
281
+ const choices = apps.map((app) => ({
282
+ name: i18n.t("commands.init.choiceLabel", {
283
+ name: app.name,
284
+ namespace: app.namespace,
285
+ }),
286
+ value: app,
287
+ }));
288
+
289
+ const { selectedApp } = await inquirer.prompt([
290
+ {
291
+ type: "list",
292
+ name: "selectedApp",
293
+ message: i18n.t("commands.init.selectAppMessage"),
294
+ choices,
295
+ },
296
+ ]);
297
+
298
+ i18n.success("commands.init.selectedApp", { app: selectedApp.name });
299
+ return selectedApp;
300
+ }
301
+
302
+ /**
303
+ * Create project folder structure and configuration files
304
+ * @param {Object} selectedApp - Selected app object (includes workspace fields)
305
+ * @param {string} asoid - Account asoid from /api/v3/account
306
+ * @returns {Promise<string>} Created folder name
307
+ */
308
+ async function createProjectStructure(selectedApp, asoid) {
309
+ const folderName = selectedApp.name;
310
+
311
+ i18n.info("commands.init.creatingFolder", { app: folderName });
312
+
313
+ await fs.mkdir(folderName, { recursive: true });
314
+ await writeConfigFile(folderName, selectedApp, asoid);
315
+ await writeWebpackConfig(folderName);
316
+ await writePackageJson(folderName, selectedApp);
317
+ await fs.mkdir(join(folderName, "assets"), { recursive: true });
318
+
319
+ i18n.success("commands.init.structureCreated");
320
+ return folderName;
321
+ }
322
+
323
+ /**
324
+ * Write ZS configuration file
325
+ * @param {string} folderName
326
+ * @param {Object} app
327
+ * @param {string} asoid - Account asoid stored for x-site-id on resource APIs
328
+ */
329
+ async function writeConfigFile(folderName, app, asoid) {
330
+ const environment = await SecureStorage.getEnvironment();
331
+
332
+ const configData = {
333
+ namespace: app.namespace,
334
+ asoid: asoid,
335
+ appName: app.name,
336
+ defaultSite: app.defaultSite,
337
+ workspace: app.workspace,
338
+ environment: environment,
339
+ createdAt: new Date().toISOString(),
340
+ version: "1.0.0",
341
+ };
342
+
343
+ const configPath = join(folderName, CONFIG_FILE_NAME);
344
+ await fs.writeFile(configPath, JSON.stringify(configData, null, 2));
345
+ }
346
+
347
+ /**
348
+ * Write webpack overrides configuration file
349
+ */
350
+ async function writeWebpackConfig(folderName) {
351
+ const webpackConfigContent = `module.exports = (mode, ctx) => ({
352
+ // Add your webpack overrides here
353
+ });
354
+ `;
355
+ const webpackConfigPath = join(folderName, WEBPACK_OVERRIDES_FILE);
356
+ await fs.writeFile(webpackConfigPath, webpackConfigContent, "utf8");
357
+ }
358
+
359
+ /**
360
+ * Write package.json with project metadata
361
+ */
362
+ async function writePackageJson(folderName, app) {
363
+ const sanitizeName = (name) =>
364
+ name
365
+ .toLowerCase()
366
+ .replace(/[^a-z0-9]+/g, "-")
367
+ .replace(/(^-|-$)/g, "");
368
+
369
+ let authorName = "";
370
+ let authorEmail = "";
371
+ try {
372
+ const storage = new SecureStorage();
373
+ const auth = await storage.getAuthData();
374
+ if (auth) {
375
+ authorName = auth.user_name || "";
376
+ authorEmail = auth.email || "";
377
+ }
378
+ } catch (_) {
379
+ // Ignore errors, author info is optional
380
+ }
381
+
382
+ const packageJson = {
383
+ name: sanitizeName(app.name),
384
+ version: "1.0.0",
385
+ description: `ZS project for ${app.name} namespace`,
386
+ author: authorEmail ? `${authorName} <${authorEmail}>` : authorName,
387
+ license: "MIT",
388
+ private: true,
389
+ type: "commonjs",
390
+ scripts: {
391
+ start: `${getCliName()} serve`,
392
+ serve: `${getCliName()} serve`,
393
+ pull: `${getCliName()} pull`,
394
+ create: `${getCliName()} create`,
395
+ },
396
+ };
397
+
398
+ const packageJsonPath = join(folderName, "package.json");
399
+ await fs.writeFile(
400
+ packageJsonPath,
401
+ JSON.stringify(packageJson, null, 2),
402
+ "utf8"
403
+ );
404
+ }
405
+
406
+ /**
407
+ * Initialize a new ZS project: select workspace, then app.
408
+ */
409
+ async function init() {
410
+ try {
411
+ i18n.info("commands.init.initCommand");
412
+ i18n.info("commands.init.initializingNewProject");
413
+
414
+ await assertNotInExistingProject();
415
+
416
+ // Account asoid is required as x-site-id for all resource API calls
417
+ const asoid = await fetchAccountAsoid();
418
+
419
+ const workspaces = await fetchWorkspaces(asoid);
420
+ const selectedWorkspace = await selectWorkspaceFromUser(workspaces);
421
+
422
+ const apps = await fetchAppsForWorkspace(selectedWorkspace, asoid);
423
+ const selectedApp = await selectAppFromUser(apps);
424
+
425
+ await createProjectStructure(selectedApp, asoid);
426
+
427
+ i18n.success("commands.init.projectInitializationCompleted");
428
+ } catch (error) {
429
+ i18n.error("commands.init.errorDuringInitialization", {
430
+ error: error.message,
431
+ });
432
+ process.exit(1);
433
+ }
434
+ }
435
+
436
+ module.exports = {
437
+ init,
438
+ fetchAccountAsoid,
439
+ parseAccountAsoid,
440
+ buildSiteIdHeaders,
441
+ fetchWorkspaces,
442
+ fetchAppsForWorkspace,
443
+ selectWorkspaceFromUser,
444
+ selectAppFromUser,
445
+ parseQueryResourceResponse,
446
+ buildQueryPayload,
447
+ createProjectStructure,
448
+ writeConfigFile,
449
+ };
@@ -0,0 +1,90 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const { spawn } = require("node:child_process");
4
+ const { i18n } = require("../utils/i18n.js");
5
+ const { getCliName } = require("../utils/cliName.js");
6
+
7
+ function sanitizePackageName(name) {
8
+ if (!name) {
9
+ return "zs-project";
10
+ }
11
+ return name
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9-_.]+/g, "-")
14
+ .replace(/^-+|-+$/g, "");
15
+ }
16
+
17
+ function ensurePackageJson(cwd) {
18
+ const pkgPath = path.join(cwd, "package.json");
19
+ if (fs.existsSync(pkgPath)) {
20
+ return false;
21
+ }
22
+
23
+ const dirName = path.basename(cwd);
24
+ const pkg = {
25
+ name: sanitizePackageName(dirName) || "zs-project",
26
+ version: "1.0.0",
27
+ private: true,
28
+ license: "MIT",
29
+ type: "commonjs",
30
+ scripts: {
31
+ start: `${getCliName()} serve`
32
+ }
33
+ };
34
+
35
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), "utf8");
36
+ return true;
37
+ }
38
+
39
+ function runNpmInstall(packages, { dev = false } = {}) {
40
+ return new Promise((resolve, reject) => {
41
+ const args = ["install", ...packages];
42
+ if (dev) {
43
+ args.push("--save-dev");
44
+ }
45
+
46
+ const child = spawn("npm", args, { stdio: "inherit", shell: true });
47
+ child.on("close", (code) => {
48
+ if (code === 0) {
49
+ resolve();
50
+ } else {
51
+ reject(new Error(`npm exited with code ${code}`));
52
+ }
53
+ });
54
+ child.on("error", (err) => reject(err));
55
+ });
56
+ }
57
+
58
+ async function install(packages, options = {}) {
59
+ try {
60
+ const packagesArray = Array.isArray(packages)
61
+ ? packages
62
+ : packages
63
+ ? [packages]
64
+ : [];
65
+ if (!packagesArray.length) {
66
+ i18n.error("commands.install.packageRequired");
67
+ return;
68
+ }
69
+
70
+ i18n.info("commands.install.title");
71
+
72
+ const created = ensurePackageJson(process.cwd());
73
+ if (created) {
74
+ i18n.success("commands.install.packageJsonCreated");
75
+ } else {
76
+ i18n.info("commands.install.packageJsonExists");
77
+ }
78
+
79
+ i18n.info("commands.install.runningNpmInstall", {
80
+ packages: packagesArray.join(" ")
81
+ });
82
+ await runNpmInstall(packagesArray, { dev: options.dev });
83
+ i18n.success("commands.install.npmInstallSuccess");
84
+ } catch (error) {
85
+ i18n.error("commands.install.npmInstallFailed", { error: error.message });
86
+ process.exitCode = 1;
87
+ }
88
+ }
89
+
90
+ module.exports = { install };