@seanningtatum/software-factory-lint 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,1100 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/lint.ts
4
+ import { readFileSync as readFileSync5 } from "node:fs";
5
+ import { join as join6 } from "node:path";
6
+ import ts7 from "@typescript/typescript6";
7
+
8
+ // src/config.ts
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ var CONFIG_FILE = "software-factory-lint.json";
12
+ var defaultFeatureLayout = {
13
+ dir: "src/features",
14
+ folders: ["api", "routes", "components", "machines", "lib", "e2e"],
15
+ files: [
16
+ "feature.json",
17
+ "TIMELINE.md",
18
+ "constants.ts",
19
+ "schema.ts",
20
+ "events.ts",
21
+ "errors.ts",
22
+ "layer.ts",
23
+ "nav.ts",
24
+ "viewer.ts",
25
+ "auth-plugins.ts",
26
+ "workflows.ts"
27
+ ],
28
+ required: ["feature.json", "TIMELINE.md"],
29
+ placement: {
30
+ "*.machine.ts": ["components", "machines"],
31
+ "*.spec.ts": ["e2e"]
32
+ },
33
+ core: {
34
+ dir: "core",
35
+ lib: "lib",
36
+ componentFolders: ["components", "lib"],
37
+ componentFiles: ["feature.json", "TIMELINE.md", "constants.ts"],
38
+ serviceFolders: ["api", "lib", "machines", "routes"],
39
+ serverRoutes: "api"
40
+ }
41
+ };
42
+ var defaults = {
43
+ include: ["src/**/*.{ts,tsx}"],
44
+ exclude: ["src/gen/**", "src/routeTree.gen.ts", "**/*.d.ts"],
45
+ allow: {},
46
+ maxLines: 400,
47
+ maxRulesLines: 80,
48
+ testMap: [
49
+ { files: "src/**/*.machine.ts", requires: ["{dir}/{file}.test.ts"] },
50
+ {
51
+ files: "src/features/*/components/*.machine.ts",
52
+ requires: ["src/features/{feature}/e2e/{name}.paths.spec.ts"]
53
+ },
54
+ { files: "src/{app,features}/**/*.ts", requires: ["{dir}/{file}.test.ts"] },
55
+ {
56
+ files: "src/features/*/routes/**/*.{ts,tsx}",
57
+ requires: ["src/features/{feature}/e2e/{route}.route.spec.ts"],
58
+ always: true
59
+ },
60
+ {
61
+ files: "src/features/core/*/routes/**/*.{ts,tsx}",
62
+ requires: ["src/features/home/e2e/{route}.route.spec.ts"],
63
+ always: true
64
+ }
65
+ ],
66
+ testExempt: ["**/*.test.ts", "**/*.spec.ts"],
67
+ featureLayout: defaultFeatureLayout
68
+ };
69
+ var loadConfig = (root) => {
70
+ const path = join(root, CONFIG_FILE);
71
+ if (!existsSync(path))
72
+ return defaults;
73
+ const user = JSON.parse(readFileSync(path, "utf8"));
74
+ return {
75
+ ...defaults,
76
+ ...user,
77
+ exclude: [...defaults.exclude, ...user.exclude ?? []],
78
+ testExempt: [...defaults.testExempt, ...user.testExempt ?? []],
79
+ featureLayout: {
80
+ ...defaults.featureLayout,
81
+ ...user.featureLayout,
82
+ core: { ...defaults.featureLayout.core, ...user.featureLayout?.core }
83
+ }
84
+ };
85
+ };
86
+
87
+ // src/files.ts
88
+ import { readdirSync } from "node:fs";
89
+ import { createRequire } from "node:module";
90
+ import { join as join2, relative, sep } from "node:path";
91
+ var toSlash = (path, separator = sep) => path.split(separator).join("/");
92
+ var walk = (root, dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
93
+ if (entry.name === "node_modules" || entry.name.startsWith("."))
94
+ return [];
95
+ const path = join2(dir, entry.name);
96
+ return entry.isDirectory() ? walk(root, path) : [toSlash(relative(root, path))];
97
+ });
98
+ var ts;
99
+ var importSpecifiers = (text) => {
100
+ ts ??= createRequire(import.meta.url)("@typescript/typescript6");
101
+ return ts.preProcessFile(text, true, true).importedFiles.map((f) => f.fileName);
102
+ };
103
+ var TEST_FILE = /\.(test|spec)\.tsx?$/;
104
+ var byCodeUnit = (a, b) => Number(a > b) - Number(a < b);
105
+
106
+ // src/glob.ts
107
+ var escapeRegExp = (s) => s.replace(/[.+^$()|[\]\\]/g, "\\$&");
108
+ var token = (glob, i) => {
109
+ const c = glob[i];
110
+ if (c === "*" && glob[i + 1] === "*") {
111
+ return glob[i + 2] === "/" ? { out: "(?:.*/)?", used: 3 } : { out: ".*", used: 2 };
112
+ }
113
+ if (c === "*")
114
+ return { out: "[^/]*", used: 1 };
115
+ if (c === "?")
116
+ return { out: "[^/]", used: 1 };
117
+ if (c === "{") {
118
+ const end = glob.indexOf("}", i);
119
+ if (end < 0)
120
+ return { out: "\\{", used: 1 };
121
+ const options = glob.slice(i + 1, end).split(",").map(source);
122
+ return { out: `(?:${options.join("|")})`, used: end - i + 1 };
123
+ }
124
+ return { out: escapeRegExp(c), used: 1 };
125
+ };
126
+ function source(glob) {
127
+ let out = "";
128
+ for (let i = 0;i < glob.length; ) {
129
+ const t = token(glob, i);
130
+ out += t.out;
131
+ i += t.used;
132
+ }
133
+ return out;
134
+ }
135
+ var globToRegExp = (glob) => new RegExp(`^${source(glob)}$`);
136
+ var matchesAny = (path, globs) => globs.some((g) => globToRegExp(g).test(path));
137
+
138
+ // src/rules/api-paths.ts
139
+ import { readFileSync as readFileSync2 } from "node:fs";
140
+ import { join as join3 } from "node:path";
141
+ import ts3 from "@typescript/typescript6";
142
+
143
+ // src/rules/ast-rules.ts
144
+ import ts2 from "@typescript/typescript6";
145
+
146
+ // src/place.ts
147
+ var split = (rest) => {
148
+ const cut = rest.indexOf("/");
149
+ return cut < 0 ? undefined : [rest.slice(0, cut), rest.slice(cut + 1)];
150
+ };
151
+ var placeOf = (layout, path) => {
152
+ const prefix = `${layout.dir}/`;
153
+ if (!path.startsWith(prefix))
154
+ return;
155
+ const rest = path.slice(prefix.length);
156
+ const top = split(rest);
157
+ if (!top)
158
+ return { kind: "loose", folder: "", inner: rest };
159
+ const [name, inner] = top;
160
+ if (name !== layout.core.dir)
161
+ return { kind: "feature", folder: name, inner };
162
+ const sub = split(inner);
163
+ if (!sub)
164
+ return { kind: "loose", folder: name, inner };
165
+ const [module, moduleInner] = sub;
166
+ const folder = `${name}/${module}`;
167
+ return module === layout.core.lib ? { kind: "lib", folder, inner: moduleInner } : { kind: "core", folder, inner: moduleInner };
168
+ };
169
+
170
+ // src/rules/ast-rules.ts
171
+ var lineOf = (source, node) => source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
172
+ var visit = (node, fn) => {
173
+ fn(node);
174
+ ts2.forEachChild(node, (child) => visit(child, fn));
175
+ };
176
+ var collect = (source, match) => {
177
+ const out = [];
178
+ visit(source, (n) => {
179
+ const message = match(n);
180
+ if (message)
181
+ out.push({ line: lineOf(source, n), message });
182
+ });
183
+ return out;
184
+ };
185
+ var calledName = (n) => {
186
+ if (!ts2.isCallExpression(n))
187
+ return;
188
+ const e = n.expression;
189
+ if (ts2.isIdentifier(e))
190
+ return e.text;
191
+ return ts2.isPropertyAccessExpression(e) ? e.name.text : undefined;
192
+ };
193
+ var noThrow = {
194
+ id: "no-throw",
195
+ description: "Fail in the error channel (`return yield* new SomeError()`), not with `throw`.",
196
+ check: ({ source }) => collect(source, (n) => ts2.isThrowStatement(n) ? "use a tagged error in the Effect error channel instead of throw" : undefined)
197
+ };
198
+ var noTryCatch = {
199
+ id: "no-try-catch",
200
+ description: "Wrap code that can throw in Effect.try / Effect.tryPromise.",
201
+ check: ({ source }) => collect(source, (n) => ts2.isTryStatement(n) ? "use Effect.try or Effect.tryPromise instead of try/catch" : undefined)
202
+ };
203
+ var RUNNERS = /^run(Promise|Sync|Fork|Callback)(Exit)?(With)?$/;
204
+ var noRunEffect = {
205
+ id: "no-run-effect",
206
+ description: "Only edges run effects: server functions go through runEffect, the worker through the request runtime.",
207
+ check: ({ source }) => collect(source, (n) => ts2.isIdentifier(n) && RUNNERS.test(n.text) ? `${n.text} outside an edge; return the Effect and let the edge run it` : undefined)
208
+ };
209
+ var isProcess = (e) => ts2.isIdentifier(e) && e.text === "process" || ts2.isPropertyAccessExpression(e) && e.name.text === "process" && ts2.isIdentifier(e.expression) && e.expression.text === "globalThis";
210
+ var readsProcessEnv = (n) => {
211
+ if (ts2.isPropertyAccessExpression(n))
212
+ return n.name.text === "env" && isProcess(n.expression);
213
+ if (ts2.isElementAccessExpression(n)) {
214
+ const key = n.argumentExpression;
215
+ return ts2.isStringLiteralLike(key) && key.text === "env" && isProcess(n.expression);
216
+ }
217
+ if (ts2.isVariableDeclaration(n) && n.initializer && ts2.isObjectBindingPattern(n.name)) {
218
+ const names = n.name.elements.map((el) => (el.propertyName ?? el.name).getText());
219
+ return names.includes("env") && isProcess(n.initializer);
220
+ }
221
+ if (ts2.isImportDeclaration(n) && ts2.isStringLiteral(n.moduleSpecifier)) {
222
+ const bindings = n.importClause?.namedBindings;
223
+ return /^(node:)?process$/.test(n.moduleSpecifier.text) && bindings !== undefined && ts2.isNamedImports(bindings) && bindings.elements.some((el) => (el.propertyName ?? el.name).text === "env");
224
+ }
225
+ return false;
226
+ };
227
+ var noProcessEnv = {
228
+ id: "no-process-env",
229
+ description: "Workers have no process.env; read settings from the CloudflareEnv service.",
230
+ check: ({ source }) => collect(source, (n) => readsProcessEnv(n) ? "read settings from the CloudflareEnv service, not process.env" : undefined)
231
+ };
232
+ var isSpanned = (node) => {
233
+ for (let cur = node.parent;cur; cur = cur.parent) {
234
+ if (ts2.isCallExpression(cur)) {
235
+ const text = cur.expression.getText();
236
+ if (/^(?:\w+\.)?fn\(\s*["'`]/.test(text) || /^(?:\w+\.)?fn$/.test(text) && cur.arguments[0] && ts2.isStringLiteralLike(cur.arguments[0]))
237
+ return true;
238
+ if (/\.pipe$/.test(text) && cur.arguments.some((a) => /\bwithSpan\(/.test(a.getText())))
239
+ return true;
240
+ }
241
+ }
242
+ return false;
243
+ };
244
+ var externalCallSpan = {
245
+ id: "external-call-span",
246
+ description: 'Every outside call (Effect.tryPromise) runs inside Effect.fn("name") or pipes Effect.withSpan.',
247
+ check: ({ source }) => collect(source, (n) => calledName(n) === "tryPromise" && !isSpanned(n) ? 'wrap this outside call in Effect.fn("Name.method") or pipe Effect.withSpan(...)' : undefined)
248
+ };
249
+ var insideYield = (node) => {
250
+ for (let cur = node.parent;cur && !ts2.isFunctionLike(cur); cur = cur.parent)
251
+ if (ts2.isYieldExpression(cur))
252
+ return true;
253
+ return false;
254
+ };
255
+ var noNestedYield = {
256
+ id: "no-nested-yield",
257
+ description: "One yield per expression: name the service, then call it.",
258
+ check: ({ source }) => collect(source, (n) => ts2.isYieldExpression(n) && insideYield(n) ? "name the inner yield first: `const x = yield* X;` then `yield* x.method()`" : undefined)
259
+ };
260
+ var fileSize = {
261
+ id: "file-size",
262
+ description: "Keep files small enough to read in one go.",
263
+ check: ({ source, config }) => {
264
+ const lines = source.getLineStarts().length - (source.text.endsWith(`
265
+ `) ? 1 : 0);
266
+ return lines > config.maxLines ? [{ line: 1, message: `${lines} lines; split it below ${config.maxLines}` }] : [];
267
+ }
268
+ };
269
+ var isInlineFunction = (n) => {
270
+ if (!ts2.isJsxAttribute(n) || !n.initializer || !ts2.isJsxExpression(n.initializer))
271
+ return false;
272
+ let e = n.initializer.expression;
273
+ while (e && ts2.isParenthesizedExpression(e))
274
+ e = e.expression;
275
+ return e !== undefined && (ts2.isArrowFunction(e) || ts2.isFunctionExpression(e));
276
+ };
277
+ var noInlineHandler = {
278
+ id: "no-inline-handler",
279
+ description: "Pass a named function to a JSX prop (`onClick={signOut}`), not an inline one.",
280
+ check: ({ source }) => collect(source, (n) => isInlineFunction(n) ? "name this function above the JSX and pass it: `onClick={handleClick}`" : undefined)
281
+ };
282
+ var PASCAL = /^[A-Z][A-Za-z0-9]*$/;
283
+ var hasJsx = (node) => ts2.isJsxElement(node) || ts2.isJsxSelfClosingElement(node) || ts2.isJsxFragment(node) || ts2.forEachChild(node, hasJsx) === true;
284
+ var heldFunction = (e) => {
285
+ if (!e)
286
+ return;
287
+ if (ts2.isArrowFunction(e) || ts2.isFunctionExpression(e))
288
+ return e;
289
+ return ts2.isCallExpression(e) ? heldFunction(e.arguments.find(ts2.isFunctionLike)) : undefined;
290
+ };
291
+ var componentsOf = (source) => source.statements.flatMap((s) => {
292
+ if (ts2.isFunctionDeclaration(s) && s.name && PASCAL.test(s.name.text) && hasJsx(s))
293
+ return [{ name: s.name.text, node: s }];
294
+ if (!ts2.isVariableStatement(s))
295
+ return [];
296
+ return s.declarationList.declarations.flatMap((d) => {
297
+ const fn = heldFunction(d.initializer);
298
+ return ts2.isIdentifier(d.name) && PASCAL.test(d.name.text) && fn && hasJsx(fn) ? [{ name: d.name.text, node: d }] : [];
299
+ });
300
+ });
301
+ var oneComponentPerFile = {
302
+ id: "one-component-per-file",
303
+ description: "A .tsx file declares one component; each other one gets a file of its own.",
304
+ check: ({ file, source }) => {
305
+ if (!file.endsWith(".tsx"))
306
+ return [];
307
+ const [first, ...rest] = componentsOf(source);
308
+ return rest.map(({ name, node }) => ({
309
+ line: lineOf(source, node),
310
+ message: `${name} is a second component beside ${first?.name}; move it to its own .tsx file`
311
+ }));
312
+ }
313
+ };
314
+ var isClass = (n) => ts2.isClassDeclaration(n) || ts2.isClassExpression(n);
315
+ var insideFunction = (node) => {
316
+ for (let cur = node.parent;cur; cur = cur.parent)
317
+ if (ts2.isFunctionLike(cur))
318
+ return true;
319
+ return false;
320
+ };
321
+ var classPlacement = {
322
+ id: "class-placement",
323
+ description: "Classes (errors, services) sit at the top of a .ts module: never in React files or components/, never inside a function.",
324
+ check: ({ file, source }) => collect(source, (n) => {
325
+ if (!isClass(n))
326
+ return;
327
+ if (file.endsWith(".tsx") || file.includes("/components/"))
328
+ return "no classes beside React: components are functions; put errors in the feature's errors.ts and services in api/";
329
+ return insideFunction(n) ? "declare classes at the top of a module, not inside a function" : undefined;
330
+ })
331
+ };
332
+ var baseName = (e) => {
333
+ if (ts2.isCallExpression(e))
334
+ return baseName(e.expression);
335
+ if (ts2.isExpressionWithTypeArguments(e))
336
+ return baseName(e.expression);
337
+ return ts2.isPropertyAccessExpression(e) ? e.name.text : ts2.isIdentifier(e) ? e.text : "";
338
+ };
339
+ var extendsError = (n) => (n.heritageClauses ?? []).some((h) => h.token === ts2.SyntaxKind.ExtendsKeyword && h.types.some((t) => /Error(Class)?$/.test(baseName(t.expression))));
340
+ var errorPlacement = {
341
+ id: "error-placement",
342
+ description: "Error classes live in their feature's errors.ts (src/app/errors.ts for the kernel), beside their status.",
343
+ check: ({ file, source, config }) => {
344
+ const place = placeOf(config.featureLayout, file);
345
+ const home = place && place.kind !== "loose" && place.kind !== "lib" ? `${config.featureLayout.dir}/${place.folder}/errors.ts` : "src/app/errors.ts";
346
+ if (file === home)
347
+ return [];
348
+ return collect(source, (n) => isClass(n) && extendsError(n) ? `move ${n.name?.text ?? "this error"} to ${home}` : undefined);
349
+ }
350
+ };
351
+ var serverFnPlacement = {
352
+ id: "server-fn-placement",
353
+ description: "A feature's server functions live in its api/; pages only call them.",
354
+ check: ({ file, source, config }) => {
355
+ const place = placeOf(config.featureLayout, file);
356
+ if (!place || place.inner.startsWith("api/"))
357
+ return [];
358
+ return collect(source, (n) => calledName(n) === "createServerFn" ? `move this server function to ${config.featureLayout.dir}/${place.folder}/api/ and import it here` : undefined);
359
+ }
360
+ };
361
+ var importsMachine = (source) => source.statements.some((s) => ts2.isImportDeclaration(s) && ts2.isStringLiteral(s.moduleSpecifier) && /^(xstate|@xstate\/react)$|\.machine(\.ts)?$/.test(s.moduleSpecifier.text));
362
+ var isEventType = (n) => ts2.isTypeLiteralNode(n) && n.members.some((m) => ts2.isPropertySignature(m) && m.name.getText() === "type" && m.type !== undefined && ts2.isLiteralTypeNode(m.type) && ts2.isStringLiteral(m.type.literal));
363
+ var derivedMachineTypes = {
364
+ id: "derived-machine-types",
365
+ description: "A machine's events are declared once, in its *.machine.ts; code beside it derives them instead of writing them again.",
366
+ check: ({ file, source }) => {
367
+ if (file.endsWith(".machine.ts") || !importsMachine(source))
368
+ return [];
369
+ return collect(source, (n) => isEventType(n) ? 'derive this event type from the machine: EventFrom<typeof machine>, or ActorRefFrom<typeof machine>["send"] for send' : undefined);
370
+ }
371
+ };
372
+
373
+ // src/rules/api-paths.ts
374
+ var API_PATH = /^\/api\/[\w\-./$]+$/;
375
+ var declaresRoute = (n) => ts3.isCallExpression(n.parent) && ts3.isIdentifier(n.parent.expression) && n.parent.expression.text === "createFileRoute";
376
+ var pathsIn = (source) => {
377
+ const out = [];
378
+ const visit = (n) => {
379
+ if (ts3.isStringLiteralLike(n) && API_PATH.test(n.text) && !declaresRoute(n))
380
+ out.push({ path: n.text, line: lineOf(source, n) });
381
+ ts3.forEachChild(n, visit);
382
+ };
383
+ visit(source);
384
+ return out;
385
+ };
386
+ var noRepeatedApiPath = {
387
+ id: "no-repeated-api-path",
388
+ description: "Write each /api/ path once, in its feature's constants.ts; a copy elsewhere breaks silently on a rename.",
389
+ checkProject: ({ root, config, allFiles }) => {
390
+ const allowed = config.allow["no-repeated-api-path"] ?? [];
391
+ const files = [...allFiles].filter((f) => matchesAny(f, config.include) && !matchesAny(f, config.exclude)).filter((f) => !TEST_FILE.test(f) && !matchesAny(f, allowed)).sort(byCodeUnit);
392
+ const seen = new Map;
393
+ for (const file of files) {
394
+ const text = readFileSync2(join3(root, file), "utf8");
395
+ const source = ts3.createSourceFile(file, text, ts3.ScriptTarget.Latest, true);
396
+ for (const { path, line } of pathsIn(source))
397
+ seen.set(path, [...seen.get(path) ?? [], { file, line }]);
398
+ }
399
+ return [...seen].flatMap(([path, at]) => {
400
+ const where = new Set(at.map((a) => a.file));
401
+ if (where.size < 2)
402
+ return [];
403
+ return at.map(({ file, line }) => ({
404
+ file,
405
+ line,
406
+ message: `"${path}" is also in ${[...where].filter((f) => f !== file).join(", ")}; export it once from the feature's constants.ts`
407
+ }));
408
+ });
409
+ }
410
+ };
411
+
412
+ // src/rules/comments.ts
413
+ import { readFileSync as readFileSync3 } from "node:fs";
414
+ import { join as join4 } from "node:path";
415
+ import ts4 from "@typescript/typescript6";
416
+ var commentsOf = (source, merge) => {
417
+ const text = source.text;
418
+ const ranges = new Map;
419
+ const add = (found) => {
420
+ for (const r of found ?? [])
421
+ ranges.set(r.pos, r);
422
+ };
423
+ const visit = (n) => {
424
+ add(ts4.getLeadingCommentRanges(text, n.getFullStart()));
425
+ add(ts4.getTrailingCommentRanges(text, n.end));
426
+ for (const child of n.getChildren(source))
427
+ visit(child);
428
+ };
429
+ visit(source);
430
+ const out = [];
431
+ for (const r of [...ranges.values()].sort((a, b) => a.pos - b.pos)) {
432
+ const raw = text.slice(r.pos, r.end);
433
+ const line = source.getLineAndCharacterOfPosition(r.pos).line + 1;
434
+ const endLine = source.getLineAndCharacterOfPosition(r.end).line + 1;
435
+ const single = r.kind === ts4.SyntaxKind.SingleLineCommentTrivia;
436
+ const body = single ? raw.slice(2) : raw.slice(2, -2).split(`
437
+ `).map((l) => l.replace(/^\s*\*(?!\*)/, "")).join(`
438
+ `);
439
+ const last = out.at(-1);
440
+ if (merge && single && last?.single && line === last.endLine + 1) {
441
+ last.text += `
442
+ ${body}`;
443
+ last.endLine = endLine;
444
+ } else
445
+ out.push({ line, endLine, single, text: body });
446
+ }
447
+ return out;
448
+ };
449
+ var DIRECTIVE = /^\s*(\/\s*<|biome-ignore|@ts-|eslint-)/;
450
+ var MARKER = /\b(TODO|FIXME|XXX|HACK)\b/;
451
+ var DIVIDER = /([-=*#~_])\1{3,}/;
452
+ var PROSE = /`|^\s*(e\.g\.|i\.e\.|[A-Za-z]+:\s)/;
453
+ var CODE_HINT = /[;{}=]|\)[ \t]*$|^[ \t]*(import|export|const|let|return|await|if|for)\b/m;
454
+ var parses = (code) => ts4.transpileModule(code, {
455
+ reportDiagnostics: true,
456
+ fileName: "comment.tsx",
457
+ compilerOptions: { jsx: ts4.JsxEmit.Preserve }
458
+ }).diagnostics?.length === 0;
459
+ var lineProblem = (text) => {
460
+ if (DIRECTIVE.test(text))
461
+ return;
462
+ if (!text.trim())
463
+ return "delete the empty comment";
464
+ if (MARKER.test(text))
465
+ return "put open work in the backlog or an issue; for a known limit write `shortcut: <limit>, <when to fix>`";
466
+ if (DIVIDER.test(text))
467
+ return "drop the divider; split the file if it needs sections";
468
+ return;
469
+ };
470
+ var isCode = (text) => !DIRECTIVE.test(text) && !PROSE.test(text) && CODE_HINT.test(text) && parses(text);
471
+ var noUselessComment = {
472
+ id: "no-useless-comment",
473
+ description: "No commented-out code, TODO markers, dividers or empty comments.",
474
+ check: ({ source }) => {
475
+ const code = commentsOf(source, true).filter((c) => isCode(c.text)).map((c) => ({ line: c.line, message: "delete the commented-out code; git keeps it" }));
476
+ const lines = commentsOf(source, false).flatMap((c) => {
477
+ const message = lineProblem(c.text);
478
+ return message ? [{ line: c.line, message }] : [];
479
+ });
480
+ return [...code, ...lines].sort((a, b) => a.line - b.line);
481
+ }
482
+ };
483
+ var ALLOW = "software-factory-lint allow comments";
484
+ var lineOf2 = (source, pos) => source.getLineAndCharacterOfPosition(pos).line + 1;
485
+ var noComment = {
486
+ id: "no-comment",
487
+ description: `No comments, unless the file opens with \`// ${ALLOW}\`.`,
488
+ check: ({ source }) => {
489
+ const prose = commentsOf(source, false).filter((c) => !DIRECTIVE.test(c.text));
490
+ const first = source.statements[0];
491
+ const codeStarts = first ? lineOf2(source, first.getStart()) : Number.POSITIVE_INFINITY;
492
+ const opener = prose[0];
493
+ if (opener?.text.trim() === ALLOW && opener.line < codeStarts)
494
+ return prose.length > 1 ? [] : [{ line: opener.line, message: "delete this line: the file has no comments to allow" }];
495
+ const message = `delete the comment, or open the file with \`// ${ALLOW}\` to keep its comments`;
496
+ return prose.map((c) => ({ line: c.line, message }));
497
+ }
498
+ };
499
+ var MIN_WORDS = 5;
500
+ var noDuplicateComment = {
501
+ id: "no-duplicate-comment",
502
+ description: "Say a thing once: the same comment in two places goes stale in one of them.",
503
+ checkProject: ({ root, config, allFiles }) => {
504
+ const first = new Map;
505
+ const files = [...allFiles].filter((f) => matchesAny(f, config.include) && !matchesAny(f, config.exclude)).sort(byCodeUnit);
506
+ return files.flatMap((file) => {
507
+ const text = readFileSync3(join4(root, file), "utf8");
508
+ const source = ts4.createSourceFile(file, text, ts4.ScriptTarget.Latest, true);
509
+ return commentsOf(source, true).flatMap((c) => {
510
+ const key = c.text.replace(/\s+/g, " ").trim().toLowerCase();
511
+ if (DIRECTIVE.test(c.text) || key.split(" ").length < MIN_WORDS)
512
+ return [];
513
+ const seen = first.get(key);
514
+ if (!seen)
515
+ first.set(key, `${file}:${c.line}`);
516
+ return seen ? [{ file, line: c.line, message: `same comment as ${seen}; keep one` }] : [];
517
+ });
518
+ });
519
+ }
520
+ };
521
+
522
+ // src/rules/feature-layout.ts
523
+ import { basename } from "node:path";
524
+ var PURPOSE = {
525
+ api: "server functions and services",
526
+ routes: "file routes",
527
+ components: "React, with UI machines beside them",
528
+ machines: "lifecycle machines",
529
+ lib: "pure helpers",
530
+ e2e: "Playwright specs"
531
+ };
532
+ var folderList = (layout) => layout.folders.map((f) => PURPOSE[f] ? `${f}/ (${PURPOSE[f]})` : `${f}/`).join(", ");
533
+ var allowed = (layout) => `A feature holds only the folders ${folderList(layout)} and the top-level files ${layout.files.join(", ")}, each with an optional sibling *.test.ts.`;
534
+ var coreRule = (layout) => `Core holds shared modules of one kind: components only (${layout.core.componentFolders.map((f) => `${f}/`).join(", ")}), or services and helpers only (no components/, server routes only under routes/${layout.core.serverRoutes}/). A module with both, or with a page, is a feature; move it out of core to ${layout.dir}/<name>.`;
535
+ var isListedFile = (files, name) => {
536
+ if (files.includes(name))
537
+ return true;
538
+ const tested = /^(.+)\.test\.ts$/.exec(name)?.[1];
539
+ return tested !== undefined && files.includes(`${tested}.ts`);
540
+ };
541
+ var placementProblem = (layout, folder, name) => {
542
+ for (const [pattern, folders] of Object.entries(layout.placement)) {
543
+ if (globToRegExp(pattern).test(name) && (folder === undefined || !folders.includes(folder))) {
544
+ return `${pattern} files go only in ${folders.map((f) => `${f}/`).join(" or ")}.`;
545
+ }
546
+ }
547
+ return;
548
+ };
549
+ var misplaced = (layout, inner) => {
550
+ const [first = "", ...rest] = inner;
551
+ const folder = rest.length ? first : undefined;
552
+ if (folder !== undefined && !layout.folders.includes(folder)) {
553
+ return `"${folder}/" is not a feature folder. ${allowed(layout)}`;
554
+ }
555
+ if (folder === undefined && !isListedFile(layout.files, first)) {
556
+ return `"${first}" may not sit at the top of a feature. ${allowed(layout)}`;
557
+ }
558
+ return placementProblem(layout, folder, basename(inner.join("/")));
559
+ };
560
+ var componentsProblem = (layout, inner) => {
561
+ const { componentFolders, componentFiles } = layout.core;
562
+ const [first = "", ...rest] = inner;
563
+ const folder = rest.length ? first : undefined;
564
+ const name = basename(inner.join("/"));
565
+ if (folder !== undefined && !componentFolders.includes(folder)) {
566
+ return `"${folder}/" next to components/ mixes kinds. ${coreRule(layout)}`;
567
+ }
568
+ if (folder === undefined && !isListedFile(componentFiles, first)) {
569
+ return `"${first}" next to components/ mixes kinds; a components module has only ${componentFiles.join(", ")} at its top. ${coreRule(layout)}`;
570
+ }
571
+ if (name.endsWith(".machine.ts")) {
572
+ return `a machine beside shared components gives them logic of their own. ${coreRule(layout)}`;
573
+ }
574
+ return;
575
+ };
576
+ var servicesProblem = (layout, inner) => {
577
+ const { serviceFolders, serverRoutes } = layout.core;
578
+ const [first = "", second, ...rest] = inner;
579
+ const folder = second === undefined ? undefined : first;
580
+ if (folder !== undefined && !serviceFolders.includes(folder)) {
581
+ return `"${folder}/" has no place in a core module. ${coreRule(layout)}`;
582
+ }
583
+ if (folder === "routes" && !(second === serverRoutes && rest.length)) {
584
+ return `"routes/${[second, ...rest].join("/")}" is a page; a core module serves only server routes under routes/${serverRoutes}/. ${coreRule(layout)}`;
585
+ }
586
+ if (inner.join("/").endsWith(".tsx")) {
587
+ return `"${inner.join("/")}" is React in a services module. ${coreRule(layout)}`;
588
+ }
589
+ return misplaced(layout, inner);
590
+ };
591
+ var coreProblem = (layout, files, inner) => {
592
+ const isComponents = files.some((f) => f.startsWith("components/"));
593
+ const parts = inner.split("/");
594
+ return isComponents ? componentsProblem(layout, parts) : servicesProblem(layout, parts);
595
+ };
596
+ var libProblem = (layout, inner) => {
597
+ if (!inner.includes("/") && /\.ts$/.test(inner) && !inner.endsWith(".d.ts"))
598
+ return;
599
+ return `${layout.dir}/${layout.core.dir}/${layout.core.lib}/ holds flat .ts helpers, each with a sibling test: no folders, no React, no feature.json.`;
600
+ };
601
+ var byFolder = (layout, allFiles) => {
602
+ const out = new Map;
603
+ for (const file of allFiles) {
604
+ const place = placeOf(layout, file);
605
+ if (!place)
606
+ continue;
607
+ const key = place.kind === "loose" ? `loose:${place.folder}` : place.folder;
608
+ const entry = out.get(key) ?? { kind: place.kind, files: [] };
609
+ entry.files.push(place.inner);
610
+ out.set(key, entry);
611
+ }
612
+ return out;
613
+ };
614
+ var missing = (layout, folder, has) => layout.required.filter((required) => !has.includes(required)).map((required) => {
615
+ const fix = required === "TIMELINE.md" ? " `software-factory-blocks sync` writes a fresh one." : "";
616
+ const message = `missing; every feature has ${layout.required.join(" and ")}.${fix}`;
617
+ return { file: `${folder}/${required}`, line: 1, message };
618
+ });
619
+ var folderFindings = (layout, key, kind, files) => {
620
+ if (kind === "loose") {
621
+ const where = key.slice("loose:".length);
622
+ const at = where ? `${layout.dir}/${where}` : layout.dir;
623
+ const message = where ? "core modules are folders; move this into one." : "features are folders; move this into one.";
624
+ return files.map((f) => ({ file: `${at}/${f}`, line: 1, message }));
625
+ }
626
+ const folder = `${layout.dir}/${key}`;
627
+ const check = (inner) => {
628
+ if (kind === "lib")
629
+ return libProblem(layout, inner);
630
+ if (kind === "core")
631
+ return coreProblem(layout, files, inner);
632
+ return misplaced(layout, inner.split("/"));
633
+ };
634
+ const stray = files.flatMap((f) => {
635
+ const message = check(f);
636
+ return message ? [{ file: `${folder}/${f}`, line: 1, message }] : [];
637
+ });
638
+ return kind === "lib" ? stray : [...stray, ...missing(layout, folder, files)];
639
+ };
640
+ var featureLayout = {
641
+ id: "feature-layout",
642
+ description: "Every path inside a feature uses the fixed vocabulary; each core module is of one kind: components only, or services and helpers only.",
643
+ checkProject: ({ config, allFiles }) => {
644
+ const layout = config.featureLayout;
645
+ return [...byFolder(layout, allFiles)].flatMap(([key, { kind, files }]) => folderFindings(layout, key, kind, files));
646
+ }
647
+ };
648
+
649
+ // src/rules/rules-file.ts
650
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "node:fs";
651
+ import { join as join5 } from "node:path";
652
+ var FILE = "CLAUDE.md";
653
+ var TOKEN = /`([^`\n]+)`/g;
654
+ var SCRIPT = /^bun run ([\w:-]+)$/;
655
+ var RULE = /rules? $/;
656
+ var PATH = /^[^\s<*{/.][^\s<*{/]*\/[^\s<*{]*$/;
657
+ var untrue = (root, token, before, scripts, ruleIds) => {
658
+ const script = SCRIPT.exec(token)?.[1];
659
+ if (script) {
660
+ return scripts && !(script in scripts) ? `\`${token}\`: package.json has no script "${script}"` : undefined;
661
+ }
662
+ if (RULE.test(before)) {
663
+ return ruleIds.has(token) ? undefined : `rule \`${token}\` is not a software-factory-lint rule`;
664
+ }
665
+ const top = token.split("/")[0] ?? "";
666
+ return PATH.test(token) && existsSync2(join5(root, top)) && !existsSync2(join5(root, token)) ? `\`${token}\` does not exist` : undefined;
667
+ };
668
+ var rulesFile = {
669
+ id: "rules-file",
670
+ description: `Keep ${FILE} short and true: under the line limit, naming only paths, scripts and rules that exist.`,
671
+ checkProject: ({ root, config, allFiles, ruleIds }) => {
672
+ if (!allFiles.has(FILE))
673
+ return [];
674
+ const text = readFileSync4(join5(root, FILE), "utf8").trimEnd();
675
+ const count = text.split(`
676
+ `).length;
677
+ const found = (line, message) => ({ file: FILE, line, message });
678
+ const scripts = allFiles.has("package.json") ? JSON.parse(readFileSync4(join5(root, "package.json"), "utf8")).scripts : undefined;
679
+ const limit = count > config.maxRulesLines ? [
680
+ found(config.maxRulesLines + 1, `${count} lines; keep it to ${config.maxRulesLines} by moving detail into the check that enforces it`)
681
+ ] : [];
682
+ const wrong = [...text.matchAll(TOKEN)].flatMap((m) => {
683
+ const message = untrue(root, m[1] ?? "", text.slice(Math.max(0, m.index - 6), m.index), scripts, ruleIds);
684
+ return message ? [found(text.slice(0, m.index).split(`
685
+ `).length, message)] : [];
686
+ });
687
+ return [...limit, ...wrong];
688
+ }
689
+ };
690
+
691
+ // src/rules/shared-lib.ts
692
+ import ts5 from "@typescript/typescript6";
693
+ var REACT = /^(react|react-dom)(\/|$)|^@tanstack\/react-|\.tsx$/;
694
+ var SERVICE = /^(Context\.(Service|Tag|Reference)|Layer\.\w+)$/;
695
+ var offence = (n) => {
696
+ if (ts5.isImportDeclaration(n) && ts5.isStringLiteral(n.moduleSpecifier)) {
697
+ return REACT.test(n.moduleSpecifier.text) ? `imports React (${n.moduleSpecifier.text})` : undefined;
698
+ }
699
+ if (ts5.isPropertyAccessExpression(n) && SERVICE.test(n.getText())) {
700
+ return `uses ${n.getText()}`;
701
+ }
702
+ return;
703
+ };
704
+ var sharedLib = {
705
+ id: "shared-lib",
706
+ description: "core/lib holds pure helpers: plain functions and Effect functions, no services, layers or React.",
707
+ check: ({ file, source, config }) => {
708
+ if (placeOf(config.featureLayout, file)?.kind !== "lib")
709
+ return [];
710
+ const out = [];
711
+ const visit = (n) => {
712
+ const what = offence(n);
713
+ if (what) {
714
+ out.push({
715
+ line: source.getLineAndCharacterOfPosition(n.getStart(source)).line + 1,
716
+ message: `${what}; core/lib holds pure helpers (Effect functions are fine, services, layers and React are not). Put this in a core module.`
717
+ });
718
+ return;
719
+ }
720
+ ts5.forEachChild(n, visit);
721
+ };
722
+ visit(source);
723
+ return out;
724
+ }
725
+ };
726
+
727
+ // src/rules/test-map.ts
728
+ import { basename as basename2, dirname } from "node:path";
729
+ var fileStem = (file) => basename2(file).replace(/\.tsx?$/, "");
730
+ var nameStem = (file) => fileStem(file).replace(/\.machine$/, "");
731
+ var routeStem = (file) => (file.split("/routes/")[1] ?? "").replace(/\.tsx?$/, "").split("/").map((segment) => segment.replace(/^\$/, "") || "splat").join(".");
732
+ var testMap = {
733
+ id: "test-map",
734
+ description: "Every source file has its proof: the tests the test map requires for it.",
735
+ check: ({ file, config, allFiles }) => {
736
+ const exempt = matchesAny(file, config.testExempt);
737
+ const required = config.testMap.filter((e) => globToRegExp(e.files).test(file) && (!exempt || e.always)).flatMap((e) => e.requires);
738
+ const missing = [...new Set(required)].map((pattern) => pattern.replaceAll("{dir}", dirname(file)).replaceAll("{file}", fileStem(file)).replaceAll("{name}", nameStem(file)).replaceAll("{route}", () => routeStem(file)).replaceAll("{feature}", placeOf(config.featureLayout, file)?.folder ?? "")).filter((pattern) => {
739
+ const re = globToRegExp(pattern);
740
+ return ![...allFiles].some((f) => re.test(f));
741
+ });
742
+ return missing.map((m) => ({ line: 1, message: `missing its test: ${m}` }));
743
+ }
744
+ };
745
+
746
+ // src/rules/test-rules.ts
747
+ import ts6 from "@typescript/typescript6";
748
+ var isLiteral = (e) => {
749
+ if (ts6.isStringLiteralLike(e) || ts6.isNumericLiteral(e) || ts6.isRegularExpressionLiteral(e) || e.kind === ts6.SyntaxKind.TrueKeyword || e.kind === ts6.SyntaxKind.FalseKeyword || e.kind === ts6.SyntaxKind.NullKeyword)
750
+ return true;
751
+ if (ts6.isPrefixUnaryExpression(e))
752
+ return isLiteral(e.operand);
753
+ if (ts6.isArrayLiteralExpression(e))
754
+ return e.elements.every(isLiteral);
755
+ if (ts6.isObjectLiteralExpression(e))
756
+ return e.properties.every((p) => ts6.isPropertyAssignment(p) && isLiteral(p.initializer));
757
+ return false;
758
+ };
759
+ var importedNames = (source) => {
760
+ const names = new Set;
761
+ for (const s of source.statements) {
762
+ const clause = ts6.isImportDeclaration(s) ? s.importClause : undefined;
763
+ if (clause?.name)
764
+ names.add(clause.name.text);
765
+ const bindings = clause?.namedBindings;
766
+ if (bindings && ts6.isNamedImports(bindings))
767
+ for (const el of bindings.elements)
768
+ names.add(el.name.text);
769
+ if (bindings && ts6.isNamespaceImport(bindings))
770
+ names.add(bindings.name.text);
771
+ }
772
+ return names;
773
+ };
774
+ var rootName = (e) => {
775
+ if (ts6.isIdentifier(e))
776
+ return e.text;
777
+ if (ts6.isPropertyAccessExpression(e) || ts6.isElementAccessExpression(e))
778
+ return rootName(e.expression);
779
+ return;
780
+ };
781
+ var loopOverConstants = (node, name, isConstant) => {
782
+ for (let cur = node.parent;cur; cur = cur.parent) {
783
+ if (!ts6.isForOfStatement(cur) || !ts6.isVariableDeclarationList(cur.initializer))
784
+ continue;
785
+ const declared = cur.initializer.declarations.some((d) => ts6.isIdentifier(d.name) && d.name.text === name);
786
+ if (declared)
787
+ return ts6.isArrayLiteralExpression(cur.expression) && cur.expression.elements.every(isConstant);
788
+ }
789
+ return false;
790
+ };
791
+ var constantIn = (source) => {
792
+ const imported = importedNames(source);
793
+ const isConstant = (e) => {
794
+ if (isLiteral(e))
795
+ return true;
796
+ const name = rootName(e);
797
+ if (name === undefined || ts6.isCallExpression(e))
798
+ return false;
799
+ return imported.has(name) || loopOverConstants(e, name, isConstant);
800
+ };
801
+ return isConstant;
802
+ };
803
+ var matcherOf = (expectCall) => {
804
+ let cur = expectCall;
805
+ while (ts6.isPropertyAccessExpression(cur.parent))
806
+ cur = cur.parent;
807
+ return ts6.isCallExpression(cur.parent) && cur.parent.expression === cur ? cur.parent : undefined;
808
+ };
809
+ var callsIn = (body) => {
810
+ const out = [];
811
+ const visit = (n) => {
812
+ if (ts6.isCallExpression(n))
813
+ out.push(n);
814
+ ts6.forEachChild(n, visit);
815
+ };
816
+ visit(body);
817
+ return out;
818
+ };
819
+ var isExpect = (n) => ts6.isIdentifier(n.expression) && n.expression.text === "expect";
820
+ var TEST_CALL = /^(it|test)$/;
821
+ var noRestatingTest = {
822
+ id: "no-restating-test",
823
+ description: "A test runs code. One that calls nothing and only checks constants against literals restates the source.",
824
+ check: ({ file, source }) => {
825
+ if (!TEST_FILE.test(file))
826
+ return [];
827
+ const isConstant = constantIn(source);
828
+ const restates = (e) => {
829
+ const subject = e.arguments[0];
830
+ const matcher = matcherOf(e);
831
+ return subject !== undefined && matcher !== undefined && isConstant(subject) && matcher.arguments.every(isLiteral);
832
+ };
833
+ return collect(source, (n) => {
834
+ if (!ts6.isCallExpression(n) || !ts6.isIdentifier(n.expression))
835
+ return;
836
+ const body = n.arguments[1];
837
+ if (!TEST_CALL.test(n.expression.text) || !body)
838
+ return;
839
+ const calls = callsIn(body);
840
+ const expects = calls.filter(isExpect);
841
+ const asserting = new Set(expects.flatMap((e) => [e, matcherOf(e)]));
842
+ if (calls.some((c) => !asserting.has(c)) || !expects.length)
843
+ return;
844
+ return expects.every(restates) ? "this test only checks constants against literals; test the code that uses them, or list the file in testExempt" : undefined;
845
+ });
846
+ }
847
+ };
848
+
849
+ // src/lint.ts
850
+ var rules = [
851
+ noThrow,
852
+ noTryCatch,
853
+ noRunEffect,
854
+ noProcessEnv,
855
+ externalCallSpan,
856
+ noNestedYield,
857
+ noInlineHandler,
858
+ oneComponentPerFile,
859
+ classPlacement,
860
+ errorPlacement,
861
+ serverFnPlacement,
862
+ derivedMachineTypes,
863
+ noUselessComment,
864
+ noComment,
865
+ fileSize,
866
+ testMap,
867
+ sharedLib,
868
+ noRestatingTest
869
+ ];
870
+ var projectRules = [
871
+ featureLayout,
872
+ rulesFile,
873
+ noDuplicateComment,
874
+ noRepeatedApiPath
875
+ ];
876
+ var SOURCE_ONLY = new Set([
877
+ "no-throw",
878
+ "no-try-catch",
879
+ "no-run-effect",
880
+ "external-call-span",
881
+ "no-inline-handler",
882
+ "one-component-per-file",
883
+ "class-placement",
884
+ "error-placement",
885
+ "derived-machine-types"
886
+ ]);
887
+ var fileFindings = (root, file, config, allFiles) => {
888
+ const text = readFileSync5(join6(root, file), "utf8");
889
+ const source = ts7.createSourceFile(file, text, ts7.ScriptTarget.Latest, true);
890
+ return rules.filter((rule) => !(TEST_FILE.test(file) && SOURCE_ONLY.has(rule.id))).filter((rule) => !matchesAny(file, config.allow[rule.id] ?? [])).flatMap((rule) => rule.check({ root, file, source, config, allFiles }).map((f) => ({ rule: rule.id, file, ...f })));
891
+ };
892
+ var projectFindings = (root, config, allFiles) => {
893
+ const ruleIds = new Set([...rules, ...projectRules].map((r) => r.id));
894
+ return projectRules.flatMap((rule) => rule.checkProject({ root, config, allFiles, ruleIds }).filter((f) => !matchesAny(f.file, config.allow[rule.id] ?? [])).map((f) => ({ rule: rule.id, ...f })));
895
+ };
896
+ var lint = (root, config = loadConfig(root)) => {
897
+ const allFiles = new Set(walk(root, root));
898
+ const targets = [...allFiles].filter((f) => matchesAny(f, config.include) && !matchesAny(f, config.exclude));
899
+ const message = `no file matches "include" (${config.include.join(", ")})`;
900
+ const findings = [
901
+ ...targets.length ? [] : [{ rule: "no-files", file: "software-factory-lint.json", line: 1, message }],
902
+ ...targets.sort(byCodeUnit).flatMap((file) => fileFindings(root, file, config, allFiles)),
903
+ ...projectFindings(root, config, allFiles)
904
+ ];
905
+ return findings.sort((a, b) => byCodeUnit(a.file, b.file) || a.line - b.line);
906
+ };
907
+
908
+ // src/timeline-git.ts
909
+ import { spawnSync } from "node:child_process";
910
+ import { existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
911
+ import { join as join7 } from "node:path";
912
+
913
+ // src/timeline-doc.ts
914
+ var TIMELINE_FILE = "TIMELINE.md";
915
+ var GENERATED_START = "<!-- generated:start -->";
916
+ var GENERATED_END = "<!-- generated:end -->";
917
+ var MACHINES_START = "<!-- machines:start -->";
918
+ var MACHINES_END = "<!-- machines:end -->";
919
+ var span = (text, start, end) => {
920
+ const from = text.indexOf(start);
921
+ const to = from < 0 ? -1 : text.indexOf(end, from);
922
+ return to < 0 ? undefined : { from, to: to + end.length };
923
+ };
924
+ var handWritten = (text) => [
925
+ [GENERATED_START, GENERATED_END],
926
+ [MACHINES_START, MACHINES_END]
927
+ ].reduce((acc, [start = "", end = ""]) => {
928
+ const s = span(acc, start, end);
929
+ return s ? acc.slice(0, s.from) + acc.slice(s.to) : acc;
930
+ }, text);
931
+ var withBlock = (text, start, end, block, anchor) => {
932
+ const s = span(text, start, end);
933
+ if (s) {
934
+ if (block)
935
+ return text.slice(0, s.from) + block + text.slice(s.to);
936
+ const from = text.slice(s.from - 2, s.from) === `
937
+
938
+ ` ? s.from - 2 : s.from;
939
+ return text.slice(0, from) + text.slice(s.to);
940
+ }
941
+ if (!block)
942
+ return text;
943
+ const at = text.indexOf(anchor);
944
+ if (at < 0)
945
+ return `${text.trimEnd()}
946
+
947
+ ${block}
948
+ `;
949
+ const after = at + anchor.length;
950
+ return `${text.slice(0, after)}
951
+
952
+ ${block}${text.slice(after)}`;
953
+ };
954
+
955
+ // src/timeline.ts
956
+ var ENTRY = /^- \d{4}-\d{2}-\d{2}\b/;
957
+ var entries = (text) => handWritten(text ?? "").split(`
958
+ `).map((line) => line.trimEnd()).filter((line) => ENTRY.test(line));
959
+ var newEntries = (before, after) => {
960
+ const old = new Set(entries(before));
961
+ return entries(after).filter((line) => !old.has(line));
962
+ };
963
+ var touchedFeatures = (featuresDir, changed, coreDir = defaultFeatureLayout.core.dir) => {
964
+ const out = new Map;
965
+ const layout = {
966
+ ...defaultFeatureLayout,
967
+ dir: featuresDir,
968
+ core: { ...defaultFeatureLayout.core, dir: coreDir }
969
+ };
970
+ for (const path of [...new Set(changed)].sort(byCodeUnit)) {
971
+ const place = placeOf(layout, path);
972
+ if (!place || place.kind === "loose" || place.kind === "lib")
973
+ continue;
974
+ if (place.inner === TIMELINE_FILE)
975
+ continue;
976
+ out.set(place.folder, [...out.get(place.folder) ?? [], place.inner]);
977
+ }
978
+ return out;
979
+ };
980
+ var timelineProblems = (featuresDir, changed, timelines, coreDir = defaultFeatureLayout.core.dir) => [...touchedFeatures(featuresDir, changed, coreDir)].flatMap(([feature, files]) => {
981
+ const timeline = timelines.get(feature);
982
+ if (timeline?.after === undefined)
983
+ return [];
984
+ if (newEntries(timeline.before, timeline.after).length)
985
+ return [];
986
+ const path = `${featuresDir}/${feature}/${TIMELINE_FILE}`;
987
+ const shown = files.length > 3 ? [...files.slice(0, 3), "..."] : files;
988
+ return [
989
+ {
990
+ feature,
991
+ message: `${feature} changed (${shown.join(", ")}) with no new line in ${path}. Add "- YYYY-MM-DD — what and why" under ## Decisions or ## History.`
992
+ }
993
+ ];
994
+ });
995
+
996
+ // src/timeline-git.ts
997
+ var git = (root, args) => {
998
+ const out = spawnSync("git", args, { cwd: root, encoding: "utf8" });
999
+ return out.status === 0 ? out.stdout : undefined;
1000
+ };
1001
+ var verified = (root, ref) => git(root, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]) !== undefined;
1002
+ var paths = (text) => (text ?? "").split("\x00").filter(Boolean);
1003
+ var skipped = (why) => ({
1004
+ code: 0,
1005
+ lines: [`timeline: ${why}; skipped.`]
1006
+ });
1007
+ var runTimeline = (root, options = {}) => {
1008
+ if (options.skip)
1009
+ return skipped("asked to skip (--skip or TIMELINE_SKIP=1)");
1010
+ if (git(root, ["rev-parse", "--is-inside-work-tree"]) === undefined) {
1011
+ return skipped("not a git repository");
1012
+ }
1013
+ const candidates = options.base ? [options.base] : ["origin/staging", "origin/main", "HEAD~1"];
1014
+ const base = candidates.find((ref) => verified(root, ref));
1015
+ if (!base && options.base) {
1016
+ return { code: 1, lines: [`timeline: base ref "${options.base}" not found; fetch it first.`] };
1017
+ }
1018
+ if (!base)
1019
+ return skipped(`no base ref (${candidates.join(", ")})`);
1020
+ const from = git(root, ["merge-base", base, "HEAD"])?.trim() || base;
1021
+ const changed = [
1022
+ ...paths(git(root, ["diff", "--name-only", "-z", "--no-renames", "--relative", from])),
1023
+ ...paths(git(root, ["ls-files", "-z", "--others", "--exclude-standard"]))
1024
+ ];
1025
+ const { dir, core } = loadConfig(root).featureLayout;
1026
+ const timelines = new Map;
1027
+ for (const feature of touchedFeatures(dir, changed, core.dir).keys()) {
1028
+ const path = `${dir}/${feature}/${TIMELINE_FILE}`;
1029
+ const full = join7(root, path);
1030
+ timelines.set(feature, {
1031
+ before: git(root, ["show", `${from}:./${path}`]),
1032
+ after: existsSync3(full) ? readFileSync6(full, "utf8") : undefined
1033
+ });
1034
+ }
1035
+ const problems = timelineProblems(dir, changed, timelines, core.dir);
1036
+ if (!problems.length) {
1037
+ return { code: 0, lines: [`timeline: every changed feature has a new line (base ${base}).`] };
1038
+ }
1039
+ return {
1040
+ code: 1,
1041
+ lines: [
1042
+ ...problems.map((p) => p.message),
1043
+ `
1044
+ ${problems.length} feature(s) changed without a timeline line. For a trivial change, set TIMELINE_SKIP=1 or add the no-timeline label to the pull request.`
1045
+ ]
1046
+ };
1047
+ };
1048
+
1049
+ // src/bin.ts
1050
+ var args = process.argv.slice(2);
1051
+ var usage = `software-factory-lint [command]
1052
+
1053
+ (none) run the house rules on this project
1054
+ --rules list the rules
1055
+ timeline [--base <ref>] fail when a feature changed since <ref> (default origin/staging,
1056
+ [--skip] else origin/main, else HEAD~1) without a new line in its
1057
+ TIMELINE.md; --skip or TIMELINE_SKIP=1 skips it`;
1058
+ var runLint = () => {
1059
+ const findings = lint(process.cwd());
1060
+ for (const f of findings)
1061
+ console.error(`${f.file}:${f.line} ${f.rule} ${f.message}`);
1062
+ if (!findings.length) {
1063
+ console.log("software-factory-lint: no problems.");
1064
+ return 0;
1065
+ }
1066
+ console.error(`
1067
+ ${findings.length} problem(s). Allow a file only in software-factory-lint.json "allow", with a reason in review.`);
1068
+ return 1;
1069
+ };
1070
+ var timeline = () => {
1071
+ const at = args.indexOf("--base");
1072
+ const base = at >= 0 ? args[at + 1] : undefined;
1073
+ const skip = args.includes("--skip") || ["1", "true"].includes(process.env.TIMELINE_SKIP ?? "");
1074
+ const result = runTimeline(process.cwd(), { base, skip });
1075
+ for (const line of result.lines)
1076
+ (result.code ? console.error : console.log)(line);
1077
+ return result.code;
1078
+ };
1079
+ var main = () => {
1080
+ if (args.includes("--help") || args.includes("-h")) {
1081
+ console.log(usage);
1082
+ return 0;
1083
+ }
1084
+ if (args.includes("--rules")) {
1085
+ for (const rule of [...rules, ...projectRules]) {
1086
+ console.log(`${rule.id.padEnd(20)} ${rule.description}`);
1087
+ }
1088
+ return 0;
1089
+ }
1090
+ if (args[0] === "timeline")
1091
+ return timeline();
1092
+ if (args[0]) {
1093
+ console.error(`Unknown command "${args[0]}".
1094
+
1095
+ ${usage}`);
1096
+ return 1;
1097
+ }
1098
+ return runLint();
1099
+ };
1100
+ process.exitCode = main();