@starci/eslint-canon-be 3.19.5 → 3.19.7
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/CHANGELOG.md +11 -0
- package/README.md +1 -1
- package/dist/error-handling.d.ts +13 -1
- package/dist/error-handling.js +101 -33
- package/dist/lib/config.d.ts +4 -0
- package/dist/lib/config.js +16 -5
- package/dist/sonar-parity.js +2 -2
- package/package.json +4 -2
- package/runtime/scripts/lib/sonar-syntax-rules.mjs +263 -5
- package/runtime/scripts/lib/sonar-way.mjs +54 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 3.19.7 - 2026-11-08
|
|
4
|
+
|
|
5
|
+
- Fixed: the test-scope Sonar way block selects the specs with a positive selector (`files: ['**/*.{spec,e2e-spec}.{ts,mts,cts,js,mjs,cjs}']`, exported as `SPEC_FILES`) instead of `ignores: ['**/*', '!**/*.spec...']`. The harness lint scope (`canonScope` of `@starci/hfs`) refuses a negated selector, so every app's `starci app check --gate lint` ended in `ESLint tool error: eslint source scope is unavailable ... unsupported canon ignores selectors` and linted nothing. The block selects the same files as before and carries the name `starci-be/sonar-way-tests`, by which the packages config narrows it to the specs of the package subpaths.
|
|
6
|
+
|
|
7
|
+
## 3.19.6 - 2026-11-08
|
|
8
|
+
|
|
9
|
+
- Added (R235 `SCAN_SMELL`, the first Sonar way scan of a real app against local lint): the lint now reports what the server reported. `starci-be/no-duplicate-import` (S3863, fixable) replaces the core `no-duplicate-imports` that spared a separate type import: a value and a type from one module are one `import { value, type Type }`, and `--fix` merges them. `starci-be/no-nested-conditional` (S3358) now follows the server: a conditional inside a branch, a test, a call argument, a template or a cast is nested, and only an array, object, function or JSX expression starts a new reading. `starci-be/prefer-string-raw` (S7780) also refuses a `String.raw` template that holds no backslash (fixable). `starci-be/no-bidirectional-character` (text:S6389) refuses a raw bidirectional control character in any file.
|
|
10
|
+
- Added: the Sonar way block maps S7739 `unicorn/no-thenable`, S7746 `unicorn/no-useless-promise-resolve-reject` (fixable), S6606 `@typescript-eslint/prefer-nullish-coalescing`, S7781 `unicorn/prefer-string-replace-all` (fixable), S7718 `unicorn/catch-error-name` (fixable), S7727 `unicorn/no-array-callback-reference`, S6671 `prefer-promise-reject-errors`, S6325 `prefer-regex-literals`, S1186 `@typescript-eslint/no-empty-function`, S878 `no-sequences`, S6535 `no-useless-escape`, S7753 `unicorn/prefer-array-index-of` (fixable), S7737 `unicorn/no-object-as-default-parameter`, S7755 `unicorn/prefer-at` (fixable), S7787 `unicorn/require-module-specifiers`, S7766 `unicorn/prefer-math-min-max` (fixable), S6661 `prefer-object-spread` (fixable) and S4123 `@typescript-eslint/await-thenable`, all at error. A catch parameter is `error` (`error_` where `error` is already declared in scope; `cause` stays allowed, the scan accepts it and a back end's wrapped failures are named so).
|
|
11
|
+
- Added: the specs of the product source run the test-scoped Sonar way rules (the sonarjs rules whose Sonar scope is Tests, among them S5906, S8754 and S9073) in a fourth block, because the scan reads `sonar.tests` with them; the product source block still leaves the specs out.
|
|
12
|
+
- Changed: `starci-be/throw-domain-error` judges a rejection as a throw. `Promise.reject(value)` and the `reject(value)` of a `new Promise` executor must carry a `DomainError`, so a helper such as `rejectionOf(reason: unknown) { return Promise.reject(reason) }`, which only dodges S7746 and this rule, is an error, and the one form that satisfies both is `throw new <C>Error(...)`. A rethrown caught value stays allowed. Added: its option `controlFlowSignals` (default the closed list BullMQ `UnrecoverableError`, `DelayedError` and `WaitingChildrenError`, which BullMQ reads with `instanceof` and which cannot be domain errors) lets `throw new X(...)` of a listed signal pass; a signal is thrown, never rejected.
|
|
13
|
+
|
|
3
14
|
## 3.19.5 - 2026-11-08
|
|
4
15
|
|
|
5
16
|
- Fixed: the `@starci/hfs` peer is `~6.2.0`, the range of the hfs the canon pins name, so an app on hfs 6.2 installs with `npm ci`.
|
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@ A sample, not the list:
|
|
|
43
43
|
| **Model calls** (R326, R327, R344) | Every model call goes through the `@starci/ai-router` gateway: an upstream provider key variable (`PROVIDER_KEY_VARIABLES` of `src/ai-gateway.ts`, with its `_FILE` twin) is named only in the gateway's custody owner `integrations/ai-gateway`, specs and the test world included; code builds only `ChatOpenAI` and `OpenAIEmbeddings` of `@langchain/openai`, each from an inline options object whose `configuration.baseURL` is read from a `<c>.options.ts` type and whose `apiKey` is a `platform/config` `Secret` revealed; `integrations/ai` reads exactly `STARCI_AI_KEY`, the one virtual key of every client, and the custody owner passes the gateway no `adminToken`. Which owner may import LangChain, `openai`, a provider SDK or an agent framework is the infrastructure table (`provider-key-custody`, `ai-client-through-gateway`, `ai-virtual-key-name`, `infra-import-owner`) |
|
|
44
44
|
| **Ambient ids** (R142) | `randomUUID` of Node's crypto (named, namespace or global), the `v1`, `v4`, `v6` and `v7` generators of `uuid`, `nanoid` and `ulid` are used only inside `platform/ids`, specs included: code asks the injected `Ids` port and a spec provides `fakeIds()`; the generators are found by the module they are imported from, never by a local name (`no-ambient-id`) |
|
|
45
45
|
| **App composition** (R245, R246) | `apps/<app>/src/<app>.env.ts` exports an explicit typed `<App>Env` interface and `read<App>Env(env: EnvSource): <App>Env` (for example `ApiEnv` and `readApiEnv`). The interface declares its own readonly parsed members, such as `readonly server: ReturnType<typeof parseServerConfig>`, structurally compatible with the app's options. The role name stays `<app>.env.ts`, never `env.ts`; capability `<capability>.config.ts` files stay unchanged. `main.ts` creates `EnvSource` once, imports and calls the reader, builds options and boots. The env file holds fail-fast parsing only, with no localhost or default host fallback, logic, module composition, business code or feature imports; `<app>.options.ts` holds env-derived options and port bindings only, with no parsing. Both refuse an array listing `*Module` classes, module or queue registrations (`register`, `forRoot`, `registerQueue`) or scheduler entries, and an `imports`, `modules`, `schedulers` or `processors` list; the env file also refuses standalone module or queue registration calls. Composition belongs in a `compose/<area>.ts` group that `app.module.ts` spreads (`app-options-composition-free`, `BE_APP_OPTIONS_COMPOSITION`). Each app file stays within its slot's line budget: `main.ts` 80, env 150, options 200, group 120, root 250 (`app-file-budget`, `BE_APP_COMPOSITION_BUDGET`). The interface and reader exports are a documented scaffold contract; they need no new lint rule |
|
|
46
|
-
| **Sonar parity** (R235) | The smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (`no-await-in-loop`, S9382; `for (;;)` and `while (true)` are spared), no `charCodeAt`/`fromCharCode` (`prefer-code-point`), no string that only escapes backslashes (`prefer-string-raw`), no nested conditional (`no-nested-conditional`), `void` only on a call (`no-void-operator`), no unused import (`no-unused-import`), `export ... from` for an import that is only handed on (`prefer-export-from`), no raw U+2028, U+2029 or U+0085 in any file, specs included (`no-line-separator-literal`: the scanner counts them as line breaks and aborts; the finding names the escape); the factory also turns on typescript-eslint `no-deprecated`, `no-base-to-string` and `require-await`. The files `*.spec.ts` and `*.e2e-spec.ts` are outside the scan, so outside these rules |
|
|
46
|
+
| **Sonar parity** (R235) | The smells SonarCloud measures that a lint rule can decide: no `await` inside a loop (`no-await-in-loop`, S9382; `for (;;)` and `while (true)` are spared), no `charCodeAt`/`fromCharCode` (`prefer-code-point`), no string that only escapes backslashes (`prefer-string-raw`), no nested conditional (`no-nested-conditional`), `void` only on a call (`no-void-operator`), no unused import (`no-unused-import`), `export ... from` for an import that is only handed on (`prefer-export-from`), no raw U+2028, U+2029 or U+0085 in any file, specs included (`no-line-separator-literal`: the scanner counts them as line breaks and aborts; the finding names the escape), no raw bidirectional control character (`no-bidirectional-character`), one import per module with `--fix` merging a value and a type import (`no-duplicate-import`); the Sonar way block also maps the unicorn, core and typescript-eslint rules of `scripts/lib/sonar-way.mjs`, and the specs run the test-scoped rules of the profile; the factory also turns on typescript-eslint `no-deprecated`, `no-base-to-string` and `require-await`. The files `*.spec.ts` and `*.e2e-spec.ts` are outside the scan, so outside these rules |
|
|
47
47
|
| **Cookies** (R141) | A cookie a door writes through the response of Express or Fastify (`cookie`, `setCookie`) states `httpOnly: true`, `secure: true` and `sameSite` `lax` or `strict` in options typed with those literals, and `Set-Cookie` is never written as a header; the call is recognised by where its signature is declared (`response-cookie-attributes`). A secret-derived value is compared with `timingSafeEqual`: a `Secret` of `platform/config` and the `.digest()` of a `Hash` or `Hmac` of Node's crypto are recognised by type (`secret-compare-timing-safe`) |
|
|
48
48
|
| **Default deny** | Typed bodies and arguments, no `GraphQLJSON` tunnel, no `switch (operation)`, `@Public` carries a `PublicReason` member of `domain/identity`, no `@UseGuards` (the global `APP_GUARD` chain decides) and no guard injected into another guard (`no-untyped-body`, `public-needs-reason`, `no-auth-use-guards`, `no-guard-injects-guard`) |
|
|
49
49
|
| **Module shape** | No `@Global()`; `isGlobal: true` only in an app's `app.module.ts`; no import of another owner's module; typed `ConfigurableModuleBuilder`; `static register` is the only factory; every module (capability, sub-module, feature, transport, cli group) has a sibling `<x>.module-definition.ts` and `<x>.options.ts`, extends its own `ConfigurableModuleClass` and is listed only as `X.register(...)` (`module-definition-required`); only a capability's representative module keeps `.setExtras({ isGlobal: false })` and the `register` override (`capability-module-shape`); one module per file; no `new` of a provider; no module-level `let` (`no-global-decorator`, `is-global-only-in-app`, `no-cross-owner-module-import`, `static-module-register`) |
|
package/dist/error-handling.d.ts
CHANGED
|
@@ -5,7 +5,18 @@ export declare const catchMustAccount: RuleModule;
|
|
|
5
5
|
export declare const replacementThrowCarriesCause: RuleModule;
|
|
6
6
|
/** An error class is declared at its owner in `errors/<capability>.error.ts` and derives from `DomainError`. */
|
|
7
7
|
export declare const errorHome: RuleModule;
|
|
8
|
-
/**
|
|
8
|
+
/** A framework signal a throw may carry beside a domain error: the class `name`, exported by the package `module`. */
|
|
9
|
+
interface ControlFlowSignal {
|
|
10
|
+
readonly name: string;
|
|
11
|
+
readonly module: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The closed list of framework control-flow signals: BullMQ reads them with `instanceof` to fail a job without a retry, to delay it or to wait
|
|
15
|
+
* for its children, so they cannot derive from `DomainError`. BullMQ is owned by `platform/queue` (the infra-owner rule), which is where they are thrown.
|
|
16
|
+
* The rule option `controlFlowSignals` replaces this list; an app has no other way to extend it.
|
|
17
|
+
*/
|
|
18
|
+
export declare const CONTROL_FLOW_SIGNALS: readonly ControlFlowSignal[];
|
|
19
|
+
/** Every thrown value is a `DomainError` of the owner that throws it, or one of the framework control-flow signals. */
|
|
9
20
|
export declare const throwDomainError: RuleModule;
|
|
10
21
|
/** The one shape of an owner's `errors/<capability>.error.ts`. */
|
|
11
22
|
export declare const errorFamilyShape: RuleModule;
|
|
@@ -19,3 +30,4 @@ export declare const rules: {
|
|
|
19
30
|
};
|
|
20
31
|
/** All start at error: HFS has no baseline, and the migration lanes clear the debt before a repository adopts them. */
|
|
21
32
|
export declare const recommended: Recommended;
|
|
33
|
+
export {};
|
package/dist/error-handling.js
CHANGED
|
@@ -15,7 +15,10 @@
|
|
|
15
15
|
* `errors/<capability>.error.ts` of its own owner, and a class that derives from the built-in `Error` some other way
|
|
16
16
|
* (`AbstractException`, a framework `HttpException` subclass, a bare `extends Error`) is refused.
|
|
17
17
|
* - `throw-domain-error` refuses a `throw` whose type does not derive from `DomainError` (`throw new Error`, the Nest
|
|
18
|
-
* `HttpException` family, a thrown string or object), and a domain owner that throws a platform error outward.
|
|
18
|
+
* `HttpException` family, a thrown string or object), and a domain owner that throws a platform error outward. A rejection is
|
|
19
|
+
* a throw: `Promise.reject(value)` and the `reject(value)` of a `new Promise((resolve, reject) => ...)` executor are judged
|
|
20
|
+
* the same way, so the one form that also satisfies Sonar S7746 (`throw` in an async function) and S6671 (an Error rejects)
|
|
21
|
+
* is `throw new <C>Error(...)`.
|
|
19
22
|
*
|
|
20
23
|
* The error base of a file is `DomainError` of `platform/errors`; a root workspace package, which cannot import an app owner, declares
|
|
21
24
|
* its own base in its manifest (`starci.errorBase`: `{ name, file }`), and both rules read that class, in that file, as its `DomainError`:
|
|
@@ -305,17 +308,67 @@ const isCaughtValue = (context, identifier) => {
|
|
|
305
308
|
}
|
|
306
309
|
return false;
|
|
307
310
|
};
|
|
308
|
-
/**
|
|
311
|
+
/** The call is `Promise.reject(...)`. */
|
|
312
|
+
const isPromiseReject = (call) => {
|
|
313
|
+
const callee = call.callee;
|
|
314
|
+
return callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && callee.object.name === "Promise" && callee.property.type === "Identifier" && callee.property.name === "reject";
|
|
315
|
+
};
|
|
316
|
+
/** The call is the `reject` parameter (the second one) of the executor of `new Promise(...)`. */
|
|
317
|
+
const isExecutorReject = (context, call) => {
|
|
318
|
+
if (call.callee.type !== "Identifier")
|
|
319
|
+
return false;
|
|
320
|
+
const name = call.callee.name;
|
|
321
|
+
for (let scope = context.sourceCode.getScope(call); scope; scope = scope.upper) {
|
|
322
|
+
const variable = scope.set.get(name);
|
|
323
|
+
if (!variable)
|
|
324
|
+
continue;
|
|
325
|
+
return variable.defs.some((definition) => {
|
|
326
|
+
if (definition.type !== "Parameter")
|
|
327
|
+
return false;
|
|
328
|
+
const fn = definition.node;
|
|
329
|
+
const owner = fn.parent;
|
|
330
|
+
return ((fn.type === "ArrowFunctionExpression" || fn.type === "FunctionExpression") &&
|
|
331
|
+
owner?.type === "NewExpression" &&
|
|
332
|
+
owner.callee.type === "Identifier" &&
|
|
333
|
+
owner.callee.name === "Promise" &&
|
|
334
|
+
owner.arguments[0] === fn &&
|
|
335
|
+
fn.params[1] === definition.name);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
return false;
|
|
339
|
+
};
|
|
340
|
+
/**
|
|
341
|
+
* The closed list of framework control-flow signals: BullMQ reads them with `instanceof` to fail a job without a retry, to delay it or to wait
|
|
342
|
+
* for its children, so they cannot derive from `DomainError`. BullMQ is owned by `platform/queue` (the infra-owner rule), which is where they are thrown.
|
|
343
|
+
* The rule option `controlFlowSignals` replaces this list; an app has no other way to extend it.
|
|
344
|
+
*/
|
|
345
|
+
export const CONTROL_FLOW_SIGNALS = Object.freeze([
|
|
346
|
+
{ name: "UnrecoverableError", module: "bullmq" },
|
|
347
|
+
{ name: "DelayedError", module: "bullmq" },
|
|
348
|
+
{ name: "WaitingChildrenError", module: "bullmq" },
|
|
349
|
+
]);
|
|
350
|
+
/** The `controlFlowSignals` option of the rule, when the config gives one. */
|
|
351
|
+
const readSignals = (option) => {
|
|
352
|
+
if (typeof option !== "object" || option === null || !("controlFlowSignals" in option) || !Array.isArray(option.controlFlowSignals))
|
|
353
|
+
return undefined;
|
|
354
|
+
return option.controlFlowSignals.filter((entry) => typeof entry?.name === "string" && typeof entry?.module === "string");
|
|
355
|
+
};
|
|
356
|
+
/** Every thrown value is a `DomainError` of the owner that throws it, or one of the framework control-flow signals. */
|
|
309
357
|
export const throwDomainError = {
|
|
310
358
|
meta: {
|
|
311
359
|
type: "problem",
|
|
312
|
-
docs: { description: "A thrown value's type derives from `DomainError
|
|
313
|
-
schema: [
|
|
360
|
+
docs: { description: "A thrown value's type derives from `DomainError` (or is a listed framework control-flow signal); a domain owner never throws a platform error outward." },
|
|
361
|
+
schema: [{
|
|
362
|
+
type: "object",
|
|
363
|
+
properties: { controlFlowSignals: { type: "array", items: { type: "object", properties: { name: { type: "string" }, module: { type: "string" } }, required: ["name", "module"], additionalProperties: false } } },
|
|
364
|
+
additionalProperties: false,
|
|
365
|
+
}],
|
|
314
366
|
messages: {
|
|
315
367
|
bareError: "`throw new Error(...)` carries a sentence and no code, so nothing downstream can group or map it. Throw the `<C>Error` of the owning capability with one of its codes.",
|
|
316
368
|
framework: "`throw new {{name}}(...)` carries an HTTP status and no identity. Throw the `<C>Error` of the owning capability; the one filter of `platform/errors` maps its code to a status.",
|
|
317
369
|
notDomainError: "This `throw` does not throw a `DomainError`. Throw the `<C>Error` of the owning capability with one of its codes, or return an `Outcome` and let the transport unwrap it; a root workspace package throws the error base its `package.json` declares (`starci.errorBase`).",
|
|
318
370
|
platformThrown: "A domain owner throws `{{name}}`, an error of a platform owner. Translate it into the error of this capability so platform details do not cross the boundary.",
|
|
371
|
+
rejectNotDomainError: "This rejection does not carry a `DomainError`. In an `async` function or a promise callback write `throw new <C>Error(...)` with one of the capability's codes (`return Promise.reject(value)` is Sonar S7746, and a value that is no `DomainError` breaks this rule); in a `new Promise` executor reject with the `<C>Error` of the owning capability.",
|
|
319
372
|
},
|
|
320
373
|
},
|
|
321
374
|
create(context) {
|
|
@@ -323,38 +376,53 @@ export const throwDomainError = {
|
|
|
323
376
|
const filename = normalizePath(context.filename);
|
|
324
377
|
const { checker } = typed(context);
|
|
325
378
|
const isHttpException = (type) => derives(checker, type, (name, file) => name === "HttpException" && /\/node_modules\/@nestjs\/common\//.test(file));
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
if (
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
}
|
|
343
|
-
else {
|
|
344
|
-
context.report({ node: thrown, messageId: "notDomainError" });
|
|
345
|
-
}
|
|
346
|
-
return;
|
|
379
|
+
const signals = readSignals(context.options[0]) ?? CONTROL_FLOW_SIGNALS;
|
|
380
|
+
const isSignal = (type) => derives(checker, type, (name, file) => signals.some((signal) => signal.name === name && file.includes(`/node_modules/${signal.module}/`)));
|
|
381
|
+
/** Judges the value a statement throws or a call rejects with; a rejection that is no domain error has its own message. */
|
|
382
|
+
const judge = (thrown, rejection) => {
|
|
383
|
+
if (thrown.type === "Identifier" && isCaughtValue(context, thrown))
|
|
384
|
+
return;
|
|
385
|
+
const type = typeOf(context, thrown);
|
|
386
|
+
const parts = partsOf(type);
|
|
387
|
+
const foreign = parts.find((part) => !derivesFromErrorBase(context, part) && (rejection || !isSignal(part)));
|
|
388
|
+
if (parts.length === 0 || foreign) {
|
|
389
|
+
if (rejection)
|
|
390
|
+
context.report({ node: thrown, messageId: "rejectNotDomainError" });
|
|
391
|
+
else if (foreign && isHttpException(foreign)) {
|
|
392
|
+
context.report({ node: thrown, messageId: "framework", data: { name: foreign.getSymbol()?.name ?? "HttpException" } });
|
|
393
|
+
}
|
|
394
|
+
else if (foreign && derivesFromBuiltinError(context, foreign)) {
|
|
395
|
+
context.report({ node: thrown, messageId: "bareError" });
|
|
347
396
|
}
|
|
348
|
-
|
|
397
|
+
else {
|
|
398
|
+
context.report({ node: thrown, messageId: "notDomainError" });
|
|
399
|
+
}
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
if (hfs.tierOf(filename) !== "domain")
|
|
403
|
+
return;
|
|
404
|
+
for (const part of parts) {
|
|
405
|
+
const declarations = part.getSymbol()?.declarations ?? [];
|
|
406
|
+
const platform = declarations.find((declaration) => hfs.tierOf(String(declaration.getSourceFile().fileName).replace(/\\/g, "/")) === "platform");
|
|
407
|
+
if (platform) {
|
|
408
|
+
context.report({ node: thrown, messageId: "platformThrown", data: { name: part.getSymbol()?.name } });
|
|
349
409
|
return;
|
|
350
|
-
for (const part of parts) {
|
|
351
|
-
const declarations = part.getSymbol()?.declarations ?? [];
|
|
352
|
-
const platform = declarations.find((declaration) => hfs.tierOf(String(declaration.getSourceFile().fileName).replace(/\\/g, "/")) === "platform");
|
|
353
|
-
if (platform) {
|
|
354
|
-
context.report({ node: thrown, messageId: "platformThrown", data: { name: part.getSymbol()?.name } });
|
|
355
|
-
return;
|
|
356
|
-
}
|
|
357
410
|
}
|
|
411
|
+
}
|
|
412
|
+
};
|
|
413
|
+
return {
|
|
414
|
+
ThrowStatement(node) {
|
|
415
|
+
if (node.argument)
|
|
416
|
+
judge(node.argument, false);
|
|
417
|
+
},
|
|
418
|
+
CallExpression(node) {
|
|
419
|
+
if (!isPromiseReject(node) && !isExecutorReject(context, node))
|
|
420
|
+
return;
|
|
421
|
+
const reason = node.arguments[0];
|
|
422
|
+
if (reason === undefined || reason.type === "SpreadElement")
|
|
423
|
+
context.report({ node, messageId: "rejectNotDomainError" });
|
|
424
|
+
else
|
|
425
|
+
judge(reason, true);
|
|
358
426
|
},
|
|
359
427
|
};
|
|
360
428
|
},
|
package/dist/lib/config.d.ts
CHANGED
|
@@ -20,6 +20,10 @@ export declare const SOURCE_FILES: readonly string[];
|
|
|
20
20
|
export declare const IGNORED: readonly string[];
|
|
21
21
|
/** The typescript-eslint rules the canon borrows (BE-CONVENTION 1.17, R72/R73; Sonar S1874, S6551 and S7503 through R235), all `error`. */
|
|
22
22
|
export declare const BORROWED: Recommended;
|
|
23
|
+
/** The specs of the source, as the positive `files` of the block that judges the specs alone (no negated selector: the lint scope of the harness proves a scope from plain globs only). */
|
|
24
|
+
export declare const SPEC_FILES: readonly string[];
|
|
25
|
+
/** The name of the test-scope Sonar way block, which the package config narrows to the specs of the package subpaths. */
|
|
26
|
+
export declare const TEST_SCOPE_BLOCK = "starci-be/sonar-way-tests";
|
|
23
27
|
/**
|
|
24
28
|
* The flat config of one back-end repository.
|
|
25
29
|
*
|
package/dist/lib/config.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import tsParser from "@typescript-eslint/parser";
|
|
20
20
|
import { OUTSIDE_THE_SCAN_FILES } from "../../runtime/scripts/lib/sonar-syntax-rules.mjs";
|
|
21
|
-
import { sonarWayRules } from "../../runtime/scripts/lib/sonar-way.mjs";
|
|
21
|
+
import { sonarWayRules, sonarWayTestRules } from "../../runtime/scripts/lib/sonar-way.mjs";
|
|
22
22
|
/** A disable directive is a weakening of lint, and one that suppresses nothing is dead weight. */
|
|
23
23
|
export const linterOptions = Object.freeze({ noInlineConfig: true, reportUnusedDisableDirectives: "error" });
|
|
24
24
|
/** Every tracked source a back end holds; the factory lints them all. */
|
|
@@ -49,6 +49,10 @@ export const BORROWED = Object.freeze({
|
|
|
49
49
|
"@typescript-eslint/no-unsafe-argument": "error",
|
|
50
50
|
"no-console": "error",
|
|
51
51
|
});
|
|
52
|
+
/** The specs of the source, as the positive `files` of the block that judges the specs alone (no negated selector: the lint scope of the harness proves a scope from plain globs only). */
|
|
53
|
+
export const SPEC_FILES = Object.freeze(["**/*.{spec,e2e-spec}.{ts,mts,cts,js,mjs,cjs}"]);
|
|
54
|
+
/** The name of the test-scope Sonar way block, which the package config narrows to the specs of the package subpaths. */
|
|
55
|
+
export const TEST_SCOPE_BLOCK = "starci-be/sonar-way-tests";
|
|
52
56
|
const levelOf = (setting) => (Array.isArray(setting) ? setting[0] : setting);
|
|
53
57
|
/**
|
|
54
58
|
* The flat config of one back-end repository.
|
|
@@ -93,10 +97,14 @@ export const buildBeConfig = async ({ hfs, plugin, recommended }) => {
|
|
|
93
97
|
},
|
|
94
98
|
// Sonar way: what the scan raises is refused while the code is written; a spec is outside the scan, so outside this block.
|
|
95
99
|
{ files: [...SOURCE_FILES], ignores: [...OUTSIDE_THE_SCAN_FILES], plugins: { sonarjs, unicorn }, rules: sonarWayRules(sonarjs, "be").rules },
|
|
100
|
+
// Sonar way, test scope: the scan reads the specs with the rules of the tests (sonar.tests), so the specs of the source are judged by those and by no other.
|
|
101
|
+
{ name: TEST_SCOPE_BLOCK, files: [...SPEC_FILES], plugins: { sonarjs }, rules: sonarWayTestRules(sonarjs) },
|
|
96
102
|
];
|
|
97
103
|
};
|
|
98
104
|
/** The back-end subpaths of a root workspace package: everything under `src/` but the front-end subpaths `workbench/` and `public/`; the workbench contract (`workbench/contract/`) is React-free and stays back end. */
|
|
99
105
|
export const PACKAGE_SOURCE_FILES = Object.freeze(["packages/*/src/**/*.{ts,mts,cts,js,mjs,cjs}"]);
|
|
106
|
+
const PACKAGE_SPEC_FILES = Object.freeze(["packages/*/src/**/*.{spec,e2e-spec}.{ts,mts,cts,js,mjs,cjs}"]);
|
|
107
|
+
const PACKAGE_CONTRACT_SPEC_FILES = Object.freeze(["packages/*/src/workbench/contract/**/*.{spec,e2e-spec}.{ts,mts,cts,js,mjs,cjs}"]);
|
|
100
108
|
const PACKAGE_FRONT_END = Object.freeze(["packages/*/src/workbench/**", "packages/*/src/public/**"]);
|
|
101
109
|
const PACKAGE_CONTRACT_FILES = Object.freeze(["packages/*/src/workbench/contract/**/*.{ts,mts,cts,js,mjs,cjs}"]);
|
|
102
110
|
/** What a package folder never lints: build output, coverage output and installed packages. */
|
|
@@ -114,9 +122,12 @@ export const buildBePackagesConfig = async (input) => {
|
|
|
114
122
|
const [, ...blocks] = await buildBeConfig(input);
|
|
115
123
|
return [
|
|
116
124
|
{ ignores: [...PACKAGE_IGNORED] },
|
|
117
|
-
...blocks.flatMap((block) =>
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
125
|
+
...blocks.flatMap((block) => {
|
|
126
|
+
const tests = block.name === TEST_SCOPE_BLOCK;
|
|
127
|
+
return [
|
|
128
|
+
{ ...block, files: [...(tests ? PACKAGE_SPEC_FILES : PACKAGE_SOURCE_FILES)], ignores: [...(block.ignores ?? []), ...PACKAGE_FRONT_END] },
|
|
129
|
+
{ ...block, files: [...(tests ? PACKAGE_CONTRACT_SPEC_FILES : PACKAGE_CONTRACT_FILES)] },
|
|
130
|
+
];
|
|
131
|
+
}),
|
|
121
132
|
];
|
|
122
133
|
};
|
package/dist/sonar-parity.js
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Each rule is the syntax-tree form of one Sonar rule, shared with the front-end canon (scripts/lib/sonar-syntax-rules.mjs,
|
|
5
5
|
* bundled under `runtime/`): `no-await-in-loop` (S9382), `prefer-code-point` (S7758), `prefer-string-raw` (S7780),
|
|
6
|
-
* `no-nested-conditional` (S3358), `no-void-operator` (S3735), `no-unused-import` (S1128) and `prefer-export-from` (S7763); the rest of
|
|
6
|
+
* `no-nested-conditional` (S3358), `no-void-operator` (S3735), `no-unused-import` (S1128) and `prefer-export-from` (S7763), `no-duplicate-import` (S3863, fixable) and `no-bidirectional-character` (text:S6389); the rest of
|
|
7
7
|
* Sonar way is the factory's Sonar way block (scripts/lib/sonar-way.mjs).
|
|
8
8
|
* The three Sonar rules that need the type checker, S1874 (a deprecated API), S6551 (an object turned into text) and S7503 (an `async`
|
|
9
9
|
* function that never awaits and returns no promise), are the typescript-eslint rules `no-deprecated`, `no-base-to-string` and
|
|
10
10
|
* `require-await` the factory turns on.
|
|
11
11
|
*/
|
|
12
12
|
import { SONAR_SYNTAX_RULES } from "../runtime/scripts/lib/sonar-syntax-rules.mjs";
|
|
13
|
-
const NAMES = ["no-await-in-loop", "prefer-code-point", "prefer-string-raw", "no-nested-conditional", "no-void-operator", "no-unused-import", "prefer-export-from", "max-params", "no-line-separator-literal"];
|
|
13
|
+
const NAMES = ["no-await-in-loop", "prefer-code-point", "prefer-string-raw", "no-nested-conditional", "no-void-operator", "no-unused-import", "prefer-export-from", "max-params", "no-line-separator-literal", "no-bidirectional-character", "no-duplicate-import"];
|
|
14
14
|
/** The rules this law contributes to the plugin. */
|
|
15
15
|
export const rules = Object.fromEntries(NAMES.flatMap((name) => {
|
|
16
16
|
const rule = SONAR_SYNTAX_RULES[name];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@starci/eslint-canon-be",
|
|
3
|
-
"version": "3.19.
|
|
3
|
+
"version": "3.19.7",
|
|
4
4
|
"description": "The StarCi back-end lint canon: every rule its laws publish, gathered as one flat-config plugin.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -73,5 +73,7 @@
|
|
|
73
73
|
"eslint": "^9.18.0",
|
|
74
74
|
"typescript": "^6.0.3"
|
|
75
75
|
},
|
|
76
|
-
"types": "./dist/index.d.ts"
|
|
76
|
+
"types": "./dist/index.d.ts",
|
|
77
|
+
"gitHead": "1ac3e3ed36e167ca7dbed5cad593ca8033106f44",
|
|
78
|
+
"starciSource": "1dcbc5e6c5a518233f880f381f5b2eafc909497891d9b60815cfd49b101cd608"
|
|
77
79
|
}
|
|
@@ -74,23 +74,47 @@ const KEEPS_ITS_ESCAPES = new Set(['ImportDeclaration', 'ExportAllDeclaration',
|
|
|
74
74
|
const isMatcherValue = (node) => (node.parent?.type === 'Property' && node.parent.value === node && node.parent.key?.name === 'matcher')
|
|
75
75
|
|| (node.parent?.type === 'ArrayExpression' && isMatcherValue(node.parent));
|
|
76
76
|
|
|
77
|
-
/**
|
|
77
|
+
/** Whether the tag is `String.raw`. */
|
|
78
|
+
const isStringRaw = (tag) => tag.type === 'MemberExpression' && !tag.computed && tag.object.type === 'Identifier' && tag.object.name === 'String' && tag.property.type === 'Identifier' && tag.property.name === 'raw';
|
|
79
|
+
|
|
80
|
+
/** S7780: a string whose only escapes are backslashes reads better as `String.raw`; a `String.raw` template with no backslash in it needs no tag. */
|
|
78
81
|
const preferStringRaw = {
|
|
79
|
-
meta: {
|
|
82
|
+
meta: {
|
|
83
|
+
type: 'suggestion',
|
|
84
|
+
fixable: 'code',
|
|
85
|
+
schema: [],
|
|
86
|
+
messages: {
|
|
87
|
+
raw: 'S7780: write this string with `String.raw` so its backslashes are not escaped.',
|
|
88
|
+
needless: 'S7780: this `String.raw` template holds no backslash; write a plain template literal.',
|
|
89
|
+
},
|
|
90
|
+
},
|
|
80
91
|
create: (context) => ({
|
|
81
92
|
Literal: (node) => {
|
|
82
93
|
if (KEEPS_ITS_ESCAPES.has(node.parent?.type) || node.parent?.type === 'ExpressionStatement' || isMatcherValue(node)) return;
|
|
83
94
|
if (onlyBackslashEscapes(node)) context.report({ node, messageId: 'raw' });
|
|
84
95
|
},
|
|
96
|
+
TaggedTemplateExpression: (node) => {
|
|
97
|
+
if (!isStringRaw(node.tag) || node.quasi.quasis.some((quasi) => quasi.value.raw.includes('\\'))) return;
|
|
98
|
+
context.report({ node, messageId: 'needless', fix: (fixer) => fixer.removeRange([node.tag.range[0], node.quasi.range[0]]) });
|
|
99
|
+
},
|
|
85
100
|
}),
|
|
86
101
|
};
|
|
87
102
|
|
|
88
|
-
/**
|
|
103
|
+
/** What starts a new reading context between two conditional expressions: the inner one is then a value of its own, not a branch of the outer. */
|
|
104
|
+
const BREAKS_NESTING = new Set(['ArrayExpression', 'ObjectExpression', 'FunctionExpression', 'ArrowFunctionExpression', 'JSXExpressionContainer']);
|
|
105
|
+
|
|
106
|
+
/** S3358: a conditional expression anywhere inside another one (a branch, a test, a call argument, a template, a cast), up to an array, object, function or JSX expression, is read inside out; name the inner one. */
|
|
89
107
|
const noNestedConditional = {
|
|
90
108
|
meta: { type: 'suggestion', schema: [], messages: { nested: 'S3358: extract this nested conditional expression into its own statement or a named function.' } },
|
|
91
109
|
create: (context) => ({
|
|
92
110
|
ConditionalExpression: (node) => {
|
|
93
|
-
|
|
111
|
+
for (let parent = node.parent; parent; parent = parent.parent) {
|
|
112
|
+
if (parent.type === 'ConditionalExpression') {
|
|
113
|
+
context.report({ node, messageId: 'nested' });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (BREAKS_NESTING.has(parent.type)) return;
|
|
117
|
+
}
|
|
94
118
|
},
|
|
95
119
|
}),
|
|
96
120
|
};
|
|
@@ -264,6 +288,233 @@ const noLineSeparatorLiteral = {
|
|
|
264
288
|
}),
|
|
265
289
|
};
|
|
266
290
|
|
|
291
|
+
/** The line width of @starci/prettier-config: a merged import longer than this is laid out one specifier a line. */
|
|
292
|
+
const PRINT_WIDTH = 120;
|
|
293
|
+
const TRAILING_BLANK = /[ \t]*\r?\n?/y;
|
|
294
|
+
|
|
295
|
+
/** S3863: one module is imported once; a value and a type from the same module are one `import { value, type Type }`. */
|
|
296
|
+
const noDuplicateImport = {
|
|
297
|
+
meta: { type: 'suggestion', fixable: 'code', schema: [], messages: { duplicate: 'S3863: \'{{ source }}\' is imported more than once. Merge the imports into one: `import { value, type Type } from \'{{ source }}\'`.' } },
|
|
298
|
+
create: (context) => {
|
|
299
|
+
const { sourceCode } = context;
|
|
300
|
+
const groups = new Map();
|
|
301
|
+
/** The specifier list of one merged import, or null when the group cannot be merged without changing what it binds. */
|
|
302
|
+
const mergedText = (group) => {
|
|
303
|
+
const defaults = group.filter((declaration) => declaration.specifiers.some((specifier) => specifier.type === 'ImportDefaultSpecifier'));
|
|
304
|
+
const mergeable = group.every((declaration) => (declaration.attributes?.length ?? 0) === 0 && declaration.specifiers.every((specifier) => specifier.type !== 'ImportNamespaceSpecifier'))
|
|
305
|
+
&& defaults.length <= 1 && defaults.every((declaration) => declaration.importKind !== 'type');
|
|
306
|
+
if (!mergeable) return null;
|
|
307
|
+
const allType = group.every((declaration) => declaration.importKind === 'type');
|
|
308
|
+
const names = new Set();
|
|
309
|
+
for (const declaration of group) {
|
|
310
|
+
for (const specifier of declaration.specifiers) {
|
|
311
|
+
if (specifier.type !== 'ImportSpecifier') continue;
|
|
312
|
+
const text = sourceCode.getText(specifier);
|
|
313
|
+
names.add(declaration.importKind === 'type' && !allType && specifier.importKind !== 'type' ? `type ${text}` : text);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
const head = defaults[0]?.specifiers.find((specifier) => specifier.type === 'ImportDefaultSpecifier');
|
|
317
|
+
const parts = [head ? sourceCode.getText(head) : null, names.size > 0 ? `{ ${[...names].join(', ')} }` : null].filter(Boolean);
|
|
318
|
+
const semicolon = sourceCode.getText(group[0]).endsWith(';') ? ';' : '';
|
|
319
|
+
const kind = allType ? 'type ' : '';
|
|
320
|
+
const tail = ` from ${sourceCode.getText(group[0].source)}${semicolon}`;
|
|
321
|
+
const single = `import ${kind}${parts.join(', ')}${tail}`;
|
|
322
|
+
if (single.length <= PRINT_WIDTH || names.size === 0) return single;
|
|
323
|
+
// as Prettier lays out an import that does not fit one line: one specifier a line, a trailing comma
|
|
324
|
+
const lines = [...names].map((name) => ` ${name},`).join('\n');
|
|
325
|
+
return `import ${kind}${head ? `${sourceCode.getText(head)}, ` : ''}{\n${lines}\n}${tail}`;
|
|
326
|
+
};
|
|
327
|
+
const removal = (declaration) => {
|
|
328
|
+
TRAILING_BLANK.lastIndex = declaration.range[1];
|
|
329
|
+
const tail = TRAILING_BLANK.exec(sourceCode.text);
|
|
330
|
+
return [declaration.range[0], declaration.range[1] + (tail ? tail[0].length : 0)];
|
|
331
|
+
};
|
|
332
|
+
return {
|
|
333
|
+
ImportDeclaration: (node) => {
|
|
334
|
+
if (node.specifiers.length === 0) return;
|
|
335
|
+
const key = `${String(node.source.value)}\u0000${(node.attributes ?? []).map((attribute) => sourceCode.getText(attribute)).join(',')}`;
|
|
336
|
+
groups.set(key, [...(groups.get(key) ?? []), node]);
|
|
337
|
+
},
|
|
338
|
+
'Program:exit': () => {
|
|
339
|
+
for (const group of groups.values()) {
|
|
340
|
+
if (group.length < 2) continue;
|
|
341
|
+
const merged = mergedText(group);
|
|
342
|
+
group.slice(1).forEach((declaration, index) => {
|
|
343
|
+
const fix = index === 0 && merged !== null
|
|
344
|
+
? (fixer) => [fixer.replaceText(group[0], merged), ...group.slice(1).map((later) => fixer.removeRange(removal(later)))]
|
|
345
|
+
: undefined;
|
|
346
|
+
context.report({ node: declaration, messageId: 'duplicate', data: { source: String(declaration.source.value) }, fix });
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
/** The first non-whitespace-only children of a fragment or element: JSX trims a text of blanks that holds a line break. */
|
|
355
|
+
const significantChildren = (children) => children.filter((child) => !(child.type === 'JSXText' && /^\s*$/u.test(child.value) && /[\r\n]/u.test(child.value)) && !(child.type === 'JSXExpressionContainer' && child.expression.type === 'JSXEmptyExpression'));
|
|
356
|
+
|
|
357
|
+
/** Whether the opening element is a fragment: `<>` (a JSXFragment) is handled apart, this is `<Fragment>` or `<React.Fragment>`. */
|
|
358
|
+
const isFragmentElement = (opening) => (opening.name.type === 'JSXIdentifier' && opening.name.name === 'Fragment')
|
|
359
|
+
|| (opening.name.type === 'JSXMemberExpression' && opening.name.property.name === 'Fragment' && opening.name.object.type === 'JSXIdentifier');
|
|
360
|
+
|
|
361
|
+
/** S6749: a fragment that wraps nothing or one child is removed; the child stands for it. */
|
|
362
|
+
const noUselessFragment = {
|
|
363
|
+
meta: {
|
|
364
|
+
type: 'suggestion',
|
|
365
|
+
fixable: 'code',
|
|
366
|
+
schema: [],
|
|
367
|
+
messages: {
|
|
368
|
+
empty: 'S6749: remove this empty fragment.',
|
|
369
|
+
single: 'S6749: this fragment wraps one child; remove the fragment and keep the child.',
|
|
370
|
+
},
|
|
371
|
+
},
|
|
372
|
+
create: (context) => {
|
|
373
|
+
const { sourceCode } = context;
|
|
374
|
+
const check = (node, children) => {
|
|
375
|
+
const parentIsJsx = node.parent?.type === 'JSXElement' || node.parent?.type === 'JSXFragment';
|
|
376
|
+
const kept = significantChildren(children);
|
|
377
|
+
if (kept.length === 0) {
|
|
378
|
+
context.report({ node, messageId: 'empty' });
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (kept.length !== 1) return;
|
|
382
|
+
const [only] = kept;
|
|
383
|
+
if (only.type === 'JSXText' && !parentIsJsx) return;
|
|
384
|
+
const fix = only.type === 'JSXElement' || only.type === 'JSXFragment' ? (fixer) => fixer.replaceText(node, sourceCode.getText(only)) : undefined;
|
|
385
|
+
context.report({ node, messageId: 'single', fix });
|
|
386
|
+
};
|
|
387
|
+
return {
|
|
388
|
+
JSXFragment: (node) => check(node, node.children),
|
|
389
|
+
JSXElement: (node) => {
|
|
390
|
+
if (isFragmentElement(node.openingElement) && node.openingElement.attributes.length === 0) check(node, node.children);
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
const isUppercaseName = (name) => typeof name === 'string' && /^[A-Z]/u.test(name);
|
|
397
|
+
|
|
398
|
+
/** The name a function is bound to: its own id, or the variable that holds it directly or through `memo(...)` / `forwardRef(...)`. */
|
|
399
|
+
function functionName(node) {
|
|
400
|
+
if (node.id?.name) return node.id.name;
|
|
401
|
+
let holder = node.parent;
|
|
402
|
+
while (holder?.type === 'CallExpression') holder = holder.parent;
|
|
403
|
+
return holder?.type === 'VariableDeclarator' && holder.id.type === 'Identifier' ? holder.id.name : null;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** S6478: a component declared inside another component is a new type on every render and remounts its subtree; declare it at module level. */
|
|
407
|
+
const noNestedComponent = {
|
|
408
|
+
meta: { type: 'problem', schema: [], messages: { nested: 'S6478: the component `{{ name }}` is declared inside the component `{{ outer }}`, so it is a new component on every render and its state is lost. Move it to module level and pass what it reads as props.' } },
|
|
409
|
+
create: (context) => {
|
|
410
|
+
const frames = [];
|
|
411
|
+
const enter = (node) => frames.push({ node, name: functionName(node), jsx: false, nested: [] });
|
|
412
|
+
const markJsx = () => frames.forEach((frame) => { frame.jsx = true; });
|
|
413
|
+
const exit = () => {
|
|
414
|
+
const frame = frames.pop();
|
|
415
|
+
if (isUppercaseName(frame.name) && frame.jsx) {
|
|
416
|
+
const outer = [...frames].reverse().find((candidate) => isUppercaseName(candidate.name));
|
|
417
|
+
outer?.nested.push(frame);
|
|
418
|
+
}
|
|
419
|
+
if (frame.jsx) for (const inner of frame.nested) context.report({ node: inner.node.id ?? inner.node.parent ?? inner.node, messageId: 'nested', data: { name: inner.name, outer: frame.name } });
|
|
420
|
+
};
|
|
421
|
+
return { FunctionDeclaration: enter, FunctionExpression: enter, ArrowFunctionExpression: enter, 'FunctionDeclaration:exit': exit, 'FunctionExpression:exit': exit, 'ArrowFunctionExpression:exit': exit, JSXElement: markJsx, JSXFragment: markJsx };
|
|
422
|
+
},
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
/** S6748: children go between the tags. Where they cannot (a connected block that renders a pure component), the slot has a name of its own. */
|
|
426
|
+
const noChildrenProp = {
|
|
427
|
+
meta: {
|
|
428
|
+
type: 'problem',
|
|
429
|
+
schema: [],
|
|
430
|
+
messages: {
|
|
431
|
+
children: 'S6748: do not pass `children` as a prop; nest the content between the tags. In a connected block (`blocks/*/index.tsx`, FE_CONNECTED_BLOCK_RENDER_PAIR, FE_WORLD_OWNER_RENDER_BOUNDARY) nesting is not available: pass the slot under a prop of another name (`content`, `footer`, ...) to the pure component.',
|
|
432
|
+
},
|
|
433
|
+
},
|
|
434
|
+
create: (context) => ({
|
|
435
|
+
JSXAttribute: (node) => {
|
|
436
|
+
if (node.name.type === 'JSXIdentifier' && node.name.name === 'children') context.report({ node, messageId: 'children' });
|
|
437
|
+
},
|
|
438
|
+
CallExpression: (node) => {
|
|
439
|
+
const callee = node.callee;
|
|
440
|
+
const creates = (callee.type === 'Identifier' && callee.name === 'createElement') || (callee.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier' && callee.property.name === 'createElement');
|
|
441
|
+
const props = node.arguments[1];
|
|
442
|
+
if (!creates || props?.type !== 'ObjectExpression') return;
|
|
443
|
+
for (const property of props.properties) {
|
|
444
|
+
if (property.type === 'Property' && !property.computed && (property.key.name === 'children' || property.key.value === 'children')) context.report({ node: property, messageId: 'children' });
|
|
445
|
+
}
|
|
446
|
+
},
|
|
447
|
+
}),
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
/** S6754: `useState` is destructured into a value and its setter, named after each other. */
|
|
451
|
+
const useStateDestructured = {
|
|
452
|
+
meta: {
|
|
453
|
+
type: 'suggestion',
|
|
454
|
+
schema: [],
|
|
455
|
+
messages: {
|
|
456
|
+
pair: 'S6754: destructure the `useState` result into a value and its setter: `const [value, setValue] = useState(...)`.',
|
|
457
|
+
symmetric: 'S6754: name the setter after the value: `[{{ value }}, set{{ Value }}]`.',
|
|
458
|
+
},
|
|
459
|
+
},
|
|
460
|
+
create: (context) => ({
|
|
461
|
+
CallExpression: (node) => {
|
|
462
|
+
const callee = node.callee;
|
|
463
|
+
const isUseState = (callee.type === 'Identifier' && callee.name === 'useState') || (callee.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier' && callee.property.name === 'useState');
|
|
464
|
+
if (!isUseState || node.parent?.type !== 'VariableDeclarator' || node.parent.init !== node) return;
|
|
465
|
+
const id = node.parent.id;
|
|
466
|
+
if (id.type !== 'ArrayPattern' || id.elements.length !== 2) {
|
|
467
|
+
context.report({ node: id, messageId: 'pair' });
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const [value, setter] = id.elements;
|
|
471
|
+
if (value?.type !== 'Identifier' || setter?.type !== 'Identifier') return;
|
|
472
|
+
const Value = value.name.charAt(0).toUpperCase() + value.name.slice(1);
|
|
473
|
+
if (setter.name !== `set${Value}`) context.report({ node: setter, messageId: 'symmetric', data: { value: value.name, Value } });
|
|
474
|
+
},
|
|
475
|
+
}),
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
/** The native element each ARIA role stands for: a host element with the role and another tag is written as the native one (S6819). A role with no native element, or an ambiguous one (`img` on an `svg`, `group`), is not listed. */
|
|
479
|
+
const NATIVE_FOR_ROLE = Object.freeze({
|
|
480
|
+
status: ['output'], navigation: ['nav'], main: ['main'], article: ['article'], complementary: ['aside'], contentinfo: ['footer'], banner: ['header'],
|
|
481
|
+
form: ['form'], button: ['button'], dialog: ['dialog'], figure: ['figure'], heading: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'], link: ['a'],
|
|
482
|
+
list: ['ul', 'ol', 'menu'], listitem: ['li'], progressbar: ['progress'], region: ['section'], separator: ['hr'], table: ['table'], row: ['tr'], cell: ['td'],
|
|
483
|
+
columnheader: ['th'], rowheader: ['th'], checkbox: ['input'], radio: ['input'], slider: ['input'], spinbutton: ['input'], searchbox: ['input'],
|
|
484
|
+
textbox: ['input', 'textarea'], option: ['option'], combobox: ['select', 'input'], term: ['dt'], definition: ['dd'],
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
/** S6819: a native element carries its role; a host element given a `role` that another native element has is that element. */
|
|
488
|
+
const preferTagOverRole = {
|
|
489
|
+
meta: { type: 'suggestion', schema: [], messages: { tag: 'S6819: use the native <{{ tag }}> element instead of role="{{ role }}" on <{{ name }}>.' } },
|
|
490
|
+
create: (context) => ({
|
|
491
|
+
JSXOpeningElement: (node) => {
|
|
492
|
+
if (node.name.type !== 'JSXIdentifier' || !/^[a-z]/u.test(node.name.name)) return;
|
|
493
|
+
const attribute = attributeOf(node, 'role');
|
|
494
|
+
const literal = attribute?.value?.type === 'JSXExpressionContainer' ? attribute.value.expression : attribute?.value;
|
|
495
|
+
const role = literal?.type === 'Literal' ? literal.value : undefined;
|
|
496
|
+
const tags = typeof role === 'string' ? NATIVE_FOR_ROLE[role.trim().split(/\s+/u)[0]] : undefined;
|
|
497
|
+
if (tags === undefined || tags.includes(node.name.name)) return;
|
|
498
|
+
context.report({ node: attribute, messageId: 'tag', data: { tag: tags[0], role: role.trim(), name: node.name.name } });
|
|
499
|
+
},
|
|
500
|
+
}),
|
|
501
|
+
};
|
|
502
|
+
|
|
503
|
+
/** The bidirectional control characters of text:S6389: they reorder the text a reader sees against the text the compiler reads. */
|
|
504
|
+
const BIDI_CONTROLS = /[--]/gu;
|
|
505
|
+
/** text:S6389 (Trojan Source): a raw embedding, override, isolate or pop control character anywhere in a file, specs included, is refused. */
|
|
506
|
+
const noBidirectionalCharacter = {
|
|
507
|
+
meta: { type: 'problem', schema: [], messages: { raw: 'A bidirectional control character ({{ code }}) reorders how this line reads. Write the escape `\\u{{{ hex }}}` inside a string, template or regular expression, or delete the character anywhere else.' } },
|
|
508
|
+
create: (context) => ({
|
|
509
|
+
Program: () => {
|
|
510
|
+
for (const found of context.sourceCode.text.matchAll(BIDI_CONTROLS)) {
|
|
511
|
+
const hex = found[0].codePointAt(0).toString(16).toUpperCase();
|
|
512
|
+
context.report({ loc: context.sourceCode.getLocFromIndex(found.index), messageId: 'raw', data: { code: `U+${hex}`, hex } });
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
}),
|
|
516
|
+
};
|
|
517
|
+
|
|
267
518
|
/** The files the example scans leave out: a unit spec and an end-to-end spec (the regex, and the flat-config globs of the same set). */
|
|
268
519
|
const OUTSIDE_THE_SCAN = /\.(?:e2e-)?spec\.[cm]?[jt]sx?$/;
|
|
269
520
|
export const OUTSIDE_THE_SCAN_FILES = Object.freeze(['**/*.spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', '**/*.e2e-spec.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']);
|
|
@@ -271,7 +522,7 @@ export const OUTSIDE_THE_SCAN_FILES = Object.freeze(['**/*.spec.{js,mjs,cjs,ts,m
|
|
|
271
522
|
/** The rule judging only the files the scan judges. */
|
|
272
523
|
const scanned = (rule) => ({ ...rule, create: (context) => (OUTSIDE_THE_SCAN.test(context.filename) ? {} : rule.create(context)) });
|
|
273
524
|
|
|
274
|
-
/** The rules both canons publish, by published name. */
|
|
525
|
+
/** The rules both canons publish, by published name (the React ones, from `no-useless-fragment` to `prefer-tag-over-role`, only the front end names). */
|
|
275
526
|
export const SONAR_SYNTAX_RULES = Object.freeze({
|
|
276
527
|
'no-await-in-loop': scanned(noAwaitInLoop),
|
|
277
528
|
'prefer-code-point': scanned(preferCodePoint),
|
|
@@ -284,4 +535,11 @@ export const SONAR_SYNTAX_RULES = Object.freeze({
|
|
|
284
535
|
'media-has-caption': scanned(mediaHasCaption),
|
|
285
536
|
'max-params': scanned(maxParams),
|
|
286
537
|
'no-line-separator-literal': noLineSeparatorLiteral,
|
|
538
|
+
'no-bidirectional-character': noBidirectionalCharacter,
|
|
539
|
+
'no-duplicate-import': scanned(noDuplicateImport),
|
|
540
|
+
'no-useless-fragment': scanned(noUselessFragment),
|
|
541
|
+
'no-nested-component': scanned(noNestedComponent),
|
|
542
|
+
'no-children-prop': scanned(noChildrenProp),
|
|
543
|
+
'use-state-destructured': scanned(useStateDestructured),
|
|
544
|
+
'prefer-tag-over-role': scanned(preferTagOverRole),
|
|
287
545
|
});
|
|
@@ -34,12 +34,33 @@ export const SONAR_WAY_NOT_APPLICABLE = Object.freeze({
|
|
|
34
34
|
|
|
35
35
|
/**
|
|
36
36
|
* The Sonar way rules SonarSource implements on an ESLint rule outside eslint-plugin-sonarjs: `{ sonar, rule, options? }`. The canon syntax
|
|
37
|
-
* rules carry S107 (`max-params`, which spares the constructor of an injectable class as the server does)
|
|
38
|
-
*
|
|
37
|
+
* rules (sonar-syntax-rules.mjs) carry S107 (`max-params`, which spares the constructor of an injectable class as the server does), S3863
|
|
38
|
+
* (`no-duplicate-import`: a value and a type from one module are one import, and `--fix` merges them), S4084 (`media-has-caption`), S6478
|
|
39
|
+
* (`no-nested-component`), S6748 (`no-children-prop`), S6749 (`no-useless-fragment`), S6754 (`use-state-destructured`) and S6819
|
|
40
|
+
* (`prefer-tag-over-role`), the last five front end; S6582 is typescript-eslint's `prefer-optional-chain`, which needs the type information
|
|
41
|
+
* the canons' typed block provides, and so do S6606 and S4123. S7718 keeps `cause` as a catch parameter's name beside `error` (and `error_`
|
|
42
|
+
* where `error` is already declared): the scan accepts it, and the back end's wrapped failures are named so.
|
|
39
43
|
*/
|
|
40
44
|
export const SONAR_WAY_EXTRA = Object.freeze([
|
|
41
|
-
{ sonar: 'S3863', rule: 'no-duplicate-imports', options: [{ allowSeparateTypeImports: true }] },
|
|
42
45
|
{ sonar: 'S6582', rule: '@typescript-eslint/prefer-optional-chain' },
|
|
46
|
+
{ sonar: 'S6606', rule: '@typescript-eslint/prefer-nullish-coalescing' },
|
|
47
|
+
{ sonar: 'S4123', rule: '@typescript-eslint/await-thenable' },
|
|
48
|
+
{ sonar: 'S1186', rule: '@typescript-eslint/no-empty-function' },
|
|
49
|
+
{ sonar: 'S6671', rule: 'prefer-promise-reject-errors', options: [{ allowEmptyReject: false }] },
|
|
50
|
+
{ sonar: 'S6325', rule: 'prefer-regex-literals' },
|
|
51
|
+
{ sonar: 'S878', rule: 'no-sequences', options: [{ allowInParentheses: false }] },
|
|
52
|
+
{ sonar: 'S6535', rule: 'no-useless-escape' },
|
|
53
|
+
{ sonar: 'S6661', rule: 'prefer-object-spread' },
|
|
54
|
+
{ sonar: 'S7718', rule: 'unicorn/catch-error-name', options: [{ name: 'error', ignore: [/^cause$/u] }] },
|
|
55
|
+
{ sonar: 'S7727', rule: 'unicorn/no-array-callback-reference' },
|
|
56
|
+
{ sonar: 'S7737', rule: 'unicorn/no-object-as-default-parameter' },
|
|
57
|
+
{ sonar: 'S7739', rule: 'unicorn/no-thenable' },
|
|
58
|
+
{ sonar: 'S7746', rule: 'unicorn/no-useless-promise-resolve-reject' },
|
|
59
|
+
{ sonar: 'S7753', rule: 'unicorn/prefer-array-index-of' },
|
|
60
|
+
{ sonar: 'S7755', rule: 'unicorn/prefer-at' },
|
|
61
|
+
{ sonar: 'S7766', rule: 'unicorn/prefer-math-min-max' },
|
|
62
|
+
{ sonar: 'S7781', rule: 'unicorn/prefer-string-replace-all' },
|
|
63
|
+
{ sonar: 'S7787', rule: 'unicorn/require-module-specifiers' },
|
|
43
64
|
{ sonar: 'S4138', rule: 'unicorn/no-for-loop' },
|
|
44
65
|
{ sonar: 'S7721', rule: 'unicorn/consistent-function-scoping' },
|
|
45
66
|
{ sonar: 'S7732', rule: 'unicorn/no-instanceof-builtins' },
|
|
@@ -56,6 +77,36 @@ export const SONAR_WAY_EXTRA = Object.freeze([
|
|
|
56
77
|
{ sonar: 'S7784', rule: 'unicorn/prefer-structured-clone' },
|
|
57
78
|
]);
|
|
58
79
|
|
|
80
|
+
/**
|
|
81
|
+
* The sonarjs rules whose Sonar scope is Tests (a `scope = 'Tests'` in the rule's generated meta, asserted in sonar-way.spec.ts): the scan
|
|
82
|
+
* runs them over the files `sonar.tests` names and not over the product source, so the canons run them over the specs and nowhere else
|
|
83
|
+
* is added. S9073 is outside sonarjs' own recommended set and inside the profile.
|
|
84
|
+
*/
|
|
85
|
+
export const SONAR_WAY_TEST_RULES = Object.freeze([
|
|
86
|
+
'no-skipped-tests', 'no-empty-test-file', 'assertions-in-tests', 'no-fixed-wait-in-tests', 'no-incomplete-assertions', 'inverted-assertion-arguments',
|
|
87
|
+
'no-incompatible-assertion-types', 'no-same-argument-assert', 'prefer-specific-assertions', 'no-trivial-assertions', 'test-check-exception',
|
|
88
|
+
'stable-tests', 'parameterized-tests', 'no-code-after-done', 'disabled-timeout', 'chai-determinate-assertion', 'no-exclusive-tests',
|
|
89
|
+
'no-duplicate-test-title', 'async-test-assertions', 'no-empty-test-title', 'hooks-before-test-cases', 'no-forced-browser-interaction',
|
|
90
|
+
'assertions-in-test-cases', 'synchronous-suite-callback', 'no-debug-commands-in-ui-tests', 'no-interpolation-in-inline-snapshots',
|
|
91
|
+
'explicit-test-skip', 'no-empty-parameterized-test-dataset', 'testing-library-query-assertion', 'synchronous-exception-assertions',
|
|
92
|
+
'composite-assertions', 'no-duplicate-parameterized-test-case', 'testing-library-prefer-query-by-disappearance', 'prefer-cypress-should',
|
|
93
|
+
'vitest-mock-at-module-scope', 'no-networkidle-wait',
|
|
94
|
+
]);
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The flat-config rule levels of the test-scoped Sonar way rules, for the spec files the product source block leaves out.
|
|
98
|
+
*
|
|
99
|
+
* @param {object} sonarjs - The eslint-plugin-sonarjs plugin.
|
|
100
|
+
*/
|
|
101
|
+
export function sonarWayTestRules(sonarjs) {
|
|
102
|
+
const rules = {};
|
|
103
|
+
for (const name of SONAR_WAY_TEST_RULES) {
|
|
104
|
+
const declared = sonarjs.configs.recommended.rules[`sonarjs/${name}`];
|
|
105
|
+
rules[`sonarjs/${name}`] = ['error', ...(Array.isArray(declared) ? declared.slice(1) : [])];
|
|
106
|
+
}
|
|
107
|
+
return rules;
|
|
108
|
+
}
|
|
109
|
+
|
|
59
110
|
/** The ESM-only Sonar way rules: S7785 prefers top-level await (see SONAR_WAY_NOT_APPLICABLE). */
|
|
60
111
|
const SONAR_WAY_ESM = Object.freeze([{ sonar: 'S7785', rule: 'unicorn/prefer-top-level-await' }]);
|
|
61
112
|
|