@cerios/sparta-lint-rules 0.0.0-stage → 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.
- package/LICENSE +8 -0
- package/README.md +251 -2
- package/dist/index.cjs +18 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.mjs +18 -0
- package/dist/index.mjs.map +1 -0
- package/dist/oxlint.cjs +18 -0
- package/dist/oxlint.cjs.map +1 -0
- package/dist/oxlint.d.cts +13 -0
- package/dist/oxlint.d.mts +13 -0
- package/dist/oxlint.mjs +19 -0
- package/dist/oxlint.mjs.map +1 -0
- package/dist/plugin-types-CXFDQLJF.d.cts +38 -0
- package/dist/plugin-types-CXFDQLJF.d.mts +38 -0
- package/dist/rules-D94N3gGx.mjs +2449 -0
- package/dist/rules-D94N3gGx.mjs.map +1 -0
- package/dist/rules-T_C5segG.cjs +2488 -0
- package/dist/rules-T_C5segG.cjs.map +1 -0
- package/dist/settings.cjs +0 -0
- package/dist/settings.d.cts +105 -0
- package/dist/settings.d.mts +105 -0
- package/dist/settings.mjs +1 -0
- package/package.json +120 -5
|
@@ -0,0 +1,2488 @@
|
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __copyProps = (to, from, except, desc) => {
|
|
9
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
10
|
+
key = keys[i];
|
|
11
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
12
|
+
get: ((k) => from[k]).bind(null, key),
|
|
13
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
19
|
+
value: mod,
|
|
20
|
+
enumerable: true
|
|
21
|
+
}) : target, mod));
|
|
22
|
+
let node_path = require("node:path");
|
|
23
|
+
node_path = __toESM(node_path);
|
|
24
|
+
let node_fs = require("node:fs");
|
|
25
|
+
let node_module = require("node:module");
|
|
26
|
+
let oxc_parser = require("oxc-parser");
|
|
27
|
+
// src/utils/ast.ts
|
|
28
|
+
const isIdentifier = (node, name) => node?.type === "Identifier" && node.name === name;
|
|
29
|
+
/** The value of a string literal node, or `undefined` for any other node. */
|
|
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);
|
|
33
|
+
/** True for `@step` and `@step("...")` decorators, or any of the given decorator `names`. */
|
|
34
|
+
const isStepDecorator = (decorator, names) => {
|
|
35
|
+
const { expression } = decorator;
|
|
36
|
+
const callee = expression.type === "CallExpression" ? expression.callee : expression;
|
|
37
|
+
return callee.type === "Identifier" && names.has(callee.name);
|
|
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
|
+
}
|
|
76
|
+
// src/utils/docs.ts
|
|
77
|
+
const REPOSITORY = "https://github.com/CeriosTesting/sparta-lint-rules";
|
|
78
|
+
const docsUrl = (ruleName) => `${REPOSITORY}/blob/main/docs/rules/${ruleName}.md`;
|
|
79
|
+
// src/utils/conventions.ts
|
|
80
|
+
/** The standard layer folders, with the layer the architecture rules know them as and their file name suffix. */
|
|
81
|
+
const LAYER_FOLDERS = {
|
|
82
|
+
asserters: {
|
|
83
|
+
layer: "asserter",
|
|
84
|
+
suffix: "asserter"
|
|
85
|
+
},
|
|
86
|
+
builders: {
|
|
87
|
+
layer: "builder",
|
|
88
|
+
suffix: "builder"
|
|
89
|
+
},
|
|
90
|
+
clients: {
|
|
91
|
+
layer: "client",
|
|
92
|
+
suffix: "client"
|
|
93
|
+
},
|
|
94
|
+
components: {
|
|
95
|
+
layer: "component",
|
|
96
|
+
suffix: "component"
|
|
97
|
+
},
|
|
98
|
+
containers: { layer: "container" },
|
|
99
|
+
databases: { layer: "database" },
|
|
100
|
+
directors: {
|
|
101
|
+
layer: "director",
|
|
102
|
+
suffix: "director"
|
|
103
|
+
},
|
|
104
|
+
factories: { suffix: "factory" },
|
|
105
|
+
pages: {
|
|
106
|
+
layer: "page",
|
|
107
|
+
suffix: "page"
|
|
108
|
+
},
|
|
109
|
+
repositories: {
|
|
110
|
+
layer: "repository",
|
|
111
|
+
suffix: "repository"
|
|
112
|
+
},
|
|
113
|
+
scenarios: {
|
|
114
|
+
layer: "scenario",
|
|
115
|
+
suffix: "scenario"
|
|
116
|
+
},
|
|
117
|
+
screens: {
|
|
118
|
+
layer: "screen",
|
|
119
|
+
suffix: "screen"
|
|
120
|
+
},
|
|
121
|
+
services: {
|
|
122
|
+
layer: "service",
|
|
123
|
+
suffix: "service"
|
|
124
|
+
},
|
|
125
|
+
steppers: {
|
|
126
|
+
layer: "stepper",
|
|
127
|
+
suffix: "stepper"
|
|
128
|
+
},
|
|
129
|
+
windows: {
|
|
130
|
+
layer: "window",
|
|
131
|
+
suffix: "window"
|
|
132
|
+
}
|
|
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"]);
|
|
136
|
+
const AREAS = [
|
|
137
|
+
"api",
|
|
138
|
+
"database",
|
|
139
|
+
"desktop",
|
|
140
|
+
"mobile",
|
|
141
|
+
"ui"
|
|
142
|
+
];
|
|
143
|
+
/** Folders directly below the sparta folder that are not areas. */
|
|
144
|
+
const TOP_LEVEL_FOLDERS = [
|
|
145
|
+
"common",
|
|
146
|
+
"fixtures",
|
|
147
|
+
"scenarios",
|
|
148
|
+
"support"
|
|
149
|
+
];
|
|
150
|
+
const POLLING_METHODS = [
|
|
151
|
+
"toPass",
|
|
152
|
+
"toPassAndReturn",
|
|
153
|
+
"poll",
|
|
154
|
+
"pollAndReturn"
|
|
155
|
+
];
|
|
156
|
+
const PREFIX = "[@cerios/sparta-lint-rules]";
|
|
157
|
+
var SettingsError = class extends Error {
|
|
158
|
+
constructor(where, problem) {
|
|
159
|
+
super(`${PREFIX} settings.sparta${where}: ${problem}`);
|
|
160
|
+
this.name = "SettingsError";
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
164
|
+
const distance = (a, b) => {
|
|
165
|
+
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
166
|
+
for (let i = 1; i <= a.length; i++) {
|
|
167
|
+
const current = [i];
|
|
168
|
+
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));
|
|
169
|
+
previous = current;
|
|
170
|
+
}
|
|
171
|
+
return previous[b.length];
|
|
172
|
+
};
|
|
173
|
+
/** `; did you mean "x"?` for the closest candidate, if it is close enough to be a typo. */
|
|
174
|
+
const suggest = (value, candidates) => {
|
|
175
|
+
const [best] = candidates.map((candidate) => ({
|
|
176
|
+
candidate,
|
|
177
|
+
score: distance(value.toLowerCase(), candidate.toLowerCase())
|
|
178
|
+
})).toSorted((a, b) => a.score - b.score);
|
|
179
|
+
return best && best.score <= Math.max(2, Math.floor(best.candidate.length / 3)) ? `; did you mean ${JSON.stringify(best.candidate)}?` : "";
|
|
180
|
+
};
|
|
181
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
182
|
+
function record(value, where) {
|
|
183
|
+
if (!isRecord$1(value)) throw new SettingsError(where, `must be an object, got ${JSON.stringify(value)}.`);
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
function checkKeys(value, allowed, where) {
|
|
187
|
+
for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new SettingsError(where, `unknown setting ${JSON.stringify(key)}${suggest(key, allowed)}`);
|
|
188
|
+
}
|
|
189
|
+
function nonEmptyString(value, where) {
|
|
190
|
+
if (typeof value !== "string" || value.trim() === "") throw new SettingsError(where, `must be a non-empty string, got ${JSON.stringify(value)}.`);
|
|
191
|
+
return value;
|
|
192
|
+
}
|
|
193
|
+
function folderName(value, where) {
|
|
194
|
+
const name = nonEmptyString(value, where);
|
|
195
|
+
if (/[/\\]/.test(name) || name === "." || name === "..") throw new SettingsError(where, `must be a single folder name, got ${JSON.stringify(name)}.`);
|
|
196
|
+
return name;
|
|
197
|
+
}
|
|
198
|
+
function identifiers(value, where) {
|
|
199
|
+
if (!Array.isArray(value)) throw new SettingsError(where, `must be an array of names, got ${JSON.stringify(value)}.`);
|
|
200
|
+
return value.map((item, index) => {
|
|
201
|
+
const name = nonEmptyString(item, `${where}[${index}]`);
|
|
202
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name)) throw new SettingsError(`${where}[${index}]`, `must be an identifier, got ${JSON.stringify(name)}.`);
|
|
203
|
+
return name;
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Maps the project's own names onto standard ones. A name that is already standard may only map onto itself,
|
|
208
|
+
* and `reserved` names may not be used at all, so a setting can never turn one concept into another.
|
|
209
|
+
*/
|
|
210
|
+
function mapping(value, where, targets, describe, reserved = []) {
|
|
211
|
+
const result = /* @__PURE__ */ new Map();
|
|
212
|
+
for (const [name, target] of Object.entries(record(value, where))) {
|
|
213
|
+
const at = `${where}.${name}`;
|
|
214
|
+
folderName(name, at);
|
|
215
|
+
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(", ")}.`);
|
|
216
|
+
if (targets.includes(name) && name !== target) throw new SettingsError(at, `${JSON.stringify(name)} is already the standard ${describe} ${JSON.stringify(name)}.`);
|
|
217
|
+
if (reserved.includes(name)) throw new SettingsError(at, `${JSON.stringify(name)} is a reserved SPARTA folder.`);
|
|
218
|
+
result.set(name, target);
|
|
219
|
+
}
|
|
220
|
+
return result;
|
|
221
|
+
}
|
|
222
|
+
/** `@app/*`, `@app/` and `@app` all become the prefix `@app/`. */
|
|
223
|
+
function aliasPrefix(alias, where) {
|
|
224
|
+
const prefix = `${alias.replace(/\/?\*?$/, "")}/`;
|
|
225
|
+
if (prefix === "/" || alias.startsWith(".") || alias.startsWith("/")) throw new SettingsError(where, `must be an alias such as "@app/*", got ${JSON.stringify(alias)}.`);
|
|
226
|
+
return prefix;
|
|
227
|
+
}
|
|
228
|
+
const SETTINGS_KEYS = [
|
|
229
|
+
"root",
|
|
230
|
+
"folders",
|
|
231
|
+
"areas",
|
|
232
|
+
"layers",
|
|
233
|
+
"aliases",
|
|
234
|
+
"supportModule",
|
|
235
|
+
"pollingMethods",
|
|
236
|
+
"stepDecorators",
|
|
237
|
+
"expectNames"
|
|
238
|
+
];
|
|
239
|
+
function parseFolders(value) {
|
|
240
|
+
const folders = value === void 0 ? {} : record(value, ".folders");
|
|
241
|
+
checkKeys(folders, ["sparta", "tests"], ".folders");
|
|
242
|
+
const spartaFolder = folders.sparta === void 0 ? "sparta" : folderName(folders.sparta, ".folders.sparta");
|
|
243
|
+
const testsFolder = folders.tests === void 0 ? "tests" : folderName(folders.tests, ".folders.tests");
|
|
244
|
+
if (spartaFolder === testsFolder) throw new SettingsError(".folders", `sparta and tests must be different folders, both are ${JSON.stringify(spartaFolder)}.`);
|
|
245
|
+
return {
|
|
246
|
+
spartaFolder,
|
|
247
|
+
testsFolder
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
/** The standard names, each mapped onto itself, plus the project's own names. */
|
|
251
|
+
function withStandard(standard, custom) {
|
|
252
|
+
return new Map([...standard.map((name) => [name, name]), ...custom ?? []]);
|
|
253
|
+
}
|
|
254
|
+
function parseAliases(value) {
|
|
255
|
+
const aliases = /* @__PURE__ */ new Map([["@sparta/", "sparta"], ["@tests/", "tests"]]);
|
|
256
|
+
if (value === void 0) return aliases;
|
|
257
|
+
for (const [alias, target] of Object.entries(record(value, ".aliases"))) {
|
|
258
|
+
const at = `.aliases.${alias}`;
|
|
259
|
+
const prefix = aliasPrefix(alias, at);
|
|
260
|
+
if (target !== "sparta" && target !== "tests") throw new SettingsError(at, `must point to "sparta" or "tests", got ${JSON.stringify(target)}.`);
|
|
261
|
+
if (aliases.has(prefix) && aliases.get(prefix) !== target) throw new SettingsError(at, `${JSON.stringify(alias)} already points to ${JSON.stringify(aliases.get(prefix))}.`);
|
|
262
|
+
aliases.set(prefix, target);
|
|
263
|
+
}
|
|
264
|
+
return aliases;
|
|
265
|
+
}
|
|
266
|
+
/** The default names plus the configured extra ones. */
|
|
267
|
+
const withExtra = (defaults, value, where) => /* @__PURE__ */ new Set([...defaults, ...value === void 0 ? [] : identifiers(value, where)]);
|
|
268
|
+
function buildPatterns(spartaFolder, testsFolder, areas) {
|
|
269
|
+
const sparta = escape(spartaFolder);
|
|
270
|
+
const tests = escape(testsFolder);
|
|
271
|
+
const areaNames = [...areas.keys()].map(escape).join("|");
|
|
272
|
+
const end = "(?=/|$)";
|
|
273
|
+
return {
|
|
274
|
+
area: new RegExp(`/${sparta}/(${areaNames})${end}(?:/([^/]+))?(?:/([^/]+))?`),
|
|
275
|
+
layer: new RegExp(`/${sparta}/(?:${areaNames})/[^/]+/([^/]+)/`),
|
|
276
|
+
top: new RegExp(`/${sparta}/(${TOP_LEVEL_FOLDERS.join("|")})${end}`),
|
|
277
|
+
checked: new RegExp(`/(?:${sparta}|${tests})/`),
|
|
278
|
+
sparta: new RegExp(`/${sparta}/`),
|
|
279
|
+
tests: new RegExp(`/${tests}${end}`),
|
|
280
|
+
framework: new RegExp(`/${tests}/framework${end}`)
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const STANDARD_LAYER_FOLDERS = Object.keys(LAYER_FOLDERS);
|
|
284
|
+
/**
|
|
285
|
+
* Validates `settings.sparta` and resolves it against the defaults. Throws a descriptive error for anything it
|
|
286
|
+
* does not understand, so a typo cannot silently weaken the checks. A relative `root` resolves against `cwd`.
|
|
287
|
+
*/
|
|
288
|
+
function parseSettings(raw, cwd) {
|
|
289
|
+
const settings = raw === void 0 || raw === null ? {} : record(raw, "");
|
|
290
|
+
checkKeys(settings, SETTINGS_KEYS, "");
|
|
291
|
+
const root = settings.root === void 0 ? void 0 : node_path.default.resolve(cwd, nonEmptyString(settings.root, ".root")).split("\\").join("/");
|
|
292
|
+
const { spartaFolder, testsFolder } = parseFolders(settings.folders);
|
|
293
|
+
const areas = withStandard(AREAS, settings.areas === void 0 ? void 0 : mapping(settings.areas, ".areas", AREAS, "area", TOP_LEVEL_FOLDERS));
|
|
294
|
+
const layerFolders = withStandard(STANDARD_LAYER_FOLDERS, settings.layers === void 0 ? void 0 : mapping(settings.layers, ".layers", STANDARD_LAYER_FOLDERS, "layer folder", ["common"]));
|
|
295
|
+
return {
|
|
296
|
+
key: JSON.stringify(raw ?? null) + (root ?? ""),
|
|
297
|
+
root,
|
|
298
|
+
spartaFolder,
|
|
299
|
+
testsFolder,
|
|
300
|
+
areas,
|
|
301
|
+
layerFolders,
|
|
302
|
+
aliases: [...parseAliases(settings.aliases)].toSorted(([a], [b]) => b.length - a.length),
|
|
303
|
+
supportModule: settings.supportModule === void 0 ? "@sparta/support" : nonEmptyString(settings.supportModule, ".supportModule"),
|
|
304
|
+
pollingMethods: withExtra(POLLING_METHODS, settings.pollingMethods, ".pollingMethods"),
|
|
305
|
+
stepDecorators: withExtra(["step"], settings.stepDecorators, ".stepDecorators"),
|
|
306
|
+
expectNames: withExtra([], settings.expectNames, ".expectNames"),
|
|
307
|
+
patterns: buildPatterns(spartaFolder, testsFolder, areas)
|
|
308
|
+
};
|
|
309
|
+
}
|
|
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
|
+
}
|
|
501
|
+
// src/utils/sparta-paths.ts
|
|
502
|
+
const normalize = (value) => value.split("\\").join("/");
|
|
503
|
+
const TOP_LEVEL_KINDS = {
|
|
504
|
+
fixtures: "fixture",
|
|
505
|
+
scenarios: "top-scenario"
|
|
506
|
+
};
|
|
507
|
+
/** The standard layer folder that a project's folder name follows, if any. */
|
|
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
|
+
};
|
|
520
|
+
const caseInsensitivePaths = process.platform === "win32";
|
|
521
|
+
/**
|
|
522
|
+
* The part of `filename` below the project `root`, with a leading `/` (`/sparta/ui/...`), or `undefined` for files
|
|
523
|
+
* outside the root. Only this part is matched against the SPARTA folder names, so folders above the project (such
|
|
524
|
+
* as a checkout inside a folder named `tests`) never change how a file is classified.
|
|
525
|
+
*/
|
|
526
|
+
function projectPath(filename, root) {
|
|
527
|
+
const file = normalize(filename);
|
|
528
|
+
const base = normalize(root).replace(/\/$/, "");
|
|
529
|
+
const prefix = file.slice(0, base.length);
|
|
530
|
+
return (caseInsensitivePaths ? prefix.toLowerCase() === base.toLowerCase() : prefix === base) && file[base.length] === "/" ? file.slice(base.length) : void 0;
|
|
531
|
+
}
|
|
532
|
+
/** What a file is in the SPARTA architecture, judged by its path below `root`. */
|
|
533
|
+
function classify(filename, conventions, root) {
|
|
534
|
+
const file = projectPath(filename, root);
|
|
535
|
+
const { patterns } = conventions;
|
|
536
|
+
if (file === void 0 || patterns.framework.test(file)) return void 0;
|
|
537
|
+
if (patterns.tests.test(file)) return { kind: "test" };
|
|
538
|
+
const area = file.match(patterns.area);
|
|
539
|
+
if (area) {
|
|
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
|
+
};
|
|
548
|
+
const base = file.match(/-base-(client|repository|service)(?:\.[cm]?[jt]s)?$/)?.[1];
|
|
549
|
+
const layer = base ? `base-${base}` : layerOf(standardFolder(conventions, folder));
|
|
550
|
+
return {
|
|
551
|
+
kind: group === "common" ? "area-common" : "group",
|
|
552
|
+
area: conventions.areas.get(areaName),
|
|
553
|
+
areaFolder: areaName,
|
|
554
|
+
group,
|
|
555
|
+
layer
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
const top = file.match(patterns.top)?.[1];
|
|
559
|
+
return top ? { kind: TOP_LEVEL_KINDS[top] ?? "shared" } : void 0;
|
|
560
|
+
}
|
|
561
|
+
/** Project root per directory, kept for the lifetime of the linter process. */
|
|
562
|
+
const rootCache = /* @__PURE__ */ new Map();
|
|
563
|
+
/**
|
|
564
|
+
* The project root of a file: the nearest directory, from the file upwards, that contains a `package.json`.
|
|
565
|
+
* Falls back to the working directory when there is none.
|
|
566
|
+
*/
|
|
567
|
+
function projectRoot(filename) {
|
|
568
|
+
const visited = [];
|
|
569
|
+
let root;
|
|
570
|
+
for (let dir = node_path.default.dirname(node_path.default.resolve(filename));;) {
|
|
571
|
+
root = rootCache.get(dir);
|
|
572
|
+
if (root !== void 0) break;
|
|
573
|
+
visited.push(dir);
|
|
574
|
+
if ((0, node_fs.existsSync)(node_path.default.join(dir, "package.json"))) {
|
|
575
|
+
root = normalize(dir);
|
|
576
|
+
break;
|
|
577
|
+
}
|
|
578
|
+
const parent = node_path.default.dirname(dir);
|
|
579
|
+
if (parent === dir) {
|
|
580
|
+
root = normalize(process.cwd());
|
|
581
|
+
break;
|
|
582
|
+
}
|
|
583
|
+
dir = parent;
|
|
584
|
+
}
|
|
585
|
+
for (const dir of visited) rootCache.set(dir, root);
|
|
586
|
+
return root;
|
|
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;
|
|
605
|
+
/**
|
|
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`.
|
|
615
|
+
*/
|
|
616
|
+
function resolveImport(filename, request, root, conventions) {
|
|
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;
|
|
626
|
+
}
|
|
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
|
+
*/
|
|
631
|
+
const layerFolder = (filename, conventions, root) => {
|
|
632
|
+
const file = projectPath(filename, root);
|
|
633
|
+
if (file === void 0) return void 0;
|
|
634
|
+
if (file.match(conventions.patterns.top)?.[1] === "scenarios") return {
|
|
635
|
+
name: "scenarios",
|
|
636
|
+
standard: "scenarios"
|
|
637
|
+
};
|
|
638
|
+
const areaLayer = areaLayerFolder(file, conventions);
|
|
639
|
+
if (areaLayer) return areaLayer;
|
|
640
|
+
const folder = file.match(conventions.patterns.layer)?.[1];
|
|
641
|
+
return folder === void 0 ? void 0 : {
|
|
642
|
+
name: folder,
|
|
643
|
+
standard: standardFolder(conventions, folder)
|
|
644
|
+
};
|
|
645
|
+
};
|
|
646
|
+
/** The file name suffix the files in a layer folder must use (`stepper` for `steppers/`), if it has one. */
|
|
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);
|
|
652
|
+
/** True for files that follow the layer naming convention (layer folders and fixtures). */
|
|
653
|
+
const isLayerFile = (filename, conventions, root) => layerSuffix(layerFolder(filename, conventions, root)) !== void 0 || projectPath(filename, root)?.match(conventions.patterns.top)?.[1] === "fixtures";
|
|
654
|
+
// src/utils/settings.ts
|
|
655
|
+
/** Parsed settings per raw settings and working directory, kept for the lifetime of the linter process. */
|
|
656
|
+
const cache = /* @__PURE__ */ new Map();
|
|
657
|
+
/** The validated `settings.sparta` for this file. Throws a descriptive error for invalid settings. */
|
|
658
|
+
function conventionsFor(context) {
|
|
659
|
+
const raw = context.settings?.sparta;
|
|
660
|
+
const key = `${context.cwd}\0${JSON.stringify(raw ?? null)}`;
|
|
661
|
+
let conventions = cache.get(key);
|
|
662
|
+
if (conventions === void 0) {
|
|
663
|
+
conventions = parseSettings(raw, context.cwd);
|
|
664
|
+
cache.set(key, conventions);
|
|
665
|
+
}
|
|
666
|
+
return conventions;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* The project root the aliases resolve against: `settings.sparta.root` when set (relative paths resolve against
|
|
670
|
+
* the linter's working directory), otherwise the nearest folder with a `package.json`.
|
|
671
|
+
*/
|
|
672
|
+
const rootFor = (context, conventions = conventionsFor(context)) => conventions.root ?? projectRoot(context.filename);
|
|
673
|
+
// src/rules/architecture-boundaries.ts
|
|
674
|
+
const DATABASE_LAYERS = [
|
|
675
|
+
"asserter",
|
|
676
|
+
"base-repository",
|
|
677
|
+
"base-service",
|
|
678
|
+
"container",
|
|
679
|
+
"database",
|
|
680
|
+
"repository",
|
|
681
|
+
"scenario",
|
|
682
|
+
"service",
|
|
683
|
+
"stepper"
|
|
684
|
+
];
|
|
685
|
+
/** The UI layers; `view` is the area's name for a page (`page` for web, `screen` for mobile, `window` for desktop). */
|
|
686
|
+
const uiLayers = (view) => ({
|
|
687
|
+
component: /* @__PURE__ */ new Set([
|
|
688
|
+
view,
|
|
689
|
+
"stepper",
|
|
690
|
+
"asserter",
|
|
691
|
+
"scenario"
|
|
692
|
+
]),
|
|
693
|
+
[view]: /* @__PURE__ */ new Set([
|
|
694
|
+
"stepper",
|
|
695
|
+
"asserter",
|
|
696
|
+
"scenario"
|
|
697
|
+
]),
|
|
698
|
+
stepper: /* @__PURE__ */ new Set(["asserter", "scenario"]),
|
|
699
|
+
asserter: /* @__PURE__ */ new Set([
|
|
700
|
+
"stepper",
|
|
701
|
+
"asserter",
|
|
702
|
+
"scenario"
|
|
703
|
+
]),
|
|
704
|
+
scenario: /* @__PURE__ */ new Set([view, "component"])
|
|
705
|
+
});
|
|
706
|
+
/** Forbidden target layers inside the same area (API -> API, UI -> UI, database -> database, and so on). */
|
|
707
|
+
const FORBIDDEN_LAYERS = {
|
|
708
|
+
api: {
|
|
709
|
+
client: /* @__PURE__ */ new Set([
|
|
710
|
+
"client",
|
|
711
|
+
"service",
|
|
712
|
+
"base-service",
|
|
713
|
+
"stepper",
|
|
714
|
+
"asserter",
|
|
715
|
+
"scenario"
|
|
716
|
+
]),
|
|
717
|
+
"base-client": /* @__PURE__ */ new Set([
|
|
718
|
+
"client",
|
|
719
|
+
"base-client",
|
|
720
|
+
"service",
|
|
721
|
+
"base-service",
|
|
722
|
+
"stepper",
|
|
723
|
+
"asserter",
|
|
724
|
+
"scenario"
|
|
725
|
+
]),
|
|
726
|
+
service: /* @__PURE__ */ new Set([
|
|
727
|
+
"service",
|
|
728
|
+
"stepper",
|
|
729
|
+
"asserter",
|
|
730
|
+
"scenario"
|
|
731
|
+
]),
|
|
732
|
+
"base-service": /* @__PURE__ */ new Set([
|
|
733
|
+
"service",
|
|
734
|
+
"base-service",
|
|
735
|
+
"stepper",
|
|
736
|
+
"asserter",
|
|
737
|
+
"scenario"
|
|
738
|
+
]),
|
|
739
|
+
stepper: /* @__PURE__ */ new Set([
|
|
740
|
+
"client",
|
|
741
|
+
"base-client",
|
|
742
|
+
"asserter",
|
|
743
|
+
"scenario"
|
|
744
|
+
]),
|
|
745
|
+
asserter: /* @__PURE__ */ new Set([
|
|
746
|
+
"stepper",
|
|
747
|
+
"asserter",
|
|
748
|
+
"scenario"
|
|
749
|
+
]),
|
|
750
|
+
scenario: /* @__PURE__ */ new Set([
|
|
751
|
+
"service",
|
|
752
|
+
"base-service",
|
|
753
|
+
"client",
|
|
754
|
+
"base-client"
|
|
755
|
+
])
|
|
756
|
+
},
|
|
757
|
+
database: {
|
|
758
|
+
repository: /* @__PURE__ */ new Set([
|
|
759
|
+
"service",
|
|
760
|
+
"base-service",
|
|
761
|
+
"stepper",
|
|
762
|
+
"asserter",
|
|
763
|
+
"scenario"
|
|
764
|
+
]),
|
|
765
|
+
"base-repository": /* @__PURE__ */ new Set([
|
|
766
|
+
"repository",
|
|
767
|
+
"base-repository",
|
|
768
|
+
"service",
|
|
769
|
+
"base-service",
|
|
770
|
+
"stepper",
|
|
771
|
+
"asserter",
|
|
772
|
+
"scenario"
|
|
773
|
+
]),
|
|
774
|
+
service: /* @__PURE__ */ new Set([
|
|
775
|
+
"service",
|
|
776
|
+
"stepper",
|
|
777
|
+
"asserter",
|
|
778
|
+
"scenario"
|
|
779
|
+
]),
|
|
780
|
+
"base-service": /* @__PURE__ */ new Set([
|
|
781
|
+
"service",
|
|
782
|
+
"base-service",
|
|
783
|
+
"stepper",
|
|
784
|
+
"asserter",
|
|
785
|
+
"scenario"
|
|
786
|
+
]),
|
|
787
|
+
database: new Set(DATABASE_LAYERS),
|
|
788
|
+
container: new Set(DATABASE_LAYERS.filter((layer) => layer !== "database")),
|
|
789
|
+
stepper: /* @__PURE__ */ new Set([
|
|
790
|
+
"repository",
|
|
791
|
+
"base-repository",
|
|
792
|
+
"asserter",
|
|
793
|
+
"scenario"
|
|
794
|
+
]),
|
|
795
|
+
asserter: /* @__PURE__ */ new Set([
|
|
796
|
+
"repository",
|
|
797
|
+
"base-repository",
|
|
798
|
+
"stepper",
|
|
799
|
+
"asserter",
|
|
800
|
+
"scenario"
|
|
801
|
+
]),
|
|
802
|
+
scenario: /* @__PURE__ */ new Set([
|
|
803
|
+
"service",
|
|
804
|
+
"base-service",
|
|
805
|
+
"repository",
|
|
806
|
+
"base-repository"
|
|
807
|
+
])
|
|
808
|
+
},
|
|
809
|
+
desktop: uiLayers("window"),
|
|
810
|
+
mobile: uiLayers("screen"),
|
|
811
|
+
ui: uiLayers("page")
|
|
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
|
+
]);
|
|
822
|
+
const DATABASE_ACCESS = [
|
|
823
|
+
"repository",
|
|
824
|
+
"base-repository",
|
|
825
|
+
"service",
|
|
826
|
+
"base-service",
|
|
827
|
+
"container",
|
|
828
|
+
"database"
|
|
829
|
+
];
|
|
830
|
+
/** Layers that code orchestrating flows (top-level scenarios, tests) must not touch directly. */
|
|
831
|
+
const FORBIDDEN_FOR_ORCHESTRATION = {
|
|
832
|
+
"top-scenario": {
|
|
833
|
+
api: /* @__PURE__ */ new Set([
|
|
834
|
+
"client",
|
|
835
|
+
"base-client",
|
|
836
|
+
"service",
|
|
837
|
+
"base-service"
|
|
838
|
+
]),
|
|
839
|
+
database: new Set(DATABASE_ACCESS),
|
|
840
|
+
desktop: /* @__PURE__ */ new Set(["window", "component"]),
|
|
841
|
+
mobile: /* @__PURE__ */ new Set(["screen", "component"]),
|
|
842
|
+
ui: /* @__PURE__ */ new Set(["page", "component"])
|
|
843
|
+
},
|
|
844
|
+
test: {
|
|
845
|
+
api: /* @__PURE__ */ new Set([
|
|
846
|
+
"client",
|
|
847
|
+
"base-client",
|
|
848
|
+
"service",
|
|
849
|
+
"base-service",
|
|
850
|
+
"stepper",
|
|
851
|
+
"asserter"
|
|
852
|
+
]),
|
|
853
|
+
database: /* @__PURE__ */ new Set([
|
|
854
|
+
...DATABASE_ACCESS,
|
|
855
|
+
"stepper",
|
|
856
|
+
"asserter"
|
|
857
|
+
]),
|
|
858
|
+
desktop: /* @__PURE__ */ new Set([
|
|
859
|
+
"window",
|
|
860
|
+
"component",
|
|
861
|
+
"stepper",
|
|
862
|
+
"asserter"
|
|
863
|
+
]),
|
|
864
|
+
mobile: /* @__PURE__ */ new Set([
|
|
865
|
+
"screen",
|
|
866
|
+
"component",
|
|
867
|
+
"stepper",
|
|
868
|
+
"asserter"
|
|
869
|
+
]),
|
|
870
|
+
ui: /* @__PURE__ */ new Set([
|
|
871
|
+
"page",
|
|
872
|
+
"component",
|
|
873
|
+
"stepper",
|
|
874
|
+
"asserter"
|
|
875
|
+
])
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
const REEXPORT_LAYERS = /* @__PURE__ */ new Set([
|
|
879
|
+
"asserter",
|
|
880
|
+
"builder",
|
|
881
|
+
"client",
|
|
882
|
+
"base-client",
|
|
883
|
+
"base-repository",
|
|
884
|
+
"component",
|
|
885
|
+
"director",
|
|
886
|
+
"page",
|
|
887
|
+
"repository",
|
|
888
|
+
"scenario",
|
|
889
|
+
"screen",
|
|
890
|
+
"service",
|
|
891
|
+
"base-service",
|
|
892
|
+
"stepper",
|
|
893
|
+
"window"
|
|
894
|
+
]);
|
|
895
|
+
const describe = (info, { spartaFolder, testsFolder }) => ({
|
|
896
|
+
group: `${info.areaFolder}${info.group === void 0 ? "" : `/${info.group}`}${info.layer ? ` ${info.layer}` : ""}`,
|
|
897
|
+
"area-common": `${info.areaFolder}/common`,
|
|
898
|
+
"area-layer": `${info.areaFolder} ${info.layer}`,
|
|
899
|
+
"top-scenario": `${spartaFolder}/scenarios`,
|
|
900
|
+
fixture: `${spartaFolder}/fixtures`,
|
|
901
|
+
shared: `${spartaFolder}/common|support`,
|
|
902
|
+
test: testsFolder
|
|
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
|
+
}
|
|
912
|
+
/** Isolation compares area folders, not area types: `web/` and `ui/` are separate areas even when both follow `ui`. */
|
|
913
|
+
function isolationViolation(source, target) {
|
|
914
|
+
if (target.kind === "test") return source.kind !== "test";
|
|
915
|
+
if (source.kind === "shared") return [
|
|
916
|
+
"group",
|
|
917
|
+
"area-common",
|
|
918
|
+
"area-layer",
|
|
919
|
+
"fixture",
|
|
920
|
+
"top-scenario"
|
|
921
|
+
].includes(target.kind);
|
|
922
|
+
if (source.kind === "area-common") {
|
|
923
|
+
if ([
|
|
924
|
+
"fixture",
|
|
925
|
+
"top-scenario",
|
|
926
|
+
"group",
|
|
927
|
+
"area-layer"
|
|
928
|
+
].includes(target.kind)) return true;
|
|
929
|
+
return target.kind === "area-common" && target.areaFolder !== source.areaFolder;
|
|
930
|
+
}
|
|
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);
|
|
940
|
+
}
|
|
941
|
+
function layerViolation(source, target) {
|
|
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;
|
|
945
|
+
if (source.kind === "group" || source.kind === "area-common") {
|
|
946
|
+
if (!source.area || !source.layer) return false;
|
|
947
|
+
return source.areaFolder === target.areaFolder && Boolean(FORBIDDEN_LAYERS[source.area][source.layer]?.has(target.layer));
|
|
948
|
+
}
|
|
949
|
+
if (source.kind === "top-scenario" || source.kind === "test") return FORBIDDEN_FOR_ORCHESTRATION[source.kind][target.area].has(target.layer);
|
|
950
|
+
return false;
|
|
951
|
+
}
|
|
952
|
+
const isForbiddenReexport = (source, target) => target.layer !== void 0 && REEXPORT_LAYERS.has(target.layer) && target.layer !== source.layer && !["fixture", "test"].includes(source.kind);
|
|
953
|
+
const rule$13 = {
|
|
954
|
+
meta: {
|
|
955
|
+
type: "problem",
|
|
956
|
+
docs: {
|
|
957
|
+
description: "Enforce the SPARTA layer and isolation boundaries between imports.",
|
|
958
|
+
url: docsUrl("architecture-boundaries")
|
|
959
|
+
},
|
|
960
|
+
schema: [],
|
|
961
|
+
messages: {
|
|
962
|
+
isolation: "{{source}} must not depend on {{target}} ({{request}}). Move shared code to the area's common/ folder or the top-level common/ folder.",
|
|
963
|
+
layer: "{{source}} must not depend on {{target}} ({{request}}).",
|
|
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."
|
|
967
|
+
}
|
|
968
|
+
},
|
|
969
|
+
create(context) {
|
|
970
|
+
const filename = context.filename;
|
|
971
|
+
const conventions = conventionsFor(context);
|
|
972
|
+
const root = rootFor(context, conventions);
|
|
973
|
+
const source = classify(filename, conventions, root);
|
|
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;
|
|
979
|
+
const check = (node, request, reexport = false) => {
|
|
980
|
+
if (request === void 0) return;
|
|
981
|
+
const resolved = resolveImport(filename, request, root, conventions);
|
|
982
|
+
const target = resolved ? classify(resolved, conventions, root) : void 0;
|
|
983
|
+
if (!target || isOwnBarrel(target)) return;
|
|
984
|
+
const data = {
|
|
985
|
+
source: describe(source, conventions),
|
|
986
|
+
target: describe(target, conventions),
|
|
987
|
+
request
|
|
988
|
+
};
|
|
989
|
+
if (isolationViolation(source, target)) context.report({
|
|
990
|
+
node,
|
|
991
|
+
messageId: "isolation",
|
|
992
|
+
data
|
|
993
|
+
});
|
|
994
|
+
else if (layerViolation(source, target)) context.report({
|
|
995
|
+
node,
|
|
996
|
+
messageId: "layer",
|
|
997
|
+
data
|
|
998
|
+
});
|
|
999
|
+
else if (source.kind === "area-layer" && target.layer === "service" && !isNormalClass) context.report({
|
|
1000
|
+
node,
|
|
1001
|
+
messageId: "staticService",
|
|
1002
|
+
data
|
|
1003
|
+
});
|
|
1004
|
+
else if (reexport && isForbiddenReexport(source, target)) context.report({
|
|
1005
|
+
node,
|
|
1006
|
+
messageId: "reexport",
|
|
1007
|
+
data
|
|
1008
|
+
});
|
|
1009
|
+
};
|
|
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
|
+
},
|
|
1023
|
+
ImportDeclaration: (node) => check(node, stringValue(node.source)),
|
|
1024
|
+
ExportNamedDeclaration: (node) => check(node, stringValue(node.source), true),
|
|
1025
|
+
ExportAllDeclaration: (node) => check(node, stringValue(node.source), true),
|
|
1026
|
+
ImportExpression: (node) => check(node, staticString(node.source)),
|
|
1027
|
+
TSImportType: (node) => check(node, stringValue(node.source)),
|
|
1028
|
+
TSImportEqualsDeclaration(node) {
|
|
1029
|
+
if (node.moduleReference.type === "TSExternalModuleReference") check(node, stringValue(node.moduleReference.expression));
|
|
1030
|
+
},
|
|
1031
|
+
CallExpression(node) {
|
|
1032
|
+
if (node.callee.type === "Identifier" && node.callee.name === "require") check(node, staticString(node.arguments[0]));
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
// src/rules/class-matches-filename.ts
|
|
1038
|
+
const toPascalCase = (name) => name.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
1039
|
+
const classOf = (statement) => {
|
|
1040
|
+
const node = (statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") && statement.declaration ? statement.declaration : statement;
|
|
1041
|
+
return node.type === "ClassDeclaration" ? node : void 0;
|
|
1042
|
+
};
|
|
1043
|
+
const rule$12 = {
|
|
1044
|
+
meta: {
|
|
1045
|
+
type: "suggestion",
|
|
1046
|
+
docs: {
|
|
1047
|
+
description: "Require a layer file to contain exactly one class, named after the file in PascalCase.",
|
|
1048
|
+
url: docsUrl("class-matches-filename")
|
|
1049
|
+
},
|
|
1050
|
+
schema: [],
|
|
1051
|
+
messages: {
|
|
1052
|
+
name: "Class '{{found}}' must be named '{{expected}}' to match the file name.",
|
|
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}}'."
|
|
1055
|
+
}
|
|
1056
|
+
},
|
|
1057
|
+
create(context) {
|
|
1058
|
+
const conventions = conventionsFor(context);
|
|
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;
|
|
1065
|
+
return { Program(program) {
|
|
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) => {
|
|
1076
|
+
const found = node.id?.name ?? "(anonymous)";
|
|
1077
|
+
if (index > 0) context.report({
|
|
1078
|
+
node: node.id ?? node,
|
|
1079
|
+
messageId: "single",
|
|
1080
|
+
data: { found }
|
|
1081
|
+
});
|
|
1082
|
+
else if (found !== expected) context.report({
|
|
1083
|
+
node: node.id ?? node,
|
|
1084
|
+
messageId: "name",
|
|
1085
|
+
data: {
|
|
1086
|
+
found,
|
|
1087
|
+
expected
|
|
1088
|
+
}
|
|
1089
|
+
});
|
|
1090
|
+
});
|
|
1091
|
+
} };
|
|
1092
|
+
}
|
|
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
|
+
};
|
|
1156
|
+
// src/rules/expect-from-support.ts
|
|
1157
|
+
/** Files inside the sparta folder, except its support folder (where `expect` itself is defined). */
|
|
1158
|
+
const appliesTo = (filename, { patterns }, root) => {
|
|
1159
|
+
const file = projectPath(filename, root);
|
|
1160
|
+
return file !== void 0 && patterns.sparta.test(file) && file.match(patterns.top)?.[1] !== "support";
|
|
1161
|
+
};
|
|
1162
|
+
const rule$10 = {
|
|
1163
|
+
meta: {
|
|
1164
|
+
type: "problem",
|
|
1165
|
+
docs: {
|
|
1166
|
+
description: "Require `expect` to be imported from the support module (`@sparta/support`) inside sparta/.",
|
|
1167
|
+
url: docsUrl("expect-from-support")
|
|
1168
|
+
},
|
|
1169
|
+
fixable: "code",
|
|
1170
|
+
schema: [],
|
|
1171
|
+
messages: { expectFromSupport: "Import expect from '{{module}}' instead of '{{source}}'." }
|
|
1172
|
+
},
|
|
1173
|
+
create(context) {
|
|
1174
|
+
const conventions = conventionsFor(context);
|
|
1175
|
+
const { supportModule } = conventions;
|
|
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
|
+
};
|
|
1188
|
+
return { ImportDeclaration(node) {
|
|
1189
|
+
const source = node.source.value;
|
|
1190
|
+
if (isSupport(String(source))) return;
|
|
1191
|
+
const specifier = node.specifiers.find((item) => item.type === "ImportSpecifier" && item.imported.type === "Identifier" && item.imported.name === "expect");
|
|
1192
|
+
if (specifier === void 0) return;
|
|
1193
|
+
const data = {
|
|
1194
|
+
source: String(source),
|
|
1195
|
+
module: supportModule
|
|
1196
|
+
};
|
|
1197
|
+
if (node.specifiers.length !== 1) {
|
|
1198
|
+
context.report({
|
|
1199
|
+
node: specifier,
|
|
1200
|
+
messageId: "expectFromSupport",
|
|
1201
|
+
data
|
|
1202
|
+
});
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
context.report({
|
|
1206
|
+
node: specifier,
|
|
1207
|
+
messageId: "expectFromSupport",
|
|
1208
|
+
data,
|
|
1209
|
+
fix: (fixer) => fixer.replaceText(node.source, JSON.stringify(supportModule))
|
|
1210
|
+
});
|
|
1211
|
+
} };
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
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();
|
|
1219
|
+
const rule$9 = {
|
|
1220
|
+
meta: {
|
|
1221
|
+
type: "suggestion",
|
|
1222
|
+
docs: {
|
|
1223
|
+
description: "Require files in a layer folder to be kebab-case and end with the layer suffix (e.g. `orders-stepper.ts`).",
|
|
1224
|
+
url: docsUrl("file-naming")
|
|
1225
|
+
},
|
|
1226
|
+
schema: [],
|
|
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
|
+
}
|
|
1231
|
+
},
|
|
1232
|
+
create(context) {
|
|
1233
|
+
const conventions = conventionsFor(context);
|
|
1234
|
+
const folder = layerFolder(context.filename, conventions, rootFor(context, conventions));
|
|
1235
|
+
const suffix = layerSuffix(folder);
|
|
1236
|
+
const name = node_path.default.basename(context.filename);
|
|
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 {};
|
|
1242
|
+
return { Program(node) {
|
|
1243
|
+
if (!hasSuffix) context.report({
|
|
1244
|
+
node,
|
|
1245
|
+
messageId: "suffix",
|
|
1246
|
+
data: {
|
|
1247
|
+
folder: folder.name,
|
|
1248
|
+
suffix,
|
|
1249
|
+
name
|
|
1250
|
+
}
|
|
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
|
+
}
|
|
1263
|
+
} };
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
// src/rules/lines-between-class-members.ts
|
|
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;
|
|
1271
|
+
const rule$8 = {
|
|
1272
|
+
meta: {
|
|
1273
|
+
type: "layout",
|
|
1274
|
+
docs: {
|
|
1275
|
+
description: "Require a blank line after every multi-line method-like class member, and disallow blank lines between method overloads.",
|
|
1276
|
+
url: docsUrl("lines-between-class-members")
|
|
1277
|
+
},
|
|
1278
|
+
fixable: "whitespace",
|
|
1279
|
+
schema: [],
|
|
1280
|
+
messages: {
|
|
1281
|
+
expectedBlankLine: "Expected a blank line between class members.",
|
|
1282
|
+
unexpectedBlankLine: "Unexpected blank line between overloads of the same method."
|
|
1283
|
+
}
|
|
1284
|
+
},
|
|
1285
|
+
create(context) {
|
|
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);
|
|
1291
|
+
return { ClassBody(node) {
|
|
1292
|
+
for (let index = 1; index < node.body.length; index++) {
|
|
1293
|
+
const previous = node.body[index - 1];
|
|
1294
|
+
const current = node.body[index];
|
|
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;
|
|
1307
|
+
if (BLANK_LINE$1.test(textBetween)) continue;
|
|
1308
|
+
context.report({
|
|
1309
|
+
node: current,
|
|
1310
|
+
messageId: "expectedBlankLine",
|
|
1311
|
+
fix: (fixer) => {
|
|
1312
|
+
const lineBreak = textBetween.includes("\r\n") ? "\r\n" : "\n";
|
|
1313
|
+
const replacement = textBetween.includes(lineBreak) ? textBetween.replace(lineBreak, `${lineBreak}${lineBreak}`) : `${lineBreak}${lineBreak}${textBetween}`;
|
|
1314
|
+
return fixer.replaceTextRange([previous.range[1], current.range[0]], replacement);
|
|
1315
|
+
}
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
} };
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
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
|
+
};
|
|
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 = {
|
|
1469
|
+
meta: {
|
|
1470
|
+
type: "problem",
|
|
1471
|
+
docs: {
|
|
1472
|
+
description: "Disallow constructing SPARTA layer classes in tests; use the fixtures instead.",
|
|
1473
|
+
url: docsUrl("no-direct-construction-in-tests")
|
|
1474
|
+
},
|
|
1475
|
+
schema: [],
|
|
1476
|
+
messages: { useFixture: "Do not construct '{{name}}' in a test; use it via the SPARTA fixtures." }
|
|
1477
|
+
},
|
|
1478
|
+
create(context) {
|
|
1479
|
+
const conventions = conventionsFor(context);
|
|
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
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
};
|
|
1512
|
+
// src/rules/no-expect-in-tests.ts
|
|
1513
|
+
/**
|
|
1514
|
+
* Names of `expect` and its extensions: `expect`, `expectly`, `expectlyLocator`, `expectApi`, `expect_soft`.
|
|
1515
|
+
* `expected`, `expecting` and the like are left alone. `settings.sparta.expectNames` adds exact names.
|
|
1516
|
+
*/
|
|
1517
|
+
const EXPECT_NAME = /^expect(?:ly)?(?:[A-Z_$\d]|$)/;
|
|
1518
|
+
const rule$5 = {
|
|
1519
|
+
meta: {
|
|
1520
|
+
type: "problem",
|
|
1521
|
+
docs: {
|
|
1522
|
+
description: "Disallow `expect` in test files; checks belong in steppers and asserters.",
|
|
1523
|
+
url: docsUrl("no-expect-in-tests")
|
|
1524
|
+
},
|
|
1525
|
+
schema: [],
|
|
1526
|
+
messages: { noExpect: "Do not use expect in a test file. Put checkpoints in a stepper and technical or functional checks in an asserter." }
|
|
1527
|
+
},
|
|
1528
|
+
create(context) {
|
|
1529
|
+
const conventions = conventionsFor(context);
|
|
1530
|
+
if (classify(context.filename, conventions, rootFor(context, conventions))?.kind !== "test") return {};
|
|
1531
|
+
const isExpectName = (name) => EXPECT_NAME.test(name) || conventions.expectNames.has(name);
|
|
1532
|
+
/** Local names bound to an expect through a renamed import, such as `import { expect as check }`. */
|
|
1533
|
+
const aliases = /* @__PURE__ */ new Set();
|
|
1534
|
+
const isExpect = (node) => node.type === "Identifier" && (isExpectName(node.name) || aliases.has(node.name));
|
|
1535
|
+
return {
|
|
1536
|
+
ImportSpecifier(node) {
|
|
1537
|
+
const { imported, local } = node;
|
|
1538
|
+
const importedName = imported.type === "Identifier" ? imported.name : String(imported.value);
|
|
1539
|
+
if (!isExpectName(importedName) && !isExpectName(local.name)) return;
|
|
1540
|
+
aliases.add(local.name);
|
|
1541
|
+
context.report({
|
|
1542
|
+
node,
|
|
1543
|
+
messageId: "noExpect"
|
|
1544
|
+
});
|
|
1545
|
+
},
|
|
1546
|
+
CallExpression(node) {
|
|
1547
|
+
let callee = node.callee;
|
|
1548
|
+
while (callee.type === "MemberExpression") callee = callee.object;
|
|
1549
|
+
if (isExpect(callee)) context.report({
|
|
1550
|
+
node: node.callee,
|
|
1551
|
+
messageId: "noExpect"
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
};
|
|
1557
|
+
// src/rules/no-hard-waits.ts
|
|
1558
|
+
const TIMER_MODULES = /* @__PURE__ */ new Set(["timers/promises", "node:timers/promises"]);
|
|
1559
|
+
const isSetTimeout = (callee) => isIdentifier(callee, "setTimeout") || callee.type === "MemberExpression" && (isIdentifier(callee.object, "globalThis") || isIdentifier(callee.object, "window")) && isIdentifier(callee.property, "setTimeout");
|
|
1560
|
+
/** The `resolve` parameter of the nearest enclosing `new Promise(resolve => ...)` executor. */
|
|
1561
|
+
const promiseResolveName = (node) => {
|
|
1562
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
1563
|
+
if (current.type !== "ArrowFunctionExpression" && current.type !== "FunctionExpression") continue;
|
|
1564
|
+
const { parent } = current;
|
|
1565
|
+
if (parent.type === "NewExpression" && isIdentifier(parent.callee, "Promise") && parent.arguments[0] === current) {
|
|
1566
|
+
const [resolve] = current.params;
|
|
1567
|
+
return resolve?.type === "Identifier" ? resolve.name : void 0;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
/** True when the timer callback only resolves the promise, i.e. the timer is a plain sleep. */
|
|
1572
|
+
const resolvesPromise = (callback, resolve) => {
|
|
1573
|
+
if (!callback) return false;
|
|
1574
|
+
if (isIdentifier(callback, resolve)) return true;
|
|
1575
|
+
if (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression") return false;
|
|
1576
|
+
const { body } = callback;
|
|
1577
|
+
if (!body) return false;
|
|
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;
|
|
1579
|
+
return call?.type === "CallExpression" && isIdentifier(call.callee, resolve);
|
|
1580
|
+
};
|
|
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 = {
|
|
1590
|
+
meta: {
|
|
1591
|
+
type: "problem",
|
|
1592
|
+
docs: {
|
|
1593
|
+
description: "Disallow fixed-time waits such as `waitForTimeout` and `setTimeout` sleeps.",
|
|
1594
|
+
url: docsUrl("no-hard-waits")
|
|
1595
|
+
},
|
|
1596
|
+
schema: [],
|
|
1597
|
+
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." }
|
|
1598
|
+
},
|
|
1599
|
+
create(context) {
|
|
1600
|
+
const conventions = conventionsFor(context);
|
|
1601
|
+
const { patterns } = conventions;
|
|
1602
|
+
const file = projectPath(context.filename, rootFor(context, conventions));
|
|
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
|
+
};
|
|
1624
|
+
return {
|
|
1625
|
+
ImportDeclaration(node) {
|
|
1626
|
+
if (typeof node.source.value !== "string" || !TIMER_MODULES.has(node.source.value)) return;
|
|
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
|
+
}
|
|
1641
|
+
},
|
|
1642
|
+
CallExpression(node) {
|
|
1643
|
+
const { callee } = node;
|
|
1644
|
+
if (callee.type === "MemberExpression" && isIdentifier(callee.property, "waitForTimeout") || isTimersSleep(callee)) {
|
|
1645
|
+
context.report({
|
|
1646
|
+
node,
|
|
1647
|
+
messageId: "hardWait"
|
|
1648
|
+
});
|
|
1649
|
+
return;
|
|
1650
|
+
}
|
|
1651
|
+
if (!isSetTimeout(callee)) return;
|
|
1652
|
+
const resolve = promiseResolveName(node);
|
|
1653
|
+
if (resolve !== void 0 && resolvesPromise(node.arguments[0], resolve)) context.report({
|
|
1654
|
+
node,
|
|
1655
|
+
messageId: "hardWait"
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
};
|
|
1659
|
+
}
|
|
1660
|
+
};
|
|
1661
|
+
// src/utils/polling.ts
|
|
1662
|
+
/**
|
|
1663
|
+
* Retrying assertions are recognised by method name only, so `expect`, `expect.soft`, `expectly` and wrappers all
|
|
1664
|
+
* match. The names come from the conventions: `toPass`, `toPassAndReturn`, `poll`, `pollAndReturn`, plus
|
|
1665
|
+
* `settings.sparta.pollingMethods`.
|
|
1666
|
+
*/
|
|
1667
|
+
/** Methods that take the callback they retry as their own first argument (`expect.poll(cb)`). */
|
|
1668
|
+
const CALLBACK_ARGUMENT_METHODS = /* @__PURE__ */ new Set(["poll", "pollAndReturn"]);
|
|
1669
|
+
/** Methods that retry the callback given to the start of their chain (`expect(cb).toPass()`). */
|
|
1670
|
+
const CALLBACK_SUBJECT_METHODS = /* @__PURE__ */ new Set(["toPass", "toPassAndReturn"]);
|
|
1671
|
+
/** The static name of a member access (`a.b`, `a["b"]`), or `undefined` for computed or private access. */
|
|
1672
|
+
const memberName = (node) => {
|
|
1673
|
+
if (node.type !== "MemberExpression") return void 0;
|
|
1674
|
+
const { property } = node;
|
|
1675
|
+
if (!node.computed && property.type === "Identifier") return property.name;
|
|
1676
|
+
if (node.computed && property.type === "Literal" && typeof property.value === "string") return property.value;
|
|
1677
|
+
};
|
|
1678
|
+
/** The polling method a call invokes (`toPass` for `expect(cb).toPass()`), or `undefined` for any other node. */
|
|
1679
|
+
const pollingMethod = (node, methods) => {
|
|
1680
|
+
if (node.type !== "CallExpression") return void 0;
|
|
1681
|
+
const name = memberName(node.callee);
|
|
1682
|
+
return name !== void 0 && methods.has(name) ? name : void 0;
|
|
1683
|
+
};
|
|
1684
|
+
const isFunction$1 = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression";
|
|
1685
|
+
const firstArgument = (call) => {
|
|
1686
|
+
const [argument] = call.arguments;
|
|
1687
|
+
return argument?.type === "SpreadElement" ? void 0 : argument;
|
|
1688
|
+
};
|
|
1689
|
+
/** `X(cb).method()`: the first argument of the call the chain starts from, also through `.soft(cb)` and `.not`. */
|
|
1690
|
+
const subjectCallback = (call) => {
|
|
1691
|
+
if (call.callee.type !== "MemberExpression") return void 0;
|
|
1692
|
+
let object = call.callee.object;
|
|
1693
|
+
while (object.type === "MemberExpression") object = object.object;
|
|
1694
|
+
return object.type === "CallExpression" ? firstArgument(object) : void 0;
|
|
1695
|
+
};
|
|
1696
|
+
/**
|
|
1697
|
+
* The callback that a polling call retries:
|
|
1698
|
+
* - `X.poll(cb)` and `X.pollAndReturn(cb)`: the first argument.
|
|
1699
|
+
* - `X(cb).toPass()` and `X(cb).toPassAndReturn()`: the first argument of the call the chain starts from,
|
|
1700
|
+
* also through `.soft(cb)` and `.not`.
|
|
1701
|
+
* - other configured methods: the first argument when it is a function, otherwise the start of the chain.
|
|
1702
|
+
*/
|
|
1703
|
+
const pollCallback = (call, methods) => {
|
|
1704
|
+
const method = pollingMethod(call, methods);
|
|
1705
|
+
if (method === void 0 || call.callee.type !== "MemberExpression") return void 0;
|
|
1706
|
+
if (CALLBACK_ARGUMENT_METHODS.has(method)) return firstArgument(call);
|
|
1707
|
+
if (CALLBACK_SUBJECT_METHODS.has(method)) return subjectCallback(call);
|
|
1708
|
+
const argument = firstArgument(call);
|
|
1709
|
+
return isFunction$1(argument) ? argument : subjectCallback(call);
|
|
1710
|
+
};
|
|
1711
|
+
// src/utils/project-index.ts
|
|
1712
|
+
const MAX_DEPTH = 10;
|
|
1713
|
+
const SKIPPED_KEYS = /* @__PURE__ */ new Set([
|
|
1714
|
+
"parent",
|
|
1715
|
+
"loc",
|
|
1716
|
+
"range",
|
|
1717
|
+
"start",
|
|
1718
|
+
"end",
|
|
1719
|
+
"typeAnnotation",
|
|
1720
|
+
"returnType",
|
|
1721
|
+
"decorators"
|
|
1722
|
+
]);
|
|
1723
|
+
const isNode = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
|
|
1724
|
+
/** Visits `node` and its descendants depth-first. Returning `false` from `visit` skips the node's children. */
|
|
1725
|
+
function walk(node, visit) {
|
|
1726
|
+
if (visit(node) === false) return;
|
|
1727
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1728
|
+
if (SKIPPED_KEYS.has(key)) continue;
|
|
1729
|
+
if (Array.isArray(value)) {
|
|
1730
|
+
for (const item of value) if (isNode(item)) walk(item, visit);
|
|
1731
|
+
} else if (isNode(value)) walk(value, visit);
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
const isFunctionLike = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "FunctionDeclaration";
|
|
1735
|
+
/** `X` for a `: X` or `: X<T>` annotation. */
|
|
1736
|
+
const typeName = (annotation) => {
|
|
1737
|
+
const type = annotation?.typeAnnotation;
|
|
1738
|
+
return type?.type === "TSTypeReference" && type.typeName.type === "Identifier" ? type.typeName.name : void 0;
|
|
1739
|
+
};
|
|
1740
|
+
/** `X` for `new X(...)`. */
|
|
1741
|
+
const newName = (node) => node?.type === "NewExpression" && node.callee.type === "Identifier" ? node.callee.name : void 0;
|
|
1742
|
+
const keyName = (key) => key.type === "Identifier" ? key.name : key.type === "Literal" && typeof key.value === "string" ? key.value : void 0;
|
|
1743
|
+
function summarizeClass(name, node) {
|
|
1744
|
+
const info = {
|
|
1745
|
+
name,
|
|
1746
|
+
node,
|
|
1747
|
+
superClass: node.superClass?.type === "Identifier" ? node.superClass.name : void 0,
|
|
1748
|
+
methods: /* @__PURE__ */ new Map(),
|
|
1749
|
+
fields: /* @__PURE__ */ new Map()
|
|
1750
|
+
};
|
|
1751
|
+
for (const member of node.body.body) {
|
|
1752
|
+
if (member.type === "PropertyDefinition") summarizeField(info, member);
|
|
1753
|
+
if (member.type === "MethodDefinition") summarizeMethod(info, member);
|
|
1754
|
+
}
|
|
1755
|
+
return info;
|
|
1756
|
+
}
|
|
1757
|
+
/** A typed field (`x: X`), a field created with `new X()`, or a function-valued field, which acts as a method. */
|
|
1758
|
+
function summarizeField(info, member) {
|
|
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
|
+
}
|
|
1765
|
+
const type = typeName(member.typeAnnotation) ?? newName(member.value);
|
|
1766
|
+
if (type !== void 0) info.fields.set(field, type);
|
|
1767
|
+
}
|
|
1768
|
+
/** Methods, getters (whose return type acts as a field type) and the constructor. */
|
|
1769
|
+
function summarizeMethod(info, member) {
|
|
1770
|
+
const name = member.computed ? void 0 : keyName(member.key);
|
|
1771
|
+
const { value } = member;
|
|
1772
|
+
if (name === void 0 || value.type !== "FunctionExpression" || !value.body) return;
|
|
1773
|
+
if (member.kind === "constructor") summarizeConstructor(info, value);
|
|
1774
|
+
else if (member.kind === "get") {
|
|
1775
|
+
const type = typeName(value.returnType);
|
|
1776
|
+
if (type !== void 0) info.fields.set(name, type);
|
|
1777
|
+
} else if (member.kind === "method") info.methods.set(name, value);
|
|
1778
|
+
}
|
|
1779
|
+
/** Fields from constructor parameter properties and from `this.x = new X()` assignments. */
|
|
1780
|
+
function summarizeConstructor(info, constructor) {
|
|
1781
|
+
for (const param of constructor.params) {
|
|
1782
|
+
if (param.type !== "TSParameterProperty") continue;
|
|
1783
|
+
const binding = param.parameter.type === "AssignmentPattern" ? param.parameter.left : param.parameter;
|
|
1784
|
+
const type = binding.type === "Identifier" ? typeName(binding.typeAnnotation) : void 0;
|
|
1785
|
+
if (binding.type === "Identifier" && type !== void 0) info.fields.set(binding.name, type);
|
|
1786
|
+
}
|
|
1787
|
+
if (!constructor.body) return;
|
|
1788
|
+
walk(constructor.body, (node) => {
|
|
1789
|
+
if (node.type !== "AssignmentExpression" || node.left.type !== "MemberExpression") return;
|
|
1790
|
+
if (node.left.object.type !== "ThisExpression") return;
|
|
1791
|
+
const field = memberName(node.left);
|
|
1792
|
+
const type = newName(node.right);
|
|
1793
|
+
if (field !== void 0 && type !== void 0 && !info.fields.has(field)) info.fields.set(field, type);
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
const importedName = (node) => node.type === "Identifier" ? node.name : node.type === "Literal" ? String(node.value) : "";
|
|
1797
|
+
function summarizeDeclaration(summary, node, exported) {
|
|
1798
|
+
if ((node.type === "ClassDeclaration" || node.type === "ClassExpression") && node.id) {
|
|
1799
|
+
summary.classes.set(node.id.name, summarizeClass(node.id.name, node));
|
|
1800
|
+
if (exported !== void 0) summary.exports.set(exported === "" ? node.id.name : exported, node.id.name);
|
|
1801
|
+
} else if (node.type === "FunctionDeclaration" && node.id) {
|
|
1802
|
+
summary.functions.set(node.id.name, node);
|
|
1803
|
+
if (exported !== void 0) summary.exports.set(exported === "" ? node.id.name : exported, node.id.name);
|
|
1804
|
+
} else if (node.type === "VariableDeclaration") for (const declarator of node.declarations) {
|
|
1805
|
+
if (declarator.id.type !== "Identifier" || !isFunctionLike(declarator.init)) continue;
|
|
1806
|
+
summary.functions.set(declarator.id.name, declarator.init);
|
|
1807
|
+
if (exported !== void 0) summary.exports.set(declarator.id.name, declarator.id.name);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
/** Collects the imports, exports, classes and functions of a module. */
|
|
1811
|
+
function summarize(file, program, root, conventions) {
|
|
1812
|
+
const summary = {
|
|
1813
|
+
file,
|
|
1814
|
+
root,
|
|
1815
|
+
conventions,
|
|
1816
|
+
imports: /* @__PURE__ */ new Map(),
|
|
1817
|
+
classes: /* @__PURE__ */ new Map(),
|
|
1818
|
+
functions: /* @__PURE__ */ new Map(),
|
|
1819
|
+
exports: /* @__PURE__ */ new Map(),
|
|
1820
|
+
reexports: /* @__PURE__ */ new Map(),
|
|
1821
|
+
starExports: []
|
|
1822
|
+
};
|
|
1823
|
+
for (const statement of program.body) if (statement.type === "ImportDeclaration") summarizeImport(summary, statement);
|
|
1824
|
+
else if (statement.type === "ExportNamedDeclaration") summarizeNamedExport(summary, statement);
|
|
1825
|
+
else if (statement.type === "ExportDefaultDeclaration") {
|
|
1826
|
+
const { declaration } = statement;
|
|
1827
|
+
if (declaration.type === "Identifier") summary.exports.set("default", declaration.name);
|
|
1828
|
+
else summarizeDeclaration(summary, declaration, "default");
|
|
1829
|
+
} else if (statement.type === "ExportAllDeclaration") {
|
|
1830
|
+
const module = resolveModule(file, statement.source.value, root, conventions);
|
|
1831
|
+
if (!statement.exported && module !== void 0) summary.starExports.push(module);
|
|
1832
|
+
} else summarizeDeclaration(summary, statement, void 0);
|
|
1833
|
+
return summary;
|
|
1834
|
+
}
|
|
1835
|
+
function summarizeImport(summary, statement) {
|
|
1836
|
+
const module = resolveModule(summary.file, statement.source.value, summary.root, summary.conventions);
|
|
1837
|
+
for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier") summary.imports.set(specifier.local.name, {
|
|
1838
|
+
module,
|
|
1839
|
+
imported: importedName(specifier.imported)
|
|
1840
|
+
});
|
|
1841
|
+
else if (specifier.type === "ImportDefaultSpecifier") summary.imports.set(specifier.local.name, {
|
|
1842
|
+
module,
|
|
1843
|
+
imported: "default"
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
/** `export class X`, `export { X as Y }` and `export { X } from "..."`. */
|
|
1847
|
+
function summarizeNamedExport(summary, statement) {
|
|
1848
|
+
if (statement.declaration) {
|
|
1849
|
+
summarizeDeclaration(summary, statement.declaration, "");
|
|
1850
|
+
return;
|
|
1851
|
+
}
|
|
1852
|
+
const module = statement.source ? resolveModule(summary.file, statement.source.value, summary.root, summary.conventions) : void 0;
|
|
1853
|
+
for (const specifier of statement.specifiers) {
|
|
1854
|
+
const exported = importedName(specifier.exported);
|
|
1855
|
+
const local = importedName(specifier.local);
|
|
1856
|
+
if (statement.source) summary.reexports.set(exported, {
|
|
1857
|
+
module,
|
|
1858
|
+
imported: local
|
|
1859
|
+
});
|
|
1860
|
+
else summary.exports.set(exported, local);
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
/** Resolves a relative, aliased or tsconfig-mapped import to a TypeScript file. Package imports resolve to `undefined`. */
|
|
1864
|
+
function resolveModule(fromFile, request, root, conventions) {
|
|
1865
|
+
const base = resolveImport(fromFile, request, root, conventions);
|
|
1866
|
+
return base === void 0 ? void 0 : moduleFile(base);
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Summaries of files on disk per project root and conventions (imports resolve against them), kept for the lifetime of the
|
|
1870
|
+
* linter process and refreshed when a file changes.
|
|
1871
|
+
*/
|
|
1872
|
+
const diskCache = /* @__PURE__ */ new Map();
|
|
1873
|
+
function diskSummary(file, root, conventions) {
|
|
1874
|
+
const stats = (0, node_fs.statSync)(file, { throwIfNoEntry: false });
|
|
1875
|
+
if (!stats?.isFile()) return void 0;
|
|
1876
|
+
const key = `${conventions.key}\0${root}\0${file}`;
|
|
1877
|
+
const cached = diskCache.get(key);
|
|
1878
|
+
if (cached?.mtimeMs === stats.mtimeMs) return cached.summary;
|
|
1879
|
+
const { program } = (0, oxc_parser.parseSync)(file, (0, node_fs.readFileSync)(file, "utf8"));
|
|
1880
|
+
const summary = summarize(file, program, root, conventions);
|
|
1881
|
+
diskCache.set(key, {
|
|
1882
|
+
mtimeMs: stats.mtimeMs,
|
|
1883
|
+
summary
|
|
1884
|
+
});
|
|
1885
|
+
return summary;
|
|
1886
|
+
}
|
|
1887
|
+
/** Shows paths relative to the project root (`sparta/...`) instead of absolute ones. */
|
|
1888
|
+
const display = (file, root) => file.startsWith(`${root}/`) ? file.slice(root.length + 1) : node_path.default.basename(file);
|
|
1889
|
+
/**
|
|
1890
|
+
* Cross-file view for one linted file. The linted file uses the linter's in-memory AST (so unsaved
|
|
1891
|
+
* changes count); every other file is parsed from disk.
|
|
1892
|
+
*/
|
|
1893
|
+
var ProjectIndex = class {
|
|
1894
|
+
current;
|
|
1895
|
+
memo = /* @__PURE__ */ new Map();
|
|
1896
|
+
inProgress = /* @__PURE__ */ new Set();
|
|
1897
|
+
/** Summaries looked up while linting this file, so every other file is checked on disk at most once. */
|
|
1898
|
+
summaries = /* @__PURE__ */ new Map();
|
|
1899
|
+
/**
|
|
1900
|
+
* Counts the lookups cut short by a call cycle or by `MAX_DEPTH`. A "does not poll" answer computed while this
|
|
1901
|
+
* changed is only true for that call chain, so it is not cached.
|
|
1902
|
+
*/
|
|
1903
|
+
truncations = 0;
|
|
1904
|
+
constructor(current) {
|
|
1905
|
+
this.current = current;
|
|
1906
|
+
}
|
|
1907
|
+
/** Finds the polling calls, and the calls that lead to polling, inside `root`. Stops descending at a polling call. */
|
|
1908
|
+
collectHits(root, scope, depth = 0, firstOnly = false) {
|
|
1909
|
+
const hits = [];
|
|
1910
|
+
walk(root, (node) => {
|
|
1911
|
+
if (firstOnly && hits.length > 0) return false;
|
|
1912
|
+
if (node.type !== "CallExpression") return;
|
|
1913
|
+
const method = pollingMethod(node, this.current.conventions.pollingMethods);
|
|
1914
|
+
if (method !== void 0) {
|
|
1915
|
+
hits.push({
|
|
1916
|
+
node,
|
|
1917
|
+
method
|
|
1918
|
+
});
|
|
1919
|
+
return false;
|
|
1920
|
+
}
|
|
1921
|
+
const target = this.resolveCall(node, scope);
|
|
1922
|
+
const path = target ? this.pollingPath(target, depth + 1) : void 0;
|
|
1923
|
+
if (path) hits.push({
|
|
1924
|
+
node,
|
|
1925
|
+
path
|
|
1926
|
+
});
|
|
1927
|
+
});
|
|
1928
|
+
return hits;
|
|
1929
|
+
}
|
|
1930
|
+
/** The chain from `target` to a polling call, e.g. `["Page.open", "Page.find", "poll (sparta/.../page.ts)"]`. */
|
|
1931
|
+
pollingPath(target, depth = 0) {
|
|
1932
|
+
const label = target.kind === "method" ? `${target.cls.info.name}.${target.name}` : target.name;
|
|
1933
|
+
const key = `${target.file}#${label}`;
|
|
1934
|
+
const known = this.memo.get(key);
|
|
1935
|
+
if (known !== void 0) return known ?? void 0;
|
|
1936
|
+
if (!target.fn.body) return void 0;
|
|
1937
|
+
if (depth > MAX_DEPTH || this.inProgress.has(key)) {
|
|
1938
|
+
this.truncations++;
|
|
1939
|
+
return;
|
|
1940
|
+
}
|
|
1941
|
+
const truncationsBefore = this.truncations;
|
|
1942
|
+
this.inProgress.add(key);
|
|
1943
|
+
const scope = {
|
|
1944
|
+
file: target.file,
|
|
1945
|
+
cls: target.kind === "method" ? target.cls : void 0,
|
|
1946
|
+
locals: collectLocals(target.fn)
|
|
1947
|
+
};
|
|
1948
|
+
const [hit] = this.collectHits(target.fn.body, scope, depth, true);
|
|
1949
|
+
this.inProgress.delete(key);
|
|
1950
|
+
const result = hit ? "method" in hit ? [label, `${hit.method} (${display(target.file, this.current.root)})`] : [label, ...hit.path] : void 0;
|
|
1951
|
+
if (result !== void 0) this.memo.set(key, result);
|
|
1952
|
+
else if (this.truncations === truncationsBefore) this.memo.set(key, null);
|
|
1953
|
+
return result;
|
|
1954
|
+
}
|
|
1955
|
+
/** Resolves a call such as `fn()`, `this.method()`, `this.field.method()` or `local.method()`. */
|
|
1956
|
+
resolveCall(call, scope) {
|
|
1957
|
+
return this.resolveReference(call.callee, scope);
|
|
1958
|
+
}
|
|
1959
|
+
/** Resolves a reference to a function or method, such as `fn` or `this.page.method`. */
|
|
1960
|
+
resolveReference(node, scope) {
|
|
1961
|
+
if (node.type === "Identifier") {
|
|
1962
|
+
const found = this.resolveLocal(scope.file, node.name);
|
|
1963
|
+
const fn = found ? this.summary(found.file)?.functions.get(found.local) : void 0;
|
|
1964
|
+
return found && fn ? {
|
|
1965
|
+
kind: "function",
|
|
1966
|
+
file: found.file,
|
|
1967
|
+
name: found.local,
|
|
1968
|
+
fn
|
|
1969
|
+
} : void 0;
|
|
1970
|
+
}
|
|
1971
|
+
const method = memberName(node);
|
|
1972
|
+
if (method === void 0 || node.type !== "MemberExpression") return void 0;
|
|
1973
|
+
const receiver = this.receiverClass(node.object, scope);
|
|
1974
|
+
return receiver ? this.findMethod(receiver, method) : void 0;
|
|
1975
|
+
}
|
|
1976
|
+
/** Builds the scope for code in the linted file, inside `classNode` and the function `fn` (whose locals count). */
|
|
1977
|
+
scopeFor(classNode, fn) {
|
|
1978
|
+
const cls = [...this.current.classes.values()].find((info) => info.node === classNode);
|
|
1979
|
+
return {
|
|
1980
|
+
file: this.current.file,
|
|
1981
|
+
cls: cls ? {
|
|
1982
|
+
file: this.current.file,
|
|
1983
|
+
info: cls
|
|
1984
|
+
} : void 0,
|
|
1985
|
+
locals: isFunctionLike(fn) ? collectLocals(fn) : /* @__PURE__ */ new Map()
|
|
1986
|
+
};
|
|
1987
|
+
}
|
|
1988
|
+
summary(file) {
|
|
1989
|
+
if (file === this.current.file) return this.current;
|
|
1990
|
+
if (this.summaries.has(file)) return this.summaries.get(file);
|
|
1991
|
+
const summary = diskSummary(file, this.current.root, this.current.conventions);
|
|
1992
|
+
this.summaries.set(file, summary);
|
|
1993
|
+
return summary;
|
|
1994
|
+
}
|
|
1995
|
+
receiverClass(node, scope, depth = 0) {
|
|
1996
|
+
if (depth > MAX_DEPTH) return void 0;
|
|
1997
|
+
switch (node.type) {
|
|
1998
|
+
case "ThisExpression": return scope.cls;
|
|
1999
|
+
case "Identifier": {
|
|
2000
|
+
const type = scope.locals.get(node.name);
|
|
2001
|
+
return this.resolveClass(scope.file, type ?? node.name);
|
|
2002
|
+
}
|
|
2003
|
+
case "NewExpression": return node.callee.type === "Identifier" ? this.resolveClass(scope.file, node.callee.name) : void 0;
|
|
2004
|
+
case "TSNonNullExpression":
|
|
2005
|
+
case "ParenthesizedExpression": return this.receiverClass(node.expression, scope, depth + 1);
|
|
2006
|
+
case "MemberExpression": {
|
|
2007
|
+
const field = memberName(node);
|
|
2008
|
+
const owner = field === void 0 ? void 0 : this.receiverClass(node.object, scope, depth + 1);
|
|
2009
|
+
return owner && field !== void 0 ? this.fieldClass(owner, field) : void 0;
|
|
2010
|
+
}
|
|
2011
|
+
default: return;
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
fieldClass(cls, field, depth = 0) {
|
|
2015
|
+
if (depth > MAX_DEPTH) return void 0;
|
|
2016
|
+
const type = cls.info.fields.get(field);
|
|
2017
|
+
if (type !== void 0) return this.resolveClass(cls.file, type);
|
|
2018
|
+
const parent = this.superClass(cls);
|
|
2019
|
+
return parent ? this.fieldClass(parent, field, depth + 1) : void 0;
|
|
2020
|
+
}
|
|
2021
|
+
findMethod(cls, name, depth = 0) {
|
|
2022
|
+
if (depth > MAX_DEPTH) return void 0;
|
|
2023
|
+
const fn = cls.info.methods.get(name);
|
|
2024
|
+
if (fn) return {
|
|
2025
|
+
kind: "method",
|
|
2026
|
+
file: cls.file,
|
|
2027
|
+
cls,
|
|
2028
|
+
name,
|
|
2029
|
+
fn
|
|
2030
|
+
};
|
|
2031
|
+
const parent = this.superClass(cls);
|
|
2032
|
+
return parent ? this.findMethod(parent, name, depth + 1) : void 0;
|
|
2033
|
+
}
|
|
2034
|
+
superClass(cls) {
|
|
2035
|
+
return cls.info.superClass === void 0 ? void 0 : this.resolveClass(cls.file, cls.info.superClass);
|
|
2036
|
+
}
|
|
2037
|
+
resolveClass(file, localName) {
|
|
2038
|
+
const found = this.resolveLocal(file, localName);
|
|
2039
|
+
const info = found ? this.summary(found.file)?.classes.get(found.local) : void 0;
|
|
2040
|
+
return found && info ? {
|
|
2041
|
+
file: found.file,
|
|
2042
|
+
info
|
|
2043
|
+
} : void 0;
|
|
2044
|
+
}
|
|
2045
|
+
/** Finds where a name used in `file` is declared, following imports and re-exports. */
|
|
2046
|
+
resolveLocal(file, localName, depth = 0) {
|
|
2047
|
+
const summary = this.summary(file);
|
|
2048
|
+
if (!summary || depth > MAX_DEPTH) return void 0;
|
|
2049
|
+
if (summary.classes.has(localName) || summary.functions.has(localName)) return {
|
|
2050
|
+
file,
|
|
2051
|
+
local: localName
|
|
2052
|
+
};
|
|
2053
|
+
const imported = summary.imports.get(localName);
|
|
2054
|
+
return imported?.module === void 0 ? void 0 : this.resolveExport(imported.module, imported.imported, depth + 1);
|
|
2055
|
+
}
|
|
2056
|
+
resolveExport(file, exported, depth) {
|
|
2057
|
+
const summary = this.summary(file);
|
|
2058
|
+
if (!summary || depth > MAX_DEPTH) return void 0;
|
|
2059
|
+
const local = summary.exports.get(exported);
|
|
2060
|
+
if (local !== void 0) return this.resolveLocal(file, local, depth + 1);
|
|
2061
|
+
const reexport = summary.reexports.get(exported);
|
|
2062
|
+
if (reexport) return reexport.module === void 0 ? void 0 : this.resolveExport(reexport.module, reexport.imported, depth + 1);
|
|
2063
|
+
for (const module of summary.starExports) {
|
|
2064
|
+
const found = this.resolveExport(module, exported, depth + 1);
|
|
2065
|
+
if (found) return found;
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
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
|
+
*/
|
|
2080
|
+
function collectLocals(fn) {
|
|
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);
|
|
2089
|
+
if (!fn.body) return locals;
|
|
2090
|
+
walk(fn.body, (node) => {
|
|
2091
|
+
if (isFunctionLike(node)) addParameters(node);
|
|
2092
|
+
if (node.type !== "VariableDeclarator" || node.id.type !== "Identifier") return;
|
|
2093
|
+
const type = typeName(node.id.typeAnnotation) ?? newName(node.init);
|
|
2094
|
+
if (type !== void 0) locals.set(node.id.name, type);
|
|
2095
|
+
});
|
|
2096
|
+
return locals;
|
|
2097
|
+
}
|
|
2098
|
+
// src/rules/no-nested-polling.ts
|
|
2099
|
+
const isFunction = (node) => node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration";
|
|
2100
|
+
/** The class around `node`, and the outermost function inside that class (the method), for resolving `this` and locals. */
|
|
2101
|
+
function enclosing(node) {
|
|
2102
|
+
let fn;
|
|
2103
|
+
for (let current = node.parent; current; current = current.parent) {
|
|
2104
|
+
if (current.type === "ClassDeclaration" || current.type === "ClassExpression") return {
|
|
2105
|
+
classNode: current,
|
|
2106
|
+
fn
|
|
2107
|
+
};
|
|
2108
|
+
if (isFunction(current)) fn = current;
|
|
2109
|
+
}
|
|
2110
|
+
return { fn };
|
|
2111
|
+
}
|
|
2112
|
+
const rule$3 = {
|
|
2113
|
+
meta: {
|
|
2114
|
+
type: "problem",
|
|
2115
|
+
docs: {
|
|
2116
|
+
description: "Disallow polling (`toPass`, `poll`, ...) inside the callback of another poll, also through calls into other files.",
|
|
2117
|
+
url: docsUrl("no-nested-polling")
|
|
2118
|
+
},
|
|
2119
|
+
schema: [],
|
|
2120
|
+
messages: {
|
|
2121
|
+
nested: "'{{inner}}' polls inside the callback of '{{outer}}'. Nested polling multiplies the timeouts; poll once, at the outermost level.",
|
|
2122
|
+
nestedCall: "'{{call}}' polls inside the callback of '{{outer}}' (via {{path}}). Nested polling multiplies the timeouts; poll once, at the outermost level."
|
|
2123
|
+
}
|
|
2124
|
+
},
|
|
2125
|
+
create(context) {
|
|
2126
|
+
const { sourceCode } = context;
|
|
2127
|
+
const conventions = conventionsFor(context);
|
|
2128
|
+
const { pollingMethods } = conventions;
|
|
2129
|
+
if (![...pollingMethods].some((method) => sourceCode.text.includes(method))) return {};
|
|
2130
|
+
let index;
|
|
2131
|
+
const getIndex = () => index ??= new ProjectIndex(summarize(normalize(context.filename), sourceCode.ast, rootFor(context, conventions), conventions));
|
|
2132
|
+
const report = (hit, outer) => {
|
|
2133
|
+
const node = hit.node;
|
|
2134
|
+
if ("method" in hit) context.report({
|
|
2135
|
+
node,
|
|
2136
|
+
messageId: "nested",
|
|
2137
|
+
data: {
|
|
2138
|
+
inner: hit.method,
|
|
2139
|
+
outer
|
|
2140
|
+
}
|
|
2141
|
+
});
|
|
2142
|
+
else {
|
|
2143
|
+
const callee = sourceCode.getText(hit.node.callee);
|
|
2144
|
+
context.report({
|
|
2145
|
+
node,
|
|
2146
|
+
messageId: "nestedCall",
|
|
2147
|
+
data: {
|
|
2148
|
+
call: `${callee}()`,
|
|
2149
|
+
outer,
|
|
2150
|
+
path: hit.path.join(" → ")
|
|
2151
|
+
}
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
};
|
|
2155
|
+
return { CallExpression(node) {
|
|
2156
|
+
const call = node;
|
|
2157
|
+
const outer = pollingMethod(call, pollingMethods);
|
|
2158
|
+
const callback = outer === void 0 ? void 0 : pollCallback(call, pollingMethods);
|
|
2159
|
+
if (outer === void 0 || callback === void 0) return;
|
|
2160
|
+
const { classNode, fn } = enclosing(node);
|
|
2161
|
+
const projectIndex = getIndex();
|
|
2162
|
+
const scope = projectIndex.scopeFor(classNode, fn ? fn : callback);
|
|
2163
|
+
if (callback.type === "ArrowFunctionExpression" || callback.type === "FunctionExpression") {
|
|
2164
|
+
for (const hit of projectIndex.collectHits(callback.body, scope)) report(hit, outer);
|
|
2165
|
+
return;
|
|
2166
|
+
}
|
|
2167
|
+
const target = projectIndex.resolveReference(callback, scope);
|
|
2168
|
+
const path = target ? projectIndex.pollingPath(target) : void 0;
|
|
2169
|
+
if (path) context.report({
|
|
2170
|
+
node: callback,
|
|
2171
|
+
messageId: "nestedCall",
|
|
2172
|
+
data: {
|
|
2173
|
+
call: sourceCode.getText(callback),
|
|
2174
|
+
outer,
|
|
2175
|
+
path: path.join(" → ")
|
|
2176
|
+
}
|
|
2177
|
+
});
|
|
2178
|
+
} };
|
|
2179
|
+
}
|
|
2180
|
+
};
|
|
2181
|
+
// src/rules/padding-lines.ts
|
|
2182
|
+
const BLANK_LINE = /\r?\n[\t ]*\r?\n/;
|
|
2183
|
+
const BLANK_LINES = /(\r?\n)(?:[\t ]*\r?\n)+/g;
|
|
2184
|
+
const unwrapExport = (node) => (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") && node.declaration ? node.declaration : node;
|
|
2185
|
+
const isFunctionValue = (node) => node?.type === "ArrowFunctionExpression" || node?.type === "FunctionExpression" || node?.type === "TSEmptyBodyFunctionExpression";
|
|
2186
|
+
const isImport = (node) => node.type === "ImportDeclaration" || node.type === "TSImportEqualsDeclaration" && node.moduleReference.type === "TSExternalModuleReference";
|
|
2187
|
+
const isFunctionStatement = (node) => {
|
|
2188
|
+
const statement = unwrapExport(node);
|
|
2189
|
+
if (statement.type === "FunctionDeclaration" || statement.type === "TSDeclareFunction" || isFunctionValue(statement)) return true;
|
|
2190
|
+
return statement.type === "VariableDeclaration" && statement.declarations.some(({ init }) => isFunctionValue(init));
|
|
2191
|
+
};
|
|
2192
|
+
const functionStatementName = (node) => {
|
|
2193
|
+
const statement = unwrapExport(node);
|
|
2194
|
+
return (statement.type === "FunctionDeclaration" || statement.type === "TSDeclareFunction") && statement.id ? statement.id.name : void 0;
|
|
2195
|
+
};
|
|
2196
|
+
const isOverloadPair = (previous, current) => {
|
|
2197
|
+
const name = functionStatementName(previous);
|
|
2198
|
+
return unwrapExport(previous).type === "TSDeclareFunction" && name !== void 0 && name === functionStatementName(current);
|
|
2199
|
+
};
|
|
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 = {
|
|
2206
|
+
meta: {
|
|
2207
|
+
type: "layout",
|
|
2208
|
+
docs: {
|
|
2209
|
+
description: "Require blank lines after imports, around top-level functions and around object methods, and disallow blank lines between function overloads.",
|
|
2210
|
+
url: docsUrl("padding-lines")
|
|
2211
|
+
},
|
|
2212
|
+
fixable: "whitespace",
|
|
2213
|
+
schema: [],
|
|
2214
|
+
messages: {
|
|
2215
|
+
afterImports: "Expected a blank line after the import declarations.",
|
|
2216
|
+
aroundFunctions: "Expected a blank line between a function and the adjacent statement.",
|
|
2217
|
+
betweenObjectMethods: "Expected a blank line around methods in an object literal.",
|
|
2218
|
+
betweenOverloads: "Unexpected blank line between overloads of the same function."
|
|
2219
|
+
}
|
|
2220
|
+
},
|
|
2221
|
+
create(context) {
|
|
2222
|
+
const { text } = context.sourceCode;
|
|
2223
|
+
const lineBreak = text.includes("\r\n") ? "\r\n" : "\n";
|
|
2224
|
+
const requireBlankLine = (previous, current, messageId) => {
|
|
2225
|
+
const textBetween = text.slice(previous.range[1], current.range[0]);
|
|
2226
|
+
if (BLANK_LINE.test(textBetween)) return;
|
|
2227
|
+
context.report({
|
|
2228
|
+
node: current,
|
|
2229
|
+
messageId,
|
|
2230
|
+
fix: (fixer) => {
|
|
2231
|
+
const firstBreak = textBetween.search(/\r?\n/);
|
|
2232
|
+
if (firstBreak === -1) return fixer.insertTextAfterRange(previous.range, `${lineBreak}${lineBreak}`);
|
|
2233
|
+
return fixer.insertTextAfterRange([0, previous.range[1] + firstBreak], lineBreak);
|
|
2234
|
+
}
|
|
2235
|
+
});
|
|
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
|
+
};
|
|
2247
|
+
const checkStatements = (statements) => {
|
|
2248
|
+
for (let index = 1; index < statements.length; index++) {
|
|
2249
|
+
const previous = statements[index - 1];
|
|
2250
|
+
const current = statements[index];
|
|
2251
|
+
if (isImport(previous) && !isImport(current)) requireBlankLine(previous, current, "afterImports");
|
|
2252
|
+
else if (isOverloadPair(previous, current)) forbidBlankLines(previous, current);
|
|
2253
|
+
else if (isFunctionStatement(previous) || isFunctionStatement(current)) requireBlankLine(previous, current, "aroundFunctions");
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
return {
|
|
2257
|
+
Program: (node) => checkStatements(node.body),
|
|
2258
|
+
TSModuleBlock: (node) => checkStatements(node.body),
|
|
2259
|
+
ObjectExpression(node) {
|
|
2260
|
+
for (let index = 1; index < node.properties.length; index++) {
|
|
2261
|
+
const previous = node.properties[index - 1];
|
|
2262
|
+
const current = node.properties[index];
|
|
2263
|
+
if (previous.loc.end.line === current.loc.start.line) continue;
|
|
2264
|
+
if (isMethodProperty(previous) || isMethodProperty(current)) requireBlankLine(previous, current, "betweenObjectMethods");
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
};
|
|
2270
|
+
// src/rules/step-placeholders.ts
|
|
2271
|
+
/** The same pattern `@step` uses at runtime: the path is taken as written, so `{{ name }}` looks up " name ". */
|
|
2272
|
+
const NAMED = /\{\{(.*?)\}\}/g;
|
|
2273
|
+
const INDEX = /\[\[(\d+)\]\]/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;
|
|
2276
|
+
const findAll = (pattern, text) => {
|
|
2277
|
+
const regex = new RegExp(pattern.source, "g");
|
|
2278
|
+
const found = [];
|
|
2279
|
+
for (let match = regex.exec(text); match !== null; match = regex.exec(text)) found.push(match);
|
|
2280
|
+
return found;
|
|
2281
|
+
};
|
|
2282
|
+
const paramName = (param) => {
|
|
2283
|
+
const target = param.type === "TSParameterProperty" ? param.parameter : param;
|
|
2284
|
+
const binding = target.type === "AssignmentPattern" ? target.left : target.type === "RestElement" ? target.argument : target;
|
|
2285
|
+
return binding.type === "Identifier" ? binding.name : void 0;
|
|
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
|
+
};
|
|
2292
|
+
/**
|
|
2293
|
+
* What is wrong with the path of a `{{path}}` placeholder, if anything. `@step` reads the path exactly as written,
|
|
2294
|
+
* so spaces around it either fail the parameter lookup or read a property that does not exist.
|
|
2295
|
+
*/
|
|
2296
|
+
const namedProblem = (path, names) => {
|
|
2297
|
+
const trimmed = path.trim();
|
|
2298
|
+
const isParameter = (value) => isKnownRoot(value, names);
|
|
2299
|
+
if (trimmed !== path && isParameter(trimmed)) return "whitespace";
|
|
2300
|
+
return trimmed === path && isParameter(path) ? void 0 : "unknownParameter";
|
|
2301
|
+
};
|
|
2302
|
+
const isLiteralDescription = (node) => node.type === "Literal" && typeof node.value === "string" || node.type === "TemplateLiteral" && node.expressions.length === 0;
|
|
2303
|
+
const rule$1 = {
|
|
2304
|
+
meta: {
|
|
2305
|
+
type: "problem",
|
|
2306
|
+
docs: {
|
|
2307
|
+
description: "Validate the placeholders in `@step` descriptions against the method parameters.",
|
|
2308
|
+
url: docsUrl("step-placeholders")
|
|
2309
|
+
},
|
|
2310
|
+
fixable: "code",
|
|
2311
|
+
schema: [],
|
|
2312
|
+
messages: {
|
|
2313
|
+
singleBraces: "'{{found}}' is printed literally; use '{{expected}}' for a named placeholder.",
|
|
2314
|
+
whitespace: "'{{found}}' does not resolve, because @step does not trim the spaces inside placeholders; use '{{expected}}'.",
|
|
2315
|
+
unknownParameter: "Placeholder '{{found}}' does not match a parameter of '{{method}}' ({{params}}).",
|
|
2316
|
+
indexOutOfRange: "Placeholder '{{found}}' is out of range; '{{method}}' has {{count}} parameter(s).",
|
|
2317
|
+
notLast: "@step must be the decorator directly above the method, otherwise placeholders cannot be resolved."
|
|
2318
|
+
}
|
|
2319
|
+
},
|
|
2320
|
+
create(context) {
|
|
2321
|
+
const { stepDecorators } = conventionsFor(context);
|
|
2322
|
+
/** Reports a `{{path}}` placeholder in `description` that `@step` cannot resolve. */
|
|
2323
|
+
const checkNamed = (description, match, names, methodName) => {
|
|
2324
|
+
const problem = namedProblem(match[1], names);
|
|
2325
|
+
if (problem === "whitespace") {
|
|
2326
|
+
const from = description.range[0] + match.index;
|
|
2327
|
+
const range = [from, from + match[0].length];
|
|
2328
|
+
const expected = `{{${match[1].trim()}}}`;
|
|
2329
|
+
context.report({
|
|
2330
|
+
node: description,
|
|
2331
|
+
messageId: "whitespace",
|
|
2332
|
+
data: {
|
|
2333
|
+
found: match[0],
|
|
2334
|
+
expected
|
|
2335
|
+
},
|
|
2336
|
+
fix: (fixer) => fixer.replaceTextRange(range, expected)
|
|
2337
|
+
});
|
|
2338
|
+
} else if (problem === "unknownParameter") context.report({
|
|
2339
|
+
node: description,
|
|
2340
|
+
messageId: "unknownParameter",
|
|
2341
|
+
data: {
|
|
2342
|
+
found: match[0],
|
|
2343
|
+
method: methodName,
|
|
2344
|
+
params: names.filter(Boolean).join(", ") || "none"
|
|
2345
|
+
}
|
|
2346
|
+
});
|
|
2347
|
+
};
|
|
2348
|
+
return { Decorator(node) {
|
|
2349
|
+
if (!isStepDecorator(node, stepDecorators)) return;
|
|
2350
|
+
const method = node.parent;
|
|
2351
|
+
if (method.type !== "MethodDefinition") return;
|
|
2352
|
+
const { decorators } = method;
|
|
2353
|
+
if (decorators[decorators.length - 1] !== node) context.report({
|
|
2354
|
+
node,
|
|
2355
|
+
messageId: "notLast"
|
|
2356
|
+
});
|
|
2357
|
+
const { expression } = node;
|
|
2358
|
+
const description = expression.type === "CallExpression" ? expression.arguments[0] : void 0;
|
|
2359
|
+
if (!description || !isLiteralDescription(description)) return;
|
|
2360
|
+
const { params } = method.value;
|
|
2361
|
+
const names = params.map(paramName);
|
|
2362
|
+
const hasRest = params.some((param) => param.type === "RestElement");
|
|
2363
|
+
const methodName = context.sourceCode.getText(method.key);
|
|
2364
|
+
const raw = context.sourceCode.getText(description);
|
|
2365
|
+
const start = description.range[0];
|
|
2366
|
+
for (const match of findAll(NAMED, raw)) checkNamed(description, match, names, methodName);
|
|
2367
|
+
for (const match of findAll(INDEX, raw)) {
|
|
2368
|
+
const index = Number(match[1]);
|
|
2369
|
+
if (!hasRest && index >= params.length) context.report({
|
|
2370
|
+
node: description,
|
|
2371
|
+
messageId: "indexOutOfRange",
|
|
2372
|
+
data: {
|
|
2373
|
+
found: match[0],
|
|
2374
|
+
method: methodName,
|
|
2375
|
+
count: String(params.length)
|
|
2376
|
+
}
|
|
2377
|
+
});
|
|
2378
|
+
}
|
|
2379
|
+
for (const match of findAll(SINGLE_BRACES, raw)) {
|
|
2380
|
+
const placeholder = match[1];
|
|
2381
|
+
const from = start + match.index;
|
|
2382
|
+
const range = [from, from + placeholder.length + 2];
|
|
2383
|
+
const data = {
|
|
2384
|
+
found: `{${placeholder}}`,
|
|
2385
|
+
expected: `{{${placeholder}}}`
|
|
2386
|
+
};
|
|
2387
|
+
if (isKnownRoot(placeholder, names)) context.report({
|
|
2388
|
+
node: description,
|
|
2389
|
+
messageId: "singleBraces",
|
|
2390
|
+
data,
|
|
2391
|
+
fix: (fixer) => fixer.replaceTextRange(range, data.expected)
|
|
2392
|
+
});
|
|
2393
|
+
else context.report({
|
|
2394
|
+
node: description,
|
|
2395
|
+
messageId: "singleBraces",
|
|
2396
|
+
data
|
|
2397
|
+
});
|
|
2398
|
+
}
|
|
2399
|
+
} };
|
|
2400
|
+
}
|
|
2401
|
+
};
|
|
2402
|
+
// src/rules/step-required.ts
|
|
2403
|
+
const STEP_LAYERS = /* @__PURE__ */ new Set([
|
|
2404
|
+
"stepper",
|
|
2405
|
+
"asserter",
|
|
2406
|
+
"scenario"
|
|
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";
|
|
2411
|
+
// src/rules/index.ts
|
|
2412
|
+
const rules = {
|
|
2413
|
+
"architecture-boundaries": rule$13,
|
|
2414
|
+
"class-matches-filename": rule$12,
|
|
2415
|
+
"director-composes-builders": rule$11,
|
|
2416
|
+
"expect-from-support": rule$10,
|
|
2417
|
+
"file-naming": rule$9,
|
|
2418
|
+
"lines-between-class-members": rule$8,
|
|
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,
|
|
2425
|
+
"step-placeholders": rule$1,
|
|
2426
|
+
"step-required": {
|
|
2427
|
+
meta: {
|
|
2428
|
+
type: "suggestion",
|
|
2429
|
+
docs: {
|
|
2430
|
+
description: "Require a `@step` decorator on public methods of steppers, asserters and scenarios.",
|
|
2431
|
+
url: docsUrl("step-required")
|
|
2432
|
+
},
|
|
2433
|
+
schema: [],
|
|
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
|
+
}
|
|
2438
|
+
},
|
|
2439
|
+
create(context) {
|
|
2440
|
+
const conventions = conventionsFor(context);
|
|
2441
|
+
const info = classify(context.filename, conventions, rootFor(context, conventions));
|
|
2442
|
+
const layer = info?.kind === "top-scenario" ? "scenario" : info?.layer;
|
|
2443
|
+
if (layer === void 0 || !STEP_LAYERS.has(layer)) return {};
|
|
2444
|
+
const report = (key, messageId) => {
|
|
2445
|
+
context.report({
|
|
2446
|
+
node: key,
|
|
2447
|
+
messageId,
|
|
2448
|
+
data: {
|
|
2449
|
+
method: context.sourceCode.getText(key),
|
|
2450
|
+
layer
|
|
2451
|
+
}
|
|
2452
|
+
});
|
|
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
|
+
};
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
};
|
|
2466
|
+
const PLUGIN_NAME = "sparta";
|
|
2467
|
+
/** Recommended severities: `problem` rules are errors, `suggestion` and `layout` rules are warnings. */
|
|
2468
|
+
const recommendedRules = Object.fromEntries(Object.entries(rules).map(([name, rule]) => [`${PLUGIN_NAME}/${name}`, rule.meta?.type === "problem" ? "error" : "warn"]));
|
|
2469
|
+
Object.defineProperty(exports, "PLUGIN_NAME", {
|
|
2470
|
+
enumerable: true,
|
|
2471
|
+
get: function() {
|
|
2472
|
+
return PLUGIN_NAME;
|
|
2473
|
+
}
|
|
2474
|
+
});
|
|
2475
|
+
Object.defineProperty(exports, "recommendedRules", {
|
|
2476
|
+
enumerable: true,
|
|
2477
|
+
get: function() {
|
|
2478
|
+
return recommendedRules;
|
|
2479
|
+
}
|
|
2480
|
+
});
|
|
2481
|
+
Object.defineProperty(exports, "rules", {
|
|
2482
|
+
enumerable: true,
|
|
2483
|
+
get: function() {
|
|
2484
|
+
return rules;
|
|
2485
|
+
}
|
|
2486
|
+
});
|
|
2487
|
+
|
|
2488
|
+
//# sourceMappingURL=rules-T_C5segG.cjs.map
|