@softspark/ai-toolkit 3.0.2 → 3.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.
- package/AGENTS.md +13 -0
- package/CHANGELOG.md +23 -0
- package/README.md +30 -23
- package/app/.claude-plugin/plugin.json +1 -1
- package/app/skills/cpp-rules/SKILL.md +275 -0
- package/app/skills/csharp-rules/SKILL.md +282 -0
- package/app/skills/dart-rules/SKILL.md +299 -0
- package/app/skills/golang-rules/SKILL.md +262 -0
- package/app/skills/java-rules/SKILL.md +273 -0
- package/app/skills/kotlin-rules/SKILL.md +271 -0
- package/app/skills/medplum-rules/SKILL.md +271 -0
- package/app/skills/php-rules/SKILL.md +292 -0
- package/app/skills/python-rules/SKILL.md +257 -0
- package/app/skills/ruby-rules/SKILL.md +286 -0
- package/app/skills/rust-rules/SKILL.md +276 -0
- package/app/skills/swift-rules/SKILL.md +293 -0
- package/app/skills/typescript-rules/SKILL.md +249 -0
- package/benchmarks/ecosystem-doctor-snapshot.json +14 -14
- package/kb/history/completed/deep-coverage-v3-20260423.md +3 -3
- package/kb/history/completed/ecosystem-deep-sweep-20260423.md +1 -1
- package/kb/procedures/release-preparation-sop.md +4 -4
- package/kb/procedures/release-verification-sop.md +11 -12
- package/kb/reference/architecture-overview.md +1 -1
- package/kb/reference/global-install-model.md +29 -6
- package/kb/reference/language-rules.md +54 -18
- package/kb/reference/mcp-editor-compatibility.md +4 -3
- package/kb/reference/mcp-templates.md +3 -2
- package/kb/reference/supported-tools-registry.md +10 -8
- package/llms-full.txt +133 -58
- package/manifest.json +3 -3
- package/package.json +10 -3
- package/scripts/codex_skill_adapter.py +19 -3
- package/scripts/ecosystem_tools.json +7 -7
- package/scripts/generate_cline_rules.py +17 -8
- package/scripts/generate_codex_skills.py +33 -96
- package/scripts/generate_language_rules_skills.py +232 -0
- package/scripts/generate_roo_rules.py +11 -3
- package/scripts/install.py +6 -1
- package/scripts/install_steps/ai_tools.py +154 -51
- package/scripts/install_steps/install_state.py +14 -2
- package/scripts/mcp_editors.py +7 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: csharp-rules
|
|
3
|
+
description: "C#/.NET coding rules from ai-toolkit: coding-style, frameworks, patterns, security, testing. Triggers: .cs, .csproj, .sln, ASP.NET, ASP.NET Core, EF Core, LINQ, NUnit, xUnit, dotnet. Load when writing, reviewing, or editing C#/.NET code."
|
|
4
|
+
effort: medium
|
|
5
|
+
user-invocable: false
|
|
6
|
+
allowed-tools: Read
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# C#/.NET Rules
|
|
10
|
+
|
|
11
|
+
These rules come from `app/rules/csharp/` in ai-toolkit. They cover
|
|
12
|
+
the project's standards for coding style, frameworks, patterns,
|
|
13
|
+
security, and testing in C#/.NET. Apply them when writing or
|
|
14
|
+
reviewing C#/.NET code.
|
|
15
|
+
|
|
16
|
+
# C# Coding Style
|
|
17
|
+
|
|
18
|
+
## Naming
|
|
19
|
+
- PascalCase: classes, structs, enums, interfaces, methods, properties, events.
|
|
20
|
+
- camelCase: local variables, parameters, private fields.
|
|
21
|
+
- Prefix interfaces with `I`: `IUserRepository`, `IDisposable`.
|
|
22
|
+
- Prefix private fields with `_`: `private readonly ILogger _logger;`.
|
|
23
|
+
- UPPER_SNAKE: not conventional in C#. Use PascalCase for constants.
|
|
24
|
+
|
|
25
|
+
## Nullable Reference Types
|
|
26
|
+
- Enable `<Nullable>enable</Nullable>` in all projects.
|
|
27
|
+
- Use `string?` only when null is semantically meaningful.
|
|
28
|
+
- Use `!` (null-forgiving) operator sparingly -- only when compiler cannot infer.
|
|
29
|
+
- Use `??` (null-coalescing) and `?.` (null-conditional) for safe navigation.
|
|
30
|
+
- Use `required` modifier (C# 11) on properties that must be set at initialization.
|
|
31
|
+
|
|
32
|
+
## Records and Types
|
|
33
|
+
- Use `record` for immutable value objects and DTOs.
|
|
34
|
+
- Use `record struct` for small, stack-allocated value types.
|
|
35
|
+
- Use `init` properties for immutable-after-construction objects.
|
|
36
|
+
- Use `with` expressions for non-destructive mutation of records.
|
|
37
|
+
- Use primary constructors (C# 12) for concise class definitions.
|
|
38
|
+
|
|
39
|
+
## Pattern Matching
|
|
40
|
+
- Use `is` pattern for type checks: `if (obj is string s)`.
|
|
41
|
+
- Use `switch` expressions for exhaustive matching over enums/types.
|
|
42
|
+
- Use property patterns: `user is { Age: > 18, Role: "admin" }`.
|
|
43
|
+
- Use relational patterns: `size is > 0 and < 100`.
|
|
44
|
+
- Use list patterns (C# 11): `numbers is [1, 2, .., var last]`.
|
|
45
|
+
|
|
46
|
+
## Async/Await
|
|
47
|
+
- Suffix async methods with `Async`: `GetUserAsync()`.
|
|
48
|
+
- Return `Task<T>` or `ValueTask<T>`, never `void` (except event handlers).
|
|
49
|
+
- Use `await` with `ConfigureAwait(false)` in library code.
|
|
50
|
+
- Use `CancellationToken` parameters in all async public APIs.
|
|
51
|
+
- Prefer `ValueTask<T>` when synchronous completion is common.
|
|
52
|
+
|
|
53
|
+
## File Organization
|
|
54
|
+
- One type per file. File name matches type name.
|
|
55
|
+
- Use file-scoped namespaces (C# 10): `namespace MyApp.Services;`.
|
|
56
|
+
- Order members: fields, constructors, properties, public methods, private methods.
|
|
57
|
+
- Use `global using` directives in a single `GlobalUsings.cs` file.
|
|
58
|
+
|
|
59
|
+
## Formatting
|
|
60
|
+
- Use `.editorconfig` with C# style rules committed to the repository.
|
|
61
|
+
- Use `dotnet format` for automated formatting.
|
|
62
|
+
- Use Roslyn analyzers for compile-time style enforcement.
|
|
63
|
+
- Max line length: 120 characters.
|
|
64
|
+
|
|
65
|
+
# C# Frameworks
|
|
66
|
+
|
|
67
|
+
## ASP.NET Core
|
|
68
|
+
- Use minimal APIs for simple endpoints. Use controllers for complex APIs.
|
|
69
|
+
- Use `[ApiController]` attribute for automatic model validation and error responses.
|
|
70
|
+
- Use `Results.Ok()`, `Results.NotFound()` for typed HTTP results.
|
|
71
|
+
- Use endpoint filters / middleware for cross-cutting concerns.
|
|
72
|
+
- Use `IHostedService` / `BackgroundService` for long-running background tasks.
|
|
73
|
+
- Map routes with `app.MapGet()`, `app.MapPost()` for minimal API style.
|
|
74
|
+
|
|
75
|
+
## Entity Framework Core
|
|
76
|
+
- Use code-first migrations: `dotnet ef migrations add`, `dotnet ef database update`.
|
|
77
|
+
- Use `DbContext` with scoped lifetime (one per request).
|
|
78
|
+
- Use `AsNoTracking()` for read-only queries. Use `AsTracking()` only for updates.
|
|
79
|
+
- Use `Include()` / `ThenInclude()` for eager loading related entities.
|
|
80
|
+
- Use shadow properties for audit fields (`CreatedAt`, `UpdatedAt`).
|
|
81
|
+
- Use `HasQueryFilter()` for soft-delete and multi-tenancy global filters.
|
|
82
|
+
|
|
83
|
+
## Blazor
|
|
84
|
+
- Use Blazor Server for internal tools. Use Blazor WASM for public-facing SPAs.
|
|
85
|
+
- Use `@inject` for dependency injection in components.
|
|
86
|
+
- Use `EventCallback<T>` for parent-child component communication.
|
|
87
|
+
- Use `CascadingValue` for deeply shared state (theme, auth).
|
|
88
|
+
- Use `StateContainer` pattern with events for cross-component state management.
|
|
89
|
+
|
|
90
|
+
## SignalR
|
|
91
|
+
- Use strongly-typed hubs: `Hub<IClientMethods>` for compile-time safety.
|
|
92
|
+
- Use `HubContext<T>` for sending messages from outside hubs.
|
|
93
|
+
- Use groups for targeted broadcasting: `Groups.AddToGroupAsync()`.
|
|
94
|
+
- Configure automatic reconnection on the client side.
|
|
95
|
+
|
|
96
|
+
## MassTransit / Messaging
|
|
97
|
+
- Use MassTransit for message bus abstraction over RabbitMQ/Azure Service Bus.
|
|
98
|
+
- Define messages as `record` types for immutability.
|
|
99
|
+
- Use consumers (`IConsumer<T>`) for message handling.
|
|
100
|
+
- Use sagas for long-running, multi-step workflows with state.
|
|
101
|
+
- Use retry and circuit breaker policies for transient failures.
|
|
102
|
+
|
|
103
|
+
## Logging
|
|
104
|
+
- Use `ILogger<T>` via DI. Never instantiate loggers manually.
|
|
105
|
+
- Use structured logging: `_logger.LogInformation("User {UserId} logged in", userId)`.
|
|
106
|
+
- Use Serilog with sinks for structured, centralized logging.
|
|
107
|
+
- Use log scopes for request correlation: `using (_logger.BeginScope(...))`.
|
|
108
|
+
|
|
109
|
+
## Configuration
|
|
110
|
+
- Use `appsettings.json` + environment-specific overrides + environment variables.
|
|
111
|
+
- Bind configuration sections to strongly-typed classes with `IOptions<T>`.
|
|
112
|
+
- Use `IOptionsMonitor<T>` for configuration that changes at runtime.
|
|
113
|
+
- Validate configuration at startup with `ValidateDataAnnotations()`.
|
|
114
|
+
|
|
115
|
+
## Health Checks
|
|
116
|
+
- Use `app.MapHealthChecks("/health")` for liveness probes.
|
|
117
|
+
- Register custom health checks for database, cache, and external service dependencies.
|
|
118
|
+
- Use `AspNetCore.HealthChecks.*` NuGet packages for common checks.
|
|
119
|
+
|
|
120
|
+
# C# Patterns
|
|
121
|
+
|
|
122
|
+
## Error Handling
|
|
123
|
+
- Use exceptions for truly exceptional conditions. Use `Result<T>` pattern for expected failures.
|
|
124
|
+
- Create domain exception hierarchies: `class DomainException : Exception`.
|
|
125
|
+
- Use `when` clause in catch: `catch (HttpRequestException e) when (e.StatusCode == 404)`.
|
|
126
|
+
- Use `ExceptionDispatchInfo.Capture(e).Throw()` to preserve original stack trace.
|
|
127
|
+
- Return `Result<T, Error>` types for operations with expected failure modes.
|
|
128
|
+
|
|
129
|
+
## Async Patterns
|
|
130
|
+
- Use `Task.WhenAll()` for concurrent independent operations.
|
|
131
|
+
- Use `SemaphoreSlim` for async-compatible resource limiting.
|
|
132
|
+
- Use `Channel<T>` for async producer-consumer patterns.
|
|
133
|
+
- Use `IAsyncEnumerable<T>` for streaming data from async sources.
|
|
134
|
+
- Use `Polly` for retry, circuit breaker, and timeout policies.
|
|
135
|
+
- Never use `.Result` or `.Wait()` on tasks (deadlock risk). Always `await`.
|
|
136
|
+
|
|
137
|
+
## Dependency Injection
|
|
138
|
+
- Use constructor injection exclusively. Avoid service locator pattern.
|
|
139
|
+
- Register services in `Program.cs` or `IServiceCollection` extension methods.
|
|
140
|
+
- Use `Scoped` for request-lifetime services, `Singleton` for stateless, `Transient` for lightweight.
|
|
141
|
+
- Use `IOptions<T>` pattern for configuration injection.
|
|
142
|
+
- Validate DI registrations at startup with `ValidateOnBuild = true`.
|
|
143
|
+
|
|
144
|
+
## LINQ
|
|
145
|
+
- Use method syntax for complex queries. Use query syntax for joins.
|
|
146
|
+
- Use `FirstOrDefault()` over `First()` for safe access.
|
|
147
|
+
- Use `AsNoTracking()` for read-only EF Core queries (performance).
|
|
148
|
+
- Avoid materializing large collections: use `IQueryable<T>` until final projection.
|
|
149
|
+
- Use `Select()` to project only needed columns from database queries.
|
|
150
|
+
|
|
151
|
+
## Disposable Pattern
|
|
152
|
+
- Implement `IAsyncDisposable` for async cleanup.
|
|
153
|
+
- Use `await using var resource = ...;` for deterministic async disposal.
|
|
154
|
+
- Use `IDisposable` with `using` declaration (C# 8) for scope-based cleanup.
|
|
155
|
+
- Register disposable services in DI container (auto-disposed at scope end).
|
|
156
|
+
|
|
157
|
+
## Mediator / CQRS
|
|
158
|
+
- Use MediatR for command/query separation and pipeline behaviors.
|
|
159
|
+
- Commands: `IRequest<Result>` for mutations. Queries: `IRequest<T>` for reads.
|
|
160
|
+
- Use pipeline behaviors for cross-cutting: validation, logging, transactions.
|
|
161
|
+
- Keep handlers thin: delegate to domain services for business logic.
|
|
162
|
+
|
|
163
|
+
## Value Objects
|
|
164
|
+
- Use `record` types for value objects with structural equality.
|
|
165
|
+
- Use factory methods with validation: `public static Result<Email> Create(string value)`.
|
|
166
|
+
- Override `ToString()` for logging-friendly representations.
|
|
167
|
+
- Use implicit/explicit operators sparingly for primitive wrapper conversions.
|
|
168
|
+
|
|
169
|
+
## Anti-Patterns
|
|
170
|
+
- Service locator: inject dependencies, do not resolve from container.
|
|
171
|
+
- `async void`: use only for event handlers. Everything else returns `Task`.
|
|
172
|
+
- Nested `try-catch`: flatten with early returns or guard clauses.
|
|
173
|
+
- Anemic domain model: put behavior in domain objects, not only services.
|
|
174
|
+
- Over-abstracting: do not create interfaces for classes with only one implementation.
|
|
175
|
+
|
|
176
|
+
# C# Security
|
|
177
|
+
|
|
178
|
+
## Input Validation
|
|
179
|
+
- Use data annotations (`[Required]`, `[StringLength]`, `[Range]`) on request models.
|
|
180
|
+
- Use `[ApiController]` for automatic 400 responses on validation failure.
|
|
181
|
+
- Use FluentValidation for complex, rule-based validation logic.
|
|
182
|
+
- Never trust client-provided IDs. Verify resource ownership server-side.
|
|
183
|
+
- Sanitize HTML input with a library like HtmlSanitizer. Never render raw user HTML.
|
|
184
|
+
|
|
185
|
+
## SQL Injection
|
|
186
|
+
- Use EF Core parameterized queries exclusively. Never concatenate SQL.
|
|
187
|
+
- Use `FromSqlInterpolated()` over `FromSqlRaw()` for raw SQL (auto-parameterized).
|
|
188
|
+
- Use stored procedures via `context.Database.ExecuteSqlInterpolatedAsync()`.
|
|
189
|
+
- Audit all `FromSqlRaw()` calls for parameter interpolation risks.
|
|
190
|
+
- Use Dapper with parameterized queries: `@param` syntax in SQL strings.
|
|
191
|
+
|
|
192
|
+
## Authentication
|
|
193
|
+
- Use ASP.NET Core Identity for user management and password hashing.
|
|
194
|
+
- Use `AddAuthentication().AddJwtBearer()` for JWT-based API auth.
|
|
195
|
+
- Use short-lived access tokens (15 min) with refresh token rotation.
|
|
196
|
+
- Use `[Authorize]` attribute globally. Use `[AllowAnonymous]` selectively.
|
|
197
|
+
- Use HTTPS redirection: `app.UseHttpsRedirection()`.
|
|
198
|
+
|
|
199
|
+
## Authorization
|
|
200
|
+
- Use policy-based authorization: `[Authorize(Policy = "AdminOnly")]`.
|
|
201
|
+
- Use `IAuthorizationHandler` for custom authorization logic.
|
|
202
|
+
- Use resource-based authorization for object-level access control.
|
|
203
|
+
- Default deny: apply `[Authorize]` at controller/app level, opt out per endpoint.
|
|
204
|
+
- Check ownership in service layer, not just role membership.
|
|
205
|
+
|
|
206
|
+
## CSRF and XSS
|
|
207
|
+
- Use anti-forgery tokens for form-based submissions.
|
|
208
|
+
- Razor/Blazor auto-encodes output. Never use `@Html.Raw()` with user data.
|
|
209
|
+
- Set `Content-Security-Policy` headers to restrict script sources.
|
|
210
|
+
- Use `SameSite=Strict` on cookies for CSRF mitigation.
|
|
211
|
+
- Enable CORS only for specific origins. Never use `AllowAnyOrigin()` with credentials.
|
|
212
|
+
|
|
213
|
+
## Data Protection
|
|
214
|
+
- Use `IDataProtectionProvider` for symmetric encryption of sensitive data.
|
|
215
|
+
- Use `SecureString` or `ProtectedData` for in-memory sensitive data (limited use).
|
|
216
|
+
- Use ASP.NET Core Data Protection API for token and cookie encryption.
|
|
217
|
+
- Hash passwords with `PasswordHasher<T>` (PBKDF2 with salt).
|
|
218
|
+
|
|
219
|
+
## Secrets Management
|
|
220
|
+
- Use `dotnet user-secrets` for local development. Use Azure Key Vault for production.
|
|
221
|
+
- Use `IConfiguration` with environment variable providers. Never hardcode secrets.
|
|
222
|
+
- Use `[SensitiveData]` attributes to exclude fields from logging and serialization.
|
|
223
|
+
- Never log request headers containing Authorization or cookie values.
|
|
224
|
+
|
|
225
|
+
## Dependency Security
|
|
226
|
+
- Run `dotnet list package --vulnerable` to check for known CVEs.
|
|
227
|
+
- Use Dependabot or NuGetAudit for automated vulnerability scanning.
|
|
228
|
+
- Pin package versions explicitly. Avoid floating version ranges.
|
|
229
|
+
- Update `Microsoft.AspNetCore.*` packages promptly for security patches.
|
|
230
|
+
|
|
231
|
+
# C# Testing
|
|
232
|
+
|
|
233
|
+
## Framework
|
|
234
|
+
- Use xUnit as the primary test framework (modern, extensible).
|
|
235
|
+
- Use NSubstitute for mocking (clean syntax, no setup boilerplate).
|
|
236
|
+
- Use FluentAssertions for readable, expressive assertions.
|
|
237
|
+
- Use Testcontainers for integration tests with databases and services.
|
|
238
|
+
|
|
239
|
+
## File Naming
|
|
240
|
+
- Test files: `FooTests.cs` in a separate `*.Tests` project.
|
|
241
|
+
- Mirror source project namespace structure in test project.
|
|
242
|
+
- Integration tests: separate `*.IntegrationTests` project.
|
|
243
|
+
- Use `[Collection("Database")]` for shared fixtures across test classes.
|
|
244
|
+
|
|
245
|
+
## Structure
|
|
246
|
+
- Use `[Fact]` for single test cases. Use `[Theory]` for parameterized tests.
|
|
247
|
+
- Use `[InlineData]` or `[MemberData]` for test data in theories.
|
|
248
|
+
- Use constructor injection for per-test setup. Use `IClassFixture<T>` for shared setup.
|
|
249
|
+
- Name tests: `MethodName_Scenario_ExpectedResult`.
|
|
250
|
+
|
|
251
|
+
## Assertions (FluentAssertions)
|
|
252
|
+
- Use `result.Should().Be(expected)` for value assertions.
|
|
253
|
+
- Use `action.Should().Throw<InvalidOperationException>()` for exception testing.
|
|
254
|
+
- Use `collection.Should().ContainSingle(x => x.Id == 1)` for collection assertions.
|
|
255
|
+
- Use `result.Should().BeEquivalentTo(expected)` for deep object comparison.
|
|
256
|
+
- Use `execution.Should().CompleteWithinAsync(5.Seconds())` for timeout assertions.
|
|
257
|
+
|
|
258
|
+
## Mocking (NSubstitute)
|
|
259
|
+
- Create mocks: `var repo = Substitute.For<IUserRepository>()`.
|
|
260
|
+
- Stub returns: `repo.GetAsync(1).Returns(user)`.
|
|
261
|
+
- Verify calls: `repo.Received(1).SaveAsync(Arg.Any<User>())`.
|
|
262
|
+
- Use `Arg.Is<T>(predicate)` for argument matching.
|
|
263
|
+
- Use `ReturnsForAnyArgs()` for lenient stubs in arrangement-focused tests.
|
|
264
|
+
|
|
265
|
+
## Integration Testing
|
|
266
|
+
- Use `WebApplicationFactory<Program>` for ASP.NET Core integration tests.
|
|
267
|
+
- Override services with `WithWebHostBuilder(b => b.ConfigureServices(...))`.
|
|
268
|
+
- Use `HttpClient` from factory for endpoint testing.
|
|
269
|
+
- Use `Respawn` for database cleanup between tests.
|
|
270
|
+
- Use `[Collection]` attribute to prevent parallel execution of shared-resource tests.
|
|
271
|
+
|
|
272
|
+
## Test Data
|
|
273
|
+
- Use Builder pattern for complex test data: `new UserBuilder().WithName("Ada").Build()`.
|
|
274
|
+
- Use `AutoFixture` for auto-generated test data.
|
|
275
|
+
- Use `Bogus` library for realistic fake data generation.
|
|
276
|
+
- Keep test data creation close to the test, not in distant shared files.
|
|
277
|
+
|
|
278
|
+
## Best Practices
|
|
279
|
+
- Test behavior, not implementation. Avoid testing private methods.
|
|
280
|
+
- Keep tests independent. No shared mutable state between tests.
|
|
281
|
+
- Use `CancellationToken.None` explicitly in async test calls.
|
|
282
|
+
- Run tests in CI with `dotnet test --blame-hang-timeout 60s`.
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: dart-rules
|
|
3
|
+
description: "Dart/Flutter coding rules from ai-toolkit: coding-style, frameworks, patterns, security, testing. Triggers: .dart, pubspec.yaml, Flutter, Riverpod, Bloc, widget, StatelessWidget, StatefulWidget. Load when writing, reviewing, or editing Dart/Flutter code."
|
|
4
|
+
effort: medium
|
|
5
|
+
user-invocable: false
|
|
6
|
+
allowed-tools: Read
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Dart/Flutter Rules
|
|
10
|
+
|
|
11
|
+
These rules come from `app/rules/dart/` in ai-toolkit. They cover
|
|
12
|
+
the project's standards for coding style, frameworks, patterns,
|
|
13
|
+
security, and testing in Dart/Flutter. Apply them when writing or
|
|
14
|
+
reviewing Dart/Flutter code.
|
|
15
|
+
|
|
16
|
+
# Dart Coding Style
|
|
17
|
+
|
|
18
|
+
## Naming
|
|
19
|
+
- PascalCase: classes, enums, typedefs, extensions, mixins.
|
|
20
|
+
- camelCase: variables, functions, methods, parameters, named constants.
|
|
21
|
+
- snake_case: libraries, packages, directories, source files.
|
|
22
|
+
- UPPER_SNAKE: not used in Dart. Use camelCase for constants.
|
|
23
|
+
- Prefix private members with `_`: `_internalState`, `_helper()`.
|
|
24
|
+
|
|
25
|
+
## Null Safety
|
|
26
|
+
- Enable sound null safety (default since Dart 2.12).
|
|
27
|
+
- Use `?` types only when null is semantically meaningful.
|
|
28
|
+
- Use `!` operator sparingly. Prefer null checks or `??` fallback.
|
|
29
|
+
- Use `late` keyword only when initialization is guaranteed before access.
|
|
30
|
+
- Use `required` keyword for mandatory named parameters.
|
|
31
|
+
|
|
32
|
+
## Classes
|
|
33
|
+
- Use `const` constructors for immutable classes.
|
|
34
|
+
- Use factory constructors for caching, subtype selection, or validation.
|
|
35
|
+
- Use named constructors for clarity: `Point.fromJson(json)`.
|
|
36
|
+
- Use `final` fields for immutable properties.
|
|
37
|
+
- Use `@immutable` annotation on classes that should be immutable.
|
|
38
|
+
|
|
39
|
+
## Functions
|
|
40
|
+
- Use named parameters for functions with >2 parameters.
|
|
41
|
+
- Use `required` for mandatory named parameters.
|
|
42
|
+
- Use default values for optional parameters.
|
|
43
|
+
- Use fat arrow (`=>`) for single-expression functions.
|
|
44
|
+
- Always specify return types for public functions.
|
|
45
|
+
|
|
46
|
+
## Collections
|
|
47
|
+
- Use collection literals: `[]`, `{}`, `<String, int>{}`.
|
|
48
|
+
- Use `if` and `for` inside collection literals for conditional/iterative building.
|
|
49
|
+
- Use spread operator: `[...list1, ...list2]`.
|
|
50
|
+
- Use `whereType<T>()` for type-safe filtering.
|
|
51
|
+
- Prefer `const` collections when values are known at compile time.
|
|
52
|
+
|
|
53
|
+
## Async
|
|
54
|
+
- Use `async`/`await` for all asynchronous operations.
|
|
55
|
+
- Return `Future<T>` from async functions. Never return `void`.
|
|
56
|
+
- Use `Stream<T>` for continuous data (events, real-time updates).
|
|
57
|
+
- Use `Future.wait()` for concurrent independent operations.
|
|
58
|
+
- Use `Completer<T>` only when wrapping callback-based APIs.
|
|
59
|
+
|
|
60
|
+
## Imports
|
|
61
|
+
- Order: `dart:` SDK, `package:` external, relative project imports.
|
|
62
|
+
- Use `show`/`hide` to limit import scope when names conflict.
|
|
63
|
+
- Use `as` prefix for namespace conflicts: `import 'package:foo/foo.dart' as foo`.
|
|
64
|
+
- Prefer relative imports within the same package.
|
|
65
|
+
|
|
66
|
+
## Formatting
|
|
67
|
+
- Use `dart format` (line length 80) for consistent formatting.
|
|
68
|
+
- Use `dart analyze` for static analysis with default lint rules.
|
|
69
|
+
- Use `analysis_options.yaml` with recommended lints: `flutter_lints` or `lints`.
|
|
70
|
+
- Use trailing commas in multi-line argument lists for cleaner diffs.
|
|
71
|
+
|
|
72
|
+
# Dart Frameworks
|
|
73
|
+
|
|
74
|
+
## Flutter
|
|
75
|
+
- Use `StatelessWidget` by default. Use `StatefulWidget` only for local state.
|
|
76
|
+
- Use `const` constructors and `const` widgets for build optimization.
|
|
77
|
+
- Use `Key` parameters for widgets in lists for correct diffing.
|
|
78
|
+
- Extract large `build()` methods into smaller widget classes (not methods).
|
|
79
|
+
- Use `Theme.of(context)` and `TextTheme` for consistent styling.
|
|
80
|
+
|
|
81
|
+
## Navigation
|
|
82
|
+
- Use `GoRouter` for declarative, type-safe routing.
|
|
83
|
+
- Define routes as constants: `static const String home = '/home'`.
|
|
84
|
+
- Use `ShellRoute` for persistent navigation bars across routes.
|
|
85
|
+
- Use `context.go()` for navigation, `context.push()` for stacking.
|
|
86
|
+
- Pass arguments via path parameters or `extra` for complex objects.
|
|
87
|
+
|
|
88
|
+
## Networking
|
|
89
|
+
- Use `dio` for HTTP with interceptors, retry, and cancellation.
|
|
90
|
+
- Use `retrofit` (code gen) for type-safe REST client definitions.
|
|
91
|
+
- Use interceptors for auth token injection and refresh logic.
|
|
92
|
+
- Set timeouts on every request: `connectTimeout`, `receiveTimeout`.
|
|
93
|
+
- Use `CancelToken` for cancelling in-flight requests on navigation.
|
|
94
|
+
|
|
95
|
+
## JSON Serialization
|
|
96
|
+
- Use `json_serializable` (+ `build_runner`) for generated `fromJson`/`toJson`. Default `fieldRename: FieldRename.none` uses Dart property names as-is — combined with Effective Dart `lowerCamelCase`, this produces `camelCase` JSON keys with zero configuration.
|
|
97
|
+
- Flutter docs recommend: *"best if both server and client follow the same naming strategy"* ([Flutter — JSON and serialization](https://docs.flutter.dev/data-and-backend/serialization/json)). When they do, no mapping is needed.
|
|
98
|
+
- When server uses a different convention, prefer `@JsonSerializable(fieldRename: FieldRename.snake)` at the class level (or globally in `build.yaml`) over sprinkling `@JsonKey(name:)` on every field. Community recommendation from the `json_serializable` docs and pub.dev guides.
|
|
99
|
+
- Use individual `@JsonKey(name: '...')` only for exceptional cases: external API with mixed conventions, reserved Dart keyword collision (`class`, `is`, `new`), or legacy field rename during deprecation window. Document the reason in a comment.
|
|
100
|
+
- For enum / status / permission values on the wire: `UPPER_SNAKE_CASE` is the cross-language community consensus (see `common/coding-style.md` — JSON Wire Format Conventions). Dart enum case names themselves stay `lowerCamelCase` per Effective Dart; map them to uppercase strings in `fromJson`/`toJson` (`value.toUpperCase()` + `switch`).
|
|
101
|
+
- Write unit tests asserting both directions (`fromJson` + `toJson`) with explicit expected keys. Catches contract drift at CI time.
|
|
102
|
+
|
|
103
|
+
## Local Storage
|
|
104
|
+
- Use `shared_preferences` for simple key-value persistence.
|
|
105
|
+
- Use `drift` (formerly Moor) for type-safe SQLite with reactive queries.
|
|
106
|
+
- Use `hive` for fast, lightweight NoSQL local storage.
|
|
107
|
+
- Use `flutter_secure_storage` for sensitive data (tokens, passwords).
|
|
108
|
+
- Never store secrets in `shared_preferences` (not encrypted).
|
|
109
|
+
|
|
110
|
+
## Dependency Injection
|
|
111
|
+
- Use `get_it` for service locator pattern. Register at app startup.
|
|
112
|
+
- Use `injectable` (code gen) for automatic registration from annotations.
|
|
113
|
+
- Use Riverpod providers as DI containers for testable architecture.
|
|
114
|
+
- Register singletons for services, factories for per-use instances.
|
|
115
|
+
|
|
116
|
+
## Platform Channels
|
|
117
|
+
- Use `MethodChannel` for invoking native (iOS/Android) code.
|
|
118
|
+
- Use `EventChannel` for streaming data from native to Dart.
|
|
119
|
+
- Use `Pigeon` (code gen) for type-safe platform channel definitions.
|
|
120
|
+
- Handle `MissingPluginException` gracefully on unsupported platforms.
|
|
121
|
+
|
|
122
|
+
## Testing Frameworks
|
|
123
|
+
- Use `flutter_test` for widget tests with `WidgetTester`.
|
|
124
|
+
- Use `integration_test` package for full app integration tests.
|
|
125
|
+
- Use `patrol` for native-aware integration testing (permissions, notifications).
|
|
126
|
+
- Use `golden_toolkit` for advanced visual regression testing.
|
|
127
|
+
|
|
128
|
+
## Build and CI
|
|
129
|
+
- Use `flutter build` with `--release` and `--dart-define` for env configuration.
|
|
130
|
+
- Use flavors (`--flavor`) for dev/staging/prod build variants.
|
|
131
|
+
- Use `flutter analyze` in CI for static analysis enforcement.
|
|
132
|
+
- Use `flutter test --coverage` with `lcov` for coverage reporting.
|
|
133
|
+
|
|
134
|
+
# Dart Patterns
|
|
135
|
+
|
|
136
|
+
## Error Handling
|
|
137
|
+
- Use typed exceptions for domain errors: `class UserNotFoundException implements Exception`.
|
|
138
|
+
- Use `try-catch` with specific exception types. Avoid bare `catch (e)`.
|
|
139
|
+
- Use `rethrow` to preserve stack trace when re-raising exceptions.
|
|
140
|
+
- Use `Result<T, E>` pattern (e.g., `dartz` Either) for expected failures.
|
|
141
|
+
- Use `Future.catchError()` only when `async/await` is not applicable.
|
|
142
|
+
|
|
143
|
+
## State Management (Flutter)
|
|
144
|
+
- Use Riverpod for compile-safe, testable state management.
|
|
145
|
+
- Use BLoC pattern for event-driven state with clear input/output.
|
|
146
|
+
- Use `ChangeNotifier` / `ValueNotifier` for simple local state.
|
|
147
|
+
- Use `StateNotifier` (Riverpod) for immutable state transitions.
|
|
148
|
+
- Keep state classes immutable. Use `copyWith()` for updates.
|
|
149
|
+
|
|
150
|
+
## Riverpod
|
|
151
|
+
- Use `@riverpod` annotation (code gen) for provider definitions.
|
|
152
|
+
- Use `ref.watch()` for reactive dependencies. Use `ref.read()` for one-time access.
|
|
153
|
+
- Use `AsyncNotifier` for async state management.
|
|
154
|
+
- Use `autoDispose` for providers that should clean up when unused.
|
|
155
|
+
- Use `family` modifier for parameterized providers.
|
|
156
|
+
|
|
157
|
+
## BLoC Pattern
|
|
158
|
+
- Separate events (input), states (output), and logic (bloc).
|
|
159
|
+
- Use `sealed class` for events and states (exhaustive `switch`).
|
|
160
|
+
- Use `Emitter<State>` for emitting state transitions.
|
|
161
|
+
- Use `transformEvents()` for debouncing search inputs.
|
|
162
|
+
- Use `BlocObserver` for global logging and error tracking.
|
|
163
|
+
|
|
164
|
+
## Repository Pattern
|
|
165
|
+
- Abstract data sources behind repository interfaces.
|
|
166
|
+
- Repositories return domain models, not DTOs or raw data.
|
|
167
|
+
- Use `Future<T>` for single values, `Stream<T>` for real-time updates.
|
|
168
|
+
- Cache data in repository layer when appropriate.
|
|
169
|
+
- Inject repositories via constructor. Use Riverpod/GetIt for DI.
|
|
170
|
+
|
|
171
|
+
## Freezed (Code Generation)
|
|
172
|
+
- Use `@freezed` for immutable data classes with `copyWith`, equality, `toString`.
|
|
173
|
+
- Use `@freezed` sealed unions for state modeling: `factory State.loading()`.
|
|
174
|
+
- Use `when()` / `map()` for exhaustive pattern matching on freezed unions.
|
|
175
|
+
- Run `dart run build_runner build` after modifying freezed classes.
|
|
176
|
+
|
|
177
|
+
## Async Patterns
|
|
178
|
+
- Use `Stream.asyncMap()` for transforming streams with async operations.
|
|
179
|
+
- Use `StreamController<T>` for custom streams. Close in `dispose()`.
|
|
180
|
+
- Use `Completer<T>` to bridge callback APIs to Future-based APIs.
|
|
181
|
+
- Use `Timer.periodic()` for polling. Cancel in `dispose()`.
|
|
182
|
+
- Use `compute()` (Flutter) for CPU-intensive work on isolates.
|
|
183
|
+
|
|
184
|
+
## Anti-Patterns
|
|
185
|
+
- Using `dynamic` type: defeats type safety. Use `Object?` or generics.
|
|
186
|
+
- Not disposing controllers/subscriptions: causes memory leaks.
|
|
187
|
+
- Putting business logic in widgets: extract to services/blocs.
|
|
188
|
+
- Using `setState()` for global state: use proper state management.
|
|
189
|
+
- Deep widget nesting: extract sub-widgets as separate classes.
|
|
190
|
+
|
|
191
|
+
# Dart Security
|
|
192
|
+
|
|
193
|
+
## Input Validation
|
|
194
|
+
- Validate all user input in form fields with `TextFormField` validators.
|
|
195
|
+
- Use `RegExp` for pattern validation (email, phone, URL).
|
|
196
|
+
- Sanitize HTML content before rendering. Never use `Html` widget with raw user input.
|
|
197
|
+
- Validate deep link parameters before navigation or data loading.
|
|
198
|
+
- Limit text input length with `maxLength` on `TextFormField`.
|
|
199
|
+
|
|
200
|
+
## Network Security
|
|
201
|
+
- Use HTTPS exclusively. Configure `SecurityContext` for certificate pinning.
|
|
202
|
+
- Use `dio` interceptors for consistent auth header injection.
|
|
203
|
+
- Validate SSL certificates in production. Do not disable certificate checks.
|
|
204
|
+
- Set connection and read timeouts on all HTTP requests.
|
|
205
|
+
- Use `CancelToken` to abort requests when the user navigates away.
|
|
206
|
+
|
|
207
|
+
## Data Storage
|
|
208
|
+
- Use `flutter_secure_storage` for tokens, passwords, and API keys.
|
|
209
|
+
- Never store sensitive data in `shared_preferences` (stored in plaintext).
|
|
210
|
+
- Encrypt local databases (`drift` with `sqlcipher`, or `hive` with encryption).
|
|
211
|
+
- Clear secure storage on user logout.
|
|
212
|
+
- Use `kIsWeb` checks to handle web platform storage limitations.
|
|
213
|
+
|
|
214
|
+
## Authentication
|
|
215
|
+
- Use OAuth 2.0 / OIDC with PKCE flow for mobile authentication.
|
|
216
|
+
- Store refresh tokens in secure storage. Store access tokens in memory.
|
|
217
|
+
- Use `flutter_appauth` for standards-compliant OAuth flows.
|
|
218
|
+
- Implement biometric authentication with `local_auth` package.
|
|
219
|
+
- Never store credentials in Dart source code or asset files.
|
|
220
|
+
|
|
221
|
+
## Platform Channel Security
|
|
222
|
+
- Validate all data received from native code via platform channels.
|
|
223
|
+
- Do not pass sensitive data through `MethodChannel` logging-enabled calls.
|
|
224
|
+
- Use `Pigeon` for type-safe channel communication (prevents mismatched types).
|
|
225
|
+
- Handle `PlatformException` gracefully for missing native implementations.
|
|
226
|
+
|
|
227
|
+
## Obfuscation and Hardening
|
|
228
|
+
- Use `--obfuscate --split-debug-info=<dir>` for release builds.
|
|
229
|
+
- Use `--dart-define` for environment-specific configuration (not secrets).
|
|
230
|
+
- Do not embed API keys in the Dart source. Use server-side proxying.
|
|
231
|
+
- Use ProGuard rules (Android) and symbol stripping (iOS) for native code.
|
|
232
|
+
|
|
233
|
+
## WebView Security
|
|
234
|
+
- Use `webview_flutter` with JavaScript disabled unless explicitly needed.
|
|
235
|
+
- Restrict navigation to allowlisted domains with `NavigationDelegate`.
|
|
236
|
+
- Sanitize any data passed from WebView to Dart via JavaScript channels.
|
|
237
|
+
- Do not load untrusted URLs in WebViews.
|
|
238
|
+
|
|
239
|
+
## Dependency Security
|
|
240
|
+
- Run `dart pub outdated` regularly. Update dependencies promptly.
|
|
241
|
+
- Audit `pubspec.lock` for unexpected transitive dependencies.
|
|
242
|
+
- Use `dart pub audit` (when available) for vulnerability scanning.
|
|
243
|
+
- Prefer well-maintained packages with high pub.dev scores.
|
|
244
|
+
- Pin exact versions in `pubspec.yaml` for production apps.
|
|
245
|
+
|
|
246
|
+
# Dart Testing
|
|
247
|
+
|
|
248
|
+
## Framework
|
|
249
|
+
- Use `package:test` for pure Dart unit tests.
|
|
250
|
+
- Use `package:flutter_test` for Flutter widget and integration tests.
|
|
251
|
+
- Use `package:mockito` with `@GenerateMocks` for mock generation.
|
|
252
|
+
- Use `package:mocktail` as a simpler alternative (no code generation).
|
|
253
|
+
|
|
254
|
+
## File Naming
|
|
255
|
+
- Test files: `foo_test.dart` in `test/` mirroring `lib/` structure.
|
|
256
|
+
- Widget tests: `test/widgets/` for Flutter widget tests.
|
|
257
|
+
- Integration tests: `integration_test/` directory (Flutter convention).
|
|
258
|
+
- Golden tests: `test/goldens/` for visual regression snapshots.
|
|
259
|
+
|
|
260
|
+
## Structure
|
|
261
|
+
- Use `group()` for organizing related tests.
|
|
262
|
+
- Use `setUp()` / `tearDown()` for per-test setup and cleanup.
|
|
263
|
+
- Use `setUpAll()` / `tearDownAll()` for expensive one-time setup.
|
|
264
|
+
- Name tests descriptively: `test('returns null when user is not found', ...)`.
|
|
265
|
+
|
|
266
|
+
## Assertions
|
|
267
|
+
- Use `expect(actual, matcher)` with built-in matchers.
|
|
268
|
+
- Use `equals()`, `isNull`, `isNotNull`, `isA<T>()` for type/value checks.
|
|
269
|
+
- Use `throwsA(isA<FormatException>())` for exception testing.
|
|
270
|
+
- Use `completion(expected)` for Future assertions.
|
|
271
|
+
- Use `emitsInOrder([...])` for Stream emission testing.
|
|
272
|
+
|
|
273
|
+
## Mocking (Mockito)
|
|
274
|
+
- Annotate: `@GenerateMocks([UserRepository])`. Run `build_runner`.
|
|
275
|
+
- Stub: `when(mock.getUser(any)).thenAnswer((_) async => user)`.
|
|
276
|
+
- Verify: `verify(mock.saveUser(captureAny)).called(1)`.
|
|
277
|
+
- Use `verifyNever()` to assert a method was not called.
|
|
278
|
+
- Use `throwOnMissingStub()` to catch unstubbed method calls.
|
|
279
|
+
|
|
280
|
+
## Widget Testing (Flutter)
|
|
281
|
+
- Use `testWidgets('description', (tester) async { ... })`.
|
|
282
|
+
- Use `tester.pumpWidget(MaterialApp(home: MyWidget()))` to render.
|
|
283
|
+
- Use `tester.pump()` to trigger rebuilds after state changes.
|
|
284
|
+
- Use `tester.pumpAndSettle()` to wait for animations to complete.
|
|
285
|
+
- Use `find.byType()`, `find.text()`, `find.byKey()` for widget lookups.
|
|
286
|
+
- Use `tester.tap()`, `tester.enterText()` for interaction simulation.
|
|
287
|
+
|
|
288
|
+
## Golden Tests
|
|
289
|
+
- Use `matchesGoldenFile('goldens/my_widget.png')` for visual comparison.
|
|
290
|
+
- Run `flutter test --update-goldens` to regenerate baseline images.
|
|
291
|
+
- Use golden tests for complex UI components, not simple widgets.
|
|
292
|
+
- Keep golden tests platform-specific (render output varies by OS).
|
|
293
|
+
|
|
294
|
+
## Best Practices
|
|
295
|
+
- Test public API behavior, not implementation details.
|
|
296
|
+
- Use `fake` classes (implementing interfaces) for simple test doubles.
|
|
297
|
+
- Use `addTearDown()` to register cleanup in the test body.
|
|
298
|
+
- Run `flutter test --coverage` and check `coverage/lcov.info`.
|
|
299
|
+
- Use `blocTest()` from `bloc_test` package for BLoC testing.
|