@cerios/sparta-lint-rules 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1770 @@
1
+ import path from "node:path";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { parseSync } from "oxc-parser";
4
+ // src/utils/ast.ts
5
+ const isIdentifier = (node, name) => node?.type === "Identifier" && node.name === name;
6
+ /** The value of a string literal node, or `undefined` for any other node. */
7
+ const stringValue = (node) => node?.type === "Literal" && typeof node.value === "string" ? node.value : void 0;
8
+ /** True for `@step` and `@step("...")` decorators, or any of the given decorator `names`. */
9
+ const isStepDecorator = (decorator, names) => {
10
+ const { expression } = decorator;
11
+ const callee = expression.type === "CallExpression" ? expression.callee : expression;
12
+ return callee.type === "Identifier" && names.has(callee.name);
13
+ };
14
+ // src/utils/docs.ts
15
+ const REPOSITORY = "https://github.com/CeriosTesting/sparta-lint-rules";
16
+ const docsUrl = (ruleName) => `${REPOSITORY}/blob/main/docs/rules/${ruleName}.md`;
17
+ // src/utils/conventions.ts
18
+ /** The standard layer folders, with the layer the architecture rules know them as and their file name suffix. */
19
+ const LAYER_FOLDERS = {
20
+ asserters: {
21
+ layer: "asserter",
22
+ suffix: "asserter"
23
+ },
24
+ builders: {
25
+ layer: "builder",
26
+ suffix: "builder"
27
+ },
28
+ clients: {
29
+ layer: "client",
30
+ suffix: "client"
31
+ },
32
+ components: {
33
+ layer: "component",
34
+ suffix: "component"
35
+ },
36
+ containers: { layer: "container" },
37
+ databases: { layer: "database" },
38
+ directors: {
39
+ layer: "director",
40
+ suffix: "director"
41
+ },
42
+ factories: { suffix: "factory" },
43
+ pages: {
44
+ layer: "page",
45
+ suffix: "page"
46
+ },
47
+ repositories: {
48
+ layer: "repository",
49
+ suffix: "repository"
50
+ },
51
+ scenarios: {
52
+ layer: "scenario",
53
+ suffix: "scenario"
54
+ },
55
+ screens: {
56
+ layer: "screen",
57
+ suffix: "screen"
58
+ },
59
+ services: {
60
+ layer: "service",
61
+ suffix: "service"
62
+ },
63
+ steppers: {
64
+ layer: "stepper",
65
+ suffix: "stepper"
66
+ }
67
+ };
68
+ const AREAS = [
69
+ "api",
70
+ "database",
71
+ "mobile",
72
+ "ui"
73
+ ];
74
+ /** Folders directly below the sparta folder that are not areas. */
75
+ const TOP_LEVEL_FOLDERS = [
76
+ "common",
77
+ "fixtures",
78
+ "scenarios",
79
+ "support"
80
+ ];
81
+ const POLLING_METHODS = [
82
+ "toPass",
83
+ "toPassAndReturn",
84
+ "poll",
85
+ "pollAndReturn"
86
+ ];
87
+ const PREFIX = "[@cerios/sparta-lint-rules]";
88
+ var SettingsError = class extends Error {
89
+ constructor(where, problem) {
90
+ super(`${PREFIX} settings.sparta${where}: ${problem}`);
91
+ this.name = "SettingsError";
92
+ }
93
+ };
94
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
95
+ const distance = (a, b) => {
96
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
97
+ for (let i = 1; i <= a.length; i++) {
98
+ const current = [i];
99
+ for (let j = 1; j <= b.length; j++) current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
100
+ previous = current;
101
+ }
102
+ return previous[b.length];
103
+ };
104
+ /** `; did you mean "x"?` for the closest candidate, if it is close enough to be a typo. */
105
+ const suggest = (value, candidates) => {
106
+ const [best] = candidates.map((candidate) => ({
107
+ candidate,
108
+ score: distance(value.toLowerCase(), candidate.toLowerCase())
109
+ })).toSorted((a, b) => a.score - b.score);
110
+ return best && best.score <= Math.max(2, Math.floor(best.candidate.length / 3)) ? `; did you mean ${JSON.stringify(best.candidate)}?` : "";
111
+ };
112
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
113
+ function record(value, where) {
114
+ if (!isRecord(value)) throw new SettingsError(where, `must be an object, got ${JSON.stringify(value)}.`);
115
+ return value;
116
+ }
117
+ function checkKeys(value, allowed, where) {
118
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new SettingsError(where, `unknown setting ${JSON.stringify(key)}${suggest(key, allowed)}`);
119
+ }
120
+ function nonEmptyString(value, where) {
121
+ if (typeof value !== "string" || value.trim() === "") throw new SettingsError(where, `must be a non-empty string, got ${JSON.stringify(value)}.`);
122
+ return value;
123
+ }
124
+ function folderName(value, where) {
125
+ const name = nonEmptyString(value, where);
126
+ if (/[/\\]/.test(name) || name === "." || name === "..") throw new SettingsError(where, `must be a single folder name, got ${JSON.stringify(name)}.`);
127
+ return name;
128
+ }
129
+ function identifiers(value, where) {
130
+ if (!Array.isArray(value)) throw new SettingsError(where, `must be an array of names, got ${JSON.stringify(value)}.`);
131
+ return value.map((item, index) => {
132
+ const name = nonEmptyString(item, `${where}[${index}]`);
133
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new SettingsError(`${where}[${index}]`, `must be an identifier, got ${JSON.stringify(name)}.`);
134
+ return name;
135
+ });
136
+ }
137
+ /**
138
+ * Maps the project's own names onto standard ones. A name that is already standard may only map onto itself,
139
+ * and `reserved` names may not be used at all, so a setting can never turn one concept into another.
140
+ */
141
+ function mapping(value, where, targets, describe, reserved = []) {
142
+ const result = /* @__PURE__ */ new Map();
143
+ for (const [name, target] of Object.entries(record(value, where))) {
144
+ const at = `${where}.${name}`;
145
+ folderName(name, at);
146
+ if (typeof target !== "string" || !targets.includes(target)) throw new SettingsError(at, `unknown ${describe} ${JSON.stringify(target)}${typeof target === "string" ? suggest(target, targets) : ""}. Use one of: ${targets.join(", ")}.`);
147
+ if (targets.includes(name) && name !== target) throw new SettingsError(at, `${JSON.stringify(name)} is already the standard ${describe} ${JSON.stringify(name)}.`);
148
+ if (reserved.includes(name)) throw new SettingsError(at, `${JSON.stringify(name)} is a reserved SPARTA folder.`);
149
+ result.set(name, target);
150
+ }
151
+ return result;
152
+ }
153
+ /** `@app/*`, `@app/` and `@app` all become the prefix `@app/`. */
154
+ function aliasPrefix(alias, where) {
155
+ const prefix = `${alias.replace(/\/?\*?$/, "")}/`;
156
+ if (prefix === "/" || alias.startsWith(".") || alias.startsWith("/")) throw new SettingsError(where, `must be an alias such as "@app/*", got ${JSON.stringify(alias)}.`);
157
+ return prefix;
158
+ }
159
+ const SETTINGS_KEYS = [
160
+ "root",
161
+ "folders",
162
+ "areas",
163
+ "layers",
164
+ "aliases",
165
+ "supportModule",
166
+ "pollingMethods",
167
+ "stepDecorators",
168
+ "expectNames"
169
+ ];
170
+ function parseFolders(value) {
171
+ const folders = value === void 0 ? {} : record(value, ".folders");
172
+ checkKeys(folders, ["sparta", "tests"], ".folders");
173
+ const spartaFolder = folders.sparta === void 0 ? "sparta" : folderName(folders.sparta, ".folders.sparta");
174
+ const testsFolder = folders.tests === void 0 ? "tests" : folderName(folders.tests, ".folders.tests");
175
+ if (spartaFolder === testsFolder) throw new SettingsError(".folders", `sparta and tests must be different folders, both are ${JSON.stringify(spartaFolder)}.`);
176
+ return {
177
+ spartaFolder,
178
+ testsFolder
179
+ };
180
+ }
181
+ /** The standard names, each mapped onto itself, plus the project's own names. */
182
+ function withStandard(standard, custom) {
183
+ return new Map([...standard.map((name) => [name, name]), ...custom ?? []]);
184
+ }
185
+ function parseAliases(value) {
186
+ const aliases = /* @__PURE__ */ new Map([["@sparta/", "sparta"], ["@tests/", "tests"]]);
187
+ if (value === void 0) return aliases;
188
+ for (const [alias, target] of Object.entries(record(value, ".aliases"))) {
189
+ const at = `.aliases.${alias}`;
190
+ const prefix = aliasPrefix(alias, at);
191
+ if (target !== "sparta" && target !== "tests") throw new SettingsError(at, `must point to "sparta" or "tests", got ${JSON.stringify(target)}.`);
192
+ if (aliases.has(prefix) && aliases.get(prefix) !== target) throw new SettingsError(at, `${JSON.stringify(alias)} already points to ${JSON.stringify(aliases.get(prefix))}.`);
193
+ aliases.set(prefix, target);
194
+ }
195
+ return aliases;
196
+ }
197
+ /** The default names plus the configured extra ones. */
198
+ const withExtra = (defaults, value, where) => /* @__PURE__ */ new Set([...defaults, ...value === void 0 ? [] : identifiers(value, where)]);
199
+ function buildPatterns(spartaFolder, testsFolder, areas) {
200
+ const sparta = escape(spartaFolder);
201
+ const tests = escape(testsFolder);
202
+ const areaNames = [...areas.keys()].map(escape).join("|");
203
+ return {
204
+ area: new RegExp(`/${sparta}/(${areaNames})/([^/]+)(?:/([^/]+))?`),
205
+ layer: new RegExp(`/${sparta}/(?:${areaNames})/[^/]+/([^/]+)/`),
206
+ top: new RegExp(`/${sparta}/(${TOP_LEVEL_FOLDERS.join("|")})/`),
207
+ checked: new RegExp(`/(?:${sparta}|${tests})/`),
208
+ sparta: new RegExp(`/${sparta}/`),
209
+ tests: new RegExp(`/${tests}/`),
210
+ framework: new RegExp(`/${tests}/framework/`)
211
+ };
212
+ }
213
+ const STANDARD_LAYER_FOLDERS = Object.keys(LAYER_FOLDERS);
214
+ /**
215
+ * Validates `settings.sparta` and resolves it against the defaults. Throws a descriptive error for anything it
216
+ * does not understand, so a typo cannot silently weaken the checks. A relative `root` resolves against `cwd`.
217
+ */
218
+ function parseSettings(raw, cwd) {
219
+ const settings = raw === void 0 || raw === null ? {} : record(raw, "");
220
+ checkKeys(settings, SETTINGS_KEYS, "");
221
+ const root = settings.root === void 0 ? void 0 : path.resolve(cwd, nonEmptyString(settings.root, ".root")).split("\\").join("/");
222
+ const { spartaFolder, testsFolder } = parseFolders(settings.folders);
223
+ const areas = withStandard(AREAS, settings.areas === void 0 ? void 0 : mapping(settings.areas, ".areas", AREAS, "area", TOP_LEVEL_FOLDERS));
224
+ const layerFolders = withStandard(STANDARD_LAYER_FOLDERS, settings.layers === void 0 ? void 0 : mapping(settings.layers, ".layers", STANDARD_LAYER_FOLDERS, "layer folder", ["common"]));
225
+ return {
226
+ key: JSON.stringify(raw ?? null) + (root ?? ""),
227
+ root,
228
+ spartaFolder,
229
+ testsFolder,
230
+ areas,
231
+ layerFolders,
232
+ aliases: [...parseAliases(settings.aliases)].toSorted(([a], [b]) => b.length - a.length),
233
+ supportModule: settings.supportModule === void 0 ? "@sparta/support" : nonEmptyString(settings.supportModule, ".supportModule"),
234
+ pollingMethods: withExtra(POLLING_METHODS, settings.pollingMethods, ".pollingMethods"),
235
+ stepDecorators: withExtra(["step"], settings.stepDecorators, ".stepDecorators"),
236
+ expectNames: withExtra([], settings.expectNames, ".expectNames"),
237
+ patterns: buildPatterns(spartaFolder, testsFolder, areas)
238
+ };
239
+ }
240
+ parseSettings(void 0, process.cwd());
241
+ // src/utils/sparta-paths.ts
242
+ const normalize = (value) => value.split("\\").join("/");
243
+ const TOP_LEVEL_KINDS = {
244
+ fixtures: "fixture",
245
+ scenarios: "top-scenario"
246
+ };
247
+ /** The standard layer folder that a project's folder name follows, if any. */
248
+ const standardFolder = (conventions, folder) => folder === void 0 ? void 0 : conventions.layerFolders.get(folder);
249
+ const caseInsensitivePaths = process.platform === "win32";
250
+ /**
251
+ * The part of `filename` below the project `root`, with a leading `/` (`/sparta/ui/...`), or `undefined` for files
252
+ * outside the root. Only this part is matched against the SPARTA folder names, so folders above the project (such
253
+ * as a checkout inside a folder named `tests`) never change how a file is classified.
254
+ */
255
+ function projectPath(filename, root) {
256
+ const file = normalize(filename);
257
+ const base = normalize(root).replace(/\/$/, "");
258
+ const prefix = file.slice(0, base.length);
259
+ return (caseInsensitivePaths ? prefix.toLowerCase() === base.toLowerCase() : prefix === base) && file[base.length] === "/" ? file.slice(base.length) : void 0;
260
+ }
261
+ /** What a file is in the SPARTA architecture, judged by its path below `root`. */
262
+ function classify(filename, conventions, root) {
263
+ const file = projectPath(filename, root);
264
+ const { patterns } = conventions;
265
+ if (file === void 0 || patterns.framework.test(file)) return void 0;
266
+ if (patterns.tests.test(file)) return { kind: "test" };
267
+ const area = file.match(patterns.area);
268
+ if (area) {
269
+ const [, areaName, group, folder] = area;
270
+ const base = file.match(/-base-(client|repository|service)(?:\.[cm]?[jt]s)?$/)?.[1];
271
+ const standard = standardFolder(conventions, folder);
272
+ const layer = base ? `base-${base}` : standard === void 0 ? void 0 : LAYER_FOLDERS[standard].layer;
273
+ return {
274
+ kind: group === "common" ? "area-common" : "group",
275
+ area: conventions.areas.get(areaName),
276
+ areaFolder: areaName,
277
+ group,
278
+ layer
279
+ };
280
+ }
281
+ const top = file.match(patterns.top)?.[1];
282
+ return top ? { kind: TOP_LEVEL_KINDS[top] ?? "shared" } : void 0;
283
+ }
284
+ /** Project root per directory, kept for the lifetime of the linter process. */
285
+ const rootCache = /* @__PURE__ */ new Map();
286
+ /**
287
+ * The project root of a file: the nearest directory, from the file upwards, that contains a `package.json`.
288
+ * Falls back to the working directory when there is none.
289
+ */
290
+ function projectRoot(filename) {
291
+ const visited = [];
292
+ let root;
293
+ for (let dir = path.dirname(path.resolve(filename));;) {
294
+ root = rootCache.get(dir);
295
+ if (root !== void 0) break;
296
+ visited.push(dir);
297
+ if (existsSync(path.join(dir, "package.json"))) {
298
+ root = normalize(dir);
299
+ break;
300
+ }
301
+ const parent = path.dirname(dir);
302
+ if (parent === dir) {
303
+ root = normalize(process.cwd());
304
+ break;
305
+ }
306
+ dir = parent;
307
+ }
308
+ for (const dir of visited) rootCache.set(dir, root);
309
+ return root;
310
+ }
311
+ /**
312
+ * Resolves a relative or aliased import (`@sparta/*`, `@tests/*` and `settings.sparta.aliases`) to an absolute,
313
+ * normalized path. Other imports are ignored. Aliases resolve against `root`.
314
+ */
315
+ function resolveImport(filename, request, root, conventions) {
316
+ for (const [prefix, target] of conventions.aliases) if (request.startsWith(prefix)) return `${root}/${target === "sparta" ? conventions.spartaFolder : conventions.testsFolder}/${request.slice(prefix.length)}`;
317
+ if (request.startsWith(".")) return normalize(path.resolve(path.dirname(filename), request));
318
+ }
319
+ /** The layer folder a file lives in (`steppers`, `pages`, ...), with `sparta/scenarios/` counting as `scenarios`. */
320
+ const layerFolder = (filename, conventions, root) => {
321
+ const file = projectPath(filename, root);
322
+ if (file === void 0) return void 0;
323
+ if (file.match(conventions.patterns.top)?.[1] === "scenarios") return {
324
+ name: "scenarios",
325
+ standard: "scenarios"
326
+ };
327
+ const folder = file.match(conventions.patterns.layer)?.[1];
328
+ return folder === void 0 ? void 0 : {
329
+ name: folder,
330
+ standard: standardFolder(conventions, folder)
331
+ };
332
+ };
333
+ /** The file name suffix the files in a layer folder must use (`stepper` for `steppers/`), if it has one. */
334
+ const layerSuffix = (folder) => folder?.standard === void 0 ? void 0 : LAYER_FOLDERS[folder.standard].suffix;
335
+ /** True for files that follow the layer naming convention (layer folders and fixtures). */
336
+ const isLayerFile = (filename, conventions, root) => layerSuffix(layerFolder(filename, conventions, root)) !== void 0 || projectPath(filename, root)?.match(conventions.patterns.top)?.[1] === "fixtures";
337
+ // src/utils/settings.ts
338
+ /** Parsed settings per raw settings and working directory, kept for the lifetime of the linter process. */
339
+ const cache = /* @__PURE__ */ new Map();
340
+ /** The validated `settings.sparta` for this file. Throws a descriptive error for invalid settings. */
341
+ function conventionsFor(context) {
342
+ const raw = context.settings?.sparta;
343
+ const key = `${context.cwd}\0${JSON.stringify(raw ?? null)}`;
344
+ let conventions = cache.get(key);
345
+ if (conventions === void 0) {
346
+ conventions = parseSettings(raw, context.cwd);
347
+ cache.set(key, conventions);
348
+ }
349
+ return conventions;
350
+ }
351
+ /**
352
+ * The project root the aliases resolve against: `settings.sparta.root` when set (relative paths resolve against
353
+ * the linter's working directory), otherwise the nearest folder with a `package.json`.
354
+ */
355
+ const rootFor = (context, conventions = conventionsFor(context)) => conventions.root ?? projectRoot(context.filename);
356
+ // src/rules/architecture-boundaries.ts
357
+ const DATABASE_LAYERS = [
358
+ "asserter",
359
+ "base-repository",
360
+ "base-service",
361
+ "container",
362
+ "database",
363
+ "repository",
364
+ "scenario",
365
+ "service",
366
+ "stepper"
367
+ ];
368
+ /** The UI layers; `view` is the area's name for a page (`page` for web, `screen` for mobile). */
369
+ const uiLayers = (view) => ({
370
+ component: /* @__PURE__ */ new Set([
371
+ view,
372
+ "stepper",
373
+ "asserter",
374
+ "scenario",
375
+ "builder",
376
+ "director"
377
+ ]),
378
+ [view]: /* @__PURE__ */ new Set([
379
+ "stepper",
380
+ "asserter",
381
+ "scenario",
382
+ "builder",
383
+ "director"
384
+ ]),
385
+ stepper: /* @__PURE__ */ new Set(["asserter", "scenario"]),
386
+ asserter: /* @__PURE__ */ new Set([
387
+ "stepper",
388
+ "asserter",
389
+ "scenario"
390
+ ]),
391
+ builder: /* @__PURE__ */ new Set([
392
+ view,
393
+ "component",
394
+ "stepper",
395
+ "asserter",
396
+ "scenario"
397
+ ]),
398
+ director: /* @__PURE__ */ new Set([
399
+ view,
400
+ "component",
401
+ "stepper",
402
+ "asserter",
403
+ "scenario"
404
+ ]),
405
+ scenario: /* @__PURE__ */ new Set([view, "component"])
406
+ });
407
+ /** Forbidden target layers inside the same area (API -> API, UI -> UI, database -> database, mobile -> mobile). */
408
+ const FORBIDDEN_LAYERS = {
409
+ api: {
410
+ client: /* @__PURE__ */ new Set([
411
+ "client",
412
+ "service",
413
+ "base-service",
414
+ "stepper",
415
+ "asserter",
416
+ "scenario"
417
+ ]),
418
+ "base-client": /* @__PURE__ */ new Set([
419
+ "client",
420
+ "base-client",
421
+ "service",
422
+ "base-service",
423
+ "stepper",
424
+ "asserter",
425
+ "scenario"
426
+ ]),
427
+ service: /* @__PURE__ */ new Set([
428
+ "service",
429
+ "stepper",
430
+ "asserter",
431
+ "scenario"
432
+ ]),
433
+ "base-service": /* @__PURE__ */ new Set([
434
+ "service",
435
+ "base-service",
436
+ "stepper",
437
+ "asserter",
438
+ "scenario"
439
+ ]),
440
+ stepper: /* @__PURE__ */ new Set([
441
+ "client",
442
+ "base-client",
443
+ "asserter",
444
+ "scenario"
445
+ ]),
446
+ asserter: /* @__PURE__ */ new Set([
447
+ "stepper",
448
+ "asserter",
449
+ "scenario"
450
+ ]),
451
+ scenario: /* @__PURE__ */ new Set([
452
+ "service",
453
+ "base-service",
454
+ "client",
455
+ "base-client"
456
+ ])
457
+ },
458
+ database: {
459
+ repository: /* @__PURE__ */ new Set([
460
+ "service",
461
+ "base-service",
462
+ "stepper",
463
+ "asserter",
464
+ "scenario"
465
+ ]),
466
+ "base-repository": /* @__PURE__ */ new Set([
467
+ "repository",
468
+ "base-repository",
469
+ "service",
470
+ "base-service",
471
+ "stepper",
472
+ "asserter",
473
+ "scenario"
474
+ ]),
475
+ service: /* @__PURE__ */ new Set([
476
+ "service",
477
+ "stepper",
478
+ "asserter",
479
+ "scenario"
480
+ ]),
481
+ "base-service": /* @__PURE__ */ new Set([
482
+ "service",
483
+ "base-service",
484
+ "stepper",
485
+ "asserter",
486
+ "scenario"
487
+ ]),
488
+ database: new Set(DATABASE_LAYERS),
489
+ container: new Set(DATABASE_LAYERS.filter((layer) => layer !== "database")),
490
+ stepper: /* @__PURE__ */ new Set([
491
+ "repository",
492
+ "base-repository",
493
+ "asserter",
494
+ "scenario"
495
+ ]),
496
+ asserter: /* @__PURE__ */ new Set([
497
+ "repository",
498
+ "base-repository",
499
+ "stepper",
500
+ "asserter",
501
+ "scenario"
502
+ ]),
503
+ scenario: /* @__PURE__ */ new Set([
504
+ "service",
505
+ "base-service",
506
+ "repository",
507
+ "base-repository"
508
+ ])
509
+ },
510
+ mobile: uiLayers("screen"),
511
+ ui: uiLayers("page")
512
+ };
513
+ const DATABASE_ACCESS = [
514
+ "repository",
515
+ "base-repository",
516
+ "service",
517
+ "base-service",
518
+ "container",
519
+ "database"
520
+ ];
521
+ /** Layers that code orchestrating flows (top-level scenarios, tests) must not touch directly. */
522
+ const FORBIDDEN_FOR_ORCHESTRATION = {
523
+ "top-scenario": {
524
+ api: /* @__PURE__ */ new Set([
525
+ "client",
526
+ "base-client",
527
+ "service",
528
+ "base-service"
529
+ ]),
530
+ database: new Set(DATABASE_ACCESS),
531
+ mobile: /* @__PURE__ */ new Set(["screen", "component"]),
532
+ ui: /* @__PURE__ */ new Set(["page", "component"])
533
+ },
534
+ test: {
535
+ api: /* @__PURE__ */ new Set([
536
+ "client",
537
+ "base-client",
538
+ "service",
539
+ "base-service",
540
+ "stepper",
541
+ "asserter"
542
+ ]),
543
+ database: /* @__PURE__ */ new Set([
544
+ ...DATABASE_ACCESS,
545
+ "stepper",
546
+ "asserter"
547
+ ]),
548
+ mobile: /* @__PURE__ */ new Set([
549
+ "screen",
550
+ "component",
551
+ "stepper",
552
+ "asserter"
553
+ ]),
554
+ ui: /* @__PURE__ */ new Set([
555
+ "page",
556
+ "component",
557
+ "stepper",
558
+ "asserter"
559
+ ])
560
+ }
561
+ };
562
+ const REEXPORT_LAYERS = /* @__PURE__ */ new Set([
563
+ "asserter",
564
+ "client",
565
+ "base-client",
566
+ "base-repository",
567
+ "component",
568
+ "page",
569
+ "repository",
570
+ "scenario",
571
+ "screen",
572
+ "service",
573
+ "base-service",
574
+ "stepper"
575
+ ]);
576
+ const describe = (info, { spartaFolder, testsFolder }) => ({
577
+ group: `${info.areaFolder}/${info.group}${info.layer ? ` ${info.layer}` : ""}`,
578
+ "area-common": `${info.areaFolder}/common`,
579
+ "top-scenario": `${spartaFolder}/scenarios`,
580
+ fixture: `${spartaFolder}/fixtures`,
581
+ shared: `${spartaFolder}/common|support`,
582
+ test: testsFolder
583
+ })[info.kind];
584
+ /** Isolation compares area folders, not area types: `web/` and `ui/` are separate areas even when both follow `ui`. */
585
+ function isolationViolation(source, target) {
586
+ if (target.kind === "test") return source.kind !== "test";
587
+ if (source.kind === "shared") return [
588
+ "group",
589
+ "area-common",
590
+ "fixture",
591
+ "top-scenario"
592
+ ].includes(target.kind);
593
+ if (source.kind === "area-common") {
594
+ if ([
595
+ "fixture",
596
+ "top-scenario",
597
+ "group"
598
+ ].includes(target.kind)) return true;
599
+ return target.kind === "area-common" && target.areaFolder !== source.areaFolder;
600
+ }
601
+ if (source.kind === "group") {
602
+ if (["fixture", "top-scenario"].includes(target.kind)) return true;
603
+ if (target.areaFolder === void 0) return false;
604
+ if (target.areaFolder !== source.areaFolder) return true;
605
+ return target.kind === "group" && target.group !== source.group;
606
+ }
607
+ return false;
608
+ }
609
+ function layerViolation(source, target) {
610
+ if (!target.layer || !target.area) return false;
611
+ if (source.kind === "group" || source.kind === "area-common") {
612
+ if (!source.area || !source.layer) return false;
613
+ return source.areaFolder === target.areaFolder && Boolean(FORBIDDEN_LAYERS[source.area][source.layer]?.has(target.layer));
614
+ }
615
+ if (source.kind === "top-scenario" || source.kind === "test") return FORBIDDEN_FOR_ORCHESTRATION[source.kind][target.area].has(target.layer);
616
+ return false;
617
+ }
618
+ const isForbiddenReexport = (source, target) => target.layer !== void 0 && REEXPORT_LAYERS.has(target.layer) && target.layer !== source.layer && !["fixture", "test"].includes(source.kind);
619
+ const rule$12 = {
620
+ meta: {
621
+ type: "problem",
622
+ docs: {
623
+ description: "Enforce the SPARTA layer and isolation boundaries between imports.",
624
+ url: docsUrl("architecture-boundaries")
625
+ },
626
+ schema: [],
627
+ messages: {
628
+ isolation: "{{source}} must not depend on {{target}} ({{request}}). Move shared code to the area's common/ folder or the top-level common/ folder.",
629
+ layer: "{{source}} must not depend on {{target}} ({{request}}).",
630
+ reexport: "Do not re-export {{target}} outside its layer; this bypasses the architecture boundaries."
631
+ }
632
+ },
633
+ create(context) {
634
+ const filename = context.filename;
635
+ const conventions = conventionsFor(context);
636
+ const root = rootFor(context, conventions);
637
+ const source = classify(filename, conventions, root);
638
+ if (!source) return {};
639
+ const check = (node, request, reexport = false) => {
640
+ if (request === void 0) return;
641
+ const resolved = resolveImport(filename, request, root, conventions);
642
+ const target = resolved ? classify(resolved, conventions, root) : void 0;
643
+ if (!target) return;
644
+ const data = {
645
+ source: describe(source, conventions),
646
+ target: describe(target, conventions),
647
+ request
648
+ };
649
+ if (isolationViolation(source, target)) context.report({
650
+ node,
651
+ messageId: "isolation",
652
+ data
653
+ });
654
+ else if (layerViolation(source, target)) context.report({
655
+ node,
656
+ messageId: "layer",
657
+ data
658
+ });
659
+ else if (reexport && isForbiddenReexport(source, target)) context.report({
660
+ node,
661
+ messageId: "reexport",
662
+ data
663
+ });
664
+ };
665
+ return {
666
+ ImportDeclaration: (node) => check(node, stringValue(node.source)),
667
+ ExportNamedDeclaration: (node) => check(node, stringValue(node.source), true),
668
+ ExportAllDeclaration: (node) => check(node, stringValue(node.source), true),
669
+ ImportExpression: (node) => check(node, stringValue(node.source)),
670
+ TSImportEqualsDeclaration(node) {
671
+ if (node.moduleReference.type === "TSExternalModuleReference") check(node, stringValue(node.moduleReference.expression));
672
+ },
673
+ CallExpression(node) {
674
+ if (node.callee.type === "Identifier" && node.callee.name === "require") check(node, stringValue(node.arguments[0]));
675
+ }
676
+ };
677
+ }
678
+ };
679
+ // src/rules/class-matches-filename.ts
680
+ const toPascalCase = (name) => name.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
681
+ const classOf = (statement) => {
682
+ const node = (statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && statement.declaration ? statement.declaration : statement;
683
+ return node.type === "ClassDeclaration" ? node : void 0;
684
+ };
685
+ const rule$11 = {
686
+ meta: {
687
+ type: "suggestion",
688
+ docs: {
689
+ description: "Require a layer file to contain exactly one class, named after the file in PascalCase.",
690
+ url: docsUrl("class-matches-filename")
691
+ },
692
+ schema: [],
693
+ messages: {
694
+ name: "Class '{{found}}' must be named '{{expected}}' to match the file name.",
695
+ single: "A layer file contains exactly one class; move '{{found}}' to its own file."
696
+ }
697
+ },
698
+ create(context) {
699
+ const conventions = conventionsFor(context);
700
+ if (!isLayerFile(context.filename, conventions, rootFor(context, conventions))) return {};
701
+ const expected = toPascalCase(path.basename(context.filename).replace(/\.ts$/, ""));
702
+ return { Program(program) {
703
+ program.body.map(classOf).filter((node) => node !== void 0).forEach((node, index) => {
704
+ const found = node.id?.name ?? "(anonymous)";
705
+ if (index > 0) context.report({
706
+ node: node.id ?? node,
707
+ messageId: "single",
708
+ data: { found }
709
+ });
710
+ else if (found !== expected) context.report({
711
+ node: node.id ?? node,
712
+ messageId: "name",
713
+ data: {
714
+ found,
715
+ expected
716
+ }
717
+ });
718
+ });
719
+ } };
720
+ }
721
+ };
722
+ // src/rules/expect-from-support.ts
723
+ /** Files inside the sparta folder, except its support folder (where `expect` itself is defined). */
724
+ const appliesTo = (filename, { patterns }, root) => {
725
+ const file = projectPath(filename, root);
726
+ return file !== void 0 && patterns.sparta.test(file) && file.match(patterns.top)?.[1] !== "support";
727
+ };
728
+ const rule$10 = {
729
+ meta: {
730
+ type: "problem",
731
+ docs: {
732
+ description: "Require `expect` to be imported from the support module (`@sparta/support`) inside sparta/.",
733
+ url: docsUrl("expect-from-support")
734
+ },
735
+ fixable: "code",
736
+ schema: [],
737
+ messages: { expectFromSupport: "Import expect from '{{module}}' instead of '{{source}}'." }
738
+ },
739
+ create(context) {
740
+ const conventions = conventionsFor(context);
741
+ const { supportModule } = conventions;
742
+ if (!appliesTo(context.filename, conventions, rootFor(context, conventions))) return {};
743
+ return { ImportDeclaration(node) {
744
+ const source = node.source.value;
745
+ if (source === supportModule) return;
746
+ const specifier = node.specifiers.find((item) => item.type === "ImportSpecifier" && item.imported.type === "Identifier" && item.imported.name === "expect");
747
+ if (specifier === void 0) return;
748
+ const data = {
749
+ source: String(source),
750
+ module: supportModule
751
+ };
752
+ if (node.specifiers.length !== 1) {
753
+ context.report({
754
+ node: specifier,
755
+ messageId: "expectFromSupport",
756
+ data
757
+ });
758
+ return;
759
+ }
760
+ context.report({
761
+ node: specifier,
762
+ messageId: "expectFromSupport",
763
+ data,
764
+ fix: (fixer) => fixer.replaceText(node.source, JSON.stringify(supportModule))
765
+ });
766
+ } };
767
+ }
768
+ };
769
+ // src/rules/file-naming.ts
770
+ const rule$9 = {
771
+ meta: {
772
+ type: "suggestion",
773
+ docs: {
774
+ description: "Require files in a layer folder to end with the layer suffix (e.g. `*-stepper.ts`).",
775
+ url: docsUrl("file-naming")
776
+ },
777
+ schema: [],
778
+ messages: { suffix: "Files in '{{folder}}/' must be named '*-{{suffix}}.ts' (found '{{name}}')." }
779
+ },
780
+ create(context) {
781
+ const conventions = conventionsFor(context);
782
+ const folder = layerFolder(context.filename, conventions, rootFor(context, conventions));
783
+ const suffix = layerSuffix(folder);
784
+ const name = path.basename(context.filename);
785
+ if (folder === void 0 || suffix === void 0 || name === "index.ts" || name.endsWith(`-${suffix}.ts`)) return {};
786
+ return { Program(node) {
787
+ context.report({
788
+ node,
789
+ messageId: "suffix",
790
+ data: {
791
+ folder: folder.name,
792
+ suffix,
793
+ name
794
+ }
795
+ });
796
+ } };
797
+ }
798
+ };
799
+ // src/rules/lines-between-class-members.ts
800
+ const BLANK_LINE$1 = /\r?\n[\t ]*\r?\n/;
801
+ const rule$8 = {
802
+ meta: {
803
+ type: "layout",
804
+ docs: {
805
+ description: "Require a blank line after every multi-line class member.",
806
+ url: docsUrl("lines-between-class-members")
807
+ },
808
+ fixable: "whitespace",
809
+ schema: [],
810
+ messages: { expectedBlankLine: "Expected a blank line between class members." }
811
+ },
812
+ create(context) {
813
+ const { text } = context.sourceCode;
814
+ return { ClassBody(node) {
815
+ for (let index = 1; index < node.body.length; index++) {
816
+ const previous = node.body[index - 1];
817
+ const current = node.body[index];
818
+ if (previous.loc.start.line === previous.loc.end.line) continue;
819
+ const textBetween = text.slice(previous.range[1], current.range[0]);
820
+ if (BLANK_LINE$1.test(textBetween)) continue;
821
+ context.report({
822
+ node: current,
823
+ messageId: "expectedBlankLine",
824
+ fix: (fixer) => {
825
+ const lineBreak = textBetween.includes("\r\n") ? "\r\n" : "\n";
826
+ const replacement = textBetween.includes(lineBreak) ? textBetween.replace(lineBreak, `${lineBreak}${lineBreak}`) : `${lineBreak}${lineBreak}${textBetween}`;
827
+ return fixer.replaceTextRange([previous.range[1], current.range[0]], replacement);
828
+ }
829
+ });
830
+ }
831
+ } };
832
+ }
833
+ };
834
+ // src/rules/no-direct-construction-in-tests.ts
835
+ const LAYER_CLASS = /(Stepper|Asserter|Scenario|Service|Client|Repository|Page|Screen|Component|Builder|Director|Factory|Provider)$/;
836
+ const rule$7 = {
837
+ meta: {
838
+ type: "problem",
839
+ docs: {
840
+ description: "Disallow constructing SPARTA layer classes in tests; use the fixtures instead.",
841
+ url: docsUrl("no-direct-construction-in-tests")
842
+ },
843
+ schema: [],
844
+ messages: { useFixture: "Do not construct '{{name}}' in a test; use it via the SPARTA fixtures." }
845
+ },
846
+ create(context) {
847
+ const conventions = conventionsFor(context);
848
+ if (classify(context.filename, conventions, rootFor(context, conventions))?.kind !== "test") return {};
849
+ return { NewExpression(node) {
850
+ const { callee } = node;
851
+ if (callee.type === "Identifier" && LAYER_CLASS.test(callee.name)) context.report({
852
+ node,
853
+ messageId: "useFixture",
854
+ data: { name: callee.name }
855
+ });
856
+ } };
857
+ }
858
+ };
859
+ // src/rules/no-expect-in-tests.ts
860
+ /**
861
+ * Names of `expect` and its extensions: `expect`, `expectly`, `expectlyLocator`, `expectApi`, `expect_soft`.
862
+ * `expected`, `expecting` and the like are left alone. `settings.sparta.expectNames` adds exact names.
863
+ */
864
+ const EXPECT_NAME = /^expect(?:ly)?(?:[A-Z_$\d]|$)/;
865
+ const rule$6 = {
866
+ meta: {
867
+ type: "problem",
868
+ docs: {
869
+ description: "Disallow `expect` in test files; checks belong in steppers and asserters.",
870
+ url: docsUrl("no-expect-in-tests")
871
+ },
872
+ schema: [],
873
+ messages: { noExpect: "Do not use expect in a test file. Put checkpoints in a stepper and technical or functional checks in an asserter." }
874
+ },
875
+ create(context) {
876
+ const conventions = conventionsFor(context);
877
+ if (classify(context.filename, conventions, rootFor(context, conventions))?.kind !== "test") return {};
878
+ const isExpectName = (name) => EXPECT_NAME.test(name) || conventions.expectNames.has(name);
879
+ /** Local names bound to an expect through a renamed import, such as `import { expect as check }`. */
880
+ const aliases = /* @__PURE__ */ new Set();
881
+ const isExpect = (node) => node.type === "Identifier" && (isExpectName(node.name) || aliases.has(node.name));
882
+ return {
883
+ ImportSpecifier(node) {
884
+ const { imported, local } = node;
885
+ const importedName = imported.type === "Identifier" ? imported.name : String(imported.value);
886
+ if (!isExpectName(importedName) && !isExpectName(local.name)) return;
887
+ aliases.add(local.name);
888
+ context.report({
889
+ node,
890
+ messageId: "noExpect"
891
+ });
892
+ },
893
+ CallExpression(node) {
894
+ let callee = node.callee;
895
+ while (callee.type === "MemberExpression") callee = callee.object;
896
+ if (isExpect(callee)) context.report({
897
+ node: node.callee,
898
+ messageId: "noExpect"
899
+ });
900
+ }
901
+ };
902
+ }
903
+ };
904
+ // src/rules/no-hard-waits.ts
905
+ const TIMER_MODULES = /* @__PURE__ */ new Set(["timers/promises", "node:timers/promises"]);
906
+ const isSetTimeout = (callee) => isIdentifier(callee, "setTimeout") || callee.type === "MemberExpression" && (isIdentifier(callee.object, "globalThis") || isIdentifier(callee.object, "window")) && isIdentifier(callee.property, "setTimeout");
907
+ /** The `resolve` parameter of the nearest enclosing `new Promise(resolve => ...)` executor. */
908
+ const promiseResolveName = (node) => {
909
+ for (let current = node.parent; current; current = current.parent) {
910
+ if (current.type !== "ArrowFunctionExpression" && current.type !== "FunctionExpression") continue;
911
+ const { parent } = current;
912
+ if (parent.type === "NewExpression" && isIdentifier(parent.callee, "Promise") && parent.arguments[0] === current) {
913
+ const [resolve] = current.params;
914
+ return resolve?.type === "Identifier" ? resolve.name : void 0;
915
+ }
916
+ }
917
+ };
918
+ /** True when the timer callback only resolves the promise, i.e. the timer is a plain sleep. */
919
+ const resolvesPromise = (callback, resolve) => {
920
+ if (!callback) return false;
921
+ if (isIdentifier(callback, resolve)) return true;
922
+ if (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression") return false;
923
+ const { body } = callback;
924
+ if (!body) return false;
925
+ const call = body.type === "CallExpression" ? body : body.type === "BlockStatement" && body.body.length === 1 && body.body[0].type === "ExpressionStatement" ? body.body[0].expression : void 0;
926
+ return call?.type === "CallExpression" && isIdentifier(call.callee, resolve);
927
+ };
928
+ const rule$5 = {
929
+ meta: {
930
+ type: "problem",
931
+ docs: {
932
+ description: "Disallow fixed-time waits such as `waitForTimeout` and `setTimeout` sleeps.",
933
+ url: docsUrl("no-hard-waits")
934
+ },
935
+ schema: [],
936
+ messages: { hardWait: "Do not wait a fixed amount of time; wait for a state with web-first assertions or polling in a stepper or asserter." }
937
+ },
938
+ create(context) {
939
+ const conventions = conventionsFor(context);
940
+ const { patterns } = conventions;
941
+ const file = projectPath(context.filename, rootFor(context, conventions));
942
+ if (file === void 0 || !patterns.checked.test(file) || patterns.framework.test(file)) return {};
943
+ return {
944
+ ImportDeclaration(node) {
945
+ if (typeof node.source.value !== "string" || !TIMER_MODULES.has(node.source.value)) return;
946
+ for (const specifier of node.specifiers) if (specifier.type === "ImportSpecifier" && isIdentifier(specifier.imported, "setTimeout")) context.report({
947
+ node: specifier,
948
+ messageId: "hardWait"
949
+ });
950
+ },
951
+ CallExpression(node) {
952
+ const { callee } = node;
953
+ if (callee.type === "MemberExpression" && isIdentifier(callee.property, "waitForTimeout")) {
954
+ context.report({
955
+ node,
956
+ messageId: "hardWait"
957
+ });
958
+ return;
959
+ }
960
+ if (!isSetTimeout(callee)) return;
961
+ const resolve = promiseResolveName(node);
962
+ if (resolve !== void 0 && resolvesPromise(node.arguments[0], resolve)) context.report({
963
+ node,
964
+ messageId: "hardWait"
965
+ });
966
+ }
967
+ };
968
+ }
969
+ };
970
+ // src/utils/polling.ts
971
+ /**
972
+ * Retrying assertions are recognised by method name only, so `expect`, `expect.soft`, `expectly` and wrappers all
973
+ * match. The names come from the conventions: `toPass`, `toPassAndReturn`, `poll`, `pollAndReturn`, plus
974
+ * `settings.sparta.pollingMethods`.
975
+ */
976
+ /** Methods that take the callback they retry as their own first argument (`expect.poll(cb)`). */
977
+ const CALLBACK_ARGUMENT_METHODS = /* @__PURE__ */ new Set(["poll", "pollAndReturn"]);
978
+ /** Methods that retry the callback given to the start of their chain (`expect(cb).toPass()`). */
979
+ const CALLBACK_SUBJECT_METHODS = /* @__PURE__ */ new Set(["toPass", "toPassAndReturn"]);
980
+ /** The static name of a member access (`a.b`, `a["b"]`), or `undefined` for computed or private access. */
981
+ const memberName$1 = (node) => {
982
+ if (node.type !== "MemberExpression") return void 0;
983
+ const { property } = node;
984
+ if (!node.computed && property.type === "Identifier") return property.name;
985
+ if (node.computed && property.type === "Literal" && typeof property.value === "string") return property.value;
986
+ };
987
+ /** The polling method a call invokes (`toPass` for `expect(cb).toPass()`), or `undefined` for any other node. */
988
+ const pollingMethod = (node, methods) => {
989
+ if (node.type !== "CallExpression") return void 0;
990
+ const name = memberName$1(node.callee);
991
+ return name !== void 0 && methods.has(name) ? name : void 0;
992
+ };
993
+ const isFunction$1 = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression";
994
+ const firstArgument = (call) => {
995
+ const [argument] = call.arguments;
996
+ return argument?.type === "SpreadElement" ? void 0 : argument;
997
+ };
998
+ /** `X(cb).method()`: the first argument of the call the chain starts from, also through `.soft(cb)` and `.not`. */
999
+ const subjectCallback = (call) => {
1000
+ if (call.callee.type !== "MemberExpression") return void 0;
1001
+ let object = call.callee.object;
1002
+ while (object.type === "MemberExpression") object = object.object;
1003
+ return object.type === "CallExpression" ? firstArgument(object) : void 0;
1004
+ };
1005
+ /**
1006
+ * The callback that a polling call retries:
1007
+ * - `X.poll(cb)` and `X.pollAndReturn(cb)`: the first argument.
1008
+ * - `X(cb).toPass()` and `X(cb).toPassAndReturn()`: the first argument of the call the chain starts from,
1009
+ * also through `.soft(cb)` and `.not`.
1010
+ * - other configured methods: the first argument when it is a function, otherwise the start of the chain.
1011
+ */
1012
+ const pollCallback = (call, methods) => {
1013
+ const method = pollingMethod(call, methods);
1014
+ if (method === void 0 || call.callee.type !== "MemberExpression") return void 0;
1015
+ if (CALLBACK_ARGUMENT_METHODS.has(method)) return firstArgument(call);
1016
+ if (CALLBACK_SUBJECT_METHODS.has(method)) return subjectCallback(call);
1017
+ const argument = firstArgument(call);
1018
+ return isFunction$1(argument) ? argument : subjectCallback(call);
1019
+ };
1020
+ // src/utils/project-index.ts
1021
+ const MAX_DEPTH = 10;
1022
+ const SKIPPED_KEYS = /* @__PURE__ */ new Set([
1023
+ "parent",
1024
+ "loc",
1025
+ "range",
1026
+ "start",
1027
+ "end",
1028
+ "typeAnnotation",
1029
+ "returnType",
1030
+ "decorators"
1031
+ ]);
1032
+ const MODULE_EXTENSIONS = [
1033
+ "",
1034
+ ".ts",
1035
+ ".tsx",
1036
+ ".mts",
1037
+ ".cts",
1038
+ "/index.ts"
1039
+ ];
1040
+ const isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
1041
+ /** Visits `node` and its descendants depth-first. Returning `false` from `visit` skips the node's children. */
1042
+ function walk(node, visit) {
1043
+ if (visit(node) === false) return;
1044
+ for (const [key, value] of Object.entries(node)) {
1045
+ if (SKIPPED_KEYS.has(key)) continue;
1046
+ if (Array.isArray(value)) {
1047
+ for (const item of value) if (isNode(item)) walk(item, visit);
1048
+ } else if (isNode(value)) walk(value, visit);
1049
+ }
1050
+ }
1051
+ const isFunctionLike = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "FunctionDeclaration";
1052
+ /** `X` for a `: X` or `: X<T>` annotation. */
1053
+ const typeName = (annotation) => {
1054
+ const type = annotation?.typeAnnotation;
1055
+ return type?.type === "TSTypeReference" && type.typeName.type === "Identifier" ? type.typeName.name : void 0;
1056
+ };
1057
+ /** `X` for `new X(...)`. */
1058
+ const newName = (node) => node?.type === "NewExpression" && node.callee.type === "Identifier" ? node.callee.name : void 0;
1059
+ const keyName = (key) => key.type === "Identifier" ? key.name : key.type === "Literal" && typeof key.value === "string" ? key.value : void 0;
1060
+ function summarizeClass(name, node) {
1061
+ const info = {
1062
+ name,
1063
+ node,
1064
+ superClass: node.superClass?.type === "Identifier" ? node.superClass.name : void 0,
1065
+ methods: /* @__PURE__ */ new Map(),
1066
+ fields: /* @__PURE__ */ new Map()
1067
+ };
1068
+ for (const member of node.body.body) {
1069
+ if (member.type === "PropertyDefinition") summarizeField(info, member);
1070
+ if (member.type === "MethodDefinition") summarizeMethod(info, member);
1071
+ }
1072
+ return info;
1073
+ }
1074
+ /** A typed field (`x: X`) or a field created with `new X()`. */
1075
+ function summarizeField(info, member) {
1076
+ const field = member.computed ? void 0 : keyName(member.key);
1077
+ const type = typeName(member.typeAnnotation) ?? newName(member.value);
1078
+ if (field !== void 0 && type !== void 0) info.fields.set(field, type);
1079
+ }
1080
+ /** Methods, getters (whose return type acts as a field type) and the constructor. */
1081
+ function summarizeMethod(info, member) {
1082
+ const name = member.computed ? void 0 : keyName(member.key);
1083
+ const { value } = member;
1084
+ if (name === void 0 || value.type !== "FunctionExpression" || !value.body) return;
1085
+ if (member.kind === "constructor") summarizeConstructor(info, value);
1086
+ else if (member.kind === "get") {
1087
+ const type = typeName(value.returnType);
1088
+ if (type !== void 0) info.fields.set(name, type);
1089
+ } else if (member.kind === "method") info.methods.set(name, value);
1090
+ }
1091
+ /** Fields from constructor parameter properties and from `this.x = new X()` assignments. */
1092
+ function summarizeConstructor(info, constructor) {
1093
+ for (const param of constructor.params) {
1094
+ if (param.type !== "TSParameterProperty") continue;
1095
+ const binding = param.parameter.type === "AssignmentPattern" ? param.parameter.left : param.parameter;
1096
+ const type = binding.type === "Identifier" ? typeName(binding.typeAnnotation) : void 0;
1097
+ if (binding.type === "Identifier" && type !== void 0) info.fields.set(binding.name, type);
1098
+ }
1099
+ if (!constructor.body) return;
1100
+ walk(constructor.body, (node) => {
1101
+ if (node.type !== "AssignmentExpression" || node.left.type !== "MemberExpression") return;
1102
+ if (node.left.object.type !== "ThisExpression") return;
1103
+ const field = memberName$1(node.left);
1104
+ const type = newName(node.right);
1105
+ if (field !== void 0 && type !== void 0 && !info.fields.has(field)) info.fields.set(field, type);
1106
+ });
1107
+ }
1108
+ const importedName = (node) => node.type === "Identifier" ? node.name : node.type === "Literal" ? String(node.value) : "";
1109
+ function summarizeDeclaration(summary, node, exported) {
1110
+ if ((node.type === "ClassDeclaration" || node.type === "ClassExpression") && node.id) {
1111
+ summary.classes.set(node.id.name, summarizeClass(node.id.name, node));
1112
+ if (exported !== void 0) summary.exports.set(exported === "" ? node.id.name : exported, node.id.name);
1113
+ } else if (node.type === "FunctionDeclaration" && node.id) {
1114
+ summary.functions.set(node.id.name, node);
1115
+ if (exported !== void 0) summary.exports.set(exported === "" ? node.id.name : exported, node.id.name);
1116
+ } else if (node.type === "VariableDeclaration") for (const declarator of node.declarations) {
1117
+ if (declarator.id.type !== "Identifier" || !isFunctionLike(declarator.init)) continue;
1118
+ summary.functions.set(declarator.id.name, declarator.init);
1119
+ if (exported !== void 0) summary.exports.set(declarator.id.name, declarator.id.name);
1120
+ }
1121
+ }
1122
+ /** Collects the imports, exports, classes and functions of a module. */
1123
+ function summarize(file, program, root, conventions) {
1124
+ const summary = {
1125
+ file,
1126
+ root,
1127
+ conventions,
1128
+ imports: /* @__PURE__ */ new Map(),
1129
+ classes: /* @__PURE__ */ new Map(),
1130
+ functions: /* @__PURE__ */ new Map(),
1131
+ exports: /* @__PURE__ */ new Map(),
1132
+ reexports: /* @__PURE__ */ new Map(),
1133
+ starExports: []
1134
+ };
1135
+ for (const statement of program.body) if (statement.type === "ImportDeclaration") summarizeImport(summary, statement);
1136
+ else if (statement.type === "ExportNamedDeclaration") summarizeNamedExport(summary, statement);
1137
+ else if (statement.type === "ExportDefaultDeclaration") {
1138
+ const { declaration } = statement;
1139
+ if (declaration.type === "Identifier") summary.exports.set("default", declaration.name);
1140
+ else summarizeDeclaration(summary, declaration, "default");
1141
+ } else if (statement.type === "ExportAllDeclaration") {
1142
+ const module = resolveModule(file, statement.source.value, root, conventions);
1143
+ if (!statement.exported && module !== void 0) summary.starExports.push(module);
1144
+ } else summarizeDeclaration(summary, statement, void 0);
1145
+ return summary;
1146
+ }
1147
+ function summarizeImport(summary, statement) {
1148
+ const module = resolveModule(summary.file, statement.source.value, summary.root, summary.conventions);
1149
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier") summary.imports.set(specifier.local.name, {
1150
+ module,
1151
+ imported: importedName(specifier.imported)
1152
+ });
1153
+ else if (specifier.type === "ImportDefaultSpecifier") summary.imports.set(specifier.local.name, {
1154
+ module,
1155
+ imported: "default"
1156
+ });
1157
+ }
1158
+ /** `export class X`, `export { X as Y }` and `export { X } from "..."`. */
1159
+ function summarizeNamedExport(summary, statement) {
1160
+ if (statement.declaration) {
1161
+ summarizeDeclaration(summary, statement.declaration, "");
1162
+ return;
1163
+ }
1164
+ const module = statement.source ? resolveModule(summary.file, statement.source.value, summary.root, summary.conventions) : void 0;
1165
+ for (const specifier of statement.specifiers) {
1166
+ const exported = importedName(specifier.exported);
1167
+ const local = importedName(specifier.local);
1168
+ if (statement.source) summary.reexports.set(exported, {
1169
+ module,
1170
+ imported: local
1171
+ });
1172
+ else summary.exports.set(exported, local);
1173
+ }
1174
+ }
1175
+ const isFile = (file) => statSync(file, { throwIfNoEntry: false })?.isFile() ?? false;
1176
+ /** Resolves a relative or aliased import to a TypeScript file. Package imports resolve to `undefined`. */
1177
+ function resolveModule(fromFile, request, root, conventions) {
1178
+ const base = resolveImport(fromFile, request, root, conventions);
1179
+ if (base === void 0) return void 0;
1180
+ const stripped = base.replace(/\.(?:m|c)?js$/, "");
1181
+ for (const candidate of [base, ...MODULE_EXTENSIONS.map((extension) => `${stripped}${extension}`)]) if (isFile(candidate)) return normalize(candidate);
1182
+ }
1183
+ /**
1184
+ * Summaries of files on disk per project root and conventions (imports resolve against them), kept for the lifetime of the
1185
+ * linter process and refreshed when a file changes.
1186
+ */
1187
+ const diskCache = /* @__PURE__ */ new Map();
1188
+ function diskSummary(file, root, conventions) {
1189
+ const stats = statSync(file, { throwIfNoEntry: false });
1190
+ if (!stats?.isFile()) return void 0;
1191
+ const key = `${conventions.key}\0${root}\0${file}`;
1192
+ const cached = diskCache.get(key);
1193
+ if (cached?.mtimeMs === stats.mtimeMs) return cached.summary;
1194
+ const { program } = parseSync(file, readFileSync(file, "utf8"));
1195
+ const summary = summarize(file, program, root, conventions);
1196
+ diskCache.set(key, {
1197
+ mtimeMs: stats.mtimeMs,
1198
+ summary
1199
+ });
1200
+ return summary;
1201
+ }
1202
+ /** Shows paths relative to the project root (`sparta/...`) instead of absolute ones. */
1203
+ const display = (file, root) => file.startsWith(`${root}/`) ? file.slice(root.length + 1) : path.basename(file);
1204
+ /**
1205
+ * Cross-file view for one linted file. The linted file uses the linter's in-memory AST (so unsaved
1206
+ * changes count); every other file is parsed from disk.
1207
+ */
1208
+ var ProjectIndex = class {
1209
+ current;
1210
+ memo = /* @__PURE__ */ new Map();
1211
+ inProgress = /* @__PURE__ */ new Set();
1212
+ /** Summaries looked up while linting this file, so every other file is checked on disk at most once. */
1213
+ summaries = /* @__PURE__ */ new Map();
1214
+ /**
1215
+ * Counts the lookups cut short by a call cycle or by `MAX_DEPTH`. A "does not poll" answer computed while this
1216
+ * changed is only true for that call chain, so it is not cached.
1217
+ */
1218
+ truncations = 0;
1219
+ constructor(current) {
1220
+ this.current = current;
1221
+ }
1222
+ /** Finds the polling calls, and the calls that lead to polling, inside `root`. Stops descending at a polling call. */
1223
+ collectHits(root, scope, depth = 0, firstOnly = false) {
1224
+ const hits = [];
1225
+ walk(root, (node) => {
1226
+ if (firstOnly && hits.length > 0) return false;
1227
+ if (node.type !== "CallExpression") return;
1228
+ const method = pollingMethod(node, this.current.conventions.pollingMethods);
1229
+ if (method !== void 0) {
1230
+ hits.push({
1231
+ node,
1232
+ method
1233
+ });
1234
+ return false;
1235
+ }
1236
+ const target = this.resolveCall(node, scope);
1237
+ const path = target ? this.pollingPath(target, depth + 1) : void 0;
1238
+ if (path) hits.push({
1239
+ node,
1240
+ path
1241
+ });
1242
+ });
1243
+ return hits;
1244
+ }
1245
+ /** The chain from `target` to a polling call, e.g. `["Page.open", "Page.find", "poll (sparta/.../page.ts)"]`. */
1246
+ pollingPath(target, depth = 0) {
1247
+ const label = target.kind === "method" ? `${target.cls.info.name}.${target.name}` : target.name;
1248
+ const key = `${target.file}#${label}`;
1249
+ const known = this.memo.get(key);
1250
+ if (known !== void 0) return known ?? void 0;
1251
+ if (!target.fn.body) return void 0;
1252
+ if (depth > MAX_DEPTH || this.inProgress.has(key)) {
1253
+ this.truncations++;
1254
+ return;
1255
+ }
1256
+ const truncationsBefore = this.truncations;
1257
+ this.inProgress.add(key);
1258
+ const scope = {
1259
+ file: target.file,
1260
+ cls: target.kind === "method" ? target.cls : void 0,
1261
+ locals: collectLocals(target.fn)
1262
+ };
1263
+ const [hit] = this.collectHits(target.fn.body, scope, depth, true);
1264
+ this.inProgress.delete(key);
1265
+ const result = hit ? "method" in hit ? [label, `${hit.method} (${display(target.file, this.current.root)})`] : [label, ...hit.path] : void 0;
1266
+ if (result !== void 0) this.memo.set(key, result);
1267
+ else if (this.truncations === truncationsBefore) this.memo.set(key, null);
1268
+ return result;
1269
+ }
1270
+ /** Resolves a call such as `fn()`, `this.method()`, `this.field.method()` or `local.method()`. */
1271
+ resolveCall(call, scope) {
1272
+ return this.resolveReference(call.callee, scope);
1273
+ }
1274
+ /** Resolves a reference to a function or method, such as `fn` or `this.page.method`. */
1275
+ resolveReference(node, scope) {
1276
+ if (node.type === "Identifier") {
1277
+ const found = this.resolveLocal(scope.file, node.name);
1278
+ const fn = found ? this.summary(found.file)?.functions.get(found.local) : void 0;
1279
+ return found && fn ? {
1280
+ kind: "function",
1281
+ file: found.file,
1282
+ name: found.local,
1283
+ fn
1284
+ } : void 0;
1285
+ }
1286
+ const method = memberName$1(node);
1287
+ if (method === void 0 || node.type !== "MemberExpression") return void 0;
1288
+ const receiver = this.receiverClass(node.object, scope);
1289
+ return receiver ? this.findMethod(receiver, method) : void 0;
1290
+ }
1291
+ /** Builds the scope for code in the linted file, inside `classNode` and the function `fn` (whose locals count). */
1292
+ scopeFor(classNode, fn) {
1293
+ const cls = [...this.current.classes.values()].find((info) => info.node === classNode);
1294
+ return {
1295
+ file: this.current.file,
1296
+ cls: cls ? {
1297
+ file: this.current.file,
1298
+ info: cls
1299
+ } : void 0,
1300
+ locals: isFunctionLike(fn) ? collectLocals(fn) : /* @__PURE__ */ new Map()
1301
+ };
1302
+ }
1303
+ summary(file) {
1304
+ if (file === this.current.file) return this.current;
1305
+ if (this.summaries.has(file)) return this.summaries.get(file);
1306
+ const summary = diskSummary(file, this.current.root, this.current.conventions);
1307
+ this.summaries.set(file, summary);
1308
+ return summary;
1309
+ }
1310
+ receiverClass(node, scope, depth = 0) {
1311
+ if (depth > MAX_DEPTH) return void 0;
1312
+ switch (node.type) {
1313
+ case "ThisExpression": return scope.cls;
1314
+ case "Identifier": {
1315
+ const type = scope.locals.get(node.name);
1316
+ return type === void 0 ? void 0 : this.resolveClass(scope.file, type);
1317
+ }
1318
+ case "NewExpression": return node.callee.type === "Identifier" ? this.resolveClass(scope.file, node.callee.name) : void 0;
1319
+ case "TSNonNullExpression":
1320
+ case "ParenthesizedExpression": return this.receiverClass(node.expression, scope, depth + 1);
1321
+ case "MemberExpression": {
1322
+ const field = memberName$1(node);
1323
+ const owner = field === void 0 ? void 0 : this.receiverClass(node.object, scope, depth + 1);
1324
+ return owner && field !== void 0 ? this.fieldClass(owner, field) : void 0;
1325
+ }
1326
+ default: return;
1327
+ }
1328
+ }
1329
+ fieldClass(cls, field, depth = 0) {
1330
+ if (depth > MAX_DEPTH) return void 0;
1331
+ const type = cls.info.fields.get(field);
1332
+ if (type !== void 0) return this.resolveClass(cls.file, type);
1333
+ const parent = this.superClass(cls);
1334
+ return parent ? this.fieldClass(parent, field, depth + 1) : void 0;
1335
+ }
1336
+ findMethod(cls, name, depth = 0) {
1337
+ if (depth > MAX_DEPTH) return void 0;
1338
+ const fn = cls.info.methods.get(name);
1339
+ if (fn) return {
1340
+ kind: "method",
1341
+ file: cls.file,
1342
+ cls,
1343
+ name,
1344
+ fn
1345
+ };
1346
+ const parent = this.superClass(cls);
1347
+ return parent ? this.findMethod(parent, name, depth + 1) : void 0;
1348
+ }
1349
+ superClass(cls) {
1350
+ return cls.info.superClass === void 0 ? void 0 : this.resolveClass(cls.file, cls.info.superClass);
1351
+ }
1352
+ resolveClass(file, localName) {
1353
+ const found = this.resolveLocal(file, localName);
1354
+ const info = found ? this.summary(found.file)?.classes.get(found.local) : void 0;
1355
+ return found && info ? {
1356
+ file: found.file,
1357
+ info
1358
+ } : void 0;
1359
+ }
1360
+ /** Finds where a name used in `file` is declared, following imports and re-exports. */
1361
+ resolveLocal(file, localName, depth = 0) {
1362
+ const summary = this.summary(file);
1363
+ if (!summary || depth > MAX_DEPTH) return void 0;
1364
+ if (summary.classes.has(localName) || summary.functions.has(localName)) return {
1365
+ file,
1366
+ local: localName
1367
+ };
1368
+ const imported = summary.imports.get(localName);
1369
+ return imported?.module === void 0 ? void 0 : this.resolveExport(imported.module, imported.imported, depth + 1);
1370
+ }
1371
+ resolveExport(file, exported, depth) {
1372
+ const summary = this.summary(file);
1373
+ if (!summary || depth > MAX_DEPTH) return void 0;
1374
+ const local = summary.exports.get(exported);
1375
+ if (local !== void 0) return this.resolveLocal(file, local, depth + 1);
1376
+ const reexport = summary.reexports.get(exported);
1377
+ if (reexport) return reexport.module === void 0 ? void 0 : this.resolveExport(reexport.module, reexport.imported, depth + 1);
1378
+ for (const module of summary.starExports) {
1379
+ const found = this.resolveExport(module, exported, depth + 1);
1380
+ if (found) return found;
1381
+ }
1382
+ }
1383
+ };
1384
+ /** Local variables whose class is known: `const x = new X()` and `const x: X = ...`. */
1385
+ function collectLocals(fn) {
1386
+ const locals = /* @__PURE__ */ new Map();
1387
+ if (!fn.body) return locals;
1388
+ walk(fn.body, (node) => {
1389
+ if (node.type !== "VariableDeclarator" || node.id.type !== "Identifier") return;
1390
+ const type = typeName(node.id.typeAnnotation) ?? newName(node.init);
1391
+ if (type !== void 0) locals.set(node.id.name, type);
1392
+ });
1393
+ return locals;
1394
+ }
1395
+ // src/rules/no-nested-polling.ts
1396
+ const isFunction = (node) => node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration";
1397
+ /** The class around `node`, and the outermost function inside that class (the method), for resolving `this` and locals. */
1398
+ function enclosing(node) {
1399
+ let fn;
1400
+ for (let current = node.parent; current; current = current.parent) {
1401
+ if (current.type === "ClassDeclaration" || current.type === "ClassExpression") return {
1402
+ classNode: current,
1403
+ fn
1404
+ };
1405
+ if (isFunction(current)) fn = current;
1406
+ }
1407
+ return { fn };
1408
+ }
1409
+ const rule$4 = {
1410
+ meta: {
1411
+ type: "problem",
1412
+ docs: {
1413
+ description: "Disallow polling (`toPass`, `poll`, ...) inside the callback of another poll, also through calls into other files.",
1414
+ url: docsUrl("no-nested-polling")
1415
+ },
1416
+ schema: [],
1417
+ messages: {
1418
+ nested: "'{{inner}}' polls inside the callback of '{{outer}}'. Nested polling multiplies the timeouts; poll once, at the outermost level.",
1419
+ nestedCall: "'{{call}}' polls inside the callback of '{{outer}}' (via {{path}}). Nested polling multiplies the timeouts; poll once, at the outermost level."
1420
+ }
1421
+ },
1422
+ create(context) {
1423
+ const { sourceCode } = context;
1424
+ const conventions = conventionsFor(context);
1425
+ const { pollingMethods } = conventions;
1426
+ if (![...pollingMethods].some((method) => sourceCode.text.includes(method))) return {};
1427
+ let index;
1428
+ const getIndex = () => index ??= new ProjectIndex(summarize(normalize(context.filename), sourceCode.ast, rootFor(context, conventions), conventions));
1429
+ const report = (hit, outer) => {
1430
+ const node = hit.node;
1431
+ if ("method" in hit) context.report({
1432
+ node,
1433
+ messageId: "nested",
1434
+ data: {
1435
+ inner: hit.method,
1436
+ outer
1437
+ }
1438
+ });
1439
+ else {
1440
+ const callee = sourceCode.getText(hit.node.callee);
1441
+ context.report({
1442
+ node,
1443
+ messageId: "nestedCall",
1444
+ data: {
1445
+ call: `${callee}()`,
1446
+ outer,
1447
+ path: hit.path.join(" → ")
1448
+ }
1449
+ });
1450
+ }
1451
+ };
1452
+ return { CallExpression(node) {
1453
+ const call = node;
1454
+ const outer = pollingMethod(call, pollingMethods);
1455
+ const callback = outer === void 0 ? void 0 : pollCallback(call, pollingMethods);
1456
+ if (outer === void 0 || callback === void 0) return;
1457
+ const { classNode, fn } = enclosing(node);
1458
+ const projectIndex = getIndex();
1459
+ const scope = projectIndex.scopeFor(classNode, fn ? fn : callback);
1460
+ if (callback.type === "ArrowFunctionExpression" || callback.type === "FunctionExpression") {
1461
+ for (const hit of projectIndex.collectHits(callback.body, scope)) report(hit, outer);
1462
+ return;
1463
+ }
1464
+ const target = projectIndex.resolveReference(callback, scope);
1465
+ const path = target ? projectIndex.pollingPath(target) : void 0;
1466
+ if (path) context.report({
1467
+ node: callback,
1468
+ messageId: "nestedCall",
1469
+ data: {
1470
+ call: sourceCode.getText(callback),
1471
+ outer,
1472
+ path: path.join(" → ")
1473
+ }
1474
+ });
1475
+ } };
1476
+ }
1477
+ };
1478
+ // src/rules/padding-lines.ts
1479
+ const BLANK_LINE = /\r?\n[\t ]*\r?\n/;
1480
+ const unwrapExport = (node) => (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") && node.declaration ? node.declaration : node;
1481
+ const isFunctionValue = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "TSEmptyBodyFunctionExpression";
1482
+ const isImport = (node) => node.type === "ImportDeclaration" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
1483
+ const isFunctionStatement = (node) => {
1484
+ const statement = unwrapExport(node);
1485
+ if (statement.type === "FunctionDeclaration" || statement.type === "TSDeclareFunction" || isFunctionValue(statement)) return true;
1486
+ return statement.type === "VariableDeclaration" && statement.declarations.some(({ init }) => isFunctionValue(init));
1487
+ };
1488
+ const functionStatementName = (node) => {
1489
+ const statement = unwrapExport(node);
1490
+ return (statement.type === "FunctionDeclaration" || statement.type === "TSDeclareFunction") && statement.id ? statement.id.name : void 0;
1491
+ };
1492
+ const isOverloadPair = (previous, current) => {
1493
+ const name = functionStatementName(previous);
1494
+ return unwrapExport(previous).type === "TSDeclareFunction" && name !== void 0 && name === functionStatementName(current);
1495
+ };
1496
+ const isMethodProperty = (property) => property.type === "Property" && (property.method || property.kind !== "init" || isFunctionValue(property.value));
1497
+ const rule$3 = {
1498
+ meta: {
1499
+ type: "layout",
1500
+ docs: {
1501
+ description: "Require blank lines after imports, around top-level functions and around object methods.",
1502
+ url: docsUrl("padding-lines")
1503
+ },
1504
+ fixable: "whitespace",
1505
+ schema: [],
1506
+ messages: {
1507
+ afterImports: "Expected a blank line after the import declarations.",
1508
+ aroundFunctions: "Expected a blank line between a function and the adjacent statement.",
1509
+ betweenObjectMethods: "Expected a blank line around methods in an object literal."
1510
+ }
1511
+ },
1512
+ create(context) {
1513
+ const { text } = context.sourceCode;
1514
+ const lineBreak = text.includes("\r\n") ? "\r\n" : "\n";
1515
+ const requireBlankLine = (previous, current, messageId) => {
1516
+ const textBetween = text.slice(previous.range[1], current.range[0]);
1517
+ if (BLANK_LINE.test(textBetween)) return;
1518
+ context.report({
1519
+ node: current,
1520
+ messageId,
1521
+ fix: (fixer) => {
1522
+ const firstBreak = textBetween.search(/\r?\n/);
1523
+ if (firstBreak === -1) return fixer.insertTextAfterRange(previous.range, `${lineBreak}${lineBreak}`);
1524
+ return fixer.insertTextAfterRange([0, previous.range[1] + firstBreak], lineBreak);
1525
+ }
1526
+ });
1527
+ };
1528
+ const checkStatements = (statements) => {
1529
+ for (let index = 1; index < statements.length; index++) {
1530
+ const previous = statements[index - 1];
1531
+ const current = statements[index];
1532
+ if (isImport(previous) && !isImport(current)) requireBlankLine(previous, current, "afterImports");
1533
+ else if ((isFunctionStatement(previous) || isFunctionStatement(current)) && !isOverloadPair(previous, current)) requireBlankLine(previous, current, "aroundFunctions");
1534
+ }
1535
+ };
1536
+ return {
1537
+ Program: (node) => checkStatements(node.body),
1538
+ TSModuleBlock: (node) => checkStatements(node.body),
1539
+ ObjectExpression(node) {
1540
+ for (let index = 1; index < node.properties.length; index++) {
1541
+ const previous = node.properties[index - 1];
1542
+ const current = node.properties[index];
1543
+ if (previous.loc.end.line === current.loc.start.line) continue;
1544
+ if (isMethodProperty(previous) || isMethodProperty(current)) requireBlankLine(previous, current, "betweenObjectMethods");
1545
+ }
1546
+ }
1547
+ };
1548
+ }
1549
+ };
1550
+ // src/rules/private-members-last.ts
1551
+ const isMethodLike = (member) => (member.type === "MethodDefinition" || member.type === "TSAbstractMethodDefinition") && member.kind !== "constructor";
1552
+ const isPrivate = (member) => "accessibility" in member && member.accessibility === "private" || "key" in member && member.key.type === "PrivateIdentifier";
1553
+ const memberName = (member) => {
1554
+ const key = "key" in member ? member.key : void 0;
1555
+ if (key && "name" in key && typeof key.name === "string") return key.name;
1556
+ if (key && "value" in key && typeof key.value === "string") return key.value;
1557
+ return "<computed>";
1558
+ };
1559
+ const rule$2 = {
1560
+ meta: {
1561
+ type: "suggestion",
1562
+ docs: {
1563
+ description: "Require public methods to be placed above private methods.",
1564
+ url: docsUrl("private-members-last")
1565
+ },
1566
+ schema: [],
1567
+ messages: { privateMembersLast: "Public method '{{name}}' must be placed above all private methods (private method '{{privateName}}' comes first)." }
1568
+ },
1569
+ create(context) {
1570
+ return { ClassBody(node) {
1571
+ let firstPrivate;
1572
+ for (const member of node.body) {
1573
+ if (!isMethodLike(member)) continue;
1574
+ if (isPrivate(member)) {
1575
+ firstPrivate ??= member;
1576
+ continue;
1577
+ }
1578
+ if (firstPrivate !== void 0) context.report({
1579
+ node: member,
1580
+ messageId: "privateMembersLast",
1581
+ data: {
1582
+ name: memberName(member),
1583
+ privateName: memberName(firstPrivate)
1584
+ }
1585
+ });
1586
+ }
1587
+ } };
1588
+ }
1589
+ };
1590
+ // src/rules/step-placeholders.ts
1591
+ /** The same pattern `@step` uses at runtime: the path is taken as written, so `{{ name }}` looks up " name ". */
1592
+ const NAMED = /\{\{(.*?)\}\}/g;
1593
+ const INDEX = /\[\[(\d+)\]\]/g;
1594
+ const SINGLE_BRACES = /(^|[^{])\{([A-Za-z_$][\w$]*(?:\.[\w$]+)*)\}(?!\})/g;
1595
+ const findAll = (pattern, text) => {
1596
+ const regex = new RegExp(pattern.source, "g");
1597
+ const found = [];
1598
+ for (let match = regex.exec(text); match !== null; match = regex.exec(text)) found.push(match);
1599
+ return found;
1600
+ };
1601
+ const paramName = (param) => {
1602
+ const target = param.type === "TSParameterProperty" ? param.parameter : param;
1603
+ const binding = target.type === "AssignmentPattern" ? target.left : target.type === "RestElement" ? target.argument : target;
1604
+ return binding.type === "Identifier" ? binding.name : void 0;
1605
+ };
1606
+ /**
1607
+ * What is wrong with the path of a `{{path}}` placeholder, if anything. `@step` reads the path exactly as written,
1608
+ * so spaces around it either fail the parameter lookup or read a property that does not exist.
1609
+ */
1610
+ const namedProblem = (path, names) => {
1611
+ const trimmed = path.trim();
1612
+ const isParameter = (value) => names.includes(value.split(".")[0]);
1613
+ if (trimmed !== path && isParameter(trimmed)) return "whitespace";
1614
+ return trimmed === path && isParameter(path) ? void 0 : "unknownParameter";
1615
+ };
1616
+ const isLiteralDescription = (node) => node.type === "Literal" && typeof node.value === "string" || node.type === "TemplateLiteral" && node.expressions.length === 0;
1617
+ const rule$1 = {
1618
+ meta: {
1619
+ type: "problem",
1620
+ docs: {
1621
+ description: "Validate the placeholders in `@step` descriptions against the method parameters.",
1622
+ url: docsUrl("step-placeholders")
1623
+ },
1624
+ fixable: "code",
1625
+ schema: [],
1626
+ messages: {
1627
+ singleBraces: "'{{found}}' is printed literally; use '{{expected}}' for a named placeholder.",
1628
+ whitespace: "'{{found}}' does not resolve, because @step does not trim the spaces inside placeholders; use '{{expected}}'.",
1629
+ unknownParameter: "Placeholder '{{found}}' does not match a parameter of '{{method}}' ({{params}}).",
1630
+ indexOutOfRange: "Placeholder '{{found}}' is out of range; '{{method}}' has {{count}} parameter(s).",
1631
+ notLast: "@step must be the decorator directly above the method, otherwise placeholders cannot be resolved."
1632
+ }
1633
+ },
1634
+ create(context) {
1635
+ const { stepDecorators } = conventionsFor(context);
1636
+ /** Reports a `{{path}}` placeholder in `description` that `@step` cannot resolve. */
1637
+ const checkNamed = (description, match, names, methodName) => {
1638
+ const problem = namedProblem(match[1], names);
1639
+ if (problem === "whitespace") {
1640
+ const from = description.range[0] + match.index;
1641
+ const range = [from, from + match[0].length];
1642
+ const expected = `{{${match[1].trim()}}}`;
1643
+ context.report({
1644
+ node: description,
1645
+ messageId: "whitespace",
1646
+ data: {
1647
+ found: match[0],
1648
+ expected
1649
+ },
1650
+ fix: (fixer) => fixer.replaceTextRange(range, expected)
1651
+ });
1652
+ } else if (problem === "unknownParameter") context.report({
1653
+ node: description,
1654
+ messageId: "unknownParameter",
1655
+ data: {
1656
+ found: match[0],
1657
+ method: methodName,
1658
+ params: names.filter(Boolean).join(", ") || "none"
1659
+ }
1660
+ });
1661
+ };
1662
+ return { Decorator(node) {
1663
+ if (!isStepDecorator(node, stepDecorators)) return;
1664
+ const method = node.parent;
1665
+ if (method.type !== "MethodDefinition") return;
1666
+ const { decorators } = method;
1667
+ if (decorators[decorators.length - 1] !== node) context.report({
1668
+ node,
1669
+ messageId: "notLast"
1670
+ });
1671
+ const { expression } = node;
1672
+ const description = expression.type === "CallExpression" ? expression.arguments[0] : void 0;
1673
+ if (!description || !isLiteralDescription(description)) return;
1674
+ const { params } = method.value;
1675
+ const names = params.map(paramName);
1676
+ const hasRest = params.some((param) => param.type === "RestElement");
1677
+ const methodName = context.sourceCode.getText(method.key);
1678
+ const raw = context.sourceCode.getText(description);
1679
+ const start = description.range[0];
1680
+ for (const match of findAll(NAMED, raw)) checkNamed(description, match, names, methodName);
1681
+ for (const match of findAll(INDEX, raw)) {
1682
+ const index = Number(match[1]);
1683
+ if (!hasRest && index >= params.length) context.report({
1684
+ node: description,
1685
+ messageId: "indexOutOfRange",
1686
+ data: {
1687
+ found: match[0],
1688
+ method: methodName,
1689
+ count: String(params.length)
1690
+ }
1691
+ });
1692
+ }
1693
+ for (const match of findAll(SINGLE_BRACES, raw)) {
1694
+ const placeholder = match[2];
1695
+ const from = start + match.index + match[1].length;
1696
+ const range = [from, from + placeholder.length + 2];
1697
+ const data = {
1698
+ found: `{${placeholder}}`,
1699
+ expected: `{{${placeholder}}}`
1700
+ };
1701
+ if (names.includes(placeholder.split(".")[0])) context.report({
1702
+ node: description,
1703
+ messageId: "singleBraces",
1704
+ data,
1705
+ fix: (fixer) => fixer.replaceTextRange(range, data.expected)
1706
+ });
1707
+ else context.report({
1708
+ node: description,
1709
+ messageId: "singleBraces",
1710
+ data
1711
+ });
1712
+ }
1713
+ } };
1714
+ }
1715
+ };
1716
+ // src/rules/step-required.ts
1717
+ const STEP_LAYERS = /* @__PURE__ */ new Set([
1718
+ "stepper",
1719
+ "asserter",
1720
+ "scenario"
1721
+ ]);
1722
+ // src/rules/index.ts
1723
+ const rules = {
1724
+ "architecture-boundaries": rule$12,
1725
+ "class-matches-filename": rule$11,
1726
+ "expect-from-support": rule$10,
1727
+ "file-naming": rule$9,
1728
+ "lines-between-class-members": rule$8,
1729
+ "no-direct-construction-in-tests": rule$7,
1730
+ "no-expect-in-tests": rule$6,
1731
+ "no-hard-waits": rule$5,
1732
+ "no-nested-polling": rule$4,
1733
+ "padding-lines": rule$3,
1734
+ "private-members-last": rule$2,
1735
+ "step-placeholders": rule$1,
1736
+ "step-required": {
1737
+ meta: {
1738
+ type: "suggestion",
1739
+ docs: {
1740
+ description: "Require a `@step` decorator on public methods of steppers, asserters and scenarios.",
1741
+ url: docsUrl("step-required")
1742
+ },
1743
+ schema: [],
1744
+ messages: { missingStep: "Public method '{{method}}' in a {{layer}} needs a @step decorator so it is visible in the report." }
1745
+ },
1746
+ create(context) {
1747
+ const conventions = conventionsFor(context);
1748
+ const info = classify(context.filename, conventions, rootFor(context, conventions));
1749
+ const layer = info?.kind === "top-scenario" ? "scenario" : info?.layer;
1750
+ if (layer === void 0 || !STEP_LAYERS.has(layer)) return {};
1751
+ return { MethodDefinition(node) {
1752
+ 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;
1753
+ context.report({
1754
+ node: node.key,
1755
+ messageId: "missingStep",
1756
+ data: {
1757
+ method: context.sourceCode.getText(node.key),
1758
+ layer
1759
+ }
1760
+ });
1761
+ } };
1762
+ }
1763
+ }
1764
+ };
1765
+ const PLUGIN_NAME = "sparta";
1766
+ /** Recommended severities: `problem` rules are errors, `suggestion` and `layout` rules are warnings. */
1767
+ const recommendedRules = Object.fromEntries(Object.entries(rules).map(([name, rule]) => [`${PLUGIN_NAME}/${name}`, rule.meta?.type === "problem" ? "error" : "warn"]));
1768
+ export { recommendedRules as n, rules as r, PLUGIN_NAME as t };
1769
+
1770
+ //# sourceMappingURL=rules-BSRYNh4F.mjs.map