forked from Sitecore/content-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLMs.txt
More file actions
425 lines (336 loc) · 13 KB
/
Copy pathLLMs.txt
File metadata and controls
425 lines (336 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# Sitecore Content SDK - LLM Guidance
## Project Context
This is the **Sitecore Content SDK** repository - a comprehensive TypeScript/JavaScript SDK for building modern web applications with Sitecore XM Cloud. The project is a monorepo containing multiple packages that provide core functionality, React components, Next.js integration, and CLI tools.
## Repository Structure
```
content-sdk/
├── packages/
│ ├── create-content-sdk-app/ # Scaffolding CLI & templates
│ ├── core/ # Core SDK functionality
│ ├── nextjs/ # Next.js-specific SDK
│ ├── react/ # React-specific SDK
│ └── cli/ # Additional CLI tools
└── samples/ # Example applications
```
### Key Directories
- **Sources**: `src/**`
- **Never edit**: `dist/**` (compiled output)
- **Templates**: Copied to generated apps, self-contained, use `.env.*.example` for env values
- **Initializers**: Each exposes `init(args)`, reuse common processes/utilities
## Technology Stack
- **Language**: TypeScript (Node LTS)
- **Runtime**: Node LTS
- **Build**: `tsc` -> `dist/`, templates bundled via `scripts/build-templates.ts`
- **Testing**: Mocha + Sinon + Chai, coverage via `nyc`
- **Lint/format**: ESLint + Prettier
- **Package Manager**: Yarn 3.1.0
## Code Style
### Vibe-Coding Principles
Core Philosophy:
- Write clean, modular, and idiomatic code
- Prefer declarative over imperative patterns
- Make code readable and self-documenting
- TypeScript-first development approach
Code Organization:
- Use Node LTS
- Export public types at module boundaries
- Prefer pure functions and thin wrappers
- No top-level side effects (except CLI entry)
- Modular architecture with clear separation of concerns
### Code Quality Standards
TypeScript Usage:
- Enable strict mode in all projects
- Prefer explicit types over `any`
- Use discriminated unions for complex state
- Export types at module boundaries for reusability
Functional Programming:
- Prefer pure functions where possible
- Use immutable data patterns
- Avoid side effects in business logic
- Compose small, focused functions
Readability:
- Use descriptive variable and function names
- Keep functions small and focused (single responsibility)
- Add comments for complex business logic only
- Prefer self-documenting code over extensive comments
### Error Handling
Error Strategy:
- Fail fast with clear, actionable messages
- Propagate child-process errors with context
- Use custom error classes for domain-specific errors
- Handle edge cases explicitly with guard clauses
Security:
- Sanitize user inputs
- Validate data at boundaries
- Never log sensitive information
- Use environment variables for configuration
### Development Workflow
Logging:
- Clear phases and results
- Support silent flag if available
- Use appropriate log levels (debug, info, warn, error)
- Include context in error messages
Imports:
- Relative for local modules
- Never import from `dist/`
- Group imports logically (external, internal, relative)
- Use barrel exports (index.ts) for clean APIs
Lint and Format:
- Keep ESLint + Prettier passing at all times
- Follow configured style rules consistently
- Use automated formatting on save
- Address linting warnings promptly
## JavaScript/TypeScript Rules
### Naming Conventions
Variables and Functions:
- Use camelCase: `getUserData()`, `isLoading`, `currentUser`
- Boolean variables: prefix with `is`, `has`, `can`, `should`
- Event handlers: prefix with `handle` or `on`: `handleClick`, `onSubmit`
Components (React):
- Use PascalCase: `SitecoreComponent`, `PageLayout`, `ContentBlock`
- File names match component names: `SitecoreComponent.tsx`
Constants:
- Use UPPER_SNAKE_CASE: `API_ENDPOINT`, `DEFAULT_TIMEOUT`, `MAX_RETRIES`
- Export at module level when shared
Directories:
- Use kebab-case: `src/components`, `src/api-clients`, `src/sitecore-utils`
- Organize by feature when appropriate: `src/content-management/`
Types and Interfaces:
- Use PascalCase with descriptive names: `ContentItem`, `LayoutProps`, `SitecoreConfig`
- Prefix interfaces with `I` only when needed for disambiguation
### Code Layout and Organization
Directory Structure:
```
src/
components/ # UI components (React)
utils/ # Helper functions and utilities
api/ # Sitecore integrations and API clients
lib/ # Third-party library configurations
types/ # TypeScript type definitions
hooks/ # Custom React hooks
styles/ # Styling files
```
File Organization:
- Group related functionality in feature directories
- Keep components co-located with their styles and tests
- Export public APIs through index.ts files
### Error Handling
API Calls:
- Always wrap in try/catch blocks
- Throw custom errors with context: `SitecoreFetchError`, `ConfigurationError`
- Handle edge cases with guard clauses
### Security
Input Validation:
- Sanitize user inputs before processing
- Validate data at application boundaries
- Use type guards for runtime type checking
- Escape content when rendering to prevent XSS
### Performance
Optimization Patterns:
- Memoize components with React.memo when appropriate
- Lazy-load non-critical modules: `const Component = lazy(() => import('./Component'))`
- Use useCallback and useMemo for expensive operations
TypeScript:
- Enable strict mode in tsconfig.json
- Prefer type assertions over any: `value as ContentItem`
- Use discriminated unions for complex state management
### Documentation
JSDoc Comments:
- All new functions, interfaces, classes must have JSDoc style comments
- Include @param tags for all parameters with types and descriptions
- Include @returns tag for return values with type and description
- Use descriptive comments that explain the purpose and behavior
- Follow existing Content SDK JSDoc patterns
## Sitecore SDK Rules
### XM Cloud Integration
Configuration:
- Always use environment variables for API endpoints and keys
- Never hardcode API keys in source code
- Use `.env.example` files to document required environment variables
- Prefer `sitecore.config.ts` for centralized configuration
```typescript
// sitecore.config.ts
import { defineConfig } from '@sitecore-content-sdk/nextjs/config';
export default defineConfig({
api: {
edge: {
contextId: process.env.SITECORE_EDGE_CONTEXT_ID || '',
clientContextId: process.env.NEXT_PUBLIC_SITECORE_EDGE_CONTEXT_ID,
edgeUrl: process.env.SITECORE_EDGE_URL || 'https://edge-platform.sitecorecloud.io',
},
local: {
apiKey: process.env.SITECORE_API_KEY || '',
apiHost: process.env.SITECORE_API_HOST || '',
},
},
defaultSite: process.env.NEXT_PUBLIC_DEFAULT_SITE_NAME || 'default',
defaultLanguage: process.env.NEXT_PUBLIC_DEFAULT_LANGUAGE || 'en',
editingSecret: process.env.SITECORE_EDITING_SECRET,
});
```
API Client Usage:
- Use HTTPS for all XM Cloud endpoints
- Implement proper retry logic with exponential backoff
- Cache responses appropriately (consider content freshness)
- Handle GraphQL errors gracefully
### Component Development
Sitecore Component Naming:
- Use descriptive, feature-based names: `HeroWithContent`, `ProductListing`, `ContentBlockGrid`
- Follow PascalCase convention
- Include component type in name when helpful: `LayoutContainer`, `ContentRenderer`
Component Registration:
- Register components in the component map
- Use consistent component names across registration and files
- Include TypeScript types for all component props
```typescript
// Component props interface
interface ContentBlockProps {
fields: {
title: Field;
content: Field;
image: Field;
};
}
```
### Content Management
Field Handling:
- Always validate field existence before rendering
- Use helper functions for common field operations
- Handle empty/null fields gracefully
- Prefer Sitecore field components over manual rendering
```typescript
// Good: Using Sitecore field components
<Text field={fields?.title} tag="h1" />
<RichText field={fields?.content} />
// Avoid: Manual field value extraction unless necessary
```
Content SDK Client Methods:
- Prefer using `scClient.getPage()` for page data and layout fetching
- Use `scClient.getDictionary()` for localized content
- Leverage `scClient.getErrorPage()` for error page handling
- Use `scClient.getPreview()` for preview mode content
- Implement proper error boundaries for layout rendering
- Handle missing placeholder content gracefully
- Cache layout data when appropriate
### Performance and Security
Content Fetching:
- Implement caching strategy for content (React Query recommended)
- Use GraphQL queries efficiently (avoid over-fetching)
- Implement proper loading states and error handling
- Consider content preview vs. published content scenarios
Security Best Practices:
- Sanitize user inputs before processing
- Validate content from Sitecore before rendering
- Use Content Security Policy (CSP) headers
- Never expose sensitive configuration in client-side code
```typescript
// Content validation example
function validateContentItem(item: unknown): ContentItem {
if (!item || typeof item !== 'object') {
throw new Error('Invalid content item');
}
// Additional validation logic
return item as ContentItem;
}
```
### Development Patterns
Error Handling:
- Create custom error classes: `SitecoreFetchError`, `ComponentRenderError`
- Log errors appropriately for debugging
- Provide fallback content when components fail to render
- Use error boundaries in React applications
Placeholder Management:
- Use strongly-typed placeholder names
- Handle dynamic placeholders appropriately
- Implement fallback rendering for missing placeholders
- Follow Sitecore's placeholder naming conventions
Testing:
- Mock Sitecore services in unit tests
- Test component rendering with various field configurations
- Include tests for error scenarios (missing fields, API failures)
- Use Sitecore's test data helpers when available
## Testing Strategy
### Testing Framework
- **Mocha with ts-node/register**
- **Nearby `*.test.ts` with success + failure cases**
- **Stub child-process and fs as needed**
### Commands
- **Package level**: `npm run test`, `npm run coverage`
- **Monorepo level**: `yarn test-packages`, `yarn coverage-packages`
## CLI Development
### CLI Behavior
- **Drive init via `Initializer.init(args)`**
- **Clear prompts and defaults**
- **Install dependencies after scaffolding**
- **Print next steps**
### Non-goals
- **No deployments or CI flows**
- **No global user state changes**
### Backwards compatibility
- **Avoid breaking arg names**
- **Additive changes with defaults**
## Safety Guidelines
### Critical Rules
- **Never edit `dist/**`** - These are compiled artifacts
- **Do not commit secrets** - `.env` ignored, use `.env.example`
- **Template edits must build/run** with `npm install && npm run build`
- **Reuse common processes** - Don't duplicate functionality
## General Coding Principles
### Universal Standards
DRY Principle:
- Don't Repeat Yourself - extract common functionality
- Create reusable utilities and helper functions
- Use composition over inheritance
- Share types and interfaces across modules
SOLID Principles:
- Single Responsibility: each function/class has one purpose
- Open/Closed: extend functionality through composition
- Dependency Inversion: depend on abstractions, not implementations
Code Clarity:
- Write self-documenting code with clear intent
- Use meaningful names that express business concepts
- Prefer explicit over implicit behavior
- Make dependencies and requirements obvious
### Architecture Patterns
Modular Design:
- Organize code into focused, cohesive modules
- Minimize coupling between modules
- Use clear interfaces between layers
- Follow established patterns consistently
Data Flow:
- Prefer unidirectional data flow
- Validate inputs at system boundaries
- Transform data at appropriate layers
- Handle errors close to their source
Testing:
- Write testable code with minimal dependencies
- Use dependency injection for better testability
- Mock external services and side effects
- Test behavior, not implementation details
### Development Standards
Version Control:
- Write descriptive commit messages
- Keep commits focused and atomic
- Use branching strategies appropriate to team size
- Review code before merging
Documentation:
- Document public APIs and interfaces
- Include usage examples for complex functionality
- Keep documentation close to code
- Update documentation with code changes
Performance:
- Optimize for readability first, performance second
- Profile before optimizing
- Cache expensive operations appropriately
- Consider memory usage and cleanup
### Quality Assurance
Code Review:
- Review for logic, readability, and maintainability
- Check error handling and edge cases
- Verify tests cover new functionality
- Ensure documentation is updated
Continuous Integration:
- All tests must pass before merging
- Linting and formatting checks must pass
- Build process must complete successfully
- No breaking changes without proper migration