@timeax/scaffold 0.0.2 → 0.0.4

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