@shivaedev/quality 0.51.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +26 -13
  3. package/biome/declarations.json +0 -5
  4. package/biome/plugins/ambient-runtime.grit +1 -1
  5. package/biome/preset.json +1 -1
  6. package/dist/baseline/format.d.ts +1 -0
  7. package/dist/baseline/format.d.ts.map +1 -1
  8. package/dist/baseline/format.js +3 -2
  9. package/dist/baseline/format.js.map +1 -1
  10. package/dist/baseline/update.js +1 -1
  11. package/dist/baseline/update.js.map +1 -1
  12. package/dist/cli/lint.d.ts +2 -3
  13. package/dist/cli/lint.d.ts.map +1 -1
  14. package/dist/cli/lint.js +4 -2
  15. package/dist/cli/lint.js.map +1 -1
  16. package/dist/config/globs.d.ts +17 -0
  17. package/dist/config/globs.d.ts.map +1 -0
  18. package/dist/config/globs.js +18 -0
  19. package/dist/config/globs.js.map +1 -0
  20. package/dist/engine/runRules.d.ts +2 -1
  21. package/dist/engine/runRules.d.ts.map +1 -1
  22. package/dist/engine/runRules.js +4 -1
  23. package/dist/engine/runRules.js.map +1 -1
  24. package/dist/engine/session.d.ts +1 -1
  25. package/dist/engine/session.d.ts.map +1 -1
  26. package/dist/engine/session.js +9 -5
  27. package/dist/engine/session.js.map +1 -1
  28. package/dist/hooks/preCommit.d.ts +2 -1
  29. package/dist/hooks/preCommit.d.ts.map +1 -1
  30. package/dist/imports/fences/compilePolicy.d.ts.map +1 -1
  31. package/dist/imports/fences/compilePolicy.js +6 -2
  32. package/dist/imports/fences/compilePolicy.js.map +1 -1
  33. package/dist/inventory/shadcnAlias.js.map +1 -1
  34. package/dist/rule.d.ts +1 -0
  35. package/dist/rule.d.ts.map +1 -1
  36. package/dist/rule.js +7 -3
  37. package/dist/rule.js.map +1 -1
  38. package/dist/rules/builtIn.d.ts +36 -9
  39. package/dist/rules/builtIn.d.ts.map +1 -1
  40. package/dist/rules/effect/boundary.js +1 -1
  41. package/dist/rules/effect/boundary.js.map +1 -1
  42. package/dist/rules/effect/boundaryCalls.js +1 -1
  43. package/dist/rules/effect/boundaryCalls.js.map +1 -1
  44. package/dist/rules/effect/boundaryReference.js +1 -1
  45. package/dist/rules/effect/boundaryReference.js.map +1 -1
  46. package/dist/rules/files/folderNames.d.ts +8 -2
  47. package/dist/rules/files/folderNames.d.ts.map +1 -1
  48. package/dist/rules/files/folderNames.js +7 -5
  49. package/dist/rules/files/folderNames.js.map +1 -1
  50. package/dist/rules/files/namedAfterExport.d.ts +4 -1
  51. package/dist/rules/files/namedAfterExport.d.ts.map +1 -1
  52. package/dist/rules/files/namedAfterExport.js +6 -7
  53. package/dist/rules/files/namedAfterExport.js.map +1 -1
  54. package/dist/rules/files/otherNames.d.ts +8 -2
  55. package/dist/rules/files/otherNames.d.ts.map +1 -1
  56. package/dist/rules/files/otherNames.js +7 -5
  57. package/dist/rules/files/otherNames.js.map +1 -1
  58. package/dist/rules/noBarrel.js +1 -1
  59. package/dist/rules/noBarrel.js.map +1 -1
  60. package/dist/rules/secondNames.d.ts.map +1 -1
  61. package/dist/rules/secondNames.js +5 -1
  62. package/dist/rules/secondNames.js.map +1 -1
  63. package/dist/rules/stories/authSql.d.ts +4 -1
  64. package/dist/rules/stories/authSql.d.ts.map +1 -1
  65. package/dist/rules/stories/authSql.js +6 -3
  66. package/dist/rules/stories/authSql.js.map +1 -1
  67. package/dist/rules/stories/collectionOrigins.d.ts +5 -0
  68. package/dist/rules/stories/collectionOrigins.d.ts.map +1 -0
  69. package/dist/rules/stories/collectionOrigins.js +17 -0
  70. package/dist/rules/stories/collectionOrigins.js.map +1 -0
  71. package/dist/rules/stories/httpStatus.d.ts +4 -1
  72. package/dist/rules/stories/httpStatus.d.ts.map +1 -1
  73. package/dist/rules/stories/httpStatus.js +6 -3
  74. package/dist/rules/stories/httpStatus.js.map +1 -1
  75. package/dist/rules/stories/namedValues.d.ts.map +1 -1
  76. package/dist/rules/stories/namedValues.js +5 -5
  77. package/dist/rules/stories/namedValues.js.map +1 -1
  78. package/dist/rules/stories/noLimitImports.d.ts.map +1 -1
  79. package/dist/rules/stories/noLimitImports.js +4 -2
  80. package/dist/rules/stories/noLimitImports.js.map +1 -1
  81. package/dist/rules/stories/origins.d.ts +1 -2
  82. package/dist/rules/stories/origins.d.ts.map +1 -1
  83. package/dist/rules/stories/origins.js +12 -6
  84. package/dist/rules/stories/origins.js.map +1 -1
  85. package/dist/rules/stories/prerequisites.d.ts.map +1 -1
  86. package/dist/rules/stories/prerequisites.js +6 -24
  87. package/dist/rules/stories/prerequisites.js.map +1 -1
  88. package/dist/rules/stories/program.d.ts.map +1 -1
  89. package/dist/rules/stories/program.js +8 -1
  90. package/dist/rules/stories/program.js.map +1 -1
  91. package/dist/rules/stories/sources.d.ts.map +1 -1
  92. package/dist/rules/stories/sources.js +19 -7
  93. package/dist/rules/stories/sources.js.map +1 -1
  94. package/dist/rules/stories/specHelpers.d.ts.map +1 -1
  95. package/dist/rules/stories/specHelpers.js +4 -2
  96. package/dist/rules/stories/specHelpers.js.map +1 -1
  97. package/dist/rules/stories/specs.js +1 -1
  98. package/dist/rules/stories/specs.js.map +1 -1
  99. package/dist/rules/stories/syntax.d.ts +0 -1
  100. package/dist/rules/stories/syntax.d.ts.map +1 -1
  101. package/dist/rules/stories/syntax.js +0 -4
  102. package/dist/rules/stories/syntax.js.map +1 -1
  103. package/dist/rules/suppressions/hiddenCast.d.ts +4 -0
  104. package/dist/rules/suppressions/hiddenCast.d.ts.map +1 -0
  105. package/dist/rules/suppressions/hiddenCast.js +80 -0
  106. package/dist/rules/suppressions/hiddenCast.js.map +1 -0
  107. package/dist/rules/suppressions/noDoubleCast.d.ts.map +1 -1
  108. package/dist/rules/suppressions/noDoubleCast.js +55 -4
  109. package/dist/rules/suppressions/noDoubleCast.js.map +1 -1
  110. package/dist/rules/suppressions/readonlyWrite.d.ts +4 -0
  111. package/dist/rules/suppressions/readonlyWrite.d.ts.map +1 -0
  112. package/dist/rules/suppressions/readonlyWrite.js +113 -0
  113. package/dist/rules/suppressions/readonlyWrite.js.map +1 -0
  114. package/dist/rules/test-names/colocated.d.ts +4 -1
  115. package/dist/rules/test-names/colocated.d.ts.map +1 -1
  116. package/dist/rules/test-names/colocated.js +5 -3
  117. package/dist/rules/test-names/colocated.js.map +1 -1
  118. package/dist/rules/test-names/follow.d.ts +4 -1
  119. package/dist/rules/test-names/follow.d.ts.map +1 -1
  120. package/dist/rules/test-names/follow.js +5 -3
  121. package/dist/rules/test-names/follow.js.map +1 -1
  122. package/dist/unitIoGuard.config.js +2 -2
  123. package/dist/unitIoGuard.config.js.map +1 -1
  124. package/package.json +3 -2
  125. package/src/baseline/format.ts +4 -2
  126. package/src/baseline/update.ts +1 -1
  127. package/src/cli/lint.ts +33 -27
  128. package/src/config/globs.ts +31 -0
  129. package/src/engine/runRules.ts +7 -2
  130. package/src/engine/session.ts +10 -5
  131. package/src/imports/fences/compilePolicy.ts +10 -2
  132. package/src/inventory/shadcnAlias.ts +1 -1
  133. package/src/rule.ts +12 -2
  134. package/src/rules/effect/boundary.ts +1 -1
  135. package/src/rules/effect/boundaryCalls.ts +1 -1
  136. package/src/rules/effect/boundaryReference.ts +1 -1
  137. package/src/rules/files/folderNames.ts +7 -5
  138. package/src/rules/files/namedAfterExport.ts +6 -7
  139. package/src/rules/files/otherNames.ts +7 -5
  140. package/src/rules/noBarrel.ts +1 -1
  141. package/src/rules/secondNames.ts +7 -1
  142. package/src/rules/stories/authSql.ts +6 -3
  143. package/src/rules/stories/collectionOrigins.ts +20 -0
  144. package/src/rules/stories/httpStatus.ts +6 -3
  145. package/src/rules/stories/namedValues.ts +7 -5
  146. package/src/rules/stories/noLimitImports.ts +4 -2
  147. package/src/rules/stories/origins.ts +12 -8
  148. package/src/rules/stories/prerequisites.ts +6 -25
  149. package/src/rules/stories/program.ts +9 -1
  150. package/src/rules/stories/sources.ts +21 -9
  151. package/src/rules/stories/specHelpers.ts +4 -2
  152. package/src/rules/stories/specs.ts +1 -1
  153. package/src/rules/stories/syntax.ts +0 -5
  154. package/src/rules/suppressions/hiddenCast.ts +95 -0
  155. package/src/rules/suppressions/noDoubleCast.ts +61 -5
  156. package/src/rules/suppressions/readonlyWrite.ts +140 -0
  157. package/src/rules/test-names/colocated.ts +5 -3
  158. package/src/rules/test-names/follow.ts +5 -3
  159. package/src/unitIoGuard.config.ts +3 -3
@@ -2,12 +2,11 @@ import { join } from "node:path";
2
2
  import ts from "typescript";
3
3
  import type { ImportGraph } from "#imports/graph.ts";
4
4
  import type { RuleInputs } from "#rule.ts";
5
+ import { iterationOrigin, type Origin } from "./collectionOrigins.ts";
5
6
  import { importOrigin } from "./importOrigin.ts";
6
7
  import { storyProgram } from "./program.ts";
7
8
  import { returnValues } from "./returnValues.ts";
8
9
 
9
- type Origin = "factory" | "kit" | "story" | "plain" | "suite" | "vitest" | "stories" | "function" | undefined;
10
-
11
10
  function importFrom(node: ts.Node): string | undefined {
12
11
  for (let current: ts.Node | undefined = node; current !== undefined; current = current.parent) {
13
12
  if (ts.isImportDeclaration(current) && ts.isStringLiteral(current.moduleSpecifier)) {
@@ -27,9 +26,12 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
27
26
  if (!ts.isVariableDeclaration(node.parent.parent)) {
28
27
  return undefined;
29
28
  }
30
- const value = node.parent.parent.initializer;
29
+ const value = visit(node.parent.parent);
30
+ if (ts.isArrayBindingPattern(node.parent)) {
31
+ return typeof value === "object" ? value[node.parent.elements.indexOf(node)] : undefined;
32
+ }
31
33
  const name = node.propertyName ?? node.name;
32
- return value !== undefined && (ts.isIdentifier(name) || ts.isStringLiteral(name)) ? member(value, name.text) : undefined;
34
+ return ts.isIdentifier(name) || ts.isStringLiteral(name) ? member(value, name.text) : undefined;
33
35
  }
34
36
 
35
37
  function declaration(node: ts.Node): Origin {
@@ -40,7 +42,7 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
40
42
  return importOrigin(importFrom(node));
41
43
  }
42
44
  if (ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node)) {
43
- return node.initializer === undefined ? undefined : origin(node.initializer);
45
+ return node.initializer === undefined ? iterationOrigin(node, visit) : visit(node.initializer);
44
46
  }
45
47
  return localBinding(node);
46
48
  }
@@ -72,8 +74,7 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
72
74
  return undefined;
73
75
  }
74
76
 
75
- function member(value: ts.Expression, name: string): Origin {
76
- const receiver = visit(value);
77
+ function member(receiver: Origin, name: string): Origin {
77
78
  if (receiver === "kit" && name === "it") {
78
79
  return "story";
79
80
  }
@@ -99,6 +100,9 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
99
100
  if (ts.isObjectLiteralExpression(node)) {
100
101
  return object(node);
101
102
  }
103
+ if (ts.isArrayLiteralExpression(node)) {
104
+ return node.elements.map(visit);
105
+ }
102
106
  return expression(node);
103
107
  }
104
108
 
@@ -119,7 +123,7 @@ export function storyOrigins(inputs: RuleInputs, graph: ImportGraph) {
119
123
  return call(node);
120
124
  }
121
125
  if (ts.isPropertyAccessExpression(node)) {
122
- return member(node.expression, node.name.text) ?? symbol(checker.getSymbolAtLocation(node.name));
126
+ return member(visit(node.expression), node.name.text) ?? symbol(checker.getSymbolAtLocation(node.name));
123
127
  }
124
128
  return ts.isIdentifier(node) ? identifier(node) : declaration(node);
125
129
  }
@@ -1,33 +1,14 @@
1
- import { posix } from "node:path";
2
1
  import { readPackageManifest } from "#adapters/manifestInventory.ts";
3
2
  import type { WorkspacePackage } from "#imports/workspace.ts";
4
3
  import type { RuleInputs } from "#rule.ts";
5
4
 
6
- const DEPENDENCIES = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"] as const;
7
-
8
- function object(value: unknown): value is Record<string, unknown> {
9
- return typeof value === "object" && value !== null && !Array.isArray(value);
10
- }
5
+ const PREREQUISITES = new Set(["@shivaedev/test-story", "@shivaedev/test", "@shivaedev/types"]);
11
6
 
12
7
  export async function storyPrerequisites(inputs: RuleInputs, packages: readonly WorkspacePackage[]): Promise<ReadonlySet<string>> {
13
- const root = (await readPackageManifest(inputs.readText, "package.json")) ?? {};
14
- const members = typeof root.name === "string" ? [...packages, { directory: "", name: root.name }] : packages;
15
- const byName = new Map(members.map((member) => [member.name, member]));
16
- const pending = ["@shivaedev/test-story"];
17
- const directories = new Set<string>();
18
- while (pending.length > 0) {
19
- const current = byName.get(pending.pop() ?? "");
20
- if (current === undefined || directories.has(current.directory)) {
21
- continue;
22
- }
23
- directories.add(current.directory);
24
- const value = (await readPackageManifest(inputs.readText, posix.join(current.directory, "package.json"))) ?? {};
25
- for (const key of DEPENDENCIES) {
26
- const dependencies = value[key];
27
- if (object(dependencies)) {
28
- pending.push(...Object.keys(dependencies).filter((name) => byName.has(name)));
29
- }
30
- }
8
+ const root = await readPackageManifest(inputs.readText, "package.json");
9
+ const directories = packages.filter((member) => PREREQUISITES.has(member.name)).map((member) => member.directory);
10
+ if (typeof root?.name === "string" && PREREQUISITES.has(root.name)) {
11
+ directories.push("");
31
12
  }
32
- return directories;
13
+ return new Set(directories);
33
14
  }
@@ -3,7 +3,13 @@ import ts from "typescript";
3
3
  import type { ImportGraph } from "#imports/graph.ts";
4
4
  import type { RuleInputs } from "#rule.ts";
5
5
 
6
+ const programs = new WeakMap<RuleInputs["sources"], ts.Program>();
7
+
6
8
  export function storyProgram(inputs: RuleInputs, graph: ImportGraph): ts.Program {
9
+ const known = programs.get(inputs.sources);
10
+ if (known !== undefined) {
11
+ return known;
12
+ }
7
13
  const sources = new Map(inputs.sources.map((file) => [join(inputs.root, file.path), file.text]));
8
14
  const targets = new Map(
9
15
  graph.edges.flatMap((edge) =>
@@ -25,5 +31,7 @@ export function storyProgram(inputs: RuleInputs, graph: ImportGraph): ts.Program
25
31
  return path === undefined ? undefined : { extension: ts.Extension.Ts, resolvedFileName: path };
26
32
  }),
27
33
  };
28
- return ts.createProgram([...sources.keys()], options, host);
34
+ const program = ts.createProgram([...sources.keys()], options, host);
35
+ programs.set(inputs.sources, program);
36
+ return program;
29
37
  }
@@ -1,20 +1,32 @@
1
1
  import { Effect } from "effect";
2
- import { packageOf, workspacePackages } from "#imports/workspace.ts";
2
+ import ts from "typescript";
3
+ import { importGraph } from "#imports/graph.ts";
4
+ import { packageOf } from "#imports/workspace.ts";
3
5
  import { isTestSupport, testName } from "#naming/testName.ts";
4
6
  import type { RuleInputs } from "#rule.ts";
7
+ import { storyOrigins } from "./origins.ts";
5
8
  import { storyPrerequisites } from "./prerequisites.ts";
6
9
 
7
10
  export const storySources = Effect.fn("Stories.storySources")(function* (inputs: RuleInputs) {
8
- const packages = yield* Effect.promise(() => workspacePackages(inputs));
11
+ const graph = yield* Effect.promise(() => importGraph(inputs));
12
+ const packages = graph.packages;
13
+ const origins = storyOrigins(inputs, graph);
9
14
  const exempt = yield* Effect.promise(() => storyPrerequisites(inputs, packages));
15
+ function hasStory(node: ts.Node): boolean {
16
+ return (ts.isCallExpression(node) && origins.origin(node.expression) === "story") || ts.forEachChild(node, hasStory) === true;
17
+ }
10
18
  return inputs.sources.filter((file) => {
11
19
  const modifiers = testName(file.path)?.modifiers;
12
- return (
13
- modifiers !== undefined
14
- && !isTestSupport(file.path)
15
- && !modifiers.includes("typecheck")
16
- && !modifiers.includes("unit")
17
- && !exempt.has(packageOf(packages, file.path)?.directory ?? "")
18
- );
20
+ if (
21
+ modifiers === undefined
22
+ || isTestSupport(file.path)
23
+ || modifiers.includes("typecheck")
24
+ || modifiers.includes("unit")
25
+ || exempt.has(packageOf(packages, file.path)?.directory ?? "")
26
+ ) {
27
+ return false;
28
+ }
29
+ const source = origins.source(file.path);
30
+ return source !== undefined && hasStory(source);
19
31
  });
20
32
  });
@@ -1,10 +1,12 @@
1
+ import { Effect } from "effect";
1
2
  import { defineRule } from "#rule.ts";
2
- import { isSpec, syntaxFindings, topLevelHelpers } from "./syntax.ts";
3
+ import { storySources } from "./sources.ts";
4
+ import { syntaxFindings, topLevelHelpers } from "./syntax.ts";
3
5
 
4
6
  const MESSAGE = "Declares a top-level helper in a spec. Move the action into the story kit's verbs or the setup into its traits in test-support/.";
5
7
 
6
8
  export const specHelpers = defineRule({
7
- check: ({ sources }) => sources.filter((file) => isSpec(file.path)).flatMap((file) => syntaxFindings(file, topLevelHelpers, MESSAGE)),
9
+ check: (inputs) => Effect.map(storySources(inputs), (stories) => stories.flatMap((file) => syntaxFindings(file, topLevelHelpers, MESSAGE))),
8
10
  description: "Specs state expectations; story-kit traits and verbs in test-support own helpers.",
9
11
  id: "tests/spec-helpers",
10
12
  });
@@ -95,6 +95,6 @@ export const storySpecs = defineRule({
95
95
  });
96
96
  },
97
97
  description:
98
- "Every package tests its real engine through its own test-story kit, and a plain test lives only in a .unit file that reaches no engine and mocks nothing. Typecheck tests and test-story's workspace prerequisites need no kit.",
98
+ "Every package tests its real engine through its own test-story kit, and a plain test lives only in a .unit file that reaches no engine and mocks nothing. Typecheck tests and the test-story, test and types packages need no kit.",
99
99
  id: "tests/story-specs",
100
100
  });
@@ -1,12 +1,7 @@
1
1
  import ts from "typescript";
2
- import { isTestSupport, testName } from "#naming/testName.ts";
3
2
  import type { Finding, SourceFile } from "#rule.ts";
4
3
  import { parse } from "#rules/parse.ts";
5
4
 
6
- export function isSpec(path: string): boolean {
7
- return testName(path)?.kind === "spec" && !isTestSupport(path);
8
- }
9
-
10
5
  export function unwrapped(node: ts.Expression): ts.Expression {
11
6
  return ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isNonNullExpression(node)
12
7
  ? unwrapped(node.expression)
@@ -0,0 +1,95 @@
1
+ import ts from "typescript";
2
+
3
+ function concrete(type: ts.TypeNode | undefined): boolean {
4
+ return type !== undefined && type.kind !== ts.SyntaxKind.UnknownKeyword;
5
+ }
6
+
7
+ function called(node: ts.Node, owner: string, method: string): node is ts.CallExpression {
8
+ return (
9
+ ts.isCallExpression(node)
10
+ && ts.isPropertyAccessExpression(node.expression)
11
+ && ts.isIdentifier(node.expression.expression)
12
+ && ownerName(node.expression.expression) === owner
13
+ && node.expression.name.text === method
14
+ );
15
+ }
16
+
17
+ function ownerName(node: ts.Identifier): string {
18
+ for (const statement of node.getSourceFile().statements) {
19
+ if (!(ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier))) {
20
+ continue;
21
+ }
22
+ const bindings = statement.importClause?.namedBindings;
23
+ if (bindings !== undefined && ts.isNamedImports(bindings)) {
24
+ const imported = bindings.elements.find((element) => element.name.text === node.text);
25
+ if (statement.moduleSpecifier.text === "effect" && imported !== undefined) {
26
+ return imported.propertyName?.text ?? imported.name.text;
27
+ }
28
+ }
29
+ if (
30
+ bindings !== undefined
31
+ && ts.isNamespaceImport(bindings)
32
+ && bindings.name.text === node.text
33
+ && statement.moduleSpecifier.text === "effect/Context"
34
+ ) {
35
+ return "Context";
36
+ }
37
+ }
38
+ return node.text;
39
+ }
40
+
41
+ function unwrapped(node: ts.Expression): ts.Expression {
42
+ return ts.isParenthesizedExpression(node) ? unwrapped(node.expression) : node;
43
+ }
44
+
45
+ function bindingCast(node: ts.Node): string | undefined {
46
+ if (!ts.isVariableDeclaration(node) || node.initializer === undefined) {
47
+ return undefined;
48
+ }
49
+ const value = unwrapped(node.initializer);
50
+ if (called(value, "JSON", "parse") && concrete(node.type)) {
51
+ return `Assigns JSON.parse directly to ${node.type?.getText()}. Keep the result unknown and use Schema.decodeUnknownEffect with a schema for that declared type.`;
52
+ }
53
+ if (called(value, "Reflect", "get") && node.type?.kind !== ts.SyntaxKind.UnknownKeyword) {
54
+ return "Binds an unchecked Reflect.get result. Declare the result unknown and narrow it or use Schema.decodeUnknownEffect with the required schema.";
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ function hasMapUnsafe(node: ts.Node): boolean {
60
+ return (ts.isPropertyAccessExpression(node) && node.name.text === "mapUnsafe") || ts.forEachChild(node, hasMapUnsafe) === true;
61
+ }
62
+
63
+ function identityOverload(node: ts.Node): string | undefined {
64
+ if (!ts.isFunctionDeclaration(node) || node.body === undefined || node.type?.kind !== ts.SyntaxKind.UnknownKeyword || node.name === undefined) {
65
+ return undefined;
66
+ }
67
+ const statement = node.body.statements[0];
68
+ if (node.body.statements.length !== 1 || statement === undefined || !ts.isReturnStatement(statement) || statement.expression === undefined) {
69
+ return undefined;
70
+ }
71
+ const returned = unwrapped(statement.expression);
72
+ if (!(ts.isIdentifier(returned) && node.parameters.some((parameter) => ts.isIdentifier(parameter.name) && parameter.name.text === returned.text))) {
73
+ return undefined;
74
+ }
75
+ const siblings = ts.isSourceFile(node.parent) || ts.isBlock(node.parent) || ts.isModuleBlock(node.parent) ? node.parent.statements : [];
76
+ const overload = siblings.find(
77
+ (sibling) => ts.isFunctionDeclaration(sibling) && sibling.body === undefined && sibling.name?.text === node.name?.text && concrete(sibling.type),
78
+ );
79
+ return overload === undefined || !ts.isFunctionDeclaration(overload)
80
+ ? undefined
81
+ : `An identity overload hides an unknown return value. Give the implementation the declared overload return type ${overload.type?.getText()} and let TypeScript check it; decode unknown input with Schema.decodeUnknownEffect.`;
82
+ }
83
+
84
+ export function hiddenCast(node: ts.Node): string | undefined {
85
+ if (ts.isTaggedTemplateExpression(node) && node.typeArguments?.length && ts.isIdentifier(node.tag) && node.tag.text === "sql") {
86
+ return SQL_ROW_CAST;
87
+ }
88
+ if (called(node, "Context", "makeUnsafe") && node.arguments.some(hasMapUnsafe)) {
89
+ return "Retags a Context through mapUnsafe. Preserve its declared Context service type and use Context.add or Effect.provideService for the required services.";
90
+ }
91
+ return bindingCast(node) ?? identityOverload(node);
92
+ }
93
+
94
+ export const SQL_ROW_CAST =
95
+ "Declares SQL rows with a generic instead of checking them. Use SqlSchema.findAll or SqlSchema.findOne with the declared row schema to decode the result.";
@@ -1,6 +1,10 @@
1
+ import { join } from "node:path";
1
2
  import ts from "typescript";
2
- import { defineRule, type Finding, type SourceFile } from "#rule.ts";
3
+ import { defineRule, type Finding, type RuleInputs, type SourceFile } from "#rule.ts";
4
+ import { effectProgram } from "#rules/effect/program.ts";
3
5
  import { parse } from "#rules/parse.ts";
6
+ import { hiddenCast, SQL_ROW_CAST } from "./hiddenCast.ts";
7
+ import { readonlyWrite, writeCandidate } from "./readonlyWrite.ts";
4
8
 
5
9
  const BRIDGES: ReadonlyMap<ts.SyntaxKind, string> = new Map([
6
10
  [ts.SyntaxKind.UnknownKeyword, "unknown"],
@@ -25,11 +29,14 @@ function bridgeOf(node: Assertion): string | undefined {
25
29
 
26
30
  function castsIn(path: string, source: ts.SourceFile): readonly Finding[] {
27
31
  const findings: Finding[] = [];
32
+ const hidden = !/(?:^|\/)(?:adapters|test-support)\//u.test(path);
28
33
  function visit(node: ts.Node): void {
29
34
  const bridge = isAssertion(node) ? bridgeOf(node) : undefined;
30
- if (bridge !== undefined) {
35
+ const implicit = hidden ? hiddenCast(node) : undefined;
36
+ const message = bridge === undefined ? implicit : `Casts through "${bridge}" to reach a type the value does not have.`;
37
+ if (message !== undefined) {
31
38
  const line = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1;
32
- findings.push({ file: path, line, message: `Casts through "${bridge}" to reach a type the value does not have.` });
39
+ findings.push({ file: path, line, message });
33
40
  }
34
41
  ts.forEachChild(node, visit);
35
42
  }
@@ -42,10 +49,59 @@ function doubleCasts(file: SourceFile): readonly Finding[] {
42
49
  return source === undefined ? [] : castsIn(file.path, source);
43
50
  }
44
51
 
52
+ function typedNodes(source: ts.SourceFile): readonly ts.Node[] {
53
+ const nodes: ts.Node[] = [];
54
+ function visit(node: ts.Node): void {
55
+ if (writeCandidate(node) || (ts.isTaggedTemplateExpression(node) && node.typeArguments?.length && node.tag.getText() !== "sql")) {
56
+ nodes.push(node);
57
+ }
58
+ ts.forEachChild(node, visit);
59
+ }
60
+ visit(source);
61
+ return nodes;
62
+ }
63
+
64
+ function typedCast(node: ts.Node, checker: ts.TypeChecker): string | undefined {
65
+ if (ts.isTaggedTemplateExpression(node)) {
66
+ const nativeSql = checker
67
+ .getTypeAtLocation(node.tag)
68
+ .getSymbol()
69
+ ?.getDeclarations()
70
+ ?.some((declaration) =>
71
+ /(?:^|\/)effect\/(?:src|dist(?:\/[^/]+)?)\/sql\/(?:SqlClient|Statement)\.(?:d\.)?ts$/u.test(declaration.getSourceFile().fileName),
72
+ );
73
+ return nativeSql ? SQL_ROW_CAST : undefined;
74
+ }
75
+ return readonlyWrite(node, checker);
76
+ }
77
+
78
+ function typedCasts(inputs: RuleInputs): readonly Finding[] {
79
+ const sources = inputs.sources.filter((file) => {
80
+ const source = parse(file);
81
+ return !/(?:^|\/)(?:adapters|test-support)\//u.test(file.path) && source !== undefined && typedNodes(source).length > 0;
82
+ });
83
+ if (sources.length === 0) {
84
+ return [];
85
+ }
86
+ const program = effectProgram({ ...inputs, sources });
87
+ const checker = program.getTypeChecker();
88
+ return sources.flatMap((file) => {
89
+ const source = program.getSourceFile(join(inputs.root, file.path));
90
+ return source === undefined
91
+ ? []
92
+ : typedNodes(source).flatMap((node) => {
93
+ const message = typedCast(node, checker);
94
+ return message === undefined
95
+ ? []
96
+ : [{ file: file.path, line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1, message }];
97
+ });
98
+ });
99
+ }
100
+
45
101
  export const noDoubleCast = defineRule({
46
- check: ({ sources }) => sources.flatMap(doubleCasts),
102
+ check: (inputs) => [...inputs.sources.flatMap(doubleCasts), ...typedCasts(inputs)],
47
103
  description:
48
- "A cast through unknown, any or never silences the compiler the way a suppression does. Decode the value at its boundary, narrow it, or fix the type that disagrees.",
104
+ "Decode unknown values with Schema.decodeUnknownEffect and SQL rows with SqlSchema. Check declared overload returns and preserve Context service types and readonly native fields. Reports double casts everywhere and hidden casts outside adapters/ and test-support/.",
49
105
  id: "suppressions/no-double-cast",
50
106
  registrable: false,
51
107
  });
@@ -0,0 +1,140 @@
1
+ import ts from "typescript";
2
+
3
+ function propertyName(node: ts.Expression, checker: ts.TypeChecker): string | undefined {
4
+ if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) {
5
+ return node.text;
6
+ }
7
+ const type = checker.getTypeAtLocation(node);
8
+ return type.isStringLiteral() || type.isNumberLiteral() ? String(type.value) : undefined;
9
+ }
10
+
11
+ function readonlyProperty(checker: ts.TypeChecker, target: ts.Expression, key: string): boolean {
12
+ const type = checker.getTypeAtLocation(target);
13
+ if (type.isUnionOrIntersection()) {
14
+ return type.types.some((part) => readonlyIn(part, key));
15
+ }
16
+ return readonlyIn(type, key);
17
+ }
18
+
19
+ function readonlyIn(type: ts.Type, key: string): boolean {
20
+ const symbol = type.getProperty(key);
21
+ const mapped = type.getSymbol()?.getDeclarations()?.find(ts.isMappedTypeNode);
22
+ if (symbol !== undefined && mapped?.readonlyToken !== undefined) {
23
+ return mapped.readonlyToken.kind !== ts.SyntaxKind.MinusToken;
24
+ }
25
+ return (
26
+ symbol
27
+ ?.getDeclarations()
28
+ ?.some(
29
+ (declaration) =>
30
+ (ts.canHaveModifiers(declaration) && ts.getModifiers(declaration)?.some((modifier) => modifier.kind === ts.SyntaxKind.ReadonlyKeyword))
31
+ || (ts.isGetAccessorDeclaration(declaration) && !symbol.getDeclarations()?.some(ts.isSetAccessorDeclaration)),
32
+ ) === true
33
+ );
34
+ }
35
+
36
+ function scopeState(checker: ts.TypeChecker, target: ts.Expression, key: string): boolean {
37
+ if (key !== "state") {
38
+ return false;
39
+ }
40
+ return (
41
+ checker
42
+ .getTypeAtLocation(target)
43
+ .getProperty("state")
44
+ ?.getDeclarations()
45
+ ?.some((declaration) => /(?:^|\/)effect\/(?:src|dist(?:\/[^/]+)?)\/Scope\.(?:d\.)?ts$/u.test(declaration.getSourceFile().fileName)) === true
46
+ );
47
+ }
48
+
49
+ function overwritten(checker: ts.TypeChecker, target: ts.Expression, keys: readonly string[]): string | undefined {
50
+ const key = keys.find((name) => readonlyProperty(checker, target, name) || scopeState(checker, target, name));
51
+ return key === undefined
52
+ ? undefined
53
+ : `Writes ${key} on ${checker.typeToString(checker.getTypeAtLocation(target))}. Use the native constructor or copy API and preserve the declared readonly type; use Scope.close for Scope state.`;
54
+ }
55
+
56
+ function assignedKeys(checker: ts.TypeChecker, source: ts.Expression): readonly string[] {
57
+ return checker
58
+ .getTypeAtLocation(source)
59
+ .getProperties()
60
+ .map((property) => property.name);
61
+ }
62
+
63
+ function writeTarget(node: ts.Node): ts.Expression | undefined {
64
+ if (
65
+ ts.isBinaryExpression(node)
66
+ && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment
67
+ && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
68
+ ) {
69
+ return node.left;
70
+ }
71
+ if (
72
+ (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))
73
+ && (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)
74
+ ) {
75
+ return node.operand;
76
+ }
77
+ return ts.isDeleteExpression(node) ? node.expression : undefined;
78
+ }
79
+
80
+ export function writeCandidate(node: ts.Node): boolean {
81
+ const target = writeTarget(node);
82
+ return (
83
+ (target !== undefined
84
+ && (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target))
85
+ && !constructorInitialization(node, target.expression))
86
+ || (ts.isCallExpression(node)
87
+ && ts.isPropertyAccessExpression(node.expression)
88
+ && ts.isIdentifier(node.expression.expression)
89
+ && ((node.expression.expression.text === "Object" && ["assign", "defineProperty"].includes(node.expression.name.text))
90
+ || (node.expression.expression.text === "Reflect" && node.expression.name.text === "set")))
91
+ );
92
+ }
93
+
94
+ function constructorInitialization(node: ts.Node, target: ts.Expression | undefined): boolean {
95
+ if (target?.kind !== ts.SyntaxKind.ThisKeyword) {
96
+ return false;
97
+ }
98
+ for (let parent = node.parent; parent !== undefined; parent = parent.parent) {
99
+ if (ts.isConstructorDeclaration(parent)) {
100
+ return true;
101
+ }
102
+ if (ts.isFunctionLike(parent)) {
103
+ break;
104
+ }
105
+ }
106
+ return false;
107
+ }
108
+
109
+ function callWrite(node: ts.CallExpression, checker: ts.TypeChecker): string | undefined {
110
+ const target = node.arguments[0];
111
+ if (target === undefined || constructorInitialization(node, target)) {
112
+ return undefined;
113
+ }
114
+ const method = ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : undefined;
115
+ if (method === "assign") {
116
+ return overwritten(
117
+ checker,
118
+ target,
119
+ node.arguments.slice(1).flatMap((source) => assignedKeys(checker, source)),
120
+ );
121
+ }
122
+ const argument = node.arguments[1];
123
+ const key = argument === undefined ? undefined : propertyName(argument, checker);
124
+ return key === undefined ? undefined : overwritten(checker, target, [key]);
125
+ }
126
+
127
+ export function readonlyWrite(node: ts.Node, checker: ts.TypeChecker): string | undefined {
128
+ if (ts.isCallExpression(node)) {
129
+ return callWrite(node, checker);
130
+ }
131
+ const target = writeTarget(node);
132
+ if (target === undefined || !(ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target))) {
133
+ return undefined;
134
+ }
135
+ if (constructorInitialization(node, target.expression)) {
136
+ return undefined;
137
+ }
138
+ const key = ts.isPropertyAccessExpression(target) ? target.name.text : propertyName(target.argumentExpression, checker);
139
+ return key === undefined ? undefined : overwritten(checker, target.expression, [key]);
140
+ }
@@ -1,13 +1,14 @@
1
1
  import { posix } from "node:path";
2
- import { Effect, Schema } from "effect";
2
+ import { Schema } from "effect";
3
3
  import ignore from "ignore";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
4
5
  import { isTestCode, testName } from "#naming/testName.ts";
5
6
  import { defineRule, type Finding } from "#rule.ts";
6
7
 
7
8
  const MIRROR_FOLDERS: ReadonlySet<string> = new Set(["__tests__", "spec", "test", "tests"]);
8
9
 
9
10
  const TestsColocatedOptions = Schema.Struct({
10
- suites: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
11
+ suites: GlobDeclarations,
11
12
  });
12
13
 
13
14
  function findingOf(path: string, sourceFolders: ReadonlySet<string>): readonly Finding[] {
@@ -31,7 +32,7 @@ function findingOf(path: string, sourceFolders: ReadonlySet<string>): readonly F
31
32
 
32
33
  export const testsColocated = defineRule({
33
34
  check: ({ files, options }) => {
34
- const suites = ignore().add([...options.suites]);
35
+ const suites = ignore().add([...globPatterns(options.suites)]);
35
36
  const sourceFolders = new Set(files.filter((path) => !isTestCode(path)).map((path) => posix.dirname(path)));
36
37
  return files.filter((path) => !suites.ignores(path)).flatMap((path) => findingOf(path, sourceFolders));
37
38
  },
@@ -39,4 +40,5 @@ export const testsColocated = defineRule({
39
40
  "A test sits beside the code it covers, at its module root or directly beside its module folder. Outside declared suites, __tests__ is always a test folder; test, tests and spec are test folders only when their directly contained checked files are all tests or test support. Shared test support belongs in test-support/.",
40
41
  id: "tests/colocated",
41
42
  options: Schema.toStandardSchemaV1(TestsColocatedOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
43
+ validate: validateGlobs,
42
44
  });
@@ -1,6 +1,7 @@
1
1
  import { posix } from "node:path";
2
- import { Effect, Schema } from "effect";
2
+ import { Schema } from "effect";
3
3
  import ignore from "ignore";
4
+ import { GlobDeclarations, globPatterns, validateGlobs } from "#config/globs.ts";
4
5
  import { ENVIRONMENTS, type TestName, testName } from "#naming/testName.ts";
5
6
  import { CAMEL } from "#naming/words.ts";
6
7
  import { defineRule, type Finding, type SourceFile } from "#rule.ts";
@@ -16,7 +17,7 @@ const GRAMMAR =
16
17
  "A test file is <file>[.<modifier>].test.ts beside its file or <behaviour>[.<modifier>].spec.ts in the folder it covers, with at most one modifier of dom, slow, typecheck and unit.";
17
18
 
18
19
  const TestsFollowOptions = Schema.Struct({
19
- suites: Schema.Array(Schema.String).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
20
+ suites: GlobDeclarations,
20
21
  });
21
22
 
22
23
  function siblingsIn(files: readonly string[]): ReadonlySet<string> {
@@ -78,7 +79,7 @@ function findingsOf(source: SourceFile, siblings: ReadonlySet<string>): readonly
78
79
 
79
80
  export const testsFollow = defineRule({
80
81
  check: ({ files, options, sources }) => {
81
- const suites = ignore().add([...options.suites]);
82
+ const suites = ignore().add([...globPatterns(options.suites)]);
82
83
  const siblings = siblingsIn(files);
83
84
  return sources.filter((source) => !suites.ignores(source.path)).flatMap((source) => findingsOf(source, siblings));
84
85
  },
@@ -86,4 +87,5 @@ export const testsFollow = defineRule({
86
87
  "A .test file follows the file beside it, a .spec names a behaviour of its folder, the only suffix is one modifier of dom, slow, typecheck and unit, and a test that uses the DOM is a .dom test.",
87
88
  id: "tests/follow",
88
89
  options: Schema.toStandardSchemaV1(TestsFollowOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
90
+ validate: validateGlobs,
89
91
  });
@@ -7,9 +7,9 @@ const installed = Symbol.for("@shivaedev/quality/unitIoGuard");
7
7
  let loading = 0;
8
8
 
9
9
  function assertUnitIoAllowed(call: string, boundary: (...args: never[]) => unknown): void {
10
- const worker: { readonly filepath?: string } | undefined = Reflect.get(globalThis, "__vitest_worker__");
11
- const file = worker?.filepath;
12
- if (loading > 0 || file === undefined || !/\.unit\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(file)) {
10
+ const worker: unknown = Reflect.get(globalThis, "__vitest_worker__");
11
+ const file = typeof worker === "object" && worker !== null && "filepath" in worker ? worker.filepath : undefined;
12
+ if (loading > 0 || typeof file !== "string" || !/\.unit\.(?:test|spec)\.[cm]?[jt]sx?$/u.test(file)) {
13
13
  return;
14
14
  }
15
15
  const error = new Error(`Unit test ${file} cannot call ${call}; use a story through the package's kit for I/O.`);