@craft-ng/dev-tools 0.1.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.
@@ -0,0 +1,141 @@
1
+ module.exports = {
2
+ meta: {
3
+ type: 'problem',
4
+ docs: {
5
+ description:
6
+ 'Disallow Angular inject(), @Injectable, and @Service usage so dependencies go through craftService or toCraftService.',
7
+ },
8
+ schema: [],
9
+ },
10
+ create(context) {
11
+ const angularNamespaceImports = new Set();
12
+ const angularInjectableImports = new Set();
13
+ const angularServiceImports = new Set();
14
+
15
+ return {
16
+ ImportDeclaration(node) {
17
+ if (!isAngularModule(node.source.value)) {
18
+ return;
19
+ }
20
+
21
+ for (const specifier of node.specifiers) {
22
+ if (
23
+ specifier.type === 'ImportSpecifier' &&
24
+ specifier.imported.type === 'Identifier' &&
25
+ specifier.imported.name === 'inject'
26
+ ) {
27
+ context.report({
28
+ node: specifier,
29
+ message:
30
+ 'Angular inject() is forbidden. Expose a craftService/toCraftService injector instead.',
31
+ });
32
+ continue;
33
+ }
34
+
35
+ if (
36
+ specifier.type === 'ImportSpecifier' &&
37
+ specifier.imported.type === 'Identifier' &&
38
+ specifier.imported.name === 'Injectable'
39
+ ) {
40
+ angularInjectableImports.add(specifier.local.name);
41
+ continue;
42
+ }
43
+
44
+ if (
45
+ specifier.type === 'ImportSpecifier' &&
46
+ specifier.imported.type === 'Identifier' &&
47
+ specifier.imported.name === 'Service'
48
+ ) {
49
+ angularServiceImports.add(specifier.local.name);
50
+ continue;
51
+ }
52
+
53
+ if (specifier.type === 'ImportNamespaceSpecifier') {
54
+ angularNamespaceImports.add(specifier.local.name);
55
+ }
56
+ }
57
+ },
58
+ CallExpression(node) {
59
+ const callee = node.callee;
60
+ if (
61
+ callee.type !== 'MemberExpression' ||
62
+ callee.computed ||
63
+ callee.object.type !== 'Identifier' ||
64
+ !angularNamespaceImports.has(callee.object.name) ||
65
+ callee.property.type !== 'Identifier' ||
66
+ callee.property.name !== 'inject'
67
+ ) {
68
+ return;
69
+ }
70
+
71
+ context.report({
72
+ node: callee.property,
73
+ message:
74
+ 'Angular inject() is forbidden. Expose a craftService/toCraftService injector instead.',
75
+ });
76
+ },
77
+ Decorator(node) {
78
+ const decoratorName = getAngularBlockedDecoratorName(
79
+ node.expression,
80
+ angularInjectableImports,
81
+ angularServiceImports,
82
+ angularNamespaceImports,
83
+ );
84
+ if (!decoratorName) {
85
+ return;
86
+ }
87
+
88
+ context.report({
89
+ node,
90
+ message: `Angular @${decoratorName} is forbidden. Expose the dependency through craftService or toCraftService instead.`,
91
+ });
92
+ },
93
+ };
94
+ },
95
+ };
96
+
97
+ function isAngularModule(sourceValue) {
98
+ return typeof sourceValue === 'string' && sourceValue.startsWith('@angular/');
99
+ }
100
+
101
+ function getAngularBlockedDecoratorName(
102
+ expression,
103
+ angularInjectableImports,
104
+ angularServiceImports,
105
+ angularNamespaceImports,
106
+ ) {
107
+ if (expression.type === 'Identifier') {
108
+ if (angularInjectableImports.has(expression.name)) {
109
+ return 'Injectable';
110
+ }
111
+
112
+ if (angularServiceImports.has(expression.name)) {
113
+ return 'Service';
114
+ }
115
+
116
+ return undefined;
117
+ }
118
+
119
+ if (expression.type === 'CallExpression') {
120
+ return getAngularBlockedDecoratorName(
121
+ expression.callee,
122
+ angularInjectableImports,
123
+ angularServiceImports,
124
+ angularNamespaceImports,
125
+ );
126
+ }
127
+
128
+ if (
129
+ expression.type === 'MemberExpression' &&
130
+ !expression.computed &&
131
+ expression.object.type === 'Identifier' &&
132
+ angularNamespaceImports.has(expression.object.name) &&
133
+ expression.property.type === 'Identifier' &&
134
+ (expression.property.name === 'Injectable' ||
135
+ expression.property.name === 'Service')
136
+ ) {
137
+ return expression.property.name;
138
+ }
139
+
140
+ return undefined;
141
+ }
@@ -0,0 +1,234 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+
4
+ const { Project, Node, SyntaxKind } = require('ts-morph');
5
+ const { getAngularKind } = require('../scripts/angular-brand-codemod.js');
6
+
7
+ const projectCache = new Map();
8
+
9
+ module.exports = {
10
+ meta: {
11
+ type: 'problem',
12
+ docs: {
13
+ description:
14
+ 'Disallow direct exports of Angular symbols managed through brandAngularSymbol.',
15
+ },
16
+ schema: [],
17
+ },
18
+ create(context) {
19
+ return {
20
+ 'Program:exit'() {
21
+ const sourceCode = context.sourceCode ?? context.getSourceCode();
22
+ const filePath = getFilePath(context);
23
+ if (!filePath || !filePath.endsWith('.ts')) {
24
+ return;
25
+ }
26
+
27
+ const text = sourceCode.getText();
28
+ if (!text.includes('export')) {
29
+ return;
30
+ }
31
+
32
+ const sourceFile = getProjectSourceFile(
33
+ getProject(getCwd(context)),
34
+ filePath,
35
+ text,
36
+ );
37
+ const angularClasses = sourceFile
38
+ .getClasses()
39
+ .map((classDeclaration) => ({
40
+ classDeclaration,
41
+ angularKind: getAngularKind(classDeclaration),
42
+ }))
43
+ .filter((entry) => Boolean(entry.angularKind));
44
+
45
+ for (const { classDeclaration, angularKind } of angularClasses) {
46
+ reportDirectClassExport(
47
+ context,
48
+ sourceCode,
49
+ classDeclaration,
50
+ angularKind,
51
+ );
52
+ reportIdentifierExportAssignment(
53
+ context,
54
+ sourceCode,
55
+ sourceFile,
56
+ classDeclaration,
57
+ angularKind,
58
+ );
59
+ reportNamedExports(
60
+ context,
61
+ sourceCode,
62
+ sourceFile,
63
+ classDeclaration,
64
+ angularKind,
65
+ );
66
+ }
67
+ },
68
+ };
69
+ },
70
+ };
71
+
72
+ function getProject(cwd) {
73
+ let project = projectCache.get(cwd);
74
+ if (project) {
75
+ return project;
76
+ }
77
+
78
+ const tsConfigFilePath = path.join(cwd, 'tsconfig.json');
79
+ project = fs.existsSync(tsConfigFilePath)
80
+ ? new Project({ tsConfigFilePath })
81
+ : new Project({
82
+ compilerOptions: {
83
+ experimentalDecorators: true,
84
+ target: 9,
85
+ },
86
+ });
87
+
88
+ projectCache.set(cwd, project);
89
+ return project;
90
+ }
91
+
92
+ function getProjectSourceFile(project, filePath, text) {
93
+ const normalizedPath = path.resolve(filePath);
94
+ const existingSourceFile = project.getSourceFile(normalizedPath);
95
+ if (existingSourceFile) {
96
+ existingSourceFile.replaceWithText(text);
97
+ return existingSourceFile;
98
+ }
99
+
100
+ const sourceFile = project.addSourceFileAtPathIfExists(normalizedPath);
101
+ if (sourceFile) {
102
+ sourceFile.replaceWithText(text);
103
+ return sourceFile;
104
+ }
105
+
106
+ return project.createSourceFile(normalizedPath, text, { overwrite: true });
107
+ }
108
+
109
+ function getFilePath(context) {
110
+ const filePath = context.filename ?? context.getFilename();
111
+ if (!filePath || filePath === '<input>') {
112
+ return undefined;
113
+ }
114
+
115
+ return filePath;
116
+ }
117
+
118
+ function getCwd(context) {
119
+ return context.cwd ?? process.cwd();
120
+ }
121
+
122
+ function reportDirectClassExport(
123
+ context,
124
+ sourceCode,
125
+ classDeclaration,
126
+ angularKind,
127
+ ) {
128
+ const hasDirectExportModifier = classDeclaration
129
+ .getModifiers()
130
+ .some(
131
+ (modifier) =>
132
+ modifier.getKind() === SyntaxKind.ExportKeyword ||
133
+ modifier.getKind() === SyntaxKind.DefaultKeyword,
134
+ );
135
+
136
+ if (!hasDirectExportModifier) {
137
+ return;
138
+ }
139
+
140
+ reportNode(
141
+ context,
142
+ sourceCode,
143
+ classDeclaration,
144
+ `Do not export ${formatAngularKind(angularKind)} classes directly. Keep the class local and export default brandAngularSymbol(...).`,
145
+ );
146
+ }
147
+
148
+ function reportIdentifierExportAssignment(
149
+ context,
150
+ sourceCode,
151
+ sourceFile,
152
+ classDeclaration,
153
+ angularKind,
154
+ ) {
155
+ const className = classDeclaration.getName();
156
+ if (!className) {
157
+ return;
158
+ }
159
+
160
+ for (const exportAssignment of sourceFile.getExportAssignments()) {
161
+ if (exportAssignment.isExportEquals()) {
162
+ continue;
163
+ }
164
+
165
+ const expression = exportAssignment.getExpression();
166
+ if (!Node.isIdentifier(expression) || expression.getText() !== className) {
167
+ continue;
168
+ }
169
+
170
+ reportNode(
171
+ context,
172
+ sourceCode,
173
+ exportAssignment,
174
+ `Do not export ${formatAngularKind(angularKind)} classes directly. Use export default brandAngularSymbol(${className}, deps(...)).`,
175
+ );
176
+ }
177
+ }
178
+
179
+ function reportNamedExports(
180
+ context,
181
+ sourceCode,
182
+ sourceFile,
183
+ classDeclaration,
184
+ angularKind,
185
+ ) {
186
+ const className = classDeclaration.getName();
187
+ if (!className) {
188
+ return;
189
+ }
190
+
191
+ for (const exportDeclaration of sourceFile.getExportDeclarations()) {
192
+ if (exportDeclaration.getModuleSpecifier()) {
193
+ continue;
194
+ }
195
+
196
+ for (const namedExport of exportDeclaration.getNamedExports()) {
197
+ if (namedExport.getName() !== className) {
198
+ continue;
199
+ }
200
+
201
+ reportNode(
202
+ context,
203
+ sourceCode,
204
+ namedExport,
205
+ `Do not export ${formatAngularKind(angularKind)} classes directly. Keep ${className} local and export the branded symbol instead.`,
206
+ );
207
+ }
208
+ }
209
+ }
210
+
211
+ function reportNode(context, sourceCode, node, message) {
212
+ context.report({
213
+ loc: {
214
+ start: sourceCode.getLocFromIndex(node.getStart()),
215
+ end: sourceCode.getLocFromIndex(node.getEnd()),
216
+ },
217
+ message,
218
+ });
219
+ }
220
+
221
+ function formatAngularKind(angularKind) {
222
+ switch (angularKind) {
223
+ case 'component':
224
+ return '@Component';
225
+ case 'directive':
226
+ return '@Directive';
227
+ case 'pipe':
228
+ return '@Pipe';
229
+ case 'injectable':
230
+ return '@Injectable';
231
+ default:
232
+ return 'Angular';
233
+ }
234
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './scripts/angular-brand-codemod';
package/src/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // Export programmatic API for codemod
2
+ export * from './scripts/angular-brand-codemod';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../libs/dev-tools/src/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,cAAc,iCAAiC,CAAC"}
@@ -0,0 +1,75 @@
1
+ import { ClassDeclaration, Node, SourceFile } from 'ts-morph';
2
+ export type AngularKind = 'component' | 'directive' | 'pipe' | 'injectable';
3
+ export type TransformResult = {
4
+ changed: boolean;
5
+ skipped: boolean;
6
+ warnings: string[];
7
+ angularKind?: string;
8
+ className?: string;
9
+ dependencies: string[];
10
+ dependencyGroups: DependencyGroups;
11
+ };
12
+ export type AngularBrandCodemodOptions = {
13
+ helperImportPath?: string;
14
+ transformOnlyStandaloneDeclarables?: boolean;
15
+ includeProviders?: boolean;
16
+ includeViewProviders?: boolean;
17
+ };
18
+ export type AngularClassSearchResult = {
19
+ classDeclaration?: ClassDeclaration;
20
+ angularKind?: AngularKind;
21
+ className?: string;
22
+ skipped: boolean;
23
+ warnings: string[];
24
+ };
25
+ export type DependencyExtractionResult = {
26
+ dependencies: string[];
27
+ warnings: string[];
28
+ };
29
+ export type DependencyGroups = {
30
+ injected: string[];
31
+ importDeps: string[];
32
+ providers: string[];
33
+ };
34
+ export type DependencyAnalysisResult = Omit<TransformResult, 'changed'> & {
35
+ classDeclaration?: ClassDeclaration;
36
+ };
37
+ export type ExistingDependencyGroupsResult = {
38
+ found: boolean;
39
+ warnings: string[];
40
+ dependencyGroups: DependencyGroups;
41
+ exportAssignmentNode?: Node;
42
+ depsObjectNode?: Node;
43
+ propertyNodes: Partial<Record<keyof DependencyGroups, Node>>;
44
+ };
45
+ type RunFileReport = TransformResult & {
46
+ filePath: string;
47
+ };
48
+ export type RunSummary = {
49
+ transformedFiles: number;
50
+ skippedFiles: number;
51
+ warnings: number;
52
+ countByAngularKind: Record<AngularKind, number>;
53
+ files: RunFileReport[];
54
+ };
55
+ export declare function transformSourceFile(sourceFile: SourceFile, options?: AngularBrandCodemodOptions): TransformResult;
56
+ export declare function analyzeSourceFileDependencies(sourceFile: SourceFile, options?: AngularBrandCodemodOptions): DependencyAnalysisResult;
57
+ export declare function findAngularDecoratedClass(sourceFile: SourceFile): AngularClassSearchResult;
58
+ export declare function getAngularKind(classDeclaration: ClassDeclaration): AngularKind | undefined;
59
+ export declare function isStandaloneDeclarable(classDeclaration: ClassDeclaration): boolean;
60
+ export declare function extractDecoratorMetadataDeps(classDeclaration: ClassDeclaration, angularKind?: AngularKind | undefined, options?: AngularBrandCodemodOptions): DependencyExtractionResult;
61
+ export declare function extractConstructorDeps(classDeclaration: ClassDeclaration): DependencyExtractionResult;
62
+ export declare function extractInjectCallDeps(classDeclaration: ClassDeclaration): DependencyExtractionResult;
63
+ export declare function mergeDeps(...dependencyGroups: readonly string[][]): string[];
64
+ export declare function ensureHelperImports(sourceFile: SourceFile, helperImportPath: string): void;
65
+ export declare function removeConflictingExports(sourceFile: SourceFile, classDeclaration: ClassDeclaration, className: string): void;
66
+ export declare function writeDefaultBrandExport(sourceFile: SourceFile, className: string, dependencyGroups: DependencyGroups): void;
67
+ export declare function readExistingDependencyGroups(sourceFile: SourceFile, className?: string): ExistingDependencyGroupsResult;
68
+ export declare function formatDependencyGroups(dependencyGroups: DependencyGroups): string;
69
+ export declare function runAngularBrandCodemod(options?: AngularBrandCodemodOptions & {
70
+ rootDir?: string;
71
+ tsConfigFilePath?: string;
72
+ dryRun?: boolean;
73
+ log?: (message: string) => void;
74
+ }): Promise<RunSummary>;
75
+ export {};