@shivaedev/quality 0.57.1 → 0.58.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 (127) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +11 -4
  3. package/dist/adapters/ImportAnalysisFailure.d.ts +10 -0
  4. package/dist/adapters/ImportAnalysisFailure.d.ts.map +1 -0
  5. package/dist/adapters/ImportAnalysisFailure.js +4 -0
  6. package/dist/adapters/ImportAnalysisFailure.js.map +1 -0
  7. package/dist/adapters/ImportCompiler.d.ts +2 -13
  8. package/dist/adapters/ImportCompiler.d.ts.map +1 -1
  9. package/dist/adapters/ImportCompiler.js +7 -13
  10. package/dist/adapters/ImportCompiler.js.map +1 -1
  11. package/dist/adapters/imports/analysisFailure.d.ts +3 -0
  12. package/dist/adapters/imports/analysisFailure.d.ts.map +1 -0
  13. package/dist/adapters/imports/analysisFailure.js +5 -0
  14. package/dist/adapters/imports/analysisFailure.js.map +1 -0
  15. package/dist/adapters/imports/analyzeDepartures.d.ts +5 -0
  16. package/dist/adapters/imports/analyzeDepartures.d.ts.map +1 -0
  17. package/dist/adapters/imports/analyzeDepartures.js +5 -0
  18. package/dist/adapters/imports/analyzeDepartures.js.map +1 -0
  19. package/dist/adapters/imports/analyzeGraph.d.ts +4 -0
  20. package/dist/adapters/imports/analyzeGraph.d.ts.map +1 -0
  21. package/dist/adapters/imports/analyzeGraph.js +6 -0
  22. package/dist/adapters/imports/analyzeGraph.js.map +1 -0
  23. package/dist/adapters/imports/checkBrowser.d.ts +4 -0
  24. package/dist/adapters/imports/checkBrowser.d.ts.map +1 -0
  25. package/dist/adapters/imports/checkBrowser.js +4 -0
  26. package/dist/adapters/imports/checkBrowser.js.map +1 -0
  27. package/dist/adapters/indirectServiceReferences.d.ts +3 -0
  28. package/dist/adapters/indirectServiceReferences.d.ts.map +1 -0
  29. package/dist/adapters/indirectServiceReferences.js +19 -0
  30. package/dist/adapters/indirectServiceReferences.js.map +1 -0
  31. package/dist/adapters/knip/entryPointFindings.d.ts +1 -1
  32. package/dist/adapters/knip/entryPointFindings.d.ts.map +1 -1
  33. package/dist/adapters/nativeTransactionFindings.d.ts +4 -0
  34. package/dist/adapters/nativeTransactionFindings.d.ts.map +1 -0
  35. package/dist/adapters/nativeTransactionFindings.js +98 -0
  36. package/dist/adapters/nativeTransactionFindings.js.map +1 -0
  37. package/dist/adapters/outsideImportFindings.d.ts +1 -1
  38. package/dist/adapters/outsideImportFindings.d.ts.map +1 -1
  39. package/dist/adapters/queueReadoutFindings.d.ts +1 -1
  40. package/dist/adapters/queueReadoutFindings.d.ts.map +1 -1
  41. package/dist/adapters/serviceAssemblyImports.d.ts +10 -0
  42. package/dist/adapters/serviceAssemblyImports.d.ts.map +1 -0
  43. package/dist/adapters/serviceAssemblyImports.js +71 -0
  44. package/dist/adapters/serviceAssemblyImports.js.map +1 -0
  45. package/dist/adapters/serviceAssemblySyntax.d.ts +10 -0
  46. package/dist/adapters/serviceAssemblySyntax.d.ts.map +1 -0
  47. package/dist/adapters/serviceAssemblySyntax.js +105 -0
  48. package/dist/adapters/serviceAssemblySyntax.js.map +1 -0
  49. package/dist/adapters/serviceDefinitionProblems.d.ts +7 -0
  50. package/dist/adapters/serviceDefinitionProblems.d.ts.map +1 -0
  51. package/dist/adapters/serviceDefinitionProblems.js +43 -0
  52. package/dist/adapters/serviceDefinitionProblems.js.map +1 -0
  53. package/dist/adapters/serviceIdFindings.d.ts.map +1 -1
  54. package/dist/adapters/serviceIdFindings.js +12 -7
  55. package/dist/adapters/serviceIdFindings.js.map +1 -1
  56. package/dist/adapters/transactionChanges.d.ts +3 -0
  57. package/dist/adapters/transactionChanges.d.ts.map +1 -0
  58. package/dist/adapters/transactionChanges.js +81 -0
  59. package/dist/adapters/transactionChanges.js.map +1 -0
  60. package/dist/imports/departures.d.ts +1 -1
  61. package/dist/imports/departures.d.ts.map +1 -1
  62. package/dist/imports/fences/check.d.ts +1 -1
  63. package/dist/imports/fences/check.d.ts.map +1 -1
  64. package/dist/imports/graph.d.ts +1 -1
  65. package/dist/imports/graph.d.ts.map +1 -1
  66. package/dist/rules/builtIn.d.ts +1 -1
  67. package/dist/rules/builtIn.d.ts.map +1 -1
  68. package/dist/rules/builtIn.js +4 -0
  69. package/dist/rules/builtIn.js.map +1 -1
  70. package/dist/rules/effect/serviceCatalog.d.ts +1 -1
  71. package/dist/rules/effect/serviceCatalog.d.ts.map +1 -1
  72. package/dist/rules/effect/serviceCatalog.js +4 -2
  73. package/dist/rules/effect/serviceCatalog.js.map +1 -1
  74. package/dist/rules/effect/serviceDefinitionAssembly.d.ts +2 -0
  75. package/dist/rules/effect/serviceDefinitionAssembly.d.ts.map +1 -0
  76. package/dist/rules/effect/serviceDefinitionAssembly.js +43 -0
  77. package/dist/rules/effect/serviceDefinitionAssembly.js.map +1 -0
  78. package/dist/rules/effect/serviceIds.js +1 -1
  79. package/dist/rules/effect/serviceIds.js.map +1 -1
  80. package/dist/rules/effect/serviceParameters.d.ts.map +1 -1
  81. package/dist/rules/effect/serviceParameters.js +12 -6
  82. package/dist/rules/effect/serviceParameters.js.map +1 -1
  83. package/dist/rules/effect/sqlTransact.d.ts +2 -0
  84. package/dist/rules/effect/sqlTransact.d.ts.map +1 -0
  85. package/dist/rules/effect/sqlTransact.js +9 -0
  86. package/dist/rules/effect/sqlTransact.js.map +1 -0
  87. package/dist/rules/stories/sources.d.ts +1 -1
  88. package/dist/rules/stories/sources.d.ts.map +1 -1
  89. package/dist/testing/adapters/cli.d.ts +2 -2
  90. package/dist/testing/adapters/cli.d.ts.map +1 -1
  91. package/dist/testing/adapters/cli.js +11 -14
  92. package/dist/testing/adapters/cli.js.map +1 -1
  93. package/dist/testing/adapters/git.d.ts +10 -0
  94. package/dist/testing/adapters/git.d.ts.map +1 -1
  95. package/dist/testing/adapters/git.js +6 -2
  96. package/dist/testing/adapters/git.js.map +1 -1
  97. package/dist/testing/adapters/hookRepository.d.ts.map +1 -1
  98. package/dist/testing/adapters/hookRepository.js +6 -2
  99. package/dist/testing/adapters/hookRepository.js.map +1 -1
  100. package/dist/testing/ruleStory.d.ts.map +1 -1
  101. package/dist/testing/ruleStory.js +1 -2
  102. package/dist/testing/ruleStory.js.map +1 -1
  103. package/package.json +5 -5
  104. package/src/adapters/ImportAnalysisFailure.ts +6 -0
  105. package/src/adapters/ImportCompiler.ts +7 -20
  106. package/src/adapters/imports/analysisFailure.ts +5 -0
  107. package/src/adapters/imports/analyzeDepartures.ts +9 -0
  108. package/src/adapters/imports/analyzeGraph.ts +9 -0
  109. package/src/adapters/imports/checkBrowser.ts +5 -0
  110. package/src/adapters/indirectServiceReferences.ts +25 -0
  111. package/src/adapters/nativeTransactionFindings.ts +108 -0
  112. package/src/adapters/outsideImportFindings.ts +1 -1
  113. package/src/adapters/serviceAssemblyImports.ts +93 -0
  114. package/src/adapters/serviceAssemblySyntax.ts +129 -0
  115. package/src/adapters/serviceDefinitionProblems.ts +63 -0
  116. package/src/adapters/serviceIdFindings.ts +16 -13
  117. package/src/adapters/transactionChanges.ts +85 -0
  118. package/src/rules/builtIn.ts +4 -0
  119. package/src/rules/effect/serviceCatalog.ts +4 -2
  120. package/src/rules/effect/serviceDefinitionAssembly.ts +46 -0
  121. package/src/rules/effect/serviceIds.ts +1 -1
  122. package/src/rules/effect/serviceParameters.ts +12 -6
  123. package/src/rules/effect/sqlTransact.ts +10 -0
  124. package/src/testing/adapters/cli.ts +22 -14
  125. package/src/testing/adapters/git.ts +7 -2
  126. package/src/testing/adapters/hookRepository.ts +6 -2
  127. package/src/testing/ruleStory.ts +1 -2
@@ -0,0 +1,108 @@
1
+ import { join } from "node:path";
2
+ import { Effect } from "effect";
3
+ import ts from "typescript";
4
+ import type { Finding, RuleInputs } from "#rule.ts";
5
+ import { effectProgram } from "#rules/effect/program.ts";
6
+ import { parse } from "#rules/parse.ts";
7
+ import { memberName, nodesWhere, unwrapped } from "#rules/stories/syntax.ts";
8
+ import { transactionChanges } from "./transactionChanges.ts";
9
+
10
+ function candidates(source: ts.SourceFile): readonly ts.Node[] {
11
+ const aliases = new Set(["withTransaction"]);
12
+ for (const node of nodesWhere(source, (candidate) => ts.isVariableDeclaration(candidate) || ts.isBindingElement(candidate))) {
13
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer !== undefined) {
14
+ const value = unwrapped(node.initializer);
15
+ if (memberName(value) === "withTransaction" || (ts.isIdentifier(value) && aliases.has(value.text))) {
16
+ aliases.add(node.name.text);
17
+ }
18
+ }
19
+ if (ts.isBindingElement(node) && node.propertyName?.getText() === "withTransaction" && ts.isIdentifier(node.name)) {
20
+ aliases.add(node.name.text);
21
+ }
22
+ }
23
+ function reference(expression: ts.Expression): boolean {
24
+ const value = unwrapped(expression);
25
+ return memberName(value) === "withTransaction" || (ts.isIdentifier(value) && aliases.has(value.text));
26
+ }
27
+ return nodesWhere(source, (node) => ts.isCallExpression(node) && (reference(node.expression) || node.arguments.some(reference)));
28
+ }
29
+
30
+ function nativeTransaction(checker: ts.TypeChecker, expression: ts.Expression): boolean {
31
+ const value = unwrapped(expression);
32
+ if (!ts.isIdentifier(value) && memberName(value) !== "withTransaction") {
33
+ return false;
34
+ }
35
+ const signature = checker.getTypeAtLocation(value).getCallSignatures()[0];
36
+ const declaration = signature?.getDeclaration();
37
+ if (declaration === undefined) {
38
+ return false;
39
+ }
40
+ const path = declaration.getSourceFile().fileName.replaceAll("\\", "/");
41
+ return (
42
+ /\/effect\/(?:src|dist(?:\/dts)?)\/sql\/SqlClient\.(?:d\.)?ts$/u.test(path)
43
+ && ts.isPropertySignature(declaration.parent)
44
+ && declaration.parent.name.getText() === "withTransaction"
45
+ );
46
+ }
47
+
48
+ function changedBodies(checker: ts.TypeChecker, call: ts.CallExpression): readonly ts.Expression[] {
49
+ if (nativeTransaction(checker, call.expression)) {
50
+ return call.arguments.slice(0, 1);
51
+ }
52
+ const callee = unwrapped(call.expression);
53
+ const index = call.arguments.findIndex((argument) => nativeTransaction(checker, argument));
54
+ if (index < 0) {
55
+ return [];
56
+ }
57
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === "pipe") {
58
+ return [callee.expression, ...call.arguments.slice(0, index)];
59
+ }
60
+ const declaration = checker.getResolvedSignature(call)?.getDeclaration();
61
+ return declaration !== undefined && /\/effect\/(?:src|dist(?:\/dts)?)\/Function\.(?:d\.)?ts$/u.test(declaration.getSourceFile().fileName)
62
+ ? call.arguments.slice(0, index)
63
+ : [];
64
+ }
65
+
66
+ function findingsIn(inputs: RuleInputs): readonly Finding[] {
67
+ const program = effectProgram(inputs);
68
+ const checker = program.getTypeChecker();
69
+ return inputs.sources.flatMap((file) => {
70
+ const source = program.getSourceFile(join(inputs.root, file.path));
71
+ if (source === undefined) {
72
+ return [];
73
+ }
74
+ return candidates(source).flatMap((node): readonly Finding[] => {
75
+ if (!ts.isCallExpression(node)) {
76
+ return [];
77
+ }
78
+ if (!changedBodies(checker, node).some((body) => transactionChanges(checker, body))) {
79
+ return [];
80
+ }
81
+ return [
82
+ {
83
+ file: file.path,
84
+ line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
85
+ message:
86
+ "Uses native sql.withTransaction around repository writes or change announcements. Begin the outer transaction with transact(effect, { onSqlError }) so changed keys follow its commit.",
87
+ },
88
+ ];
89
+ });
90
+ });
91
+ }
92
+
93
+ export const nativeTransactionFindings = Effect.fn("NativeTransactions.nativeTransactionFindings")((inputs: RuleInputs) =>
94
+ Effect.sync(() => {
95
+ const groups = new Map<string, RuleInputs["sources"][number][]>();
96
+ for (const source of inputs.sources) {
97
+ const syntax = source.text.includes("withTransaction") ? parse(source) : undefined;
98
+ if (syntax === undefined || candidates(syntax).length === 0) {
99
+ continue;
100
+ }
101
+ const group = /^(?:packages|examples)\/[^/]+/u.exec(source.path)?.[0] ?? ".";
102
+ const sources = groups.get(group) ?? [];
103
+ sources.push(source);
104
+ groups.set(group, sources);
105
+ }
106
+ return [...groups.values()].flatMap((sources) => findingsIn({ ...inputs, sources }));
107
+ }),
108
+ );
@@ -1,6 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import ts from "typescript";
3
- import type { ImportAnalysisFailure } from "#adapters/ImportCompiler.ts";
3
+ import type { ImportAnalysisFailure } from "#adapters/ImportAnalysisFailure.ts";
4
4
  import { readPackageManifest } from "#adapters/manifestInventory.ts";
5
5
  import { importGraph } from "#imports/graph.ts";
6
6
  import { packageNameOf } from "#imports/packageName.ts";
@@ -0,0 +1,93 @@
1
+ import ts from "typescript";
2
+
3
+ export interface ServiceAssemblyImports {
4
+ readonly definitions: ReadonlySet<string>;
5
+ readonly effects: ReadonlySet<string>;
6
+ readonly generics: ReadonlySet<string>;
7
+ readonly unsupported: readonly ts.Node[];
8
+ readonly values: ReadonlySet<string>;
9
+ }
10
+
11
+ function importedNames(clause: ts.ImportClause, name: string): readonly string[] {
12
+ const bindings = clause.namedBindings;
13
+ if (bindings === undefined || !ts.isNamedImports(bindings)) {
14
+ return [];
15
+ }
16
+ return bindings.elements.flatMap((element) =>
17
+ !element.isTypeOnly && (element.propertyName?.text ?? element.name.text) === name ? [element.name.text] : [],
18
+ );
19
+ }
20
+
21
+ function valueImport(statement: ts.Statement):
22
+ | {
23
+ readonly clause: ts.ImportClause;
24
+ readonly module: string;
25
+ }
26
+ | undefined {
27
+ if (
28
+ !(ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier))
29
+ || statement.importClause === undefined
30
+ || statement.importClause.isTypeOnly
31
+ ) {
32
+ return;
33
+ }
34
+ return {
35
+ clause: statement.importClause,
36
+ module: statement.moduleSpecifier.text,
37
+ };
38
+ }
39
+
40
+ function collectDefinitionImport(clause: ts.ImportClause, definitions: Set<string>, unsupported: ts.Node[]): void {
41
+ if (clause.namedBindings !== undefined && ts.isNamespaceImport(clause.namedBindings)) {
42
+ unsupported.push(clause.namedBindings);
43
+ }
44
+ for (const name of importedNames(clause, "defineService")) {
45
+ definitions.add(name);
46
+ }
47
+ }
48
+
49
+ function collectValueImports(clause: ts.ImportClause, values: Set<string>): void {
50
+ if (clause.namedBindings === undefined || !ts.isNamedImports(clause.namedBindings)) {
51
+ return;
52
+ }
53
+ for (const element of clause.namedBindings.elements) {
54
+ if (!element.isTypeOnly) {
55
+ values.add(element.name.text);
56
+ }
57
+ }
58
+ }
59
+
60
+ function effectNames(clause: ts.ImportClause, module: string): readonly string[] {
61
+ if (module === "effect") {
62
+ return importedNames(clause, "Effect");
63
+ }
64
+ const bindings = clause.namedBindings;
65
+ return module === "effect/Effect" && bindings !== undefined && ts.isNamespaceImport(bindings) ? [bindings.name.text] : [];
66
+ }
67
+
68
+ export function serviceAssemblyImports(source: ts.SourceFile): ServiceAssemblyImports {
69
+ const definitions = new Set<string>();
70
+ const effects = new Set<string>();
71
+ const generics = new Set<string>();
72
+ const unsupported: ts.Node[] = [];
73
+ const values = new Set<string>();
74
+ for (const statement of source.statements) {
75
+ const imported = valueImport(statement);
76
+ if (imported === undefined) {
77
+ continue;
78
+ }
79
+ collectValueImports(imported.clause, values);
80
+ if (imported.module === "@shivaedev/service/defineService.ts") {
81
+ collectDefinitionImport(imported.clause, definitions, unsupported);
82
+ }
83
+ if (imported.module === "@shivaedev/service/genericMethod.ts") {
84
+ for (const name of importedNames(imported.clause, "genericMethod")) {
85
+ generics.add(name);
86
+ }
87
+ }
88
+ for (const name of effectNames(imported.clause, imported.module)) {
89
+ effects.add(name);
90
+ }
91
+ }
92
+ return { definitions, effects, generics, unsupported, values };
93
+ }
@@ -0,0 +1,129 @@
1
+ import ts from "typescript";
2
+
3
+ export function unwrapExpression(expression: ts.Expression): ts.Expression {
4
+ if (ts.isParenthesizedExpression(expression) || ts.isAsExpression(expression) || ts.isSatisfiesExpression(expression)) {
5
+ return unwrapExpression(expression.expression);
6
+ }
7
+ return expression;
8
+ }
9
+
10
+ export function directServiceDefinitions(source: ts.SourceFile, names: ReadonlySet<string>): readonly ts.CallExpression[] {
11
+ const found: ts.CallExpression[] = [];
12
+ for (const statement of source.statements) {
13
+ if (!ts.isVariableStatement(statement)) {
14
+ continue;
15
+ }
16
+ for (const declaration of statement.declarationList.declarations) {
17
+ if (declaration.initializer === undefined) {
18
+ continue;
19
+ }
20
+ const value = unwrapExpression(declaration.initializer);
21
+ if (!ts.isCallExpression(value)) {
22
+ continue;
23
+ }
24
+ const called = unwrapExpression(value.expression);
25
+ if (ts.isIdentifier(called) && names.has(called.text)) {
26
+ found.push(value);
27
+ }
28
+ }
29
+ }
30
+ return found;
31
+ }
32
+
33
+ const CONFIG_MEMBERS = new Set(["id", "initialize", "methods", "requires"]);
34
+
35
+ export function invalidServiceMembers(config: ts.ObjectLiteralExpression): readonly ts.ObjectLiteralElementLike[] {
36
+ return config.properties.filter(
37
+ (member) =>
38
+ !(
39
+ (ts.isPropertyAssignment(member) || ts.isShorthandPropertyAssignment(member))
40
+ && ts.isIdentifier(member.name)
41
+ && CONFIG_MEMBERS.has(member.name.text)
42
+ ),
43
+ );
44
+ }
45
+
46
+ export function serviceProperty(object: ts.ObjectLiteralExpression, name: string): ts.Expression | undefined {
47
+ const member = object.properties.find(
48
+ (candidate) =>
49
+ (ts.isPropertyAssignment(candidate) || ts.isShorthandPropertyAssignment(candidate))
50
+ && ts.isIdentifier(candidate.name)
51
+ && candidate.name.text === name,
52
+ );
53
+ if (member !== undefined && ts.isPropertyAssignment(member)) {
54
+ return member.initializer;
55
+ }
56
+ return member !== undefined && ts.isShorthandPropertyAssignment(member) ? member.name : undefined;
57
+ }
58
+
59
+ export function returnedServiceMethods(value: ts.Expression): ts.ObjectLiteralExpression | undefined {
60
+ if (!ts.isArrowFunction(value)) {
61
+ return;
62
+ }
63
+ if (!ts.isBlock(value.body)) {
64
+ const body = unwrapExpression(value.body);
65
+ return ts.isObjectLiteralExpression(body) ? body : undefined;
66
+ }
67
+ if (value.body.statements.length !== 1) {
68
+ return;
69
+ }
70
+ const [statement] = value.body.statements;
71
+ if (statement === undefined || !ts.isReturnStatement(statement) || statement.expression === undefined) {
72
+ return;
73
+ }
74
+ const result = unwrapExpression(statement.expression);
75
+ return ts.isObjectLiteralExpression(result) ? result : undefined;
76
+ }
77
+
78
+ export function isEffectVoid(value: ts.Expression, effects: ReadonlySet<string>): boolean {
79
+ return (
80
+ ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression) && effects.has(value.expression.text) && value.name.text === "void"
81
+ );
82
+ }
83
+
84
+ export function isOperationReference(member: ts.ObjectLiteralElementLike, imports: ReadonlySet<string>, generics: ReadonlySet<string>): boolean {
85
+ if (ts.isShorthandPropertyAssignment(member)) {
86
+ return imports.has(member.name.text);
87
+ }
88
+ if (!ts.isPropertyAssignment(member) || ts.isComputedPropertyName(member.name)) {
89
+ return false;
90
+ }
91
+ const value = unwrapExpression(member.initializer);
92
+ if (ts.isIdentifier(value)) {
93
+ return imports.has(value.text);
94
+ }
95
+ if (ts.isCallExpression(value) && ts.isIdentifier(value.expression) && generics.has(value.expression.text)) {
96
+ const method = value.arguments[0];
97
+ return method !== undefined && isOperationValue(unwrapExpression(method), imports);
98
+ }
99
+ return isOperationValue(value, imports);
100
+ }
101
+
102
+ function isOperationValue(value: ts.Expression, imports: ReadonlySet<string>): boolean {
103
+ return (
104
+ (ts.isIdentifier(value) && imports.has(value.text))
105
+ || (ts.isCallExpression(value)
106
+ && ts.isIdentifier(unwrapExpression(value.expression))
107
+ && imports.has(unwrapExpression(value.expression).getText()))
108
+ );
109
+ }
110
+
111
+ function isFunctionBody(node: ts.Node): node is ts.FunctionLikeDeclaration {
112
+ return (
113
+ (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node))
114
+ && node.body !== undefined
115
+ );
116
+ }
117
+
118
+ export function implementationBodies(source: ts.SourceFile, allowed: ReadonlySet<ts.Node>): readonly ts.Node[] {
119
+ const found: ts.Node[] = [];
120
+ function visit(node: ts.Node): void {
121
+ if (isFunctionBody(node) && !allowed.has(node)) {
122
+ found.push(node);
123
+ return;
124
+ }
125
+ ts.forEachChild(node, visit);
126
+ }
127
+ visit(source);
128
+ return found;
129
+ }
@@ -0,0 +1,63 @@
1
+ import ts from "typescript";
2
+ import {
3
+ invalidServiceMembers,
4
+ isEffectVoid,
5
+ isOperationReference,
6
+ returnedServiceMethods,
7
+ serviceProperty,
8
+ unwrapExpression,
9
+ } from "#adapters/serviceAssemblySyntax.ts";
10
+
11
+ export interface ServiceAssemblyProblem {
12
+ readonly message: string;
13
+ readonly node: ts.Node;
14
+ }
15
+
16
+ export function serviceDefinitionProblems(
17
+ definition: ts.CallExpression,
18
+ effects: ReadonlySet<string>,
19
+ imports: ReadonlySet<string>,
20
+ allowedBodies: Set<ts.Node>,
21
+ generics: ReadonlySet<string>,
22
+ ): readonly ServiceAssemblyProblem[] {
23
+ const config = definition.arguments[0];
24
+ if (config === undefined || !ts.isObjectLiteralExpression(config)) {
25
+ return [{ message: "Inline the service inventory.", node: definition }];
26
+ }
27
+ const found: ServiceAssemblyProblem[] = invalidServiceMembers(config).map((node) => ({
28
+ message: "List id, initialize, methods, and requires directly; computed members and spreads cannot hide the service inventory.",
29
+ node,
30
+ }));
31
+ const initialize = serviceProperty(config, "initialize");
32
+ if (
33
+ initialize !== undefined
34
+ && !(ts.isIdentifier(unwrapExpression(initialize)) && imports.has(unwrapExpression(initialize).getText()))
35
+ && !isEffectVoid(unwrapExpression(initialize), effects)
36
+ ) {
37
+ found.push({
38
+ message: "Reference a named initializer export or use Effect.void.",
39
+ node: initialize,
40
+ });
41
+ }
42
+ const methodsValue = serviceProperty(config, "methods");
43
+ const methods = methodsValue && returnedServiceMethods(methodsValue);
44
+ if (methodsValue !== undefined && methods === undefined) {
45
+ found.push({
46
+ message: "Keep methods as a direct operation inventory.",
47
+ node: methodsValue,
48
+ });
49
+ return found;
50
+ }
51
+ if (methodsValue !== undefined) {
52
+ allowedBodies.add(methodsValue);
53
+ }
54
+ for (const operation of methods?.properties ?? []) {
55
+ if (!isOperationReference(operation, imports, generics)) {
56
+ found.push({
57
+ message: "Reference a named operation export or call its named state factory.",
58
+ node: operation,
59
+ });
60
+ }
61
+ }
62
+ return found;
63
+ }
@@ -1,6 +1,7 @@
1
1
  import { join } from "node:path";
2
2
  import { Effect } from "effect";
3
3
  import ts from "typescript";
4
+ import { packageOf, type WorkspacePackage, workspacePackages } from "#imports/workspace.ts";
4
5
  import type { Finding, RuleInputs } from "#rule.ts";
5
6
  import { boundaryReference } from "#rules/effect/boundaryReference.ts";
6
7
 
@@ -64,17 +65,19 @@ function checkPackage(inputs: RuleInputs, prefix: string): readonly Finding[] {
64
65
  });
65
66
  }
66
67
 
67
- export const serviceIdFindings = Effect.fn("ServiceIds.serviceIdFindings")((inputs: RuleInputs) =>
68
- Effect.sync(() => {
69
- const groups = new Map<string, RuleInputs["sources"][number][]>();
70
- for (const source of inputs.sources) {
71
- const name = /^packages\/(?<name>[^/]+)\/.+\.[cm]?[jt]sx?$/u.exec(source.path)?.groups?.name;
72
- if (name !== undefined) {
73
- const files = groups.get(name) ?? [];
74
- files.push(source);
75
- groups.set(name, files);
76
- }
68
+ export const serviceIdFindings = Effect.fn("ServiceIds.serviceIdFindings")(function* (inputs: RuleInputs) {
69
+ const packages = yield* Effect.promise(() => workspacePackages(inputs));
70
+ const groups = new Map<WorkspacePackage, RuleInputs["sources"][number][]>();
71
+ for (const source of inputs.sources) {
72
+ if (!source.path.startsWith("packages/")) {
73
+ continue;
74
+ }
75
+ const owner = packageOf(packages, source.path);
76
+ if (owner !== undefined) {
77
+ const files = groups.get(owner) ?? [];
78
+ files.push(source);
79
+ groups.set(owner, files);
77
80
  }
78
- return [...groups].flatMap(([name, sources]) => checkPackage({ ...inputs, sources }, `@shivaedev/${name}/`));
79
- }),
80
- );
81
+ }
82
+ return [...groups].flatMap(([owner, sources]) => checkPackage({ ...inputs, sources }, `${owner.name}/`));
83
+ });
@@ -0,0 +1,85 @@
1
+ import ts from "typescript";
2
+ import { memberName, unwrapped } from "#rules/stories/syntax.ts";
3
+
4
+ const WRITES = new Set([
5
+ "insert",
6
+ "insertVoid",
7
+ "insertOrIgnore",
8
+ "insertMany",
9
+ "insertManyOrIgnore",
10
+ "insertFromSelect",
11
+ "insertFromSelectOrIgnore",
12
+ "update",
13
+ "updateVoid",
14
+ "upsert",
15
+ "upsertMany",
16
+ "delete",
17
+ "deleteBatched",
18
+ ]);
19
+
20
+ function sqlModule(path: string): boolean {
21
+ return /\/(?:@shivaedev\/)?sql\/(?:src|dist)\//u.test(path.replaceAll("\\", "/"));
22
+ }
23
+
24
+ export function transactionChanges(checker: ts.TypeChecker, body: ts.Expression): boolean {
25
+ const seen = new Set<ts.Node>();
26
+ function repositoryWrite(expression: ts.Expression, name: string | undefined): boolean {
27
+ if (!WRITES.has(name ?? "")) {
28
+ return false;
29
+ }
30
+ const purge = checker.getTypeAtLocation(expression).getProperty("deleteBatched");
31
+ return purge?.declarations?.some((declaration) => sqlModule(declaration.getSourceFile().fileName)) ?? false;
32
+ }
33
+ function bindingWrite(declaration: ts.BindingElement): boolean {
34
+ if (!ts.isVariableDeclaration(declaration.parent.parent)) {
35
+ return false;
36
+ }
37
+ const value = declaration.parent.parent.initializer;
38
+ const property = declaration.propertyName ?? declaration.name;
39
+ return value !== undefined && repositoryWrite(value, ts.isIdentifier(property) ? property.text : undefined);
40
+ }
41
+ function declarationChanges(declaration: ts.Declaration, name: string): boolean {
42
+ const source = declaration.getSourceFile();
43
+ if (sqlModule(source.fileName)) {
44
+ return ["transact", "invalidateOnCommit"].includes(name) && /\/transact\.(?:d\.)?ts$/u.test(source.fileName);
45
+ }
46
+ if (source.isDeclarationFile || source.fileName.includes("/node_modules/")) {
47
+ return false;
48
+ }
49
+ if (ts.isVariableDeclaration(declaration)) {
50
+ return declaration.initializer !== undefined && visit(declaration.initializer);
51
+ }
52
+ if (ts.isFunctionDeclaration(declaration)) {
53
+ return declaration.body !== undefined && visit(declaration.body);
54
+ }
55
+ if (ts.isBindingElement(declaration)) {
56
+ return bindingWrite(declaration);
57
+ }
58
+ return false;
59
+ }
60
+ function reference(node: ts.Identifier): boolean {
61
+ const symbol = checker.getSymbolAtLocation(node);
62
+ if (symbol === undefined) {
63
+ return false;
64
+ }
65
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
66
+ return target.declarations?.some((declaration) => declarationChanges(declaration, target.name)) ?? false;
67
+ }
68
+ function visit(node: ts.Node): boolean {
69
+ if (seen.has(node) || ts.isTypeNode(node)) {
70
+ return false;
71
+ }
72
+ seen.add(node);
73
+ if (ts.isIdentifier(node) && reference(node)) {
74
+ return true;
75
+ }
76
+ if (
77
+ (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
78
+ && repositoryWrite(unwrapped(node.expression), memberName(node))
79
+ ) {
80
+ return true;
81
+ }
82
+ return ts.forEachChild(node, (child) => visit(child) || undefined) ?? false;
83
+ }
84
+ return visit(body);
85
+ }
@@ -10,9 +10,11 @@ import { docsUnversionedInstalls } from "#rules/docs/unversionedInstalls.ts";
10
10
  import { adapterImports } from "#rules/effect/adapterImports.ts";
11
11
  import { effectBoundary } from "#rules/effect/boundary.ts";
12
12
  import { failureHonesty } from "#rules/effect/failureHonesty.ts";
13
+ import { serviceDefinitionAssembly } from "#rules/effect/serviceDefinitionAssembly.ts";
13
14
  import { serviceIds } from "#rules/effect/serviceIds.ts";
14
15
  import { serviceParameters } from "#rules/effect/serviceParameters.ts";
15
16
  import { sharedErrorClasses } from "#rules/effect/sharedErrorClasses.ts";
17
+ import { sqlTransact } from "#rules/effect/sqlTransact.ts";
16
18
  import { distinctCase } from "#rules/files/distinctCase.ts";
17
19
  import { folderNames } from "#rules/files/folderNames.ts";
18
20
  import { namedAfterExport } from "#rules/files/namedAfterExport.ts";
@@ -66,9 +68,11 @@ export const builtInRules = [
66
68
  adapterImports,
67
69
  effectBoundary,
68
70
  failureHonesty,
71
+ serviceDefinitionAssembly,
69
72
  serviceIds,
70
73
  serviceParameters,
71
74
  sharedErrorClasses,
75
+ sqlTransact,
72
76
  jsxConditionals,
73
77
  maxLines,
74
78
  maxDepth,
@@ -1,8 +1,10 @@
1
1
  import ts from "typescript";
2
+ import servicePackage from "@shivaedev/service/package.json" with { type: "json" };
2
3
  import { serviceOrigin } from "#rules/effect/serviceOrigin.ts";
3
4
  import { serviceTypes } from "#rules/effect/serviceTypes.ts";
4
5
 
5
- export function serviceCatalog(program: ts.Program, checker: ts.TypeChecker) {
6
+ export function serviceCatalog(program: ts.Program, checker: ts.TypeChecker, packages: readonly string[] = []) {
7
+ const prefixes = [servicePackage.name, ...packages].map((name) => `${name.startsWith("@") ? name.split("/")[0] : name}/`);
6
8
  const services = serviceTypes(checker);
7
9
  function imported(node: ts.ImportSpecifier | ts.NamespaceImport): void {
8
10
  const symbol = checker.getSymbolAtLocation(node.name);
@@ -49,7 +51,7 @@ export function serviceCatalog(program: ts.Program, checker: ts.TypeChecker) {
49
51
  ts.forEachChild(node, discover);
50
52
  }
51
53
  for (const source of program.getSourceFiles()) {
52
- if (!source.fileName.includes("/node_modules/") || source.fileName.includes("/@shivaedev/")) {
54
+ if (!source.fileName.includes("/node_modules/") || prefixes.some((prefix) => source.fileName.includes(`/${prefix}`))) {
53
55
  discover(source);
54
56
  }
55
57
  }
@@ -0,0 +1,46 @@
1
+ import type ts from "typescript";
2
+ import { indirectServiceReferences } from "#adapters/indirectServiceReferences.ts";
3
+ import { serviceAssemblyImports } from "#adapters/serviceAssemblyImports.ts";
4
+ import { directServiceDefinitions, implementationBodies } from "#adapters/serviceAssemblySyntax.ts";
5
+ import { serviceDefinitionProblems } from "#adapters/serviceDefinitionProblems.ts";
6
+ import { defineRule, type Finding, type SourceFile } from "#rule.ts";
7
+ import { parse } from "#rules/parse.ts";
8
+
9
+ function fileFindings(file: SourceFile): readonly Finding[] {
10
+ const source = parse(file);
11
+ if (source === undefined) {
12
+ return [];
13
+ }
14
+ const imports = serviceAssemblyImports(source);
15
+ if (imports.definitions.size === 0 && imports.unsupported.length === 0) {
16
+ return [];
17
+ }
18
+ const definitions = directServiceDefinitions(source, imports.definitions);
19
+ const found = imports.unsupported.map((node) => ({ message: "Import and call defineService directly.", node }));
20
+ for (const node of indirectServiceReferences(source, imports.definitions, definitions)) {
21
+ found.push({ message: "Call the imported defineService directly in a top-level service declaration.", node });
22
+ }
23
+ if (imports.definitions.size > 0 && definitions.length === 0) {
24
+ found.push({ message: "Call the imported defineService directly in a top-level service declaration.", node: source });
25
+ }
26
+ const allowedBodies = new Set<ts.Node>();
27
+ for (const definition of definitions) {
28
+ found.push(...serviceDefinitionProblems(definition, imports.effects, imports.values, allowedBodies, imports.generics));
29
+ }
30
+ for (const node of implementationBodies(source, allowedBodies)) {
31
+ found.push({ message: "Move this implementation body to a named export in its own focused file.", node });
32
+ }
33
+ return found.map(({ node, message }) => ({
34
+ file: file.path,
35
+ line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
36
+ message,
37
+ }));
38
+ }
39
+
40
+ export const serviceDefinitionAssembly = defineRule({
41
+ check: ({ sources }) => sources.flatMap(fileFindings),
42
+ description:
43
+ "Keep defineService declarations as top-level operation inventories: list id, requires, initialize and methods directly. Import a named initializer (or use Effect.void) and named operations or state factories from focused files; genericMethod may wrap those references. Move implementation bodies out of the assembly file. Effect.fn span names follow the existing Biome checks. Includes adapters and tests; no config exceptions or inline suppressions.",
44
+ id: "effect/service-definition-assembly",
45
+ registrable: false,
46
+ });
@@ -4,7 +4,7 @@ import { defineRule } from "#rule.ts";
4
4
  export const serviceIds = defineRule({
5
5
  check: serviceIdFindings,
6
6
  description:
7
- "Literal Context.Service, Context.Reference, defineService and RPC middleware ids in packages/<name>/ start with @shivaedev/<name>/. Prefix the id and update its references. Includes adapters and tests; computed ids and files outside packages/ are not checked. No config exceptions or inline suppressions.",
7
+ "Literal Context.Service, Context.Reference, defineService and RPC middleware ids in workspace packages under packages/ start with the owning manifest's name and a slash. Prefix the id and update its references. Includes adapters and tests; computed ids, files without a named workspace owner and files outside packages/ are not checked. No config exceptions or inline suppressions.",
8
8
  id: "effect/service-ids",
9
9
  registrable: false,
10
10
  });