@shivaedev/quality 0.44.1 → 0.45.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 (81) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +11 -6
  3. package/biome/preset.json +11 -2
  4. package/dist/adapters/knip/entryPointFindings.d.ts.map +1 -1
  5. package/dist/adapters/knip/entryPointFindings.js +11 -2
  6. package/dist/adapters/knip/entryPointFindings.js.map +1 -1
  7. package/dist/appTestConfig.d.ts +2 -1
  8. package/dist/appTestConfig.d.ts.map +1 -1
  9. package/dist/appTestConfig.js +2 -2
  10. package/dist/appTestConfig.js.map +1 -1
  11. package/dist/appViteConfig.d.ts +1 -1
  12. package/dist/appViteConfig.d.ts.map +1 -1
  13. package/dist/appViteConfig.js +2 -2
  14. package/dist/appViteConfig.js.map +1 -1
  15. package/dist/biome/exceptionConfig.d.ts.map +1 -1
  16. package/dist/biome/exceptionConfig.js +13 -4
  17. package/dist/biome/exceptionConfig.js.map +1 -1
  18. package/dist/biome/recommendedRules.js +1 -1
  19. package/dist/biome/recommendedRules.js.map +1 -1
  20. package/dist/biome/run.d.ts.map +1 -1
  21. package/dist/biome/run.js +7 -9
  22. package/dist/biome/run.js.map +1 -1
  23. package/dist/cli/args.d.ts +2 -1
  24. package/dist/cli/args.d.ts.map +1 -1
  25. package/dist/cli/args.js +4 -3
  26. package/dist/cli/args.js.map +1 -1
  27. package/dist/cli/ci.d.ts +1 -1
  28. package/dist/cli/ci.d.ts.map +1 -1
  29. package/dist/cli/ci.js +13 -2
  30. package/dist/cli/ci.js.map +1 -1
  31. package/dist/cli/messages.d.ts +1 -1
  32. package/dist/cli/messages.d.ts.map +1 -1
  33. package/dist/cli/messages.js +2 -1
  34. package/dist/cli/messages.js.map +1 -1
  35. package/dist/cli/program.js +1 -1
  36. package/dist/cli/program.js.map +1 -1
  37. package/dist/rules/builtIn.d.ts +1 -1
  38. package/dist/rules/builtIn.d.ts.map +1 -1
  39. package/dist/rules/builtIn.js +6 -0
  40. package/dist/rules/builtIn.js.map +1 -1
  41. package/dist/rules/stories/authSql.d.ts.map +1 -1
  42. package/dist/rules/stories/authSql.js +22 -3
  43. package/dist/rules/stories/authSql.js.map +1 -1
  44. package/dist/rules/stories/domainOutcomes.d.ts +2 -0
  45. package/dist/rules/stories/domainOutcomes.d.ts.map +1 -0
  46. package/dist/rules/stories/domainOutcomes.js +34 -0
  47. package/dist/rules/stories/domainOutcomes.js.map +1 -0
  48. package/dist/rules/stories/groupedOutcomes.d.ts +2 -0
  49. package/dist/rules/stories/groupedOutcomes.d.ts.map +1 -0
  50. package/dist/rules/stories/groupedOutcomes.js +55 -0
  51. package/dist/rules/stories/groupedOutcomes.js.map +1 -0
  52. package/dist/rules/stories/importBindings.d.ts +8 -0
  53. package/dist/rules/stories/importBindings.d.ts.map +1 -0
  54. package/dist/rules/stories/importBindings.js +29 -0
  55. package/dist/rules/stories/importBindings.js.map +1 -0
  56. package/dist/rules/stories/specSources.d.ts +4 -0
  57. package/dist/rules/stories/specSources.d.ts.map +1 -0
  58. package/dist/rules/stories/specSources.js +17 -0
  59. package/dist/rules/stories/specSources.js.map +1 -0
  60. package/dist/rules/stories/waitOnEvents.d.ts +2 -0
  61. package/dist/rules/stories/waitOnEvents.d.ts.map +1 -0
  62. package/dist/rules/stories/waitOnEvents.js +52 -0
  63. package/dist/rules/stories/waitOnEvents.js.map +1 -0
  64. package/package.json +10 -8
  65. package/src/adapters/knip/entryPointFindings.ts +15 -2
  66. package/src/appTestConfig.ts +3 -3
  67. package/src/appViteConfig.ts +2 -2
  68. package/src/biome/exceptionConfig.ts +14 -6
  69. package/src/biome/recommendedRules.ts +1 -1
  70. package/src/biome/run.ts +7 -10
  71. package/src/cli/args.ts +5 -4
  72. package/src/cli/ci.ts +14 -2
  73. package/src/cli/messages.ts +2 -1
  74. package/src/cli/program.ts +1 -1
  75. package/src/rules/builtIn.ts +6 -0
  76. package/src/rules/stories/authSql.ts +25 -3
  77. package/src/rules/stories/domainOutcomes.ts +45 -0
  78. package/src/rules/stories/groupedOutcomes.ts +67 -0
  79. package/src/rules/stories/importBindings.ts +37 -0
  80. package/src/rules/stories/specSources.ts +20 -0
  81. package/src/rules/stories/waitOnEvents.ts +62 -0
@@ -1,9 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { access, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { rm, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- import { Schema } from "effect";
4
+ import { NodeFileSystem } from "@effect/platform-node";
5
+ import { Effect, Schema } from "effect";
5
6
  import ts from "typescript";
6
7
  import type { ExceptionDeclaration } from "#exceptions/declaration.ts";
8
+ import { readOptionalText } from "#inventory/filesystem.ts";
7
9
 
8
10
  function nativeOverride(files: readonly string[], rule: string): unknown {
9
11
  const [, tool, group = "", name = ""] = rule.split("/");
@@ -36,11 +38,17 @@ export async function withExceptionConfig<TValue>(
36
38
  }
37
39
  const name = `.quality-biome-${randomUUID()}.json`;
38
40
  const path = join(root, name);
39
- const config = await access(join(root, "biome.json")).then(
40
- () => "biome.json",
41
- () => "biome.jsonc",
41
+ const { config, text } = await Effect.runPromise(
42
+ Effect.gen(function* () {
43
+ for (const candidate of ["biome.json", "biome.jsonc"]) {
44
+ const content = yield* readOptionalText(join(root, candidate));
45
+ if (content !== undefined) {
46
+ return { config: candidate, text: content };
47
+ }
48
+ }
49
+ return { config: "biome.json", text: "{}" };
50
+ }).pipe(Effect.provide(NodeFileSystem.layer)),
42
51
  );
43
- const text = await readFile(join(root, config), "utf8");
44
52
  const parsed = ts.parseConfigFileTextToJson(config, text);
45
53
  if (parsed.error !== undefined) {
46
54
  throw new Error(`Cannot load ${config}: ${ts.flattenDiagnosticMessageText(parsed.error.messageText, " ")}`);
@@ -11,7 +11,7 @@ export async function recommendedRules(): Promise<readonly string[]> {
11
11
  const directory = await mkdtemp(join(tmpdir(), "quality-biome-recommended-"));
12
12
  try {
13
13
  await writeFile(join(directory, "biome.json"), RECOMMENDED_ONLY);
14
- const rage = await runBiome(directory, ["rage", "--linter", `--config-path=${directory}`]);
14
+ const rage = await runBiome(directory, ["rage", "--linter"]);
15
15
  const rules = [...rage.stdout.matchAll(ENABLED_RULE)].flatMap((match) => match.groups?.rule ?? []);
16
16
  if (rules.length === 0) {
17
17
  throw new Error(`biome rage --linter listed no enabled rules under the recommended preset:\n${[rage.stdout, rage.stderr].join("\n").trim()}`);
package/src/biome/run.ts CHANGED
@@ -17,16 +17,13 @@ const BIN = createRequire(import.meta.url).resolve("@biomejs/biome/bin/biome");
17
17
 
18
18
  export async function runBiome(root: string, args: readonly string[], exceptions: readonly ExceptionDeclaration[] = []): Promise<BiomeRun> {
19
19
  const folders = await Effect.runPromise(shadcnFolders(root).pipe(Effect.provide(NodeFileSystem.layer)));
20
- const toolOwned: readonly ExceptionDeclaration[] =
21
- folders.length === 0
22
- ? []
23
- : [
24
- {
25
- files: ["**", ...folders.map((folder) => `!${folder}`)],
26
- reason: "components.json assigns these folders to the shadcn CLI.",
27
- rules: ["biome/files/includes"],
28
- },
29
- ];
20
+ const toolOwned: readonly ExceptionDeclaration[] = [
21
+ {
22
+ files: ["**", "!**/pnpm-lock.yaml", ...folders.map((folder) => `!${folder}`)],
23
+ reason: "pnpm writes its lockfiles; components.json assigns UI folders to the shadcn CLI.",
24
+ rules: ["biome/files/includes"],
25
+ },
26
+ ];
30
27
  return withExceptionConfig(
31
28
  root,
32
29
  [...exceptions, ...toolOwned],
package/src/cli/args.ts CHANGED
@@ -3,7 +3,7 @@ import { Result } from "effect";
3
3
  import { USAGE as COMMAND_USAGE, SUBCOMMANDS } from "./messages.ts";
4
4
 
5
5
  export type Command =
6
- | { readonly _tag: "Ci" }
6
+ | { readonly _tag: "Ci"; readonly coverage: boolean }
7
7
  | { readonly _tag: "Setup"; readonly config: string | undefined }
8
8
  | { readonly _tag: "Lint"; readonly config: string | undefined }
9
9
  | { readonly _tag: "ExceptionsMigrate"; readonly config: string | undefined; readonly from: string | undefined }
@@ -27,6 +27,7 @@ export const USAGE = COMMAND_USAGE;
27
27
  const OPTIONS = {
28
28
  against: { type: "string" },
29
29
  config: { type: "string" },
30
+ coverage: { type: "boolean" },
30
31
  force: { type: "boolean" },
31
32
  from: { type: "string" },
32
33
  help: { short: "h", type: "boolean" },
@@ -46,7 +47,7 @@ type Values = ReturnType<typeof parseArgs<{ options: typeof OPTIONS; allowPositi
46
47
 
47
48
  type Option = Exclude<keyof Values, "config" | "help">;
48
49
 
49
- const COMMAND_OPTIONS: readonly Option[] = ["against", "force", "from", "rule", "staged"];
50
+ const COMMAND_OPTIONS: readonly Option[] = ["against", "coverage", "force", "from", "rule", "staged"];
50
51
 
51
52
  const ACCEPTS: Readonly<Record<string, readonly Option[]>> = {
52
53
  "baseline install-driver": [],
@@ -54,7 +55,7 @@ const ACCEPTS: Readonly<Record<string, readonly Option[]>> = {
54
55
  "baseline prune": ["against"],
55
56
  "baseline tighten": ["staged"],
56
57
  "baseline write": ["rule"],
57
- ci: [],
58
+ ci: ["coverage"],
58
59
  "exceptions migrate": ["from"],
59
60
  fix: [],
60
61
  "hooks install": ["force"],
@@ -79,7 +80,7 @@ function commandFor(name: string, values: Values): Parsed {
79
80
  const config = values.config;
80
81
  switch (name) {
81
82
  case "ci":
82
- return parsed({ _tag: "Ci" });
83
+ return parsed({ _tag: "Ci", coverage: values.coverage === true });
83
84
  case "setup":
84
85
  return parsed({ _tag: "Setup", config });
85
86
  case "lint":
package/src/cli/ci.ts CHANGED
@@ -2,9 +2,21 @@ import { Console, Effect } from "effect";
2
2
  import { ChildProcess, ChildProcessSpawner } from "effect/process";
3
3
  import { GateFailed } from "#failure.ts";
4
4
 
5
- export const ci = Effect.fn("Cli.ci")(function* (cwd: string) {
5
+ const coverageArgs = [
6
+ "--coverage",
7
+ "--coverage.provider=v8",
8
+ "--coverage.reporter=lcov",
9
+ "--coverage.reportOnFailure",
10
+ "--coverage.reportsDirectory=coverage",
11
+ "--reporter=default",
12
+ "--reporter=junit",
13
+ "--outputFile.junit=coverage/junit.xml",
14
+ ];
15
+
16
+ export const ci = Effect.fn("Cli.ci")(function* (cwd: string, coverage = false) {
6
17
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
7
- for (const args of [["peers", "check"], ...["lint", "typecheck", "build", "test"].map((script) => ["run", script])]) {
18
+ const scripts = ["lint", "typecheck", "build", "test"].map((script) => ["run", script, ...(script === "test" && coverage ? coverageArgs : [])]);
19
+ for (const args of [["peers", "check"], ...scripts]) {
8
20
  yield* Console.log(`quality: running \`pnpm ${args.join(" ")}\``);
9
21
  const code = yield* spawner.exitCode(ChildProcess.make("pnpm", args, { cwd, stderr: "inherit", stdout: "inherit" }));
10
22
  if (code !== 0) {
@@ -1,6 +1,6 @@
1
1
  export const USAGE = `Usage:
2
2
  quality lint [--config <file>]
3
- quality ci
3
+ quality ci [--coverage]
4
4
  quality setup [--config <file>]
5
5
  quality fix [--config <file>]
6
6
  quality exceptions migrate [--config <file>] [--from <registry>]
@@ -35,6 +35,7 @@ hooks pre-commit What the hook runs: lint, then package.json scripts typecheck
35
35
 
36
36
  --config <file> Config file; its directory is the repository root. Without this option, uses ./quality.config.ts when present, otherwise defaults.
37
37
  --against <ref> The branch the work merges into, whose merge base prune follows moves from. Defaults to origin/HEAD, then origin/main, then origin/master.
38
+ --coverage Collect V8 coverage and JUnit from ci's single test run into coverage/, including failed tests.
38
39
  Exit codes: 0 passed, 1 failed the gate, 2 could not run.`;
39
40
 
40
41
  export const SUBCOMMANDS: Readonly<Record<string, string>> = {
@@ -32,7 +32,7 @@ export const program = Effect.fn("Cli.program")(function* (args: readonly string
32
32
  case "Help":
33
33
  return yield* Console.log(USAGE);
34
34
  case "Ci":
35
- return yield* ci(cwd);
35
+ return yield* ci(cwd, command.coverage);
36
36
  case "Setup":
37
37
  return yield* setupHook({ config: command.config, cwd, launch });
38
38
  case "Lint":
@@ -22,7 +22,9 @@ import { importsResolvable } from "#rules/imports/resolvable.ts";
22
22
  import { importsRuntime } from "#rules/imports/runtime.ts";
23
23
  import { jsxConditionals } from "#rules/react/jsxConditionals.ts";
24
24
  import { authSql } from "#rules/stories/authSql.ts";
25
+ import { domainOutcomes } from "#rules/stories/domainOutcomes.ts";
25
26
  import { storyEngine } from "#rules/stories/engine.ts";
27
+ import { groupedOutcomes } from "#rules/stories/groupedOutcomes.ts";
26
28
  import { httpStatus } from "#rules/stories/httpStatus.ts";
27
29
  import { namedValues } from "#rules/stories/namedValues.ts";
28
30
  import { noExpect } from "#rules/stories/noExpect.ts";
@@ -31,6 +33,7 @@ import { queueSql } from "#rules/stories/queueSql.ts";
31
33
  import { storySetup } from "#rules/stories/setup.ts";
32
34
  import { specHelpers } from "#rules/stories/specHelpers.ts";
33
35
  import { storySpecs } from "#rules/stories/specs.ts";
36
+ import { waitOnEvents } from "#rules/stories/waitOnEvents.ts";
34
37
  import { biomeOverrides } from "#rules/suppressions/biomeOverrides.ts";
35
38
  import { biomeRecommended } from "#rules/suppressions/biomeRecommended.ts";
36
39
  import { noDoubleCast } from "#rules/suppressions/noDoubleCast.ts";
@@ -98,4 +101,7 @@ export const builtInRules = [
98
101
  httpStatus,
99
102
  namedValues,
100
103
  noLimitImports,
104
+ domainOutcomes,
105
+ groupedOutcomes,
106
+ waitOnEvents,
101
107
  ] as const;
@@ -58,6 +58,24 @@ function tableBoundary(tokens: readonly string[], index: number, statementStart:
58
58
  };
59
59
  }
60
60
 
61
+ function userForeignKeyAt(tokens: readonly string[], index: number, statementStart: number): boolean {
62
+ const statement = tokens.slice(statementStart, index).map((token) => token.toLowerCase());
63
+ if (tokens[index]?.toLowerCase() !== "references" || !["create", "alter"].includes(statement[0] ?? "") || !statement.includes("table")) {
64
+ return false;
65
+ }
66
+ let table = index + 1;
67
+ while (tokens[table + 1] === ".") {
68
+ table += 2;
69
+ }
70
+ if (tokens[table + 1] !== "(" || !["id", '"id"'].includes(tokens[table + 2]?.toLowerCase() ?? "") || tokens[table + 3] !== ")") {
71
+ return false;
72
+ }
73
+ const remainder = tokens.slice(table + 4);
74
+ const end = remainder.findIndex((token) => [",", ";", ")"].includes(token));
75
+ const clause = remainder.slice(0, end === -1 ? undefined : end).join(" ");
76
+ return /\bon delete (?:cascade|set null)\b/iu.test(clause);
77
+ }
78
+
61
79
  interface SqlContext {
62
80
  depth: number;
63
81
  readonly expressionFromDepths: Set<number>;
@@ -97,7 +115,11 @@ function authTableIn(text: string): boolean {
97
115
  if (boundary.starts) {
98
116
  context.tablesAtDepth.add(context.depth);
99
117
  }
100
- return (boundary.starts || (token === "," && context.tablesAtDepth.has(context.depth))) && AUTH_TABLES.has(tableAt(tokens, index + 1));
118
+ return (
119
+ (boundary.starts || (token === "," && context.tablesAtDepth.has(context.depth)))
120
+ && AUTH_TABLES.has(tableAt(tokens, index + 1))
121
+ && !(tableAt(tokens, index + 1) === "user" && userForeignKeyAt(tokens, index, context.statementStart))
122
+ );
101
123
  });
102
124
  }
103
125
 
@@ -109,9 +131,9 @@ export const authSql = defineRule({
109
131
  file: query.file,
110
132
  line: query.line,
111
133
  message:
112
- "SQL accesses a Better Auth table (user, account, session or verification). Use platform's auth API; only platform's auth implementation and its migrations, named in the repository's auth-sql owners, own those tables.",
134
+ "SQL accesses a Better Auth table (user, account, session or verification). Use platform's auth API (@shivaedev/identity) for account data; app migrations may only reference user(id) with ON DELETE CASCADE or ON DELETE SET NULL. Only the configured auth-sql owners manage auth storage.",
113
135
  })),
114
- description: "Apps use platform's auth API instead of querying or modifying Better Auth's tables.",
136
+ description: "Apps reference user IDs by foreign key and use identity for account data.",
115
137
  id: "boundaries/auth-sql",
116
138
  options: Schema.toStandardSchemaV1(AuthSqlOptions, { parseOptions: { errors: "all", onExcessProperty: "error" } }),
117
139
  });
@@ -0,0 +1,45 @@
1
+ import { Effect } from "effect";
2
+ import ts from "typescript";
3
+ import { defineRule } from "#rule.ts";
4
+ import { bindsModule, importBindings } from "./importBindings.ts";
5
+ import { storySpecSources } from "./specSources.ts";
6
+ import { memberName, nodesWhere, syntaxFindings, unwrapped } from "./syntax.ts";
7
+
8
+ const MESSAGE =
9
+ 'Uses an Exit, Cause or Result value or reads a _tag in a spec. Have the kit\'s verb or readout return the outcome in the domain\'s words, such as "unauthorized" or "rolled back", and expect that; build failing inputs in a kit trait.';
10
+
11
+ const SHAPES = ["Exit", "Cause", "Result"];
12
+ const OUTCOME_TAGS = new Set(["Failure", "Success"]);
13
+
14
+ function shapeModule(source: ts.SourceFile): (node: ts.Expression) => boolean {
15
+ const bindings = importBindings(source);
16
+ return (node) => {
17
+ const value = unwrapped(node);
18
+ return ts.isIdentifier(value) && SHAPES.some((shape) => bindsModule(bindings.get(value.text), shape, ["effect"]));
19
+ };
20
+ }
21
+
22
+ function outcomeTag(node: ts.PropertyAssignment): boolean {
23
+ const name = ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : undefined;
24
+ const value = unwrapped(node.initializer);
25
+ return name === "_tag" && ts.isStringLiteralLike(value) && OUTCOME_TAGS.has(value.text);
26
+ }
27
+
28
+ function shapeReads(source: ts.SourceFile): readonly ts.Node[] {
29
+ const fromShapeModule = shapeModule(source);
30
+ return nodesWhere(
31
+ source,
32
+ (node) =>
33
+ ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
34
+ && (memberName(node) === "_tag" || fromShapeModule(node.expression)))
35
+ || (ts.isBindingElement(node) && (node.propertyName ?? node.name).getText(source) === "_tag")
36
+ || (ts.isPropertyAssignment(node) && outcomeTag(node)),
37
+ );
38
+ }
39
+
40
+ export const domainOutcomes = defineRule({
41
+ check: (inputs) =>
42
+ Effect.runPromise(Effect.map(storySpecSources(inputs), (specs) => specs.flatMap((file) => syntaxFindings(file, shapeReads, MESSAGE)))),
43
+ description: "Story verbs and readouts return outcomes in the domain's words, not Exit, Cause or Result shapes or _tag reads.",
44
+ id: "tests/domain-outcomes",
45
+ });
@@ -0,0 +1,67 @@
1
+ import { Effect } from "effect";
2
+ import ts from "typescript";
3
+ import { defineRule } from "#rule.ts";
4
+ import { importBindings } from "./importBindings.ts";
5
+ import { storySpecSources } from "./specSources.ts";
6
+ import { memberName, syntaxFindings, unwrapped } from "./syntax.ts";
7
+
8
+ const MESSAGE =
9
+ 'Checks several outcomes with consecutive expect(yield* …) lines. Let the story\'s words lead: yield* outcomes({ "label": [readout, expected], … }) from @shivaedev/test-story/server/outcomes.ts, one row per outcome. Keep a plain expect for a single outcome.';
10
+
11
+ const EXPECT_MODULES = ["vitest", "@effect/vitest"];
12
+
13
+ function yields(node: ts.Node): boolean {
14
+ return (
15
+ (ts.isYieldExpression(node) && node.asteriskToken !== undefined)
16
+ || (!ts.isFunctionLike(node) && ts.forEachChild(node, (child) => yields(child) || undefined) === true)
17
+ );
18
+ }
19
+
20
+ function expectNames(source: ts.SourceFile): ReadonlySet<string> {
21
+ const imported = [...importBindings(source)].filter(([, binding]) => binding.imported === "expect" && EXPECT_MODULES.includes(binding.module));
22
+ return new Set(["expect", ...imported.map(([local]) => local)]);
23
+ }
24
+
25
+ function expectCall(node: ts.Expression, names: ReadonlySet<string>): ts.CallExpression | undefined {
26
+ const value = unwrapped(node);
27
+ if (ts.isCallExpression(value)) {
28
+ const callee = unwrapped(value.expression);
29
+ const receiver = ts.isPropertyAccessExpression(callee) && memberName(callee) === "soft" ? unwrapped(callee.expression) : callee;
30
+ return ts.isIdentifier(receiver) && names.has(receiver.text) ? value : expectCall(value.expression, names);
31
+ }
32
+ return ts.isPropertyAccessExpression(value) || ts.isElementAccessExpression(value) ? expectCall(value.expression, names) : undefined;
33
+ }
34
+
35
+ function statementsOf(node: ts.Node): readonly ts.Statement[] {
36
+ return ts.isBlock(node) || ts.isSourceFile(node) || ts.isCaseClause(node) || ts.isDefaultClause(node) || ts.isModuleBlock(node)
37
+ ? node.statements
38
+ : [];
39
+ }
40
+
41
+ function consecutiveChecks(source: ts.SourceFile): readonly ts.Node[] {
42
+ const names = expectNames(source);
43
+ function checksYield(statement: ts.Statement | undefined): boolean {
44
+ const subject =
45
+ statement !== undefined && ts.isExpressionStatement(statement) ? expectCall(statement.expression, names)?.arguments[0] : undefined;
46
+ return subject !== undefined && yields(subject);
47
+ }
48
+ const runs: ts.Node[] = [];
49
+ function visit(node: ts.Node): void {
50
+ const statements = statementsOf(node);
51
+ for (const [index, statement] of statements.entries()) {
52
+ if (checksYield(statement) && checksYield(statements[index + 1]) && !checksYield(statements[index - 1])) {
53
+ runs.push(statement);
54
+ }
55
+ }
56
+ ts.forEachChild(node, visit);
57
+ }
58
+ visit(source);
59
+ return runs;
60
+ }
61
+
62
+ export const groupedOutcomes = defineRule({
63
+ check: (inputs) =>
64
+ Effect.runPromise(Effect.map(storySpecSources(inputs), (specs) => specs.flatMap((file) => syntaxFindings(file, consecutiveChecks, MESSAGE)))),
65
+ description: "Several outcomes after one action are rows of one outcomes call, so the story's words lead each line.",
66
+ id: "tests/grouped-outcomes",
67
+ });
@@ -0,0 +1,37 @@
1
+ import ts from "typescript";
2
+
3
+ export interface ImportBinding {
4
+ readonly imported: string;
5
+ readonly module: string;
6
+ }
7
+
8
+ const NAMESPACE = "*";
9
+
10
+ export function importBindings(source: ts.SourceFile): ReadonlyMap<string, ImportBinding> {
11
+ const bindings = new Map<string, ImportBinding>();
12
+ for (const statement of source.statements) {
13
+ if (!(ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier))) {
14
+ continue;
15
+ }
16
+ const module = statement.moduleSpecifier.text;
17
+ const clause = statement.importClause;
18
+ const named = clause?.namedBindings;
19
+ if (named !== undefined && ts.isNamespaceImport(named)) {
20
+ bindings.set(named.name.text, { imported: NAMESPACE, module });
21
+ } else if (named !== undefined) {
22
+ for (const element of named.elements) {
23
+ bindings.set(element.name.text, { imported: (element.propertyName ?? element.name).text, module });
24
+ }
25
+ }
26
+ }
27
+ return bindings;
28
+ }
29
+
30
+ export function bindsModule(binding: ImportBinding | undefined, name: string, modules: readonly string[]): boolean {
31
+ return (
32
+ binding !== undefined
33
+ && (binding.imported === NAMESPACE
34
+ ? modules.some((module) => binding.module === `${module}/${name}`)
35
+ : binding.imported === name && modules.includes(binding.module))
36
+ );
37
+ }
@@ -0,0 +1,20 @@
1
+ import { Effect } from "effect";
2
+ import { packageOf, workspacePackages } from "#imports/workspace.ts";
3
+ import { testName } from "#naming/testName.ts";
4
+ import type { RuleInputs } from "#rule.ts";
5
+ import { storyPrerequisites } from "./prerequisites.ts";
6
+ import { isSpec } from "./syntax.ts";
7
+
8
+ export const storySpecSources = Effect.fn("Stories.storySpecSources")(function* (inputs: RuleInputs) {
9
+ const packages = yield* Effect.promise(() => workspacePackages(inputs));
10
+ const exempt = yield* Effect.promise(() => storyPrerequisites(inputs, packages));
11
+ return inputs.sources.filter((file) => {
12
+ const modifiers = testName(file.path)?.modifiers ?? [];
13
+ return (
14
+ isSpec(file.path)
15
+ && !modifiers.includes("typecheck")
16
+ && !modifiers.includes("unit")
17
+ && !exempt.has(packageOf(packages, file.path)?.directory ?? "")
18
+ );
19
+ });
20
+ });
@@ -0,0 +1,62 @@
1
+ import { Effect } from "effect";
2
+ import ts from "typescript";
3
+ import { defineRule } from "#rule.ts";
4
+ import { bindsModule, type ImportBinding, importBindings } from "./importBindings.ts";
5
+ import { storySpecSources } from "./specSources.ts";
6
+ import { memberName, syntaxFindings, unwrapped } from "./syntax.ts";
7
+
8
+ const MESSAGE =
9
+ "Waits on time in a spec: a sleep, a timer, polling with eventually or waitFor, fake timers or a TestClock adjustment. Settle on the engine's own signal through a kit verb, such as a Deferred the engine completes, story.runUntil or screenDriver's settle(); when time passing is the behaviour, name it in a kit verb that advances the clock.";
10
+
11
+ const TIMERS = new Set(["setInterval", "setTimeout"]);
12
+ const VI_TIMING = /^(?:useFakeTimers|advanceTimers\w*|runAllTimers\w*|runOnlyPendingTimers\w*|runAllTicks|setSystemTime|waitFor|waitUntil)$/u;
13
+ const CLOCK_CHANGES = new Set(["adjust", "setTime"]);
14
+
15
+ function receiverOf(callee: ts.Expression): ts.Identifier | undefined {
16
+ const receiver = ts.isPropertyAccessExpression(callee) ? unwrapped(callee.expression) : undefined;
17
+ return receiver !== undefined && ts.isIdentifier(receiver) ? receiver : undefined;
18
+ }
19
+
20
+ function vitestTiming(receiver: ts.Identifier, bindings: ReadonlyMap<string, ImportBinding>): boolean {
21
+ const binding = bindings.get(receiver.text);
22
+ return binding === undefined ? receiver.text === "vi" : bindsModule(binding, "vi", ["vitest", "@effect/vitest"]);
23
+ }
24
+
25
+ function timedWait(call: ts.CallExpression, bindings: ReadonlyMap<string, ImportBinding>): boolean {
26
+ const callee = unwrapped(call.expression);
27
+ if (ts.isIdentifier(callee)) {
28
+ return TIMERS.has(callee.text) || bindings.get(callee.text)?.imported === "eventually";
29
+ }
30
+ const member = memberName(callee) ?? "";
31
+ const receiver = receiverOf(callee);
32
+ if (receiver === undefined) {
33
+ return false;
34
+ }
35
+ const binding = bindings.get(receiver.text);
36
+ return (
37
+ (member === "sleep" && bindsModule(binding, "Effect", ["effect"]))
38
+ || (VI_TIMING.test(member) && vitestTiming(receiver, bindings))
39
+ || (CLOCK_CHANGES.has(member) && bindsModule(binding, "TestClock", ["effect/testing"]))
40
+ || (TIMERS.has(member) && receiver.text === "globalThis")
41
+ );
42
+ }
43
+
44
+ function timedWaits(source: ts.SourceFile): readonly ts.Node[] {
45
+ const bindings = importBindings(source);
46
+ const found: ts.Node[] = [];
47
+ function visit(node: ts.Node): void {
48
+ if (ts.isCallExpression(node) && timedWait(node, bindings)) {
49
+ found.push(node);
50
+ }
51
+ ts.forEachChild(node, visit);
52
+ }
53
+ visit(source);
54
+ return found;
55
+ }
56
+
57
+ export const waitOnEvents = defineRule({
58
+ check: (inputs) =>
59
+ Effect.runPromise(Effect.map(storySpecSources(inputs), (specs) => specs.flatMap((file) => syntaxFindings(file, timedWaits, MESSAGE)))),
60
+ description: "Stories settle on the engine's own signals, never on sleeps, polling, fake timers or clock adjustments in the spec.",
61
+ id: "tests/wait-on-events",
62
+ });