quilltap 4.13.0 → 4.14.0-dev.44

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.
@@ -8,19 +8,22 @@
8
8
  * - list: Show installed themes
9
9
  * - install: Install a .qtap-theme bundle
10
10
  * - uninstall: Remove a bundle theme
11
- * - validate: Check a .qtap-theme file
11
+ * - validate: Check a .qtap-theme file or a bundle directory
12
12
  * - export: Export a theme as .qtap-theme
13
13
  *
14
+ * Bundles are validated, extracted and packed by the app's own theme engine,
15
+ * bundled into ./theme-engine.generated.js (scripts/build-cli-theme-engine.mjs
16
+ * in the server repository). Only version 2 bundles are accepted; one made
17
+ * for an earlier Quilltap is refused by every command that takes a bundle.
18
+ *
14
19
  * @module quilltap/lib/theme-commands
15
20
  */
16
21
 
17
- const fs = require('fs');
18
22
  const fsp = require('fs/promises');
19
23
  const path = require('path');
20
24
  const os = require('os');
21
25
  const crypto = require('crypto');
22
- const { execSync } = require('child_process');
23
- const { validateThemeBundle, validateManifest } = require('./theme-validation');
26
+ const engine = require('./theme-engine.generated');
24
27
  const { getDefaultBaseDir } = require('./platform-paths');
25
28
 
26
29
  // ============================================================================
@@ -87,61 +90,82 @@ async function writeIndex(index, overrideDir) {
87
90
  }
88
91
 
89
92
  // ============================================================================
90
- // ZIP EXTRACTION (uses yauzl)
93
+ // BUNDLE HELPERS
91
94
  // ============================================================================
92
95
 
93
- async function extractZipToDir(zipPath, destDir) {
94
- const yauzl = require('yauzl');
96
+ const THEME_ID_PATTERN = /^[a-z][a-z0-9-]*$/;
95
97
 
96
- const zipFile = await new Promise((resolve, reject) => {
97
- yauzl.open(zipPath, { lazyEntries: true, autoClose: false }, (err, zf) => {
98
- if (err) reject(err);
99
- else resolve(zf);
100
- });
101
- });
98
+ /** The install directory for a theme id, or null when the id is not one. */
99
+ function installPathFor(themeId, dataDir) {
100
+ if (typeof themeId !== 'string' || !THEME_ID_PATTERN.test(themeId)) return null;
101
+ return path.join(getThemesDir(dataDir), themeId);
102
+ }
102
103
 
104
+ /** Validate a .qtap-theme file or a bundle directory with the theme engine. */
105
+ async function validateSource(sourcePath) {
106
+ let stat;
103
107
  try {
104
- await new Promise((resolve, reject) => {
105
- zipFile.readEntry();
106
- zipFile.on('entry', async (entry) => {
107
- try {
108
- const entryPath = path.join(destDir, entry.fileName);
109
-
110
- // Security: prevent path traversal
111
- if (!entryPath.startsWith(destDir + path.sep) && entryPath !== destDir) {
112
- reject(new Error(`Path traversal detected: ${entry.fileName}`));
113
- return;
114
- }
108
+ stat = await fsp.stat(sourcePath);
109
+ } catch {
110
+ return { valid: false, errors: ['Bundle file not found or not readable'], warnings: [], fileCount: 0, totalSize: 0 };
111
+ }
112
+ return stat.isDirectory() ? engine.validateThemeDirectory(sourcePath) : engine.validateThemeBundle(sourcePath);
113
+ }
115
114
 
116
- if (/\/$/.test(entry.fileName)) {
117
- await fsp.mkdir(entryPath, { recursive: true });
118
- zipFile.readEntry();
119
- } else {
120
- await fsp.mkdir(path.dirname(entryPath), { recursive: true });
121
- const data = await new Promise((res, rej) => {
122
- zipFile.openReadStream(entry, (err, stream) => {
123
- if (err) { rej(err); return; }
124
- const chunks = [];
125
- stream.on('data', (chunk) => chunks.push(chunk));
126
- stream.on('end', () => res(Buffer.concat(chunks)));
127
- stream.on('error', rej);
128
- });
129
- });
130
- await fsp.writeFile(entryPath, data);
131
- zipFile.readEntry();
132
- }
133
- } catch (err) {
134
- reject(err);
135
- }
136
- });
137
- zipFile.on('end', resolve);
138
- zipFile.on('error', reject);
115
+ function printProblems(result, indent) {
116
+ for (const error of result.errors) console.log(`${indent}${c.red}Error:${c.reset} ${error}`);
117
+ if (result.refused) console.log(`${indent}${c.dim}Only version ${engine.CURRENT_THEME_FORMAT_VERSION} theme bundles are accepted.${c.reset}`);
118
+ }
119
+
120
+ function printWarnings(result, indent) {
121
+ if (!result.warnings || result.warnings.length === 0) return;
122
+ console.log('');
123
+ for (const warning of result.warnings) console.log(`${indent}${c.yellow}Warning:${c.reset} ${warning}`);
124
+ }
125
+
126
+ /**
127
+ * Validate a downloaded or local .qtap-theme file and install it: the old
128
+ * install is removed only after validation passes, the archive is extracted
129
+ * through the engine's one extraction routine, and the index is updated.
130
+ * Returns { ok, manifest?, validation, error? }.
131
+ */
132
+ async function installBundleFile(zipPath, dataDir, indexFields) {
133
+ const validation = await engine.validateThemeBundle(zipPath);
134
+ if (!validation.valid || !validation.manifest) return { ok: false, validation };
135
+
136
+ const manifest = validation.manifest;
137
+ const installPath = installPathFor(manifest.id, dataDir);
138
+ if (!installPath) return { ok: false, validation, error: `Invalid theme id: ${manifest.id}` };
139
+
140
+ try {
141
+ await fsp.rm(installPath, { recursive: true, force: true });
142
+ await engine.extractThemeBundle(zipPath, installPath);
143
+
144
+ const index = await readIndex(dataDir);
145
+ index.themes = index.themes.filter(t => t.id !== manifest.id);
146
+ index.themes.push({
147
+ id: manifest.id,
148
+ version: manifest.version,
149
+ installedAt: new Date().toISOString(),
150
+ source: 'file',
151
+ sourceUrl: null,
152
+ registrySource: null,
153
+ signatureVerified: false,
154
+ ...indexFields,
139
155
  });
140
- } finally {
141
- zipFile.close();
156
+ await writeIndex(index, dataDir);
157
+ return { ok: true, manifest, validation, installPath };
158
+ } catch (err) {
159
+ await fsp.rm(installPath, { recursive: true, force: true }).catch(() => {});
160
+ return { ok: false, validation, error: err.message };
142
161
  }
143
162
  }
144
163
 
164
+ function authorName(author) {
165
+ if (!author) return '';
166
+ return typeof author === 'string' ? author : author.name || '';
167
+ }
168
+
145
169
  // ============================================================================
146
170
  // COMMANDS
147
171
  // ============================================================================
@@ -194,23 +218,24 @@ async function listThemes(dataDir) {
194
218
  }
195
219
 
196
220
  /**
197
- * Validate a .qtap-theme file
221
+ * Validate a .qtap-theme file or a bundle directory
198
222
  */
199
223
  async function validateTheme(filePath) {
200
224
  const resolvedPath = path.resolve(filePath);
201
225
 
202
226
  console.log(`\n${c.bold}Validating:${c.reset} ${resolvedPath}\n`);
203
227
 
204
- const result = await validateThemeBundle(resolvedPath);
228
+ const result = await validateSource(resolvedPath);
205
229
 
206
230
  if (result.valid) {
207
- console.log(` ${c.green}Valid${c.reset} .qtap-theme bundle\n`);
231
+ console.log(` ${c.green}Valid${c.reset} version ${engine.CURRENT_THEME_FORMAT_VERSION} theme bundle\n`);
208
232
  if (result.manifest) {
233
+ const author = authorName(result.manifest.author);
209
234
  console.log(` Name: ${result.manifest.name}`);
210
235
  console.log(` ID: ${result.manifest.id}`);
211
236
  console.log(` Version: ${result.manifest.version}`);
212
237
  console.log(` Dark Mode: ${result.manifest.supportsDarkMode ? 'Yes' : 'No'}`);
213
- if (result.manifest.author) console.log(` Author: ${result.manifest.author}`);
238
+ if (author) console.log(` Author: ${author}`);
214
239
  if (result.manifest.description) {
215
240
  console.log(` Description: ${result.manifest.description.substring(0, 60)}${result.manifest.description.length > 60 ? '...' : ''}`);
216
241
  }
@@ -218,19 +243,11 @@ async function validateTheme(filePath) {
218
243
  console.log(` Files: ${result.fileCount}`);
219
244
  console.log(` Size: ${(result.totalSize / 1024).toFixed(1)} KB`);
220
245
  } else {
221
- console.log(` ${c.red}Invalid${c.reset} .qtap-theme bundle\n`);
222
- for (const error of result.errors) {
223
- console.log(` ${c.red}Error:${c.reset} ${error}`);
224
- }
225
- }
226
-
227
- if (result.warnings.length > 0) {
228
- console.log('');
229
- for (const warning of result.warnings) {
230
- console.log(` ${c.yellow}Warning:${c.reset} ${warning}`);
231
- }
246
+ console.log(` ${c.red}Invalid${c.reset} theme bundle\n`);
247
+ printProblems(result, ' ');
232
248
  }
233
249
 
250
+ printWarnings(result, ' ');
234
251
  console.log('');
235
252
  return result.valid;
236
253
  }
@@ -243,101 +260,36 @@ async function installTheme(source, dataDir) {
243
260
 
244
261
  console.log(`\n${c.bold}Installing theme from:${c.reset} ${resolvedSource}\n`);
245
262
 
246
- // Validate first
247
- const validation = await validateThemeBundle(resolvedSource);
248
- if (!validation.valid || !validation.manifest) {
249
- console.log(` ${c.red}Validation failed:${c.reset}`);
250
- for (const error of validation.errors) {
251
- console.log(` ${c.red}-${c.reset} ${error}`);
263
+ const result = await installBundleFile(resolvedSource, dataDir, {});
264
+ if (!result.ok) {
265
+ if (result.error) console.log(` ${c.red}Installation failed:${c.reset} ${result.error}`);
266
+ else {
267
+ console.log(` ${c.red}Validation failed:${c.reset}`);
268
+ printProblems(result.validation, ' ');
252
269
  }
253
270
  console.log('');
254
271
  return false;
255
272
  }
256
273
 
257
- const manifest = validation.manifest;
258
- const themeId = manifest.id;
259
- const themesDir = getThemesDir(dataDir);
260
- const installPath = path.join(themesDir, themeId);
261
-
262
- // Remove existing installation
263
- try {
264
- await fsp.rm(installPath, { recursive: true, force: true });
265
- } catch {
266
- // Ignore
267
- }
268
-
269
- // Create directory and extract
270
- await fsp.mkdir(installPath, { recursive: true });
271
-
272
- try {
273
- await extractZipToDir(resolvedSource, installPath);
274
-
275
- // If theme.json is in a subdirectory, move contents up
276
- const directThemeJson = path.join(installPath, 'theme.json');
277
- try {
278
- await fsp.access(directThemeJson);
279
- } catch {
280
- const entries = await fsp.readdir(installPath, { withFileTypes: true });
281
- const subdirs = entries.filter(e => e.isDirectory());
282
- for (const subdir of subdirs) {
283
- const subThemeJson = path.join(installPath, subdir.name, 'theme.json');
284
- try {
285
- await fsp.access(subThemeJson);
286
- const subPath = path.join(installPath, subdir.name);
287
- const subEntries = await fsp.readdir(subPath);
288
- for (const entry of subEntries) {
289
- await fsp.rename(
290
- path.join(subPath, entry),
291
- path.join(installPath, entry)
292
- );
293
- }
294
- await fsp.rmdir(subPath);
295
- break;
296
- } catch {
297
- continue;
298
- }
299
- }
300
- }
301
-
302
- // Update index
303
- const index = await readIndex(dataDir);
304
- index.themes = index.themes.filter(t => t.id !== themeId);
305
- index.themes.push({
306
- id: themeId,
307
- version: manifest.version,
308
- installedAt: new Date().toISOString(),
309
- source: 'file',
310
- sourceUrl: null,
311
- registrySource: null,
312
- signatureVerified: false,
313
- });
314
- await writeIndex(index, dataDir);
315
-
316
- console.log(` ${c.green}Installed successfully${c.reset}`);
317
- console.log(` Theme: ${manifest.name} (${themeId}) v${manifest.version}`);
318
- console.log(` Path: ${installPath}`);
319
- console.log('');
320
- return true;
321
- } catch (err) {
322
- // Clean up on failure
323
- try { await fsp.rm(installPath, { recursive: true, force: true }); } catch { /* ignore */ }
324
- console.log(` ${c.red}Installation failed:${c.reset} ${err.message}`);
325
- console.log('');
326
- return false;
327
- }
274
+ console.log(` ${c.green}Installed successfully${c.reset}`);
275
+ console.log(` Theme: ${result.manifest.name} (${result.manifest.id}) v${result.manifest.version}`);
276
+ console.log(` Path: ${result.installPath}`);
277
+ printWarnings(result.validation, ' ');
278
+ console.log('');
279
+ return true;
328
280
  }
329
281
 
330
282
  /**
331
283
  * Uninstall a theme bundle
332
284
  */
333
285
  async function uninstallTheme(themeId, dataDir) {
334
- const themesDir = getThemesDir(dataDir);
335
- const installPath = path.join(themesDir, themeId);
286
+ const installPath = installPathFor(themeId, dataDir);
336
287
 
337
288
  console.log(`\n${c.bold}Uninstalling theme:${c.reset} ${themeId}\n`);
338
289
 
339
290
  // Check if theme exists
340
291
  try {
292
+ if (!installPath) throw new Error('not a theme id');
341
293
  await fsp.access(installPath);
342
294
  } catch {
343
295
  console.log(` ${c.red}Theme "${themeId}" not found.${c.reset}`);
@@ -359,32 +311,35 @@ async function uninstallTheme(themeId, dataDir) {
359
311
  }
360
312
 
361
313
  /**
362
- * Export a theme as .qtap-theme bundle
314
+ * Export an installed theme as a .qtap-theme bundle. The installed directory
315
+ * is validated first; a theme made for an earlier Quilltap is refused.
363
316
  */
364
317
  async function exportTheme(themeId, outputPath, dataDir) {
365
318
  const themesDir = getThemesDir(dataDir);
366
- const themePath = path.join(themesDir, themeId);
319
+ const themePath = installPathFor(themeId, dataDir);
367
320
 
368
321
  console.log(`\n${c.bold}Exporting theme:${c.reset} ${themeId}\n`);
369
322
 
370
- // Check if theme exists
371
323
  try {
324
+ if (!themePath) throw new Error('not a theme id');
372
325
  await fsp.access(path.join(themePath, 'theme.json'));
373
326
  } catch {
374
327
  console.log(` ${c.red}Theme "${themeId}" not found in ${themesDir}.${c.reset}`);
375
- console.log(` ${c.dim}Note: Only installed bundle themes can be exported from the CLI.${c.reset}`);
376
- console.log(` ${c.dim}To export plugin themes, use the web UI export button.${c.reset}`);
377
328
  console.log('');
378
329
  return false;
379
330
  }
380
331
 
381
- // Default output path
382
- const finalOutput = outputPath || `${themeId}.qtap-theme`;
383
- const resolvedOutput = path.resolve(finalOutput);
332
+ const validation = await engine.validateThemeDirectory(themePath);
333
+ if (!validation.valid) {
334
+ console.log(` ${c.red}Not exported:${c.reset}`);
335
+ printProblems(validation, ' ');
336
+ console.log('');
337
+ return false;
338
+ }
384
339
 
385
- // Create zip
340
+ const resolvedOutput = path.resolve(outputPath || `${themeId}.qtap-theme`);
386
341
  try {
387
- execSync(`cd "${themePath}" && zip -r "${resolvedOutput}" .`, { stdio: 'pipe' });
342
+ await engine.packThemeDirectory(themePath, resolvedOutput);
388
343
  console.log(` ${c.green}Exported successfully${c.reset}`);
389
344
  console.log(` Output: ${resolvedOutput}`);
390
345
  console.log('');
@@ -759,67 +714,21 @@ async function updateThemes(themeId, dataDir) {
759
714
  console.log(`${c.green}OK${c.reset}`);
760
715
  process.stdout.write(` Installing... `);
761
716
 
762
- // Use existing install logic
763
- const validation = await validateThemeBundle(tmpFile);
764
- if (!validation.valid || !validation.manifest) {
765
- console.log(`${c.red}validation failed${c.reset}`);
766
- await fsp.unlink(tmpFile).catch(() => {});
767
- continue;
768
- }
769
-
770
- const manifest = validation.manifest;
771
- const themesDir = getThemesDir(dataDir);
772
- const installPath = path.join(themesDir, installed.id);
773
-
774
- await fsp.rm(installPath, { recursive: true, force: true });
775
- await fsp.mkdir(installPath, { recursive: true });
776
- await extractZipToDir(tmpFile, installPath);
777
-
778
- // Handle subdirectory layout
779
- const directThemeJson = path.join(installPath, 'theme.json');
780
- try {
781
- await fsp.access(directThemeJson);
782
- } catch {
783
- const entries = await fsp.readdir(installPath, { withFileTypes: true });
784
- const subdirs = entries.filter(e => e.isDirectory());
785
- for (const subdir of subdirs) {
786
- const subThemeJson = path.join(installPath, subdir.name, 'theme.json');
787
- try {
788
- await fsp.access(subThemeJson);
789
- const subPath = path.join(installPath, subdir.name);
790
- const subEntries = await fsp.readdir(subPath);
791
- for (const entry of subEntries) {
792
- await fsp.rename(
793
- path.join(subPath, entry),
794
- path.join(installPath, entry)
795
- );
796
- }
797
- await fsp.rmdir(subPath);
798
- break;
799
- } catch {
800
- continue;
801
- }
802
- }
803
- }
804
-
805
- // Update index entry
806
- const currentIndex = await readIndex(dataDir);
807
- currentIndex.themes = currentIndex.themes.filter(t => t.id !== installed.id);
808
- currentIndex.themes.push({
809
- id: installed.id,
810
- version: manifest.version,
811
- installedAt: new Date().toISOString(),
717
+ const result = await installBundleFile(tmpFile, dataDir, {
812
718
  source: 'registry',
813
719
  sourceUrl: available.downloadUrl,
814
720
  registrySource: available._registry,
815
- signatureVerified: false,
816
721
  });
817
- await writeIndex(currentIndex, dataDir);
722
+ await fsp.unlink(tmpFile).catch(() => {});
723
+ if (!result.ok) {
724
+ console.log(`${c.red}${result.error || 'validation failed'}${c.reset}`);
725
+ if (!result.error) printProblems(result.validation, ' ');
726
+ console.log('');
727
+ continue;
728
+ }
729
+ const manifest = result.manifest;
818
730
 
819
731
  console.log(`${c.green}OK${c.reset} (v${manifest.version})`);
820
-
821
- // Clean up temp file
822
- await fsp.unlink(tmpFile).catch(() => {});
823
732
  } catch (err) {
824
733
  console.log(`${c.red}${err.message}${c.reset}`);
825
734
  }
@@ -1040,6 +949,47 @@ ${c.bold}For Registry Operators:${c.reset}
1040
949
  }
1041
950
  }
1042
951
 
952
+ /**
953
+ * Create a blank theme bundle in ./<id>/, the id derived from the name as
954
+ * the Atelier derives one. The files are the engine's blank bundle, the same
955
+ * a new draft in the Atelier starts from. Refuses a directory that exists.
956
+ */
957
+ async function createTheme(name, cwd = process.cwd()) {
958
+ const trimmed = name.trim();
959
+ if (!trimmed) {
960
+ console.error('Error: create requires a theme name');
961
+ console.error('Usage: quilltap themes create <name>');
962
+ return false;
963
+ }
964
+ const id = engine.themeIdFromName(trimmed);
965
+ const dir = path.join(cwd, id);
966
+ const relDir = `./${id}`;
967
+
968
+ try {
969
+ await fsp.mkdir(dir);
970
+ } catch (err) {
971
+ if (err.code === 'EEXIST') {
972
+ console.error(`${c.red}Error:${c.reset} ${relDir} already exists; choose another name or move it aside.`);
973
+ } else {
974
+ console.error(`${c.red}Error:${c.reset} could not create ${relDir}: ${err.message}`);
975
+ }
976
+ return false;
977
+ }
978
+
979
+ for (const file of engine.blankThemeBundle({ id, name: trimmed })) {
980
+ await fsp.writeFile(path.join(dir, file.path), file.text, 'utf-8');
981
+ }
982
+
983
+ console.log(`\n${c.green}Created${c.reset} ${c.bold}${trimmed}${c.reset} in ${relDir}\n`);
984
+ console.log(`${c.bold}Next steps:${c.reset}`);
985
+ console.log(` 1. Check it: quilltap themes validate ${relDir}`);
986
+ console.log(` 2. Pack it: cd ${id} && zip -r ../${id}.qtap-theme . && cd ..`);
987
+ console.log(` 3. Open ${id}.qtap-theme in the Atelier (/calliope → "Open a theme file")`);
988
+ console.log(' and carry on there.');
989
+ console.log('');
990
+ return true;
991
+ }
992
+
1043
993
  // ============================================================================
1044
994
  // HELP
1045
995
  // ============================================================================
@@ -1054,9 +1004,9 @@ ${c.bold}Commands:${c.reset}
1054
1004
  list List installed theme bundles
1055
1005
  install <file> Install a .qtap-theme bundle
1056
1006
  uninstall <id> Uninstall a theme bundle
1057
- validate <file> Validate a .qtap-theme file
1007
+ validate <file|dir> Validate a .qtap-theme file or a bundle directory
1058
1008
  export <id> [--output <path>] Export a theme as .qtap-theme
1059
- create <name> Create a new theme (delegates to create-quilltap-theme)
1009
+ create <name> Create a blank theme bundle in ./<id>/
1060
1010
  search <query> Search across registries for themes
1061
1011
  update [id] Update one or all themes from registry
1062
1012
 
@@ -1080,6 +1030,7 @@ ${c.bold}Options:${c.reset}
1080
1030
  ${c.bold}Examples:${c.reset}
1081
1031
  quilltap themes list
1082
1032
  quilltap themes validate my-theme.qtap-theme
1033
+ quilltap themes validate ./my-theme/
1083
1034
  quilltap themes install my-theme.qtap-theme
1084
1035
  quilltap themes uninstall my-theme
1085
1036
  quilltap themes export my-theme --output ./my-theme.qtap-theme
@@ -1159,8 +1110,8 @@ async function themesCommand(args) {
1159
1110
 
1160
1111
  case 'validate': {
1161
1112
  if (positional.length === 0) {
1162
- console.error('Error: validate requires a file path');
1163
- console.error('Usage: quilltap themes validate <file.qtap-theme>');
1113
+ console.error('Error: validate requires a file or directory path');
1114
+ console.error('Usage: quilltap themes validate <file.qtap-theme | bundle-dir>');
1164
1115
  process.exit(1);
1165
1116
  }
1166
1117
  const isValid = await validateTheme(positional[0]);
@@ -1202,17 +1153,13 @@ async function themesCommand(args) {
1202
1153
  }
1203
1154
 
1204
1155
  case 'create': {
1205
- // Delegate to create-quilltap-theme
1206
- const createArgs = positional.join(' ');
1207
- console.log(`\nDelegating to create-quilltap-theme...\n`);
1208
- try {
1209
- execSync(`npx create-quilltap-theme ${createArgs}`, {
1210
- stdio: 'inherit',
1211
- cwd: process.cwd(),
1212
- });
1213
- } catch {
1156
+ if (positional.length === 0) {
1157
+ console.error('Error: create requires a theme name');
1158
+ console.error('Usage: quilltap themes create <name>');
1214
1159
  process.exit(1);
1215
1160
  }
1161
+ const created = await createTheme(positional.join(' '));
1162
+ process.exit(created ? 0 : 1);
1216
1163
  break;
1217
1164
  }
1218
1165
 
@@ -1236,4 +1183,4 @@ async function themesCommand(args) {
1236
1183
  }
1237
1184
  }
1238
1185
 
1239
- module.exports = { themesCommand };
1186
+ module.exports = { themesCommand, createTheme };