@timeax/scaffold 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,1070 @@
1
+ #!/usr/bin/env node
2
+ import readline from 'readline';
3
+ import path2 from 'path';
4
+ import fs7 from 'fs';
5
+ import { Command } from 'commander';
6
+ import os from 'os';
7
+ import crypto from 'crypto';
8
+ import { pathToFileURL } from 'url';
9
+ import { transform } from 'esbuild';
10
+ import { minimatch } from 'minimatch';
11
+ import chokidar from 'chokidar';
12
+
13
+ // src/util/logger.ts
14
+ var supportsColor = typeof process !== "undefined" && process.stdout && process.stdout.isTTY && process.env.NO_COLOR !== "1";
15
+ function wrap(code) {
16
+ const open = `\x1B[${code}m`;
17
+ const close = `\x1B[0m`;
18
+ return (text) => supportsColor ? `${open}${text}${close}` : text;
19
+ }
20
+ var color = {
21
+ red: wrap(31),
22
+ yellow: wrap(33),
23
+ green: wrap(32),
24
+ cyan: wrap(36),
25
+ magenta: wrap(35),
26
+ dim: wrap(2),
27
+ bold: wrap(1),
28
+ gray: wrap(90)
29
+ };
30
+ function colorForLevel(level) {
31
+ switch (level) {
32
+ case "error":
33
+ return color.red;
34
+ case "warn":
35
+ return color.yellow;
36
+ case "info":
37
+ return color.cyan;
38
+ case "debug":
39
+ return color.gray;
40
+ default:
41
+ return (s) => s;
42
+ }
43
+ }
44
+ var Logger = class _Logger {
45
+ level;
46
+ prefix;
47
+ constructor(options = {}) {
48
+ this.level = options.level ?? "info";
49
+ this.prefix = options.prefix;
50
+ }
51
+ setLevel(level) {
52
+ this.level = level;
53
+ }
54
+ getLevel() {
55
+ return this.level;
56
+ }
57
+ /**
58
+ * Create a child logger with an additional prefix.
59
+ */
60
+ child(prefix) {
61
+ const combined = this.prefix ? `${this.prefix}${prefix}` : prefix;
62
+ return new _Logger({ level: this.level, prefix: combined });
63
+ }
64
+ formatMessage(msg, lvl) {
65
+ const text = typeof msg === "string" ? msg : msg instanceof Error ? msg.message : String(msg);
66
+ const levelColor = colorForLevel(lvl);
67
+ const prefixColored = this.prefix ? color.magenta(this.prefix) : void 0;
68
+ const textColored = lvl === "debug" ? color.dim(text) : levelColor(text);
69
+ if (prefixColored) {
70
+ return `${prefixColored} ${textColored}`;
71
+ }
72
+ return textColored;
73
+ }
74
+ shouldLog(targetLevel) {
75
+ const order = ["silent", "error", "warn", "info", "debug"];
76
+ const currentIdx = order.indexOf(this.level);
77
+ const targetIdx = order.indexOf(targetLevel);
78
+ if (currentIdx === -1 || targetIdx === -1) return true;
79
+ if (this.level === "silent") return false;
80
+ return targetIdx <= currentIdx || targetLevel === "error";
81
+ }
82
+ error(msg, ...rest) {
83
+ if (!this.shouldLog("error")) return;
84
+ console.error(this.formatMessage(msg, "error"), ...rest);
85
+ }
86
+ warn(msg, ...rest) {
87
+ if (!this.shouldLog("warn")) return;
88
+ console.warn(this.formatMessage(msg, "warn"), ...rest);
89
+ }
90
+ info(msg, ...rest) {
91
+ if (!this.shouldLog("info")) return;
92
+ console.log(this.formatMessage(msg, "info"), ...rest);
93
+ }
94
+ debug(msg, ...rest) {
95
+ if (!this.shouldLog("debug")) return;
96
+ console.debug(this.formatMessage(msg, "debug"), ...rest);
97
+ }
98
+ };
99
+ var defaultLogger = new Logger({
100
+ level: process.env.SCAFFOLD_LOG_LEVEL ?? "info",
101
+ prefix: "[scaffold]"
102
+ });
103
+ function toPosixPath(p) {
104
+ return p.replace(/\\/g, "/");
105
+ }
106
+ function ensureDirSync(dirPath) {
107
+ if (!fs7.existsSync(dirPath)) {
108
+ fs7.mkdirSync(dirPath, { recursive: true });
109
+ }
110
+ return dirPath;
111
+ }
112
+ function statSafeSync(targetPath) {
113
+ try {
114
+ return fs7.statSync(targetPath);
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+ function toProjectRelativePath(projectRoot, absolutePath) {
120
+ const absRoot = path2.resolve(projectRoot);
121
+ const absTarget = path2.resolve(absolutePath);
122
+ const rootWithSep = absRoot.endsWith(path2.sep) ? absRoot : absRoot + path2.sep;
123
+ if (!absTarget.startsWith(rootWithSep) && absTarget !== absRoot) {
124
+ throw new Error(
125
+ `Path "${absTarget}" is not inside project root "${absRoot}".`
126
+ );
127
+ }
128
+ const rel = path2.relative(absRoot, absTarget);
129
+ return toPosixPath(rel);
130
+ }
131
+
132
+ // src/core/config-loader.ts
133
+ var logger = defaultLogger.child("[config]");
134
+ async function loadScaffoldConfig(cwd, options = {}) {
135
+ const absCwd = path2.resolve(cwd);
136
+ const initialScaffoldDir = options.scaffoldDir ? path2.resolve(absCwd, options.scaffoldDir) : path2.join(absCwd, "scaffold");
137
+ const configPath = options.configPath ?? resolveConfigPath(initialScaffoldDir);
138
+ const config = await importConfig(configPath);
139
+ let configRoot = absCwd;
140
+ if (config.root) {
141
+ configRoot = path2.resolve(absCwd, config.root);
142
+ }
143
+ const scaffoldDir = options.scaffoldDir ? path2.resolve(absCwd, options.scaffoldDir) : path2.join(configRoot, "scaffold");
144
+ const baseRoot = config.base ? path2.resolve(configRoot, config.base) : configRoot;
145
+ logger.debug(
146
+ `Loaded config: configRoot=${configRoot}, baseRoot=${baseRoot}, scaffoldDir=${scaffoldDir}`
147
+ );
148
+ return {
149
+ config,
150
+ scaffoldDir,
151
+ projectRoot: baseRoot
152
+ };
153
+ }
154
+ function resolveConfigPath(scaffoldDir) {
155
+ const candidates = [
156
+ "config.ts",
157
+ "config.mts",
158
+ "config.mjs",
159
+ "config.js",
160
+ "config.cjs"
161
+ ];
162
+ for (const file of candidates) {
163
+ const full = path2.join(scaffoldDir, file);
164
+ if (fs7.existsSync(full)) {
165
+ return full;
166
+ }
167
+ }
168
+ throw new Error(
169
+ `Could not find scaffold config in ${scaffoldDir}. Looked for: ${candidates.join(
170
+ ", "
171
+ )}`
172
+ );
173
+ }
174
+ async function importConfig(configPath) {
175
+ const ext = path2.extname(configPath).toLowerCase();
176
+ if (ext === ".ts" || ext === ".tsx") {
177
+ return importTsConfig(configPath);
178
+ }
179
+ const url = pathToFileURL(configPath).href;
180
+ const mod = await import(url);
181
+ return mod.default ?? mod;
182
+ }
183
+ async function importTsConfig(configPath) {
184
+ const source = fs7.readFileSync(configPath, "utf8");
185
+ const stat = fs7.statSync(configPath);
186
+ const hash = crypto.createHash("sha1").update(configPath).update(String(stat.mtimeMs)).digest("hex");
187
+ const tmpDir = path2.join(os.tmpdir(), "timeax-scaffold-config");
188
+ ensureDirSync(tmpDir);
189
+ const tmpFile = path2.join(tmpDir, `${hash}.mjs`);
190
+ if (!fs7.existsSync(tmpFile)) {
191
+ const result = await transform(source, {
192
+ loader: "ts",
193
+ format: "esm",
194
+ sourcemap: "inline",
195
+ target: "ESNext",
196
+ tsconfigRaw: {
197
+ compilerOptions: {}
198
+ }
199
+ });
200
+ fs7.writeFileSync(tmpFile, result.code, "utf8");
201
+ }
202
+ const url = pathToFileURL(tmpFile).href;
203
+ const mod = await import(url);
204
+ return mod.default ?? mod;
205
+ }
206
+
207
+ // src/core/structure-txt.ts
208
+ function parseLine(line, lineNo) {
209
+ const match = line.match(/^(\s*)(.+)$/);
210
+ if (!match) return null;
211
+ const indentSpaces = match[1].length;
212
+ const rest = match[2].trim();
213
+ if (!rest || rest.startsWith("#")) return null;
214
+ const parts = rest.split(/\s+/);
215
+ const pathToken = parts[0];
216
+ let stub;
217
+ const include = [];
218
+ const exclude = [];
219
+ for (const token of parts.slice(1)) {
220
+ if (token.startsWith("@stub:")) {
221
+ stub = token.slice("@stub:".length);
222
+ } else if (token.startsWith("@include:")) {
223
+ const val = token.slice("@include:".length);
224
+ if (val) {
225
+ include.push(
226
+ ...val.split(",").map((s) => s.trim()).filter(Boolean)
227
+ );
228
+ }
229
+ } else if (token.startsWith("@exclude:")) {
230
+ const val = token.slice("@exclude:".length);
231
+ if (val) {
232
+ exclude.push(
233
+ ...val.split(",").map((s) => s.trim()).filter(Boolean)
234
+ );
235
+ }
236
+ }
237
+ }
238
+ return {
239
+ lineNo,
240
+ indentSpaces,
241
+ rawPath: pathToken,
242
+ stub,
243
+ include: include.length ? include : void 0,
244
+ exclude: exclude.length ? exclude : void 0
245
+ };
246
+ }
247
+ function parseStructureText(text) {
248
+ const lines = text.split(/\r?\n/);
249
+ const parsed = [];
250
+ for (let i = 0; i < lines.length; i++) {
251
+ const lineNo = i + 1;
252
+ const p = parseLine(lines[i], lineNo);
253
+ if (p) parsed.push(p);
254
+ }
255
+ const rootEntries = [];
256
+ const stack = [];
257
+ const INDENT_STEP = 2;
258
+ for (const p of parsed) {
259
+ const { indentSpaces, lineNo } = p;
260
+ if (indentSpaces % INDENT_STEP !== 0) {
261
+ throw new Error(
262
+ `structure.txt: Invalid indent on line ${lineNo}. Indent must be multiples of ${INDENT_STEP} spaces.`
263
+ );
264
+ }
265
+ const level = indentSpaces / INDENT_STEP;
266
+ if (level > stack.length) {
267
+ if (level !== stack.length + 1) {
268
+ throw new Error(
269
+ `structure.txt: Invalid indentation on line ${lineNo}. You cannot jump more than one level at a time. Previous depth: ${stack.length}, this line depth: ${level}.`
270
+ );
271
+ }
272
+ }
273
+ if (level > 0) {
274
+ const parent2 = stack[level - 1];
275
+ if (!parent2) {
276
+ throw new Error(
277
+ `structure.txt: Indented entry without a parent on line ${lineNo}.`
278
+ );
279
+ }
280
+ if (!parent2.isDir) {
281
+ throw new Error(
282
+ `structure.txt: Cannot indent under a file on line ${lineNo}. Files cannot have children. Parent: "${parent2.entry.path}".`
283
+ );
284
+ }
285
+ }
286
+ const isDir = p.rawPath.endsWith("/");
287
+ const clean = p.rawPath.replace(/\/$/, "");
288
+ const basePath = toPosixPath(clean);
289
+ while (stack.length > level) {
290
+ stack.pop();
291
+ }
292
+ const parent = stack[stack.length - 1]?.entry;
293
+ const parentPath = parent ? parent.path.replace(/\/$/, "") : "";
294
+ const fullPath = parentPath ? `${parentPath}/${basePath}${isDir ? "/" : ""}` : `${basePath}${isDir ? "/" : ""}`;
295
+ if (isDir) {
296
+ const dirEntry = {
297
+ type: "dir",
298
+ path: fullPath,
299
+ children: [],
300
+ ...p.stub ? { stub: p.stub } : {},
301
+ ...p.include ? { include: p.include } : {},
302
+ ...p.exclude ? { exclude: p.exclude } : {}
303
+ };
304
+ if (parent && parent.type === "dir") {
305
+ parent.children = parent.children ?? [];
306
+ parent.children.push(dirEntry);
307
+ } else if (!parent) {
308
+ rootEntries.push(dirEntry);
309
+ }
310
+ stack.push({ level, entry: dirEntry, isDir: true });
311
+ } else {
312
+ const fileEntry = {
313
+ type: "file",
314
+ path: fullPath,
315
+ ...p.stub ? { stub: p.stub } : {},
316
+ ...p.include ? { include: p.include } : {},
317
+ ...p.exclude ? { exclude: p.exclude } : {}
318
+ };
319
+ if (parent && parent.type === "dir") {
320
+ parent.children = parent.children ?? [];
321
+ parent.children.push(fileEntry);
322
+ } else if (!parent) {
323
+ rootEntries.push(fileEntry);
324
+ }
325
+ stack.push({ level, entry: fileEntry, isDir: false });
326
+ }
327
+ }
328
+ return rootEntries;
329
+ }
330
+
331
+ // src/core/resolve-structure.ts
332
+ var logger2 = defaultLogger.child("[structure]");
333
+ function resolveGroupStructure(scaffoldDir, group) {
334
+ if (group.structure && group.structure.length) {
335
+ logger2.debug(`Using inline structure for group "${group.name}"`);
336
+ return group.structure;
337
+ }
338
+ const fileName = group.structureFile ?? `${group.name}.txt`;
339
+ const filePath = path2.join(scaffoldDir, fileName);
340
+ if (!fs7.existsSync(filePath)) {
341
+ throw new Error(
342
+ `@timeax/scaffold: Group "${group.name}" has no structure. Expected file "${fileName}" in "${scaffoldDir}".`
343
+ );
344
+ }
345
+ logger2.debug(`Reading structure for group "${group.name}" from ${filePath}`);
346
+ const raw = fs7.readFileSync(filePath, "utf8");
347
+ return parseStructureText(raw);
348
+ }
349
+ function resolveSingleStructure(scaffoldDir, config) {
350
+ if (config.structure && config.structure.length) {
351
+ logger2.debug("Using inline single structure (no groups)");
352
+ return config.structure;
353
+ }
354
+ const fileName = config.structureFile ?? "structure.txt";
355
+ const filePath = path2.join(scaffoldDir, fileName);
356
+ if (!fs7.existsSync(filePath)) {
357
+ throw new Error(
358
+ `@timeax/scaffold: No structure defined. Expected "${fileName}" in "${scaffoldDir}".`
359
+ );
360
+ }
361
+ logger2.debug(`Reading single structure from ${filePath}`);
362
+ const raw = fs7.readFileSync(filePath, "utf8");
363
+ return parseStructureText(raw);
364
+ }
365
+ var logger3 = defaultLogger.child("[cache]");
366
+ var DEFAULT_CACHE = {
367
+ version: 1,
368
+ entries: {}
369
+ };
370
+ var CacheManager = class {
371
+ constructor(projectRoot, cacheFileRelPath) {
372
+ this.projectRoot = projectRoot;
373
+ this.cacheFileRelPath = cacheFileRelPath;
374
+ }
375
+ cache = DEFAULT_CACHE;
376
+ get cachePathAbs() {
377
+ return path2.resolve(this.projectRoot, this.cacheFileRelPath);
378
+ }
379
+ load() {
380
+ const cachePath = this.cachePathAbs;
381
+ if (!fs7.existsSync(cachePath)) {
382
+ this.cache = { ...DEFAULT_CACHE, entries: {} };
383
+ return;
384
+ }
385
+ try {
386
+ const raw = fs7.readFileSync(cachePath, "utf8");
387
+ const parsed = JSON.parse(raw);
388
+ if (parsed.version === 1 && parsed.entries) {
389
+ this.cache = parsed;
390
+ } else {
391
+ logger3.warn("Cache file version mismatch or invalid, resetting cache.");
392
+ this.cache = { ...DEFAULT_CACHE, entries: {} };
393
+ }
394
+ } catch (err) {
395
+ logger3.warn("Failed to read cache file, resetting cache.", err);
396
+ this.cache = { ...DEFAULT_CACHE, entries: {} };
397
+ }
398
+ }
399
+ save() {
400
+ const cachePath = this.cachePathAbs;
401
+ const dir = path2.dirname(cachePath);
402
+ ensureDirSync(dir);
403
+ fs7.writeFileSync(cachePath, JSON.stringify(this.cache, null, 2), "utf8");
404
+ }
405
+ get(relPath) {
406
+ const key = toPosixPath(relPath);
407
+ return this.cache.entries[key];
408
+ }
409
+ set(entry) {
410
+ const key = toPosixPath(entry.path);
411
+ this.cache.entries[key] = {
412
+ ...entry,
413
+ path: key
414
+ };
415
+ }
416
+ delete(relPath) {
417
+ const key = toPosixPath(relPath);
418
+ delete this.cache.entries[key];
419
+ }
420
+ allPaths() {
421
+ return Object.keys(this.cache.entries);
422
+ }
423
+ allEntries() {
424
+ return Object.values(this.cache.entries);
425
+ }
426
+ };
427
+ function matchesFilter(pathRel, cfg) {
428
+ const { include, exclude, files } = cfg;
429
+ const patterns = [];
430
+ if (include?.length) patterns.push(...include);
431
+ if (files?.length) patterns.push(...files);
432
+ if (patterns.length) {
433
+ const ok = patterns.some((p) => minimatch(pathRel, p));
434
+ if (!ok) return false;
435
+ }
436
+ if (exclude?.length) {
437
+ const blocked = exclude.some((p) => minimatch(pathRel, p));
438
+ if (blocked) return false;
439
+ }
440
+ return true;
441
+ }
442
+ var HookRunner = class {
443
+ constructor(config) {
444
+ this.config = config;
445
+ }
446
+ async runRegular(kind, ctx) {
447
+ const configs = this.config.hooks?.[kind] ?? [];
448
+ for (const cfg of configs) {
449
+ if (!matchesFilter(ctx.targetPath, cfg)) continue;
450
+ await cfg.fn(ctx);
451
+ }
452
+ }
453
+ getStubConfig(stubName) {
454
+ if (!stubName) return void 0;
455
+ return this.config.stubs?.[stubName];
456
+ }
457
+ async runStub(kind, ctx) {
458
+ const stub = this.getStubConfig(ctx.stubName);
459
+ if (!stub?.hooks) return;
460
+ const configs = kind === "preStub" ? stub.hooks.preStub ?? [] : stub.hooks.postStub ?? [];
461
+ for (const cfg of configs) {
462
+ if (!matchesFilter(ctx.targetPath, cfg)) continue;
463
+ await cfg.fn(ctx);
464
+ }
465
+ }
466
+ async renderStubContent(ctx) {
467
+ const stub = this.getStubConfig(ctx.stubName);
468
+ if (!stub?.getContent) return void 0;
469
+ return stub.getContent(ctx);
470
+ }
471
+ };
472
+ async function applyStructure(opts) {
473
+ const {
474
+ config,
475
+ projectRoot,
476
+ baseDir,
477
+ structure,
478
+ cache,
479
+ hooks,
480
+ groupName,
481
+ groupRoot,
482
+ sizePromptThreshold,
483
+ interactiveDelete
484
+ } = opts;
485
+ const logger6 = opts.logger ?? defaultLogger.child(groupName ? `[apply:${groupName}]` : "[apply]");
486
+ const desiredPaths = /* @__PURE__ */ new Set();
487
+ const threshold = sizePromptThreshold ?? config.sizePromptThreshold ?? 128 * 1024;
488
+ async function walk(entry, inheritedStub) {
489
+ const effectiveStub = entry.stub ?? inheritedStub;
490
+ if (entry.type === "dir") {
491
+ await handleDir(entry, effectiveStub);
492
+ } else {
493
+ await handleFile(entry, effectiveStub);
494
+ }
495
+ }
496
+ async function handleDir(entry, inheritedStub) {
497
+ const relFromBase = entry.path.replace(/^[./]+/, "");
498
+ const absDir = path2.resolve(baseDir, relFromBase);
499
+ const relFromRoot = toPosixPath(
500
+ toProjectRelativePath(projectRoot, absDir)
501
+ );
502
+ desiredPaths.add(relFromRoot);
503
+ ensureDirSync(absDir);
504
+ const nextStub = entry.stub ?? inheritedStub;
505
+ if (entry.children) {
506
+ for (const child of entry.children) {
507
+ await walk(child, nextStub);
508
+ }
509
+ }
510
+ }
511
+ async function handleFile(entry, inheritedStub) {
512
+ const relFromBase = entry.path.replace(/^[./]+/, "");
513
+ const absFile = path2.resolve(baseDir, relFromBase);
514
+ const relFromRoot = toPosixPath(
515
+ toProjectRelativePath(projectRoot, absFile)
516
+ );
517
+ desiredPaths.add(relFromRoot);
518
+ const stubName = entry.stub ?? inheritedStub;
519
+ const ctx = {
520
+ projectRoot,
521
+ targetPath: relFromRoot,
522
+ absolutePath: absFile,
523
+ isDirectory: false,
524
+ stubName
525
+ };
526
+ if (fs7.existsSync(absFile)) {
527
+ return;
528
+ }
529
+ await hooks.runRegular("preCreateFile", ctx);
530
+ const dir = path2.dirname(absFile);
531
+ ensureDirSync(dir);
532
+ if (stubName) {
533
+ await hooks.runStub("preStub", ctx);
534
+ }
535
+ let content = "";
536
+ const stubContent = await hooks.renderStubContent(ctx);
537
+ if (typeof stubContent === "string") {
538
+ content = stubContent;
539
+ }
540
+ fs7.writeFileSync(absFile, content, "utf8");
541
+ const stats = fs7.statSync(absFile);
542
+ cache.set({
543
+ path: relFromRoot,
544
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
545
+ sizeAtCreate: stats.size,
546
+ createdByStub: stubName,
547
+ groupName,
548
+ groupRoot
549
+ });
550
+ logger6.info(`created ${relFromRoot}`);
551
+ if (stubName) {
552
+ await hooks.runStub("postStub", ctx);
553
+ }
554
+ await hooks.runRegular("postCreateFile", ctx);
555
+ }
556
+ for (const entry of structure) {
557
+ await walk(entry);
558
+ }
559
+ for (const cachedPath of cache.allPaths()) {
560
+ if (desiredPaths.has(cachedPath)) continue;
561
+ const abs = path2.resolve(projectRoot, cachedPath);
562
+ const stats = statSafeSync(abs);
563
+ if (!stats) {
564
+ cache.delete(cachedPath);
565
+ continue;
566
+ }
567
+ if (!stats.isFile()) {
568
+ cache.delete(cachedPath);
569
+ continue;
570
+ }
571
+ const entry = cache.get(cachedPath);
572
+ const ctx = {
573
+ projectRoot,
574
+ targetPath: cachedPath,
575
+ absolutePath: abs,
576
+ isDirectory: false,
577
+ stubName: entry?.createdByStub
578
+ };
579
+ await hooks.runRegular("preDeleteFile", ctx);
580
+ let shouldDelete = true;
581
+ if (stats.size > threshold && interactiveDelete) {
582
+ const res = await interactiveDelete({
583
+ absolutePath: abs,
584
+ relativePath: cachedPath,
585
+ size: stats.size,
586
+ createdByStub: entry?.createdByStub,
587
+ groupName: entry?.groupName
588
+ });
589
+ if (res === "keep") {
590
+ shouldDelete = false;
591
+ cache.delete(cachedPath);
592
+ logger6.info(`keeping ${cachedPath} (removed from cache)`);
593
+ }
594
+ }
595
+ if (shouldDelete) {
596
+ try {
597
+ fs7.unlinkSync(abs);
598
+ logger6.info(`deleted ${cachedPath}`);
599
+ } catch (err) {
600
+ logger6.warn(`failed to delete ${cachedPath}`, err);
601
+ }
602
+ cache.delete(cachedPath);
603
+ await hooks.runRegular("postDeleteFile", ctx);
604
+ }
605
+ }
606
+ }
607
+
608
+ // src/core/runner.ts
609
+ async function runOnce(cwd, options = {}) {
610
+ const logger6 = options.logger ?? defaultLogger.child("[runner]");
611
+ const { config, scaffoldDir, projectRoot } = await loadScaffoldConfig(cwd, {
612
+ scaffoldDir: options.scaffoldDir,
613
+ configPath: options.configPath
614
+ });
615
+ const cachePath = config.cacheFile ?? ".scaffold-cache.json";
616
+ const cache = new CacheManager(projectRoot, cachePath);
617
+ cache.load();
618
+ const hooks = new HookRunner(config);
619
+ if (config.groups && config.groups.length > 0) {
620
+ for (const group of config.groups) {
621
+ const groupRootAbs = path2.resolve(projectRoot, group.root);
622
+ const structure = resolveGroupStructure(scaffoldDir, group);
623
+ const groupLogger = logger6.child(`[group:${group.name}]`);
624
+ await applyStructure({
625
+ config,
626
+ projectRoot,
627
+ baseDir: groupRootAbs,
628
+ structure,
629
+ cache,
630
+ hooks,
631
+ groupName: group.name,
632
+ groupRoot: group.root,
633
+ interactiveDelete: options.interactiveDelete,
634
+ logger: groupLogger
635
+ });
636
+ }
637
+ } else {
638
+ const structure = resolveSingleStructure(scaffoldDir, config);
639
+ const baseLogger = logger6.child("[group:default]");
640
+ await applyStructure({
641
+ config,
642
+ projectRoot,
643
+ baseDir: projectRoot,
644
+ structure,
645
+ cache,
646
+ hooks,
647
+ groupName: "default",
648
+ groupRoot: ".",
649
+ interactiveDelete: options.interactiveDelete,
650
+ logger: baseLogger
651
+ });
652
+ }
653
+ cache.save();
654
+ }
655
+ function watchScaffold(cwd, options = {}) {
656
+ const logger6 = options.logger ?? defaultLogger.child("[watch]");
657
+ const scaffoldDir = options.scaffoldDir ? path2.resolve(cwd, options.scaffoldDir) : path2.resolve(cwd, "scaffold");
658
+ const debounceMs = options.debounceMs ?? 150;
659
+ logger6.info(`Watching scaffold directory: ${scaffoldDir}`);
660
+ let timer;
661
+ let running = false;
662
+ let pending = false;
663
+ async function run() {
664
+ if (running) {
665
+ pending = true;
666
+ return;
667
+ }
668
+ running = true;
669
+ try {
670
+ logger6.info("Change detected \u2192 running scaffold...");
671
+ await runOnce(cwd, {
672
+ ...options,
673
+ // we already resolved scaffoldDir for watcher; pass it down
674
+ scaffoldDir
675
+ });
676
+ logger6.info("Scaffold run completed.");
677
+ } catch (err) {
678
+ logger6.error("Scaffold run failed:", err);
679
+ } finally {
680
+ running = false;
681
+ if (pending) {
682
+ pending = false;
683
+ timer = setTimeout(run, debounceMs);
684
+ }
685
+ }
686
+ }
687
+ function scheduleRun() {
688
+ if (timer) clearTimeout(timer);
689
+ timer = setTimeout(run, debounceMs);
690
+ }
691
+ const watcher = chokidar.watch(
692
+ [
693
+ path2.join(scaffoldDir, "config.*"),
694
+ path2.join(scaffoldDir, "*.txt")
695
+ ],
696
+ {
697
+ ignoreInitial: false
698
+ }
699
+ );
700
+ watcher.on("add", (filePath) => {
701
+ logger6.debug(`File added: ${filePath}`);
702
+ scheduleRun();
703
+ }).on("change", (filePath) => {
704
+ logger6.debug(`File changed: ${filePath}`);
705
+ scheduleRun();
706
+ }).on("unlink", (filePath) => {
707
+ logger6.debug(`File removed: ${filePath}`);
708
+ scheduleRun();
709
+ }).on("error", (error) => {
710
+ logger6.error("Watcher error:", error);
711
+ });
712
+ scheduleRun();
713
+ }
714
+ var logger4 = defaultLogger.child("[scan]");
715
+ var DEFAULT_IGNORE = [
716
+ "node_modules/**",
717
+ ".git/**",
718
+ "dist/**",
719
+ "build/**",
720
+ ".turbo/**",
721
+ ".next/**",
722
+ "coverage/**"
723
+ ];
724
+ function scanDirectoryToStructureText(rootDir, options = {}) {
725
+ const absRoot = path2.resolve(rootDir);
726
+ const lines = [];
727
+ const ignorePatterns = options.ignore ?? DEFAULT_IGNORE;
728
+ const maxDepth = options.maxDepth ?? Infinity;
729
+ function isIgnored(absPath) {
730
+ const rel = toPosixPath(path2.relative(absRoot, absPath));
731
+ if (!rel || rel === ".") return false;
732
+ return ignorePatterns.some(
733
+ (pattern) => minimatch(rel, pattern, { dot: true })
734
+ );
735
+ }
736
+ function walk(currentAbs, depth) {
737
+ if (depth > maxDepth) return;
738
+ let dirents;
739
+ try {
740
+ dirents = fs7.readdirSync(currentAbs, { withFileTypes: true });
741
+ } catch {
742
+ return;
743
+ }
744
+ dirents.sort((a, b) => {
745
+ if (a.isDirectory() && !b.isDirectory()) return -1;
746
+ if (!a.isDirectory() && b.isDirectory()) return 1;
747
+ return a.name.localeCompare(b.name);
748
+ });
749
+ for (const dirent of dirents) {
750
+ const name = dirent.name;
751
+ const absPath = path2.join(currentAbs, name);
752
+ if (isIgnored(absPath)) continue;
753
+ const indent = " ".repeat(depth);
754
+ if (dirent.isDirectory()) {
755
+ lines.push(`${indent}${name}/`);
756
+ walk(absPath, depth + 1);
757
+ } else if (dirent.isFile()) {
758
+ lines.push(`${indent}${name}`);
759
+ }
760
+ }
761
+ }
762
+ walk(absRoot, 0);
763
+ return lines.join("\n");
764
+ }
765
+ async function scanProjectFromConfig(cwd, options = {}) {
766
+ const { config, scaffoldDir, projectRoot } = await loadScaffoldConfig(cwd, {
767
+ scaffoldDir: options.scaffoldDir
768
+ });
769
+ const ignorePatterns = options.ignore ?? DEFAULT_IGNORE;
770
+ const maxDepth = options.maxDepth ?? Infinity;
771
+ const onlyGroups = options.groups;
772
+ const results = [];
773
+ function scanGroup(cfg, group) {
774
+ const rootAbs = path2.resolve(projectRoot, group.root);
775
+ const text = scanDirectoryToStructureText(rootAbs, {
776
+ ignore: ignorePatterns,
777
+ maxDepth
778
+ });
779
+ const structureFileName = group.structureFile ?? `${group.name}.txt`;
780
+ const structureFilePath = path2.join(scaffoldDir, structureFileName);
781
+ return {
782
+ groupName: group.name,
783
+ groupRoot: group.root,
784
+ structureFileName,
785
+ structureFilePath,
786
+ text
787
+ };
788
+ }
789
+ if (config.groups && config.groups.length > 0) {
790
+ logger4.debug(
791
+ `Scanning project from config with ${config.groups.length} group(s).`
792
+ );
793
+ for (const group of config.groups) {
794
+ if (onlyGroups && !onlyGroups.includes(group.name)) {
795
+ continue;
796
+ }
797
+ const result = scanGroup(config, group);
798
+ results.push(result);
799
+ }
800
+ } else {
801
+ logger4.debug("Scanning project in single-root mode (no groups).");
802
+ const text = scanDirectoryToStructureText(projectRoot, {
803
+ ignore: ignorePatterns,
804
+ maxDepth
805
+ });
806
+ const structureFileName = config.structureFile ?? "structure.txt";
807
+ const structureFilePath = path2.join(scaffoldDir, structureFileName);
808
+ results.push({
809
+ groupName: "default",
810
+ groupRoot: ".",
811
+ structureFileName,
812
+ structureFilePath,
813
+ text
814
+ });
815
+ }
816
+ return results;
817
+ }
818
+ async function writeScannedStructuresFromConfig(cwd, options = {}) {
819
+ const { scaffoldDir } = await loadScaffoldConfig(cwd, {
820
+ scaffoldDir: options.scaffoldDir
821
+ });
822
+ ensureDirSync(scaffoldDir);
823
+ const results = await scanProjectFromConfig(cwd, options);
824
+ for (const result of results) {
825
+ fs7.writeFileSync(result.structureFilePath, result.text, "utf8");
826
+ logger4.info(
827
+ `Wrote structure for group "${result.groupName}" to ${result.structureFilePath}`
828
+ );
829
+ }
830
+ }
831
+ var logger5 = defaultLogger.child("[init]");
832
+ var DEFAULT_CONFIG_TS = `import type { ScaffoldConfig } from '@timeax/scaffold';
833
+
834
+ const config: ScaffoldConfig = {
835
+ // Root for resolving the scaffold/ folder & this config file.
836
+ // By default, this is the directory where you run \`scaffold\`.
837
+ // Example:
838
+ // root: '.', // scaffold/ at <cwd>/scaffold
839
+ // root: 'tools', // scaffold/ at <cwd>/tools/scaffold
840
+ // root: '.',
841
+
842
+ // Base directory where structures are applied and files/folders are created.
843
+ // This is resolved relative to \`root\` above. Defaults to the same as root.
844
+ // Example:
845
+ // base: '.', // apply to <root>
846
+ // base: 'src', // apply to <root>/src
847
+ // base: '..', // apply to parent of <root>
848
+ // base: '.',
849
+
850
+ // Cache file path, relative to base.
851
+ // cacheFile: '.scaffold-cache.json',
852
+
853
+ // --- Single-structure mode (simple) ---
854
+ // structureFile: 'structure.txt',
855
+
856
+ // --- Grouped mode (uncomment and adjust) ---
857
+ // groups: [
858
+ // { name: 'app', root: 'app', structureFile: 'app.txt' },
859
+ // { name: 'frontend', root: 'resources/js', structureFile: 'frontend.txt' },
860
+ // ],
861
+
862
+ hooks: {
863
+ // preCreateFile: [],
864
+ // postCreateFile: [],
865
+ // preDeleteFile: [],
866
+ // postDeleteFile: [],
867
+ },
868
+
869
+ stubs: {
870
+ // Example:
871
+ // page: {
872
+ // name: 'page',
873
+ // getContent: (ctx) =>
874
+ // \`export default function Page() { return <div>\${ctx.targetPath}</div>; }\`,
875
+ // },
876
+ },
877
+ };
878
+
879
+ export default config;
880
+ `;
881
+ var DEFAULT_STRUCTURE_TXT = `# scaffold/structure.txt
882
+ # Example structure definition.
883
+ # - Indent with 2 spaces per level
884
+ # - Directories must end with "/"
885
+ # - Files do not
886
+ # - Lines starting with "#" are comments and ignored by parser
887
+
888
+ # Example:
889
+ # src/
890
+ # index.ts
891
+ `;
892
+ async function initScaffold(cwd, options = {}) {
893
+ const scaffoldDirRel = options.scaffoldDir ?? "scaffold";
894
+ const scaffoldDirAbs = path2.resolve(cwd, scaffoldDirRel);
895
+ const configFileName = options.configFileName ?? "config.ts";
896
+ const structureFileName = options.structureFileName ?? "structure.txt";
897
+ ensureDirSync(scaffoldDirAbs);
898
+ const configPath = path2.join(scaffoldDirAbs, configFileName);
899
+ const structurePath = path2.join(scaffoldDirAbs, structureFileName);
900
+ let createdConfig = false;
901
+ let createdStructure = false;
902
+ if (fs7.existsSync(configPath) && !options.force) {
903
+ logger5.info(`Config already exists at ${configPath} (use --force to overwrite).`);
904
+ } else {
905
+ fs7.writeFileSync(configPath, DEFAULT_CONFIG_TS, "utf8");
906
+ createdConfig = true;
907
+ logger5.info(
908
+ `${fs7.existsSync(configPath) ? "Overwrote" : "Created"} config at ${configPath}`
909
+ );
910
+ }
911
+ if (fs7.existsSync(structurePath) && !options.force) {
912
+ logger5.info(
913
+ `Structure file already exists at ${structurePath} (use --force to overwrite).`
914
+ );
915
+ } else {
916
+ fs7.writeFileSync(structurePath, DEFAULT_STRUCTURE_TXT, "utf8");
917
+ createdStructure = true;
918
+ logger5.info(
919
+ `${fs7.existsSync(structurePath) ? "Overwrote" : "Created"} structure file at ${structurePath}`
920
+ );
921
+ }
922
+ return {
923
+ scaffoldDir: scaffoldDirAbs,
924
+ configPath,
925
+ structurePath,
926
+ created: {
927
+ config: createdConfig,
928
+ structure: createdStructure
929
+ }
930
+ };
931
+ }
932
+
933
+ // src/cli/main.ts
934
+ function createCliLogger(opts) {
935
+ if (opts.quiet) {
936
+ defaultLogger.setLevel("silent");
937
+ } else if (opts.debug) {
938
+ defaultLogger.setLevel("debug");
939
+ }
940
+ return defaultLogger.child("[cli]");
941
+ }
942
+ function askYesNo(question) {
943
+ const rl = readline.createInterface({
944
+ input: process.stdin,
945
+ output: process.stdout
946
+ });
947
+ return new Promise((resolve) => {
948
+ rl.question(`${question} [y/N] `, (answer) => {
949
+ rl.close();
950
+ const val = answer.trim().toLowerCase();
951
+ if (val === "y" || val === "yes") {
952
+ resolve("delete");
953
+ } else {
954
+ resolve("keep");
955
+ }
956
+ });
957
+ });
958
+ }
959
+ async function handleRunCommand(cwd, baseOpts) {
960
+ const logger6 = createCliLogger(baseOpts);
961
+ const configPath = baseOpts.config ? path2.resolve(cwd, baseOpts.config) : void 0;
962
+ const scaffoldDir = baseOpts.dir ? path2.resolve(cwd, baseOpts.dir) : void 0;
963
+ logger6.debug(
964
+ `Starting scaffold (cwd=${cwd}, config=${configPath ?? "auto"}, dir=${scaffoldDir ?? "scaffold/"}, watch=${baseOpts.watch ? "yes" : "no"})`
965
+ );
966
+ const runnerOptions = {
967
+ configPath,
968
+ scaffoldDir,
969
+ logger: logger6,
970
+ interactiveDelete: async ({
971
+ relativePath,
972
+ size,
973
+ createdByStub,
974
+ groupName
975
+ }) => {
976
+ const sizeKb = (size / 1024).toFixed(1);
977
+ const stubInfo = createdByStub ? ` (stub: ${createdByStub})` : "";
978
+ const groupInfo = groupName ? ` [group: ${groupName}]` : "";
979
+ const question = `File "${relativePath}"${groupInfo} is ~${sizeKb}KB and no longer in structure${stubInfo}. Delete it?`;
980
+ return askYesNo(question);
981
+ }
982
+ };
983
+ if (baseOpts.watch) {
984
+ watchScaffold(cwd, runnerOptions);
985
+ } else {
986
+ await runOnce(cwd, runnerOptions);
987
+ }
988
+ }
989
+ async function handleScanCommand(cwd, scanOpts, baseOpts) {
990
+ const logger6 = createCliLogger(baseOpts);
991
+ const useConfigMode = scanOpts.fromConfig || !scanOpts.root && !scanOpts.out;
992
+ if (useConfigMode) {
993
+ logger6.info("Scanning project using scaffold config/groups...");
994
+ await writeScannedStructuresFromConfig(cwd, {
995
+ ignore: scanOpts.ignore,
996
+ groups: scanOpts.groups
997
+ });
998
+ return;
999
+ }
1000
+ const rootDir = path2.resolve(cwd, scanOpts.root ?? ".");
1001
+ const ignore = scanOpts.ignore ?? [];
1002
+ logger6.info(`Scanning directory for structure: ${rootDir}`);
1003
+ const text = scanDirectoryToStructureText(rootDir, {
1004
+ ignore
1005
+ });
1006
+ if (scanOpts.out) {
1007
+ const outPath = path2.resolve(cwd, scanOpts.out);
1008
+ const dir = path2.dirname(outPath);
1009
+ ensureDirSync(dir);
1010
+ fs7.writeFileSync(outPath, text, "utf8");
1011
+ logger6.info(`Wrote structure to ${outPath}`);
1012
+ } else {
1013
+ process.stdout.write(text + "\n");
1014
+ }
1015
+ }
1016
+ async function handleInitCommand(cwd, initOpts, baseOpts) {
1017
+ const logger6 = createCliLogger(baseOpts);
1018
+ const scaffoldDirRel = baseOpts.dir ?? "scaffold";
1019
+ logger6.info(`Initializing scaffold directory at "${scaffoldDirRel}"...`);
1020
+ const result = await initScaffold(cwd, {
1021
+ scaffoldDir: scaffoldDirRel,
1022
+ force: initOpts.force
1023
+ });
1024
+ logger6.info(
1025
+ `Done. Config: ${result.configPath}, Structure: ${result.structurePath}`
1026
+ );
1027
+ }
1028
+ async function main() {
1029
+ const cwd = process.cwd();
1030
+ const program = new Command();
1031
+ program.name("scaffold").description("@timeax/scaffold \u2013 structure-based project scaffolding").option("-c, --config <path>", "Path to scaffold config file").option("-d, --dir <path>", "Path to scaffold directory (default: ./scaffold)").option("-w, --watch", "Watch scaffold directory for changes").option("--quiet", "Silence logs").option("--debug", "Enable debug logging");
1032
+ program.command("scan").description(
1033
+ "Generate structure.txt-style output (config-aware by default, or manual root/out)"
1034
+ ).option(
1035
+ "--from-config",
1036
+ "Scan based on scaffold config/groups and write structure files into scaffold/ (default if no root/out specified)"
1037
+ ).option(
1038
+ "-r, --root <path>",
1039
+ "Root directory to scan (manual mode)"
1040
+ ).option(
1041
+ "-o, --out <path>",
1042
+ "Output file path (manual mode)"
1043
+ ).option(
1044
+ "--ignore <patterns...>",
1045
+ "Additional glob patterns to ignore (relative to root)"
1046
+ ).option(
1047
+ "--groups <names...>",
1048
+ "Limit config-based scanning to specific groups (by name)"
1049
+ ).action(async (scanOpts, cmd) => {
1050
+ const baseOpts = cmd.parent?.opts() ?? {};
1051
+ await handleScanCommand(cwd, scanOpts, baseOpts);
1052
+ });
1053
+ program.command("init").description("Initialize scaffold folder and config/structure files").option(
1054
+ "--force",
1055
+ "Overwrite existing config/structure files if they already exist"
1056
+ ).action(async (initOpts, cmd) => {
1057
+ const baseOpts = cmd.parent?.opts() ?? {};
1058
+ await handleInitCommand(cwd, initOpts, baseOpts);
1059
+ });
1060
+ program.action(async (opts) => {
1061
+ await handleRunCommand(cwd, opts);
1062
+ });
1063
+ await program.parseAsync(process.argv);
1064
+ }
1065
+ main().catch((err) => {
1066
+ defaultLogger.error(err);
1067
+ process.exit(1);
1068
+ });
1069
+ //# sourceMappingURL=cli.mjs.map
1070
+ //# sourceMappingURL=cli.mjs.map