Skip to content

Commit 67eed64

Browse files
committed
feat(@angular-devkit/schematics): add schematics to generate ai context files.
* `ng generate ai-config` to prompt support tools. * `ng generate config ai --tool=gemini` to specify the tool. * `ng new --aiConfig=gemini` to create a new project with AI configuration. Supported ai tools: gemini, claude, copilot, windsurf, cursor.
1 parent 5eeebf9 commit 67eed64

File tree

10 files changed

+313
-1
lines changed

10 files changed

+313
-1
lines changed

goldens/public-api/angular_devkit/schematics/index.api.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,10 @@ export enum MergeStrategy {
637637
export function mergeWith(source: Source, strategy?: MergeStrategy): Rule;
638638

639639
// @public (undocumented)
640-
export function move(from: string, to?: string): Rule;
640+
export function move(from: string, to: string): Rule;
641+
642+
// @public (undocumented)
643+
export function move(to: string): Rule;
641644

642645
// @public (undocumented)
643646
export function noop(): Rule;

packages/angular_devkit/schematics/src/rules/move.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import { join, normalize } from '@angular-devkit/core';
1010
import { Rule } from '../engine/interface';
1111
import { noop } from './base';
1212

13+
export function move(from: string, to: string): Rule;
14+
export function move(to: string): Rule;
1315
export function move(from: string, to?: string): Rule {
1416
if (to === undefined) {
1517
to = from;
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<% if (frontmatter) { %><%= frontmatter %>
2+
3+
<% } %>You are an expert in TypeScript, Angular, and scalable web application development. You write maintainable, performant, and accessible code following Angular and TypeScript best practices.
4+
5+
## TypeScript Best Practices
6+
7+
- Use strict type checking
8+
- Prefer type inference when the type is obvious
9+
- Avoid the `any` type; use `unknown` when type is uncertain
10+
11+
## Angular Best Practices
12+
13+
- Always use standalone components over NgModules
14+
- Must NOT set `standalone: true` inside Angular decorators. It's the default.
15+
- Use signals for state management
16+
- Implement lazy loading for feature routes
17+
- Do NOT use the `@HostBinding` and `@HostListener` decorators. Put host bindings inside the `host` object of the `@Component` or `@Directive` decorator instead
18+
- Use `NgOptimizedImage` for all static images.
19+
- `NgOptimizedImage` does not work for inline base64 images.
20+
21+
## Components
22+
23+
- Keep components small and focused on a single responsibility
24+
- Use `input()` and `output()` functions instead of decorators
25+
- Use `computed()` for derived state
26+
- Set `changeDetection: ChangeDetectionStrategy.OnPush` in `@Component` decorator
27+
- Prefer inline templates for small components
28+
- Prefer Reactive forms instead of Template-driven ones
29+
- Do NOT use `ngClass`, use `class` bindings instead
30+
- DO NOT use `ngStyle`, use `style` bindings instead
31+
32+
## State Management
33+
34+
- Use signals for local component state
35+
- Use `computed()` for derived state
36+
- Keep state transformations pure and predictable
37+
- Do NOT use `mutate` on signals, use `update` or `set` instead
38+
39+
## Templates
40+
41+
- Keep templates simple and avoid complex logic
42+
- Use native control flow (`@if`, `@for`, `@switch`) instead of `*ngIf`, `*ngFor`, `*ngSwitch`
43+
- Use the async pipe to handle observables
44+
45+
## Services
46+
47+
- Design services around a single responsibility
48+
- Use the `providedIn: 'root'` option for singleton services
49+
- Use the `inject()` function instead of constructor injection
50+
51+
## Common pitfalls
52+
53+
- Control flow (`@if`):
54+
- You cannot use `as` expressions in `@else if (...)`. E.g. invalid code: `@else if (bla(); as x)`.
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import {
10+
Rule,
11+
SchematicsException,
12+
apply,
13+
applyTemplates,
14+
chain,
15+
filter,
16+
mergeWith,
17+
move,
18+
strings,
19+
url,
20+
} from '@angular-devkit/schematics';
21+
import { posix as path } from 'node:path';
22+
import { getWorkspace as readWorkspace } from '../utility/workspace';
23+
import { Schema as ConfigOptions, Tool } from './schema';
24+
25+
const geminiFile: ContextFileInfo = { rulesName: 'GEMINI.md', directory: '.gemini' };
26+
const copilotFile: ContextFileInfo = {
27+
rulesName: 'copilot-instructions.md',
28+
directory: '.github',
29+
};
30+
const claudeFile: ContextFileInfo = { rulesName: 'CLAUDE.md', directory: '.claude' };
31+
const windsurfFile: ContextFileInfo = {
32+
rulesName: 'guidelines.md',
33+
directory: path.join('.windsurf', 'rules'),
34+
};
35+
36+
// Cursor file is a bit different, it has a front matter section.
37+
const cursorFile: ContextFileInfo = {
38+
rulesName: 'cursor.mdc',
39+
directory: path.join('.cursor', 'rules'),
40+
frontmatter: `---\ncontext: true\npriority: high\nscope: project\n---`,
41+
};
42+
43+
const AI_TOOLS = {
44+
'gemini': geminiFile,
45+
'claude': claudeFile,
46+
'copilot': copilotFile,
47+
'cursor': cursorFile,
48+
'windsurf': windsurfFile,
49+
};
50+
51+
export default function (options: ConfigOptions): Rule {
52+
return addAiContextFile(options);
53+
}
54+
55+
interface ContextFileInfo {
56+
rulesName: string;
57+
directory: string;
58+
frontmatter?: string;
59+
}
60+
61+
function addAiContextFile(options: ConfigOptions): Rule {
62+
const selectedTools: Tool[] = options.tool;
63+
const files: ContextFileInfo[] = selectedTools.map(
64+
(selectedTool: keyof typeof AI_TOOLS) => AI_TOOLS[selectedTool],
65+
);
66+
67+
return async (host) => {
68+
const workspace = await readWorkspace(host);
69+
const project = workspace.projects.get(options.project);
70+
if (!project) {
71+
throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`);
72+
}
73+
74+
const rules = files.map(({ rulesName, directory, frontmatter }) =>
75+
mergeWith(
76+
apply(url('./files'), [
77+
// Keep only the single source template
78+
filter((p) => p.endsWith('__rulesName__.template')),
79+
applyTemplates({
80+
...strings,
81+
rulesName,
82+
frontmatter: frontmatter ?? '',
83+
}),
84+
move(directory),
85+
]),
86+
),
87+
);
88+
89+
return chain(rules);
90+
};
91+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
10+
import { Schema as ApplicationOptions } from '../application/schema';
11+
import { Schema as WorkspaceOptions } from '../workspace/schema';
12+
import { Schema as ConfigOptions, Tool as ConfigTool } from './schema';
13+
14+
describe('Ai Config Schematic', () => {
15+
const schematicRunner = new SchematicTestRunner(
16+
'@schematics/angular',
17+
require.resolve('../collection.json'),
18+
);
19+
20+
const workspaceOptions: WorkspaceOptions = {
21+
name: 'workspace',
22+
newProjectRoot: 'projects',
23+
version: '15.0.0',
24+
};
25+
26+
const defaultAppOptions: ApplicationOptions = {
27+
name: 'foo',
28+
inlineStyle: true,
29+
inlineTemplate: true,
30+
routing: false,
31+
skipPackageJson: false,
32+
};
33+
34+
let applicationTree: UnitTestTree;
35+
function runConfigSchematic(tool: ConfigTool[]): Promise<UnitTestTree> {
36+
return schematicRunner.runSchematic<ConfigOptions>(
37+
'ai-config',
38+
{
39+
project: 'foo',
40+
tool,
41+
},
42+
applicationTree,
43+
);
44+
}
45+
46+
beforeEach(async () => {
47+
const workspaceTree = await schematicRunner.runSchematic('workspace', workspaceOptions);
48+
applicationTree = await schematicRunner.runSchematic(
49+
'application',
50+
defaultAppOptions,
51+
workspaceTree,
52+
);
53+
});
54+
55+
it('should create a GEMINI.MD file', async () => {
56+
const tree = await runConfigSchematic([ConfigTool.Gemini]);
57+
expect(tree.readContent('.gemini/GEMINI.md')).toMatch(/^You are an expert in TypeScript/);
58+
});
59+
60+
it('should create a copilot-instructions.md file', async () => {
61+
const tree = await runConfigSchematic([ConfigTool.Copilot]);
62+
expect(tree.readContent('.github/copilot-instructions.md')).toContain(
63+
'You are an expert in TypeScript',
64+
);
65+
});
66+
67+
it('should create a cursor file', async () => {
68+
const tree = await runConfigSchematic([ConfigTool.Cursor]);
69+
const cursorFile = tree.readContent('.cursor/rules/cursor.mdc');
70+
expect(cursorFile).toContain('You are an expert in TypeScript');
71+
expect(cursorFile).toContain('context: true');
72+
expect(cursorFile).toContain('---\n\nYou are an expert in TypeScript');
73+
});
74+
75+
it('should create a windsurf file', async () => {
76+
const tree = await runConfigSchematic([ConfigTool.Windsurf]);
77+
expect(tree.readContent('.windsurf/rules/guidelines.md')).toContain(
78+
'You are an expert in TypeScript',
79+
);
80+
});
81+
82+
it('should create a claude file', async () => {
83+
const tree = await runConfigSchematic([ConfigTool.Claude]);
84+
expect(tree.readContent('.claude/CLAUDE.md')).toContain('You are an expert in TypeScript');
85+
});
86+
87+
it('should create multiple files when multiple tools are selected', async () => {
88+
const tree = await runConfigSchematic([
89+
ConfigTool.Gemini,
90+
ConfigTool.Copilot,
91+
ConfigTool.Cursor,
92+
]);
93+
expect(tree.readContent('.gemini/GEMINI.md').length).toBeGreaterThan(0);
94+
expect(tree.readContent('.github/copilot-instructions.md').length).toBeGreaterThan(0);
95+
expect(tree.readContent('.cursor/rules/cursor.mdc').length).toBeGreaterThan(0);
96+
});
97+
});
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema",
3+
"$id": "SchematicsAngularConfig",
4+
"title": "Angular Config File Options Schema",
5+
"type": "object",
6+
"additionalProperties": false,
7+
"description": "Generates configuration files for your project. These files control various aspects of your project's build process, testing, and browser compatibility. This schematic helps you create or update essential configuration files with ease.",
8+
"properties": {
9+
"project": {
10+
"type": "string",
11+
"description": "The name of the project where the configuration file should be created or updated.",
12+
"$default": {
13+
"$source": "projectName"
14+
}
15+
},
16+
"tool": {
17+
"type": "array",
18+
"uniqueItems": true,
19+
"x-prompt": "Which AI tool would you like to configure?",
20+
"description": "The AI tool for which the configuration file is being generated. This can include tools like Gemini, Copilot, Claude, Cursor, or Windsurf.",
21+
"minItems": 1,
22+
"items": {
23+
"type": "string",
24+
"enum": ["gemini", "copilot", "claude", "cursor", "windsurf"]
25+
}
26+
}
27+
},
28+
"required": ["project", "tool"]
29+
}

packages/schematics/angular/collection.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@
131131
"factory": "./config",
132132
"schema": "./config/schema.json",
133133
"description": "Generates a configuration file."
134+
},
135+
"ai-config": {
136+
"factory": "./ai-config",
137+
"schema": "./ai-config/schema.json",
138+
"description": "Generates an AI tool configuration file."
134139
}
135140
}
136141
}

packages/schematics/angular/ng-new/index.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
NodePackageInstallTask,
2323
RepositoryInitializerTask,
2424
} from '@angular-devkit/schematics/tasks';
25+
import { Tool as AiTool, Schema as ConfigOptions } from '../ai-config/schema';
2526
import { Schema as ApplicationOptions } from '../application/schema';
2627
import { Schema as WorkspaceOptions } from '../workspace/schema';
2728
import { Schema as NgNewOptions } from './schema';
@@ -60,11 +61,19 @@ export default function (options: NgNewOptions): Rule {
6061
zoneless: options.zoneless,
6162
};
6263

64+
const configOptions: ConfigOptions | undefined = options.aiConfig?.length
65+
? {
66+
project: options.name,
67+
tool: options.aiConfig as unknown as AiTool[],
68+
}
69+
: undefined;
70+
6371
return chain([
6472
mergeWith(
6573
apply(empty(), [
6674
schematic('workspace', workspaceOptions),
6775
options.createApplication ? schematic('application', applicationOptions) : noop,
76+
configOptions ? schematic('ai-config', configOptions) : noop,
6877
move(options.directory),
6978
]),
7079
),

packages/schematics/angular/ng-new/index_spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,4 +103,16 @@ describe('Ng New Schematic', () => {
103103
const { cli } = JSON.parse(tree.readContent('/bar/angular.json'));
104104
expect(cli.packageManager).toBe('npm');
105105
});
106+
107+
it('should add ai config file when aiConfig is set', async () => {
108+
const options = { ...defaultOptions, aiConfig: ['gemini', 'claude'] };
109+
110+
const tree = await schematicRunner.runSchematic('ng-new', options);
111+
const files = tree.files;
112+
expect(files).toContain('/bar/.gemini/GEMINI.md');
113+
expect(files).toContain('/bar/.claude/CLAUDE.md');
114+
115+
expect(tree.readContent('/bar/.gemini/GEMINI.md')).toMatch(/^You are an expert in TypeScript/);
116+
expect(tree.readContent('/bar/.claude/CLAUDE.md')).toMatch(/^You are an expert in TypeScript/);
117+
});
106118
});

packages/schematics/angular/ng-new/schema.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,16 @@
144144
"x-prompt": "Do you want to create a 'zoneless' application without zone.js (Developer Preview)?",
145145
"type": "boolean",
146146
"default": false
147+
},
148+
"aiConfig": {
149+
"type": "array",
150+
"default": [],
151+
"uniqueItems": true,
152+
"description": "Create an AI configuration file for the project. This file is used to improve the outputs of AI tools by following the best practices.",
153+
"items": {
154+
"type": "string",
155+
"enum": ["gemini", "copilot", "claude", "cursor", "windsurf"]
156+
}
147157
}
148158
},
149159
"required": ["name", "version"]

0 commit comments

Comments
 (0)