@timeax/scaffold 0.0.5 → 0.0.6

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 ADDED
@@ -0,0 +1,1673 @@
1
+ 'use strict';
2
+
3
+ var readline = require('readline');
4
+ var path2 = require('path');
5
+ var fs8 = require('fs');
6
+ var commander = require('commander');
7
+ var os = require('os');
8
+ var crypto = require('crypto');
9
+ var url = require('url');
10
+ var esbuild = require('esbuild');
11
+ var minimatch = require('minimatch');
12
+ var chokidar = require('chokidar');
13
+
14
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
15
+
16
+ var readline__default = /*#__PURE__*/_interopDefault(readline);
17
+ var path2__default = /*#__PURE__*/_interopDefault(path2);
18
+ var fs8__default = /*#__PURE__*/_interopDefault(fs8);
19
+ var os__default = /*#__PURE__*/_interopDefault(os);
20
+ var crypto__default = /*#__PURE__*/_interopDefault(crypto);
21
+ var chokidar__default = /*#__PURE__*/_interopDefault(chokidar);
22
+
23
+ // src/cli/main.ts
24
+
25
+ // src/schema/index.ts
26
+ var SCAFFOLD_ROOT_DIR = ".scaffold";
27
+
28
+ // src/util/logger.ts
29
+ var supportsColor = typeof process !== "undefined" && process.stdout && process.stdout.isTTY && process.env.NO_COLOR !== "1";
30
+ function wrap(code) {
31
+ const open = `\x1B[${code}m`;
32
+ const close = `\x1B[0m`;
33
+ return (text) => supportsColor ? `${open}${text}${close}` : text;
34
+ }
35
+ var color = {
36
+ red: wrap(31),
37
+ yellow: wrap(33),
38
+ green: wrap(32),
39
+ cyan: wrap(36),
40
+ magenta: wrap(35),
41
+ dim: wrap(2),
42
+ bold: wrap(1),
43
+ gray: wrap(90)
44
+ };
45
+ function colorForLevel(level) {
46
+ switch (level) {
47
+ case "error":
48
+ return color.red;
49
+ case "warn":
50
+ return color.yellow;
51
+ case "info":
52
+ return color.cyan;
53
+ case "debug":
54
+ return color.gray;
55
+ default:
56
+ return (s) => s;
57
+ }
58
+ }
59
+ var Logger = class _Logger {
60
+ level;
61
+ prefix;
62
+ constructor(options = {}) {
63
+ this.level = options.level ?? "info";
64
+ this.prefix = options.prefix;
65
+ }
66
+ setLevel(level) {
67
+ this.level = level;
68
+ }
69
+ getLevel() {
70
+ return this.level;
71
+ }
72
+ /**
73
+ * Create a child logger with an additional prefix.
74
+ */
75
+ child(prefix) {
76
+ const combined = this.prefix ? `${this.prefix}${prefix}` : prefix;
77
+ return new _Logger({ level: this.level, prefix: combined });
78
+ }
79
+ formatMessage(msg, lvl) {
80
+ const text = typeof msg === "string" ? msg : msg instanceof Error ? msg.message : String(msg);
81
+ const levelColor = colorForLevel(lvl);
82
+ const prefixColored = this.prefix ? color.magenta(this.prefix) : void 0;
83
+ const textColored = lvl === "debug" ? color.dim(text) : levelColor(text);
84
+ if (prefixColored) {
85
+ return `${prefixColored} ${textColored}`;
86
+ }
87
+ return textColored;
88
+ }
89
+ shouldLog(targetLevel) {
90
+ const order = ["silent", "error", "warn", "info", "debug"];
91
+ const currentIdx = order.indexOf(this.level);
92
+ const targetIdx = order.indexOf(targetLevel);
93
+ if (currentIdx === -1 || targetIdx === -1) return true;
94
+ if (this.level === "silent") return false;
95
+ return targetIdx <= currentIdx || targetLevel === "error";
96
+ }
97
+ error(msg, ...rest) {
98
+ if (!this.shouldLog("error")) return;
99
+ console.error(this.formatMessage(msg, "error"), ...rest);
100
+ }
101
+ warn(msg, ...rest) {
102
+ if (!this.shouldLog("warn")) return;
103
+ console.warn(this.formatMessage(msg, "warn"), ...rest);
104
+ }
105
+ info(msg, ...rest) {
106
+ if (!this.shouldLog("info")) return;
107
+ console.log(this.formatMessage(msg, "info"), ...rest);
108
+ }
109
+ debug(msg, ...rest) {
110
+ if (!this.shouldLog("debug")) return;
111
+ console.debug(this.formatMessage(msg, "debug"), ...rest);
112
+ }
113
+ };
114
+ var defaultLogger = new Logger({
115
+ level: process.env.SCAFFOLD_LOG_LEVEL ?? "info",
116
+ prefix: "[scaffold]"
117
+ });
118
+ function toPosixPath(p) {
119
+ return p.replace(/\\/g, "/");
120
+ }
121
+ function ensureDirSync(dirPath) {
122
+ if (!fs8__default.default.existsSync(dirPath)) {
123
+ fs8__default.default.mkdirSync(dirPath, { recursive: true });
124
+ }
125
+ return dirPath;
126
+ }
127
+ function statSafeSync(targetPath) {
128
+ try {
129
+ return fs8__default.default.statSync(targetPath);
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+ function toProjectRelativePath(projectRoot, absolutePath) {
135
+ const absRoot = path2__default.default.resolve(projectRoot);
136
+ const absTarget = path2__default.default.resolve(absolutePath);
137
+ const rootWithSep = absRoot.endsWith(path2__default.default.sep) ? absRoot : absRoot + path2__default.default.sep;
138
+ if (!absTarget.startsWith(rootWithSep) && absTarget !== absRoot) {
139
+ throw new Error(
140
+ `Path "${absTarget}" is not inside project root "${absRoot}".`
141
+ );
142
+ }
143
+ const rel = path2__default.default.relative(absRoot, absTarget);
144
+ return toPosixPath(rel);
145
+ }
146
+
147
+ // src/core/config-loader.ts
148
+ var logger = defaultLogger.child("[config]");
149
+ async function loadScaffoldConfig(cwd, options = {}) {
150
+ const absCwd = path2__default.default.resolve(cwd);
151
+ const initialScaffoldDir = options.scaffoldDir ? path2__default.default.resolve(absCwd, options.scaffoldDir) : path2__default.default.join(absCwd, SCAFFOLD_ROOT_DIR);
152
+ const configPath = options.configPath ?? resolveConfigPath(initialScaffoldDir);
153
+ const config = await importConfig(configPath);
154
+ let configRoot = absCwd;
155
+ if (config.root) {
156
+ configRoot = path2__default.default.resolve(absCwd, config.root);
157
+ }
158
+ const scaffoldDir = options.scaffoldDir ? path2__default.default.resolve(absCwd, options.scaffoldDir) : path2__default.default.join(configRoot, SCAFFOLD_ROOT_DIR);
159
+ const baseRoot = config.base ? path2__default.default.resolve(configRoot, config.base) : configRoot;
160
+ logger.debug(
161
+ `Loaded config: configRoot=${configRoot}, baseRoot=${baseRoot}, scaffoldDir=${scaffoldDir}`
162
+ );
163
+ return {
164
+ config,
165
+ scaffoldDir,
166
+ projectRoot: baseRoot
167
+ };
168
+ }
169
+ function resolveConfigPath(scaffoldDir) {
170
+ const candidates = [
171
+ "config.ts",
172
+ "config.mts",
173
+ "config.mjs",
174
+ "config.js",
175
+ "config.cjs"
176
+ ];
177
+ for (const file of candidates) {
178
+ const full = path2__default.default.join(scaffoldDir, file);
179
+ if (fs8__default.default.existsSync(full)) {
180
+ return full;
181
+ }
182
+ }
183
+ throw new Error(
184
+ `Could not find scaffold config in ${scaffoldDir}. Looked for: ${candidates.join(
185
+ ", "
186
+ )}`
187
+ );
188
+ }
189
+ async function importConfig(configPath) {
190
+ const ext = path2__default.default.extname(configPath).toLowerCase();
191
+ if (ext === ".ts" || ext === ".tsx") {
192
+ return importTsConfig(configPath);
193
+ }
194
+ const url$1 = url.pathToFileURL(configPath).href;
195
+ const mod = await import(url$1);
196
+ return mod.default ?? mod;
197
+ }
198
+ async function importTsConfig(configPath) {
199
+ const source = fs8__default.default.readFileSync(configPath, "utf8");
200
+ const stat = fs8__default.default.statSync(configPath);
201
+ const hash = crypto__default.default.createHash("sha1").update(configPath).update(String(stat.mtimeMs)).digest("hex");
202
+ const tmpDir = path2__default.default.join(os__default.default.tmpdir(), "timeax-scaffold-config");
203
+ ensureDirSync(tmpDir);
204
+ const tmpFile = path2__default.default.join(tmpDir, `${hash}.mjs`);
205
+ if (!fs8__default.default.existsSync(tmpFile)) {
206
+ const result = await esbuild.transform(source, {
207
+ loader: "ts",
208
+ format: "esm",
209
+ sourcemap: "inline",
210
+ target: "ESNext",
211
+ tsconfigRaw: {
212
+ compilerOptions: {}
213
+ }
214
+ });
215
+ fs8__default.default.writeFileSync(tmpFile, result.code, "utf8");
216
+ }
217
+ const url$1 = url.pathToFileURL(tmpFile).href;
218
+ const mod = await import(url$1);
219
+ return mod.default ?? mod;
220
+ }
221
+
222
+ // src/ast/parser.ts
223
+ function parseStructureAst(text, opts = {}) {
224
+ const indentStep = opts.indentStep ?? 2;
225
+ const mode = opts.mode ?? "loose";
226
+ const diagnostics = [];
227
+ const lines = [];
228
+ const rawLines = text.split(/\r?\n/);
229
+ for (let i = 0; i < rawLines.length; i++) {
230
+ const raw = rawLines[i];
231
+ const lineNo = i + 1;
232
+ const m = raw.match(/^(\s*)(.*)$/);
233
+ const indentRaw = m ? m[1] : "";
234
+ const content = m ? m[2] : "";
235
+ const { indentSpaces, hasTabs } = measureIndent(indentRaw, indentStep);
236
+ if (hasTabs) {
237
+ diagnostics.push({
238
+ line: lineNo,
239
+ message: "Tabs detected in indentation. Consider using spaces only for consistent levels.",
240
+ severity: mode === "strict" ? "warning" : "info",
241
+ code: "indent-tabs"
242
+ });
243
+ }
244
+ const trimmed = content.trim();
245
+ let kind;
246
+ if (!trimmed) {
247
+ kind = "blank";
248
+ } else if (trimmed.startsWith("#") || trimmed.startsWith("//")) {
249
+ kind = "comment";
250
+ } else {
251
+ kind = "entry";
252
+ }
253
+ lines.push({
254
+ index: i,
255
+ lineNo,
256
+ raw,
257
+ kind,
258
+ indentSpaces,
259
+ content
260
+ });
261
+ }
262
+ const rootNodes = [];
263
+ const stack = [];
264
+ const depthCtx = {
265
+ lastIndentSpaces: null,
266
+ lastDepth: null,
267
+ lastWasFile: false
268
+ };
269
+ for (const line of lines) {
270
+ if (line.kind !== "entry") continue;
271
+ const { entry, depth, diags } = parseEntryLine(
272
+ line,
273
+ indentStep,
274
+ mode,
275
+ depthCtx
276
+ );
277
+ diagnostics.push(...diags);
278
+ if (!entry) {
279
+ continue;
280
+ }
281
+ attachNode(entry, depth, line, rootNodes, stack, diagnostics, mode);
282
+ depthCtx.lastWasFile = !entry.isDir;
283
+ }
284
+ return {
285
+ rootNodes,
286
+ lines,
287
+ diagnostics,
288
+ options: {
289
+ indentStep,
290
+ mode
291
+ }
292
+ };
293
+ }
294
+ function measureIndent(rawIndent, indentStep) {
295
+ let spaces = 0;
296
+ let hasTabs = false;
297
+ for (const ch of rawIndent) {
298
+ if (ch === " ") {
299
+ spaces += 1;
300
+ } else if (ch === " ") {
301
+ hasTabs = true;
302
+ spaces += indentStep;
303
+ }
304
+ }
305
+ return { indentSpaces: spaces, hasTabs };
306
+ }
307
+ function computeDepth(line, indentStep, mode, ctx, diagnostics) {
308
+ let spaces = line.indentSpaces;
309
+ if (spaces < 0) spaces = 0;
310
+ let depth;
311
+ if (ctx.lastIndentSpaces == null || ctx.lastDepth == null) {
312
+ depth = 0;
313
+ } else {
314
+ const prevSpaces = ctx.lastIndentSpaces;
315
+ const prevDepth = ctx.lastDepth;
316
+ if (spaces > prevSpaces) {
317
+ const diff = spaces - prevSpaces;
318
+ if (ctx.lastWasFile) {
319
+ diagnostics.push({
320
+ line: line.lineNo,
321
+ message: "Entry appears indented under a file; treating it as a sibling of the file instead of a child.",
322
+ severity: mode === "strict" ? "error" : "warning",
323
+ code: "child-of-file-loose"
324
+ });
325
+ depth = prevDepth;
326
+ } else {
327
+ if (diff > indentStep) {
328
+ diagnostics.push({
329
+ line: line.lineNo,
330
+ message: `Indentation jumps from ${prevSpaces} to ${spaces} spaces; treating as one level deeper.`,
331
+ severity: mode === "strict" ? "error" : "warning",
332
+ code: "indent-skip-level"
333
+ });
334
+ }
335
+ depth = prevDepth + 1;
336
+ }
337
+ } else if (spaces === prevSpaces) {
338
+ depth = prevDepth;
339
+ } else {
340
+ const diff = prevSpaces - spaces;
341
+ const steps = Math.round(diff / indentStep);
342
+ if (diff % indentStep !== 0) {
343
+ diagnostics.push({
344
+ line: line.lineNo,
345
+ message: `Indentation decreases from ${prevSpaces} to ${spaces} spaces, which is not a multiple of indent step (${indentStep}).`,
346
+ severity: mode === "strict" ? "error" : "warning",
347
+ code: "indent-misaligned"
348
+ });
349
+ }
350
+ depth = Math.max(prevDepth - steps, 0);
351
+ }
352
+ }
353
+ ctx.lastIndentSpaces = spaces;
354
+ ctx.lastDepth = depth;
355
+ return depth;
356
+ }
357
+ function parseEntryLine(line, indentStep, mode, ctx) {
358
+ const diags = [];
359
+ const depth = computeDepth(line, indentStep, mode, ctx, diags);
360
+ const { contentWithoutComment } = extractInlineCommentParts(line.content);
361
+ const trimmed = contentWithoutComment.trim();
362
+ if (!trimmed) {
363
+ return { entry: null, depth, diags };
364
+ }
365
+ const parts = trimmed.split(/\s+/);
366
+ const pathToken = parts[0];
367
+ const annotationTokens = parts.slice(1);
368
+ if (pathToken.includes(":")) {
369
+ diags.push({
370
+ line: line.lineNo,
371
+ message: 'Path token contains ":" which is reserved for annotations. This is likely a mistake.',
372
+ severity: mode === "strict" ? "error" : "warning",
373
+ code: "path-colon"
374
+ });
375
+ }
376
+ const isDir = pathToken.endsWith("/");
377
+ const segmentName = pathToken;
378
+ let stub;
379
+ const include = [];
380
+ const exclude = [];
381
+ for (const token of annotationTokens) {
382
+ if (token.startsWith("@stub:")) {
383
+ stub = token.slice("@stub:".length);
384
+ } else if (token.startsWith("@include:")) {
385
+ const val = token.slice("@include:".length);
386
+ if (val) {
387
+ include.push(
388
+ ...val.split(",").map((s) => s.trim()).filter(Boolean)
389
+ );
390
+ }
391
+ } else if (token.startsWith("@exclude:")) {
392
+ const val = token.slice("@exclude:".length);
393
+ if (val) {
394
+ exclude.push(
395
+ ...val.split(",").map((s) => s.trim()).filter(Boolean)
396
+ );
397
+ }
398
+ } else if (token.startsWith("@")) {
399
+ diags.push({
400
+ line: line.lineNo,
401
+ message: `Unknown annotation token "${token}".`,
402
+ severity: "info",
403
+ code: "unknown-annotation"
404
+ });
405
+ }
406
+ }
407
+ const entry = {
408
+ segmentName,
409
+ isDir,
410
+ stub,
411
+ include: include.length ? include : void 0,
412
+ exclude: exclude.length ? exclude : void 0
413
+ };
414
+ return { entry, depth, diags };
415
+ }
416
+ function mapThrough(content) {
417
+ let cutIndex = -1;
418
+ const len = content.length;
419
+ for (let i = 0; i < len; i++) {
420
+ const ch = content[i];
421
+ const prev = i > 0 ? content[i - 1] : "";
422
+ if (ch === "#") {
423
+ if (i === 0) {
424
+ continue;
425
+ }
426
+ if (prev === " " || prev === " ") {
427
+ cutIndex = i;
428
+ break;
429
+ }
430
+ }
431
+ if (ch === "/" && i + 1 < len && content[i + 1] === "/" && (prev === " " || prev === " ")) {
432
+ cutIndex = i;
433
+ break;
434
+ }
435
+ }
436
+ return cutIndex;
437
+ }
438
+ function extractInlineCommentParts(content) {
439
+ const cutIndex = mapThrough(content);
440
+ if (cutIndex === -1) {
441
+ return {
442
+ contentWithoutComment: content,
443
+ inlineComment: null
444
+ };
445
+ }
446
+ return {
447
+ contentWithoutComment: content.slice(0, cutIndex),
448
+ inlineComment: content.slice(cutIndex)
449
+ };
450
+ }
451
+ function attachNode(entry, depth, line, rootNodes, stack, diagnostics, mode) {
452
+ const lineNo = line.lineNo;
453
+ while (stack.length > depth) {
454
+ stack.pop();
455
+ }
456
+ let parent = null;
457
+ if (depth > 0) {
458
+ const candidate = stack[depth - 1];
459
+ if (!candidate) {
460
+ diagnostics.push({
461
+ line: lineNo,
462
+ message: `Entry has indent depth ${depth} but no parent at depth ${depth - 1}. Treating as root.`,
463
+ severity: mode === "strict" ? "error" : "warning",
464
+ code: "missing-parent"
465
+ });
466
+ } else if (candidate.type === "file") {
467
+ if (mode === "strict") {
468
+ diagnostics.push({
469
+ line: lineNo,
470
+ message: `Cannot attach child under file "${candidate.path}".`,
471
+ severity: "error",
472
+ code: "child-of-file"
473
+ });
474
+ } else {
475
+ diagnostics.push({
476
+ line: lineNo,
477
+ message: `Entry appears under file "${candidate.path}". Attaching as sibling at depth ${candidate.depth}.`,
478
+ severity: "warning",
479
+ code: "child-of-file-loose"
480
+ });
481
+ while (stack.length > candidate.depth) {
482
+ stack.pop();
483
+ }
484
+ }
485
+ } else {
486
+ parent = candidate;
487
+ }
488
+ }
489
+ const parentPath = parent ? parent.path.replace(/\/$/, "") : "";
490
+ const normalizedSegment = toPosixPath(entry.segmentName.replace(/\/+$/, ""));
491
+ const fullPath = parentPath ? `${parentPath}/${normalizedSegment}${entry.isDir ? "/" : ""}` : `${normalizedSegment}${entry.isDir ? "/" : ""}`;
492
+ const baseNode = {
493
+ type: entry.isDir ? "dir" : "file",
494
+ name: entry.segmentName,
495
+ depth,
496
+ line: lineNo,
497
+ path: fullPath,
498
+ parent,
499
+ ...entry.stub ? { stub: entry.stub } : {},
500
+ ...entry.include ? { include: entry.include } : {},
501
+ ...entry.exclude ? { exclude: entry.exclude } : {}
502
+ };
503
+ if (entry.isDir) {
504
+ const dirNode = {
505
+ ...baseNode,
506
+ type: "dir",
507
+ children: []
508
+ };
509
+ if (parent) {
510
+ parent.children.push(dirNode);
511
+ } else {
512
+ rootNodes.push(dirNode);
513
+ }
514
+ while (stack.length > depth) {
515
+ stack.pop();
516
+ }
517
+ stack[depth] = dirNode;
518
+ } else {
519
+ const fileNode = {
520
+ ...baseNode,
521
+ type: "file"
522
+ };
523
+ if (parent) {
524
+ parent.children.push(fileNode);
525
+ } else {
526
+ rootNodes.push(fileNode);
527
+ }
528
+ }
529
+ }
530
+
531
+ // src/ast/format.ts
532
+ function formatStructureText(text, options = {}) {
533
+ const indentStep = options.indentStep ?? 2;
534
+ const mode = options.mode ?? "loose";
535
+ const normalizeNewlines = options.normalizeNewlines === void 0 ? true : options.normalizeNewlines;
536
+ const trimTrailingWhitespace = options.trimTrailingWhitespace === void 0 ? true : options.trimTrailingWhitespace;
537
+ const normalizeAnnotations = options.normalizeAnnotations === void 0 ? true : options.normalizeAnnotations;
538
+ const ast = parseStructureAst(text, {
539
+ indentStep,
540
+ mode
541
+ });
542
+ const rawLines = text.split(/\r?\n/);
543
+ const lineCount = rawLines.length;
544
+ if (ast.lines.length !== lineCount) {
545
+ return {
546
+ text: basicNormalize(text, { normalizeNewlines, trimTrailingWhitespace }),
547
+ ast
548
+ };
549
+ }
550
+ const entryLineIndexes = [];
551
+ const inlineComments = [];
552
+ for (let i = 0; i < lineCount; i++) {
553
+ const lineMeta = ast.lines[i];
554
+ if (lineMeta.kind === "entry") {
555
+ entryLineIndexes.push(i);
556
+ const { inlineComment } = extractInlineCommentParts(lineMeta.content);
557
+ inlineComments.push(inlineComment);
558
+ }
559
+ }
560
+ const flattened = [];
561
+ flattenAstNodes(ast.rootNodes, 0, flattened);
562
+ if (flattened.length !== entryLineIndexes.length) {
563
+ return {
564
+ text: basicNormalize(text, { normalizeNewlines, trimTrailingWhitespace }),
565
+ ast
566
+ };
567
+ }
568
+ const canonicalEntryLines = flattened.map(
569
+ ({ node, level }) => formatAstNodeLine(node, level, indentStep, normalizeAnnotations)
570
+ );
571
+ const resultLines = [];
572
+ let entryIdx = 0;
573
+ for (let i = 0; i < lineCount; i++) {
574
+ const lineMeta = ast.lines[i];
575
+ const originalLine = rawLines[i];
576
+ if (lineMeta.kind === "entry") {
577
+ const base = canonicalEntryLines[entryIdx].replace(/[ \t]+$/g, "");
578
+ const inline = inlineComments[entryIdx];
579
+ entryIdx++;
580
+ if (inline) {
581
+ resultLines.push(base + " " + inline);
582
+ } else {
583
+ resultLines.push(base);
584
+ }
585
+ } else {
586
+ let out = originalLine;
587
+ if (trimTrailingWhitespace) {
588
+ out = out.replace(/[ \t]+$/g, "");
589
+ }
590
+ resultLines.push(out);
591
+ }
592
+ }
593
+ const eol = normalizeNewlines ? detectPreferredEol(text) : getRawEol(text);
594
+ return {
595
+ text: resultLines.join(eol),
596
+ ast
597
+ };
598
+ }
599
+ function basicNormalize(text, opts) {
600
+ const lines = text.split(/\r?\n/);
601
+ const normalizedLines = opts.trimTrailingWhitespace ? lines.map((line) => line.replace(/[ \t]+$/g, "")) : lines;
602
+ const eol = opts.normalizeNewlines ? detectPreferredEol(text) : getRawEol(text);
603
+ return normalizedLines.join(eol);
604
+ }
605
+ function detectPreferredEol(text) {
606
+ const crlfCount = (text.match(/\r\n/g) || []).length;
607
+ const lfCount = (text.match(/(?<!\r)\n/g) || []).length;
608
+ if (crlfCount === 0 && lfCount === 0) {
609
+ return "\n";
610
+ }
611
+ if (crlfCount > lfCount) {
612
+ return "\r\n";
613
+ }
614
+ return "\n";
615
+ }
616
+ function getRawEol(text) {
617
+ return text.includes("\r\n") ? "\r\n" : "\n";
618
+ }
619
+ function flattenAstNodes(nodes, level, out) {
620
+ for (const node of nodes) {
621
+ out.push({ node, level });
622
+ if (node.type === "dir" && node.children && node.children.length) {
623
+ flattenAstNodes(node.children, level + 1, out);
624
+ }
625
+ }
626
+ }
627
+ function formatAstNodeLine(node, level, indentStep, normalizeAnnotations) {
628
+ const indent = " ".repeat(indentStep * level);
629
+ const baseName = node.name;
630
+ if (!normalizeAnnotations) {
631
+ return indent + baseName;
632
+ }
633
+ const tokens = [];
634
+ if (node.stub) {
635
+ tokens.push(`@stub:${node.stub}`);
636
+ }
637
+ if (node.include && node.include.length > 0) {
638
+ tokens.push(`@include:${node.include.join(",")}`);
639
+ }
640
+ if (node.exclude && node.exclude.length > 0) {
641
+ tokens.push(`@exclude:${node.exclude.join(",")}`);
642
+ }
643
+ const annotations = tokens.length ? " " + tokens.join(" ") : "";
644
+ return indent + baseName + annotations;
645
+ }
646
+
647
+ // src/core/structure-txt.ts
648
+ function stripInlineComment(content) {
649
+ const cutIndex = mapThrough(content);
650
+ if (cutIndex === -1) {
651
+ return content.trimEnd();
652
+ }
653
+ return content.slice(0, cutIndex).trimEnd();
654
+ }
655
+ function parseLine(line, lineNo) {
656
+ const match = line.match(/^(\s*)(.*)$/);
657
+ if (!match) return null;
658
+ const indentSpaces = match[1].length;
659
+ let rest = match[2];
660
+ if (!rest.trim()) return null;
661
+ const trimmedRest = rest.trimStart();
662
+ if (trimmedRest.startsWith("#") || trimmedRest.startsWith("//")) {
663
+ return null;
664
+ }
665
+ const stripped = stripInlineComment(rest);
666
+ const trimmed = stripped.trim();
667
+ if (!trimmed) return null;
668
+ const parts = trimmed.split(/\s+/);
669
+ if (!parts.length) return null;
670
+ const pathToken = parts[0];
671
+ if (pathToken.includes(":")) {
672
+ throw new Error(
673
+ `structure.txt: ":" is reserved for annotations (@stub:, @include:, etc). Invalid path "${pathToken}" on line ${lineNo}.`
674
+ );
675
+ }
676
+ let stub;
677
+ const include = [];
678
+ const exclude = [];
679
+ for (const token of parts.slice(1)) {
680
+ if (token.startsWith("@stub:")) {
681
+ stub = token.slice("@stub:".length);
682
+ } else if (token.startsWith("@include:")) {
683
+ const val = token.slice("@include:".length);
684
+ if (val) {
685
+ include.push(
686
+ ...val.split(",").map((s) => s.trim()).filter(Boolean)
687
+ );
688
+ }
689
+ } else if (token.startsWith("@exclude:")) {
690
+ const val = token.slice("@exclude:".length);
691
+ if (val) {
692
+ exclude.push(
693
+ ...val.split(",").map((s) => s.trim()).filter(Boolean)
694
+ );
695
+ }
696
+ }
697
+ }
698
+ return {
699
+ lineNo,
700
+ indentSpaces,
701
+ rawPath: pathToken,
702
+ stub,
703
+ include: include.length ? include : void 0,
704
+ exclude: exclude.length ? exclude : void 0
705
+ };
706
+ }
707
+ function parseStructureText(text, indentStep = 2) {
708
+ const lines = text.split(/\r?\n/);
709
+ const parsed = [];
710
+ for (let i = 0; i < lines.length; i++) {
711
+ const lineNo = i + 1;
712
+ const p = parseLine(lines[i], lineNo);
713
+ if (p) parsed.push(p);
714
+ }
715
+ const rootEntries = [];
716
+ const stack = [];
717
+ for (const p of parsed) {
718
+ const { indentSpaces, lineNo } = p;
719
+ if (indentSpaces % indentStep !== 0) {
720
+ throw new Error(
721
+ `structure.txt: Invalid indent on line ${lineNo}. Indent must be multiples of ${indentStep} spaces.`
722
+ );
723
+ }
724
+ const level = indentSpaces / indentStep;
725
+ if (level > stack.length) {
726
+ if (level !== stack.length + 1) {
727
+ throw new Error(
728
+ `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}.`
729
+ );
730
+ }
731
+ }
732
+ if (level > 0) {
733
+ const parent2 = stack[level - 1];
734
+ if (!parent2) {
735
+ throw new Error(
736
+ `structure.txt: Indented entry without a parent on line ${lineNo}.`
737
+ );
738
+ }
739
+ if (!parent2.isDir) {
740
+ throw new Error(
741
+ `structure.txt: Cannot indent under a file on line ${lineNo}. Files cannot have children. Parent: "${parent2.entry.path}".`
742
+ );
743
+ }
744
+ }
745
+ const isDir = p.rawPath.endsWith("/");
746
+ const clean = p.rawPath.replace(/\/$/, "");
747
+ const basePath = toPosixPath(clean);
748
+ while (stack.length > level) {
749
+ stack.pop();
750
+ }
751
+ const parent = stack[stack.length - 1]?.entry;
752
+ const parentPath = parent ? parent.path.replace(/\/$/, "") : "";
753
+ const fullPath = parentPath ? `${parentPath}/${basePath}${isDir ? "/" : ""}` : `${basePath}${isDir ? "/" : ""}`;
754
+ if (isDir) {
755
+ const dirEntry = {
756
+ type: "dir",
757
+ path: fullPath,
758
+ children: [],
759
+ ...p.stub ? { stub: p.stub } : {},
760
+ ...p.include ? { include: p.include } : {},
761
+ ...p.exclude ? { exclude: p.exclude } : {}
762
+ };
763
+ if (parent && parent.type === "dir") {
764
+ parent.children = parent.children ?? [];
765
+ parent.children.push(dirEntry);
766
+ } else if (!parent) {
767
+ rootEntries.push(dirEntry);
768
+ }
769
+ stack.push({ level, entry: dirEntry, isDir: true });
770
+ } else {
771
+ const fileEntry = {
772
+ type: "file",
773
+ path: fullPath,
774
+ ...p.stub ? { stub: p.stub } : {},
775
+ ...p.include ? { include: p.include } : {},
776
+ ...p.exclude ? { exclude: p.exclude } : {}
777
+ };
778
+ if (parent && parent.type === "dir") {
779
+ parent.children = parent.children ?? [];
780
+ parent.children.push(fileEntry);
781
+ } else if (!parent) {
782
+ rootEntries.push(fileEntry);
783
+ }
784
+ stack.push({ level, entry: fileEntry, isDir: false });
785
+ }
786
+ }
787
+ return rootEntries;
788
+ }
789
+
790
+ // src/core/resolve-structure.ts
791
+ var logger2 = defaultLogger.child("[structure]");
792
+ function resolveGroupStructure(scaffoldDir, group) {
793
+ if (group.structure && group.structure.length) {
794
+ logger2.debug(`Using inline structure for group "${group.name}"`);
795
+ return group.structure;
796
+ }
797
+ const fileName = group.structureFile ?? `${group.name}.txt`;
798
+ const filePath = path2__default.default.join(scaffoldDir, fileName);
799
+ if (!fs8__default.default.existsSync(filePath)) {
800
+ throw new Error(
801
+ `@timeax/scaffold: Group "${group.name}" has no structure. Expected file "${fileName}" in "${scaffoldDir}".`
802
+ );
803
+ }
804
+ logger2.debug(`Reading structure for group "${group.name}" from ${filePath}`);
805
+ const raw = fs8__default.default.readFileSync(filePath, "utf8");
806
+ return parseStructureText(raw);
807
+ }
808
+ function resolveSingleStructure(scaffoldDir, config) {
809
+ if (config.structure && config.structure.length) {
810
+ logger2.debug("Using inline single structure (no groups)");
811
+ return config.structure;
812
+ }
813
+ const fileName = config.structureFile ?? "structure.txt";
814
+ const filePath = path2__default.default.join(scaffoldDir, fileName);
815
+ if (!fs8__default.default.existsSync(filePath)) {
816
+ throw new Error(
817
+ `@timeax/scaffold: No structure defined. Expected "${fileName}" in "${scaffoldDir}".`
818
+ );
819
+ }
820
+ logger2.debug(`Reading single structure from ${filePath}`);
821
+ const raw = fs8__default.default.readFileSync(filePath, "utf8");
822
+ return parseStructureText(raw);
823
+ }
824
+ var logger3 = defaultLogger.child("[cache]");
825
+ var DEFAULT_CACHE = {
826
+ version: 1,
827
+ entries: {}
828
+ };
829
+ var CacheManager = class {
830
+ constructor(projectRoot, cacheFileRelPath) {
831
+ this.projectRoot = projectRoot;
832
+ this.cacheFileRelPath = cacheFileRelPath;
833
+ }
834
+ cache = DEFAULT_CACHE;
835
+ get cachePathAbs() {
836
+ return path2__default.default.resolve(this.projectRoot, this.cacheFileRelPath);
837
+ }
838
+ load() {
839
+ const cachePath = this.cachePathAbs;
840
+ if (!fs8__default.default.existsSync(cachePath)) {
841
+ this.cache = { ...DEFAULT_CACHE, entries: {} };
842
+ return;
843
+ }
844
+ try {
845
+ const raw = fs8__default.default.readFileSync(cachePath, "utf8");
846
+ const parsed = JSON.parse(raw);
847
+ if (parsed.version === 1 && parsed.entries) {
848
+ this.cache = parsed;
849
+ } else {
850
+ logger3.warn("Cache file version mismatch or invalid, resetting cache.");
851
+ this.cache = { ...DEFAULT_CACHE, entries: {} };
852
+ }
853
+ } catch (err) {
854
+ logger3.warn("Failed to read cache file, resetting cache.", err);
855
+ this.cache = { ...DEFAULT_CACHE, entries: {} };
856
+ }
857
+ }
858
+ save() {
859
+ const cachePath = this.cachePathAbs;
860
+ const dir = path2__default.default.dirname(cachePath);
861
+ ensureDirSync(dir);
862
+ fs8__default.default.writeFileSync(cachePath, JSON.stringify(this.cache, null, 2), "utf8");
863
+ }
864
+ get(relPath) {
865
+ const key = toPosixPath(relPath);
866
+ return this.cache.entries[key];
867
+ }
868
+ set(entry) {
869
+ const key = toPosixPath(entry.path);
870
+ this.cache.entries[key] = {
871
+ ...entry,
872
+ path: key
873
+ };
874
+ }
875
+ delete(relPath) {
876
+ const key = toPosixPath(relPath);
877
+ delete this.cache.entries[key];
878
+ }
879
+ allPaths() {
880
+ return Object.keys(this.cache.entries);
881
+ }
882
+ allEntries() {
883
+ return Object.values(this.cache.entries);
884
+ }
885
+ };
886
+ function matchesFilter(pathRel, cfg) {
887
+ const { include, exclude, files } = cfg;
888
+ const patterns = [];
889
+ if (include?.length) patterns.push(...include);
890
+ if (files?.length) patterns.push(...files);
891
+ if (patterns.length) {
892
+ const ok = patterns.some((p) => minimatch.minimatch(pathRel, p));
893
+ if (!ok) return false;
894
+ }
895
+ if (exclude?.length) {
896
+ const blocked = exclude.some((p) => minimatch.minimatch(pathRel, p));
897
+ if (blocked) return false;
898
+ }
899
+ return true;
900
+ }
901
+ var HookRunner = class {
902
+ constructor(config) {
903
+ this.config = config;
904
+ }
905
+ async runRegular(kind, ctx) {
906
+ const configs = this.config.hooks?.[kind] ?? [];
907
+ for (const cfg of configs) {
908
+ if (!matchesFilter(ctx.targetPath, cfg)) continue;
909
+ await cfg.fn(ctx);
910
+ }
911
+ }
912
+ getStubConfig(stubName) {
913
+ if (!stubName) return void 0;
914
+ return this.config.stubs?.[stubName];
915
+ }
916
+ async runStub(kind, ctx) {
917
+ const stub = this.getStubConfig(ctx.stubName);
918
+ if (!stub?.hooks) return;
919
+ const configs = kind === "preStub" ? stub.hooks.preStub ?? [] : stub.hooks.postStub ?? [];
920
+ for (const cfg of configs) {
921
+ if (!matchesFilter(ctx.targetPath, cfg)) continue;
922
+ await cfg.fn(ctx);
923
+ }
924
+ }
925
+ async renderStubContent(ctx) {
926
+ const stub = this.getStubConfig(ctx.stubName);
927
+ if (!stub?.getContent) return void 0;
928
+ return stub.getContent(ctx);
929
+ }
930
+ };
931
+ async function applyStructure(opts) {
932
+ const {
933
+ config,
934
+ projectRoot,
935
+ baseDir,
936
+ structure,
937
+ cache,
938
+ hooks,
939
+ groupName,
940
+ groupRoot,
941
+ sizePromptThreshold,
942
+ interactiveDelete
943
+ } = opts;
944
+ const logger6 = opts.logger ?? defaultLogger.child(groupName ? `[apply:${groupName}]` : "[apply]");
945
+ const desiredPaths = /* @__PURE__ */ new Set();
946
+ const threshold = sizePromptThreshold ?? config.sizePromptThreshold ?? 128 * 1024;
947
+ async function walk(entry, inheritedStub) {
948
+ const effectiveStub = entry.stub ?? inheritedStub;
949
+ if (entry.type === "dir") {
950
+ await handleDir(entry, effectiveStub);
951
+ } else {
952
+ await handleFile(entry, effectiveStub);
953
+ }
954
+ }
955
+ async function handleDir(entry, inheritedStub) {
956
+ const relFromBase = entry.path.replace(/^[./]+/, "");
957
+ const absDir = path2__default.default.resolve(baseDir, relFromBase);
958
+ const relFromRoot = toPosixPath(
959
+ toProjectRelativePath(projectRoot, absDir)
960
+ );
961
+ desiredPaths.add(relFromRoot);
962
+ ensureDirSync(absDir);
963
+ const nextStub = entry.stub ?? inheritedStub;
964
+ if (entry.children) {
965
+ for (const child of entry.children) {
966
+ await walk(child, nextStub);
967
+ }
968
+ }
969
+ }
970
+ async function handleFile(entry, inheritedStub) {
971
+ const relFromBase = entry.path.replace(/^[./]+/, "");
972
+ const absFile = path2__default.default.resolve(baseDir, relFromBase);
973
+ const relFromRoot = toPosixPath(
974
+ toProjectRelativePath(projectRoot, absFile)
975
+ );
976
+ desiredPaths.add(relFromRoot);
977
+ const stubName = entry.stub ?? inheritedStub;
978
+ const ctx = {
979
+ projectRoot,
980
+ targetPath: relFromRoot,
981
+ absolutePath: absFile,
982
+ isDirectory: false,
983
+ stubName
984
+ };
985
+ if (fs8__default.default.existsSync(absFile)) {
986
+ return;
987
+ }
988
+ await hooks.runRegular("preCreateFile", ctx);
989
+ const dir = path2__default.default.dirname(absFile);
990
+ ensureDirSync(dir);
991
+ if (stubName) {
992
+ await hooks.runStub("preStub", ctx);
993
+ }
994
+ let content = "";
995
+ const stubContent = await hooks.renderStubContent(ctx);
996
+ if (typeof stubContent === "string") {
997
+ content = stubContent;
998
+ }
999
+ fs8__default.default.writeFileSync(absFile, content, "utf8");
1000
+ const stats = fs8__default.default.statSync(absFile);
1001
+ cache.set({
1002
+ path: relFromRoot,
1003
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1004
+ sizeAtCreate: stats.size,
1005
+ createdByStub: stubName,
1006
+ groupName,
1007
+ groupRoot
1008
+ });
1009
+ logger6.info(`created ${relFromRoot}`);
1010
+ if (stubName) {
1011
+ await hooks.runStub("postStub", ctx);
1012
+ }
1013
+ await hooks.runRegular("postCreateFile", ctx);
1014
+ }
1015
+ for (const entry of structure) {
1016
+ await walk(entry);
1017
+ }
1018
+ for (const cachedPath of cache.allPaths()) {
1019
+ if (desiredPaths.has(cachedPath)) continue;
1020
+ const abs = path2__default.default.resolve(projectRoot, cachedPath);
1021
+ const stats = statSafeSync(abs);
1022
+ if (!stats) {
1023
+ cache.delete(cachedPath);
1024
+ continue;
1025
+ }
1026
+ if (!stats.isFile()) {
1027
+ cache.delete(cachedPath);
1028
+ continue;
1029
+ }
1030
+ const entry = cache.get(cachedPath);
1031
+ const ctx = {
1032
+ projectRoot,
1033
+ targetPath: cachedPath,
1034
+ absolutePath: abs,
1035
+ isDirectory: false,
1036
+ stubName: entry?.createdByStub
1037
+ };
1038
+ await hooks.runRegular("preDeleteFile", ctx);
1039
+ let shouldDelete = true;
1040
+ if (stats.size > threshold && interactiveDelete) {
1041
+ const res = await interactiveDelete({
1042
+ absolutePath: abs,
1043
+ relativePath: cachedPath,
1044
+ size: stats.size,
1045
+ createdByStub: entry?.createdByStub,
1046
+ groupName: entry?.groupName
1047
+ });
1048
+ if (res === "keep") {
1049
+ shouldDelete = false;
1050
+ cache.delete(cachedPath);
1051
+ logger6.info(`keeping ${cachedPath} (removed from cache)`);
1052
+ }
1053
+ }
1054
+ if (shouldDelete) {
1055
+ try {
1056
+ fs8__default.default.unlinkSync(abs);
1057
+ logger6.info(`deleted ${cachedPath}`);
1058
+ } catch (err) {
1059
+ logger6.warn(`failed to delete ${cachedPath}`, err);
1060
+ }
1061
+ cache.delete(cachedPath);
1062
+ await hooks.runRegular("postDeleteFile", ctx);
1063
+ }
1064
+ }
1065
+ }
1066
+ var logger4 = defaultLogger.child("[scan]");
1067
+ var DEFAULT_IGNORE = [
1068
+ "node_modules/**",
1069
+ ".git/**",
1070
+ "dist/**",
1071
+ "build/**",
1072
+ ".turbo/**",
1073
+ ".next/**",
1074
+ "coverage/**"
1075
+ ];
1076
+ function scanDirectoryToStructureText(rootDir, options = {}) {
1077
+ const absRoot = path2__default.default.resolve(rootDir);
1078
+ const lines = [];
1079
+ const ignorePatterns = options.ignore ?? DEFAULT_IGNORE;
1080
+ const maxDepth = options.maxDepth ?? Infinity;
1081
+ function isIgnored(absPath) {
1082
+ const rel = toPosixPath(path2__default.default.relative(absRoot, absPath));
1083
+ if (!rel || rel === ".") return false;
1084
+ return ignorePatterns.some(
1085
+ (pattern) => minimatch.minimatch(rel, pattern, { dot: true })
1086
+ );
1087
+ }
1088
+ function walk(currentAbs, depth) {
1089
+ if (depth > maxDepth) return;
1090
+ let dirents;
1091
+ try {
1092
+ dirents = fs8__default.default.readdirSync(currentAbs, { withFileTypes: true });
1093
+ } catch {
1094
+ return;
1095
+ }
1096
+ dirents.sort((a, b) => {
1097
+ if (a.isDirectory() && !b.isDirectory()) return -1;
1098
+ if (!a.isDirectory() && b.isDirectory()) return 1;
1099
+ return a.name.localeCompare(b.name);
1100
+ });
1101
+ for (const dirent of dirents) {
1102
+ const name = dirent.name;
1103
+ const absPath = path2__default.default.join(currentAbs, name);
1104
+ if (isIgnored(absPath)) continue;
1105
+ const indent = " ".repeat(depth);
1106
+ if (dirent.isDirectory()) {
1107
+ lines.push(`${indent}${name}/`);
1108
+ walk(absPath, depth + 1);
1109
+ } else if (dirent.isFile()) {
1110
+ lines.push(`${indent}${name}`);
1111
+ }
1112
+ }
1113
+ }
1114
+ walk(absRoot, 0);
1115
+ return lines.join("\n");
1116
+ }
1117
+ async function scanProjectFromConfig(cwd, options = {}) {
1118
+ const { config, scaffoldDir, projectRoot } = await loadScaffoldConfig(cwd, {
1119
+ scaffoldDir: options.scaffoldDir
1120
+ });
1121
+ const ignorePatterns = options.ignore ?? DEFAULT_IGNORE;
1122
+ const maxDepth = options.maxDepth ?? Infinity;
1123
+ const onlyGroups = options.groups;
1124
+ const results = [];
1125
+ function scanGroup(cfg, group) {
1126
+ const rootAbs = path2__default.default.resolve(projectRoot, group.root);
1127
+ const text = scanDirectoryToStructureText(rootAbs, {
1128
+ ignore: ignorePatterns,
1129
+ maxDepth
1130
+ });
1131
+ const structureFileName = group.structureFile ?? `${group.name}.txt`;
1132
+ const structureFilePath = path2__default.default.join(scaffoldDir, structureFileName);
1133
+ return {
1134
+ groupName: group.name,
1135
+ groupRoot: group.root,
1136
+ structureFileName,
1137
+ structureFilePath,
1138
+ text
1139
+ };
1140
+ }
1141
+ if (config.groups && config.groups.length > 0) {
1142
+ logger4.debug(
1143
+ `Scanning project from config with ${config.groups.length} group(s).`
1144
+ );
1145
+ for (const group of config.groups) {
1146
+ if (onlyGroups && !onlyGroups.includes(group.name)) {
1147
+ continue;
1148
+ }
1149
+ const result = scanGroup(config, group);
1150
+ results.push(result);
1151
+ }
1152
+ } else {
1153
+ logger4.debug("Scanning project in single-root mode (no groups).");
1154
+ const text = scanDirectoryToStructureText(projectRoot, {
1155
+ ignore: ignorePatterns,
1156
+ maxDepth
1157
+ });
1158
+ const structureFileName = config.structureFile ?? "structure.txt";
1159
+ const structureFilePath = path2__default.default.join(scaffoldDir, structureFileName);
1160
+ results.push({
1161
+ groupName: "default",
1162
+ groupRoot: ".",
1163
+ structureFileName,
1164
+ structureFilePath,
1165
+ text
1166
+ });
1167
+ }
1168
+ return results;
1169
+ }
1170
+ async function writeScannedStructuresFromConfig(cwd, options = {}) {
1171
+ const { scaffoldDir } = await loadScaffoldConfig(cwd, {
1172
+ scaffoldDir: options.scaffoldDir
1173
+ });
1174
+ ensureDirSync(scaffoldDir);
1175
+ const results = await scanProjectFromConfig(cwd, options);
1176
+ for (const result of results) {
1177
+ fs8__default.default.writeFileSync(result.structureFilePath, result.text, "utf8");
1178
+ logger4.info(
1179
+ `Wrote structure for group "${result.groupName}" to ${result.structureFilePath}`
1180
+ );
1181
+ }
1182
+ }
1183
+ async function ensureStructureFilesFromConfig(cwd, options = {}) {
1184
+ const { config, scaffoldDir } = await loadScaffoldConfig(cwd, {
1185
+ scaffoldDir: options.scaffoldDirOverride
1186
+ });
1187
+ ensureDirSync(scaffoldDir);
1188
+ const created = [];
1189
+ const existing = [];
1190
+ const seen = /* @__PURE__ */ new Set();
1191
+ const ensureFile = (fileName) => {
1192
+ if (!fileName) return;
1193
+ const filePath = path2__default.default.join(scaffoldDir, fileName);
1194
+ const key = path2__default.default.resolve(filePath);
1195
+ if (seen.has(key)) return;
1196
+ seen.add(key);
1197
+ if (fs8__default.default.existsSync(filePath)) {
1198
+ existing.push(filePath);
1199
+ return;
1200
+ }
1201
+ const header = `# ${fileName}
1202
+ # Structure file for @timeax/scaffold
1203
+ # Define your desired folders/files here.
1204
+ `;
1205
+ fs8__default.default.writeFileSync(filePath, header, "utf8");
1206
+ created.push(filePath);
1207
+ };
1208
+ if (config.groups && config.groups.length > 0) {
1209
+ for (const group of config.groups) {
1210
+ const fileName = group.structureFile ?? `${group.name}.txt`;
1211
+ ensureFile(fileName);
1212
+ }
1213
+ } else {
1214
+ const fileName = config.structureFile ?? "structure.txt";
1215
+ ensureFile(fileName);
1216
+ }
1217
+ logger4.debug(
1218
+ `ensureStructureFilesFromConfig: created=${created.length}, existing=${existing.length}`
1219
+ );
1220
+ return { created, existing };
1221
+ }
1222
+
1223
+ // src/core/format.ts
1224
+ function getStructureFilesFromConfig(projectRoot, scaffoldDir, config) {
1225
+ const baseDir = path2__default.default.resolve(projectRoot, scaffoldDir || SCAFFOLD_ROOT_DIR);
1226
+ const files = [];
1227
+ if (config.groups && config.groups.length > 0) {
1228
+ for (const group of config.groups) {
1229
+ const structureFile = group.structureFile && group.structureFile.trim().length ? group.structureFile : `${group.name}.txt`;
1230
+ files.push(path2__default.default.join(baseDir, structureFile));
1231
+ }
1232
+ } else {
1233
+ const structureFile = config.structureFile || "structure.txt";
1234
+ files.push(path2__default.default.join(baseDir, structureFile));
1235
+ }
1236
+ return files;
1237
+ }
1238
+ async function formatStructureFilesFromConfig(projectRoot, scaffoldDir, config, opts = {}) {
1239
+ const formatCfg = config.format;
1240
+ const enabled = !!(formatCfg?.enabled || opts.force);
1241
+ if (!enabled) return;
1242
+ const files = getStructureFilesFromConfig(projectRoot, scaffoldDir, config);
1243
+ const indentStep = formatCfg?.indentStep ?? config.indentStep ?? 2;
1244
+ const mode = formatCfg?.mode ?? "loose";
1245
+ !!formatCfg?.sortEntries;
1246
+ for (const filePath of files) {
1247
+ let text;
1248
+ try {
1249
+ text = fs8__default.default.readFileSync(filePath, "utf8");
1250
+ } catch {
1251
+ continue;
1252
+ }
1253
+ const { text: formatted } = formatStructureText(text, {
1254
+ indentStep,
1255
+ mode});
1256
+ if (formatted !== text) {
1257
+ fs8__default.default.writeFileSync(filePath, formatted, "utf8");
1258
+ }
1259
+ }
1260
+ }
1261
+
1262
+ // src/core/runner.ts
1263
+ async function runOnce(cwd, options = {}) {
1264
+ const logger6 = options.logger ?? defaultLogger.child("[runner]");
1265
+ const { config, scaffoldDir, projectRoot } = await loadScaffoldConfig(cwd, {
1266
+ scaffoldDir: options.scaffoldDir,
1267
+ configPath: options.configPath
1268
+ });
1269
+ await formatStructureFilesFromConfig(projectRoot, scaffoldDir, config, { force: options.format });
1270
+ const cachePath = config.cacheFile ?? ".scaffold-cache.json";
1271
+ const cache = new CacheManager(projectRoot, cachePath);
1272
+ cache.load();
1273
+ const hooks = new HookRunner(config);
1274
+ if (config.groups && config.groups.length > 0) {
1275
+ for (const group of config.groups) {
1276
+ const groupRootAbs = path2__default.default.resolve(projectRoot, group.root);
1277
+ const structure = resolveGroupStructure(scaffoldDir, group);
1278
+ const groupLogger = logger6.child(`[group:${group.name}]`);
1279
+ await applyStructure({
1280
+ config,
1281
+ projectRoot,
1282
+ baseDir: groupRootAbs,
1283
+ structure,
1284
+ cache,
1285
+ hooks,
1286
+ groupName: group.name,
1287
+ groupRoot: group.root,
1288
+ interactiveDelete: options.interactiveDelete,
1289
+ logger: groupLogger
1290
+ });
1291
+ }
1292
+ } else {
1293
+ const structure = resolveSingleStructure(scaffoldDir, config);
1294
+ const baseLogger = logger6.child("[group:default]");
1295
+ await applyStructure({
1296
+ config,
1297
+ projectRoot,
1298
+ baseDir: projectRoot,
1299
+ structure,
1300
+ cache,
1301
+ hooks,
1302
+ groupName: "default",
1303
+ groupRoot: ".",
1304
+ interactiveDelete: options.interactiveDelete,
1305
+ logger: baseLogger
1306
+ });
1307
+ }
1308
+ cache.save();
1309
+ }
1310
+ function watchScaffold(cwd, options = {}) {
1311
+ const logger6 = options.logger ?? defaultLogger.child("[watch]");
1312
+ const scaffoldDir = options.scaffoldDir ? path2__default.default.resolve(cwd, options.scaffoldDir) : path2__default.default.resolve(cwd, SCAFFOLD_ROOT_DIR);
1313
+ const debounceMs = options.debounceMs ?? 150;
1314
+ logger6.info(`Watching scaffold directory: ${scaffoldDir}`);
1315
+ let timer;
1316
+ let running = false;
1317
+ let pending = false;
1318
+ async function run() {
1319
+ if (running) {
1320
+ pending = true;
1321
+ return;
1322
+ }
1323
+ running = true;
1324
+ try {
1325
+ logger6.info("Change detected \u2192 running scaffold...");
1326
+ await runOnce(cwd, {
1327
+ ...options,
1328
+ // we already resolved scaffoldDir for watcher; pass it down
1329
+ scaffoldDir
1330
+ });
1331
+ logger6.info("Scaffold run completed.");
1332
+ } catch (err) {
1333
+ logger6.error("Scaffold run failed:", err);
1334
+ } finally {
1335
+ running = false;
1336
+ if (pending) {
1337
+ pending = false;
1338
+ timer = setTimeout(run, debounceMs);
1339
+ }
1340
+ }
1341
+ }
1342
+ function scheduleRun() {
1343
+ if (timer) clearTimeout(timer);
1344
+ timer = setTimeout(run, debounceMs);
1345
+ }
1346
+ const watcher = chokidar__default.default.watch(
1347
+ [
1348
+ // config files (ts/js/etc.)
1349
+ path2__default.default.join(scaffoldDir, "config.*"),
1350
+ // structure files: plain txt + our custom extensions
1351
+ path2__default.default.join(scaffoldDir, "*.txt"),
1352
+ path2__default.default.join(scaffoldDir, "*.tss"),
1353
+ path2__default.default.join(scaffoldDir, "*.stx")
1354
+ ],
1355
+ {
1356
+ ignoreInitial: false
1357
+ }
1358
+ );
1359
+ watcher.on("add", (filePath) => {
1360
+ logger6.debug(`File added: ${filePath}`);
1361
+ scheduleRun();
1362
+ }).on("change", (filePath) => {
1363
+ logger6.debug(`File changed: ${filePath}`);
1364
+ scheduleRun();
1365
+ }).on("unlink", (filePath) => {
1366
+ logger6.debug(`File removed: ${filePath}`);
1367
+ scheduleRun();
1368
+ }).on("error", (error) => {
1369
+ logger6.error("Watcher error:", error);
1370
+ });
1371
+ scheduleRun();
1372
+ }
1373
+ var logger5 = defaultLogger.child("[init]");
1374
+ var DEFAULT_CONFIG_TS = `import type { ScaffoldConfig } from '@timeax/scaffold';
1375
+
1376
+ const config: ScaffoldConfig = {
1377
+ // Root for resolving the .scaffold folder & this config file.
1378
+ // By default, this is the directory where you run \`scaffold\`.
1379
+ // Example:
1380
+ // root: '.', // .scaffold at <cwd>/.scaffold
1381
+ // root: 'tools', // .scaffold at <cwd>/tools/.scaffold
1382
+ // root: '.',
1383
+
1384
+ // Base directory where structures are applied and files/folders are created.
1385
+ // This is resolved relative to \`root\` above. Defaults to the same as root.
1386
+ // Example:
1387
+ // base: '.', // apply to <root>
1388
+ // base: 'src', // apply to <root>/src
1389
+ // base: '..', // apply to parent of <root>
1390
+ // base: '.',
1391
+
1392
+ // Number of spaces per indent level in structure files (default: 2).
1393
+ // This also informs the formatter when indenting entries.
1394
+ // indentStep: 2,
1395
+
1396
+ // Cache file path, relative to base.
1397
+ // cacheFile: '.scaffold-cache.json',
1398
+
1399
+ // Formatting options for structure files.
1400
+ // These are used by:
1401
+ // - \`scaffold --format\` (forces formatting before apply)
1402
+ // - \`scaffold --watch\` when \`formatOnWatch\` is true
1403
+ //
1404
+ // format: {
1405
+ // // Enable config-driven formatting in general.
1406
+ // // \`scaffold --format\` always forces formatting even if this is false.
1407
+ // enabled: true,
1408
+ //
1409
+ // // Override indent step specifically for formatting (falls back to
1410
+ // // top-level \`indentStep\` if omitted).
1411
+ // indentStep: 2,
1412
+ //
1413
+ // // AST mode:
1414
+ // // - 'loose' (default): tries to repair mild indentation issues.
1415
+ // // - 'strict': mostly cosmetic changes (trims trailing whitespace, etc.).
1416
+ // mode: 'loose',
1417
+ //
1418
+ // // Sort non-comment entries lexicographically within their parent block.
1419
+ // // Comments and blank lines keep their relative positions.
1420
+ // sortEntries: true,
1421
+ //
1422
+ // // When running \`scaffold --watch\`, format structure files on each
1423
+ // // detected change before applying scaffold.
1424
+ // formatOnWatch: true,
1425
+ // },
1426
+
1427
+ // --- Single-structure mode (simple) ---
1428
+ // structureFile: 'structure.txt',
1429
+
1430
+ // --- Grouped mode (uncomment and adjust) ---
1431
+ // groups: [
1432
+ // { name: 'app', root: 'app', structureFile: 'app.txt' },
1433
+ // { name: 'frontend', root: 'resources/js', structureFile: 'frontend.txt' },
1434
+ // ],
1435
+
1436
+ hooks: {
1437
+ // preCreateFile: [],
1438
+ // postCreateFile: [],
1439
+ // preDeleteFile: [],
1440
+ // postDeleteFile: [],
1441
+ },
1442
+
1443
+ stubs: {
1444
+ // Example:
1445
+ // page: {
1446
+ // name: 'page',
1447
+ // getContent: (ctx) =>
1448
+ // \`export default function Page() { return <div>\${ctx.targetPath}</div>; }\`,
1449
+ // },
1450
+ }
1451
+ };
1452
+
1453
+ export default config;
1454
+ `;
1455
+ var DEFAULT_STRUCTURE_TXT = `# ${SCAFFOLD_ROOT_DIR}/structure.txt
1456
+ # Example structure definition.
1457
+ # - Indent with 2 spaces per level (or your configured indentStep)
1458
+ # - Directories must end with "/"
1459
+ # - Files do not
1460
+ # - Lines starting with "#" are comments and ignored by parser
1461
+ # - Inline comments are allowed after "#" or "//" separated by whitespace
1462
+ #
1463
+ # The formatter (when enabled via config.format or --format) will:
1464
+ # - Normalize indentation based on indentStep
1465
+ # - Preserve blank lines and comments
1466
+ # - Keep inline comments attached to their entries
1467
+ #
1468
+ # Example:
1469
+ # src/
1470
+ # index.ts
1471
+ `;
1472
+ async function initScaffold(cwd, options = {}) {
1473
+ const scaffoldDirRel = options.scaffoldDir ?? SCAFFOLD_ROOT_DIR;
1474
+ const scaffoldDirAbs = path2__default.default.resolve(cwd, scaffoldDirRel);
1475
+ const configFileName = options.configFileName ?? "config.ts";
1476
+ const structureFileName = options.structureFileName ?? "structure.txt";
1477
+ ensureDirSync(scaffoldDirAbs);
1478
+ const configPath = path2__default.default.join(scaffoldDirAbs, configFileName);
1479
+ const structurePath = path2__default.default.join(scaffoldDirAbs, structureFileName);
1480
+ let createdConfig = false;
1481
+ let createdStructure = false;
1482
+ if (fs8__default.default.existsSync(configPath) && !options.force) {
1483
+ logger5.info(
1484
+ `Config already exists at ${configPath} (use --force to overwrite).`
1485
+ );
1486
+ } else {
1487
+ fs8__default.default.writeFileSync(configPath, DEFAULT_CONFIG_TS, "utf8");
1488
+ createdConfig = true;
1489
+ logger5.info(
1490
+ `${fs8__default.default.existsSync(configPath) ? "Overwrote" : "Created"} config at ${configPath}`
1491
+ );
1492
+ }
1493
+ if (fs8__default.default.existsSync(structurePath) && !options.force) {
1494
+ logger5.info(
1495
+ `Structure file already exists at ${structurePath} (use --force to overwrite).`
1496
+ );
1497
+ } else {
1498
+ fs8__default.default.writeFileSync(structurePath, DEFAULT_STRUCTURE_TXT, "utf8");
1499
+ createdStructure = true;
1500
+ logger5.info(
1501
+ `${fs8__default.default.existsSync(structurePath) ? "Overwrote" : "Created"} structure file at ${structurePath}`
1502
+ );
1503
+ }
1504
+ return {
1505
+ scaffoldDir: scaffoldDirAbs,
1506
+ configPath,
1507
+ structurePath,
1508
+ created: {
1509
+ config: createdConfig,
1510
+ structure: createdStructure
1511
+ }
1512
+ };
1513
+ }
1514
+
1515
+ // src/cli/main.ts
1516
+ function createCliLogger(opts) {
1517
+ if (opts.quiet) {
1518
+ defaultLogger.setLevel("silent");
1519
+ } else if (opts.debug) {
1520
+ defaultLogger.setLevel("debug");
1521
+ }
1522
+ return defaultLogger.child("[cli]");
1523
+ }
1524
+ function askYesNo(question) {
1525
+ const rl = readline__default.default.createInterface({
1526
+ input: process.stdin,
1527
+ output: process.stdout
1528
+ });
1529
+ return new Promise((resolve) => {
1530
+ rl.question(`${question} [y/N] `, (answer) => {
1531
+ rl.close();
1532
+ const val = answer.trim().toLowerCase();
1533
+ if (val === "y" || val === "yes") {
1534
+ resolve("delete");
1535
+ } else {
1536
+ resolve("keep");
1537
+ }
1538
+ });
1539
+ });
1540
+ }
1541
+ async function handleRunCommand(cwd, baseOpts) {
1542
+ const logger6 = createCliLogger(baseOpts);
1543
+ const configPath = baseOpts.config ? path2__default.default.resolve(cwd, baseOpts.config) : void 0;
1544
+ const scaffoldDir = baseOpts.dir ? path2__default.default.resolve(cwd, baseOpts.dir) : void 0;
1545
+ logger6.debug(
1546
+ `Starting scaffold (cwd=${cwd}, config=${configPath ?? "auto"}, dir=${scaffoldDir ?? "scaffold/"}, watch=${baseOpts.watch ? "yes" : "no"})`
1547
+ );
1548
+ const runnerOptions = {
1549
+ configPath,
1550
+ scaffoldDir,
1551
+ logger: logger6,
1552
+ interactiveDelete: async ({
1553
+ relativePath,
1554
+ size,
1555
+ createdByStub,
1556
+ groupName
1557
+ }) => {
1558
+ const sizeKb = (size / 1024).toFixed(1);
1559
+ const stubInfo = createdByStub ? ` (stub: ${createdByStub})` : "";
1560
+ const groupInfo = groupName ? ` [group: ${groupName}]` : "";
1561
+ const question = `File "${relativePath}"${groupInfo} is ~${sizeKb}KB and no longer in structure${stubInfo}. Delete it?`;
1562
+ return askYesNo(question);
1563
+ }
1564
+ };
1565
+ if (baseOpts.watch) {
1566
+ watchScaffold(cwd, runnerOptions);
1567
+ } else {
1568
+ await runOnce(cwd, runnerOptions);
1569
+ }
1570
+ }
1571
+ async function handleScanCommand(cwd, scanOpts, baseOpts) {
1572
+ const logger6 = createCliLogger(baseOpts);
1573
+ const useConfigMode = scanOpts.fromConfig || !scanOpts.root && !scanOpts.out;
1574
+ if (useConfigMode) {
1575
+ logger6.info("Scanning project using scaffold config/groups...");
1576
+ await writeScannedStructuresFromConfig(cwd, {
1577
+ ignore: scanOpts.ignore,
1578
+ groups: scanOpts.groups
1579
+ });
1580
+ return;
1581
+ }
1582
+ const rootDir = path2__default.default.resolve(cwd, scanOpts.root ?? ".");
1583
+ const ignore = scanOpts.ignore ?? [];
1584
+ logger6.info(`Scanning directory for structure: ${rootDir}`);
1585
+ const text = scanDirectoryToStructureText(rootDir, {
1586
+ ignore
1587
+ });
1588
+ if (scanOpts.out) {
1589
+ const outPath = path2__default.default.resolve(cwd, scanOpts.out);
1590
+ const dir = path2__default.default.dirname(outPath);
1591
+ ensureDirSync(dir);
1592
+ fs8__default.default.writeFileSync(outPath, text, "utf8");
1593
+ logger6.info(`Wrote structure to ${outPath}`);
1594
+ } else {
1595
+ process.stdout.write(text + "\n");
1596
+ }
1597
+ }
1598
+ async function handleInitCommand(cwd, initOpts, baseOpts) {
1599
+ const logger6 = createCliLogger(baseOpts);
1600
+ const scaffoldDirRel = baseOpts.dir ?? "scaffold";
1601
+ logger6.info(`Initializing scaffold directory at "${scaffoldDirRel}"...`);
1602
+ const result = await initScaffold(cwd, {
1603
+ scaffoldDir: scaffoldDirRel,
1604
+ force: initOpts.force
1605
+ });
1606
+ logger6.info(
1607
+ `Done. Config: ${result.configPath}, Structure: ${result.structurePath}`
1608
+ );
1609
+ }
1610
+ async function handleStructuresCommand(cwd, baseOpts) {
1611
+ const logger6 = createCliLogger(baseOpts);
1612
+ logger6.info("Ensuring structure files declared in config exist...");
1613
+ const { created, existing } = await ensureStructureFilesFromConfig(cwd, {
1614
+ scaffoldDirOverride: baseOpts.dir
1615
+ });
1616
+ if (created.length === 0) {
1617
+ logger6.info("All structure files already exist. Nothing to do.");
1618
+ } else {
1619
+ for (const filePath of created) {
1620
+ logger6.info(`Created structure file: ${filePath}`);
1621
+ }
1622
+ }
1623
+ existing.forEach((p) => logger6.debug(`Structure file already exists: ${p}`));
1624
+ }
1625
+ async function main() {
1626
+ const cwd = process.cwd();
1627
+ const program = new commander.Command();
1628
+ 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");
1629
+ program.command("scan").description(
1630
+ "Generate structure.txt-style output (config-aware by default, or manual root/out)"
1631
+ ).option(
1632
+ "--from-config",
1633
+ "Scan based on scaffold config/groups and write structure files into scaffold/ (default if no root/out specified)"
1634
+ ).option(
1635
+ "-r, --root <path>",
1636
+ "Root directory to scan (manual mode)"
1637
+ ).option(
1638
+ "-o, --out <path>",
1639
+ "Output file path (manual mode)"
1640
+ ).option(
1641
+ "--ignore <patterns...>",
1642
+ "Additional glob patterns to ignore (relative to root)"
1643
+ ).option(
1644
+ "--groups <names...>",
1645
+ "Limit config-based scanning to specific groups (by name)"
1646
+ ).action(async (scanOpts, cmd) => {
1647
+ const baseOpts = cmd.parent?.opts() ?? {};
1648
+ await handleScanCommand(cwd, scanOpts, baseOpts);
1649
+ });
1650
+ program.command("init").description("Initialize scaffold folder and config/structure files").option(
1651
+ "--force",
1652
+ "Overwrite existing config/structure files if they already exist"
1653
+ ).action(async (initOpts, cmd) => {
1654
+ const baseOpts = cmd.parent?.opts() ?? {};
1655
+ await handleInitCommand(cwd, initOpts, baseOpts);
1656
+ });
1657
+ program.action(async (opts) => {
1658
+ await handleRunCommand(cwd, opts);
1659
+ });
1660
+ program.command("structures").description(
1661
+ "Create missing structure files specified in the config (does not overwrite existing files)"
1662
+ ).action(async (_opts, cmd) => {
1663
+ const baseOpts = cmd.parent?.opts() ?? {};
1664
+ await handleStructuresCommand(cwd, baseOpts);
1665
+ });
1666
+ await program.parseAsync(process.argv);
1667
+ }
1668
+ main().catch((err) => {
1669
+ defaultLogger.error(err);
1670
+ process.exit(1);
1671
+ });
1672
+ //# sourceMappingURL=cli.cjs.map
1673
+ //# sourceMappingURL=cli.cjs.map