@defai.digital/automatosx 12.8.7 → 13.1.3

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 (130) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +48 -754
  3. package/dist/bin.d.ts +8 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +16 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/index.d.ts +8 -2
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +7 -74239
  10. package/dist/index.js.map +1 -0
  11. package/package.json +35 -160
  12. package/.github/assets/ax-cli.png +0 -0
  13. package/.github/assets/axlogo.png +0 -0
  14. package/CHANGELOG.md +0 -81
  15. package/SECURITY.md +0 -173
  16. package/dist/mcp/index.d.ts +0 -2
  17. package/dist/mcp/index.js +0 -43627
  18. package/examples/AGENTS_INFO.md +0 -187
  19. package/examples/README.md +0 -434
  20. package/examples/abilities/accessibility.md +0 -115
  21. package/examples/abilities/api-design.md +0 -168
  22. package/examples/abilities/best-practices.md +0 -102
  23. package/examples/abilities/caching-strategy.md +0 -165
  24. package/examples/abilities/ci-cd.md +0 -61
  25. package/examples/abilities/clean-code.md +0 -398
  26. package/examples/abilities/code-generation.md +0 -333
  27. package/examples/abilities/code-review.md +0 -51
  28. package/examples/abilities/component-architecture.md +0 -112
  29. package/examples/abilities/content-creation.md +0 -97
  30. package/examples/abilities/data-modeling.md +0 -171
  31. package/examples/abilities/data-validation.md +0 -50
  32. package/examples/abilities/db-modeling.md +0 -167
  33. package/examples/abilities/debugging.md +0 -52
  34. package/examples/abilities/design-patterns.md +0 -437
  35. package/examples/abilities/design-system-implementation.md +0 -126
  36. package/examples/abilities/documentation.md +0 -54
  37. package/examples/abilities/etl-pipelines.md +0 -44
  38. package/examples/abilities/feasibility-study.md +0 -20
  39. package/examples/abilities/general-assistance.md +0 -26
  40. package/examples/abilities/idea-evaluation.md +0 -21
  41. package/examples/abilities/infra-as-code.md +0 -57
  42. package/examples/abilities/job-orchestration.md +0 -44
  43. package/examples/abilities/literature-review.md +0 -19
  44. package/examples/abilities/longform-report.md +0 -25
  45. package/examples/abilities/mathematical-reasoning.md +0 -170
  46. package/examples/abilities/observability.md +0 -61
  47. package/examples/abilities/orbital-mechanics.md +0 -50
  48. package/examples/abilities/our-architecture-decisions.md +0 -180
  49. package/examples/abilities/our-code-review-checklist.md +0 -149
  50. package/examples/abilities/our-coding-standards.md +0 -369
  51. package/examples/abilities/our-project-structure.md +0 -183
  52. package/examples/abilities/performance.md +0 -89
  53. package/examples/abilities/problem-solving.md +0 -50
  54. package/examples/abilities/propulsion-systems.md +0 -50
  55. package/examples/abilities/quantum-algorithm-design.md +0 -54
  56. package/examples/abilities/quantum-error-correction.md +0 -56
  57. package/examples/abilities/quantum-frameworks-transpilation.md +0 -53
  58. package/examples/abilities/quantum-noise-modeling.md +0 -58
  59. package/examples/abilities/refactoring.md +0 -223
  60. package/examples/abilities/release-strategy.md +0 -58
  61. package/examples/abilities/secrets-policy.md +0 -61
  62. package/examples/abilities/secure-coding-review.md +0 -60
  63. package/examples/abilities/software-architecture.md +0 -394
  64. package/examples/abilities/solid-principles.md +0 -341
  65. package/examples/abilities/sql-optimization.md +0 -84
  66. package/examples/abilities/state-management.md +0 -96
  67. package/examples/abilities/task-planning.md +0 -65
  68. package/examples/abilities/technical-writing.md +0 -77
  69. package/examples/abilities/telemetry-diagnostics.md +0 -51
  70. package/examples/abilities/testing.md +0 -56
  71. package/examples/abilities/threat-modeling.md +0 -58
  72. package/examples/abilities/troubleshooting.md +0 -80
  73. package/examples/abilities/typescript-zod-validation.md +0 -830
  74. package/examples/agents/AGENTS_INTEGRATION.md +0 -99
  75. package/examples/agents/aerospace-scientist.yaml +0 -159
  76. package/examples/agents/architecture.yaml +0 -244
  77. package/examples/agents/automatosx.config.json +0 -286
  78. package/examples/agents/backend.yaml +0 -141
  79. package/examples/agents/ceo.yaml +0 -105
  80. package/examples/agents/creative-marketer.yaml +0 -173
  81. package/examples/agents/cto.yaml +0 -118
  82. package/examples/agents/data-scientist.yaml +0 -200
  83. package/examples/agents/data.yaml +0 -106
  84. package/examples/agents/design.yaml +0 -115
  85. package/examples/agents/devops.yaml +0 -124
  86. package/examples/agents/frontend.yaml +0 -171
  87. package/examples/agents/fullstack.yaml +0 -172
  88. package/examples/agents/mobile.yaml +0 -185
  89. package/examples/agents/product.yaml +0 -103
  90. package/examples/agents/quality.yaml +0 -117
  91. package/examples/agents/quantum-engineer.yaml +0 -166
  92. package/examples/agents/researcher.yaml +0 -122
  93. package/examples/agents/security.yaml +0 -115
  94. package/examples/agents/standard.yaml +0 -214
  95. package/examples/agents/writer.yaml +0 -122
  96. package/examples/providers/README.md +0 -117
  97. package/examples/providers/claude/CLAUDE_INTEGRATION.md +0 -302
  98. package/examples/providers/claude/mcp/automatosx.json +0 -244
  99. package/examples/providers/codex/CODEX_INTEGRATION.md +0 -593
  100. package/examples/providers/codex/README.md +0 -349
  101. package/examples/providers/codex/usage-examples.ts +0 -421
  102. package/examples/providers/gemini/GEMINI_INTEGRATION.md +0 -236
  103. package/examples/providers/gemini/README.md +0 -76
  104. package/examples/providers/openai-codex-example.ts +0 -421
  105. package/examples/pytorch_resnet50_training.py +0 -289
  106. package/examples/specs/automatosx-release.ax.yaml +0 -380
  107. package/examples/specs/enterprise.ax.yaml +0 -121
  108. package/examples/specs/enterprise.yaml.mustache +0 -121
  109. package/examples/specs/government.ax.yaml +0 -148
  110. package/examples/specs/government.yaml.mustache +0 -148
  111. package/examples/specs/minimal.ax.yaml +0 -21
  112. package/examples/specs/minimal.yaml.mustache +0 -21
  113. package/examples/teams/business.yaml +0 -56
  114. package/examples/teams/core.yaml +0 -60
  115. package/examples/teams/design.yaml +0 -58
  116. package/examples/teams/engineering.yaml +0 -69
  117. package/examples/teams/research.yaml +0 -56
  118. package/examples/use-cases/01-web-app-development.md +0 -374
  119. package/examples/workflows/analyst.yaml +0 -60
  120. package/examples/workflows/assistant.yaml +0 -48
  121. package/examples/workflows/basic-agent.yaml +0 -28
  122. package/examples/workflows/code-reviewer.yaml +0 -52
  123. package/examples/workflows/debugger.yaml +0 -63
  124. package/examples/workflows/designer.yaml +0 -69
  125. package/examples/workflows/developer.yaml +0 -60
  126. package/examples/workflows/fullstack-developer.yaml +0 -395
  127. package/examples/workflows/qa-specialist.yaml +0 -71
  128. package/schema/ability-metadata.json +0 -21
  129. package/schema/config.json +0 -703
  130. package/schema/spec-schema.json +0 -608
@@ -1,398 +0,0 @@
1
- # Clean Code Ability
2
-
3
- Expert knowledge and application of clean code principles for writing maintainable, readable, and high-quality software.
4
-
5
- ## Overview
6
-
7
- Clean code is code that is easy to read, understand, and modify. It communicates intent clearly and minimizes cognitive load for future developers (including yourself).
8
-
9
- ## Fundamental Principles
10
-
11
- ### 1. Meaningful Names
12
-
13
- **Rule**: Names should reveal intent without requiring comments
14
-
15
- **Guidelines**:
16
- - Use intention-revealing names
17
- - Avoid disinformation and encodings
18
- - Make meaningful distinctions
19
- - Use pronounceable and searchable names
20
- - Avoid mental mapping
21
-
22
- **Examples**:
23
- ```typescript
24
- // ❌ BAD: Cryptic names
25
- const d = new Date(); // elapsed time in days
26
- const arr = ['Bob', 'Alice'];
27
-
28
- // ✅ GOOD: Intention-revealing
29
- const elapsedTimeInDays = new Date();
30
- const userNames = ['Bob', 'Alice'];
31
-
32
- // ❌ BAD: Hungarian notation, noise words
33
- const strName = 'Bob';
34
- const userData = { name: 'Bob' };
35
- const userInfo = { name: 'Bob' }; // What's the difference?
36
-
37
- // ✅ GOOD: Clean, semantic names
38
- const userName = 'Bob';
39
- const user = { name: 'Bob' };
40
- const userProfile = { name: 'Bob', bio: '...' };
41
- ```
42
-
43
- **Variable Naming**:
44
- - Use nouns or noun phrases
45
- - Boolean: `isActive`, `hasPermission`, `canEdit`
46
- - Collections: Use plural (`users`, `orders`, `products`)
47
-
48
- **Function Naming**:
49
- - Use verbs or verb phrases
50
- - `getUser()`, `calculateTotal()`, `validateInput()`
51
- - Boolean returning: `isValid()`, `hasErrors()`, `canProceed()`
52
-
53
- **Class Naming**:
54
- - Use nouns
55
- - Avoid "Manager", "Processor", "Data" suffixes
56
- - `UserRepository`, `EmailService`, `OrderValidator`
57
-
58
- ### 2. Functions
59
-
60
- **Rule**: Functions should do one thing, do it well, and do it only
61
-
62
- **Small Functions**:
63
- - Keep functions small (< 20 lines ideal)
64
- - Each function should be one level of abstraction
65
- - Functions should not have side effects
66
-
67
- **Single Responsibility**:
68
- ```typescript
69
- // ❌ BAD: Multiple responsibilities
70
- function processUser(user: User) {
71
- validateUser(user);
72
- saveToDatabase(user);
73
- sendEmail(user);
74
- logAudit(user);
75
- updateCache(user);
76
- }
77
-
78
- // ✅ GOOD: Single responsibility
79
- function registerUser(user: User) {
80
- const validated = validateUser(user);
81
- return userRepository.save(validated);
82
- }
83
-
84
- function notifyUserRegistered(user: User) {
85
- emailService.sendWelcome(user);
86
- auditLogger.log('USER_REGISTERED', user.id);
87
- }
88
- ```
89
-
90
- **Function Arguments**:
91
- - Zero arguments (niladic) is ideal
92
- - One argument (monadic) is good
93
- - Two arguments (dyadic) are okay
94
- - Three+ arguments (triadic+) require justification
95
- - Avoid flag arguments (split into two functions)
96
-
97
- **Examples**:
98
- ```typescript
99
- // ❌ BAD: Too many arguments
100
- function createUser(name: string, email: string, age: number, role: string, active: boolean) {}
101
-
102
- // ✅ GOOD: Use object parameter
103
- function createUser(userData: UserData) {}
104
-
105
- // ❌ BAD: Flag argument
106
- function saveUser(user: User, validate: boolean) {}
107
-
108
- // ✅ GOOD: Separate functions
109
- function saveUser(user: User) {}
110
- function saveUserWithoutValidation(user: User) {}
111
- ```
112
-
113
- **Command Query Separation**:
114
- - Functions should either DO something or ANSWER something, not both
115
- - Commands modify state, queries return values
116
-
117
- ```typescript
118
- // ❌ BAD: Does both
119
- function setAndReturn(value: string): boolean {
120
- this.value = value; // Command
121
- return this.value === value; // Query
122
- }
123
-
124
- // ✅ GOOD: Separated
125
- function setValue(value: string): void {
126
- this.value = value;
127
- }
128
-
129
- function getValue(): string {
130
- return this.value;
131
- }
132
- ```
133
-
134
- ### 3. Comments
135
-
136
- **Rule**: Good code mostly documents itself; use comments wisely
137
-
138
- **When to Comment**:
139
- - Explain WHY, not WHAT
140
- - Clarify complex business rules
141
- - Warn of consequences
142
- - TODO/FIXME notes (with tickets)
143
- - Legal comments (copyright, license)
144
- - API documentation (JSDoc, docstrings)
145
-
146
- **When NOT to Comment**:
147
- - Don't comment bad code, rewrite it
148
- - Avoid redundant comments
149
- - Don't comment out code (use version control)
150
- - Avoid journal comments
151
- - Avoid position markers
152
-
153
- **Examples**:
154
- ```typescript
155
- // ❌ BAD: Redundant comments
156
- // Get the user by ID
157
- function getUserById(id: string): User {
158
- // Return the user
159
- return users.find(u => u.id === id);
160
- }
161
-
162
- // ✅ GOOD: Self-documenting code
163
- function getUserById(id: string): User {
164
- return users.find(u => u.id === id);
165
- }
166
-
167
- // ❌ BAD: Commented-out code
168
- function processOrder(order: Order) {
169
- // validateOrder(order);
170
- // checkInventory(order);
171
- saveOrder(order);
172
- }
173
-
174
- // ✅ GOOD: Clear intent without noise
175
- /**
176
- * Processes order for payment and fulfillment.
177
- * NOTE: Validation and inventory check are handled upstream.
178
- */
179
- function processOrder(order: Order) {
180
- saveOrder(order);
181
- }
182
- ```
183
-
184
- ### 4. Formatting
185
-
186
- **Rule**: Code formatting is about communication
187
-
188
- **Vertical Formatting**:
189
- - Small files are better (< 500 lines)
190
- - Blank lines separate concepts
191
- - Related code should be close together
192
- - Declare variables close to usage
193
- - Dependent functions should be close
194
-
195
- **Horizontal Formatting**:
196
- - Keep lines short (< 120 characters)
197
- - Use whitespace to associate related things
198
- - Indent to show hierarchy
199
-
200
- **Example**:
201
- ```typescript
202
- // ✅ GOOD: Well-formatted
203
- class UserService {
204
- constructor(
205
- private userRepository: UserRepository,
206
- private emailService: EmailService
207
- ) {}
208
-
209
- async registerUser(userData: UserData): Promise<User> {
210
- const validated = this.validateUserData(userData);
211
- const user = await this.userRepository.create(validated);
212
- await this.sendWelcomeEmail(user);
213
- return user;
214
- }
215
-
216
- private validateUserData(userData: UserData): UserData {
217
- if (!userData.email) throw new Error('Email required');
218
- if (!userData.name) throw new Error('Name required');
219
- return userData;
220
- }
221
-
222
- private async sendWelcomeEmail(user: User): Promise<void> {
223
- await this.emailService.send(user.email, 'Welcome!');
224
- }
225
- }
226
- ```
227
-
228
- ### 5. Objects and Data Structures
229
-
230
- **Rule**: Objects hide data, expose behavior. Data structures expose data, have no behavior.
231
-
232
- **Law of Demeter**:
233
- - Don't talk to strangers
234
- - Method should only call methods on:
235
- - Itself
236
- - Its parameters
237
- - Objects it creates
238
- - Its direct dependencies
239
-
240
- ```typescript
241
- // ❌ BAD: Violates Law of Demeter (train wreck)
242
- const street = user.getAddress().getStreet().getName();
243
-
244
- // ✅ GOOD: Tell, don't ask
245
- const street = user.getStreetName();
246
-
247
- // Inside User class:
248
- getStreetName(): string {
249
- return this.address.street.name;
250
- }
251
- ```
252
-
253
- ### 6. Error Handling
254
-
255
- **Rule**: Error handling is important, but it shouldn't obscure logic
256
-
257
- **Use Exceptions**:
258
- ```typescript
259
- // ❌ BAD: Error codes
260
- function processPayment(amount: number): number {
261
- if (amount <= 0) return -1;
262
- if (insufficientFunds()) return -2;
263
- return 0; // success
264
- }
265
-
266
- // ✅ GOOD: Exceptions
267
- function processPayment(amount: number): void {
268
- if (amount <= 0) {
269
- throw new InvalidAmountError('Amount must be positive');
270
- }
271
- if (insufficientFunds()) {
272
- throw new InsufficientFundsError('Not enough balance');
273
- }
274
- // Process payment
275
- }
276
- ```
277
-
278
- **Don't Return Null**:
279
- ```typescript
280
- // ❌ BAD: Null checks everywhere
281
- const users = getUsers();
282
- if (users !== null) {
283
- for (const user of users) {
284
- if (user !== null) {
285
- // ...
286
- }
287
- }
288
- }
289
-
290
- // ✅ GOOD: Return empty collection
291
- function getUsers(): User[] {
292
- return users ?? [];
293
- }
294
-
295
- // Or use Optional/Maybe pattern
296
- function getUserById(id: string): User | undefined {
297
- return users.find(u => u.id === id);
298
- }
299
- ```
300
-
301
- ### 7. DRY (Don't Repeat Yourself)
302
-
303
- **Rule**: Every piece of knowledge should have a single representation in the system
304
-
305
- ```typescript
306
- // ❌ BAD: Duplication
307
- function calculateOrderTotal(order: Order): number {
308
- let total = 0;
309
- for (const item of order.items) {
310
- total += item.price * item.quantity;
311
- }
312
- total += total * 0.1; // Tax
313
- total += 5; // Shipping
314
- return total;
315
- }
316
-
317
- function calculateInvoiceTotal(invoice: Invoice): number {
318
- let total = 0;
319
- for (const item of invoice.items) {
320
- total += item.price * item.quantity;
321
- }
322
- total += total * 0.1; // Tax
323
- total += 5; // Shipping
324
- return total;
325
- }
326
-
327
- // ✅ GOOD: Extract common logic
328
- function calculateSubtotal(items: Item[]): number {
329
- return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
330
- }
331
-
332
- function addTaxAndShipping(subtotal: number): number {
333
- const tax = subtotal * 0.1;
334
- const shipping = 5;
335
- return subtotal + tax + shipping;
336
- }
337
-
338
- function calculateTotal(items: Item[]): number {
339
- const subtotal = calculateSubtotal(items);
340
- return addTaxAndShipping(subtotal);
341
- }
342
- ```
343
-
344
- ## Code Quality Checklist
345
-
346
- **Naming**:
347
- - [ ] All names reveal intent
348
- - [ ] No abbreviations or encodings
349
- - [ ] Boolean names start with is/has/can
350
- - [ ] Collections are plural
351
- - [ ] Functions are verbs, classes are nouns
352
-
353
- **Functions**:
354
- - [ ] Functions are small (< 20 lines)
355
- - [ ] Functions do one thing
356
- - [ ] One level of abstraction per function
357
- - [ ] Few arguments (prefer 0-2)
358
- - [ ] No flag arguments
359
- - [ ] No side effects
360
-
361
- **Comments**:
362
- - [ ] Comments explain WHY, not WHAT
363
- - [ ] No commented-out code
364
- - [ ] No redundant comments
365
- - [ ] API documentation present where needed
366
-
367
- **Formatting**:
368
- - [ ] Consistent indentation
369
- - [ ] Lines < 120 characters
370
- - [ ] Blank lines separate concepts
371
- - [ ] Related code is together
372
-
373
- **Error Handling**:
374
- - [ ] Use exceptions, not error codes
375
- - [ ] Don't return null (use empty collections or Optional)
376
- - [ ] Exceptions are specific and meaningful
377
-
378
- **General**:
379
- - [ ] No duplication (DRY)
380
- - [ ] Code is self-documenting
381
- - [ ] Tests exist and pass
382
- - [ ] No dead code
383
-
384
- ## The Boy Scout Rule
385
-
386
- **"Leave the code better than you found it."**
387
-
388
- - Clean up small messes when you see them
389
- - Improve names, extract functions, add tests
390
- - Continuous improvement over time
391
- - Don't need permission for small improvements
392
-
393
- ## Further Reading
394
-
395
- - "Clean Code" by Robert C. Martin
396
- - "Code Complete" by Steve McConnell
397
- - "The Pragmatic Programmer" by Hunt and Thomas
398
- - "Refactoring" by Martin Fowler
@@ -1,333 +0,0 @@
1
- # Code Generation
2
-
3
- Generate high-quality, production-ready code following best practices and patterns.
4
-
5
- ## Core Principles
6
-
7
- ### 1. Type Safety & Validation
8
- - Use strong typing (TypeScript interfaces, Python type hints)
9
- - Validate inputs before processing
10
- - Define clear return types
11
- - Use enums for fixed value sets
12
-
13
- ### 2. Error Handling
14
- - Use try-catch for I/O operations
15
- - Provide specific error messages with context
16
- - Log errors appropriately
17
- - Never swallow errors silently
18
- - Return typed error objects or throw typed exceptions
19
-
20
- ### 3. Function Design
21
- - Single responsibility per function
22
- - Clear, descriptive names
23
- - Document complex logic with comments
24
- - Keep functions small (<50 lines)
25
- - Minimize side effects
26
-
27
- ### 4. API Design
28
- - RESTful conventions (GET/POST/PUT/DELETE)
29
- - Consistent response formats
30
- - Proper HTTP status codes
31
- - Request/response validation
32
- - API versioning when needed
33
-
34
- ### 5. Testing
35
- - Write unit tests for business logic
36
- - Test error cases and edge conditions
37
- - Use descriptive test names
38
- - Aim for >80% coverage on critical paths
39
- - Mock external dependencies
40
-
41
- ### 6. Code Quality
42
- - Follow project coding standards
43
- - Use linting and formatting tools
44
- - Write self-documenting code
45
- - Keep complexity low (cyclomatic complexity <10)
46
- - Remove dead code and TODOs
47
-
48
- ### 7. Security
49
- - Validate and sanitize all inputs
50
- - Use parameterized queries (prevent SQL injection)
51
- - Never log sensitive data
52
- - Follow principle of least privilege
53
- - Keep dependencies updated
54
-
55
- ### 8. Performance
56
- - Avoid N+1 queries
57
- - Use appropriate data structures
58
- - Cache when beneficial
59
- - Lazy load when possible
60
- - Profile before optimizing
61
-
62
- ## Language-Specific Patterns
63
-
64
- ### TypeScript/JavaScript
65
- - Async/await for promises
66
- - Optional chaining (?.) and nullish coalescing (??)
67
- - Destructuring for cleaner code
68
- - Use const by default, let when needed
69
- - Avoid var
70
-
71
- ### TypeScript with Zod (Preferred for Scripts)
72
-
73
- **IMPORTANT**: When writing JavaScript or TypeScript scripts, always use TypeScript with Zod for runtime type safety and validation.
74
-
75
- #### Why Zod?
76
- - Runtime type validation (catches errors TypeScript can't)
77
- - Schema-based validation with composable schemas
78
- - Automatic type inference (no duplicate type definitions)
79
- - Parse, validate, and transform data in one step
80
- - Excellent error messages for debugging
81
-
82
- #### Installation
83
- ```bash
84
- npm install zod
85
- # or
86
- pnpm add zod
87
- ```
88
-
89
- #### Basic Usage Pattern
90
-
91
- ```typescript
92
- import { z } from 'zod';
93
-
94
- // ✅ Define schema (types are automatically inferred)
95
- const UserSchema = z.object({
96
- id: z.number().positive(),
97
- email: z.string().email(),
98
- name: z.string().min(1).max(100),
99
- age: z.number().int().min(0).max(150).optional(),
100
- role: z.enum(['admin', 'user', 'guest']),
101
- metadata: z.record(z.string(), z.unknown()).optional(),
102
- });
103
-
104
- // Type is automatically inferred from schema
105
- type User = z.infer<typeof UserSchema>;
106
-
107
- // Parse and validate data
108
- function createUser(data: unknown): User {
109
- // Throws ZodError if validation fails
110
- return UserSchema.parse(data);
111
- }
112
-
113
- // Safe parsing (returns success/error object)
114
- function tryCreateUser(data: unknown): User | null {
115
- const result = UserSchema.safeParse(data);
116
- if (result.success) {
117
- return result.data;
118
- } else {
119
- console.error('Validation failed:', result.error.issues);
120
- return null;
121
- }
122
- }
123
- ```
124
-
125
- #### API Request/Response Validation
126
-
127
- ```typescript
128
- import { z } from 'zod';
129
-
130
- // ✅ Input validation schema
131
- const CreatePostSchema = z.object({
132
- title: z.string().min(1).max(200),
133
- content: z.string().min(1),
134
- tags: z.array(z.string()).max(10).optional(),
135
- publishAt: z.string().datetime().optional(),
136
- });
137
-
138
- // ✅ Response schema
139
- const PostResponseSchema = z.object({
140
- id: z.string().uuid(),
141
- title: z.string(),
142
- content: z.string(),
143
- tags: z.array(z.string()),
144
- createdAt: z.string().datetime(),
145
- updatedAt: z.string().datetime(),
146
- });
147
-
148
- type CreatePostInput = z.infer<typeof CreatePostSchema>;
149
- type PostResponse = z.infer<typeof PostResponseSchema>;
150
-
151
- // ✅ API handler with validation
152
- async function createPost(req: Request): Promise<PostResponse> {
153
- // Validate request body
154
- const input = CreatePostSchema.parse(await req.json());
155
-
156
- // Business logic
157
- const post = await db.posts.create({
158
- title: input.title,
159
- content: input.content,
160
- tags: input.tags ?? [],
161
- });
162
-
163
- // Validate response before returning
164
- return PostResponseSchema.parse({
165
- id: post.id,
166
- title: post.title,
167
- content: post.content,
168
- tags: post.tags,
169
- createdAt: post.createdAt.toISOString(),
170
- updatedAt: post.updatedAt.toISOString(),
171
- });
172
- }
173
- ```
174
-
175
- #### Configuration File Validation
176
-
177
- ```typescript
178
- import { z } from 'zod';
179
- import { readFile } from 'fs/promises';
180
-
181
- // ✅ Configuration schema
182
- const ConfigSchema = z.object({
183
- server: z.object({
184
- port: z.number().int().min(1024).max(65535).default(3000),
185
- host: z.string().default('localhost'),
186
- }),
187
- database: z.object({
188
- url: z.string().url(),
189
- poolSize: z.number().int().positive().default(10),
190
- ssl: z.boolean().default(false),
191
- }),
192
- logging: z.object({
193
- level: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
194
- pretty: z.boolean().default(false),
195
- }).optional(),
196
- });
197
-
198
- type Config = z.infer<typeof ConfigSchema>;
199
-
200
- // ✅ Load and validate configuration
201
- async function loadConfig(path: string): Promise<Config> {
202
- const raw = await readFile(path, 'utf-8');
203
- const json = JSON.parse(raw);
204
-
205
- // Parse with defaults applied
206
- return ConfigSchema.parse(json);
207
- }
208
- ```
209
-
210
- #### CLI Argument Validation
211
-
212
- ```typescript
213
- import { z } from 'zod';
214
-
215
- // ✅ CLI arguments schema
216
- const CliArgsSchema = z.object({
217
- input: z.string().min(1),
218
- output: z.string().min(1),
219
- verbose: z.boolean().default(false),
220
- format: z.enum(['json', 'yaml', 'csv']).default('json'),
221
- limit: z.number().int().positive().optional(),
222
- });
223
-
224
- type CliArgs = z.infer<typeof CliArgsSchema>;
225
-
226
- // ✅ Parse CLI arguments
227
- function parseCliArgs(argv: string[]): CliArgs {
228
- const args = {
229
- input: argv[2],
230
- output: argv[3],
231
- verbose: argv.includes('--verbose'),
232
- format: argv.includes('--format')
233
- ? argv[argv.indexOf('--format') + 1]
234
- : undefined,
235
- };
236
-
237
- return CliArgsSchema.parse(args);
238
- }
239
- ```
240
-
241
- #### Data Transformation with Zod
242
-
243
- ```typescript
244
- import { z } from 'zod';
245
-
246
- // ✅ Transform and validate data
247
- const TimestampSchema = z.string().transform((str) => new Date(str));
248
-
249
- const UserInputSchema = z.object({
250
- email: z.string().email().transform((e) => e.toLowerCase()),
251
- age: z.string().transform((s) => parseInt(s, 10)),
252
- createdAt: TimestampSchema,
253
- });
254
-
255
- // Input: { email: 'USER@EXAMPLE.COM', age: '25', createdAt: '2024-01-01T00:00:00Z' }
256
- // Output: { email: 'user@example.com', age: 25, createdAt: Date object }
257
- ```
258
-
259
- #### Error Handling Best Practices
260
-
261
- ```typescript
262
- import { z } from 'zod';
263
-
264
- function processUserData(data: unknown) {
265
- const result = UserSchema.safeParse(data);
266
-
267
- if (!result.success) {
268
- // ✅ Detailed error messages
269
- const errors = result.error.issues.map((issue) => ({
270
- field: issue.path.join('.'),
271
- message: issue.message,
272
- code: issue.code,
273
- }));
274
-
275
- throw new ValidationError('Invalid user data', errors);
276
- }
277
-
278
- return result.data;
279
- }
280
- ```
281
-
282
- #### When to Use Zod
283
-
284
- **Always use Zod for**:
285
- - ✅ API request/response validation
286
- - ✅ Configuration file parsing
287
- - ✅ CLI argument validation
288
- - ✅ External data (files, databases, APIs)
289
- - ✅ User input from any source
290
- - ✅ Environment variable validation
291
-
292
- **TypeScript types alone are sufficient for**:
293
- - Internal function parameters (within same file)
294
- - Return types of pure functions
295
- - Class properties with known types
296
- - Type aliases and interfaces for documentation
297
-
298
- #### Quick Checklist for TypeScript + Zod
299
-
300
- Before submitting TypeScript code:
301
- - [ ] Installed Zod (`npm install zod`)
302
- - [ ] Defined schemas for all external data
303
- - [ ] Used `z.infer<typeof Schema>` for type inference
304
- - [ ] Validated inputs at boundaries (API, CLI, files)
305
- - [ ] Used `safeParse()` for better error handling
306
- - [ ] Included meaningful error messages
307
- - [ ] No `any` types (use `z.unknown()` if needed)
308
-
309
- ### Python
310
- - Type hints for function signatures
311
- - List/dict comprehensions for data transformation
312
- - Context managers (with statement) for resources
313
- - Follow PEP 8 style guide
314
- - Use dataclasses for data models
315
-
316
- ### SQL
317
- - Use indexes on frequently queried columns
318
- - Avoid SELECT *
319
- - Use JOINs efficiently
320
- - Parameterize queries
321
- - Use transactions for multi-step operations
322
-
323
- ## Quick Checklist
324
-
325
- Before submitting code:
326
- - [ ] Types and interfaces defined
327
- - [ ] Error handling implemented
328
- - [ ] Input validation added
329
- - [ ] Tests written and passing
330
- - [ ] Code formatted and linted
331
- - [ ] No console.log/print in production code
332
- - [ ] Security considerations addressed
333
- - [ ] Performance optimized where needed