@velsefy/cli 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VELSEFY
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,130 @@
1
+ # @velsefy/cli
2
+
3
+ CLI **cross-platform (Windows / macOS / Linux)** de VELSEFY para gestionar temas de
4
+ eCommerce + POS en un entorno SaaS multi-tenant. Escrito en TypeScript sobre **Node.js >= 18**.
5
+
6
+ **Empezar**: [`THEME-DEVELOPMENT.md`](./THEME-DEVELOPMENT.md) (guía para crear/modificar/publicar temas).
7
+
8
+ ---
9
+
10
+ ## Instalación
11
+
12
+ ### Desde npm (recomendado para agencias/devs)
13
+
14
+ ```bash
15
+ npm install -g @velsefy/cli
16
+ velsefy --version
17
+ ```
18
+
19
+ ### Desde el repo (desarrollo)
20
+
21
+ ```bash
22
+ git clone https://github.com/fivepulsespa-spec/velsefy-cli.git
23
+ cd velsefy-cli
24
+ npm install
25
+ npm run build
26
+ node dist/bin/velsefy.js --help
27
+ ```
28
+
29
+ > Requisito: **Node.js >= 18** (usa `fetch` nativo).
30
+
31
+ ---
32
+
33
+ ## Requisitos previos
34
+
35
+ 1. Una cuenta en VELSEFY.
36
+ 2. Un **token de acceso**, que generas desde tu cuenta (panel de tu tienda).
37
+ Para **publicar un tema al catálogo global** necesitas credenciales de plataforma
38
+ con permiso de publicación.
39
+
40
+ ---
41
+
42
+ ## Comandos
43
+
44
+ | Comando | Qué hace | Token |
45
+ |---|---|---|
46
+ | `velsefy login --token <token>` | Guarda el token (almacén seguro del SO) | — |
47
+ | `velsefy logout` | Elimina el token guardado | — |
48
+ | `velsefy theme list` | Lista los temas instalados de tu tienda | token de acceso |
49
+ | `velsefy theme pull --install <id> -o <dir>` | Descarga los assets de un tema instalado | token de acceso |
50
+ | `velsefy theme pull-catalog --sku <sku> -o <dir>` | Descarga los assets del **catálogo global** (el base) | credenciales de plataforma |
51
+ | `velsefy theme push --install <id> --dir <dir>` | Sube los assets (con detección de 409/ETag) | token de acceso |
52
+ | `velsefy theme validate --dir <dir>` | Validación LOCAL (Liquid/JSON/paths/semver) | No requiere |
53
+ | `velsefy theme release --sku <sku> --changelog "..." --dir <dir>` | Publica una release al catálogo de temas | credenciales de plataforma |
54
+
55
+ ---
56
+
57
+ ## Uso rápido
58
+
59
+ ```bash
60
+ # login con un token de tu cuenta (editas la copia privada de tu tema)
61
+ velsefy login --token <TU_TOKEN>
62
+
63
+ # listar las instalaciones de tu tienda
64
+ velsefy theme list
65
+
66
+ # descargar un tema a disco
67
+ velsefy theme pull --install <installId> -o ./mi-tema
68
+
69
+ # editar en VS Code… luego validar localmente (no requiere token)
70
+ velsefy theme validate --dir ./mi-tema
71
+
72
+ # subir los cambios (409 si hubo conflicto en otro lado)
73
+ velsefy theme push --install <installId> --dir ./mi-tema
74
+ ```
75
+
76
+ ### Publicar al catálogo global (solo plataforma)
77
+
78
+ ```bash
79
+ # descargar el tema base actual (editable)
80
+ velsefy login --token <TU_TOKEN_DE_PLATAFORMA>
81
+ velsefy theme pull-catalog --sku THEME-DEFAULT -o ./mi-tema
82
+
83
+ # editar en VS Code… validar… y publicar la nueva versión
84
+ velsefy theme validate --dir ./mi-tema
85
+ velsefy theme release --sku THEME-DEFAULT --changelog "[minor] nuevo hero" --dir ./mi-tema
86
+ # → { ok: true, version: 1 }
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Almacenamiento de credenciales (seguro por SO)
92
+
93
+ | SO | Vía |
94
+ |---|---|
95
+ | macOS | Keychain (`security`) |
96
+ | Linux | libsecret (`secret-tool`), fallback a archivo `0600` |
97
+ | Windows | archivo `0600` |
98
+ | CI | `VELSEFY_TOKEN` (se lee primero, **nunca** se escribe a disco) |
99
+
100
+ - **Nunca** se guarda el token en el repo ni en logs.
101
+ - `~/.config/velsefy/config.json` → solo metadatos (`apiBase`, preferencias).
102
+ - API base: `https://api.velsefy.com/v1` (override con `VELSEFY_API_BASE`).
103
+
104
+ ---
105
+
106
+ ## Seguridad
107
+
108
+ - La validación de autenticación la hace **el servidor**. El cliente solo transpota el token.
109
+ - Los tokens se revocan desde tu cuenta VELSEFY.
110
+ - El push con `baseUpdatedAt` detecta conflictos (HTTP 409) para no pisar cambios remotos.
111
+
112
+ ---
113
+
114
+ ## Workspace
115
+
116
+ Monorepo con **npm workspaces**:
117
+
118
+ - `@velsefy/cli` — la CLI.
119
+ - `@velsefy/theme-validate` — validador de temas (Liquid balanceado, JSON, paths, semver, `theme_info`).
120
+
121
+ ---
122
+
123
+ ## TODO (`velsefy theme dev` y mejoras)
124
+
125
+ - [ ] OAuth Device Flow (RFC 8628) interactivo para `velsefy login`.
126
+ - [ ] Windows DPAPI / Credential Manager.
127
+ - [ ] `velsefy theme dev` (watch + hot reload) y `velsefy theme check` (linter).
128
+ - [ ] Resolución visual de conflictos push.
129
+
130
+ Ver también [`THEME-DEVELOPMENT.md`](./THEME-DEVELOPMENT.md).
@@ -0,0 +1,270 @@
1
+ # 🎨 Desarrollo de Temas VELSEFY (Liquid)
2
+
3
+ Guía para crear/modificar temas de tienda VELSEFY y publicarlos con `velsefy theme release`.
4
+ Estructura fiel al estándar **Shopify Online Store 2.0**, con **versionado Shopify-pura** en `theme_info`.
5
+
6
+ ---
7
+
8
+ ## 1. Estructura de un tema
9
+
10
+ ```
11
+ mi-tema/
12
+ ├── layout/
13
+ │ └── theme.liquid # Plantilla base (HTML + {{ content_for_layout }})
14
+ ├── sections/ # Secciones arrastrables (cada una con {% schema %})
15
+ │ ├── hero.liquid
16
+ │ └── product_main.liquid
17
+ ├── snippets/ # Fragmentos reutilizables ({% render 'x' %})
18
+ │ └── price.liquid
19
+ ├── assets/ # CSS / JS / imágenes / fuentes
20
+ │ ├── theme.css
21
+ │ └── theme.js
22
+ ├── config/
23
+ │ ├── settings_schema.json # Declaración de settings globales (array de grupos)
24
+ │ └── settings_data.json # Valores actuales (en VELSEFY → custom_config/theme_config)
25
+ ├── templates/ # Plantillas de página (*.json)
26
+ │ ├── index.json
27
+ │ ├── product.json
28
+ │ ├── collection.json
29
+ │ └── page.json
30
+ └── theme.json # (solo al exportar; wrapper VELSEFY con name/version)
31
+ ```
32
+
33
+ **Carpetas y extensiones permitidas** (lo valida el servidor):
34
+ `assets|sections|layout|snippets|config|templates` + `css|js|mjs|json|svg|png|jpg|jpeg|webp|gif|ico|woff|woff2|ttf|txt|xml|liquid`.
35
+
36
+ **Bloqueado:** `..`, `\`, `%` (path traversal).
37
+
38
+ ---
39
+
40
+ ## 2. Versionado del tema (Shopify-pura) — ⭐ IMPORTANTE
41
+
42
+ La versión semver (`MAJOR.MINOR.PATCH`) vive **SOLO** en `config/settings_schema.json`, dentro del grupo `theme_info`:
43
+
44
+ ```json
45
+ [
46
+ {
47
+ "name": "theme_info",
48
+ "theme_name": "Mi Tema",
49
+ "theme_version": "1.0.0",
50
+ "theme_author": "Mi Agencia",
51
+ "theme_documentation_url": "https://docs.velsefy.com",
52
+ "theme_support_url": "https://support.velsefy.com"
53
+ },
54
+ { "name": "Colores", "settings": [ /* ... */ ] }
55
+ ]
56
+ ```
57
+
58
+ - La versión se lee de `theme_info.theme_version` (semver, única fuente en el tema).
59
+ - La **versión del catálogo** (lo que se compara para "actualización disponible") la gestiona la plataforma al publicar.
60
+ - Al publicar con `velsefy theme release`, el servidor **bump** la versión (`patch` por defecto; `[major]`/`[minor]` en el changelog para subir major/minor).
61
+
62
+ ---
63
+
64
+ ## 3. `settings_schema.json` (settings globales)
65
+
66
+ Array de grupos `{ name, settings: [...] }`. El grupo `theme_info` se descarta al renderizar (solo metadata).
67
+
68
+ ```json
69
+ {
70
+ "name": "Colores",
71
+ "settings": [
72
+ { "type": "color", "id": "primaryColor", "label": "Color Principal", "default": "#000000" },
73
+ { "type": "range", "id": "fontScale", "label": "Escala", "min": 100, "max": 130, "step": 5, "unit": "%", "default": 100 },
74
+ { "type": "select", "id": "fontFamily", "label": "Fuente", "options": [{ "value": "Inter", "label": "Inter" }], "default": "Inter" },
75
+ { "type": "checkbox", "id": "enableX", "label": "Habilitar X", "default": false },
76
+ { "type": "number", "id": "maxItems", "label": "Máx", "min": 1, "max": 24, "default": 8 }
77
+ ]
78
+ }
79
+ ```
80
+
81
+ Tipos de `settings[].type` **soportados por VELSEFY** (subconjunto, no la lista completa de Shopify — el validador NO acepta los demás):
82
+ `color` · `range` · `number` · `select` · `text` · `textarea` · `checkbox` · `image_picker` · `richtext` · `url`.
83
+
84
+ > ⚠️ Si usás un tipo que no esté en esta lista (p.ej. `font_picker`, `product_list`, `blog`), el renderer de VELSEFY no lo dibuja y `velsefy theme validate` lo reportará como error.** Tipos de block (`blocks[].type`) son libres.**
85
+
86
+ En el tema se leen así: `{{ settings.primaryColor }}`, `{{ settings.fontScale }}`.
87
+
88
+ ---
89
+
90
+ ## 4. Secciones (`sections/*.liquid`) con `{% schema %}`
91
+
92
+ Cada sección declara su schema al final del archivo. **Deja y cierra `{% schema %}...{% endschema %}`** (obligatorio en secciones).
93
+
94
+ ```liquid
95
+ {% style %}
96
+ #velsefy-section-{{ section.id }} .mi-hero { color: {{ section.settings.text_color }}; }
97
+ {% endstyle %}
98
+
99
+ <div class="mi-hero">
100
+ <h1>{{ section.settings.title }}</h1>
101
+ {% for block in section.blocks %}
102
+ <p>{{ block.settings.text }}</p>
103
+ {% endfor %}
104
+ </div>
105
+
106
+ {% schema %}
107
+ {
108
+ "name": "Hero",
109
+ "tag": "section",
110
+ "settings": [
111
+ { "type": "text", "id": "title", "label": "Título", "default": "Bienvenido" },
112
+ { "type": "color", "id": "text_color", "label": "Color", "default": "#111827" }
113
+ ],
114
+ "blocks": [
115
+ { "type": "text", "name": "Texto", "settings": [ { "type": "textarea", "id": "text", "label": "Texto" } ] }
116
+ ],
117
+ "presets": [ { "name": "Hero", "blocks": [ { "type": "text" } ] } ]
118
+ }
119
+ {% endschema %}
120
+ ```
121
+
122
+ - `settings` → accesibles como `{{ section.settings.x }}`.
123
+ - `blocks` → `{% for block in section.blocks %}` → `{{ block.settings.x }}`.
124
+ - `presets` → cómo aparece al agregar la sección en el editor.
125
+ - `max_blocks` → limita la cantidad de bloques.
126
+
127
+ ---
128
+
129
+ ## 5. Snippets (`snippets/*.liquid`)
130
+
131
+ Reutilizables vía `{% render 'nombre', parametros: valor %}`:
132
+
133
+ ```liquid
134
+ {%- if price != blank -%}
135
+ <span class="vs-price">{{ price | money }}</span>
136
+ {%- endif -%}
137
+ ```
138
+
139
+ ```
140
+ {% render 'price', price: product.price, compare_at: product.compare_price %}
141
+ ```
142
+
143
+ ---
144
+
145
+ ## 6. Layout base (`layout/theme.liquid`)
146
+
147
+ ```liquid
148
+ <!doctype html>
149
+ <html lang="{{ shop.locale }}">
150
+ <head>
151
+ <meta charset="utf-8">
152
+ <title>{{ page_title }}</title>
153
+ {{ 'theme.css' | asset_url | stylesheet_tag }}
154
+ </head>
155
+ <body>
156
+ {% section 'header' %}
157
+ {{ content_for_layout }}
158
+ {% section 'footer' %}
159
+ {{ 'theme.js' | asset_url | script_tag }}
160
+ </body>
161
+ </html>
162
+ ```
163
+
164
+ ---
165
+
166
+ ## 7. Plantillas de página (`templates/*.json`)
167
+
168
+ ```json
169
+ {
170
+ "sections": [
171
+ { "id": "home-hero", "type": "hero", "area": "main", "settings": { "title": "Hola" } }
172
+ ]
173
+ }
174
+ ```
175
+
176
+ ---
177
+
178
+ ## 8. Publicar un tema
179
+
180
+ ### Contexto
181
+
182
+ - **Token de acceso de tu cuenta** → editas la **copia privada** de tu tema (pull/push).
183
+ - **Credenciales de plataforma** (con permiso de publicación) → publicas al **catálogo global**.
184
+
185
+ ### Flujo de desarrollo (editar tu copia)
186
+
187
+ ```bash
188
+ velsefy login --token <TU_TOKEN>
189
+ velsefy theme pull --install <installId> -o ./mi-tema
190
+ # edita en VS Code...
191
+ velsefy theme validate --dir ./mi-tema # validación local
192
+ velsefy theme push --install <installId> --dir ./mi-tema # sube; 409 si hay conflictos
193
+ ```
194
+
195
+ ### Flujo de publicación al catálogo (plataforma)
196
+
197
+ ```bash
198
+ velsefy login --token <TU_TOKEN_DE_PLATAFORMA>
199
+ velsefy theme release --sku THEME-DEFAULT --changelog "v2: nuevo hero" --dir ./mi-tema
200
+ ```
201
+
202
+ El servidor valida cada archivo **antes** de guardar:
203
+
204
+ - `.json` → `JSON.parse` válido.
205
+ - `.liquid` → `{% schema %}`/`{% endschema %}` balanceado (y presente en secciones).
206
+ - `.liquid` → `{% if %}`/`{% endif %}` balanceado.
207
+ - Paths permitidos + sin `..`/`\`/`%`.
208
+
209
+ Si algo falla → `400 validation_failed` con el archivo + error. **Devuelve `{ ok, version }` en 201.**
210
+
211
+ ---
212
+
213
+ ## 9. Validación local (`velsefy theme validate`)
214
+
215
+ ```bash
216
+ velsefy theme validate --dir ./mi-tema
217
+ # → "Versión del tema (theme_info): 1.0.0" + "Tema válido."
218
+ ```
219
+
220
+ No requiere token (operación 100% local). Chequea: balance Liquid (`{% %}`/`{{ }}`), **tipos de `settings[].type` del `{% schema %}` contra la whitelist** (y exige `id`), JSON válido, paths, semver y extrae `theme_info.theme_version`.
221
+
222
+ > El servidor aplica la MISMA validación de tipos al publicar (`theme release`) → si usás un tipo no soportado, el publish devuelve `400 validation_failed`.
223
+
224
+ ### Autocompletado / errores en VS Code (opcional)
225
+
226
+ Para que **VS Code valide `config/settings_schema.json`** inline (errores + autocompletado de tipos), agregá a tu `.vscode/settings.json` la referencia al JSON Schema del paquete:
227
+
228
+ ```json
229
+ {
230
+ "json.schemas": [
231
+ {
232
+ "fileMatch": ["config/settings_schema.json"],
233
+ "url": "https://raw.githubusercontent.com/fivepulsespa-spec/velsefy-cli/main/packages/theme-validate/velsefy.settings_schema.json"
234
+ }
235
+ ]
236
+ }
237
+ ```
238
+
239
+ (El schema está en `packages/theme-validate/velsefy.settings_schema.json` del repo.)
240
+
241
+ ---
242
+
243
+ ## 10. Buenas prácticas
244
+
245
+ - **Versioná semver** en `theme_info.theme_version` (nunca en otro archivo).
246
+ - **No rompas el balance** de `{% schema %}`/`{% endschema %}` y `{% if %}`/`{% endif %}` — el servidor lo rechaza.
247
+ - **Nombres de archivo** en minúsculas con guiones (`product-card.liquid`).
248
+ - **Prefija clases** con tu scope (ej. `vs-*` o `mi-*`) para no chocar con otros temas.
249
+ - **Prefijo de assets**: usa `{{ 'x.css' | asset_url }}`.
250
+ - Probá con `velsefy theme validate` antes de `release`/`push`.
251
+
252
+ ---
253
+
254
+ ## 11. Referencia rápida de Liquid
255
+
256
+ - Salida: `{{ variable }}` · Lógica: `{% if %}` / `{% for %}` / `{% case %}` / `{% assign %}`.
257
+ - Incluir: `{% render 'x' %}` · `{% section 'x' %}`.
258
+ - Formato: `{{ price | money }}` · `{{ x | escape }}`.
259
+ - Assets: `{{ 'f.js' | asset_url | script_tag }}` · `{{ 'f.css' | asset_url | stylesheet_tag }}`.
260
+
261
+ ---
262
+
263
+ ## Verificación
264
+
265
+ ```bash
266
+ cd velsefy-cli
267
+ npm install
268
+ npm run typecheck && npm run lint && npm run build
269
+ velsefy theme validate --dir examples/default-theme # ejemplo incluido
270
+ ```
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { createProgram } from "../index.js";
3
+ import { logger } from "../lib/logger.js";
4
+ const program = createProgram();
5
+ program.parseAsync(process.argv).catch((err) => {
6
+ logger.error(err instanceof Error ? err.message : String(err));
7
+ process.exitCode = 1;
8
+ });
9
+ //# sourceMappingURL=velsefy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"velsefy.js","sourceRoot":"","sources":["../../src/bin/velsefy.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;AAEhC,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;IACtD,MAAM,CAAC,KAAK,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/D,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { Command } from "commander";
2
+ export interface LoginOptions {
3
+ token?: string;
4
+ }
5
+ export declare function loginCommand(program: Command): void;
@@ -0,0 +1,21 @@
1
+ import { logger } from "../lib/logger.js";
2
+ import { setToken } from "../lib/credentials.js";
3
+ export function loginCommand(program) {
4
+ program
5
+ .command("login")
6
+ .description("Guarda un token de acceso de VELSEFY")
7
+ // TODO: OAuth Device Flow (RFC 8628) interactivo no implementado aún.
8
+ // Por ahora se acepta un token de acceso (PAT) emitido desde tu cuenta VELSEFY.
9
+ .requiredOption("--token <token>", "Token de acceso de VELSEFY")
10
+ .action((options) => {
11
+ try {
12
+ setToken(options.token);
13
+ logger.success("Credenciales guardadas.");
14
+ }
15
+ catch (err) {
16
+ logger.error(err instanceof Error ? err.message : String(err));
17
+ process.exitCode = 1;
18
+ }
19
+ });
20
+ }
21
+ //# sourceMappingURL=login.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"login.js","sourceRoot":"","sources":["../../src/commands/login.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAMjD,MAAM,UAAU,YAAY,CAAC,OAAgB;IAC3C,OAAO;SACJ,OAAO,CAAC,OAAO,CAAC;SAChB,WAAW,CAAC,sCAAsC,CAAC;QACpD,sEAAsE;QACtE,gFAAgF;SAC/E,cAAc,CAAC,iBAAiB,EAAE,4BAA4B,CAAC;SAC/D,MAAM,CAAC,CAAC,OAAqB,EAAE,EAAE;QAChC,IAAI,CAAC;YACH,QAAQ,CAAC,OAAO,CAAC,KAAe,CAAC,CAAC;YAClC,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC;QAC5C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,KAAK,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC/D,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { Command } from "commander";
2
+ export declare function logoutCommand(program: Command): void;
@@ -0,0 +1,18 @@
1
+ import { logger } from "../lib/logger.js";
2
+ import { clearToken } from "../lib/credentials.js";
3
+ export function logoutCommand(program) {
4
+ program
5
+ .command("logout")
6
+ .description("Elimina las credenciales guardadas")
7
+ .action(() => {
8
+ try {
9
+ clearToken();
10
+ logger.success("Sesión cerrada.");
11
+ }
12
+ catch (err) {
13
+ logger.error(err instanceof Error ? err.message : String(err));
14
+ process.exitCode = 1;
15
+ }
16
+ });
17
+ }
18
+ //# sourceMappingURL=logout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logout.js","sourceRoot":"","sources":["../../src/commands/logout.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAEnD,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,OAAO;SACJ,OAAO,CAAC,QAAQ,CAAC;SACjB,WAAW,CAAC,oCAAoC,CAAC;SACjD,MAAM,CAAC,GAAG,EAAE;QACX,IAAI,CAAC;YACH,UAAU,EAAE,CAAC;YACb,MAAM,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACpC,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,CAAC,KAAK,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;YAC/D,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACvB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC"}
@@ -0,0 +1,2 @@
1
+ import type { Command } from "commander";
2
+ export declare function themeCommand(program: Command): void;
@@ -0,0 +1,176 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { logger } from "../lib/logger.js";
4
+ import { requireToken } from "../lib/credentials.js";
5
+ import { listThemes, pullThemeAssets, pullCatalogThemeAssets, pushThemeAssets, releaseTheme } from "../lib/api.js";
6
+ import { validate } from "../lib/validate.js";
7
+ function walkTree(root) {
8
+ const out = [];
9
+ const stack = [root];
10
+ while (stack.length > 0) {
11
+ const current = stack.pop();
12
+ const stat = fs.statSync(current);
13
+ if (stat.isDirectory()) {
14
+ for (const name of fs.readdirSync(current)) {
15
+ stack.push(path.join(current, name));
16
+ }
17
+ }
18
+ else {
19
+ out.push(current);
20
+ }
21
+ }
22
+ return out;
23
+ }
24
+ function readAssetsFromDir(dir) {
25
+ if (!fs.existsSync(dir)) {
26
+ throw new Error(`El directorio del tema no existe: ${dir}`);
27
+ }
28
+ return walkTree(dir)
29
+ .filter((file) => !path.basename(file).startsWith(".")) // ignora estado/ocultos (.velsefy-state.json, .DS_Store)
30
+ .map((file) => {
31
+ const relative = path.relative(dir, file).split(path.sep).join("/");
32
+ return { path: relative, content: fs.readFileSync(file, "utf8") };
33
+ });
34
+ }
35
+ // Estado local del CLI para el ETag/409 en push: guarda el baseUpdatedAt del
36
+ // último pull/éxito. Es un archivo oculto (se ignora al subir) y NO se sube nunca.
37
+ const STATE_FILE = ".velsefy-state.json";
38
+ function statePath(dir) {
39
+ return path.join(dir, STATE_FILE);
40
+ }
41
+ function readBaseUpdatedAt(dir) {
42
+ try {
43
+ const raw = fs.readFileSync(statePath(dir), "utf8");
44
+ const parsed = JSON.parse(raw);
45
+ return typeof parsed.baseUpdatedAt === "string" ? parsed.baseUpdatedAt : undefined;
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ function writeBaseUpdatedAt(dir, baseUpdatedAt) {
52
+ fs.mkdirSync(dir, { recursive: true });
53
+ fs.writeFileSync(statePath(dir), JSON.stringify({ baseUpdatedAt }, null, 2));
54
+ }
55
+ /** Máximo updated_at del pull → baseUpdatedAt para el conflicto ETag del push. */
56
+ function maxUpdatedAt(assets) {
57
+ const max = assets.reduce((acc, a) => {
58
+ const ts = a.updated_at ?? a.updatedAt ?? null;
59
+ return ts && (!acc || new Date(ts).getTime() > new Date(acc).getTime()) ? ts : acc;
60
+ }, null);
61
+ return max ?? new Date().toISOString();
62
+ }
63
+ export function themeCommand(program) {
64
+ const theme = program
65
+ .command("theme")
66
+ .description("Gestiona los temas de VELSEFY");
67
+ theme
68
+ .command("list")
69
+ .description("Lista los temas instalados")
70
+ .action(async () => {
71
+ const token = requireToken("theme list");
72
+ const themes = await listThemes(token);
73
+ if (themes.length === 0) {
74
+ logger.warn("No hay temas.");
75
+ return;
76
+ }
77
+ logger.bold("ID\tNOMBRE\tESTADO");
78
+ for (const item of themes) {
79
+ logger.info(`${item.id}\t${item.name}\t${item.status}`);
80
+ }
81
+ });
82
+ theme
83
+ .command("pull")
84
+ .description("Descarga los assets de un tema a un directorio local")
85
+ .requiredOption("--install <id>", "Install ID del tema")
86
+ .option("-o, --output <dir>", "Directorio de salida", "./theme-local")
87
+ .action(async (options) => {
88
+ const token = requireToken("theme pull");
89
+ const assets = await pullThemeAssets(token, options.install);
90
+ for (const asset of assets) {
91
+ const target = path.join(options.output, asset.path.split("/").join(path.sep));
92
+ fs.mkdirSync(path.dirname(target), { recursive: true });
93
+ fs.writeFileSync(target, asset.content);
94
+ }
95
+ // Guarda el baseUpdatedAt (máx. updated_at del pull) para el ETag/409 del push.
96
+ writeBaseUpdatedAt(options.output, maxUpdatedAt(assets));
97
+ logger.success(`Descargados ${assets.length} asset(s) en ${options.output}.`);
98
+ });
99
+ theme
100
+ .command("pull-catalog")
101
+ .description("Descarga los assets del catálogo global de temas (el base)")
102
+ .requiredOption("--sku <sku>", "SKU del tema del catálogo")
103
+ .option("-o, --output <dir>", "Directorio de salida", "./theme-local")
104
+ .action(async (options) => {
105
+ const token = requireToken("theme pull-catalog");
106
+ const assets = await pullCatalogThemeAssets(token, options.sku);
107
+ for (const asset of assets) {
108
+ const target = path.join(options.output, asset.path.split("/").join(path.sep));
109
+ fs.mkdirSync(path.dirname(target), { recursive: true });
110
+ fs.writeFileSync(target, asset.content);
111
+ }
112
+ logger.success(`Descargados ${assets.length} asset(s) del catálogo en ${options.output}.`);
113
+ });
114
+ theme
115
+ .command("push")
116
+ .description("Sube los assets del tema local al instalado")
117
+ .requiredOption("--install <id>", "Install ID del tema")
118
+ .option("--dir <dir>", "Directorio del tema local", "./theme-local")
119
+ .action(async (options) => {
120
+ const token = requireToken("theme push");
121
+ const assets = readAssetsFromDir(options.dir);
122
+ const baseUpdatedAt = readBaseUpdatedAt(options.dir);
123
+ const result = await pushThemeAssets(token, options.install, assets, baseUpdatedAt);
124
+ if (result.status === "conflict") {
125
+ logger.error("Conflicto 409: el tema fue modificado en otro lado.");
126
+ for (const conflict of result.conflict.conflicts) {
127
+ logger.warn(` ${conflict.path} (servidor: ${conflict.serverUpdatedAt}${conflict.localUpdatedAt ? `, local: ${conflict.localUpdatedAt}` : ""})`);
128
+ }
129
+ logger.warn("Resuelve los conflictos desde la web o vuelve a hacer pull y reintenta.");
130
+ process.exitCode = 1;
131
+ return;
132
+ }
133
+ // El servidor devuelve updatedAt → base para el siguiente push.
134
+ writeBaseUpdatedAt(options.dir, result.updatedAt);
135
+ logger.success(`Subidos ${assets.length} asset(s). updatedAt=${result.updatedAt}`);
136
+ });
137
+ theme
138
+ .command("release")
139
+ .description("Publica una release del tema al catálogo")
140
+ .requiredOption("--sku <sku>", "SKU del catálogo")
141
+ .option("--changelog <texto>", "Notas de la release")
142
+ .option("--dir <dir>", "Directorio del tema local", "./theme-local")
143
+ .action(async (options) => {
144
+ const token = requireToken("theme release");
145
+ const assets = readAssetsFromDir(options.dir);
146
+ const result = await releaseTheme(token, options.sku, options.changelog, assets);
147
+ if (result.version) {
148
+ logger.success(`Release creada: ${result.sku ?? options.sku}@${result.version}`);
149
+ }
150
+ else {
151
+ logger.success("Release creada.");
152
+ }
153
+ });
154
+ theme
155
+ .command("validate")
156
+ .description("Valida un tema local (Liquid balanceado, JSON, paths, semver)")
157
+ .option("--dir <dir>", "Directorio del tema", "./theme-local")
158
+ .action((options) => {
159
+ // `theme validate` es una operación 100% LOCAL (no sube nada): NO pide
160
+ // token. Sirve para pre-push y para CI sin credenciales.
161
+ const result = validate(options.dir);
162
+ if (result.themeVersion) {
163
+ logger.info(`Versión del tema (theme_info): ${result.themeVersion}`);
164
+ }
165
+ if (result.valid) {
166
+ logger.success("Tema válido.");
167
+ return;
168
+ }
169
+ for (const issue of result.issues) {
170
+ logger.warn(`${issue.file}: ${issue.message}`);
171
+ }
172
+ logger.error(`Tema inválido (${result.issues.length} problema(s)).`);
173
+ process.exitCode = 1;
174
+ });
175
+ }
176
+ //# sourceMappingURL=theme.js.map