@lytjs/cli 5.0.6 → 6.5.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 (43) hide show
  1. package/dist/create.cjs +607 -0
  2. package/dist/create.cjs.map +1 -0
  3. package/dist/create.d.mts +2 -0
  4. package/dist/create.d.ts +2 -0
  5. package/dist/create.mjs +605 -0
  6. package/dist/create.mjs.map +1 -0
  7. package/dist/index.cjs +2212 -0
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.d.mts +208 -0
  10. package/dist/index.d.ts +208 -0
  11. package/dist/index.mjs +1999 -886
  12. package/dist/index.mjs.map +1 -0
  13. package/dist/lyt.cjs +2212 -0
  14. package/dist/lyt.cjs.map +1 -0
  15. package/dist/lyt.d.mts +1 -0
  16. package/dist/lyt.d.ts +1 -0
  17. package/dist/lyt.mjs +2171 -0
  18. package/dist/lyt.mjs.map +1 -0
  19. package/lyt-cli.js +3 -0
  20. package/package.json +34 -31
  21. package/README.md +0 -227
  22. package/dist/bin/cli.cjs +0 -1058
  23. package/dist/bin/cli.js +0 -2
  24. package/dist/bin/cli.mjs +0 -1058
  25. package/dist/index.js +0 -1058
  26. package/dist/types/bin/cli.d.ts +0 -8
  27. package/dist/types/bin/cli.d.ts.map +0 -1
  28. package/dist/types/build.d.ts +0 -30
  29. package/dist/types/build.d.ts.map +0 -1
  30. package/dist/types/create.d.ts +0 -19
  31. package/dist/types/create.d.ts.map +0 -1
  32. package/dist/types/dev.d.ts +0 -24
  33. package/dist/types/dev.d.ts.map +0 -1
  34. package/dist/types/generate.d.ts +0 -14
  35. package/dist/types/generate.d.ts.map +0 -1
  36. package/dist/types/hmr.d.ts +0 -55
  37. package/dist/types/hmr.d.ts.map +0 -1
  38. package/dist/types/index.d.ts +0 -20
  39. package/dist/types/index.d.ts.map +0 -1
  40. package/dist/types/scaffold.d.ts +0 -67
  41. package/dist/types/scaffold.d.ts.map +0 -1
  42. package/dist/types/utils.d.ts +0 -92
  43. package/dist/types/utils.d.ts.map +0 -1
package/dist/lyt.cjs ADDED
@@ -0,0 +1,2212 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var fs = require('fs');
5
+ var path = require('path');
6
+ var child_process = require('child_process');
7
+
8
+ function _interopNamespace(e) {
9
+ if (e && e.__esModule) return e;
10
+ var n = Object.create(null);
11
+ if (e) {
12
+ Object.keys(e).forEach(function (k) {
13
+ if (k !== 'default') {
14
+ var d = Object.getOwnPropertyDescriptor(e, k);
15
+ Object.defineProperty(n, k, d.get ? d : {
16
+ enumerable: true,
17
+ get: function () { return e[k]; }
18
+ });
19
+ }
20
+ });
21
+ }
22
+ n.default = e;
23
+ return Object.freeze(n);
24
+ }
25
+
26
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
27
+
28
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
29
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
30
+ }) : x)(function(x) {
31
+ if (typeof require !== "undefined") return require.apply(this, arguments);
32
+ throw Error('Dynamic require of "' + x + '" is not supported');
33
+ });
34
+
35
+ // src/utils/logger.ts
36
+ var colors = {
37
+ reset: "\x1B[0m",
38
+ bright: "\x1B[1m",
39
+ dim: "\x1B[2m",
40
+ red: "\x1B[31m",
41
+ green: "\x1B[32m",
42
+ yellow: "\x1B[33m",
43
+ blue: "\x1B[34m",
44
+ cyan: "\x1B[36m"
45
+ };
46
+ function colorize(text, color) {
47
+ if (!isColorSupported()) return text;
48
+ return `${colors[color]}${text}${colors.reset}`;
49
+ }
50
+ var logger = {
51
+ info(message) {
52
+ console.log(colorize("\u2139 ", "blue") + message);
53
+ },
54
+ success(message) {
55
+ console.log(colorize("\u2714 ", "green") + message);
56
+ },
57
+ warning(message) {
58
+ console.log(colorize("\u26A0 ", "yellow") + message);
59
+ },
60
+ error(message) {
61
+ console.error(colorize("\u2716 ", "red") + message);
62
+ },
63
+ dim(message) {
64
+ console.log(colorize(message, "dim"));
65
+ },
66
+ bold(message) {
67
+ return colorize(message, "bright");
68
+ }
69
+ };
70
+ function isColorSupported() {
71
+ return process.stdout.isTTY && process.env.NO_COLOR !== "1";
72
+ }
73
+ function ensureDir(dir) {
74
+ if (!fs.existsSync(dir)) {
75
+ fs.mkdirSync(dir, { recursive: true });
76
+ }
77
+ }
78
+ function writeFile(filePath, content) {
79
+ ensureDir(path.dirname(filePath));
80
+ fs.writeFileSync(filePath, content, "utf-8");
81
+ }
82
+ function readFile(filePath) {
83
+ return fs.readFileSync(filePath, "utf-8");
84
+ }
85
+ function exists(path2) {
86
+ return fs.existsSync(path2);
87
+ }
88
+ function isEmptyDir(dir) {
89
+ if (!fs.existsSync(dir)) return true;
90
+ const files = fs.readdirSync(dir);
91
+ return files.length === 0;
92
+ }
93
+ function detectPackageManager(cwd = process.cwd()) {
94
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
95
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn";
96
+ if (fs.existsSync(path.join(cwd, "package-lock.json"))) return "npm";
97
+ try {
98
+ child_process.execSync("pnpm --version", { stdio: "ignore" });
99
+ return "pnpm";
100
+ } catch {
101
+ return "npm";
102
+ }
103
+ }
104
+ function getInstallCommand(pm) {
105
+ switch (pm) {
106
+ case "pnpm":
107
+ return "pnpm install";
108
+ case "yarn":
109
+ return "yarn";
110
+ case "npm":
111
+ return "npm install";
112
+ }
113
+ }
114
+ function getRunCommand(pm, script) {
115
+ switch (pm) {
116
+ case "pnpm":
117
+ return `pnpm run ${script}`;
118
+ case "yarn":
119
+ return `yarn ${script}`;
120
+ case "npm":
121
+ return `npm run ${script}`;
122
+ }
123
+ }
124
+ function getAddCommand(pm, dep, dev2 = false) {
125
+ const devFlag = dev2 ? " -D" : "";
126
+ switch (pm) {
127
+ case "pnpm":
128
+ return `pnpm add${devFlag} ${dep}`;
129
+ case "yarn":
130
+ return `yarn add${devFlag} ${dep}`;
131
+ case "npm":
132
+ return `npm install${devFlag} ${dep}`;
133
+ }
134
+ }
135
+ var TEMPLATES = {
136
+ default: "Default template with TypeScript and Vite",
137
+ minimal: "Minimal template without extra dependencies",
138
+ ssr: "SSR-enabled template",
139
+ router: "Template with Router integration",
140
+ store: "Template with Store integration",
141
+ full: "Full-featured template with Router, Store, and UI components"
142
+ };
143
+ async function create(projectName, options = {}) {
144
+ if (!projectName) {
145
+ logger.error("Please provide a project name.");
146
+ logger.info("Usage: lyt create <project-name>");
147
+ process.exit(1);
148
+ }
149
+ const targetDir = path.resolve(process.cwd(), projectName);
150
+ if (exists(targetDir) && !isEmptyDir(targetDir) && !options.force) {
151
+ logger.error(`Directory "${projectName}" already exists and is not empty.`);
152
+ logger.info("Use --force to overwrite.");
153
+ process.exit(1);
154
+ }
155
+ logger.info(`Creating a new LytJS project in ${targetDir}...`);
156
+ ensureDir(targetDir);
157
+ generateProjectFiles(targetDir, projectName, options.template || "default");
158
+ logger.info("Installing dependencies...");
159
+ const pm = detectPackageManager();
160
+ try {
161
+ child_process.execSync(getInstallCommand(pm), { cwd: targetDir, stdio: "inherit" });
162
+ logger.success("Dependencies installed successfully!");
163
+ } catch (_error) {
164
+ logger.warning("Failed to install dependencies automatically.");
165
+ logger.info(`Please run "${getInstallCommand(pm)}" manually.`);
166
+ }
167
+ logger.success(`Project "${projectName}" created successfully!`);
168
+ logger.info("");
169
+ logger.bold("Next steps:");
170
+ logger.info(` cd ${projectName}`);
171
+ logger.info(` ${pm === "npm" ? "npm run" : pm} dev`);
172
+ }
173
+ function generateProjectFiles(targetDir, projectName, template) {
174
+ const isMinimal = template === "minimal";
175
+ const isSsr = template === "ssr";
176
+ const isRouter = template === "router" || template === "full";
177
+ const isStore = template === "store" || template === "full";
178
+ const isFull = template === "full";
179
+ const packageJson = {
180
+ name: projectName,
181
+ version: "0.0.0",
182
+ type: "module",
183
+ scripts: {
184
+ dev: "vite",
185
+ build: "vite build",
186
+ preview: "vite preview"
187
+ },
188
+ dependencies: {
189
+ "@lytjs/core": "^6.0.0"
190
+ },
191
+ devDependencies: {
192
+ "@lytjs/plugin-vite": "^6.0.0",
193
+ "vite": "^5.0.0"
194
+ }
195
+ };
196
+ if (!isMinimal) {
197
+ packageJson.scripts.test = "vitest";
198
+ packageJson.devDependencies.vitest = "^1.0.0";
199
+ }
200
+ if (isSsr) {
201
+ packageJson.dependencies["@lytjs/server"] = "^6.0.0";
202
+ packageJson.scripts["build:client"] = "vite build --ssrManifest";
203
+ packageJson.scripts["build:server"] = "vite build --ssr src/entry-server.ts";
204
+ packageJson.scripts["build"] = "npm run build:client && npm run build:server";
205
+ packageJson.scripts["preview"] = "node server";
206
+ }
207
+ if (isRouter) {
208
+ packageJson.dependencies["@lytjs/router"] = "^1.0.0";
209
+ }
210
+ if (isStore) {
211
+ packageJson.dependencies["@lytjs/store"] = "^1.0.0";
212
+ }
213
+ if (isFull) {
214
+ packageJson.dependencies["@lytjs/ui"] = "^0.4.0";
215
+ }
216
+ writeFile(path.join(targetDir, "package.json"), JSON.stringify(packageJson, null, 2));
217
+ let viteConfig;
218
+ if (isSsr) {
219
+ viteConfig = `import { defineConfig } from 'vite';
220
+ import lytjs from '@lytjs/plugin-vite';
221
+
222
+ export default defineConfig({
223
+ plugins: [lytjs()],
224
+ build: {
225
+ ssrManifest: true,
226
+ },
227
+ });
228
+ `;
229
+ } else {
230
+ viteConfig = `import { defineConfig } from 'vite';
231
+ import lytjs from '@lytjs/plugin-vite';
232
+
233
+ export default defineConfig({
234
+ plugins: [lytjs()],
235
+ });
236
+ `;
237
+ }
238
+ writeFile(path.join(targetDir, "vite.config.ts"), viteConfig);
239
+ const indexHtml = `<!DOCTYPE html>
240
+ <html lang="en">
241
+ <head>
242
+ <meta charset="UTF-8" />
243
+ <link rel="icon" type="image/svg+xml" href="/vite.svg" />
244
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
245
+ <title>${projectName}</title>
246
+ </head>
247
+ <body>
248
+ <div id="app"></div>
249
+ <script type="module" src="/src/main.ts"></script>
250
+ </body>
251
+ </html>
252
+ `;
253
+ writeFile(path.join(targetDir, "index.html"), indexHtml);
254
+ let mainTs;
255
+ if (isSsr) {
256
+ mainTs = `import { createApp } from '@lytjs/core';
257
+ import App from './App.lyt';
258
+ import { createSSRApp } from '@lytjs/server';
259
+ ${isRouter ? "import { createRouter, createWebHistory } from '@lytjs/router';" : ""}
260
+ ${isStore ? "import { createPinia } from '@lytjs/store';" : ""}
261
+
262
+ const app = createSSRApp(App);
263
+ ${isStore ? "app.use(createPinia());" : ""}
264
+ ${isRouter ? `
265
+ const router = createRouter({
266
+ history: createWebHistory(),
267
+ routes: [
268
+ { path: '/', component: () => import('./pages/Home.lyt') },
269
+ { path: '/about', component: () => import('./pages/About.lyt') },
270
+ ],
271
+ });
272
+ app.use(router);
273
+ ` : ""}
274
+ app.mount('#app');
275
+ `;
276
+ } else if (isRouter || isStore) {
277
+ mainTs = `import { createApp } from '@lytjs/core';
278
+ import App from './App.lyt';
279
+ ${isRouter ? "import { createRouter, createWebHistory } from '@lytjs/router';" : ""}
280
+ ${isStore ? "import { createPinia } from '@lytjs/store';" : ""}
281
+
282
+ const app = createApp(App);
283
+ ${isStore ? "app.use(createPinia());" : ""}
284
+ ${isRouter ? `
285
+ const router = createRouter({
286
+ history: createWebHistory(),
287
+ routes: [
288
+ { path: '/', component: () => import('./pages/Home.lyt') },
289
+ { path: '/about', component: () => import('./pages/About.lyt') },
290
+ ],
291
+ });
292
+ app.use(router);
293
+ ` : ""}
294
+ app.mount('#app');
295
+ `;
296
+ } else {
297
+ mainTs = `import { createApp } from '@lytjs/core';
298
+ import App from './App.lyt';
299
+
300
+ createApp(App).mount('#app');
301
+ `;
302
+ }
303
+ writeFile(path.join(targetDir, "src/main.ts"), mainTs);
304
+ let appLyt;
305
+ if (isMinimal) {
306
+ appLyt = `<template>
307
+ <div class="app">
308
+ <h1>{{ title }}</h1>
309
+ </div>
310
+ </template>
311
+
312
+ <script setup>
313
+ const title = 'Hello LytJS!';
314
+ </script>
315
+
316
+ <style scoped>
317
+ .app {
318
+ text-align: center;
319
+ }
320
+ </style>
321
+ `;
322
+ } else if (isRouter) {
323
+ appLyt = `<template>
324
+ <div class="app">
325
+ <nav class="nav">
326
+ <router-link to="/">Home</router-link>
327
+ <router-link to="/about">About</router-link>
328
+ </nav>
329
+ <router-view />
330
+ </div>
331
+ </template>
332
+
333
+ <script setup lang="ts">
334
+ import { RouterLink, RouterView } from '@lytjs/router';
335
+ </script>
336
+
337
+ <style scoped>
338
+ .app {
339
+ text-align: center;
340
+ padding: 2rem;
341
+ }
342
+
343
+ .nav {
344
+ margin-bottom: 2rem;
345
+ }
346
+
347
+ .nav a {
348
+ margin: 0 1rem;
349
+ color: #42b883;
350
+ text-decoration: none;
351
+ }
352
+
353
+ .nav a:hover {
354
+ text-decoration: underline;
355
+ }
356
+ </style>
357
+ `;
358
+ } else {
359
+ appLyt = `<template>
360
+ <div class="app">
361
+ <h1>{{ title }}</h1>
362
+ <p>Welcome to your LytJS app!</p>
363
+ </div>
364
+ </template>
365
+
366
+ <script setup>
367
+ const title = 'Hello LytJS!';
368
+ </script>
369
+
370
+ <style scoped>
371
+ .app {
372
+ text-align: center;
373
+ padding: 2rem;
374
+ }
375
+
376
+ h1 {
377
+ color: #42b883;
378
+ }
379
+ </style>
380
+ `;
381
+ }
382
+ writeFile(path.join(targetDir, "src/App.lyt"), appLyt);
383
+ if (isRouter) {
384
+ const homePage = `<template>
385
+ <div class="home">
386
+ <h1>Home</h1>
387
+ ${isStore ? `
388
+ <p>Count: {{ count }}</p>
389
+ <button @click="increment">Increment</button>
390
+ <button @click="decrement">Decrement</button>
391
+ ` : ""}
392
+ <p>Welcome to the Home page!</p>
393
+ </div>
394
+ </template>
395
+
396
+ <script setup lang="ts">
397
+ ${isStore ? `import { useCounterStore } from '../stores/counter';
398
+ const counterStore = useCounterStore();
399
+ const { count, increment, decrement } = counterStore;
400
+ ` : ""}
401
+ </script>
402
+
403
+ <style scoped>
404
+ .home {
405
+ padding: 1rem;
406
+ }
407
+ </style>
408
+ `;
409
+ ensureDir(path.join(targetDir, "src", "pages"));
410
+ writeFile(path.join(targetDir, "src", "pages", "Home.lyt"), homePage);
411
+ const aboutPage = `<template>
412
+ <div class="about">
413
+ <h1>About</h1>
414
+ <p>This is the About page!</p>
415
+ </div>
416
+ </template>
417
+
418
+ <script setup lang="ts">
419
+ </script>
420
+
421
+ <style scoped>
422
+ .about {
423
+ padding: 1rem;
424
+ }
425
+ </style>
426
+ `;
427
+ writeFile(path.join(targetDir, "src", "pages", "About.lyt"), aboutPage);
428
+ }
429
+ if (isStore) {
430
+ const counterStore = `import { defineStore } from '@lytjs/store';
431
+ import { signal, computed } from '@lytjs/reactivity';
432
+
433
+ export const useCounterStore = defineStore('counter', () => {
434
+ // State
435
+ const count = signal(0);
436
+
437
+ // Getters
438
+ const doubleCount = computed(() => count.value * 2);
439
+
440
+ // Actions
441
+ function increment() {
442
+ count.value++;
443
+ }
444
+
445
+ function decrement() {
446
+ count.value--;
447
+ }
448
+
449
+ function reset() {
450
+ count.value = 0;
451
+ }
452
+
453
+ return {
454
+ count,
455
+ doubleCount,
456
+ increment,
457
+ decrement,
458
+ reset,
459
+ };
460
+ });
461
+ `;
462
+ ensureDir(path.join(targetDir, "src", "stores"));
463
+ writeFile(path.join(targetDir, "src", "stores", "counter.ts"), counterStore);
464
+ }
465
+ if (isSsr) {
466
+ const entryServer = `import { createSSRApp, h } from '@lytjs/core';
467
+ import { renderToString } from '@lytjs/ssr';
468
+ import App from './App.lyt';
469
+
470
+ export async function render(url: string) {
471
+ const app = createSSRApp({
472
+ render() {
473
+ return h(App);
474
+ }
475
+ });
476
+
477
+ const html = await renderToString(app);
478
+ return html;
479
+ }
480
+ `;
481
+ writeFile(path.join(targetDir, "src/entry-server.ts"), entryServer);
482
+ const entryClient = `import { createApp } from '@lytjs/core';
483
+ import App from './App.lyt';
484
+
485
+ const app = createApp(App);
486
+ app.mount('#app');
487
+ `;
488
+ writeFile(path.join(targetDir, "src/entry-client.ts"), entryClient);
489
+ const serverTs = `/**
490
+ * LytJS SSR Server
491
+ *
492
+ * Complete SSR server with Vite dev server and production build support.
493
+ * Supports streaming SSR, route prefetching, and static file serving.
494
+ */
495
+
496
+ import fs from 'fs';
497
+ import path from 'path';
498
+ import { fileURLToPath } from 'url';
499
+ import http from 'http';
500
+
501
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
502
+ const isProduction = process.env.NODE_ENV === 'production';
503
+ const DIST_DIR = path.join(__dirname, 'dist');
504
+ const PORT = parseInt(process.env.PORT || '3000', 10);
505
+
506
+ interface RenderOptions {
507
+ url: string;
508
+ template: string;
509
+ manifest?: Record<string, string[]>;
510
+ }
511
+
512
+ async function renderPage({ url, template, manifest }: RenderOptions): Promise<string> {
513
+ let app: any;
514
+ let vite: any;
515
+
516
+ if (!isProduction) {
517
+ const { createServer: createViteServer } = await import('vite');
518
+ vite = await createViteServer({
519
+ server: { middlewareMode: true },
520
+ appType: 'custom',
521
+ });
522
+ app = (await vite.ssrLoadModule(path.join(__dirname, 'src/entry-server.ts'))).default;
523
+ } else {
524
+ app = (await import(path.join(DIST_DIR, 'server/entry-server.js'))).default;
525
+ }
526
+
527
+ const html = await app.render(url);
528
+ return template.replace('<!--app-html-->', html);
529
+ }
530
+
531
+ async function createServer() {
532
+ let vite: any;
533
+
534
+ // Load index.html template
535
+ let template: string;
536
+
537
+ if (!isProduction) {
538
+ const { createServer: createViteServer } = await import('vite');
539
+ vite = await createViteServer({
540
+ server: { middlewareMode: true },
541
+ appType: 'custom',
542
+ });
543
+ template = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf-8');
544
+ } else {
545
+ template = fs.readFileSync(path.join(DIST_DIR, 'client/index.html'), 'utf-8');
546
+ }
547
+
548
+ const server = http.createServer(async (req, res) => {
549
+ const url = req.url || '/';
550
+
551
+ try {
552
+ if (!isProduction && url.startsWith('/@')) {
553
+ // Vite dev server requests
554
+ return;
555
+ }
556
+
557
+ // Static assets
558
+ if (url.startsWith('/assets/') || url.endsWith('.js') || url.endsWith('.css')) {
559
+ const filePath = isProduction
560
+ ? path.join(DIST_DIR, 'client', url)
561
+ : path.join(__dirname, url);
562
+
563
+ if (fs.existsSync(filePath)) {
564
+ const ext = path.extname(filePath);
565
+ const contentType = ext === '.css' ? 'text/css' : 'application/javascript';
566
+ res.writeHead(200, { 'Content-Type': contentType });
567
+ res.end(fs.readFileSync(filePath));
568
+ return;
569
+ }
570
+ }
571
+
572
+ // SSR rendering
573
+ const html = await renderPage({
574
+ url,
575
+ template,
576
+ manifest: isProduction
577
+ ? JSON.parse(fs.readFileSync(path.join(DIST_DIR, 'client/ssr-manifest.json'), 'utf-8'))
578
+ : undefined
579
+ });
580
+
581
+ res.writeHead(200, { 'Content-Type': 'text/html' });
582
+ res.end(html);
583
+ } catch (err: any) {
584
+ if (!isProduction && vite) {
585
+ vite.ssrFixStacktrace(err);
586
+ }
587
+ console.error('SSR Error:', err);
588
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
589
+ res.end('Internal Server Error');
590
+ }
591
+ });
592
+
593
+ server.listen(PORT, () => {
594
+ console.log(\`LytJS SSR server running at http://localhost:\${PORT}\`);
595
+ console.log(\`Mode: \${isProduction ? 'Production' : 'Development'}\`);
596
+ });
597
+ }
598
+
599
+ createServer().catch(console.error);
600
+ `;
601
+ writeFile(path.join(targetDir, "server.ts"), serverTs);
602
+ }
603
+ const tsConfig = {
604
+ compilerOptions: {
605
+ target: "ES2020",
606
+ useDefineForClassFields: true,
607
+ module: "ESNext",
608
+ lib: ["ES2020", "DOM", "DOM.Iterable"],
609
+ skipLibCheck: true,
610
+ moduleResolution: "bundler",
611
+ allowImportingTsExtensions: true,
612
+ resolveJsonModule: true,
613
+ isolatedModules: true,
614
+ noEmit: true,
615
+ strict: true,
616
+ noUnusedLocals: true,
617
+ noUnusedParameters: true,
618
+ noFallthroughCasesInSwitch: true
619
+ },
620
+ include: ["src/**/*.ts", "src/**/*.lyt"],
621
+ references: [{ path: "./tsconfig.node.json" }]
622
+ };
623
+ writeFile(path.join(targetDir, "tsconfig.json"), JSON.stringify(tsConfig, null, 2));
624
+ const tsConfigNode = {
625
+ compilerOptions: {
626
+ composite: true,
627
+ skipLibCheck: true,
628
+ module: "ESNext",
629
+ moduleResolution: "bundler",
630
+ allowSyntheticDefaultImports: true
631
+ },
632
+ include: ["vite.config.ts"]
633
+ };
634
+ writeFile(path.join(targetDir, "tsconfig.node.json"), JSON.stringify(tsConfigNode, null, 2));
635
+ const gitignore = `# Logs
636
+ logs
637
+ *.log
638
+ npm-debug.log*
639
+ yarn-debug.log*
640
+ yarn-error.log*
641
+ pnpm-debug.log*
642
+ lerna-debug.log*
643
+
644
+ node_modules
645
+ dist
646
+ dist-ssr
647
+ *.local
648
+
649
+ # Editor directories and files
650
+ .vscode/*
651
+ !.vscode/extensions.json
652
+ .idea
653
+ .DS_Store
654
+ *.suo
655
+ *.ntvs*
656
+ *.njsproj
657
+ *.sln
658
+ *.sw?
659
+ `;
660
+ writeFile(path.join(targetDir, ".gitignore"), gitignore);
661
+ }
662
+ function listTemplates() {
663
+ logger.bold("Available templates:");
664
+ for (const [name, description] of Object.entries(TEMPLATES)) {
665
+ logger.info(` ${name.padEnd(10)} - ${description}`);
666
+ }
667
+ }
668
+ async function dev(options = {}) {
669
+ if (!exists(path.join(process.cwd(), "package.json"))) {
670
+ logger.error("No package.json found. Are you in a LytJS project directory?");
671
+ process.exit(1);
672
+ }
673
+ const pm = detectPackageManager();
674
+ const runCmd = getRunCommand(pm, "dev");
675
+ logger.info(`Starting development server with ${pm}...`);
676
+ const devArgs = [];
677
+ if (options.port) devArgs.push("--port", String(options.port));
678
+ if (options.host) devArgs.push("--host", options.host);
679
+ if (options.open) devArgs.push("--open");
680
+ const cmdParts = runCmd.split(" ");
681
+ const cmd = cmdParts[0] ?? "pnpm";
682
+ const cmdArgs = [...cmdParts.slice(1), ...devArgs];
683
+ const child = child_process.spawn(cmd, cmdArgs, {
684
+ stdio: "inherit",
685
+ shell: true
686
+ });
687
+ child.on("error", (error) => {
688
+ logger.error(`Failed to start dev server: ${error.message}`);
689
+ process.exit(1);
690
+ });
691
+ child.on("exit", (code) => {
692
+ process.exit(code || 0);
693
+ });
694
+ }
695
+ async function build(options = {}) {
696
+ if (!exists(path.join(process.cwd(), "package.json"))) {
697
+ logger.error("No package.json found. Are you in a LytJS project directory?");
698
+ process.exit(1);
699
+ }
700
+ const pm = detectPackageManager();
701
+ logger.info("Building for production...");
702
+ const args = ["vite", "build"];
703
+ if (options.outDir) args.push("--outDir", options.outDir);
704
+ if (options.ssr) args.push("--ssr");
705
+ if (options.minify === false) args.push("--minify", "false");
706
+ const child = child_process.spawn(pm === "npm" ? "npx" : pm, args, {
707
+ stdio: "inherit",
708
+ shell: true
709
+ });
710
+ child.on("error", (error) => {
711
+ logger.error(`Build failed: ${error.message}`);
712
+ process.exit(1);
713
+ });
714
+ child.on("exit", (code) => {
715
+ if (code === 0) {
716
+ logger.success("Build completed successfully!");
717
+ } else {
718
+ logger.error(`Build failed with exit code ${code}`);
719
+ }
720
+ process.exit(code || 0);
721
+ });
722
+ }
723
+ async function test(options = {}) {
724
+ if (!exists(path.join(process.cwd(), "package.json"))) {
725
+ logger.error("No package.json found. Are you in a LytJS project directory?");
726
+ process.exit(1);
727
+ }
728
+ const pm = detectPackageManager();
729
+ logger.info("Running tests...");
730
+ const args = ["vitest"];
731
+ if (options.watch === false) args.push("run");
732
+ if (options.coverage) args.push("--coverage");
733
+ if (options.grep) args.push("--grep", options.grep);
734
+ const child = child_process.spawn(pm === "npm" ? "npx" : pm, args, {
735
+ stdio: "inherit",
736
+ shell: true
737
+ });
738
+ child.on("error", (error) => {
739
+ logger.error(`Tests failed: ${error.message}`);
740
+ process.exit(1);
741
+ });
742
+ child.on("exit", (code) => {
743
+ process.exit(code || 0);
744
+ });
745
+ }
746
+ var TEMPLATES2 = {
747
+ component(name, basePath) {
748
+ const filePath = path.join(basePath, `${name}.lyt`);
749
+ return [{
750
+ filePath,
751
+ content: `<template>
752
+ <div class="${name}">
753
+ <slot />
754
+ </div>
755
+ </template>
756
+
757
+ <script setup lang="ts">
758
+ defineProps<{
759
+ /** Component props */
760
+ }>();
761
+
762
+ defineEmits<{
763
+ /** Component events */
764
+ }>();
765
+ </script>
766
+
767
+ <style scoped>
768
+ .${name} {
769
+ /* styles */
770
+ }
771
+ </style>
772
+ `
773
+ }];
774
+ },
775
+ page(name, basePath) {
776
+ const pascalName = toPascalCase(name);
777
+ const filePath = path.join(basePath, `${name}.lyt`);
778
+ return [{
779
+ filePath,
780
+ content: `<template>
781
+ <div class="page-${name}">
782
+ <h1>${pascalName}</h1>
783
+ </div>
784
+ </template>
785
+
786
+ <script setup lang="ts">
787
+ // Page logic here
788
+ </script>
789
+
790
+ <style scoped>
791
+ .page-${name} {
792
+ padding: 1rem;
793
+ }
794
+ </style>
795
+ `
796
+ }];
797
+ },
798
+ store(name, basePath) {
799
+ const filePath = path.join(basePath, `${name}.ts`);
800
+ return [{
801
+ filePath,
802
+ content: `import { defineStore } from '@lytjs/store';
803
+ import { signal, computed } from '@lytjs/reactivity';
804
+
805
+ export const use${toPascalCase(name)}Store = defineStore('${name}', () => {
806
+ // State
807
+ const count = signal(0);
808
+
809
+ // Getters
810
+ const doubleCount = computed(() => count.value * 2);
811
+
812
+ // Actions
813
+ function increment() {
814
+ count.value++;
815
+ }
816
+
817
+ function decrement() {
818
+ count.value--;
819
+ }
820
+
821
+ function reset() {
822
+ count.value = 0;
823
+ }
824
+
825
+ return {
826
+ count,
827
+ doubleCount,
828
+ increment,
829
+ decrement,
830
+ reset,
831
+ };
832
+ });
833
+ `
834
+ }];
835
+ },
836
+ directive(name, basePath) {
837
+ const filePath = path.join(basePath, `${name}.ts`);
838
+ const camelCaseName = toCamelCase(name);
839
+ return [{
840
+ filePath,
841
+ content: `import type { Directive } from '@lytjs/core';
842
+
843
+ /**
844
+ * ${toPascalCase(name)} Directive
845
+ *
846
+ * @example
847
+ * \`\`\`vue
848
+ * <div v-${camelCaseName} />
849
+ * \`\`\`
850
+ */
851
+ export const v${toPascalCase(name)}: Directive = {
852
+ mounted(el, binding) {
853
+ // Directive mounted
854
+ },
855
+
856
+ updated(el, binding) {
857
+ // Directive updated
858
+ },
859
+
860
+ unmounted(el) {
861
+ // Directive unmounted
862
+ },
863
+ };
864
+ `
865
+ }];
866
+ },
867
+ composable(name, basePath) {
868
+ const filePath = path.join(basePath, `use${toPascalCase(name)}.ts`);
869
+ return [{
870
+ filePath,
871
+ content: `import { signal, computed } from '@lytjs/reactivity';
872
+
873
+ /**
874
+ * ${toPascalCase(name)} Composable
875
+ *
876
+ * @example
877
+ * \`\`\`typescript
878
+ * const { state, actions } = use${toPascalCase(name)}();
879
+ * \`\`\`
880
+ */
881
+ export function use${toPascalCase(name)}() {
882
+ // State
883
+ const isLoading = signal(false);
884
+ const error = signal<Error | null>(null);
885
+ const data = signal<any>(null);
886
+
887
+ // Computed
888
+ const hasData = computed(() => data.value !== null);
889
+
890
+ // Actions
891
+ async function fetch() {
892
+ isLoading.value = true;
893
+ error.value = null;
894
+ try {
895
+ // TODO: Fetch logic here
896
+ // data.value = await someApi();
897
+ } catch (e) {
898
+ error.value = e as Error;
899
+ } finally {
900
+ isLoading.value = false;
901
+ }
902
+ }
903
+
904
+ function reset() {
905
+ isLoading.value = false;
906
+ error.value = null;
907
+ data.value = null;
908
+ }
909
+
910
+ return {
911
+ isLoading,
912
+ error,
913
+ data,
914
+ hasData,
915
+ fetch,
916
+ reset,
917
+ };
918
+ }
919
+ `
920
+ }];
921
+ },
922
+ hook(name, basePath) {
923
+ const filePath = path.join(basePath, `use${toPascalCase(name)}.ts`);
924
+ return [{
925
+ filePath,
926
+ content: `import { signal, onMounted, onUnmounted } from '@lytjs/core';
927
+
928
+ /**
929
+ * ${toPascalCase(name)} Hook
930
+ */
931
+ export function use${toPascalCase(name)}() {
932
+ const state = signal(null);
933
+
934
+ onMounted(() => {
935
+ // Setup code on mount
936
+ });
937
+
938
+ onUnmounted(() => {
939
+ // Cleanup on unmount
940
+ });
941
+
942
+ return {
943
+ state,
944
+ };
945
+ }
946
+ `
947
+ }];
948
+ },
949
+ util(name, basePath) {
950
+ const filePath = path.join(basePath, `${name}.ts`);
951
+ return [{
952
+ filePath,
953
+ content: `/**
954
+ * ${toPascalCase(name)} Utility Functions
955
+ */
956
+
957
+ /**
958
+ * ${toPascalCase(name)} function
959
+ *
960
+ * @param input - The input value
961
+ * @returns The processed result
962
+ */
963
+ export function ${toCamelCase(name)}(input: any) {
964
+ // TODO: Implement function
965
+ return input;
966
+ }
967
+ `
968
+ }];
969
+ },
970
+ middleware(name, basePath) {
971
+ const filePath = path.join(basePath, `${name}.ts`);
972
+ return [{
973
+ filePath,
974
+ content: `import type { NavigationGuard } from '@lytjs/router';
975
+
976
+ /**
977
+ * ${toPascalCase(name)} Middleware
978
+ */
979
+ export const ${toCamelCase(name)}Middleware: NavigationGuard = (to, from, next) => {
980
+ // Middleware logic
981
+ console.log('Middleware:', to.path);
982
+ next();
983
+ };
984
+ `
985
+ }];
986
+ }
987
+ };
988
+ function toPascalCase(str) {
989
+ return str.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
990
+ }
991
+ function toCamelCase(str) {
992
+ const pascalCase = toPascalCase(str);
993
+ return pascalCase.charAt(0).toLowerCase() + pascalCase.slice(1);
994
+ }
995
+ function resolveTargetDir(type) {
996
+ const cwd = process.cwd();
997
+ switch (type) {
998
+ case "component":
999
+ return path.join(cwd, "src", "components");
1000
+ case "page":
1001
+ return path.join(cwd, "src", "pages");
1002
+ case "store":
1003
+ return path.join(cwd, "src", "stores");
1004
+ case "directive":
1005
+ return path.join(cwd, "src", "directives");
1006
+ case "composable":
1007
+ return path.join(cwd, "src", "composables");
1008
+ case "util":
1009
+ return path.join(cwd, "src", "utils");
1010
+ case "middleware":
1011
+ return path.join(cwd, "src", "middleware");
1012
+ case "hook":
1013
+ return path.join(cwd, "src", "hooks");
1014
+ }
1015
+ }
1016
+ async function add(type, name, options = {}) {
1017
+ const targetDir = resolveTargetDir(type);
1018
+ const fullPath = path.resolve(targetDir);
1019
+ if (!exists(path.join(process.cwd(), "package.json"))) {
1020
+ logger.error("No package.json found. Are you in a LytJS project directory?");
1021
+ process.exit(1);
1022
+ }
1023
+ const template = TEMPLATES2[type];
1024
+ if (!template) {
1025
+ logger.error(`Unknown type: ${type}. Supported types: component, page, store`);
1026
+ process.exit(1);
1027
+ }
1028
+ const files = template(name, fullPath);
1029
+ for (const file of files) {
1030
+ if (exists(file.filePath) && !options.force) {
1031
+ logger.warning(`File already exists: ${file.filePath}`);
1032
+ logger.info("Use --force to overwrite.");
1033
+ continue;
1034
+ }
1035
+ ensureDir(path.resolve(file.filePath, ".."));
1036
+ writeFile(file.filePath, file.content);
1037
+ logger.success(`Created ${type}: ${file.filePath}`);
1038
+ }
1039
+ }
1040
+ var TEMPLATES3 = {
1041
+ component: (data, withStyles, withTest, template, lang) => {
1042
+ const styleImport = withStyles ? `
1043
+ import './${data.kebabName}.styles.css';` : "";
1044
+ const tsOnly = lang === "ts";
1045
+ if (template === "sfc") {
1046
+ return `<template>
1047
+ <div class="${data.kebabName}">
1048
+ <slot>
1049
+ ${data.pascalName} Component
1050
+ </slot>
1051
+ </div>
1052
+ </template>
1053
+
1054
+ <script setup${tsOnly ? ' lang="ts"' : ""}>
1055
+ ${tsOnly ? `import { ref } from '@lytjs/reactivity';
1056
+ ` : ""}
1057
+ ${tsOnly ? `
1058
+ export interface ${data.pascalName}Props {
1059
+ className?: string;
1060
+ }
1061
+
1062
+ const props = defineProps<${data.pascalName}Props>();
1063
+ ` : ""}
1064
+
1065
+ const title = ref('${data.pascalName}');
1066
+ </script>
1067
+
1068
+ <style scoped>
1069
+ .${data.kebabName} {
1070
+ /* Component styles */
1071
+ }
1072
+ </style>
1073
+ `;
1074
+ }
1075
+ const testImport = withTest ? `
1076
+ import { describe, it, expect } from 'vitest';
1077
+ import { ${data.pascalName} } from './${data.kebabName}';
1078
+
1079
+ describe('${data.pascalName}', () => {
1080
+ it('should render', () => {
1081
+ // Add test here
1082
+ expect(true).toBe(true);
1083
+ });
1084
+ });` : "";
1085
+ const propsDecl = tsOnly ? `['className', 'children']` : `[]`;
1086
+ return `/**
1087
+ * ${data.pascalName} \u7EC4\u4EF6
1088
+ *
1089
+ * @description ${data.description}
1090
+ * @created ${data.date}
1091
+ */
1092
+
1093
+ import { h, defineComponent } from '@lytjs/core';${styleImport}
1094
+
1095
+ ${tsOnly ? `export interface ${data.pascalName}Props {
1096
+ className?: string;
1097
+ children?: any;
1098
+ }
1099
+
1100
+ ` : ""}${template === "functional" ? `export function ${data.pascalName}(${tsOnly ? `props: ${data.pascalName}Props` : "props"}) {
1101
+ const { className = '', children } = props;
1102
+
1103
+ return (
1104
+ <div className={\`${data.kebabName} \${className}\`}>
1105
+ {children || '${data.pascalName} Component'}
1106
+ </div>
1107
+ );
1108
+ }` : `export const ${data.pascalName} = defineComponent({
1109
+ name: '${data.pascalName}',
1110
+ props: ${propsDecl},
1111
+ setup(props) {
1112
+ const { className = '', children } = props;
1113
+
1114
+ return () => (
1115
+ <div className={\`${data.kebabName} \${className}\`}>
1116
+ {children || '${data.pascalName} Component'}
1117
+ </div>
1118
+ );
1119
+ },
1120
+ });`}
1121
+
1122
+ export default ${data.pascalName};${testImport}
1123
+ `;
1124
+ },
1125
+ page: (data, withStyles, withTest, template, lang) => {
1126
+ const styleImport = withStyles ? `
1127
+ import './${data.kebabName}.styles.css';` : "";
1128
+ const tsOnly = lang === "ts";
1129
+ if (template === "sfc") {
1130
+ return `<template>
1131
+ <div class="${data.kebabName}-page">
1132
+ <h1>{title}</h1>
1133
+ <p>Page content for ${data.pascalName}</p>
1134
+ <slot />
1135
+ </div>
1136
+ </template>
1137
+
1138
+ <script setup${tsOnly ? ' lang="ts"' : ""}>
1139
+ ${tsOnly ? `import { ref } from '@lytjs/reactivity';
1140
+ ` : ""}
1141
+ ${tsOnly ? `
1142
+ export interface ${data.pascalName}PageProps {
1143
+ title?: string;
1144
+ }
1145
+
1146
+ const props = defineProps<${data.pascalName}PageProps>();
1147
+ ` : ""}
1148
+
1149
+ const title = ref(props.title || '${data.pascalName}');
1150
+ </script>
1151
+
1152
+ <style scoped>
1153
+ .${data.kebabName}-page {
1154
+ padding: 2rem;
1155
+ }
1156
+ </style>
1157
+ `;
1158
+ }
1159
+ const testImport = withTest ? `
1160
+ import { describe, it, expect } from 'vitest';
1161
+ import { ${data.pascalName}Page } from './${data.kebabName}';
1162
+
1163
+ describe('${data.pascalName}Page', () => {
1164
+ it('should render', () => {
1165
+ // Add test here
1166
+ expect(true).toBe(true);
1167
+ });
1168
+ });` : "";
1169
+ return `/**
1170
+ * ${data.pascalName} \u9875\u9762
1171
+ *
1172
+ * @description ${data.description}
1173
+ * @created ${data.date}
1174
+ */
1175
+
1176
+ import { h, ${tsOnly ? "signal" : "signal"} } from '@lytjs/core';
1177
+ ${styleImport}
1178
+
1179
+ ${tsOnly ? `export interface ${data.pascalName}PageProps {
1180
+ title?: string;
1181
+ }
1182
+
1183
+ ` : ""}export function ${data.pascalName}Page(${tsOnly ? `props: ${data.pascalName}PageProps` : "props"}) {
1184
+ const { title = '${data.pascalName}' } = props;
1185
+
1186
+ return (
1187
+ <div className="${data.kebabName}-page">
1188
+ <h1>{title}</h1>
1189
+ <p>Page content for ${data.pascalName}</p>
1190
+ </div>
1191
+ );
1192
+ }
1193
+
1194
+ export default ${data.pascalName}Page;${testImport}
1195
+ `;
1196
+ },
1197
+ service: (data, _withStyles, _withTest, _template, lang) => {
1198
+ const tsOnly = lang === "ts";
1199
+ return `/**
1200
+ * ${data.pascalName} \u670D\u52A1
1201
+ *
1202
+ * @description ${data.description}
1203
+ * @created ${data.date}
1204
+ */
1205
+
1206
+ ${tsOnly ? `export interface ${data.pascalName}ServiceOptions {
1207
+ baseUrl?: string;
1208
+ timeout?: number;
1209
+ }
1210
+
1211
+ ` : ""}${tsOnly ? `export class ${data.pascalName}Service {
1212
+ private baseUrl: string;
1213
+ private timeout: number;
1214
+ ` : `export class ${data.pascalName}Service {
1215
+ `}
1216
+ constructor(${tsOnly ? `options: ${data.pascalName}ServiceOptions = {}` : "options = {}"}) {
1217
+ this.baseUrl = options.baseUrl || '/api';
1218
+ this.timeout = options.timeout || 30000;
1219
+ }
1220
+
1221
+ async getAll()${tsOnly ? ": Promise<any[]>" : ""} {
1222
+ const response = await fetch(\`\${this.baseUrl}/${data.kebabName}s\`, {
1223
+ method: 'GET',
1224
+ headers: { 'Content-Type': 'application/json' },
1225
+ signal: AbortSignal.timeout(this.timeout),
1226
+ });
1227
+ return response.json();
1228
+ }
1229
+
1230
+ async getById(id)${tsOnly ? ": Promise<any>" : ""} {
1231
+ const response = await fetch(\`\${this.baseUrl}/${data.kebabName}s/\${id}\`, {
1232
+ method: 'GET',
1233
+ headers: { 'Content-Type': 'application/json' },
1234
+ signal: AbortSignal.timeout(this.timeout),
1235
+ });
1236
+ return response.json();
1237
+ }
1238
+
1239
+ async create(${tsOnly ? "data: any" : "data"})${tsOnly ? ": Promise<any>" : ""} {
1240
+ const response = await fetch(\`\${this.baseUrl}/${data.kebabName}s\`, {
1241
+ method: 'POST',
1242
+ headers: { 'Content-Type': 'application/json' },
1243
+ body: JSON.stringify(data),
1244
+ signal: AbortSignal.timeout(this.timeout),
1245
+ });
1246
+ return response.json();
1247
+ }
1248
+
1249
+ async update(id)${tsOnly ? ": Promise<any>" : ""} {
1250
+ const response = await fetch(\`\${this.baseUrl}/${data.kebabName}s/\${id}\`, {
1251
+ method: 'PUT',
1252
+ headers: { 'Content-Type': 'application/json' },
1253
+ body: JSON.stringify(data),
1254
+ signal: AbortSignal.timeout(this.timeout),
1255
+ });
1256
+ return response.json();
1257
+ }
1258
+
1259
+ async delete(id)${tsOnly ? ": Promise<void>" : ""} {
1260
+ await fetch(\`\${this.baseUrl}/${data.kebabName}s/\${id}\`, {
1261
+ method: 'DELETE',
1262
+ signal: AbortSignal.timeout(this.timeout),
1263
+ });
1264
+ }
1265
+ }
1266
+
1267
+ export default ${data.pascalName}Service;
1268
+ `;
1269
+ },
1270
+ hook: (data, _withStyles, _withTest, _template, lang) => {
1271
+ const tsOnly = lang === "ts";
1272
+ return `/**
1273
+ * ${data.pascalName} Hook
1274
+ *
1275
+ * @description ${data.description}
1276
+ * @created ${data.date}
1277
+ */
1278
+
1279
+ import { signal, effect } from '@lytjs/reactivity';
1280
+
1281
+ ${tsOnly ? `export interface ${data.pascalName}Options {
1282
+ immediate?: boolean;
1283
+ }
1284
+
1285
+ export interface ${data.pascalName}Return {
1286
+ data: ReturnType<typeof signal>;
1287
+ loading: ReturnType<typeof signal>;
1288
+ error: ReturnType<typeof signal>;
1289
+ execute: () => Promise<void>;
1290
+ reset: () => void;
1291
+ }
1292
+
1293
+ ` : ""}export function use${data.pascalName}(${tsOnly ? `options: ${data.pascalName}Options = {}` : "options = {}"})${tsOnly ? `: ${data.pascalName}Return` : ""} {
1294
+ const { immediate = false } = options;
1295
+
1296
+ const data = signal<any>(null);
1297
+ const loading = signal(false);
1298
+ const error = signal<Error | null>(null);
1299
+
1300
+ async function execute() {
1301
+ loading.value = true;
1302
+ error.value = null;
1303
+
1304
+ try {
1305
+ const result = await new Promise(resolve => setTimeout(() => resolve(null), 100));
1306
+ data.value = result;
1307
+ } catch (e) {
1308
+ error.value = e as Error;
1309
+ } finally {
1310
+ loading.value = false;
1311
+ }
1312
+ }
1313
+
1314
+ function reset() {
1315
+ data.value = null;
1316
+ loading.value = false;
1317
+ error.value = null;
1318
+ }
1319
+
1320
+ if (immediate) {
1321
+ execute();
1322
+ }
1323
+
1324
+ return {
1325
+ data,
1326
+ loading,
1327
+ error,
1328
+ execute,
1329
+ reset,
1330
+ };
1331
+ }
1332
+
1333
+ export default use${data.pascalName};
1334
+ `;
1335
+ },
1336
+ store: (data, _withStyles, _withTest, _template, lang) => {
1337
+ const tsOnly = lang === "ts";
1338
+ return `/**
1339
+ * ${data.pascalName} Store
1340
+ *
1341
+ * @description ${data.description}
1342
+ * @created ${data.date}
1343
+ */
1344
+
1345
+ import { signal, computed } from '@lytjs/reactivity';
1346
+
1347
+ ${tsOnly ? `export interface ${data.pascalName}State {
1348
+ items: any[];
1349
+ selectedId: string | null;
1350
+ loading: boolean;
1351
+ error: Error | null;
1352
+ }
1353
+
1354
+ ` : ""}export function create${data.pascalName}Store() {
1355
+ const state = signal${tsOnly ? `<${data.pascalName}State>` : ""}({
1356
+ items: [],
1357
+ selectedId: null,
1358
+ loading: false,
1359
+ error: null,
1360
+ });
1361
+
1362
+ const selectedItem = computed(() => {
1363
+ const currentState = state.value;
1364
+ return currentState.items.find(item => item.id === currentState.selectedId);
1365
+ });
1366
+
1367
+ const itemCount = computed(() => state.value.items.length);
1368
+
1369
+ function setItems(items) {
1370
+ state.value = { ...state.value, items };
1371
+ }
1372
+
1373
+ function selectItem(id) {
1374
+ state.value = { ...state.value, selectedId: id };
1375
+ }
1376
+
1377
+ function addItem(item) {
1378
+ state.value = {
1379
+ ...state.value,
1380
+ items: [...state.value.items, item],
1381
+ };
1382
+ }
1383
+
1384
+ function updateItem(id, updates) {
1385
+ state.value = {
1386
+ ...state.value,
1387
+ items: state.value.items.map(item =>
1388
+ item.id === id ? { ...item, ...updates } : item
1389
+ ),
1390
+ };
1391
+ }
1392
+
1393
+ function removeItem(id) {
1394
+ state.value = {
1395
+ ...state.value,
1396
+ items: state.value.items.filter(item => item.id !== id),
1397
+ selectedId: state.value.selectedId === id ? null : state.value.selectedId,
1398
+ };
1399
+ }
1400
+
1401
+ function setLoading(loading) {
1402
+ state.value = { ...state.value, loading };
1403
+ }
1404
+
1405
+ function setError(error) {
1406
+ state.value = { ...state.value, error };
1407
+ }
1408
+
1409
+ function reset() {
1410
+ state.value = {
1411
+ items: [],
1412
+ selectedId: null,
1413
+ loading: false,
1414
+ error: null,
1415
+ };
1416
+ }
1417
+
1418
+ return {
1419
+ state,
1420
+ selectedItem,
1421
+ itemCount,
1422
+ setItems,
1423
+ selectItem,
1424
+ addItem,
1425
+ updateItem,
1426
+ removeItem,
1427
+ setLoading,
1428
+ setError,
1429
+ reset,
1430
+ };
1431
+ }
1432
+
1433
+ ${tsOnly ? `export type ${data.pascalName}Store = ReturnType<typeof create${data.pascalName}Store>;
1434
+ ` : ""}export default create${data.pascalName}Store;
1435
+ `;
1436
+ },
1437
+ layout: (data, withStyles, _withTest, _template, lang) => {
1438
+ const tsOnly = lang === "ts";
1439
+ const styleImport = withStyles ? `
1440
+ import './${data.kebabName}.styles.css';` : "";
1441
+ return `/**
1442
+ * ${data.pascalName} \u5E03\u5C40
1443
+ *
1444
+ * @description ${data.description}
1445
+ * @created ${data.date}
1446
+ */
1447
+
1448
+ import { h, defineComponent } from '@lytjs/core';${styleImport}
1449
+
1450
+ ${tsOnly ? `export interface ${data.pascalName}LayoutProps {
1451
+ children?: any;
1452
+ }
1453
+
1454
+ ` : ""}export const ${data.pascalName}Layout = defineComponent({
1455
+ name: '${data.pascalName}Layout',
1456
+ setup(props) {
1457
+ return () => (
1458
+ <div className="${data.kebabName}-layout">
1459
+ <header className="${data.kebabName}-header">
1460
+ <slot name="header">
1461
+ <h1>${data.pascalName}</h1>
1462
+ </slot>
1463
+ </header>
1464
+ <main className="${data.kebabName}-main">
1465
+ <slot />
1466
+ </main>
1467
+ <footer className="${data.kebabName}-footer">
1468
+ <slot name="footer" />
1469
+ </footer>
1470
+ </div>
1471
+ );
1472
+ },
1473
+ });
1474
+
1475
+ export default ${data.pascalName}Layout;
1476
+ `;
1477
+ },
1478
+ middleware: (data, _withStyles, _withTest, _template, lang) => {
1479
+ const tsOnly = lang === "ts";
1480
+ return `/**
1481
+ * ${data.pascalName} \u4E2D\u95F4\u4EF6
1482
+ *
1483
+ * @description ${data.description}
1484
+ * @created ${data.date}
1485
+ */
1486
+
1487
+ ${tsOnly ? `import type { Request, Response, NextFunction } from 'express';
1488
+ ` : ""}
1489
+ export function ${data.camelName}Middleware(${tsOnly ? `req: Request, res: Response, next: NextFunction` : "req, res, next"}) {
1490
+ try {
1491
+ console.log('[${data.pascalName}] Middleware executed');
1492
+ next();
1493
+ } catch (error) {
1494
+ next(error);
1495
+ }
1496
+ }
1497
+
1498
+ export default ${data.camelName}Middleware;
1499
+ `;
1500
+ }
1501
+ };
1502
+ function toPascalCase2(name) {
1503
+ return name.split(/[-_]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
1504
+ }
1505
+ function toCamelCase2(name) {
1506
+ const pascal = toPascalCase2(name);
1507
+ return pascal.charAt(0).toLowerCase() + pascal.slice(1);
1508
+ }
1509
+ function toKebabCase(name) {
1510
+ return name.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
1511
+ }
1512
+ async function generate(options) {
1513
+ const {
1514
+ type,
1515
+ name,
1516
+ path: basePath = "./src",
1517
+ withStyles = false,
1518
+ withTest = false,
1519
+ description = "",
1520
+ template = "default",
1521
+ language = "ts"
1522
+ } = options;
1523
+ const templateData = {
1524
+ name,
1525
+ pascalName: toPascalCase2(name),
1526
+ kebabName: toKebabCase(name),
1527
+ camelName: toCamelCase2(name),
1528
+ date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
1529
+ description: description || `${toPascalCase2(name)} ${type}`
1530
+ };
1531
+ const typeDirs = {
1532
+ component: "components",
1533
+ page: "pages",
1534
+ service: "services",
1535
+ hook: "hooks",
1536
+ store: "stores",
1537
+ layout: "layouts",
1538
+ middleware: "middleware"
1539
+ };
1540
+ const targetDir = path__namespace.join(
1541
+ process.cwd(),
1542
+ basePath,
1543
+ typeDirs[type] || "components"
1544
+ );
1545
+ await ensureDir(targetDir);
1546
+ const templateFn = TEMPLATES3[type];
1547
+ if (!templateFn) {
1548
+ logger.error(`Unknown type: ${type}`);
1549
+ logger.info("Available types: component, page, service, hook, store, layout, middleware");
1550
+ process.exit(1);
1551
+ }
1552
+ const extension = template === "sfc" ? "lyt" : language;
1553
+ const filename = `${templateData.kebabName}${type === "page" ? ".page" : ""}.${extension}`;
1554
+ const filePath = path__namespace.join(targetDir, filename);
1555
+ const content = templateFn(templateData, withStyles, withTest, template, language);
1556
+ await writeFile(filePath, content);
1557
+ logger.success(`Generated ${type}: ${filePath}`);
1558
+ if (withStyles && template !== "sfc") {
1559
+ const styleContent = `/**
1560
+ * ${templateData.pascalName} Styles
1561
+ */
1562
+
1563
+ .${templateData.kebabName} {
1564
+ /* Component styles */
1565
+ }
1566
+ `;
1567
+ const stylePath = path__namespace.join(targetDir, `${templateData.kebabName}.styles.css`);
1568
+ await writeFile(stylePath, styleContent);
1569
+ logger.success(`Generated styles: ${stylePath}`);
1570
+ }
1571
+ if (withTest && template !== "sfc") {
1572
+ logger.info("Test file included in generated component");
1573
+ }
1574
+ logger.info("\nNext steps:");
1575
+ logger.info(` cd ${targetDir}`);
1576
+ logger.info(` Import your ${type}: import { ${template === "sfc" ? "default" : templateData.pascalName} } from './${templateData.kebabName}'`);
1577
+ logger.info("\nAvailable options:");
1578
+ logger.info(" --template=sfc : Single File Component (.lyt)");
1579
+ logger.info(" --template=functional : Functional component");
1580
+ logger.info(" --language=js : JavaScript output");
1581
+ }
1582
+ var PLUGIN_TEMPLATES = {
1583
+ default: "Default plugin template with TypeScript",
1584
+ minimal: "Minimal plugin without extra dependencies",
1585
+ withConfig: "Plugin template with configuration schema"
1586
+ };
1587
+ function getTemplateContent(template, pluginName) {
1588
+ const packageName = `@lytjs/plugin-${pluginName}`;
1589
+ const files = {};
1590
+ files["package.json"] = JSON.stringify({
1591
+ name: packageName,
1592
+ version: "0.1.0",
1593
+ description: `LytJS plugin: ${pluginName}`,
1594
+ main: "dist/index.cjs",
1595
+ module: "dist/index.mjs",
1596
+ types: "dist/index.d.ts",
1597
+ exports: {
1598
+ ".": {
1599
+ import: "./dist/index.mjs",
1600
+ require: "./dist/index.cjs",
1601
+ types: "./dist/index.d.ts"
1602
+ }
1603
+ },
1604
+ files: ["dist"],
1605
+ scripts: {
1606
+ build: "tsup",
1607
+ dev: "tsup --watch",
1608
+ test: "vitest",
1609
+ lint: "eslint src",
1610
+ "prepublishOnly": "npm run build"
1611
+ },
1612
+ keywords: ["lytjs", "plugin"],
1613
+ license: "MIT",
1614
+ peerDependencies: {
1615
+ "@lytjs/core": ">=6.0.0"
1616
+ }
1617
+ }, null, 2);
1618
+ files["tsconfig.json"] = JSON.stringify({
1619
+ extends: "@lytjs/core/tsconfig.json",
1620
+ compilerOptions: {
1621
+ outDir: "./dist",
1622
+ rootDir: "./src",
1623
+ declaration: true,
1624
+ declarationMap: true
1625
+ },
1626
+ include: ["src"],
1627
+ exclude: ["node_modules", "dist", "tests"]
1628
+ }, null, 2);
1629
+ files["tsup.config.ts"] = `import { defineConfig } from 'tsup';
1630
+
1631
+ export default defineConfig({
1632
+ entry: { index: 'src/index.ts' },
1633
+ format: ['esm', 'cjs'],
1634
+ dts: true,
1635
+ sourcemap: true,
1636
+ clean: true,
1637
+ splitting: false,
1638
+ treeshake: true,
1639
+ minify: false,
1640
+ external: ['@lytjs/core'],
1641
+ });
1642
+ `;
1643
+ if (template === "withConfig") {
1644
+ files["src/index.ts"] = `/**
1645
+ * @lytjs/plugin-${pluginName}
1646
+ *
1647
+ * A LytJS plugin with configuration schema support.
1648
+ */
1649
+
1650
+ import { definePlugin } from '@lytjs/core';
1651
+ import type { ConfigSchema } from '@lytjs/core';
1652
+
1653
+ /**
1654
+ * Plugin options schema
1655
+ */
1656
+ const optionsSchema: ConfigSchema<${pluginName.replace(/-/g, "")}Options> = {
1657
+ type: 'object',
1658
+ properties: {
1659
+ debug: {
1660
+ type: 'boolean',
1661
+ description: 'Enable debug mode',
1662
+ default: false,
1663
+ },
1664
+ option1: {
1665
+ type: 'string',
1666
+ description: 'First option',
1667
+ default: 'default value',
1668
+ },
1669
+ },
1670
+ additionalProperties: false,
1671
+ };
1672
+
1673
+ export interface ${pluginName.replace(/-/g, "")}Options {
1674
+ debug?: boolean;
1675
+ option1?: string;
1676
+ }
1677
+
1678
+ /**
1679
+ * Create the plugin with configuration schema
1680
+ */
1681
+ export function create${pluginName.replace(/-/g, "").replace(/^\w/, (c) => c.toUpperCase())}(options?: ${pluginName.replace(/-/g, "")}Options) {
1682
+ return definePlugin({
1683
+ name: '${packageName}',
1684
+ version: '0.1.0',
1685
+ description: 'A LytJS plugin',
1686
+ schema: optionsSchema,
1687
+ install: (app, opts) => {
1688
+ const config = opts || {};
1689
+ console.log('[${packageName}] Installing with config:', config);
1690
+ },
1691
+ });
1692
+ }
1693
+
1694
+ /**
1695
+ * Direct plugin export (without schema)
1696
+ */
1697
+ export default create${pluginName.replace(/-/g, "").replace(/^\w/, (c) => c.toUpperCase())}();
1698
+ `;
1699
+ } else {
1700
+ files["src/index.ts"] = `/**
1701
+ * @lytjs/plugin-${pluginName}
1702
+ *
1703
+ * A LytJS plugin.
1704
+ */
1705
+
1706
+ import { definePlugin } from '@lytjs/core';
1707
+
1708
+ /**
1709
+ * Create the plugin
1710
+ */
1711
+ export function create${pluginName.replace(/-/g, "").replace(/^\w/, (c) => c.toUpperCase())}() {
1712
+ return definePlugin({
1713
+ name: '${packageName}',
1714
+ version: '0.1.0',
1715
+ description: 'A LytJS plugin',
1716
+ install: (app) => {
1717
+ console.log('[${packageName}] Plugin installed');
1718
+ },
1719
+ });
1720
+ }
1721
+
1722
+ /**
1723
+ * Direct plugin export
1724
+ */
1725
+ export default create${pluginName.replace(/-/g, "").replace(/^\w/, (c) => c.toUpperCase())}();
1726
+ `;
1727
+ }
1728
+ if (template === "minimal") {
1729
+ files["src/types.ts"] = `/**
1730
+ * Plugin types
1731
+ */
1732
+
1733
+ export interface PluginOptions {
1734
+ // Define your plugin options here
1735
+ }
1736
+ `;
1737
+ }
1738
+ files["README.md"] = `# @lytjs/plugin-${pluginName}
1739
+
1740
+ A LytJS plugin.
1741
+
1742
+ ## Installation
1743
+
1744
+ \`\`\`bash
1745
+ npm install @lytjs/plugin-${pluginName}
1746
+ \`\`\`
1747
+
1748
+ ## Usage
1749
+
1750
+ \`\`\`typescript
1751
+ import { createApp } from '@lytjs/core';
1752
+ import myPlugin from '@lytjs/plugin-${pluginName}';
1753
+
1754
+ const app = createApp(App);
1755
+ app.use(myPlugin);
1756
+ \`\`\`
1757
+
1758
+ ## API
1759
+
1760
+ ### createPlugin(options?)
1761
+
1762
+ Create the plugin with options.
1763
+
1764
+ ## License
1765
+
1766
+ MIT
1767
+ `;
1768
+ files[".gitignore"] = `# Logs
1769
+ logs
1770
+ *.log
1771
+ npm-debug.log*
1772
+ yarn-debug.log*
1773
+ pnpm-debug.log*
1774
+
1775
+ node_modules
1776
+ dist
1777
+ *.local
1778
+
1779
+ # IDE
1780
+ .vscode
1781
+ .idea
1782
+ *.sw?
1783
+ `;
1784
+ return files;
1785
+ }
1786
+ async function createPlugin(name, options = {}) {
1787
+ const targetDir = path.resolve(process.cwd(), name);
1788
+ const template = options.template || "default";
1789
+ if (template !== "default" && template !== "minimal" && template !== "withConfig") {
1790
+ logger.error(`Unknown template: ${template}`);
1791
+ logger.info("Available templates: default, minimal, withConfig");
1792
+ process.exit(1);
1793
+ }
1794
+ if (fs.existsSync(targetDir) && !isEmptyDir2(targetDir) && !options.force) {
1795
+ logger.error(`Directory "${name}" already exists and is not empty.`);
1796
+ logger.info("Use --force to overwrite.");
1797
+ process.exit(1);
1798
+ }
1799
+ logger.info(`Creating a new LytJS plugin in ${targetDir}...`);
1800
+ ensureDir(targetDir);
1801
+ const files = getTemplateContent(template, name);
1802
+ for (const [filePath, content] of Object.entries(files)) {
1803
+ const fullPath = path.join(targetDir, filePath);
1804
+ const fileDir = path.resolve(fullPath, "..");
1805
+ if (!fs.existsSync(fileDir)) {
1806
+ fs.mkdirSync(fileDir, { recursive: true });
1807
+ }
1808
+ fs.writeFileSync(fullPath, content, "utf-8");
1809
+ logger.success(`Created: ${filePath}`);
1810
+ }
1811
+ if (!options.skipInstall) {
1812
+ logger.info("Installing dependencies...");
1813
+ try {
1814
+ child_process.execSync("pnpm install", { cwd: targetDir, stdio: "inherit" });
1815
+ logger.success("Dependencies installed!");
1816
+ } catch (_error) {
1817
+ logger.warning("Failed to install dependencies automatically.");
1818
+ logger.info('Please run "pnpm install" manually.');
1819
+ }
1820
+ }
1821
+ logger.success(`Plugin "${name}" created successfully!`);
1822
+ logger.info("");
1823
+ logger.bold("Next steps:");
1824
+ logger.info(` cd ${name}`);
1825
+ logger.info(" pnpm dev # Start development");
1826
+ logger.info(" pnpm build # Build for production");
1827
+ logger.info(" pnpm test # Run tests");
1828
+ }
1829
+ async function buildPlugin(options = {}) {
1830
+ const cwd = process.cwd();
1831
+ const outDir = options.outDir || "dist";
1832
+ const pkgPath = path.join(cwd, "package.json");
1833
+ if (!fs.existsSync(pkgPath)) {
1834
+ logger.error("No package.json found. Are you in a plugin directory?");
1835
+ process.exit(1);
1836
+ }
1837
+ logger.info("Building plugin...");
1838
+ try {
1839
+ const buildCmd = "tsup";
1840
+ const args = ["--entry", "src/index.ts", "--outDir", outDir, "--format", "esm,cjs", "--dts", "--sourcemap"];
1841
+ if (options.minify) {
1842
+ args.push("--minify");
1843
+ }
1844
+ child_process.execSync(`${buildCmd} ${args.join(" ")}`, { cwd, stdio: "inherit" });
1845
+ logger.success("Build completed!");
1846
+ logger.info(`Output: ${path.join(cwd, outDir)}`);
1847
+ } catch (_error) {
1848
+ logger.error("Build failed. Make sure tsup is installed: pnpm add -D tsup");
1849
+ process.exit(1);
1850
+ }
1851
+ }
1852
+ async function validatePlugin(options = {}) {
1853
+ const cwd = process.cwd();
1854
+ logger.info("Validating plugin...");
1855
+ const errors = [];
1856
+ const warnings = [];
1857
+ const pkgPath = path.join(cwd, "package.json");
1858
+ if (!fs.existsSync(pkgPath)) {
1859
+ errors.push("package.json not found");
1860
+ } else {
1861
+ try {
1862
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
1863
+ if (!pkg.name) errors.push("package.json: name is required");
1864
+ if (!pkg.version) errors.push("package.json: version is required");
1865
+ if (!pkg.main) errors.push("package.json: main is required");
1866
+ if (!pkg.module) errors.push("package.json: module is required");
1867
+ if (!pkg.types) errors.push("package.json: types is required");
1868
+ if (!pkg.exports) {
1869
+ warnings.push("package.json: exports field is recommended");
1870
+ }
1871
+ if (!pkg.peerDependencies || !pkg.peerDependencies["@lytjs/core"]) {
1872
+ errors.push("package.json: @lytjs/core peerDependency is required");
1873
+ }
1874
+ if (!pkg.keywords || !pkg.keywords.includes("lytjs")) {
1875
+ warnings.push('package.json: "lytjs" keyword is recommended');
1876
+ }
1877
+ } catch (err) {
1878
+ errors.push(`package.json: Invalid JSON - ${err}`);
1879
+ }
1880
+ }
1881
+ const srcPath = path.join(cwd, "src");
1882
+ if (!fs.existsSync(srcPath)) {
1883
+ errors.push("src directory not found");
1884
+ } else {
1885
+ const indexPath = path.join(srcPath, "index.ts");
1886
+ if (!fs.existsSync(indexPath)) {
1887
+ errors.push("src/index.ts not found");
1888
+ } else {
1889
+ const content = fs.readFileSync(indexPath, "utf-8");
1890
+ if (!content.includes("definePlugin") && !content.includes("EnhancedPlugin")) {
1891
+ warnings.push("src/index.ts: Consider using definePlugin or EnhancedPlugin");
1892
+ }
1893
+ if (!content.includes("export")) {
1894
+ warnings.push("src/index.ts: No exports found");
1895
+ }
1896
+ }
1897
+ }
1898
+ const tsconfigPath = path.join(cwd, "tsconfig.json");
1899
+ if (!fs.existsSync(tsconfigPath)) {
1900
+ warnings.push("tsconfig.json not found (recommended)");
1901
+ }
1902
+ const tsupConfigPath = path.join(cwd, "tsup.config.ts");
1903
+ if (!fs.existsSync(tsupConfigPath)) {
1904
+ warnings.push("tsup.config.ts not found (recommended for builds)");
1905
+ }
1906
+ let hasErrors = errors.length > 0;
1907
+ let hasWarnings = warnings.length > 0;
1908
+ if (hasErrors) {
1909
+ logger.error("Validation failed with errors:");
1910
+ for (const err of errors) {
1911
+ logger.error(` - ${err}`);
1912
+ }
1913
+ }
1914
+ if (hasWarnings && !options.strict) {
1915
+ logger.warning("Warnings:");
1916
+ for (const warn of warnings) {
1917
+ logger.warning(` - ${warn}`);
1918
+ }
1919
+ }
1920
+ if (!hasErrors && !hasWarnings) {
1921
+ logger.success("Plugin validation passed!");
1922
+ } else if (hasWarnings && !hasErrors) {
1923
+ logger.success("Plugin validation passed (with warnings)");
1924
+ if (options.strict) {
1925
+ process.exit(1);
1926
+ }
1927
+ } else {
1928
+ if (options.warningsAsErrors && hasWarnings) {
1929
+ logger.error("Strict mode: treating warnings as errors");
1930
+ }
1931
+ process.exit(1);
1932
+ }
1933
+ }
1934
+ function isEmptyDir2(dir) {
1935
+ if (!fs.existsSync(dir)) return true;
1936
+ const files = __require("fs").readdirSync(dir);
1937
+ return files.length === 0;
1938
+ }
1939
+ function listPluginTemplates() {
1940
+ logger.bold("Available plugin templates:");
1941
+ for (const [name, description] of Object.entries(PLUGIN_TEMPLATES)) {
1942
+ logger.info(` ${name.padEnd(12)} - ${description}`);
1943
+ }
1944
+ }
1945
+
1946
+ // src/commands/run.ts
1947
+ var VERSION = "6.0.0";
1948
+ async function runCli(rawArgs = process.argv.slice(2)) {
1949
+ const { command, args, options } = parseArgs(rawArgs);
1950
+ if (options.help || command === "help") {
1951
+ showHelp();
1952
+ return;
1953
+ }
1954
+ if (options.version || command === "version" || command === "-v" || command === "--version") {
1955
+ console.log(`LytJS CLI v${VERSION}`);
1956
+ return;
1957
+ }
1958
+ switch (command) {
1959
+ case "create":
1960
+ await create(args[0] || "my-lytjs-app", {
1961
+ template: options.template,
1962
+ force: options.force
1963
+ });
1964
+ break;
1965
+ case "templates":
1966
+ listTemplates();
1967
+ break;
1968
+ case "dev":
1969
+ await dev({
1970
+ port: options.port ? parseInt(options.port, 10) : void 0,
1971
+ host: options.host,
1972
+ open: options.open
1973
+ });
1974
+ break;
1975
+ case "build":
1976
+ await build({
1977
+ outDir: options.outDir,
1978
+ ssr: options.ssr,
1979
+ minify: options.minify !== "false"
1980
+ });
1981
+ break;
1982
+ case "test":
1983
+ await test({
1984
+ watch: options.watch !== "false",
1985
+ coverage: options.coverage,
1986
+ grep: options.grep
1987
+ });
1988
+ break;
1989
+ case "add":
1990
+ const addTypes = ["component", "page", "store", "directive", "composable", "util", "middleware", "hook"];
1991
+ if (!args[0] || !addTypes.includes(args[0])) {
1992
+ logger.error("Usage: lyt add <type> <name>");
1993
+ logger.info("Types: component, page, store, directive, composable, util, middleware, hook");
1994
+ logger.info("Example: lyt add component Button");
1995
+ process.exit(1);
1996
+ }
1997
+ await add(args[0], args[1] || "Unnamed", {
1998
+ force: options.force
1999
+ });
2000
+ break;
2001
+ case "generate":
2002
+ case "g":
2003
+ const genTypes = ["component", "page", "service", "hook", "store"];
2004
+ if (!args[0] || !genTypes.includes(args[0])) {
2005
+ logger.error("Usage: lyt generate <type> <name>");
2006
+ logger.info("Types: component, page, service, hook, store");
2007
+ logger.info("Example: lyt generate component Button");
2008
+ process.exit(1);
2009
+ }
2010
+ await generate({
2011
+ type: args[0],
2012
+ name: args[1] || "Unnamed",
2013
+ path: options.path,
2014
+ withStyles: options.styles,
2015
+ withTest: options.test,
2016
+ withStorybook: options.storybook
2017
+ });
2018
+ break;
2019
+ case "plugin":
2020
+ if (!args[0]) {
2021
+ logger.error("Usage: lyt plugin <create|build|validate|templates>");
2022
+ logger.info("Example: lyt plugin create my-plugin");
2023
+ process.exit(1);
2024
+ }
2025
+ const subCommand = args[0];
2026
+ switch (subCommand) {
2027
+ case "create":
2028
+ await createPlugin(args[1] || "my-plugin", {
2029
+ template: options.template,
2030
+ force: options.force,
2031
+ skipInstall: options.skipInstall
2032
+ });
2033
+ break;
2034
+ case "build":
2035
+ await buildPlugin({
2036
+ outDir: options.outDir,
2037
+ minify: options.minify,
2038
+ sourcemap: options.sourcemap
2039
+ });
2040
+ break;
2041
+ case "validate":
2042
+ await validatePlugin({
2043
+ strict: options.strict,
2044
+ warningsAsErrors: options.warningsAsErrors
2045
+ });
2046
+ break;
2047
+ case "templates":
2048
+ listPluginTemplates();
2049
+ break;
2050
+ default:
2051
+ logger.error(`Unknown plugin sub-command: ${subCommand}`);
2052
+ logger.info("Supported sub-commands: create, build, validate, templates");
2053
+ process.exit(1);
2054
+ }
2055
+ break;
2056
+ default:
2057
+ if (command) {
2058
+ logger.error(`Unknown command: ${command}`);
2059
+ logger.info('Run "lyt --help" for usage information.');
2060
+ process.exit(1);
2061
+ } else {
2062
+ showHelp();
2063
+ }
2064
+ }
2065
+ }
2066
+ function parseArgs(args) {
2067
+ let command = args[0] ?? "";
2068
+ const positional = [];
2069
+ const options = {};
2070
+ if (command.startsWith("--") || command.startsWith("-")) {
2071
+ command = "";
2072
+ }
2073
+ const startIndex = command ? 1 : 0;
2074
+ for (let i = startIndex; i < args.length; i++) {
2075
+ const arg = args[i] ?? "";
2076
+ if (arg.startsWith("--")) {
2077
+ const parts = arg.slice(2).split("=");
2078
+ const key = parts[0];
2079
+ const value = parts[1];
2080
+ if (value !== void 0 && key) {
2081
+ options[key] = value;
2082
+ } else if (key && i + 1 < args.length && !(args[i + 1] ?? "").startsWith("-")) {
2083
+ const nextArg = args[++i];
2084
+ if (nextArg) {
2085
+ options[key] = nextArg;
2086
+ }
2087
+ } else if (key) {
2088
+ options[key] = true;
2089
+ }
2090
+ } else if (arg.startsWith("-")) {
2091
+ const key = arg.slice(1);
2092
+ if (key) {
2093
+ options[key] = true;
2094
+ }
2095
+ } else {
2096
+ positional.push(arg);
2097
+ }
2098
+ }
2099
+ return { command, args: positional, options };
2100
+ }
2101
+ function showHelp() {
2102
+ console.log(`
2103
+ ${logger.bold("LytJS CLI")} v${VERSION}
2104
+
2105
+ ${logger.bold("Usage:")}
2106
+ lyt <command> [options]
2107
+
2108
+ ${logger.bold("Commands:")}
2109
+ create <name> Create a new LytJS project
2110
+ templates List available templates
2111
+ dev Start development server
2112
+ build Build for production
2113
+ test Run tests
2114
+ add <type> <name> Generate a component, page, store, directive, composable, etc.
2115
+ generate, g Advanced code generation (component, page, service, hook, store)
2116
+ plugin <subcmd> Plugin development commands
2117
+ help Show this help message
2118
+
2119
+ ${logger.bold("Options:")}
2120
+ --version, -v Show version number
2121
+ --help Show help
2122
+
2123
+ ${logger.bold("Create Options:")}
2124
+ --template <name> Use a specific template
2125
+ --force Overwrite existing directory
2126
+
2127
+ ${logger.bold("Dev Options:")}
2128
+ --port <number> Specify port (default: 5173)
2129
+ --host <host> Specify host (default: localhost)
2130
+ --open Open browser on start
2131
+
2132
+ ${logger.bold("Build Options:")}
2133
+ --outDir <dir> Output directory (default: dist)
2134
+ --ssr Build for SSR
2135
+ --minify false Disable minification
2136
+
2137
+ ${logger.bold("Test Options:")}
2138
+ --watch false Run tests once (no watch mode)
2139
+ --coverage Generate coverage report
2140
+ --grep <pattern> Filter tests by pattern
2141
+
2142
+ ${logger.bold("Generate Options:")}
2143
+ --path <dir> Output directory (default: ./src)
2144
+ --styles Generate CSS styles file
2145
+ --test Generate test file
2146
+ --storybook Generate Storybook story file
2147
+
2148
+ ${logger.bold("Plugin Options:")}
2149
+ --template <name> Use a specific plugin template (default, minimal, withConfig)
2150
+ --force Overwrite existing directory
2151
+ --skipInstall Skip installing dependencies
2152
+ --outDir <dir> Output directory (default: dist)
2153
+ --minify Minify output
2154
+ --sourcemap Generate sourcemaps
2155
+ --strict Strict validation mode
2156
+ --warningsAsErrors Treat warnings as errors
2157
+
2158
+ ${logger.bold("Examples:")}
2159
+ lyt create my-app
2160
+ lyt create my-app --template minimal
2161
+ lyt create my-app --template router
2162
+ lyt create my-app --template full
2163
+ lyt dev --port 3000
2164
+ lyt build --ssr
2165
+ lyt add component Button
2166
+ lyt add page About
2167
+ lyt add store user
2168
+ lyt directive click-outside
2169
+ lyt add composable fetch-data
2170
+ lyt add util format
2171
+ lyt add hook window-size
2172
+ lyt generate component Button --styles --test
2173
+ lyt generate page Dashboard --path ./src/pages
2174
+ lyt generate service User --path ./src/services
2175
+ lyt generate hook useCounter
2176
+ lyt generate store Auth --path ./src/stores
2177
+ lyt g page Login
2178
+ lyt plugin create my-plugin
2179
+ lyt plugin create my-plugin --template withConfig
2180
+ lyt plugin build
2181
+ lyt plugin validate
2182
+ `);
2183
+ }
2184
+
2185
+ // src/index.ts
2186
+ if (__require.main === module) {
2187
+ runCli().catch(console.error);
2188
+ }
2189
+
2190
+ exports.add = add;
2191
+ exports.build = build;
2192
+ exports.buildPlugin = buildPlugin;
2193
+ exports.create = create;
2194
+ exports.createPlugin = createPlugin;
2195
+ exports.detectPackageManager = detectPackageManager;
2196
+ exports.dev = dev;
2197
+ exports.ensureDir = ensureDir;
2198
+ exports.exists = exists;
2199
+ exports.generate = generate;
2200
+ exports.getAddCommand = getAddCommand;
2201
+ exports.getInstallCommand = getInstallCommand;
2202
+ exports.getRunCommand = getRunCommand;
2203
+ exports.listPluginTemplates = listPluginTemplates;
2204
+ exports.listTemplates = listTemplates;
2205
+ exports.logger = logger;
2206
+ exports.readFile = readFile;
2207
+ exports.runCli = runCli;
2208
+ exports.test = test;
2209
+ exports.validatePlugin = validatePlugin;
2210
+ exports.writeFile = writeFile;
2211
+ //# sourceMappingURL=lyt.cjs.map
2212
+ //# sourceMappingURL=lyt.cjs.map