create-fs-app 2.0.5 → 3.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.
Files changed (59) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +271 -158
  3. package/dist/cli/output.js +223 -0
  4. package/dist/cli/program.js +403 -0
  5. package/dist/cli/resolve-config.js +264 -0
  6. package/dist/cli/ui/errors.js +27 -0
  7. package/dist/cli/ui/help.js +43 -0
  8. package/dist/cli/ui/hints.js +22 -0
  9. package/dist/cli/ui/layer-log.js +113 -0
  10. package/dist/cli/ui/list.js +115 -0
  11. package/dist/cli/ui/text.js +56 -0
  12. package/dist/cli/wizard.js +275 -0
  13. package/dist/core/auth/jwt.js +478 -0
  14. package/dist/core/download.js +109 -0
  15. package/dist/core/health-check.js +46 -44
  16. package/dist/core/presets.js +75 -117
  17. package/dist/core/registry-fetch.js +101 -81
  18. package/dist/core/registry.fallback.json +904 -0
  19. package/dist/core/scaffold.js +121 -75
  20. package/dist/core/stack.js +109 -0
  21. package/dist/core/template-cache.js +95 -154
  22. package/dist/core/template-clone.js +353 -656
  23. package/dist/core/template-list.js +19 -141
  24. package/dist/core/template-registry.js +116 -216
  25. package/dist/index.js +13 -963
  26. package/dist/types/index.js +30 -82
  27. package/dist/utils/cli-error.js +15 -0
  28. package/dist/utils/exec.js +62 -0
  29. package/dist/utils/logger.js +10 -9
  30. package/dist/utils/theme.js +87 -0
  31. package/dist/utils/validation.js +24 -13
  32. package/package.json +38 -32
  33. package/dist/core/health-check.d.ts +0 -15
  34. package/dist/core/health-check.js.map +0 -1
  35. package/dist/core/presets.d.ts +0 -48
  36. package/dist/core/presets.js.map +0 -1
  37. package/dist/core/registry-fetch.d.ts +0 -20
  38. package/dist/core/registry-fetch.js.map +0 -1
  39. package/dist/core/scaffold.d.ts +0 -40
  40. package/dist/core/scaffold.js.map +0 -1
  41. package/dist/core/template-cache.d.ts +0 -38
  42. package/dist/core/template-cache.js.map +0 -1
  43. package/dist/core/template-clone.d.ts +0 -27
  44. package/dist/core/template-clone.js.map +0 -1
  45. package/dist/core/template-list.d.ts +0 -45
  46. package/dist/core/template-list.js.map +0 -1
  47. package/dist/core/template-registry.d.ts +0 -78
  48. package/dist/core/template-registry.js.map +0 -1
  49. package/dist/index.d.ts +0 -2
  50. package/dist/index.js.map +0 -1
  51. package/dist/types/index.d.ts +0 -102
  52. package/dist/types/index.js.map +0 -1
  53. package/dist/utils/errors.d.ts +0 -15
  54. package/dist/utils/errors.js +0 -50
  55. package/dist/utils/errors.js.map +0 -1
  56. package/dist/utils/logger.d.ts +0 -37
  57. package/dist/utils/logger.js.map +0 -1
  58. package/dist/utils/validation.d.ts +0 -48
  59. package/dist/utils/validation.js.map +0 -1
@@ -1,104 +1,150 @@
1
1
  /**
2
2
  * Project Scaffolding
3
- * Main orchestrator for creating projects from templates
3
+ *
4
+ * planScaffold() resolves the template and where its files come from without
5
+ * writing anything (also used by --dry-run); scaffoldProject() executes a plan
6
+ * and removes the target directory again if copying or customizing fails.
4
7
  */
5
8
  import path from 'path';
6
- import { getTemplate, getSuggestedTemplates } from './template-registry.js';
7
- import { cloneTemplate, customizeTemplate, initializeGit, installDependencies } from './template-clone.js';
9
+ import fs from 'fs/promises';
10
+ import { existsSync } from 'fs';
11
+ import { getOfficialTemplates } from './template-registry.js';
12
+ import { findTemplate, suggestTemplates, describeStack } from './stack.js';
13
+ import { tarballUrl } from './download.js';
14
+ import { getCacheEntry } from './template-cache.js';
15
+ import { cloneTemplate, customizeTemplate, initializeGit, installDependencies, } from './template-clone.js';
16
+ import { CliError } from '../utils/cli-error.js';
17
+ /** Thrown when dependency installation fails; the project itself was created. */
18
+ export class InstallError extends CliError {
19
+ constructor(details) {
20
+ super('Dependency install failed', details);
21
+ this.name = 'InstallError';
22
+ }
23
+ }
24
+ function isRegistered(template) {
25
+ return 'key' in template && typeof template.key === 'string';
26
+ }
27
+ async function resolveSource(template, noCache) {
28
+ if (template.localPath)
29
+ return { type: 'local', path: template.localPath };
30
+ if (!template.url)
31
+ throw new Error('Template has neither a local path nor a repository URL');
32
+ const download = { type: 'download', url: tarballUrl(template.url, template.branch ?? 'HEAD'), subfolder: template.subfolder };
33
+ if (noCache)
34
+ return download;
35
+ const entry = await getCacheEntry(template);
36
+ if (entry?.fresh)
37
+ return { type: 'cache', path: entry.path, cachedAt: entry.cachedAt };
38
+ if (entry)
39
+ return { ...download, staleCache: { path: entry.path, cachedAt: entry.cachedAt } };
40
+ return download;
41
+ }
42
+ /** Resolve template and source for `config`. Reads the cache index; writes nothing. */
43
+ export async function planScaffold(config, options = {}) {
44
+ const template = options.template
45
+ ?? (config.stack ? findTemplate(getOfficialTemplates(), config.stack) : null);
46
+ if (!template) {
47
+ throw new TemplateNotFoundError(config);
48
+ }
49
+ const kind = options.kind ?? 'official';
50
+ const noCache = options.noCache === true;
51
+ const templateLabel = isRegistered(template)
52
+ ? template.key
53
+ : `${template.url ?? 'unknown'}${template.subfolder ? ` (${template.subfolder})` : ''}`;
54
+ return {
55
+ // A template without Docker files has nothing to keep
56
+ config: template.supports.docker ? config : { ...config, docker: false },
57
+ targetDir: path.join(options.cwd ?? process.cwd(), config.name),
58
+ template,
59
+ templateLabel,
60
+ kind,
61
+ source: await resolveSource(template, noCache),
62
+ noCache,
63
+ };
64
+ }
8
65
  /**
9
- * Main scaffolding function - creates project from template
66
+ * Execute a plan. If copying or customizing fails, the target directory is
67
+ * removed so a retry can use the same name. A failed install keeps the
68
+ * project and throws InstallError.
10
69
  */
11
- export async function scaffoldProject(config, options = {}) {
12
- const { name } = config;
13
- const targetDir = path.join(process.cwd(), name);
70
+ export async function scaffoldProject(plan, hooks = {}) {
71
+ const { config, targetDir } = plan;
72
+ await validateProjectDirectory(targetDir);
73
+ let started = 0;
74
+ const start = (step) => {
75
+ hooks.onStep?.(step);
76
+ started = performance.now();
77
+ };
78
+ const done = (step, source) => {
79
+ hooks.onStepDone?.(step, { ms: performance.now() - started, ...(source ? { source } : {}) });
80
+ };
14
81
  try {
15
- // 1. Resolve template — custom (--template-url) takes priority over registry lookup
16
- let template = options.customTemplate ?? getTemplate(config);
17
- if (!template) {
18
- throw new TemplateNotFoundError(config);
19
- }
20
- // Override with local path when --local-templates is set
21
- if (options.localTemplatesDir) {
22
- const { getTemplateKey } = await import('./template-registry.js');
23
- const key = getTemplateKey(config);
24
- const localPath = path.join(options.localTemplatesDir, 'templates', key);
25
- template = { ...template, localPath, url: undefined, subfolder: undefined };
26
- }
27
- // 2. Clone the template
28
- await cloneTemplate(template, targetDir, template.branch ?? 'main', options.skipCache ?? false);
29
- // 3. Customize the template
30
- await customizeTemplate(targetDir, config);
31
- // 4. Initialize git (if not skipped)
32
- if (!options.skipGit) {
33
- await initializeGit(targetDir, config);
34
- }
35
- // 5. Install dependencies (if not skipped)
36
- if (!options.skipInstall) {
37
- await installDependencies(targetDir, config.packageManager);
38
- }
39
- // Ensure cursor is visible
40
- process.stdout.write('\x1B[?25h');
82
+ start('copy');
83
+ const source = await cloneTemplate(plan.template, targetDir, { noCache: plan.noCache });
84
+ done('copy', source);
85
+ start('customize');
86
+ await customizeTemplate(targetDir, config, { kind: plan.kind });
87
+ done('customize');
41
88
  }
42
89
  catch (error) {
43
- // Ensure cursor is visible on error
44
- process.stdout.write('\x1B[?25h');
45
- if (error instanceof TemplateNotFoundError) {
46
- throw error;
90
+ await fs.rm(targetDir, { recursive: true, force: true });
91
+ throw error;
92
+ }
93
+ if (config.git) {
94
+ start('git');
95
+ await initializeGit(targetDir, config);
96
+ done('git');
97
+ }
98
+ if (config.install) {
99
+ start('install');
100
+ try {
101
+ await installDependencies(targetDir, config.packageManager);
102
+ }
103
+ catch (error) {
104
+ const reason = (error instanceof Error ? error.message : String(error)).replace(/^Failed to install dependencies: /, '');
105
+ throw new InstallError({
106
+ reason: `${reason}\nThe project was created in ${targetDir}.`,
107
+ fix: `cd ${config.name} && ${config.packageManager} install`,
108
+ });
47
109
  }
48
- throw new Error(`Failed to scaffold project: ${error instanceof Error ? error.message : 'Unknown error'}`);
110
+ done('install');
49
111
  }
50
112
  }
51
113
  /**
52
114
  * Custom error for when a template doesn't exist
53
115
  */
54
- export class TemplateNotFoundError extends Error {
116
+ export class TemplateNotFoundError extends CliError {
55
117
  suggestions;
56
118
  constructor(config) {
57
- const message = `
58
- ❌ Template not found for your configuration:
59
- - Monorepo: ${config.monorepo}
60
- - Frontend: ${config.apps.frontend.framework}
61
- - Backend: ${config.apps.backend.framework}
62
- - Database: ${config.apps.backend.database}
63
- - ORM: ${config.apps.backend.orm || 'none'}
64
-
65
- This combination doesn't have a pre-built template yet.
66
- `;
67
- super(message);
119
+ const suggestions = suggestTemplates(getOfficialTemplates(), config.stack ?? {}).map(t => t.key);
120
+ super(`No template for ${config.stack ? describeStack(config.stack) : 'this configuration'}`, {
121
+ reason: suggestions.length > 0 ? ['Closest:', ...suggestions.map(key => ` ${key}`)].join('\n') : undefined,
122
+ fix: 'create-fs-app list',
123
+ });
68
124
  this.name = 'TemplateNotFoundError';
69
- // Get suggested alternatives
70
- const suggested = getSuggestedTemplates(config);
71
- this.suggestions = suggested.map(t => t.description);
125
+ this.suggestions = suggestions;
72
126
  }
73
127
  }
74
128
  /**
75
- * Validate that a project directory doesn't already exist
129
+ * Validate that a project directory doesn't already exist.
130
+ * `nameOrPath` is resolved against the current directory.
76
131
  */
77
- export async function validateProjectDirectory(name) {
78
- const targetDir = path.join(process.cwd(), name);
79
- const fs = await import('fs/promises');
132
+ export async function validateProjectDirectory(nameOrPath) {
133
+ const targetDir = path.resolve(nameOrPath);
80
134
  try {
81
135
  await fs.access(targetDir);
82
- throw new Error(`Directory "${name}" already exists. Please choose a different name or remove the existing directory.`);
83
136
  }
84
137
  catch (error) {
85
- if (error.code === 'ENOENT') {
86
- // Directory doesn't exist, which is what we want
87
- return;
88
- }
138
+ if (error.code === 'ENOENT')
139
+ return; // what we want
89
140
  throw error;
90
141
  }
142
+ const name = path.basename(targetDir);
143
+ let n = 2;
144
+ while (existsSync(path.join(path.dirname(targetDir), `${name}-${n}`)))
145
+ n++;
146
+ throw new CliError(`Directory "${name}" already exists`, {
147
+ reason: 'create-fs-app only writes into a new directory.',
148
+ fix: `create-fs-app ${name}-${n}`,
149
+ });
91
150
  }
92
- /**
93
- * Check if template exists before starting
94
- */
95
- export function checkTemplateAvailability(config) {
96
- const template = getTemplate(config);
97
- if (template) {
98
- return { available: true, template };
99
- }
100
- const suggestions = getSuggestedTemplates(config)
101
- .map(t => t.description);
102
- return { available: false, suggestions };
103
- }
104
- //# sourceMappingURL=scaffold.js.map
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Stack filtering over the template registry.
3
+ *
4
+ * Pure functions: given the official templates and the answers so far, they
5
+ * tell which values are still possible for the next field, find the exact
6
+ * template for a complete stack, and suggest close alternatives.
7
+ */
8
+ /** Question order in the wizard; filtering only looks at earlier fields. */
9
+ export const STACK_FIELDS = ['monorepo', 'frontend', 'backend', 'database', 'orm'];
10
+ /** Accepted spellings (lowercase) mapped to registry values. */
11
+ export const ALIASES = {
12
+ monorepo: {},
13
+ frontend: { nextjs: 'next.js' },
14
+ backend: { nestjs: 'nest.js', 'fastify-ts': 'fastify' },
15
+ database: { postgres: 'postgresql', mongo: 'mongodb' },
16
+ orm: {},
17
+ };
18
+ export const FIELD_LABELS = {
19
+ monorepo: 'Monorepo',
20
+ frontend: 'Frontend',
21
+ backend: 'Backend',
22
+ database: 'Database',
23
+ orm: 'ORM',
24
+ };
25
+ /** Display names for registry values. Unknown values are shown as-is. */
26
+ export const LABELS = {
27
+ turborepo: 'Turborepo',
28
+ 'next.js': 'Next.js',
29
+ react: 'React',
30
+ vue: 'Vue',
31
+ 'nest.js': 'NestJS',
32
+ express: 'Express',
33
+ fastify: 'Fastify',
34
+ hono: 'Hono',
35
+ postgresql: 'PostgreSQL',
36
+ mongodb: 'MongoDB',
37
+ sqlite: 'SQLite',
38
+ prisma: 'Prisma',
39
+ mongoose: 'Mongoose',
40
+ drizzle: 'Drizzle',
41
+ };
42
+ export function labelFor(value) {
43
+ return LABELS[value] ?? value;
44
+ }
45
+ /** Lowercase, trim and resolve aliases ("NextJS" → "next.js"). */
46
+ export function normalizeValue(field, value) {
47
+ const v = value.trim().toLowerCase();
48
+ return ALIASES[field][v] ?? v;
49
+ }
50
+ /** Normalize every given field of a partial stack. */
51
+ export function normalizeStack(stack) {
52
+ const out = {};
53
+ for (const field of STACK_FIELDS) {
54
+ const value = stack[field];
55
+ if (value !== undefined)
56
+ out[field] = normalizeValue(field, value);
57
+ }
58
+ return out;
59
+ }
60
+ function matchesEarlier(template, field, answers) {
61
+ for (const earlier of STACK_FIELDS) {
62
+ if (earlier === field)
63
+ return true;
64
+ const answer = answers[earlier];
65
+ if (answer !== undefined && template.stack[earlier] !== answer)
66
+ return false;
67
+ }
68
+ return true;
69
+ }
70
+ /**
71
+ * Values of `field` that have at least one template given the answers to the
72
+ * fields before it (in STACK_FIELDS order). Registry order, no duplicates.
73
+ */
74
+ export function availableOptions(templates, field, answers) {
75
+ const values = [];
76
+ for (const template of templates) {
77
+ if (!matchesEarlier(template, field, answers))
78
+ continue;
79
+ const value = template.stack[field];
80
+ if (!values.includes(value))
81
+ values.push(value);
82
+ }
83
+ return values;
84
+ }
85
+ /** The only option, when exactly one remains. */
86
+ export function autoPick(options) {
87
+ return options.length === 1 ? options[0] : undefined;
88
+ }
89
+ /** Exact match on all five fields; no partial or prefix fallbacks. */
90
+ export function findTemplate(templates, stack) {
91
+ return templates.find(t => STACK_FIELDS.every(f => t.stack[f] === stack[f])) ?? null;
92
+ }
93
+ /** Up to `max` templates sharing the most fields with `stack` (at least one). */
94
+ export function suggestTemplates(templates, stack, max = 3) {
95
+ return templates
96
+ .map((template, index) => ({
97
+ template,
98
+ index,
99
+ score: STACK_FIELDS.filter(f => stack[f] !== undefined && template.stack[f] === stack[f]).length,
100
+ }))
101
+ .filter(s => s.score > 0)
102
+ .sort((a, b) => b.score - a.score || a.index - b.index)
103
+ .slice(0, max)
104
+ .map(s => s.template);
105
+ }
106
+ /** "Next.js + NestJS + PostgreSQL + Prisma" (monorepo omitted). */
107
+ export function describeStack(stack) {
108
+ return [stack.frontend, stack.backend, stack.database, stack.orm].map(labelFor).join(' + ');
109
+ }
@@ -1,188 +1,129 @@
1
1
  /**
2
2
  * Template Caching System
3
- * Caches templates locally for faster project creation
3
+ *
4
+ * Downloaded templates are kept in ~/.create-fs-app/cache/<key> for 24 h.
5
+ * Older copies are re-downloaded; when that fails (offline), the stale copy
6
+ * is used with a warning. Local templates are never cached.
4
7
  */
5
8
  import fs from 'fs/promises';
6
9
  import path from 'path';
7
10
  import os from 'os';
8
- import { execa } from 'execa';
11
+ import { randomUUID } from 'crypto';
9
12
  import { Logger } from '../utils/logger.js';
10
- const CACHE_DIR = path.join(os.homedir(), '.create-fs-app', 'cache');
13
+ import { CliError } from '../utils/cli-error.js';
14
+ import { downloadTemplate } from './download.js';
15
+ export const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours
11
16
  const CACHE_VERSION = '1';
12
17
  const CACHE_METADATA_FILE = 'cache-metadata.json';
13
- /**
14
- * Initialize cache directory
15
- */
16
- async function ensureCacheDir() {
17
- try {
18
- await fs.mkdir(CACHE_DIR, { recursive: true });
19
- Logger.debug(`Cache directory: ${CACHE_DIR}`);
20
- }
21
- catch (error) {
22
- Logger.warn('Failed to create cache directory');
23
- }
18
+ /** Resolved lazily so HOME can change (tests). */
19
+ export function getCacheDir() {
20
+ return path.join(os.homedir(), '.create-fs-app', 'cache');
24
21
  }
25
- /**
26
- * Get cache metadata
27
- */
28
22
  async function getCacheMetadata() {
29
- const metadataPath = path.join(CACHE_DIR, CACHE_METADATA_FILE);
30
23
  try {
31
- const content = await fs.readFile(metadataPath, 'utf-8');
32
- return JSON.parse(content);
24
+ const content = await fs.readFile(path.join(getCacheDir(), CACHE_METADATA_FILE), 'utf-8');
25
+ const parsed = JSON.parse(content);
26
+ return { version: CACHE_VERSION, templates: parsed.templates ?? {} };
33
27
  }
34
28
  catch {
35
- return {
36
- version: CACHE_VERSION,
37
- templates: {}
38
- };
29
+ return { version: CACHE_VERSION, templates: {} };
39
30
  }
40
31
  }
41
- /**
42
- * Save cache metadata
43
- */
44
32
  async function saveCacheMetadata(metadata) {
45
- const metadataPath = path.join(CACHE_DIR, CACHE_METADATA_FILE);
46
- await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2));
33
+ await fs.mkdir(getCacheDir(), { recursive: true });
34
+ await fs.writeFile(path.join(getCacheDir(), CACHE_METADATA_FILE), JSON.stringify(metadata, null, 2));
47
35
  }
48
- /**
49
- * Generate cache key for a template
50
- */
51
- function getCacheKey(template) {
52
- // For local templates, use the folder name
53
- if (template.localPath) {
54
- return path.basename(template.localPath);
55
- }
56
- // For remote templates
36
+ function refOf(template) {
37
+ return template.branch ?? 'HEAD';
38
+ }
39
+ /** Cache key = repo + ref + subfolder. */
40
+ export function getCacheKey(template) {
57
41
  if (!template.url) {
58
- throw new Error('Template must have either localPath or url');
42
+ throw new Error('Only remote templates can be cached');
59
43
  }
60
44
  const url = template.url.replace(/https?:\/\//, '').replace(/\.git$/, '');
61
- const branch = template.branch || 'main';
62
45
  const subfolder = template.subfolder || '';
63
- return `${url}-${branch}-${subfolder}`.replace(/[^a-z0-9-]/gi, '_');
46
+ return `${url}-${refOf(template)}-${subfolder}`.replace(/[^a-z0-9-]/gi, '_');
64
47
  }
65
- /**
66
- * Check if template is cached
67
- */
68
- export async function isTemplateCached(template) {
69
- await ensureCacheDir();
70
- const cacheKey = getCacheKey(template);
71
- const cachePath = path.join(CACHE_DIR, cacheKey);
48
+ async function exists(p) {
72
49
  try {
73
- await fs.access(cachePath);
74
- Logger.debug(`Template found in cache: ${cacheKey}`);
50
+ await fs.access(p);
75
51
  return true;
76
52
  }
77
53
  catch {
78
- Logger.debug(`Template not in cache: ${cacheKey}`);
79
54
  return false;
80
55
  }
81
56
  }
82
- /**
83
- * Get cached template path
84
- */
85
- export async function getCachedTemplatePath(template) {
86
- const isCached = await isTemplateCached(template);
87
- if (!isCached)
57
+ /** Look up the cached copy without writing anything. */
58
+ export async function getCacheEntry(template) {
59
+ if (template.localPath || !template.url)
60
+ return null;
61
+ const key = getCacheKey(template);
62
+ const cachePath = path.join(getCacheDir(), key);
63
+ const meta = (await getCacheMetadata()).templates[key];
64
+ if (!meta || !(await exists(cachePath)))
88
65
  return null;
89
- const cacheKey = getCacheKey(template);
90
- const cachePath = path.join(CACHE_DIR, cacheKey);
91
- // Update last used time
66
+ const cachedAt = new Date(meta.cachedAt);
67
+ const age = Date.now() - cachedAt.getTime();
68
+ return { key, path: cachePath, cachedAt, fresh: Number.isFinite(age) && age < CACHE_TTL };
69
+ }
70
+ async function touch(key) {
92
71
  const metadata = await getCacheMetadata();
93
- if (metadata.templates[cacheKey]) {
94
- metadata.templates[cacheKey].lastUsed = new Date().toISOString();
72
+ const entry = metadata.templates[key];
73
+ if (entry) {
74
+ entry.lastUsed = new Date().toISOString();
95
75
  await saveCacheMetadata(metadata);
96
76
  }
77
+ }
78
+ /** Download a template into the cache, replacing any previous copy. Returns the cache path. */
79
+ export async function cacheTemplate(template) {
80
+ if (!template.url)
81
+ throw new Error('Only remote templates can be cached');
82
+ const key = getCacheKey(template);
83
+ const cacheDir = getCacheDir();
84
+ const cachePath = path.join(cacheDir, key);
85
+ const incoming = path.join(cacheDir, `.${key}.incoming-${randomUUID()}`);
86
+ Logger.verbose(`Downloading template into cache: ${key}`);
87
+ await downloadTemplate({ repoUrl: template.url, ref: refOf(template), subfolder: template.subfolder }, incoming);
88
+ await fs.rm(cachePath, { recursive: true, force: true });
89
+ await fs.rename(incoming, cachePath);
90
+ const now = new Date().toISOString();
91
+ const metadata = await getCacheMetadata();
92
+ metadata.templates[key] = { url: template.url, branch: refOf(template), subfolder: template.subfolder, cachedAt: now, lastUsed: now };
93
+ await saveCacheMetadata(metadata);
97
94
  return cachePath;
98
95
  }
99
96
  /**
100
- * Cache a template
97
+ * Path of an up-to-date copy of `template`: the fresh cache, a new download,
98
+ * or (when the download fails) the stale cache with a warning.
101
99
  */
102
- export async function cacheTemplate(template, branch = 'main') {
103
- // Don't cache local templates
104
- if (template.localPath) {
105
- Logger.debug('Skipping cache for local template');
106
- return template.localPath;
107
- }
108
- if (!template.url) {
109
- throw new Error('Remote template must have a url');
100
+ export async function getTemplateFromCache(template) {
101
+ const entry = await getCacheEntry(template);
102
+ if (entry?.fresh) {
103
+ Logger.verbose(`Using cached template (${entry.key})`);
104
+ await touch(entry.key);
105
+ return { path: entry.path, from: 'cache' };
110
106
  }
111
- await ensureCacheDir();
112
- const cacheKey = getCacheKey(template);
113
- const cachePath = path.join(CACHE_DIR, cacheKey);
114
- Logger.verbose(`Caching template: ${cacheKey}`);
115
107
  try {
116
- // Remove existing cache if present
117
- try {
118
- await fs.rm(cachePath, { recursive: true, force: true });
119
- }
120
- catch { }
121
- // Clone to cache
122
- if (template.subfolder) {
123
- // Clone entire repo to temp, then copy subfolder
124
- const tempPath = path.join(os.tmpdir(), `cfs-cache-${cacheKey}`);
125
- try {
126
- await execa('git', [
127
- 'clone',
128
- '--depth', '1',
129
- '--branch', branch,
130
- '--single-branch',
131
- template.url,
132
- tempPath
133
- ]);
134
- const templatePath = path.join(tempPath, template.subfolder);
135
- await fs.cp(templatePath, cachePath, { recursive: true });
136
- await fs.rm(tempPath, { recursive: true, force: true });
137
- }
138
- catch (error) {
139
- await fs.rm(tempPath, { recursive: true, force: true }).catch(() => { });
140
- throw error;
141
- }
142
- }
143
- else {
144
- // Direct clone
145
- await execa('git', [
146
- 'clone',
147
- '--depth', '1',
148
- '--branch', branch,
149
- template.url,
150
- cachePath
151
- ]);
152
- // Remove .git directory
153
- const gitDir = path.join(cachePath, '.git');
154
- await fs.rm(gitDir, { recursive: true, force: true });
155
- }
156
- // Update metadata
157
- const metadata = await getCacheMetadata();
158
- metadata.templates[cacheKey] = {
159
- url: template.url,
160
- branch,
161
- cachedAt: new Date().toISOString(),
162
- lastUsed: new Date().toISOString()
163
- };
164
- await saveCacheMetadata(metadata);
165
- Logger.debug(`Template cached successfully: ${cacheKey}`);
166
- return cachePath;
108
+ return { path: await cacheTemplate(template), from: 'download' };
167
109
  }
168
110
  catch (error) {
169
- Logger.warn(`Failed to cache template: ${error instanceof Error ? error.message : 'Unknown error'}`);
170
- throw error;
111
+ if (!entry)
112
+ throw error;
113
+ const reason = error instanceof CliError && error.reason
114
+ ? error.reason
115
+ : error instanceof Error ? error.message : String(error);
116
+ Logger.warn(`Could not refresh the template (${reason}). Using the cached copy from ${entry.cachedAt.toLocaleString()}.`);
117
+ await touch(entry.key);
118
+ return { path: entry.path, from: 'stale-cache' };
171
119
  }
172
120
  }
173
- /**
174
- * Copy cached template to target directory
175
- */
176
- export async function copyCachedTemplate(cachePath, targetDir) {
177
- Logger.verbose(`Copying from cache to ${targetDir}`);
178
- await fs.cp(cachePath, targetDir, { recursive: true });
179
- }
180
121
  /**
181
122
  * Clear template cache
182
123
  */
183
124
  export async function clearCache() {
184
125
  try {
185
- await fs.rm(CACHE_DIR, { recursive: true, force: true });
126
+ await fs.rm(getCacheDir(), { recursive: true, force: true });
186
127
  Logger.success('Cache cleared successfully');
187
128
  }
188
129
  catch (error) {
@@ -192,33 +133,32 @@ export async function clearCache() {
192
133
  }
193
134
  async function getDirSize(dirPath) {
194
135
  let size = 0;
136
+ let entries;
195
137
  try {
196
- const entries = await fs.readdir(dirPath, { withFileTypes: true });
197
- for (const entry of entries) {
198
- const full = path.join(dirPath, entry.name);
199
- if (entry.isDirectory()) {
200
- size += await getDirSize(full);
201
- }
202
- else {
203
- const s = await fs.stat(full);
204
- size += s.size;
205
- }
138
+ entries = await fs.readdir(dirPath, { withFileTypes: true });
139
+ }
140
+ catch {
141
+ return 0; // missing directory counts as empty
142
+ }
143
+ for (const entry of entries) {
144
+ const full = path.join(dirPath, entry.name);
145
+ if (entry.isDirectory()) {
146
+ size += await getDirSize(full);
147
+ }
148
+ else {
149
+ size += (await fs.stat(full)).size;
206
150
  }
207
151
  }
208
- catch { }
209
152
  return size;
210
153
  }
211
154
  /**
212
155
  * Get cache statistics
213
156
  */
214
157
  export async function getCacheStats() {
215
- await ensureCacheDir();
216
158
  const metadata = await getCacheMetadata();
217
- // Calculate cache size
218
159
  let totalSize = 0;
219
160
  for (const key of Object.keys(metadata.templates)) {
220
- const cachePath = path.join(CACHE_DIR, key);
221
- totalSize += await getDirSize(cachePath);
161
+ totalSize += await getDirSize(path.join(getCacheDir(), key));
222
162
  }
223
163
  const cacheSizeMB = (totalSize / (1024 * 1024)).toFixed(2);
224
164
  return {
@@ -226,8 +166,9 @@ export async function getCacheStats() {
226
166
  cacheSize: `${cacheSizeMB} MB`,
227
167
  templates: Object.entries(metadata.templates).map(([key, data]) => ({
228
168
  key,
229
- ...data
230
- }))
169
+ url: data.url,
170
+ cachedAt: data.cachedAt,
171
+ lastUsed: data.lastUsed,
172
+ })),
231
173
  };
232
174
  }
233
- //# sourceMappingURL=template-cache.js.map