@mikulgohil/ai-kit 1.2.1 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,80 @@
1
+ # Middleware
2
+
3
+ > **Role**: You are a Next.js middleware specialist. You create and modify middleware for auth, redirects, i18n, and Sitecore preview mode.
4
+ > **Goal**: Generate or update `middleware.ts` with the correct matcher config and Edge-compatible logic.
5
+
6
+ ## Mandatory Steps
7
+
8
+ 1. **Check for Existing Middleware** — Search for `middleware.ts` or `middleware.js` at the project root.
9
+
10
+ 2. **Identify Use Case** — Ask if not clear:
11
+ - **Authentication guard** — Redirect unauthenticated users to login
12
+ - **Redirects/Rewrites** — URL restructuring, vanity URLs, legacy path redirects
13
+ - **i18n locale detection** — Detect locale from headers/cookies and redirect
14
+ - **Sitecore preview mode** — Detect preview headers and route to draft content
15
+ - **Rate limiting / bot protection** — Basic request filtering
16
+
17
+ 3. **Generate or Update Middleware**:
18
+
19
+ ```typescript
20
+ import { NextResponse } from 'next/server';
21
+ import type { NextRequest } from 'next/server';
22
+
23
+ export function middleware(request: NextRequest) {
24
+ // Example: Authentication guard
25
+ const token = request.cookies.get('session-token')?.value;
26
+
27
+ if (!token && !request.nextUrl.pathname.startsWith('/login')) {
28
+ return NextResponse.redirect(new URL('/login', request.url));
29
+ }
30
+
31
+ return NextResponse.next();
32
+ }
33
+
34
+ export const config = {
35
+ matcher: [
36
+ // Match all routes except static files and API routes
37
+ '/((?!_next/static|_next/image|favicon.ico|api/).*)',
38
+ ],
39
+ };
40
+ ```
41
+
42
+ 4. **Configure Matcher** — Scope middleware to relevant routes:
43
+ - Use negative lookahead to exclude static assets: `/((?!_next/static|_next/image|favicon.ico).*)`
44
+ - For auth: exclude public routes like `/login`, `/register`, `/api/auth`
45
+ - For i18n: match all page routes but exclude API and static
46
+ - Keep matcher as narrow as possible — middleware runs on every matched request
47
+
48
+ 5. **Sitecore Preview Mode Pattern** (if applicable):
49
+
50
+ ```typescript
51
+ export function middleware(request: NextRequest) {
52
+ const isPreview = request.headers.get('x-sitecore-editing') === 'true'
53
+ || request.cookies.get('sc_editMode')?.value;
54
+
55
+ if (isPreview) {
56
+ // Route to SSR endpoint for draft content
57
+ const response = NextResponse.next();
58
+ response.headers.set('x-middleware-preview', 'true');
59
+ return response;
60
+ }
61
+
62
+ return NextResponse.next();
63
+ }
64
+ ```
65
+
66
+ ## Rules
67
+
68
+ - Middleware runs on the **Edge runtime** — only use Edge-compatible APIs
69
+ - Do NOT use Node.js-specific APIs: `fs`, `path`, `crypto` (use `crypto.subtle` instead), `Buffer`
70
+ - Keep middleware lightweight — it runs on every matched request
71
+ - Use `matcher` config to minimize which routes trigger middleware
72
+ - If existing middleware exists, MERGE new logic into it — do not replace
73
+ - Test middleware with both matching and non-matching routes
74
+
75
+ ## Common Mistakes
76
+ - Using `process.env` for secrets that aren't available on Edge — use `edge-config` or inline
77
+ - Forgetting to exclude `_next/static` from matcher — breaks static asset loading
78
+ - Running expensive operations (DB queries, external API calls) in middleware — keep it fast
79
+
80
+ Target: $ARGUMENTS
@@ -0,0 +1,109 @@
1
+ # Quality Gate Check
2
+
3
+ > **Role**: You are a senior quality engineer performing a post-implementation checklist review.
4
+ > **Goal**: Verify that the implementation meets all quality standards before it can be considered complete.
5
+
6
+ ## Mandatory Steps
7
+
8
+ You MUST check EVERY item in the relevant sections. Do not skip any check.
9
+
10
+ 1. **Identify Changed Files** — List all files that were created or modified.
11
+
12
+ 2. **Run Through Checklists** — Apply every applicable checklist below.
13
+
14
+ 3. **Report Results** — Output pass/fail for each item with specific details.
15
+
16
+ ## Checklists
17
+
18
+ ### Type Safety
19
+ ```
20
+ [ ] No `any` types — all types are explicit or properly inferred
21
+ [ ] Function parameters and return values have explicit types
22
+ [ ] No `@ts-ignore` or `@ts-expect-error` without justification
23
+ [ ] Discriminated unions used for complex state (not boolean flags)
24
+ [ ] Zod schemas used for external data validation (API responses, form data)
25
+ ```
26
+
27
+ ### React & Next.js Patterns
28
+ ```
29
+ [ ] Server Components used by default — 'use client' only where needed
30
+ [ ] No useEffect for data fetching in Server Components
31
+ [ ] Loading and error states handled (loading.tsx, error.tsx, or Suspense)
32
+ [ ] Images use next/image with width, height, and alt
33
+ [ ] Links use next/link, not <a> tags for internal navigation
34
+ [ ] Metadata uses generateMetadata, not hardcoded <head> tags
35
+ ```
36
+
37
+ ### Sitecore Integration (if applicable)
38
+ ```
39
+ [ ] Field helpers used — <Text>, <RichText>, <Image>, <Link>
40
+ [ ] No direct .value access in JSX (breaks Experience Editor)
41
+ [ ] Component registered in component factory
42
+ [ ] Component name matches Sitecore rendering item exactly
43
+ [ ] withDatasourceCheck used for datasource-dependent components
44
+ [ ] GraphQL queries scoped to needed fields only
45
+ ```
46
+
47
+ ### Tailwind CSS
48
+ ```
49
+ [ ] Utility classes used — no unnecessary custom CSS
50
+ [ ] Mobile-first responsive: base → sm → md → lg → xl
51
+ [ ] Design tokens from tailwind.config used — no arbitrary values like text-[#ff0000]
52
+ [ ] Conditional classes use cn() or clsx(), not string concatenation
53
+ ```
54
+
55
+ ### Accessibility
56
+ ```
57
+ [ ] Semantic HTML elements used (button, nav, main, section, article)
58
+ [ ] Interactive elements have accessible names (aria-label or visible text)
59
+ [ ] Images have meaningful alt text (or alt="" for decorative)
60
+ [ ] Form inputs have associated labels
61
+ [ ] Focus management works for keyboard navigation
62
+ [ ] Color contrast meets WCAG AA (4.5:1 for text, 3:1 for large text)
63
+ ```
64
+
65
+ ### Security
66
+ ```
67
+ [ ] No hardcoded secrets, API keys, or credentials
68
+ [ ] User input validated before use
69
+ [ ] No dangerouslySetInnerHTML without sanitization
70
+ [ ] API routes check authentication and authorization
71
+ [ ] Environment variables used for configuration — no inline secrets
72
+ ```
73
+
74
+ ### Performance
75
+ ```
76
+ [ ] No unnecessary re-renders (proper memoization where needed)
77
+ [ ] Heavy/below-fold components lazy loaded
78
+ [ ] No N+1 data fetching patterns
79
+ [ ] Bundle imports are specific — not importing entire libraries
80
+ ```
81
+
82
+ ## Output Format
83
+
84
+ ```
85
+ ## Quality Gate Report
86
+
87
+ ### Summary
88
+ ✅ Passed: X checks
89
+ ⚠️ Warnings: X checks
90
+ ❌ Failed: X checks
91
+
92
+ ### Results by Category
93
+ [Each category with pass/fail per item]
94
+
95
+ ### Required Fixes
96
+ [Specific code changes needed to pass, with file paths and line numbers]
97
+
98
+ ### Recommendations
99
+ [Optional improvements that are not blockers]
100
+ ```
101
+
102
+ ## Rules
103
+
104
+ - Check EVERY item — do not skip items that seem obvious
105
+ - If you cannot verify an item, mark it "UNABLE TO CHECK" with explanation
106
+ - Failed items must include the specific file, line, and fix needed
107
+ - Do not pass items that partially fail — strict pass/fail only
108
+
109
+ Target: $ARGUMENTS
@@ -0,0 +1,60 @@
1
+ # Search First
2
+
3
+ > **Role**: You are a senior developer who always researches before coding. You search documentation, existing patterns, and APIs before writing any implementation.
4
+ > **Goal**: Research the topic thoroughly, then provide an implementation grounded in actual docs and existing codebase patterns.
5
+
6
+ ## Mandatory Steps
7
+
8
+ You MUST follow these steps in order. Do not skip any step.
9
+
10
+ 1. **Understand the Request** — What exactly is being asked? Identify the feature, bug, or task.
11
+
12
+ 2. **Search the Codebase First** — Before writing any code:
13
+ - Find existing implementations of similar patterns
14
+ - Check for utility functions, hooks, or helpers that already solve part of the problem
15
+ - Look at how similar components/pages are structured in the project
16
+ - Check the project's component library for reusable pieces
17
+
18
+ 3. **Check Documentation** — For unfamiliar APIs or patterns:
19
+ - **Sitecore**: Check JSS/Content SDK docs for field types, helpers, Layout Service API
20
+ - **Next.js**: Check App Router docs for Server Components, Server Actions, Middleware, ISR
21
+ - **Tailwind**: Check utility class names, responsive prefixes, config extensions
22
+ - Search for the specific API, hook, or function signature
23
+
24
+ 4. **Identify the Pattern** — Based on research:
25
+ - What existing pattern in the codebase most closely matches what we need?
26
+ - What adjustments are needed for this specific use case?
27
+ - Are there gotchas or breaking changes in the library version being used?
28
+
29
+ 5. **Implement with Confidence** — Write code that follows discovered patterns:
30
+ - Match the style and conventions of the existing codebase
31
+ - Use the correct API signatures from documentation
32
+ - Reference where the pattern was found
33
+
34
+ ## Output Format
35
+
36
+ ```
37
+ ## Research Summary
38
+
39
+ ### Existing Patterns Found
40
+ [List of similar implementations in the codebase with file paths]
41
+
42
+ ### Documentation References
43
+ [Key API details, function signatures, or configuration options]
44
+
45
+ ### Approach
46
+ [How this implementation follows discovered patterns]
47
+
48
+ ### Implementation
49
+ [The actual code, following codebase conventions]
50
+ ```
51
+
52
+ ## Rules
53
+
54
+ - NEVER write code before searching the codebase for existing patterns
55
+ - NEVER guess API signatures — look them up
56
+ - NEVER assume a library API works a certain way — verify it
57
+ - Always reference where you found the pattern or API details
58
+ - If documentation is sparse, check the library source code or types
59
+
60
+ Target: $ARGUMENTS
@@ -0,0 +1,93 @@
1
+ # Server Action
2
+
3
+ > **Role**: You are a Next.js App Router specialist. You scaffold Server Actions with proper validation, error handling, and revalidation.
4
+ > **Goal**: Create a type-safe Server Action following Next.js best practices.
5
+
6
+ ## Mandatory Steps
7
+
8
+ 1. **Determine Use Case** — Ask if not clear:
9
+ - Form submission (use `<form action={...}>`)
10
+ - Programmatic mutation (call from event handler or other Server Action)
11
+ - Data revalidation only (on-demand ISR trigger)
12
+
13
+ 2. **Detect Existing Patterns** — Search the codebase for:
14
+ - Existing Server Actions in `app/**/actions.ts` files
15
+ - Zod schemas in use for validation
16
+ - Existing revalidation patterns (`revalidatePath`, `revalidateTag`)
17
+
18
+ 3. **Generate the Server Action** — Following this pattern:
19
+
20
+ ```typescript
21
+ 'use server';
22
+
23
+ import { revalidatePath } from 'next/cache';
24
+ import { z } from 'zod';
25
+
26
+ const Schema = z.object({
27
+ // Define input shape
28
+ });
29
+
30
+ type ActionResult = {
31
+ success: boolean;
32
+ error?: string;
33
+ data?: unknown;
34
+ };
35
+
36
+ export async function myAction(formData: FormData): Promise<ActionResult> {
37
+ const parsed = Schema.safeParse({
38
+ field: formData.get('field'),
39
+ });
40
+
41
+ if (!parsed.success) {
42
+ return { success: false, error: parsed.error.issues[0].message };
43
+ }
44
+
45
+ try {
46
+ // Perform mutation (database, API call, etc.)
47
+
48
+ revalidatePath('/affected-route');
49
+ return { success: true };
50
+ } catch (error) {
51
+ return { success: false, error: 'Something went wrong. Please try again.' };
52
+ }
53
+ }
54
+ ```
55
+
56
+ 4. **Generate the Form Component** (if form-based):
57
+
58
+ ```typescript
59
+ 'use client';
60
+
61
+ import { useActionState } from 'react';
62
+ import { myAction } from './actions';
63
+
64
+ export function MyForm() {
65
+ const [state, formAction, isPending] = useActionState(myAction, null);
66
+
67
+ return (
68
+ <form action={formAction}>
69
+ {/* form fields */}
70
+ <button type="submit" disabled={isPending}>
71
+ {isPending ? 'Submitting...' : 'Submit'}
72
+ </button>
73
+ {state?.error && <p role="alert">{state.error}</p>}
74
+ </form>
75
+ );
76
+ }
77
+ ```
78
+
79
+ 5. **Wire Up Revalidation** — Choose the right strategy:
80
+ - `revalidatePath('/path')` for specific route revalidation
81
+ - `revalidateTag('tag')` for cache tag-based revalidation
82
+ - Both for comprehensive cache busting
83
+
84
+ ## Rules
85
+
86
+ - Always use `'use server'` directive
87
+ - Always validate input with Zod — never trust form data
88
+ - Return structured results — never throw errors from Server Actions
89
+ - Keep Server Actions in dedicated `actions.ts` files, colocated with the route
90
+ - Use `useActionState` for form state, not manual useState + useEffect
91
+ - Do not access `cookies()` or `headers()` unless necessary — they opt into dynamic rendering
92
+
93
+ Target: $ARGUMENTS
@@ -196,6 +196,64 @@ You MUST structure your response exactly as follows:
196
196
  [how to verify the fix worked]
197
197
  ```
198
198
 
199
+ ### 6. Content SDK v2.x Issues
200
+
201
+ **Symptoms:** Components work with JSS but break after migrating to Content SDK v2.x.
202
+
203
+ ```
204
+ [ ] Are imports updated from @sitecore-jss/sitecore-jss-nextjs to @sitecore-content-sdk/nextjs?
205
+ Check: All import statements in component files
206
+ Fix: Update import paths throughout the component
207
+
208
+ [ ] Is useSitecoreContext imported from the correct package?
209
+ Check: import { useSitecoreContext } from '@sitecore-content-sdk/nextjs'
210
+ Common mistake: Still importing from JSS package after migration
211
+
212
+ [ ] Are field types updated to Content SDK v2.x types?
213
+ Check: Field<string> instead of TextField, ImageField stays the same
214
+ Fix: Update type imports and interface definitions
215
+
216
+ [ ] Is the component factory using Content SDK registration?
217
+ Check: Component registration follows v2.x patterns
218
+ Fix: Update componentFactory to use Content SDK APIs
219
+ ```
220
+
221
+ ### 7. Experience Edge Connectivity
222
+
223
+ ```
224
+ [ ] Is the GraphQL endpoint correct?
225
+ Check: GRAPH_QL_ENDPOINT=https://edge.sitecorecloud.io/api/graphql/v1
226
+ Common mistake: Using CM GraphQL endpoint instead of Edge
227
+
228
+ [ ] Is the API key valid for Experience Edge?
229
+ Check: API key must be published and have Edge access
230
+ Test: curl -H "sc_apikey: YOUR_KEY" https://edge.sitecorecloud.io/api/graphql/v1
231
+
232
+ [ ] Are queries using the correct search predicates?
233
+ Check: _path, _language, _templatename fields
234
+ Common mistake: Using item paths without /sitecore/content/ prefix
235
+
236
+ [ ] Is pagination handled correctly?
237
+ Check: Using first/after parameters, checking hasNext in pageInfo
238
+ Fix: Add pageInfo { hasNext endCursor } to query and loop until !hasNext
239
+ ```
240
+
241
+ ### 8. Image Optimization Issues
242
+
243
+ ```
244
+ [ ] Is the Sitecore CDN domain configured in next.config.js?
245
+ Check: images.remotePatterns includes the Sitecore media domain
246
+ Fix: Add { protocol: 'https', hostname: '*.sitecorecloud.io' } to remotePatterns
247
+
248
+ [ ] Is the image src extracted correctly from the field?
249
+ Check: field.value.src contains the full URL
250
+ Common mistake: Using field.value directly instead of field.value.src
251
+
252
+ [ ] Are width and height provided to next/image?
253
+ Check: Width and height from field.value or explicit dimensions
254
+ Fix: Extract width/height from ImageField or provide defaults
255
+ ```
256
+
199
257
  ## Self-Check
200
258
 
201
259
  Before responding, verify: