@cerios/sparta-lint-rules 0.0.1 → 0.0.2

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.
@@ -22,17 +22,57 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
22
22
  let node_path = require("node:path");
23
23
  node_path = __toESM(node_path);
24
24
  let node_fs = require("node:fs");
25
+ let node_module = require("node:module");
25
26
  let oxc_parser = require("oxc-parser");
26
27
  // src/utils/ast.ts
27
28
  const isIdentifier = (node, name) => node?.type === "Identifier" && node.name === name;
28
29
  /** The value of a string literal node, or `undefined` for any other node. */
29
30
  const stringValue = (node) => node?.type === "Literal" && typeof node.value === "string" ? node.value : void 0;
31
+ /** The value of a string literal or a template literal without expressions (`\`./x\``), or `undefined`. */
32
+ const staticString = (node) => node?.type === "TemplateLiteral" && node.expressions.length === 0 ? node.quasis[0]?.value.cooked ?? void 0 : stringValue(node);
30
33
  /** True for `@step` and `@step("...")` decorators, or any of the given decorator `names`. */
31
34
  const isStepDecorator = (decorator, names) => {
32
35
  const { expression } = decorator;
33
36
  const callee = expression.type === "CallExpression" ? expression.callee : expression;
34
37
  return callee.type === "Identifier" && names.has(callee.name);
35
38
  };
39
+ // src/utils/class-members.ts
40
+ const isMethod = (member) => member.type === "MethodDefinition" || member.type === "TSAbstractMethodDefinition";
41
+ const FUNCTION_VALUES$1 = /* @__PURE__ */ new Set([
42
+ "ArrowFunctionExpression",
43
+ "FunctionExpression",
44
+ "ClassExpression"
45
+ ]);
46
+ /**
47
+ * A plain property declaration (`static readonly PATTERN = /.../;`, `private readonly date: Date;`, …).
48
+ * A property holding a function or class is not plain: it is treated like a method.
49
+ */
50
+ const isPlainProperty = (member) => {
51
+ if (member.type === "TSIndexSignature") return true;
52
+ if (member.type !== "PropertyDefinition" && member.type !== "TSAbstractPropertyDefinition" && member.type !== "AccessorProperty") return false;
53
+ return member.value === null || !FUNCTION_VALUES$1.has(member.value.type);
54
+ };
55
+ /** `private` or an ECMAScript `#private` name. */
56
+ const isPrivate = (member) => "accessibility" in member && member.accessibility === "private" || "key" in member && member.key.type === "PrivateIdentifier";
57
+ const memberName$1 = (member) => {
58
+ const key = "key" in member ? member.key : void 0;
59
+ if (key && "name" in key && typeof key.name === "string") return key.name;
60
+ if (key && "value" in key && typeof key.value === "string") return key.value;
61
+ return "<computed>";
62
+ };
63
+ /** A member that belongs to the class itself: `static` members, static blocks and a `private constructor`. */
64
+ const isStaticMember = (member) => member.type === "StaticBlock" || "static" in member && member.static || member.type === "MethodDefinition" && member.kind === "constructor" && member.accessibility === "private";
65
+ /** A static abstract class: `abstract`, with only static members, so it is used without ever being instantiated. */
66
+ const isStaticClass = (node) => node.abstract === true && node.body.body.every(isStaticMember);
67
+ /** The classes declared at the top level of a program, including exported ones. */
68
+ function topLevelClasses(program) {
69
+ const classes = [];
70
+ for (const statement of program.body) {
71
+ const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
72
+ if (declaration?.type === "ClassDeclaration") classes.push(declaration);
73
+ }
74
+ return classes;
75
+ }
36
76
  // src/utils/docs.ts
37
77
  const REPOSITORY = "https://github.com/CeriosTesting/sparta-lint-rules";
38
78
  const docsUrl = (ruleName) => `${REPOSITORY}/blob/main/docs/rules/${ruleName}.md`;
@@ -85,11 +125,18 @@ const LAYER_FOLDERS = {
85
125
  steppers: {
86
126
  layer: "stepper",
87
127
  suffix: "stepper"
128
+ },
129
+ windows: {
130
+ layer: "window",
131
+ suffix: "window"
88
132
  }
89
133
  };
134
+ /** Layer folders that live directly in an area (`sparta/<area>/builders/`), shared by its groups, not in a group. */
135
+ const AREA_LAYER_FOLDERS = /* @__PURE__ */ new Set(["builders", "directors"]);
90
136
  const AREAS = [
91
137
  "api",
92
138
  "database",
139
+ "desktop",
93
140
  "mobile",
94
141
  "ui"
95
142
  ];
@@ -131,9 +178,9 @@ const suggest = (value, candidates) => {
131
178
  })).toSorted((a, b) => a.score - b.score);
132
179
  return best && best.score <= Math.max(2, Math.floor(best.candidate.length / 3)) ? `; did you mean ${JSON.stringify(best.candidate)}?` : "";
133
180
  };
134
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
181
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
135
182
  function record(value, where) {
136
- if (!isRecord(value)) throw new SettingsError(where, `must be an object, got ${JSON.stringify(value)}.`);
183
+ if (!isRecord$1(value)) throw new SettingsError(where, `must be an object, got ${JSON.stringify(value)}.`);
137
184
  return value;
138
185
  }
139
186
  function checkKeys(value, allowed, where) {
@@ -222,14 +269,15 @@ function buildPatterns(spartaFolder, testsFolder, areas) {
222
269
  const sparta = escape(spartaFolder);
223
270
  const tests = escape(testsFolder);
224
271
  const areaNames = [...areas.keys()].map(escape).join("|");
272
+ const end = "(?=/|$)";
225
273
  return {
226
- area: new RegExp(`/${sparta}/(${areaNames})/([^/]+)(?:/([^/]+))?`),
274
+ area: new RegExp(`/${sparta}/(${areaNames})${end}(?:/([^/]+))?(?:/([^/]+))?`),
227
275
  layer: new RegExp(`/${sparta}/(?:${areaNames})/[^/]+/([^/]+)/`),
228
- top: new RegExp(`/${sparta}/(${TOP_LEVEL_FOLDERS.join("|")})/`),
276
+ top: new RegExp(`/${sparta}/(${TOP_LEVEL_FOLDERS.join("|")})${end}`),
229
277
  checked: new RegExp(`/(?:${sparta}|${tests})/`),
230
278
  sparta: new RegExp(`/${sparta}/`),
231
- tests: new RegExp(`/${tests}/`),
232
- framework: new RegExp(`/${tests}/framework/`)
279
+ tests: new RegExp(`/${tests}${end}`),
280
+ framework: new RegExp(`/${tests}/framework${end}`)
233
281
  };
234
282
  }
235
283
  const STANDARD_LAYER_FOLDERS = Object.keys(LAYER_FOLDERS);
@@ -260,6 +308,196 @@ function parseSettings(raw, cwd) {
260
308
  };
261
309
  }
262
310
  parseSettings(void 0, process.cwd());
311
+ // src/utils/tsconfig.ts
312
+ const normalize$1 = (value) => value.split("\\").join("/");
313
+ const CONFIG_DIR = "${configDir}";
314
+ /** Where the string or comment that starts at `index` ends (exclusive), or `undefined` when none starts there. */
315
+ function skippedEnd(text, index) {
316
+ const start = text.slice(index, index + 2);
317
+ if (text[index] === "\"") {
318
+ let end = index + 1;
319
+ while (end < text.length && text[end] !== "\"") end += text[end] === "\\" ? 2 : 1;
320
+ return end + 1;
321
+ }
322
+ if (start === "//") {
323
+ const end = text.indexOf("\n", index);
324
+ return end === -1 ? text.length : end;
325
+ }
326
+ if (start === "/*") {
327
+ const end = text.indexOf("*/", index + 2);
328
+ return end === -1 ? text.length : end + 2;
329
+ }
330
+ }
331
+ /**
332
+ * Parses JSON with comments and trailing commas, as `tsconfig.json` allows. Comments are only recognised outside
333
+ * strings, so `"https://..."` stays intact.
334
+ */
335
+ function parseJsonc(text) {
336
+ let out = "";
337
+ /** Position in `out` of a comma that may still turn out to be a trailing one. */
338
+ let pendingComma = -1;
339
+ let index = text.charCodeAt(0) === 65279 ? 1 : 0;
340
+ while (index < text.length) {
341
+ const char = text[index];
342
+ const end = skippedEnd(text, index);
343
+ if (end !== void 0) {
344
+ if (char === "\"") {
345
+ out += text.slice(index, end);
346
+ pendingComma = -1;
347
+ }
348
+ index = end;
349
+ continue;
350
+ }
351
+ if (char === ",") pendingComma = out.length;
352
+ else if ((char === "}" || char === "]") && pendingComma !== -1) {
353
+ out = `${out.slice(0, pendingComma)} ${out.slice(pendingComma + 1)}`;
354
+ pendingComma = -1;
355
+ } else if (!/\s/.test(char)) pendingComma = -1;
356
+ out += char;
357
+ index++;
358
+ }
359
+ return JSON.parse(out);
360
+ }
361
+ const isFile$1 = (file) => (0, node_fs.statSync)(file, { throwIfNoEntry: false })?.isFile() ?? false;
362
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
363
+ var TsconfigError = class extends Error {
364
+ constructor(file, message) {
365
+ super(`sparta-lint-rules: cannot read ${normalize$1(file)}: ${message}`);
366
+ this.name = "TsconfigError";
367
+ }
368
+ };
369
+ function readConfig(file) {
370
+ let config;
371
+ try {
372
+ config = parseJsonc((0, node_fs.readFileSync)(file, "utf8"));
373
+ } catch (error) {
374
+ throw new TsconfigError(file, error instanceof Error ? error.message : String(error));
375
+ }
376
+ if (!isRecord(config)) throw new TsconfigError(file, "the config must be a JSON object.");
377
+ return config;
378
+ }
379
+ /** The file an `extends` entry points to: a path relative to the config, or a package such as `@tsconfig/node22`. */
380
+ function resolveExtends(specifier, from) {
381
+ if (specifier.startsWith(".") || node_path.default.isAbsolute(specifier)) {
382
+ const file = node_path.default.resolve(node_path.default.dirname(from), specifier);
383
+ if (isFile$1(file)) return file;
384
+ if (!file.endsWith(".json") && isFile$1(`${file}.json`)) return `${file}.json`;
385
+ } else {
386
+ const require$1 = (0, node_module.createRequire)(from);
387
+ const candidates = specifier.endsWith(".json") ? [specifier] : [`${specifier}/tsconfig.json`, specifier];
388
+ for (const candidate of candidates) try {
389
+ return require$1.resolve(candidate);
390
+ } catch {}
391
+ }
392
+ throw new TsconfigError(from, `extends ${JSON.stringify(specifier)}, which cannot be found.`);
393
+ }
394
+ const substitute = (value, configDir) => value.split(CONFIG_DIR).join(configDir);
395
+ function loadOptions(file, configDir, chain, read) {
396
+ if (chain.includes(file)) throw new TsconfigError(chain[0], `circular extends: ${[...chain, file].map(normalize$1).join(" -> ")}.`);
397
+ const config = readConfig(file);
398
+ const dir = node_path.default.dirname(file);
399
+ const parents = typeof config.extends === "string" ? [config.extends] : config.extends;
400
+ let options = {};
401
+ read.push(file);
402
+ if (Array.isArray(parents)) for (const parent of parents) {
403
+ if (typeof parent !== "string") continue;
404
+ const inherited = loadOptions(resolveExtends(parent, file), configDir, [...chain, file], read);
405
+ options = {
406
+ ...options,
407
+ ...inherited
408
+ };
409
+ }
410
+ const compilerOptions = isRecord(config.compilerOptions) ? config.compilerOptions : {};
411
+ if (typeof compilerOptions.baseUrl === "string") options.baseUrl = node_path.default.resolve(dir, substitute(compilerOptions.baseUrl, configDir));
412
+ if (isRecord(compilerOptions.paths)) options.paths = {
413
+ mapping: compilerOptions.paths,
414
+ base: dir
415
+ };
416
+ return options;
417
+ }
418
+ function toMappings(options, configDir) {
419
+ if (!options.paths) return [];
420
+ const base = options.baseUrl ?? options.paths.base;
421
+ return Object.entries(options.paths.mapping).flatMap(([pattern, value]) => {
422
+ const targets = Array.isArray(value) ? value.filter((target) => typeof target === "string") : [];
423
+ const star = pattern.indexOf("*");
424
+ if (targets.length === 0) return [];
425
+ return [{
426
+ pattern,
427
+ prefix: star === -1 ? pattern : pattern.slice(0, star),
428
+ suffix: star === -1 ? "" : pattern.slice(star + 1),
429
+ wildcard: star !== -1,
430
+ targets: targets.map((target) => normalize$1(node_path.default.resolve(base, substitute(target, configDir))))
431
+ }];
432
+ });
433
+ }
434
+ /** Parsed configs per file, kept for the lifetime of the linter process and refreshed when any file in the chain changes. */
435
+ const configCache = /* @__PURE__ */ new Map();
436
+ const mtime = (file) => (0, node_fs.statSync)(file, { throwIfNoEntry: false })?.mtimeMs;
437
+ /** The `paths` and `baseUrl` of a config file, including what it extends. Throws for unreadable or invalid configs. */
438
+ function loadTsconfig(file) {
439
+ const cached = configCache.get(file);
440
+ if (cached?.read.every((entry) => mtime(entry.file) === entry.mtimeMs)) return cached.value;
441
+ const configDir = node_path.default.dirname(file);
442
+ const read = [];
443
+ const options = loadOptions(file, configDir, [], read);
444
+ const value = {
445
+ file: normalize$1(file),
446
+ baseUrl: options.baseUrl === void 0 ? void 0 : normalize$1(options.baseUrl),
447
+ paths: toMappings(options, configDir)
448
+ };
449
+ configCache.set(file, {
450
+ read: read.map((entry) => ({
451
+ file: entry,
452
+ mtimeMs: mtime(entry) ?? -1
453
+ })),
454
+ value
455
+ });
456
+ return value;
457
+ }
458
+ /** Nearest `tsconfig.json` per directory (`null` for none), kept for the lifetime of the linter process. */
459
+ const lookupCache = /* @__PURE__ */ new Map();
460
+ /** The nearest `tsconfig.json`, from the file's folder upwards, or `undefined` when there is none. */
461
+ function findTsconfig(filename) {
462
+ const visited = [];
463
+ let found;
464
+ for (let dir = node_path.default.dirname(node_path.default.resolve(filename));;) {
465
+ found = lookupCache.get(dir);
466
+ if (found !== void 0) break;
467
+ visited.push(dir);
468
+ const candidate = node_path.default.join(dir, "tsconfig.json");
469
+ if (isFile$1(candidate)) {
470
+ found = candidate;
471
+ break;
472
+ }
473
+ const parent = node_path.default.dirname(dir);
474
+ if (parent === dir) {
475
+ found = null;
476
+ break;
477
+ }
478
+ dir = parent;
479
+ }
480
+ for (const dir of visited) lookupCache.set(dir, found);
481
+ return found ?? void 0;
482
+ }
483
+ /** The `paths` and `baseUrl` that apply to a file, from its nearest `tsconfig.json`. */
484
+ function tsconfigFor(filename) {
485
+ const file = findTsconfig(filename);
486
+ return file === void 0 ? void 0 : loadTsconfig(file);
487
+ }
488
+ /**
489
+ * The candidate paths a `paths` entry maps a request to, as TypeScript picks them: an exact pattern first,
490
+ * otherwise the wildcard pattern with the longest prefix. `undefined` when no pattern matches.
491
+ */
492
+ function matchPaths(request, mappings) {
493
+ const exact = mappings.find((mapping) => !mapping.wildcard && mapping.pattern === request);
494
+ if (exact) return exact.targets;
495
+ let best;
496
+ for (const mapping of mappings) if (mapping.wildcard && request.length >= mapping.prefix.length + mapping.suffix.length && request.startsWith(mapping.prefix) && request.endsWith(mapping.suffix) && (best === void 0 || mapping.prefix.length > best.prefix.length)) best = mapping;
497
+ if (best === void 0) return void 0;
498
+ const matched = request.slice(best.prefix.length, request.length - best.suffix.length);
499
+ return best.targets.map((target) => target.replace("*", matched));
500
+ }
263
501
  // src/utils/sparta-paths.ts
264
502
  const normalize = (value) => value.split("\\").join("/");
265
503
  const TOP_LEVEL_KINDS = {
@@ -268,6 +506,17 @@ const TOP_LEVEL_KINDS = {
268
506
  };
269
507
  /** The standard layer folder that a project's folder name follows, if any. */
270
508
  const standardFolder = (conventions, folder) => folder === void 0 ? void 0 : conventions.layerFolders.get(folder);
509
+ /** The layer of a standard layer folder (`stepper` for `steppers`), if it has one. */
510
+ const layerOf = (standard) => standard === void 0 ? void 0 : LAYER_FOLDERS[standard].layer;
511
+ /** The area-level layer folder (`builders/`, `directors/` directly below an area) a project path is in, if any. */
512
+ const areaLayerFolder = (file, conventions) => {
513
+ const name = file.match(conventions.patterns.area)?.[2];
514
+ const standard = standardFolder(conventions, name);
515
+ return name !== void 0 && standard !== void 0 && AREA_LAYER_FOLDERS.has(standard) ? {
516
+ name,
517
+ standard
518
+ } : void 0;
519
+ };
271
520
  const caseInsensitivePaths = process.platform === "win32";
272
521
  /**
273
522
  * The part of `filename` below the project `root`, with a leading `/` (`/sparta/ui/...`), or `undefined` for files
@@ -289,9 +538,15 @@ function classify(filename, conventions, root) {
289
538
  const area = file.match(patterns.area);
290
539
  if (area) {
291
540
  const [, areaName, group, folder] = area;
541
+ const areaLayer = areaLayerFolder(file, conventions);
542
+ if (areaLayer) return {
543
+ kind: "area-layer",
544
+ area: conventions.areas.get(areaName),
545
+ areaFolder: areaName,
546
+ layer: layerOf(areaLayer.standard)
547
+ };
292
548
  const base = file.match(/-base-(client|repository|service)(?:\.[cm]?[jt]s)?$/)?.[1];
293
- const standard = standardFolder(conventions, folder);
294
- const layer = base ? `base-${base}` : standard === void 0 ? void 0 : LAYER_FOLDERS[standard].layer;
549
+ const layer = base ? `base-${base}` : layerOf(standardFolder(conventions, folder));
295
550
  return {
296
551
  kind: group === "common" ? "area-common" : "group",
297
552
  area: conventions.areas.get(areaName),
@@ -330,15 +585,49 @@ function projectRoot(filename) {
330
585
  for (const dir of visited) rootCache.set(dir, root);
331
586
  return root;
332
587
  }
588
+ /** The extensions tried, in order, to find the file behind an extension-less import. */
589
+ const MODULE_EXTENSIONS = [
590
+ "",
591
+ ".ts",
592
+ ".tsx",
593
+ ".mts",
594
+ ".cts",
595
+ "/index.ts"
596
+ ];
597
+ const isFile = (file) => (0, node_fs.statSync)(file, { throwIfNoEntry: false })?.isFile() ?? false;
598
+ /** The TypeScript file an import path points to (`./x` -> `./x.ts`, `./x.js` -> `./x.ts`), if it exists. */
599
+ function moduleFile(base) {
600
+ const stripped = base.replace(/\.(?:m|c)?js$/, "");
601
+ for (const candidate of [base, ...MODULE_EXTENSIONS.map((extension) => `${stripped}${extension}`)]) if (isFile(candidate)) return normalize(candidate);
602
+ }
603
+ /** True when an import path points to an existing file or folder. */
604
+ const moduleExists = (base) => ((0, node_fs.statSync)(base, { throwIfNoEntry: false })?.isDirectory() ?? false) || moduleFile(base) !== void 0;
333
605
  /**
334
- * Resolves a relative or aliased import (`@sparta/*`, `@tests/*` and `settings.sparta.aliases`) to an absolute,
335
- * normalized path. Other imports are ignored. Aliases resolve against `root`.
606
+ * Resolves an import to an absolute, normalized path, the way TypeScript would:
607
+ *
608
+ * 1. relative imports, against the importing file;
609
+ * 2. `compilerOptions.paths` of the nearest `tsconfig.json`, taking the first target that exists;
610
+ * 3. the `@sparta/*` and `@tests/*` aliases and `settings.sparta.aliases`, against `root`;
611
+ * 4. the first `paths` target when none exists (yet);
612
+ * 5. `compilerOptions.baseUrl`, only when the file exists, so package imports are not mistaken for project files.
613
+ *
614
+ * Other imports (packages) resolve to `undefined`.
336
615
  */
337
616
  function resolveImport(filename, request, root, conventions) {
338
- for (const [prefix, target] of conventions.aliases) if (request.startsWith(prefix)) return `${root}/${target === "sparta" ? conventions.spartaFolder : conventions.testsFolder}/${request.slice(prefix.length)}`;
339
617
  if (request.startsWith(".")) return normalize(node_path.default.resolve(node_path.default.dirname(filename), request));
618
+ const tsconfig = tsconfigFor(filename);
619
+ const mapped = tsconfig === void 0 ? void 0 : matchPaths(request, tsconfig.paths);
620
+ const existing = mapped?.find(moduleExists);
621
+ if (existing !== void 0) return existing;
622
+ for (const [prefix, target] of conventions.aliases) if (request.startsWith(prefix)) return `${root}/${target === "sparta" ? conventions.spartaFolder : conventions.testsFolder}/${request.slice(prefix.length)}`;
623
+ if (mapped !== void 0 && mapped.length > 0) return mapped[0];
624
+ const fromBaseUrl = tsconfig?.baseUrl === void 0 ? void 0 : `${tsconfig.baseUrl}/${request}`;
625
+ return fromBaseUrl !== void 0 && moduleExists(fromBaseUrl) ? fromBaseUrl : void 0;
340
626
  }
341
- /** The layer folder a file lives in (`steppers`, `pages`, ...), with `sparta/scenarios/` counting as `scenarios`. */
627
+ /**
628
+ * The layer folder a file lives in (`steppers`, `pages`, ...), with `sparta/scenarios/` counting as `scenarios`
629
+ * and `sparta/<area>/builders/` and `directors/` as themselves.
630
+ */
342
631
  const layerFolder = (filename, conventions, root) => {
343
632
  const file = projectPath(filename, root);
344
633
  if (file === void 0) return void 0;
@@ -346,6 +635,8 @@ const layerFolder = (filename, conventions, root) => {
346
635
  name: "scenarios",
347
636
  standard: "scenarios"
348
637
  };
638
+ const areaLayer = areaLayerFolder(file, conventions);
639
+ if (areaLayer) return areaLayer;
349
640
  const folder = file.match(conventions.patterns.layer)?.[1];
350
641
  return folder === void 0 ? void 0 : {
351
642
  name: folder,
@@ -354,6 +645,10 @@ const layerFolder = (filename, conventions, root) => {
354
645
  };
355
646
  /** The file name suffix the files in a layer folder must use (`stepper` for `steppers/`), if it has one. */
356
647
  const layerSuffix = (folder) => folder?.standard === void 0 ? void 0 : LAYER_FOLDERS[folder.standard].suffix;
648
+ /** The file name without its TypeScript extension: `orders-stepper` for `orders-stepper.ts` or `.mts`. */
649
+ const moduleName = (filename) => node_path.default.basename(filename).replace(/\.[cm]?tsx?$/, "");
650
+ /** `.d.ts`, `.d.mts` and `.d.cts` files, which only declare types. */
651
+ const isDeclarationFile = (filename) => /\.d\.[cm]?ts$/.test(filename);
357
652
  /** True for files that follow the layer naming convention (layer folders and fixtures). */
358
653
  const isLayerFile = (filename, conventions, root) => layerSuffix(layerFolder(filename, conventions, root)) !== void 0 || projectPath(filename, root)?.match(conventions.patterns.top)?.[1] === "fixtures";
359
654
  // src/utils/settings.ts
@@ -387,22 +682,18 @@ const DATABASE_LAYERS = [
387
682
  "service",
388
683
  "stepper"
389
684
  ];
390
- /** The UI layers; `view` is the area's name for a page (`page` for web, `screen` for mobile). */
685
+ /** The UI layers; `view` is the area's name for a page (`page` for web, `screen` for mobile, `window` for desktop). */
391
686
  const uiLayers = (view) => ({
392
687
  component: /* @__PURE__ */ new Set([
393
688
  view,
394
689
  "stepper",
395
690
  "asserter",
396
- "scenario",
397
- "builder",
398
- "director"
691
+ "scenario"
399
692
  ]),
400
693
  [view]: /* @__PURE__ */ new Set([
401
694
  "stepper",
402
695
  "asserter",
403
- "scenario",
404
- "builder",
405
- "director"
696
+ "scenario"
406
697
  ]),
407
698
  stepper: /* @__PURE__ */ new Set(["asserter", "scenario"]),
408
699
  asserter: /* @__PURE__ */ new Set([
@@ -410,23 +701,9 @@ const uiLayers = (view) => ({
410
701
  "asserter",
411
702
  "scenario"
412
703
  ]),
413
- builder: /* @__PURE__ */ new Set([
414
- view,
415
- "component",
416
- "stepper",
417
- "asserter",
418
- "scenario"
419
- ]),
420
- director: /* @__PURE__ */ new Set([
421
- view,
422
- "component",
423
- "stepper",
424
- "asserter",
425
- "scenario"
426
- ]),
427
704
  scenario: /* @__PURE__ */ new Set([view, "component"])
428
705
  });
429
- /** Forbidden target layers inside the same area (API -> API, UI -> UI, database -> database, mobile -> mobile). */
706
+ /** Forbidden target layers inside the same area (API -> API, UI -> UI, database -> database, and so on). */
430
707
  const FORBIDDEN_LAYERS = {
431
708
  api: {
432
709
  client: /* @__PURE__ */ new Set([
@@ -529,9 +806,19 @@ const FORBIDDEN_LAYERS = {
529
806
  "base-repository"
530
807
  ])
531
808
  },
809
+ desktop: uiLayers("window"),
532
810
  mobile: uiLayers("screen"),
533
811
  ui: uiLayers("page")
534
812
  };
813
+ /** The layers of `sparta/<area>/builders/` and `sparta/<area>/directors/`. */
814
+ const BUILDER_LAYERS = /* @__PURE__ */ new Set(["builder", "director"]);
815
+ /** The only group layers that may use their area's builders and directors. */
816
+ const BUILDER_USERS = /* @__PURE__ */ new Set([
817
+ "scenario",
818
+ "stepper",
819
+ "asserter",
820
+ "service"
821
+ ]);
535
822
  const DATABASE_ACCESS = [
536
823
  "repository",
537
824
  "base-repository",
@@ -550,6 +837,7 @@ const FORBIDDEN_FOR_ORCHESTRATION = {
550
837
  "base-service"
551
838
  ]),
552
839
  database: new Set(DATABASE_ACCESS),
840
+ desktop: /* @__PURE__ */ new Set(["window", "component"]),
553
841
  mobile: /* @__PURE__ */ new Set(["screen", "component"]),
554
842
  ui: /* @__PURE__ */ new Set(["page", "component"])
555
843
  },
@@ -567,6 +855,12 @@ const FORBIDDEN_FOR_ORCHESTRATION = {
567
855
  "stepper",
568
856
  "asserter"
569
857
  ]),
858
+ desktop: /* @__PURE__ */ new Set([
859
+ "window",
860
+ "component",
861
+ "stepper",
862
+ "asserter"
863
+ ]),
570
864
  mobile: /* @__PURE__ */ new Set([
571
865
  "screen",
572
866
  "component",
@@ -583,32 +877,45 @@ const FORBIDDEN_FOR_ORCHESTRATION = {
583
877
  };
584
878
  const REEXPORT_LAYERS = /* @__PURE__ */ new Set([
585
879
  "asserter",
880
+ "builder",
586
881
  "client",
587
882
  "base-client",
588
883
  "base-repository",
589
884
  "component",
885
+ "director",
590
886
  "page",
591
887
  "repository",
592
888
  "scenario",
593
889
  "screen",
594
890
  "service",
595
891
  "base-service",
596
- "stepper"
892
+ "stepper",
893
+ "window"
597
894
  ]);
598
895
  const describe = (info, { spartaFolder, testsFolder }) => ({
599
- group: `${info.areaFolder}/${info.group}${info.layer ? ` ${info.layer}` : ""}`,
896
+ group: `${info.areaFolder}${info.group === void 0 ? "" : `/${info.group}`}${info.layer ? ` ${info.layer}` : ""}`,
600
897
  "area-common": `${info.areaFolder}/common`,
898
+ "area-layer": `${info.areaFolder} ${info.layer}`,
601
899
  "top-scenario": `${spartaFolder}/scenarios`,
602
900
  fixture: `${spartaFolder}/fixtures`,
603
901
  shared: `${spartaFolder}/common|support`,
604
902
  test: testsFolder
605
903
  })[info.kind];
904
+ /** Whether code in an area folder (a group, or the area's builders and directors) may not depend on `target`. */
905
+ function areaIsolationViolation(source, target) {
906
+ if (["fixture", "top-scenario"].includes(target.kind)) return true;
907
+ if (target.areaFolder === void 0) return false;
908
+ if (target.areaFolder !== source.areaFolder) return true;
909
+ if (target.kind !== "group") return false;
910
+ return source.kind === "area-layer" ? target.layer !== "service" : target.group !== source.group;
911
+ }
606
912
  /** Isolation compares area folders, not area types: `web/` and `ui/` are separate areas even when both follow `ui`. */
607
913
  function isolationViolation(source, target) {
608
914
  if (target.kind === "test") return source.kind !== "test";
609
915
  if (source.kind === "shared") return [
610
916
  "group",
611
917
  "area-common",
918
+ "area-layer",
612
919
  "fixture",
613
920
  "top-scenario"
614
921
  ].includes(target.kind);
@@ -616,20 +923,25 @@ function isolationViolation(source, target) {
616
923
  if ([
617
924
  "fixture",
618
925
  "top-scenario",
619
- "group"
926
+ "group",
927
+ "area-layer"
620
928
  ].includes(target.kind)) return true;
621
929
  return target.kind === "area-common" && target.areaFolder !== source.areaFolder;
622
930
  }
623
- if (source.kind === "group") {
624
- if (["fixture", "top-scenario"].includes(target.kind)) return true;
625
- if (target.areaFolder === void 0) return false;
626
- if (target.areaFolder !== source.areaFolder) return true;
627
- return target.kind === "group" && target.group !== source.group;
628
- }
629
- return false;
931
+ return source.kind === "group" || source.kind === "area-layer" ? areaIsolationViolation(source, target) : false;
932
+ }
933
+ /**
934
+ * Whether `source` may not use the builder or director `target`: builders use no builders or directors, directors
935
+ * only use builders, and in a group only scenarios, steppers, asserters and services may use them.
936
+ */
937
+ function builderViolation(source, target) {
938
+ if (source.kind === "area-layer") return source.layer === "builder" || target.layer === "director";
939
+ if (source.kind === "group") return source.layer === void 0 || !BUILDER_USERS.has(source.layer);
630
940
  }
631
941
  function layerViolation(source, target) {
632
942
  if (!target.layer || !target.area) return false;
943
+ const builder = BUILDER_LAYERS.has(target.layer) ? builderViolation(source, target) : void 0;
944
+ if (builder !== void 0) return builder;
633
945
  if (source.kind === "group" || source.kind === "area-common") {
634
946
  if (!source.area || !source.layer) return false;
635
947
  return source.areaFolder === target.areaFolder && Boolean(FORBIDDEN_LAYERS[source.area][source.layer]?.has(target.layer));
@@ -638,7 +950,7 @@ function layerViolation(source, target) {
638
950
  return false;
639
951
  }
640
952
  const isForbiddenReexport = (source, target) => target.layer !== void 0 && REEXPORT_LAYERS.has(target.layer) && target.layer !== source.layer && !["fixture", "test"].includes(source.kind);
641
- const rule$12 = {
953
+ const rule$13 = {
642
954
  meta: {
643
955
  type: "problem",
644
956
  docs: {
@@ -649,7 +961,9 @@ const rule$12 = {
649
961
  messages: {
650
962
  isolation: "{{source}} must not depend on {{target}} ({{request}}). Move shared code to the area's common/ folder or the top-level common/ folder.",
651
963
  layer: "{{source}} must not depend on {{target}} ({{request}}).",
652
- reexport: "Do not re-export {{target}} outside its layer; this bypasses the architecture boundaries."
964
+ reexport: "Do not re-export {{target}} outside its layer; this bypasses the architecture boundaries.",
965
+ staticService: "{{source}} is a static abstract class and must not depend on {{target}} ({{request}}); only a normal class may use services.",
966
+ placement: "Builders and directors belong in '{{expected}}/', shared by the area's groups, not in a group folder."
653
967
  }
654
968
  },
655
969
  create(context) {
@@ -658,11 +972,15 @@ const rule$12 = {
658
972
  const root = rootFor(context, conventions);
659
973
  const source = classify(filename, conventions, root);
660
974
  if (!source) return {};
975
+ /** Whether the file declares a normal (instantiable) class. Set on `Program`, before any import is visited. */
976
+ let isNormalClass = false;
977
+ /** An `index.ts` barrel in `builders/` or `directors/` may import and re-export its own layer. */
978
+ const isOwnBarrel = (target) => source.kind === "area-layer" && moduleName(filename) === "index" && target.kind === "area-layer" && target.areaFolder === source.areaFolder && target.layer === source.layer;
661
979
  const check = (node, request, reexport = false) => {
662
980
  if (request === void 0) return;
663
981
  const resolved = resolveImport(filename, request, root, conventions);
664
982
  const target = resolved ? classify(resolved, conventions, root) : void 0;
665
- if (!target) return;
983
+ if (!target || isOwnBarrel(target)) return;
666
984
  const data = {
667
985
  source: describe(source, conventions),
668
986
  target: describe(target, conventions),
@@ -678,6 +996,11 @@ const rule$12 = {
678
996
  messageId: "layer",
679
997
  data
680
998
  });
999
+ else if (source.kind === "area-layer" && target.layer === "service" && !isNormalClass) context.report({
1000
+ node,
1001
+ messageId: "staticService",
1002
+ data
1003
+ });
681
1004
  else if (reexport && isForbiddenReexport(source, target)) context.report({
682
1005
  node,
683
1006
  messageId: "reexport",
@@ -685,15 +1008,28 @@ const rule$12 = {
685
1008
  });
686
1009
  };
687
1010
  return {
1011
+ Program(node) {
1012
+ isNormalClass = topLevelClasses(node).some((declaration) => !isStaticClass(declaration));
1013
+ if (source.kind === "group" && source.layer !== void 0 && BUILDER_LAYERS.has(source.layer)) {
1014
+ const folder = layerFolder(filename, conventions, root)?.name ?? `${source.layer}s`;
1015
+ const expected = `${conventions.spartaFolder}/${source.areaFolder}/${folder}`;
1016
+ context.report({
1017
+ node,
1018
+ messageId: "placement",
1019
+ data: { expected }
1020
+ });
1021
+ }
1022
+ },
688
1023
  ImportDeclaration: (node) => check(node, stringValue(node.source)),
689
1024
  ExportNamedDeclaration: (node) => check(node, stringValue(node.source), true),
690
1025
  ExportAllDeclaration: (node) => check(node, stringValue(node.source), true),
691
- ImportExpression: (node) => check(node, stringValue(node.source)),
1026
+ ImportExpression: (node) => check(node, staticString(node.source)),
1027
+ TSImportType: (node) => check(node, stringValue(node.source)),
692
1028
  TSImportEqualsDeclaration(node) {
693
1029
  if (node.moduleReference.type === "TSExternalModuleReference") check(node, stringValue(node.moduleReference.expression));
694
1030
  },
695
1031
  CallExpression(node) {
696
- if (node.callee.type === "Identifier" && node.callee.name === "require") check(node, stringValue(node.arguments[0]));
1032
+ if (node.callee.type === "Identifier" && node.callee.name === "require") check(node, staticString(node.arguments[0]));
697
1033
  }
698
1034
  };
699
1035
  }
@@ -704,7 +1040,7 @@ const classOf = (statement) => {
704
1040
  const node = (statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && statement.declaration ? statement.declaration : statement;
705
1041
  return node.type === "ClassDeclaration" ? node : void 0;
706
1042
  };
707
- const rule$11 = {
1043
+ const rule$12 = {
708
1044
  meta: {
709
1045
  type: "suggestion",
710
1046
  docs: {
@@ -714,15 +1050,29 @@ const rule$11 = {
714
1050
  schema: [],
715
1051
  messages: {
716
1052
  name: "Class '{{found}}' must be named '{{expected}}' to match the file name.",
717
- single: "A layer file contains exactly one class; move '{{found}}' to its own file."
1053
+ single: "A layer file contains exactly one class; move '{{found}}' to its own file.",
1054
+ missing: "A layer file contains exactly one class; expected a class named '{{expected}}'."
718
1055
  }
719
1056
  },
720
1057
  create(context) {
721
1058
  const conventions = conventionsFor(context);
722
- if (!isLayerFile(context.filename, conventions, rootFor(context, conventions))) return {};
723
- const expected = toPascalCase(node_path.default.basename(context.filename).replace(/\.ts$/, ""));
1059
+ const root = rootFor(context, conventions);
1060
+ const { filename } = context;
1061
+ if (isDeclarationFile(filename) || !isLayerFile(filename, conventions, root)) return {};
1062
+ const module = moduleName(filename);
1063
+ const expected = toPascalCase(module);
1064
+ const requiresClass = module !== "index" && layerSuffix(layerFolder(filename, conventions, root)) !== void 0;
724
1065
  return { Program(program) {
725
- program.body.map(classOf).filter((node) => node !== void 0).forEach((node, index) => {
1066
+ const classes = program.body.map(classOf).filter((node) => node !== void 0);
1067
+ if (classes.length === 0 && requiresClass) {
1068
+ context.report({
1069
+ node: program,
1070
+ messageId: "missing",
1071
+ data: { expected }
1072
+ });
1073
+ return;
1074
+ }
1075
+ classes.forEach((node, index) => {
726
1076
  const found = node.id?.name ?? "(anonymous)";
727
1077
  if (index > 0) context.report({
728
1078
  node: node.id ?? node,
@@ -741,6 +1091,68 @@ const rule$11 = {
741
1091
  } };
742
1092
  }
743
1093
  };
1094
+ // src/rules/director-composes-builders.ts
1095
+ const rule$11 = {
1096
+ meta: {
1097
+ type: "suggestion",
1098
+ docs: {
1099
+ description: "Require a director to compose several builders; a director using a single builder belongs on that builder.",
1100
+ url: docsUrl("director-composes-builders")
1101
+ },
1102
+ schema: [],
1103
+ messages: { singleBuilder: "This director only uses '{{builder}}'; make it a custom method on '{{builder}}'. A director composes several builders." }
1104
+ },
1105
+ create(context) {
1106
+ const filename = context.filename;
1107
+ const conventions = conventionsFor(context);
1108
+ const root = rootFor(context, conventions);
1109
+ const source = classify(filename, conventions, root);
1110
+ if (source?.kind !== "area-layer" || source.layer !== "director" || moduleName(filename) === "index") return {};
1111
+ const isBuilder = (request) => {
1112
+ if (request === void 0) return false;
1113
+ const resolved = resolveImport(filename, request, root, conventions);
1114
+ return resolved !== void 0 && classify(resolved, conventions, root)?.layer === "builder";
1115
+ };
1116
+ /** The builders the director uses, by imported name, with the import to report. */
1117
+ const builders = /* @__PURE__ */ new Map();
1118
+ /** Set when a builder is imported in a way that does not tell how many builders are used. */
1119
+ let unknown = false;
1120
+ return {
1121
+ ImportDeclaration(node) {
1122
+ if (node.importKind === "type" || typeof node.source.value !== "string" || !isBuilder(node.source.value)) return;
1123
+ for (const specifier of node.specifiers) if (specifier.type === "ImportNamespaceSpecifier") unknown = true;
1124
+ else if (specifier.type === "ImportDefaultSpecifier") builders.set(specifier.local.name, {
1125
+ local: specifier.local.name,
1126
+ node
1127
+ });
1128
+ else if (specifier.importKind !== "type") {
1129
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : String(specifier.imported.value);
1130
+ builders.set(imported, {
1131
+ local: specifier.local.name,
1132
+ node
1133
+ });
1134
+ }
1135
+ },
1136
+ ImportExpression(node) {
1137
+ if (isBuilder(staticString(node.source))) unknown = true;
1138
+ },
1139
+ CallExpression(node) {
1140
+ if (node.callee.type === "Identifier" && node.callee.name === "require") {
1141
+ if (isBuilder(staticString(node.arguments[0]))) unknown = true;
1142
+ }
1143
+ },
1144
+ "Program:exit"() {
1145
+ const [only] = builders.values();
1146
+ if (unknown || builders.size !== 1 || only === void 0) return;
1147
+ context.report({
1148
+ node: only.node,
1149
+ messageId: "singleBuilder",
1150
+ data: { builder: only.local }
1151
+ });
1152
+ }
1153
+ };
1154
+ }
1155
+ };
744
1156
  // src/rules/expect-from-support.ts
745
1157
  /** Files inside the sparta folder, except its support folder (where `expect` itself is defined). */
746
1158
  const appliesTo = (filename, { patterns }, root) => {
@@ -761,10 +1173,21 @@ const rule$10 = {
761
1173
  create(context) {
762
1174
  const conventions = conventionsFor(context);
763
1175
  const { supportModule } = conventions;
764
- if (!appliesTo(context.filename, conventions, rootFor(context, conventions))) return {};
1176
+ const root = rootFor(context, conventions);
1177
+ if (!appliesTo(context.filename, conventions, root)) return {};
1178
+ /**
1179
+ * The support module, a subpath of it, or a relative import into the support folder. Other aliases for that
1180
+ * folder are reported, so the configured module name stays the one that is used.
1181
+ */
1182
+ const isSupport = (source) => {
1183
+ if (source === supportModule || source.startsWith(`${supportModule}/`)) return true;
1184
+ if (!source.startsWith(".")) return false;
1185
+ const resolved = resolveImport(context.filename, source, root, conventions);
1186
+ return (resolved === void 0 ? void 0 : projectPath(resolved, root))?.match(conventions.patterns.top)?.[1] === "support";
1187
+ };
765
1188
  return { ImportDeclaration(node) {
766
1189
  const source = node.source.value;
767
- if (source === supportModule) return;
1190
+ if (isSupport(String(source))) return;
768
1191
  const specifier = node.specifiers.find((item) => item.type === "ImportSpecifier" && item.imported.type === "Identifier" && item.imported.name === "expect");
769
1192
  if (specifier === void 0) return;
770
1193
  const data = {
@@ -789,24 +1212,35 @@ const rule$10 = {
789
1212
  }
790
1213
  };
791
1214
  // src/rules/file-naming.ts
1215
+ /** Lowercase words of letters and digits, joined by single hyphens: `orders-v2-stepper`. */
1216
+ const KEBAB_CASE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
1217
+ /** `myOrders`, `My_APIOrders` and `checkout--flow` become `my-orders`, `my-api-orders` and `checkout-flow`. */
1218
+ const toKebabCase = (name) => name.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
792
1219
  const rule$9 = {
793
1220
  meta: {
794
1221
  type: "suggestion",
795
1222
  docs: {
796
- description: "Require files in a layer folder to end with the layer suffix (e.g. `*-stepper.ts`).",
1223
+ description: "Require files in a layer folder to be kebab-case and end with the layer suffix (e.g. `orders-stepper.ts`).",
797
1224
  url: docsUrl("file-naming")
798
1225
  },
799
1226
  schema: [],
800
- messages: { suffix: "Files in '{{folder}}/' must be named '*-{{suffix}}.ts' (found '{{name}}')." }
1227
+ messages: {
1228
+ suffix: "Files in '{{folder}}/' must be named '*-{{suffix}}.ts' (found '{{name}}').",
1229
+ kebabCase: "File name '{{name}}' must be kebab-case: '{{expected}}'."
1230
+ }
801
1231
  },
802
1232
  create(context) {
803
1233
  const conventions = conventionsFor(context);
804
1234
  const folder = layerFolder(context.filename, conventions, rootFor(context, conventions));
805
1235
  const suffix = layerSuffix(folder);
806
1236
  const name = node_path.default.basename(context.filename);
807
- if (folder === void 0 || suffix === void 0 || name === "index.ts" || name.endsWith(`-${suffix}.ts`)) return {};
1237
+ const module = moduleName(context.filename);
1238
+ if (folder === void 0 || suffix === void 0 || isDeclarationFile(name) || module === "index") return {};
1239
+ const hasSuffix = module.endsWith(`-${suffix}`);
1240
+ const isKebabCase = KEBAB_CASE.test(module);
1241
+ if (hasSuffix && isKebabCase) return {};
808
1242
  return { Program(node) {
809
- context.report({
1243
+ if (!hasSuffix) context.report({
810
1244
  node,
811
1245
  messageId: "suffix",
812
1246
  data: {
@@ -815,30 +1249,61 @@ const rule$9 = {
815
1249
  name
816
1250
  }
817
1251
  });
1252
+ if (!isKebabCase) {
1253
+ const expected = `${toKebabCase(module)}${name.slice(module.length)}`;
1254
+ context.report({
1255
+ node,
1256
+ messageId: "kebabCase",
1257
+ data: {
1258
+ name,
1259
+ expected
1260
+ }
1261
+ });
1262
+ }
818
1263
  } };
819
1264
  }
820
1265
  };
821
1266
  // src/rules/lines-between-class-members.ts
822
1267
  const BLANK_LINE$1 = /\r?\n[\t ]*\r?\n/;
1268
+ const BLANK_LINES$1 = /(\r?\n)(?:[\t ]*\r?\n)+/g;
1269
+ /** An overload signature (or abstract method): a method without a body. */
1270
+ const isSignature = (member) => isMethod(member) && member.value.body === null;
823
1271
  const rule$8 = {
824
1272
  meta: {
825
1273
  type: "layout",
826
1274
  docs: {
827
- description: "Require a blank line after every multi-line class member.",
1275
+ description: "Require a blank line after every multi-line method-like class member, and disallow blank lines between method overloads.",
828
1276
  url: docsUrl("lines-between-class-members")
829
1277
  },
830
1278
  fixable: "whitespace",
831
1279
  schema: [],
832
- messages: { expectedBlankLine: "Expected a blank line between class members." }
1280
+ messages: {
1281
+ expectedBlankLine: "Expected a blank line between class members.",
1282
+ unexpectedBlankLine: "Unexpected blank line between overloads of the same method."
1283
+ }
833
1284
  },
834
1285
  create(context) {
835
- const { text } = context.sourceCode;
1286
+ const { sourceCode } = context;
1287
+ const { text } = sourceCode;
1288
+ const keyOf = (method) => `${method.static ? "static " : ""}${method.computed ? "[]" : ""}${sourceCode.getText(method.key)}`;
1289
+ /** `current` continues the overload group that `previous` (a bodyless signature) belongs to. */
1290
+ const isOverloadOf = (previous, current) => isSignature(previous) && isMethod(current) && current.kind === previous.kind && keyOf(current) === keyOf(previous);
836
1291
  return { ClassBody(node) {
837
1292
  for (let index = 1; index < node.body.length; index++) {
838
1293
  const previous = node.body[index - 1];
839
1294
  const current = node.body[index];
840
- if (previous.loc.start.line === previous.loc.end.line) continue;
841
1295
  const textBetween = text.slice(previous.range[1], current.range[0]);
1296
+ if (isOverloadOf(previous, current)) {
1297
+ if (!BLANK_LINE$1.test(textBetween)) continue;
1298
+ context.report({
1299
+ node: current,
1300
+ messageId: "unexpectedBlankLine",
1301
+ fix: (fixer) => fixer.replaceTextRange([previous.range[1], current.range[0]], textBetween.replace(BLANK_LINES$1, "$1"))
1302
+ });
1303
+ continue;
1304
+ }
1305
+ if (previous.loc.start.line === previous.loc.end.line) continue;
1306
+ if (isPlainProperty(previous)) continue;
842
1307
  if (BLANK_LINE$1.test(textBetween)) continue;
843
1308
  context.report({
844
1309
  node: current,
@@ -853,9 +1318,154 @@ const rule$8 = {
853
1318
  } };
854
1319
  }
855
1320
  };
856
- // src/rules/no-direct-construction-in-tests.ts
857
- const LAYER_CLASS = /(Stepper|Asserter|Scenario|Service|Client|Repository|Page|Screen|Component|Builder|Director|Factory|Provider)$/;
1321
+ // src/rules/member-ordering.ts
1322
+ const KINDS = [
1323
+ "property",
1324
+ "constructor",
1325
+ "method"
1326
+ ];
1327
+ const ACCESSES = [
1328
+ "public",
1329
+ "protected",
1330
+ "private"
1331
+ ];
1332
+ /** Properties (incl. index signatures) and methods; a property holding a function or class counts as a method. */
1333
+ const kindOf = (member) => {
1334
+ if (isMethod(member)) return member.kind === "constructor" ? "constructor" : "method";
1335
+ if (member.type === "StaticBlock") return void 0;
1336
+ return isPlainProperty(member) ? "property" : "method";
1337
+ };
1338
+ const accessOf = (member) => {
1339
+ if (isPrivate(member)) return "private";
1340
+ if ("accessibility" in member && member.accessibility === "protected") return "protected";
1341
+ return "public";
1342
+ };
1343
+ /**
1344
+ * The required order: static properties, instance properties, constructor, static methods, instance methods,
1345
+ * each from public to protected to private.
1346
+ */
1347
+ const groupOf = (member) => {
1348
+ const kind = kindOf(member);
1349
+ if (kind === void 0) return void 0;
1350
+ if (kind === "constructor") return {
1351
+ rank: KINDS.indexOf(kind) * 6,
1352
+ label: "constructor"
1353
+ };
1354
+ const isStatic = "static" in member && member.static;
1355
+ const access = accessOf(member);
1356
+ return {
1357
+ rank: KINDS.indexOf(kind) * 6 + (isStatic ? 0 : 3) + ACCESSES.indexOf(access),
1358
+ label: `${isStatic ? "static " : ""}${access} ${kind}`
1359
+ };
1360
+ };
1361
+ const SKIPPED_KEYS$1 = /* @__PURE__ */ new Set([
1362
+ "parent",
1363
+ "loc",
1364
+ "range",
1365
+ "start",
1366
+ "end",
1367
+ "typeAnnotation"
1368
+ ]);
1369
+ const isNode$1 = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
1370
+ const FUNCTIONS = /* @__PURE__ */ new Set([
1371
+ "ArrowFunctionExpression",
1372
+ "FunctionExpression",
1373
+ "ClassExpression"
1374
+ ]);
1375
+ /** `x` for `this.x`, `this.#x` and `ClassName.x`. */
1376
+ const ownPropertyRead = (node, className) => {
1377
+ if (node.type !== "MemberExpression" || node.computed) return void 0;
1378
+ const { object, property } = node;
1379
+ return (object.type === "ThisExpression" || className !== void 0 && object.type === "Identifier" && object.name === className) && (property.type === "Identifier" || property.type === "PrivateIdentifier") ? property.name : void 0;
1380
+ };
1381
+ /**
1382
+ * The property names an initializer reads while it runs, as `this.x`, `this.#x` or `ClassName.x`. Code inside
1383
+ * functions is left out: it runs later, when every property is initialized.
1384
+ */
1385
+ function readsDuringInit(value, className) {
1386
+ const names = /* @__PURE__ */ new Set();
1387
+ const visit = (node) => {
1388
+ if (FUNCTIONS.has(node.type)) return;
1389
+ const read = ownPropertyRead(node, className);
1390
+ if (read !== void 0) names.add(read);
1391
+ for (const [key, child] of Object.entries(node)) {
1392
+ if (SKIPPED_KEYS$1.has(key)) continue;
1393
+ if (Array.isArray(child)) {
1394
+ for (const item of child) if (isNode$1(item)) visit(item);
1395
+ } else if (isNode$1(child)) visit(child);
1396
+ }
1397
+ };
1398
+ visit(value);
1399
+ return names;
1400
+ }
1401
+ /**
1402
+ * Initializers run in source order, so a property that reads a property declared before it must stay below it,
1403
+ * even when the order of the groups says otherwise.
1404
+ */
1405
+ const dependsOnEarlier = (member, earlier, className) => {
1406
+ if (member.type !== "PropertyDefinition" && member.type !== "AccessorProperty") return false;
1407
+ if (!member.value) return false;
1408
+ return [...readsDuringInit(member.value, className)].some((name) => earlier.has(name));
1409
+ };
858
1410
  const rule$7 = {
1411
+ meta: {
1412
+ type: "suggestion",
1413
+ docs: {
1414
+ description: "Require class members in a fixed order: properties, constructor, methods; static before instance; public before protected before private.",
1415
+ url: docsUrl("member-ordering")
1416
+ },
1417
+ schema: [],
1418
+ messages: { memberOrdering: "'{{name}}' ({{group}}) must come before '{{otherName}}' ({{otherGroup}})." }
1419
+ },
1420
+ create(context) {
1421
+ return { ClassBody(node) {
1422
+ let highest;
1423
+ const { parent } = node;
1424
+ const className = (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.id ? parent.id.name : void 0;
1425
+ /** Names of the properties declared so far. */
1426
+ const earlier = /* @__PURE__ */ new Set();
1427
+ for (const member of node.body) {
1428
+ const group = groupOf(member);
1429
+ const dependent = dependsOnEarlier(member, earlier, className);
1430
+ if (isPlainProperty(member) && member.type !== "TSIndexSignature") earlier.add(memberName$1(member));
1431
+ if (group === void 0) continue;
1432
+ if (highest === void 0 || group.rank >= highest.group.rank) {
1433
+ highest = {
1434
+ member,
1435
+ group
1436
+ };
1437
+ continue;
1438
+ }
1439
+ if (dependent) continue;
1440
+ context.report({
1441
+ node: member,
1442
+ messageId: "memberOrdering",
1443
+ data: {
1444
+ name: memberName$1(member),
1445
+ group: group.label,
1446
+ otherName: memberName$1(highest.member),
1447
+ otherGroup: highest.group.label
1448
+ }
1449
+ });
1450
+ }
1451
+ } };
1452
+ }
1453
+ };
1454
+ // src/rules/no-direct-construction-in-tests.ts
1455
+ /** Names of SPARTA layer classes, for classes whose import does not tell their layer. */
1456
+ const LAYER_CLASS = /(Stepper|Asserter|Scenario|Service|Client|Repository|Page|Screen|Window|Component|Builder|Director|Factory|Provider|Container|Database)$/;
1457
+ /** The class a `new` expression constructs: `X` for `new X()`, `ns` and `X` for `new ns.X()`. */
1458
+ const constructed = (callee) => {
1459
+ if (callee.type === "Identifier") return {
1460
+ binding: callee.name,
1461
+ name: callee.name
1462
+ };
1463
+ if (callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.property.type === "Identifier") return {
1464
+ binding: callee.object.name,
1465
+ name: callee.property.name
1466
+ };
1467
+ };
1468
+ const rule$6 = {
859
1469
  meta: {
860
1470
  type: "problem",
861
1471
  docs: {
@@ -867,15 +1477,36 @@ const rule$7 = {
867
1477
  },
868
1478
  create(context) {
869
1479
  const conventions = conventionsFor(context);
870
- if (classify(context.filename, conventions, rootFor(context, conventions))?.kind !== "test") return {};
871
- return { NewExpression(node) {
872
- const { callee } = node;
873
- if (callee.type === "Identifier" && LAYER_CLASS.test(callee.name)) context.report({
874
- node,
875
- messageId: "useFixture",
876
- data: { name: callee.name }
877
- });
878
- } };
1480
+ const root = rootFor(context, conventions);
1481
+ if (classify(context.filename, conventions, root)?.kind !== "test") return {};
1482
+ /** Local names of imports (named, default and namespace) to their module. */
1483
+ const imports = /* @__PURE__ */ new Map();
1484
+ /**
1485
+ * Whether constructing `name` (bound to the local `binding`) creates a SPARTA layer object. An import decides by
1486
+ * where it points: never for packages, always for layer folders. Otherwise the class name decides.
1487
+ */
1488
+ const isLayerClass = (binding, name) => {
1489
+ const source = imports.get(binding);
1490
+ if (source === void 0) return LAYER_CLASS.test(name);
1491
+ const resolved = resolveImport(context.filename, source, root, conventions);
1492
+ if (resolved === void 0) return false;
1493
+ const target = classify(resolved, conventions, root);
1494
+ return target?.layer !== void 0 || target?.kind === "top-scenario" || layerSuffix(layerFolder(resolved, conventions, root)) !== void 0 || LAYER_CLASS.test(name);
1495
+ };
1496
+ return {
1497
+ ImportDeclaration(node) {
1498
+ if (typeof node.source.value !== "string") return;
1499
+ for (const specifier of node.specifiers) imports.set(specifier.local.name, node.source.value);
1500
+ },
1501
+ NewExpression(node) {
1502
+ const found = constructed(node.callee);
1503
+ if (found && isLayerClass(found.binding, found.name)) context.report({
1504
+ node,
1505
+ messageId: "useFixture",
1506
+ data: { name: context.sourceCode.getText(node.callee) }
1507
+ });
1508
+ }
1509
+ };
879
1510
  }
880
1511
  };
881
1512
  // src/rules/no-expect-in-tests.ts
@@ -884,7 +1515,7 @@ const rule$7 = {
884
1515
  * `expected`, `expecting` and the like are left alone. `settings.sparta.expectNames` adds exact names.
885
1516
  */
886
1517
  const EXPECT_NAME = /^expect(?:ly)?(?:[A-Z_$\d]|$)/;
887
- const rule$6 = {
1518
+ const rule$5 = {
888
1519
  meta: {
889
1520
  type: "problem",
890
1521
  docs: {
@@ -947,7 +1578,15 @@ const resolvesPromise = (callback, resolve) => {
947
1578
  const call = body.type === "CallExpression" ? body : body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "ExpressionStatement" ? body.body[0].expression : void 0;
948
1579
  return call?.type === "CallExpression" && isIdentifier(call.callee, resolve);
949
1580
  };
950
- const rule$5 = {
1581
+ /** The name of an import specifier or object pattern key (`setTimeout`, `"setTimeout"`). */
1582
+ const propertyName = (node) => node.type === "Identifier" ? node.name : stringValue(node);
1583
+ /** `require("timers/promises")` or `require("node:timers/promises")`. */
1584
+ const isTimersRequire = (node) => {
1585
+ if (node?.type !== "CallExpression" || !isIdentifier(node.callee, "require")) return false;
1586
+ const source = staticString(node.arguments[0]);
1587
+ return source !== void 0 && TIMER_MODULES.has(source);
1588
+ };
1589
+ const rule$4 = {
951
1590
  meta: {
952
1591
  type: "problem",
953
1592
  docs: {
@@ -962,17 +1601,47 @@ const rule$5 = {
962
1601
  const { patterns } = conventions;
963
1602
  const file = projectPath(context.filename, rootFor(context, conventions));
964
1603
  if (file === void 0 || !patterns.checked.test(file) || patterns.framework.test(file)) return {};
1604
+ /** Local names bound to the `timers/promises` module (`timers`) and to its `scheduler` (`schedulers`). */
1605
+ const timers = /* @__PURE__ */ new Set();
1606
+ const schedulers = /* @__PURE__ */ new Set();
1607
+ /** Records a named binding from `timers/promises`; `setTimeout` itself is reported where it is bound. */
1608
+ const bindNamed = (imported, local, node) => {
1609
+ if (imported === "setTimeout") context.report({
1610
+ node,
1611
+ messageId: "hardWait"
1612
+ });
1613
+ if (imported === "scheduler" && local?.type === "Identifier") schedulers.add(local.name);
1614
+ };
1615
+ /** `timers.setTimeout(...)`, `scheduler.wait(...)` and `timers.scheduler.wait(...)`. */
1616
+ const isTimersSleep = (callee) => {
1617
+ if (callee.type !== "MemberExpression") return false;
1618
+ const { object, property } = callee;
1619
+ if (isIdentifier(property, "setTimeout")) return object.type === "Identifier" && timers.has(object.name);
1620
+ if (!isIdentifier(property, "wait")) return false;
1621
+ if (object.type === "Identifier") return schedulers.has(object.name);
1622
+ return object.type === "MemberExpression" && object.object.type === "Identifier" && timers.has(object.object.name) && isIdentifier(object.property, "scheduler");
1623
+ };
965
1624
  return {
966
1625
  ImportDeclaration(node) {
967
1626
  if (typeof node.source.value !== "string" || !TIMER_MODULES.has(node.source.value)) return;
968
- for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier" && isIdentifier(specifier.imported, "setTimeout")) context.report({
969
- node: specifier,
970
- messageId: "hardWait"
971
- });
1627
+ for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier") bindNamed(propertyName(specifier.imported) ?? "", specifier.local, specifier);
1628
+ else timers.add(specifier.local.name);
1629
+ },
1630
+ VariableDeclarator(node) {
1631
+ if (!isTimersRequire(node.init)) return;
1632
+ if (node.id.type === "Identifier") {
1633
+ timers.add(node.id.name);
1634
+ return;
1635
+ }
1636
+ if (node.id.type !== "ObjectPattern") return;
1637
+ for (const property of node.id.properties) {
1638
+ if (property.type !== "Property" || property.computed) continue;
1639
+ bindNamed(propertyName(property.key) ?? "", property.value, property);
1640
+ }
972
1641
  },
973
1642
  CallExpression(node) {
974
1643
  const { callee } = node;
975
- if (callee.type === "MemberExpression" && isIdentifier(callee.property, "waitForTimeout")) {
1644
+ if (callee.type === "MemberExpression" && isIdentifier(callee.property, "waitForTimeout") || isTimersSleep(callee)) {
976
1645
  context.report({
977
1646
  node,
978
1647
  messageId: "hardWait"
@@ -1000,7 +1669,7 @@ const CALLBACK_ARGUMENT_METHODS = /* @__PURE__ */ new Set(["poll", "pollAndRetur
1000
1669
  /** Methods that retry the callback given to the start of their chain (`expect(cb).toPass()`). */
1001
1670
  const CALLBACK_SUBJECT_METHODS = /* @__PURE__ */ new Set(["toPass", "toPassAndReturn"]);
1002
1671
  /** The static name of a member access (`a.b`, `a["b"]`), or `undefined` for computed or private access. */
1003
- const memberName$1 = (node) => {
1672
+ const memberName = (node) => {
1004
1673
  if (node.type !== "MemberExpression") return void 0;
1005
1674
  const { property } = node;
1006
1675
  if (!node.computed && property.type === "Identifier") return property.name;
@@ -1009,7 +1678,7 @@ const memberName$1 = (node) => {
1009
1678
  /** The polling method a call invokes (`toPass` for `expect(cb).toPass()`), or `undefined` for any other node. */
1010
1679
  const pollingMethod = (node, methods) => {
1011
1680
  if (node.type !== "CallExpression") return void 0;
1012
- const name = memberName$1(node.callee);
1681
+ const name = memberName(node.callee);
1013
1682
  return name !== void 0 && methods.has(name) ? name : void 0;
1014
1683
  };
1015
1684
  const isFunction$1 = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression";
@@ -1051,14 +1720,6 @@ const SKIPPED_KEYS = /* @__PURE__ */ new Set([
1051
1720
  "returnType",
1052
1721
  "decorators"
1053
1722
  ]);
1054
- const MODULE_EXTENSIONS = [
1055
- "",
1056
- ".ts",
1057
- ".tsx",
1058
- ".mts",
1059
- ".cts",
1060
- "/index.ts"
1061
- ];
1062
1723
  const isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
1063
1724
  /** Visits `node` and its descendants depth-first. Returning `false` from `visit` skips the node's children. */
1064
1725
  function walk(node, visit) {
@@ -1093,11 +1754,16 @@ function summarizeClass(name, node) {
1093
1754
  }
1094
1755
  return info;
1095
1756
  }
1096
- /** A typed field (`x: X`) or a field created with `new X()`. */
1757
+ /** A typed field (`x: X`), a field created with `new X()`, or a function-valued field, which acts as a method. */
1097
1758
  function summarizeField(info, member) {
1098
1759
  const field = member.computed ? void 0 : keyName(member.key);
1760
+ if (field === void 0) return;
1761
+ if (isFunctionLike(member.value)) {
1762
+ info.methods.set(field, member.value);
1763
+ return;
1764
+ }
1099
1765
  const type = typeName(member.typeAnnotation) ?? newName(member.value);
1100
- if (field !== void 0 && type !== void 0) info.fields.set(field, type);
1766
+ if (type !== void 0) info.fields.set(field, type);
1101
1767
  }
1102
1768
  /** Methods, getters (whose return type acts as a field type) and the constructor. */
1103
1769
  function summarizeMethod(info, member) {
@@ -1122,7 +1788,7 @@ function summarizeConstructor(info, constructor) {
1122
1788
  walk(constructor.body, (node) => {
1123
1789
  if (node.type !== "AssignmentExpression" || node.left.type !== "MemberExpression") return;
1124
1790
  if (node.left.object.type !== "ThisExpression") return;
1125
- const field = memberName$1(node.left);
1791
+ const field = memberName(node.left);
1126
1792
  const type = newName(node.right);
1127
1793
  if (field !== void 0 && type !== void 0 && !info.fields.has(field)) info.fields.set(field, type);
1128
1794
  });
@@ -1194,13 +1860,10 @@ function summarizeNamedExport(summary, statement) {
1194
1860
  else summary.exports.set(exported, local);
1195
1861
  }
1196
1862
  }
1197
- const isFile = (file) => (0, node_fs.statSync)(file, { throwIfNoEntry: false })?.isFile() ?? false;
1198
- /** Resolves a relative or aliased import to a TypeScript file. Package imports resolve to `undefined`. */
1863
+ /** Resolves a relative, aliased or tsconfig-mapped import to a TypeScript file. Package imports resolve to `undefined`. */
1199
1864
  function resolveModule(fromFile, request, root, conventions) {
1200
1865
  const base = resolveImport(fromFile, request, root, conventions);
1201
- if (base === void 0) return void 0;
1202
- const stripped = base.replace(/\.(?:m|c)?js$/, "");
1203
- for (const candidate of [base, ...MODULE_EXTENSIONS.map((extension) => `${stripped}${extension}`)]) if (isFile(candidate)) return normalize(candidate);
1866
+ return base === void 0 ? void 0 : moduleFile(base);
1204
1867
  }
1205
1868
  /**
1206
1869
  * Summaries of files on disk per project root and conventions (imports resolve against them), kept for the lifetime of the
@@ -1305,7 +1968,7 @@ var ProjectIndex = class {
1305
1968
  fn
1306
1969
  } : void 0;
1307
1970
  }
1308
- const method = memberName$1(node);
1971
+ const method = memberName(node);
1309
1972
  if (method === void 0 || node.type !== "MemberExpression") return void 0;
1310
1973
  const receiver = this.receiverClass(node.object, scope);
1311
1974
  return receiver ? this.findMethod(receiver, method) : void 0;
@@ -1335,13 +1998,13 @@ var ProjectIndex = class {
1335
1998
  case "ThisExpression": return scope.cls;
1336
1999
  case "Identifier": {
1337
2000
  const type = scope.locals.get(node.name);
1338
- return type === void 0 ? void 0 : this.resolveClass(scope.file, type);
2001
+ return this.resolveClass(scope.file, type ?? node.name);
1339
2002
  }
1340
2003
  case "NewExpression": return node.callee.type === "Identifier" ? this.resolveClass(scope.file, node.callee.name) : void 0;
1341
2004
  case "TSNonNullExpression":
1342
2005
  case "ParenthesizedExpression": return this.receiverClass(node.expression, scope, depth + 1);
1343
2006
  case "MemberExpression": {
1344
- const field = memberName$1(node);
2007
+ const field = memberName(node);
1345
2008
  const owner = field === void 0 ? void 0 : this.receiverClass(node.object, scope, depth + 1);
1346
2009
  return owner && field !== void 0 ? this.fieldClass(owner, field) : void 0;
1347
2010
  }
@@ -1403,11 +2066,29 @@ var ProjectIndex = class {
1403
2066
  }
1404
2067
  }
1405
2068
  };
1406
- /** Local variables whose class is known: `const x = new X()` and `const x: X = ...`. */
2069
+ /** `x` and `X` for a parameter `x: X` or `x = new X()`. Parameter properties are fields, not locals. */
2070
+ function typedParameter(param) {
2071
+ const binding = param.type === "AssignmentPattern" ? param.left : param;
2072
+ if (binding.type !== "Identifier") return void 0;
2073
+ const type = typeName(binding.typeAnnotation) ?? (param.type === "AssignmentPattern" ? newName(param.right) : void 0);
2074
+ return type === void 0 ? void 0 : [binding.name, type];
2075
+ }
2076
+ /**
2077
+ * Locals whose class is known: typed parameters of `fn` and the functions inside it, `const x = new X()` and
2078
+ * `const x: X = ...`.
2079
+ */
1407
2080
  function collectLocals(fn) {
1408
2081
  const locals = /* @__PURE__ */ new Map();
2082
+ const addParameters = (node) => {
2083
+ for (const param of node.params) {
2084
+ const found = typedParameter(param);
2085
+ if (found) locals.set(...found);
2086
+ }
2087
+ };
2088
+ addParameters(fn);
1409
2089
  if (!fn.body) return locals;
1410
2090
  walk(fn.body, (node) => {
2091
+ if (isFunctionLike(node)) addParameters(node);
1411
2092
  if (node.type !== "VariableDeclarator" || node.id.type !== "Identifier") return;
1412
2093
  const type = typeName(node.id.typeAnnotation) ?? newName(node.init);
1413
2094
  if (type !== void 0) locals.set(node.id.name, type);
@@ -1428,7 +2109,7 @@ function enclosing(node) {
1428
2109
  }
1429
2110
  return { fn };
1430
2111
  }
1431
- const rule$4 = {
2112
+ const rule$3 = {
1432
2113
  meta: {
1433
2114
  type: "problem",
1434
2115
  docs: {
@@ -1499,6 +2180,7 @@ const rule$4 = {
1499
2180
  };
1500
2181
  // src/rules/padding-lines.ts
1501
2182
  const BLANK_LINE = /\r?\n[\t ]*\r?\n/;
2183
+ const BLANK_LINES = /(\r?\n)(?:[\t ]*\r?\n)+/g;
1502
2184
  const unwrapExport = (node) => (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") && node.declaration ? node.declaration : node;
1503
2185
  const isFunctionValue = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "TSEmptyBodyFunctionExpression";
1504
2186
  const isImport = (node) => node.type === "ImportDeclaration" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
@@ -1515,12 +2197,16 @@ const isOverloadPair = (previous, current) => {
1515
2197
  const name = functionStatementName(previous);
1516
2198
  return unwrapExport(previous).type === "TSDeclareFunction" && name !== void 0 && name === functionStatementName(current);
1517
2199
  };
1518
- const isMethodProperty = (property) => property.type === "Property" && (property.method || property.kind !== "init" || isFunctionValue(property.value));
1519
- const rule$3 = {
2200
+ /**
2201
+ * A multi-line method, getter, setter or property holding a function. Single-line ones need no blank lines,
2202
+ * as in `lines-between-class-members`.
2203
+ */
2204
+ const isMethodProperty = (property) => property.type === "Property" && property.loc.start.line !== property.loc.end.line && (property.method || property.kind !== "init" || isFunctionValue(property.value));
2205
+ const rule$2 = {
1520
2206
  meta: {
1521
2207
  type: "layout",
1522
2208
  docs: {
1523
- description: "Require blank lines after imports, around top-level functions and around object methods.",
2209
+ description: "Require blank lines after imports, around top-level functions and around object methods, and disallow blank lines between function overloads.",
1524
2210
  url: docsUrl("padding-lines")
1525
2211
  },
1526
2212
  fixable: "whitespace",
@@ -1528,7 +2214,8 @@ const rule$3 = {
1528
2214
  messages: {
1529
2215
  afterImports: "Expected a blank line after the import declarations.",
1530
2216
  aroundFunctions: "Expected a blank line between a function and the adjacent statement.",
1531
- betweenObjectMethods: "Expected a blank line around methods in an object literal."
2217
+ betweenObjectMethods: "Expected a blank line around methods in an object literal.",
2218
+ betweenOverloads: "Unexpected blank line between overloads of the same function."
1532
2219
  }
1533
2220
  },
1534
2221
  create(context) {
@@ -1547,12 +2234,23 @@ const rule$3 = {
1547
2234
  }
1548
2235
  });
1549
2236
  };
2237
+ /** Overload signatures and the implementation form one group without blank lines; comments are kept. */
2238
+ const forbidBlankLines = (previous, current) => {
2239
+ const textBetween = text.slice(previous.range[1], current.range[0]);
2240
+ if (!BLANK_LINE.test(textBetween)) return;
2241
+ context.report({
2242
+ node: current,
2243
+ messageId: "betweenOverloads",
2244
+ fix: (fixer) => fixer.replaceTextRange([previous.range[1], current.range[0]], textBetween.replace(BLANK_LINES, "$1"))
2245
+ });
2246
+ };
1550
2247
  const checkStatements = (statements) => {
1551
2248
  for (let index = 1; index < statements.length; index++) {
1552
2249
  const previous = statements[index - 1];
1553
2250
  const current = statements[index];
1554
2251
  if (isImport(previous) && !isImport(current)) requireBlankLine(previous, current, "afterImports");
1555
- else if ((isFunctionStatement(previous) || isFunctionStatement(current)) && !isOverloadPair(previous, current)) requireBlankLine(previous, current, "aroundFunctions");
2252
+ else if (isOverloadPair(previous, current)) forbidBlankLines(previous, current);
2253
+ else if (isFunctionStatement(previous) || isFunctionStatement(current)) requireBlankLine(previous, current, "aroundFunctions");
1556
2254
  }
1557
2255
  };
1558
2256
  return {
@@ -1569,51 +2267,12 @@ const rule$3 = {
1569
2267
  };
1570
2268
  }
1571
2269
  };
1572
- // src/rules/private-members-last.ts
1573
- const isMethodLike = (member) => (member.type === "MethodDefinition" || member.type === "TSAbstractMethodDefinition") && member.kind !== "constructor";
1574
- const isPrivate = (member) => "accessibility" in member && member.accessibility === "private" || "key" in member && member.key.type === "PrivateIdentifier";
1575
- const memberName = (member) => {
1576
- const key = "key" in member ? member.key : void 0;
1577
- if (key && "name" in key && typeof key.name === "string") return key.name;
1578
- if (key && "value" in key && typeof key.value === "string") return key.value;
1579
- return "<computed>";
1580
- };
1581
- const rule$2 = {
1582
- meta: {
1583
- type: "suggestion",
1584
- docs: {
1585
- description: "Require public methods to be placed above private methods.",
1586
- url: docsUrl("private-members-last")
1587
- },
1588
- schema: [],
1589
- messages: { privateMembersLast: "Public method '{{name}}' must be placed above all private methods (private method '{{privateName}}' comes first)." }
1590
- },
1591
- create(context) {
1592
- return { ClassBody(node) {
1593
- let firstPrivate;
1594
- for (const member of node.body) {
1595
- if (!isMethodLike(member)) continue;
1596
- if (isPrivate(member)) {
1597
- firstPrivate ??= member;
1598
- continue;
1599
- }
1600
- if (firstPrivate !== void 0) context.report({
1601
- node: member,
1602
- messageId: "privateMembersLast",
1603
- data: {
1604
- name: memberName(member),
1605
- privateName: memberName(firstPrivate)
1606
- }
1607
- });
1608
- }
1609
- } };
1610
- }
1611
- };
1612
2270
  // src/rules/step-placeholders.ts
1613
2271
  /** The same pattern `@step` uses at runtime: the path is taken as written, so `{{ name }}` looks up " name ". */
1614
2272
  const NAMED = /\{\{(.*?)\}\}/g;
1615
2273
  const INDEX = /\[\[(\d+)\]\]/g;
1616
- const SINGLE_BRACES = /(^|[^{])\{([A-Za-z_$][\w$]*(?:\.[\w$]+)*)\}(?!\})/g;
2274
+ /** A lookbehind instead of a consumed prefix character, so adjacent placeholders (`{a}{b}`) are all found. */
2275
+ const SINGLE_BRACES = /(?<!\{)\{([A-Za-z_$][\w$]*(?:\.[\w$]+)*)\}(?!\})/g;
1617
2276
  const findAll = (pattern, text) => {
1618
2277
  const regex = new RegExp(pattern.source, "g");
1619
2278
  const found = [];
@@ -1625,13 +2284,18 @@ const paramName = (param) => {
1625
2284
  const binding = target.type === "AssignmentPattern" ? target.left : target.type === "RestElement" ? target.argument : target;
1626
2285
  return binding.type === "Identifier" ? binding.name : void 0;
1627
2286
  };
2287
+ /** True when a placeholder path starts at a parameter, or at `this` (a property of the instance). */
2288
+ const isKnownRoot = (path, names) => {
2289
+ const [root] = path.split(".");
2290
+ return root === "this" || names.includes(root);
2291
+ };
1628
2292
  /**
1629
2293
  * What is wrong with the path of a `{{path}}` placeholder, if anything. `@step` reads the path exactly as written,
1630
2294
  * so spaces around it either fail the parameter lookup or read a property that does not exist.
1631
2295
  */
1632
2296
  const namedProblem = (path, names) => {
1633
2297
  const trimmed = path.trim();
1634
- const isParameter = (value) => names.includes(value.split(".")[0]);
2298
+ const isParameter = (value) => isKnownRoot(value, names);
1635
2299
  if (trimmed !== path && isParameter(trimmed)) return "whitespace";
1636
2300
  return trimmed === path && isParameter(path) ? void 0 : "unknownParameter";
1637
2301
  };
@@ -1713,14 +2377,14 @@ const rule$1 = {
1713
2377
  });
1714
2378
  }
1715
2379
  for (const match of findAll(SINGLE_BRACES, raw)) {
1716
- const placeholder = match[2];
1717
- const from = start + match.index + match[1].length;
2380
+ const placeholder = match[1];
2381
+ const from = start + match.index;
1718
2382
  const range = [from, from + placeholder.length + 2];
1719
2383
  const data = {
1720
2384
  found: `{${placeholder}}`,
1721
2385
  expected: `{{${placeholder}}}`
1722
2386
  };
1723
- if (names.includes(placeholder.split(".")[0])) context.report({
2387
+ if (isKnownRoot(placeholder, names)) context.report({
1724
2388
  node: description,
1725
2389
  messageId: "singleBraces",
1726
2390
  data,
@@ -1741,19 +2405,23 @@ const STEP_LAYERS = /* @__PURE__ */ new Set([
1741
2405
  "asserter",
1742
2406
  "scenario"
1743
2407
  ]);
2408
+ const FUNCTION_VALUES = /* @__PURE__ */ new Set(["ArrowFunctionExpression", "FunctionExpression"]);
2409
+ /** Public instance members are steps; static members are helpers (such as factories). */
2410
+ const isPublicInstance = (member) => !member.static && member.key.type !== "PrivateIdentifier" && member.accessibility !== "private" && member.accessibility !== "protected";
1744
2411
  // src/rules/index.ts
1745
2412
  const rules = {
1746
- "architecture-boundaries": rule$12,
1747
- "class-matches-filename": rule$11,
2413
+ "architecture-boundaries": rule$13,
2414
+ "class-matches-filename": rule$12,
2415
+ "director-composes-builders": rule$11,
1748
2416
  "expect-from-support": rule$10,
1749
2417
  "file-naming": rule$9,
1750
2418
  "lines-between-class-members": rule$8,
1751
- "no-direct-construction-in-tests": rule$7,
1752
- "no-expect-in-tests": rule$6,
1753
- "no-hard-waits": rule$5,
1754
- "no-nested-polling": rule$4,
1755
- "padding-lines": rule$3,
1756
- "private-members-last": rule$2,
2419
+ "member-ordering": rule$7,
2420
+ "no-direct-construction-in-tests": rule$6,
2421
+ "no-expect-in-tests": rule$5,
2422
+ "no-hard-waits": rule$4,
2423
+ "no-nested-polling": rule$3,
2424
+ "padding-lines": rule$2,
1757
2425
  "step-placeholders": rule$1,
1758
2426
  "step-required": {
1759
2427
  meta: {
@@ -1763,24 +2431,35 @@ const rules = {
1763
2431
  url: docsUrl("step-required")
1764
2432
  },
1765
2433
  schema: [],
1766
- messages: { missingStep: "Public method '{{method}}' in a {{layer}} needs a @step decorator so it is visible in the report." }
2434
+ messages: {
2435
+ missingStep: "Public method '{{method}}' in a {{layer}} needs a @step decorator so it is visible in the report.",
2436
+ functionProperty: "Public function property '{{method}}' in a {{layer}} cannot carry a @step decorator; make it a method with @step."
2437
+ }
1767
2438
  },
1768
2439
  create(context) {
1769
2440
  const conventions = conventionsFor(context);
1770
2441
  const info = classify(context.filename, conventions, rootFor(context, conventions));
1771
2442
  const layer = info?.kind === "top-scenario" ? "scenario" : info?.layer;
1772
2443
  if (layer === void 0 || !STEP_LAYERS.has(layer)) return {};
1773
- return { MethodDefinition(node) {
1774
- if (node.kind !== "method" || node.key.type === "PrivateIdentifier" || node.accessibility === "private" || node.accessibility === "protected" || node.value.type === "TSEmptyBodyFunctionExpression" || node.decorators.some((decorator) => isStepDecorator(decorator, conventions.stepDecorators))) return;
2444
+ const report = (key, messageId) => {
1775
2445
  context.report({
1776
- node: node.key,
1777
- messageId: "missingStep",
2446
+ node: key,
2447
+ messageId,
1778
2448
  data: {
1779
- method: context.sourceCode.getText(node.key),
2449
+ method: context.sourceCode.getText(key),
1780
2450
  layer
1781
2451
  }
1782
2452
  });
1783
- } };
2453
+ };
2454
+ return {
2455
+ MethodDefinition(node) {
2456
+ if (node.kind !== "method" || !isPublicInstance(node) || node.value.type === "TSEmptyBodyFunctionExpression" || node.decorators.some((decorator) => isStepDecorator(decorator, conventions.stepDecorators))) return;
2457
+ report(node.key, "missingStep");
2458
+ },
2459
+ PropertyDefinition(node) {
2460
+ if (isPublicInstance(node) && node.value && FUNCTION_VALUES.has(node.value.type)) report(node.key, "functionProperty");
2461
+ }
2462
+ };
1784
2463
  }
1785
2464
  }
1786
2465
  };
@@ -1806,4 +2485,4 @@ Object.defineProperty(exports, "rules", {
1806
2485
  }
1807
2486
  });
1808
2487
 
1809
- //# sourceMappingURL=rules-COk7kmEU.cjs.map
2488
+ //# sourceMappingURL=rules-T_C5segG.cjs.map