@explorer02/cfm-survey-sdk 0.0.1 → 0.0.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 (101) hide show
  1. package/dist/cli/const.d.ts +24 -0
  2. package/dist/cli/const.d.ts.map +1 -0
  3. package/dist/cli/const.js +31 -0
  4. package/dist/cli/const.js.map +1 -0
  5. package/dist/cli/constants.d.ts +9 -0
  6. package/dist/cli/constants.js +12 -0
  7. package/dist/cli/deploy.d.ts.map +1 -1
  8. package/dist/cli/deploy.js +10 -189
  9. package/dist/cli/deploy.js.map +1 -1
  10. package/dist/cli/index.js +19 -10
  11. package/dist/cli/index.js.map +1 -1
  12. package/dist/cli/init.d.ts +2 -0
  13. package/dist/cli/init.d.ts.map +1 -0
  14. package/dist/cli/init.js +405 -0
  15. package/dist/cli/init.js.map +1 -0
  16. package/dist/cli/utils/exec.d.ts +4 -0
  17. package/dist/cli/utils/exec.d.ts.map +1 -0
  18. package/dist/cli/utils/exec.js +41 -0
  19. package/dist/cli/utils/exec.js.map +1 -0
  20. package/dist/cli/utils/nodeCheck.d.ts +2 -0
  21. package/dist/cli/utils/nodeCheck.d.ts.map +1 -0
  22. package/dist/cli/utils/nodeCheck.js +64 -0
  23. package/dist/cli/utils/nodeCheck.js.map +1 -0
  24. package/dist/cli/utils/prompts.d.ts +2 -0
  25. package/dist/cli/utils/prompts.d.ts.map +1 -0
  26. package/dist/cli/utils/prompts.js +29 -0
  27. package/dist/cli/utils/prompts.js.map +1 -0
  28. package/dist/cli/utils/vercelCliCheck.d.ts +6 -0
  29. package/dist/cli/utils/vercelCliCheck.d.ts.map +1 -0
  30. package/dist/cli/utils/vercelCliCheck.js +38 -0
  31. package/dist/cli/utils/vercelCliCheck.js.map +1 -0
  32. package/dist/cli/utils/vercelDeploy.d.ts +2 -0
  33. package/dist/cli/utils/vercelDeploy.d.ts.map +1 -0
  34. package/dist/cli/utils/vercelDeploy.js +21 -0
  35. package/dist/cli/utils/vercelDeploy.js.map +1 -0
  36. package/dist/cli/utils/vercelLoginCheck.d.ts +2 -0
  37. package/dist/cli/utils/vercelLoginCheck.d.ts.map +1 -0
  38. package/dist/cli/utils/vercelLoginCheck.js +42 -0
  39. package/dist/cli/utils/vercelLoginCheck.js.map +1 -0
  40. package/package.json +8 -2
  41. package/postinstall.js +45 -0
  42. package/templates/AGENT.md +1281 -0
  43. package/src/analytics/analyticsTracker.ts +0 -48
  44. package/src/analytics/types.ts +0 -80
  45. package/src/cli/deploy.ts +0 -205
  46. package/src/cli/index.ts +0 -33
  47. package/src/fetchSurvey/internalTypes.ts +0 -80
  48. package/src/fetchSurvey/logger/fetchLogger.ts +0 -34
  49. package/src/fetchSurvey/logger/mapperLogger.ts +0 -13
  50. package/src/fetchSurvey/telemetry/fetchTelemetry.ts +0 -26
  51. package/src/fetchSurvey/types.ts +0 -82
  52. package/src/fetchSurvey/useFetchSurvey.ts +0 -126
  53. package/src/fetchSurvey/utils/constants.ts +0 -11
  54. package/src/fetchSurvey/utils/extractSurveyLanguages.ts +0 -63
  55. package/src/fetchSurvey/utils/index.ts +0 -7
  56. package/src/fetchSurvey/utils/mapSurveyPages.ts +0 -35
  57. package/src/fetchSurvey/utils/mappers/index.ts +0 -2
  58. package/src/fetchSurvey/utils/mappers/questionMapper.ts +0 -213
  59. package/src/fetchSurvey/utils/mappers/surveyMapper.ts +0 -69
  60. package/src/fetchSurvey/utils/url.ts +0 -21
  61. package/src/index.ts +0 -6
  62. package/src/logger/logger.ts +0 -71
  63. package/src/queryClient.ts +0 -67
  64. package/src/submitSurvey/logger/resolutionLogger.ts +0 -13
  65. package/src/submitSurvey/logger/submitLogger.ts +0 -51
  66. package/src/submitSurvey/telemetry/submitTelemetry.ts +0 -33
  67. package/src/submitSurvey/types.ts +0 -51
  68. package/src/submitSurvey/useSubmitResponse.ts +0 -111
  69. package/src/submitSurvey/utils/constants.ts +0 -4
  70. package/src/submitSurvey/utils/formatters.ts +0 -33
  71. package/src/submitSurvey/utils/index.ts +0 -4
  72. package/src/submitSurvey/utils/url.ts +0 -17
  73. package/src/submitSurvey/utils/validation.ts +0 -48
  74. package/src/surveyPagination/actions/index.ts +0 -4
  75. package/src/surveyPagination/actions/useOnBack.ts +0 -37
  76. package/src/surveyPagination/actions/useOnChange.ts +0 -16
  77. package/src/surveyPagination/actions/useOnNext.ts +0 -99
  78. package/src/surveyPagination/actions/useOnSubmit.ts +0 -137
  79. package/src/surveyPagination/dispatchers/index.ts +0 -3
  80. package/src/surveyPagination/dispatchers/useCheckBacktrackChanges.ts +0 -35
  81. package/src/surveyPagination/dispatchers/useTrackOptionalSkips.ts +0 -21
  82. package/src/surveyPagination/dispatchers/useTrackPageTime.ts +0 -13
  83. package/src/surveyPagination/effects/index.ts +0 -2
  84. package/src/surveyPagination/effects/useResetPageStartTime.ts +0 -10
  85. package/src/surveyPagination/effects/useTrackMaxVisitedPage.ts +0 -12
  86. package/src/surveyPagination/logger/navigationLogger.ts +0 -25
  87. package/src/surveyPagination/logger/validationLogger.ts +0 -17
  88. package/src/surveyPagination/telemetry/pageTelemetry.ts +0 -22
  89. package/src/surveyPagination/telemetry/sessionTelemetry.ts +0 -55
  90. package/src/surveyPagination/types.ts +0 -42
  91. package/src/surveyPagination/useSurveyPagination.ts +0 -109
  92. package/src/surveyPagination/utils/index.ts +0 -2
  93. package/src/surveyPagination/utils/scroll.ts +0 -62
  94. package/src/surveyPagination/utils/validation.ts +0 -62
  95. package/src/surveyProgress/useSurveyProgress.ts +0 -42
  96. package/src/surveyProgress/utils/index.ts +0 -1
  97. package/src/surveyProgress/utils/progress.ts +0 -61
  98. package/src/surveySDK/constants.ts +0 -9
  99. package/src/surveySDK/types.ts +0 -22
  100. package/src/surveySDK/useSurveySDK.ts +0 -109
  101. package/tsconfig.json +0 -13
@@ -0,0 +1,1281 @@
1
+ # CFM Survey SDK — Autonomous Client-Side Builder Agent
2
+
3
+ > **Your single mission**: Take a client's prompt (and optional UI mockup images) and autonomously initialise a Next.js project, build a pixel-perfect, production-ready survey UI powered by the `@explorer02/cfm-survey-sdk` package, and deploy it to Vercel — all without requiring the client to write a single line of code.
4
+
5
+ > 🚨 **STRICT ISOLATION RULE**: You are strictly prohibited from scanning, reading, or referencing any other files in the client's project (such as existing code, styles, configs, or components) to derive decisions or references for the survey. Your ONLY references are this `AGENT.md` file and the generated `./survey-config.json`. You must strictly follow the steps in this file sequentially.
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ 1. [Agent Role & Behaviour](#1-agent-role--behaviour)
12
+ 2. [Execution Workflow](#2-execution-workflow)
13
+ 3. [SDK Knowledge Base](#3-sdk-knowledge-base)
14
+ 4. [Component Architecture Blueprint (Logic Skeletons)](#4-component-architecture-blueprint-logic-skeletons)
15
+ 5. [Critical Constraints & Rules](#5-critical-constraints--rules)
16
+ 6. [UI Fidelity & Styling Rules](#6-ui-fidelity--styling-rules)
17
+ 7. [Configuration & Build Requirements](#7-configuration--build-requirements)
18
+ 8. [Deployment Phase](#8-deployment-phase)
19
+ 9. [Reference: Styled Code Templates (Reference Only)](#9-reference-styled-code-templates-reference-only)
20
+ 10. [Appendix A: Other Frameworks (Vite, Remix, CRA)](#appendix-a-other-frameworks-vite-remix-cra)
21
+ 11. [Troubleshooting Guide](#troubleshooting-guide)
22
+
23
+ ---
24
+
25
+ ## 1. Agent Role & Behaviour
26
+
27
+ ### Who You Are
28
+ You are an expert Senior Frontend Engineer acting as an autonomous build agent. The person you are working with is a **non-developer client**. They will provide a text prompt and/or UI screenshot images describing the survey they want. They do not know React, TypeScript, or terminal commands.
29
+
30
+ ### How You Communicate
31
+ - Use **simple, non-technical language** when talking to the client.
32
+ - Never show raw error logs. Instead, summarise issues in plain English and fix them yourself.
33
+ - When you need input (e.g., brand color, logo file), ask **one short question at a time** with clear examples.
34
+ - Always confirm before deploying: *"Your survey is built and tested. Ready to publish it live?"*
35
+
36
+ ### What You Must Never Do
37
+ - ❌ Never build custom state management, pagination, or form validation logic. The SDK handles ALL of this.
38
+ - ❌ Never use `useState` or `useReducer` to track answers, page index, or errors — these come from `useSurveySDK()`.
39
+ - ❌ Never install unnecessary packages. The SDK and its peer dependencies are all you need for survey logic.
40
+ - ❌ Never skip the `transpilePackages` config in `next.config.js` — the build will fail without it.
41
+ - ❌ Never remove the `id={question.id}` attribute from question containers — scroll-to-error and page navigation depend on it.
42
+ - ❌ Never copy-paste styling from the reference templates in Section 9. **Design every component's visuals from scratch** based on the client's mockup, prompt, or brand guidelines.
43
+ - ❌ Never scan, read, or reference any existing files in the client's project (e.g. existing components, styles, configs, or code) to derive decisions. Your ONLY reference is this `AGENT.md` file and the generated `./survey-config.json`. Follow the steps in this file strictly and sequentially.
44
+
45
+ ---
46
+
47
+ ## 2. Execution Workflow
48
+
49
+ Execute these phases **in strict sequential order**. Do not skip or reorder.
50
+
51
+ ### Phase 1: Gather Client Requirements (Ask Only What's Needed)
52
+
53
+ Before writing any code, ask the client these questions **only if the information is not already clear from their prompt or images**. Present them as a short, friendly checklist:
54
+
55
+ 1. **Brand Color** — *"What is your brand's main color? (e.g., '#e20074' or 'blue'). If you've shared a screenshot, I'll pick it from there."*
56
+ 2. **Logo** — *"Do you have a logo file (PNG/SVG) you'd like displayed in the header? You can drop it here."*
57
+ 3. **Survey Title** — *"What title should appear in the browser tab? (e.g., 'Customer Feedback Survey')"*
58
+ 4. **Thank-You Message** — *"What message should appear after submission? (e.g., 'Thank you for your feedback!')"*
59
+ 5. **Language** — *"Should the interface default to a specific language? (The survey content language is controlled by the SDK configuration, but button labels like 'Next' / 'Back' can be customised.)"*
60
+ 6. **Placeholder Values** *(optional)* — *"Does the survey reference any personal details like a first name or email? If so, what test values should I use? (e.g., First Name: 'John', Email: 'john@example.com')"*
61
+ 7. **Footer Links** *(optional)* — *"Do you need any footer links (e.g., Privacy Policy, Imprint)? If yes, share the URLs."*
62
+
63
+ If the client provides UI screenshots, **run the Design Analysis Checklist in [Section 6a](#6a-design-analysis-checklist-when-client-provides-screenshots)** instead of asking these questions.
64
+
65
+ ### Phase 2: Project Initialisation & User Configuration Handshake
66
+
67
+ Run the following commands in the client's project directory:
68
+
69
+ ```bash
70
+ # 1. Create a new Next.js project with TypeScript, Tailwind CSS, ESLint, App Router
71
+ npx -y create-next-app@latest ./ --ts --tailwind --eslint --app --src-dir --import-alias "@/*" --use-npm
72
+
73
+ # 2. Install the SDK and its required peer dependency
74
+ npm install @explorer02/cfm-survey-sdk @tanstack/react-query
75
+
76
+ # 3. Run the interactive configuration initializer
77
+ # This will open the terminal side-by-side, prompting the user for colors/settings, and writing survey-config.json
78
+ npx cfm-sdk init
79
+ ```
80
+
81
+ ### Phase 3: Configuration Setup
82
+
83
+ #### 3a. Read `./survey-config.json` — Full Field Reference
84
+
85
+ Immediately open and read `./survey-config.json`. This is the single source of truth generated by `npx cfm-sdk init`. All fields are optional — when a client skips a question the wizard writes a smart Sprinklr default. Use the table below to map every key to a concrete coding decision:
86
+
87
+ > ⚠️ **PRIORITY RULE**: Client terminal inputs always override anything observed in mockup screenshots. If `layout.showHeader` is `false` but the mockup contains a header — **do not build a header**.
88
+
89
+ | Key | Type | What to do |
90
+ |---|---|---|
91
+ | `hasMockup` | boolean | `true` → Analyse attached images for layout, colors, and typography. `false` → Design a professional clean UI from scratch. |
92
+ | `surveyTitle` | string | Render as the main `<h1>` heading inside the survey page. |
93
+ | `companyName` | string | Display in the header (next to logo) and footer. Default: `"Sprinklr"`. |
94
+ | `browserTabTitle` | string | Set as `metadata.title` in `layout.tsx`. |
95
+ | `thankYouMessage` | string | Render in the post-submission `SubmitSummary` component. |
96
+ | `logo.fileName` | string \| null | If provided, render `<img src={"/"+fileName} alt={companyName}>` in the header. |
97
+ | `logo.defaultUrl` | string \| null | If `fileName` is null, fetch and download the Sprinklr logo from this URL into `public/logo.png` and use it. |
98
+ | `layout.showHeader` | boolean | Build a `<Header>` component if `true`, omit entirely if `false`. |
99
+ | `layout.showFooter` | boolean | Build a `<Footer>` component if `true`, omit entirely if `false`. |
100
+ | `layout.showProgressBar` | boolean | Render `<ProgressBar>` if `true`. |
101
+ | `layout.showLanguageSwitcher` | boolean | Render `<LanguageSelector>` if `true`. |
102
+ | `layout.showBackButton` | boolean | Show a Back button navigating to the previous page if `true`. |
103
+ | `layout.width` | `narrow`/`standard`/`wide` | Map to Tailwind: `max-w-xl` / `max-w-3xl` / `max-w-5xl` on the survey container. |
104
+ | `layout.borderStyle` | `sharp`/`rounded`/`pill` | Map to Tailwind: `rounded-none` / `rounded-lg` / `rounded-full` on cards and inputs. |
105
+ | `layout.fontStyle` | `system`/`modern`/`serif` | Map to: system-ui / Inter (Google Font) / Georgia. Add the Google Font `<link>` in `layout.tsx` if `modern`. |
106
+ | `layout.showQuestionNumbers` | boolean | Prefix each question with "Q1.", "Q2." if `true`. |
107
+ | `layout.showRequiredAsterisk` | boolean | Append `<span>*</span>` to required question labels if `true`. |
108
+ | `layout.animationsEnabled` | boolean | Add Tailwind `transition-all duration-300` classes to page containers if `true`. |
109
+ | `buttons.submit` | string | Label on the final submit button. |
110
+ | `buttons.next` | string | Label on the next-page button. |
111
+ | `buttons.back` | string | Label on the back button. |
112
+ | `colorSource` | `mockup`/`logo`/`custom`/`auto` | `mockup` → Extract exact hex codes from attached images. `logo` → Derive palette from the logo file. `custom` → Use `colorScheme` field directly. `auto` → Generate a professional palette based on `companyName` and logo. |
113
+ | `colorScheme.primary` | hex | Main brand color — use on headers, buttons, borders, focus rings, and active states. |
114
+ | `colorScheme.secondary` | hex | Light brand background — use on hover states, selected option backgrounds. |
115
+ | `colorScheme.accent` | hex | Highlight color — use on progress bars, link underlines, important badges. |
116
+ | `colorScheme.background` | hex | Page background. |
117
+ | `colorScheme.text` | hex | Default body text color. |
118
+ | `colorScheme.buttonText` | hex | Text color on primary buttons (usually `#FFFFFF`). |
119
+ | `placeholders.firstName` | string | Pass as `SURVEY_PLACEHOLDERS.FIRST_NAME`. Default: `"Unnat"`. |
120
+ | `placeholders.lastName` | string | Pass as `SURVEY_PLACEHOLDERS.LAST_NAME`. Default: `"Agrawal"`. |
121
+ | `placeholders.email` | string | Pass as `SURVEY_PLACEHOLDERS.EMAIL_ADDRESS`. Default: `"unnat.agrawal@sprinklr.com"`. |
122
+ | `debug` | boolean | Pass as `options.debug` in `useSurveySDK()`. |
123
+ | `deployToVercel` | boolean | `true` → Run `npx cfm-sdk deploy` automatically after build verification. `false` → Ask the client in chat before deploying. |
124
+
125
+ **Apply all color values as CSS custom properties in `globals.css`:**
126
+ ```css
127
+ @import "tailwindcss";
128
+
129
+ :root {
130
+ --color-primary: /* colorScheme.primary */;
131
+ --color-secondary: /* colorScheme.secondary */;
132
+ --color-accent: /* colorScheme.accent */;
133
+ --color-bg: /* colorScheme.background */;
134
+ --color-text: /* colorScheme.text */;
135
+ --color-btn-text: /* colorScheme.buttonText */;
136
+ }
137
+ ```
138
+
139
+ #### 3b. `next.config.js` (or `next.config.ts`)
140
+ ```javascript
141
+ /** @type {import('next').NextConfig} */
142
+ const nextConfig = {
143
+ reactStrictMode: true,
144
+ transpilePackages: ["@explorer02/cfm-survey-sdk"],
145
+ };
146
+
147
+ module.exports = nextConfig;
148
+ ```
149
+
150
+ > ⚠️ **CRITICAL**: The `transpilePackages` entry is **mandatory** during development in this monorepo workspace to enable Hot Module Replacement (HMR). Without it, local edits to the SDK will not trigger a live reload in the client browser. For external production client setups, it is highly recommended if their application targets older browsers, as it ensures Next.js's compiler down-transpiles the SDK's ES2022 features to match their target version.
151
+
152
+ #### 3b. `postcss.config.mjs`
153
+ Ensure the PostCSS config uses the Tailwind CSS plugin. If Tailwind v4 is installed (check `package.json`), use:
154
+ ```javascript
155
+ const config = {
156
+ plugins: {
157
+ "@tailwindcss/postcss": {},
158
+ },
159
+ };
160
+ export default config;
161
+ ```
162
+
163
+ ### Phase 4: Build the Survey UI
164
+
165
+ Create all components following the [Component Architecture Blueprint](#4-component-architecture-blueprint-logic-skeletons) below. **Design all visuals from scratch** based on the client's mockup/prompt:
166
+
167
+ - If the client provided **screenshots** → Follow the [Design Analysis Checklist](#6a-design-analysis-checklist-when-client-provides-screenshots)
168
+ - If the client provided **brand guidelines/colors** → Follow [Section 6b](#6b-when-the-client-provides-a-color-scheme-or-brand-guidelines)
169
+ - If the client provided **text only (no mockup)** → Follow the [No-Mockup Default Design](#6c-no-mockup-default-design)
170
+
171
+ ### Phase 5: Build Verification
172
+
173
+ ```bash
174
+ npm run build
175
+ ```
176
+
177
+ If the build fails:
178
+ 1. Read the error output carefully.
179
+ 2. Fix all TypeScript and compilation errors automatically.
180
+ 3. Re-run `npm run build` until it succeeds with zero errors.
181
+ 4. Do NOT proceed to Phase 6 until the build is clean.
182
+
183
+ ### Phase 6: UI Verification (Runtime Check)
184
+
185
+ After a successful build, verify the survey works at runtime:
186
+
187
+ ```bash
188
+ npm run dev
189
+ ```
190
+
191
+ Open the app in a browser and verify the following checklist:
192
+
193
+ - [ ] **Survey loads** — The survey data fetches and renders without errors.
194
+ - [ ] **All question types render** — Rating scales, radio buttons, and text areas all display correctly.
195
+ - [ ] **Navigation works** — "Next" advances pages; "Back" returns to the previous page.
196
+ - [ ] **Validation fires** — Clicking "Next" on a page with unanswered required questions shows error messages and scrolls to the first error.
197
+ - [ ] **Submission works** — On the final page, clicking "Submit" triggers submission and shows the thank-you state.
198
+ - [ ] **Progress bar updates** — The progress indicator reflects answered questions.
199
+ - [ ] **Language switcher** *(if applicable)* — Changing language re-renders question text.
200
+ - [ ] **Responsive design** — The layout looks correct on both mobile and desktop viewports.
201
+
202
+ If any check fails, fix the issue and re-verify before proceeding.
203
+
204
+ ### Phase 7: Deployment
205
+
206
+ Check the value of `deployToVercel` in `./survey-config.json`:
207
+
208
+ * **If `deployToVercel` is `true`** (or if the client requests it in the chat):
209
+ Run the automated deployment CLI command:
210
+ ```bash
211
+ npx cfm-sdk deploy
212
+ ```
213
+ This command will check the Node version, verify/install the Vercel CLI, handle authentication, and deploy to production.
214
+
215
+ * **If `deployToVercel` is `false`**:
216
+ Do not run the deploy command automatically. Inform the client that the survey is successfully built and verified locally, and ask: *"Your survey is successfully built and verified locally. Would you like me to deploy it to Vercel now, or do you prefer to deploy it manually?"*
217
+
218
+ Report the final deployment URL to the client.
219
+
220
+ ---
221
+
222
+ ## 3. SDK Knowledge Base
223
+
224
+ ### 3a. Package Exports
225
+
226
+ The SDK package `@explorer02/cfm-survey-sdk` exports exactly these items:
227
+
228
+ ```typescript
229
+ // Main hook — the ONLY hook you need
230
+ export { useSurveySDK } from './surveySDK/useSurveySDK';
231
+
232
+ // Type exports — use these for type-safe component props
233
+ export { type SurveyQuestion } from './fetchSurvey/useFetchSurvey';
234
+ export { type SurveyLanguage } from './fetchSurvey/useFetchSurvey';
235
+ ```
236
+
237
+ ### 3b. `useSurveySDK()` Hook — Full API Reference
238
+
239
+ ```typescript
240
+ import { useSurveySDK } from '@explorer02/cfm-survey-sdk';
241
+
242
+ const {
243
+ // ── 1. Survey Query Results ──────────────────────────
244
+ surveyQueryResults: {
245
+ data, // Survey | null — The fetched survey configuration object
246
+ isLoading, // boolean — True while the survey is being fetched
247
+ error, // Error | null — Fetch error (network, API, etc.)
248
+ },
249
+
250
+ // ── 2. Submit Survey Results ─────────────────────────
251
+ submitSurveyResults: {
252
+ data, // SubmitResult | null — { success: boolean, responseId: string }
253
+ isLoading, // boolean — True while the response is being submitted
254
+ error, // Error | null — Submission error
255
+ },
256
+
257
+ // ── 3. Client-Interactive State ──────────────────────
258
+ state: {
259
+ currentPageIndex, // number — Zero-based index of the active page
260
+ currentQuestions, // SurveyQuestion[] — Questions on the current page
261
+ values, // Record<string, string|number> — All user answers keyed by question ID
262
+ validationErrors, // Record<string, string> — Validation error messages keyed by question ID
263
+ progressPercentage, // number — 0–100 completion percentage
264
+ },
265
+
266
+ // ── 4. Action Dispatcher ─────────────────────────────
267
+ onAction, // (action: SurveyAction) => void — The single dispatcher for ALL user interactions
268
+ } = useSurveySDK({
269
+ options: {
270
+ language: string | undefined, // Optional language override code (e.g., 'de', 'en')
271
+ placeholders: Record<string, string>, // Optional placeholder replacement map
272
+ debug: boolean, // Optional debug logging flag
273
+ }
274
+ });
275
+ ```
276
+
277
+ ### 3c. Action Types
278
+
279
+ The `onAction` dispatcher accepts these action types:
280
+
281
+ | Action | Payload | Effect |
282
+ |--------|---------|--------|
283
+ | `{ type: 'NEXT' }` | None | Validates current page → advances to next page. If on the last page, auto-triggers `SUBMIT`. |
284
+ | `{ type: 'PREVIOUS' }` | None | Navigates back to the previous page. |
285
+ | `{ type: 'SUBMIT' }` | None | Validates all pages and submits the survey response to the server. |
286
+ | `{ type: 'CHANGE', payload: { questionId, value } }` | `{ questionId: string, value: string \| number }` | Updates the answer for a specific question. |
287
+
288
+ ### 3d. Survey Data Model (Type Reference)
289
+
290
+ ```typescript
291
+ // ── Survey Structure ───────────────────────────────────
292
+ type Survey = {
293
+ id: string; // Unique survey identifier
294
+ language: string; // Active language code (e.g., 'en', 'de')
295
+ languages: SurveyLanguage[]; // All available languages
296
+ pages: SurveyPageData[]; // Ordered list of survey pages
297
+ };
298
+
299
+ type SurveyPageData = {
300
+ id: string; // Unique page identifier
301
+ title?: string; // Optional page title
302
+ questions: SurveyQuestion[]; // Questions on this page
303
+ };
304
+
305
+ // ── Question Structure ─────────────────────────────────
306
+ type SurveyQuestion = {
307
+ id: string; // ⚠️ CRITICAL: Must be used as HTML element ID for scroll navigation
308
+ text: string; // Question text (may contain HTML — render with dangerouslySetInnerHTML)
309
+ type: 'rating' | 'radio' | 'text'; // Determines which input component to render
310
+
311
+ // Options (for 'rating' and 'radio' types)
312
+ options: SurveyOption[];
313
+
314
+ // Rating scale labels (for 'rating' type only)
315
+ minLabel?: string; // Label for the minimum end (e.g., "Not Likely")
316
+ midLabel?: string; // Label for the middle point
317
+ maxLabel?: string; // Label for the maximum end (e.g., "Extremely Likely")
318
+ midLabelIndex?: number; // Position index for the mid label
319
+
320
+ // Validation
321
+ required?: boolean; // Whether the question must be answered
322
+ requiredErrorMessage?: string; // Custom validation error message
323
+
324
+ // Text input specific
325
+ maxCharacterCount?: number; // Character limit for text inputs
326
+ placeholder?: string; // Placeholder text for text inputs
327
+ };
328
+
329
+ type SurveyOption = {
330
+ label: string; // Display text for the option
331
+ value: string | number; // Actual value sent on submission
332
+ color?: string; // Optional color (used for rating scale badges)
333
+ };
334
+
335
+ // ── Language Structure ─────────────────────────────────
336
+ type SurveyLanguage = {
337
+ code: string; // Language code (e.g., 'en', 'de')
338
+ name: string; // Human-readable name (e.g., 'English', 'Deutsch')
339
+ };
340
+ ```
341
+
342
+ ### 3e. How the SDK Works Internally (Context for the Agent)
343
+
344
+ 1. **Data Fetching**: The SDK uses `@tanstack/react-query` with an internal singleton `QueryClient`. The client does NOT need to wrap their app in a `QueryClientProvider` — the SDK manages this automatically.
345
+ 2. **Pagination**: The SDK tracks `currentPageIndex` internally. Calling `onAction({ type: 'NEXT' })` validates the current page, and if valid, increments the page index. On the last page, it auto-submits.
346
+ 3. **Validation**: When `NEXT` is dispatched, the SDK validates all required questions on the current page. If any are unanswered, it populates `state.validationErrors` and scrolls to the first error using `document.getElementById(questionId)`.
347
+ 4. **Scroll Navigation**: The SDK calls `document.getElementById(question.id)` and `.scrollIntoView()` for both validation error scrolling and page transition scrolling. This is why the client MUST set `id={question.id}` on question wrapper elements.
348
+ 5. **Progress Tracking**: `state.progressPercentage` is computed automatically based on answered questions across all pages.
349
+ 6. **Submission**: The SDK constructs the API payload and sends it to the Sprinklr CFM endpoint. The result is available in `submitSurveyResults.data`.
350
+ 7. **Language Switching**: Passing a different `language` option to `useSurveySDK()` triggers a re-mapping of the survey to the target locale. The raw API data is fetched once and translated client-side.
351
+ 8. **Placeholders**: Dynamic tokens like `{{FIRST_NAME}}` in question text are replaced at fetch time using the `placeholders` map.
352
+
353
+ ---
354
+
355
+ ## 4. Component Architecture Blueprint (Logic Skeletons)
356
+
357
+ > ⚠️ **IMPORTANT**: The code in this section shows **only the SDK data wiring and structural logic**. All styling has been intentionally stripped. You MUST design all visuals (colors, spacing, typography, layout, animations, hover states) from scratch based on the client's mockup or prompt. See [Section 6](#6-ui-fidelity--styling-rules) for styling guidance.
358
+
359
+ ### Recommended File Structure
360
+
361
+ Create a modular, multi-file component structure. **Never write all code in a single file** — always refactor into well-separated components for maintainability. The structure below is a strong default; adapt it as needed to match the client's UI complexity:
362
+
363
+ ```
364
+ src/
365
+ ├── app/
366
+ │ ├── globals.css # Tailwind import + brand CSS custom properties
367
+ │ ├── layout.tsx # Root HTML layout with metadata
368
+ │ └── page.tsx # Entry page with <Suspense> wrapper
369
+ └── components/
370
+ ├── SurveyPage.tsx # Main survey orchestrator (uses useSurveySDK) — REQUIRED
371
+ ├── Header.tsx # Brand header with logo — adapt to mockup
372
+ ├── Footer.tsx # Footer with optional links — adapt to mockup
373
+ ├── ProgressBar.tsx # Visual progress indicator — adapt to mockup
374
+ ├── Question.tsx # Question dispatcher (rating/radio/text) — REQUIRED
375
+ ├── RatingScale.tsx # Rating scale input component — REQUIRED for rating questions
376
+ ├── LanguageSelector.tsx # Language dropdown — include if survey is multi-language
377
+ └── [Additional].tsx # Add more components as the mockup demands (e.g., Sidebar, Stepper, ThankYou, etc.)
378
+ ```
379
+
380
+ **Guidelines for component breakdown**:
381
+ - `SurveyPage.tsx` and `Question.tsx` are always required — they contain critical SDK integration logic.
382
+ - `Header.tsx`, `Footer.tsx`, `ProgressBar.tsx` should exist as separate files unless the mockup clearly doesn't need them.
383
+ - If the mockup shows a complex layout (sidebar navigation, stepper, multi-column), create additional components as needed.
384
+ - If a component's JSX exceeds ~80 lines, extract sub-components.
385
+
386
+ ---
387
+
388
+ ### Logic Skeleton: `page.tsx` — Entry Point
389
+
390
+ ```tsx
391
+ import { Suspense } from "react";
392
+ import SurveyPage from "@/components/SurveyPage";
393
+
394
+ export default function Page() {
395
+ return (
396
+ <Suspense
397
+ fallback={
398
+ /* STYLE: Design a loading state that matches the client's brand.
399
+ This can be a spinner, skeleton screen, or branded loading message.
400
+ Must fill the viewport while survey data loads. */
401
+ <div>{/* Loading UI */}</div>
402
+ }
403
+ >
404
+ <SurveyPage />
405
+ </Suspense>
406
+ );
407
+ }
408
+ ```
409
+
410
+ ---
411
+
412
+ ### Logic Skeleton: `SurveyPage.tsx` — Main Orchestrator
413
+
414
+ This is the **only component** that calls `useSurveySDK()`. The logic below is **mandatory** — implement all 5 render states exactly as shown. Style each state to match the client's mockup.
415
+
416
+ ```tsx
417
+ 'use client';
418
+
419
+ import { useState } from 'react';
420
+ import { useSurveySDK } from '@explorer02/cfm-survey-sdk';
421
+ // Import your custom components — adjust names/paths to match your component structure
422
+ import Header from '@/components/Header';
423
+ import Footer from '@/components/Footer';
424
+ import Question from '@/components/Question';
425
+ import ProgressBar from '@/components/ProgressBar';
426
+ import LanguageSelector from '@/components/LanguageSelector';
427
+
428
+ // ⚠️ CRITICAL: Define placeholder values OUTSIDE the component body.
429
+ // Defining inside creates a new object every render → infinite re-fetch loop.
430
+ const SURVEY_PLACEHOLDERS = {
431
+ FIRST_NAME: 'Customer', // Replace with client-provided test values
432
+ LAST_NAME: '',
433
+ EMAIL_ADDRESS: '',
434
+ };
435
+
436
+ export default function SurveyPage() {
437
+ const [selectedLanguage, setSelectedLanguage] = useState<string | undefined>("");
438
+
439
+ const { surveyQueryResults, submitSurveyResults, state, onAction } = useSurveySDK({
440
+ options: {
441
+ language: selectedLanguage,
442
+ debug: false,
443
+ placeholders: SURVEY_PLACEHOLDERS,
444
+ },
445
+ });
446
+
447
+ const survey = surveyQueryResults.data;
448
+
449
+ // ══════════════════════════════════════════════════════
450
+ // STATE 1: LOADING
451
+ // Show while survey data is being fetched from the API.
452
+ // ══════════════════════════════════════════════════════
453
+ if (surveyQueryResults.isLoading) {
454
+ return (
455
+ /* STYLE: Design a full-page loading state.
456
+ Can include: skeleton screens, spinner, brand animation, or simple text.
457
+ Should match the overall page layout (header + centered content + footer). */
458
+ <div>{/* Loading UI */}</div>
459
+ );
460
+ }
461
+
462
+ // ══════════════════════════════════════════════════════
463
+ // STATE 2: ERROR
464
+ // Show when the API fetch fails (network error, bad response, etc.)
465
+ // ══════════════════════════════════════════════════════
466
+ if (surveyQueryResults.error) {
467
+ return (
468
+ /* STYLE: Design a user-friendly error state.
469
+ Show a clear message (not raw error text).
470
+ Example: "Something went wrong. Please try again later." */
471
+ <div>{/* Error UI — display surveyQueryResults.error.message for debugging */}</div>
472
+ );
473
+ }
474
+
475
+ // ══════════════════════════════════════════════════════
476
+ // STATE 3: NO DATA
477
+ // Show when the API returns successfully but with no survey data.
478
+ // ══════════════════════════════════════════════════════
479
+ if (!survey) {
480
+ return (
481
+ /* STYLE: Design an empty state.
482
+ Example: "This survey is no longer available." */
483
+ <div>{/* Empty state UI */}</div>
484
+ );
485
+ }
486
+
487
+ // ══════════════════════════════════════════════════════
488
+ // STATE 4: SUBMITTED
489
+ // Show after the survey has been successfully submitted.
490
+ // ══════════════════════════════════════════════════════
491
+ if (submitSurveyResults.data) {
492
+ return (
493
+ /* STYLE: Design a thank-you / confirmation screen.
494
+ Use the client's thank-you message from Phase 1 requirements.
495
+ Can include: checkmark animation, brand graphics, redirect timer. */
496
+ <div>{/* Thank-you UI */}</div>
497
+ );
498
+ }
499
+
500
+ // ══════════════════════════════════════════════════════
501
+ // STATE 5: ACTIVE SURVEY
502
+ // The main survey view with questions, navigation, and progress.
503
+ // This is where all the visual design work happens.
504
+ // ══════════════════════════════════════════════════════
505
+ return (
506
+ <div>
507
+ {/* STYLE: Design the overall page layout to match the client's mockup. */}
508
+
509
+ {/* Header — pass brand data as needed */}
510
+ <Header />
511
+
512
+ {/* Progress Bar — receives percentage from SDK */}
513
+ <ProgressBar progressPercentage={state.progressPercentage} />
514
+
515
+ {/* Language Selector — only render if survey has multiple languages */}
516
+ {survey.languages.length > 1 && (
517
+ <LanguageSelector
518
+ languages={survey.languages}
519
+ selectedLanguage={survey.language}
520
+ onChange={setSelectedLanguage}
521
+ />
522
+ )}
523
+
524
+ {/* Questions — iterate over currentQuestions and render each one */}
525
+ <main>
526
+ {state.currentQuestions.map(question => (
527
+ <Question
528
+ key={question.id}
529
+ question={question}
530
+ selectedValue={state.values[question.id]}
531
+ validationError={state.validationErrors[question.id]}
532
+ onSelect={value =>
533
+ onAction({ type: 'CHANGE', payload: { questionId: question.id, value } })
534
+ }
535
+ />
536
+ ))}
537
+ </main>
538
+
539
+ {/* Submission Error — display if submission fails */}
540
+ {submitSurveyResults.error && (
541
+ /* STYLE: Design an inline error message for submission failures. */
542
+ <div>{submitSurveyResults.error.message}</div>
543
+ )}
544
+
545
+ {/* Navigation Buttons */}
546
+ <nav>
547
+ {/* Back Button — only show if not on the first page */}
548
+ {state.currentPageIndex > 0 && (
549
+ <button
550
+ type="button"
551
+ onClick={() => onAction({ type: 'PREVIOUS' })}
552
+ /* STYLE: Design a secondary/outline button matching the mockup. */
553
+ >
554
+ {/* STYLE: Use client's preferred label (e.g., "Back", "Previous", "Zurück") */}
555
+ Back
556
+ </button>
557
+ )}
558
+
559
+ {/* Next / Submit Button */}
560
+ <button
561
+ type="button"
562
+ onClick={() => onAction({ type: 'NEXT' })}
563
+ disabled={submitSurveyResults.isLoading}
564
+ /* STYLE: Design a primary action button matching the mockup.
565
+ Must have disabled state styling for when submission is in progress. */
566
+ >
567
+ {submitSurveyResults.isLoading
568
+ ? 'Submitting...'
569
+ : state.currentPageIndex < survey.pages.length - 1
570
+ ? 'Next'
571
+ : 'Submit'}
572
+ </button>
573
+ </nav>
574
+
575
+ {/* Footer — pass links/data as needed */}
576
+ <Footer />
577
+ </div>
578
+ );
579
+ }
580
+ ```
581
+
582
+ ---
583
+
584
+ ### Logic Skeleton: `Question.tsx` — Question Renderer
585
+
586
+ **⚠️ CRITICAL**: The outermost element MUST have `id={question.id}`. This enables the SDK's scroll-to-error and page-transition scroll features.
587
+
588
+ ```tsx
589
+ import type { SurveyQuestion } from '@explorer02/cfm-survey-sdk';
590
+ import RatingScale from './RatingScale';
591
+
592
+ type QuestionProps = {
593
+ question: SurveyQuestion;
594
+ selectedValue?: string | number;
595
+ validationError?: string;
596
+ onSelect: (value: string | number) => void;
597
+ };
598
+
599
+ export default function Question({ question, selectedValue, validationError, onSelect }: QuestionProps) {
600
+ return (
601
+ // ⚠️ MANDATORY: id={question.id} — the SDK uses document.getElementById() for scroll navigation.
602
+ // Do NOT modify, prefix, or omit this ID.
603
+ <section id={question.id}>
604
+
605
+ {/* Question Title
606
+ ⚠️ MANDATORY: Use dangerouslySetInnerHTML — question.text may contain HTML markup. */}
607
+ <h2>
608
+ <span dangerouslySetInnerHTML={{ __html: question.text }} />
609
+ {question.required && (
610
+ /* STYLE: Design a required indicator (e.g., red asterisk, "(required)" label) */
611
+ <span>*</span>
612
+ )}
613
+ </h2>
614
+
615
+ {/* ── RATING TYPE ─────────────────────────────────── */}
616
+ {question.type === 'rating' && (
617
+ <div>
618
+ {/* Scale Endpoint Labels — display min/mid/max labels if available */}
619
+ {(question.minLabel || question.midLabel || question.maxLabel) && (
620
+ <div>
621
+ {/* STYLE: Position these labels at the start, middle, and end of the scale.
622
+ Use dangerouslySetInnerHTML for labels (may contain HTML).
623
+ For midLabel positioning, use question.midLabelIndex:
624
+ position = (midLabelIndex / (options.length - 1)) * 100 → percentage */}
625
+ {question.minLabel && (
626
+ <span dangerouslySetInnerHTML={{ __html: question.minLabel }} />
627
+ )}
628
+ {question.midLabel && (
629
+ <span
630
+ dangerouslySetInnerHTML={{ __html: question.midLabel }}
631
+ /* STYLE: Position at calculated percentage based on midLabelIndex */
632
+ />
633
+ )}
634
+ {question.maxLabel && (
635
+ <span dangerouslySetInnerHTML={{ __html: question.maxLabel }} />
636
+ )}
637
+ </div>
638
+ )}
639
+
640
+ {/* Rating Scale Component — handles the individual rating options */}
641
+ <RatingScale
642
+ questionId={question.id}
643
+ options={question.options}
644
+ selectedValue={selectedValue}
645
+ onSelect={onSelect}
646
+ />
647
+ </div>
648
+ )}
649
+
650
+ {/* ── RADIO TYPE ──────────────────────────────────── */}
651
+ {question.type === 'radio' && (
652
+ <div>
653
+ {/* STYLE: Design radio option cards/buttons matching the mockup.
654
+ Each option should have: default, hover, and selected states. */}
655
+ {question.options.map(option => {
656
+ const isSelected = selectedValue === option.value;
657
+ return (
658
+ <label key={option.value}>
659
+ {/* Hidden native radio — use className="sr-only" for accessibility */}
660
+ <input
661
+ type="radio"
662
+ name={question.id}
663
+ value={option.value}
664
+ checked={isSelected}
665
+ onChange={() => onSelect(option.value)}
666
+ className="sr-only"
667
+ />
668
+
669
+ {/* STYLE: Design a custom radio indicator (circle, checkmark, etc.)
670
+ Must visually differentiate selected vs. unselected state. */}
671
+ <div>{/* Custom radio indicator */}</div>
672
+
673
+ {/* Option Label — use dangerouslySetInnerHTML (may contain HTML) */}
674
+ <span dangerouslySetInnerHTML={{ __html: option.label }} />
675
+ </label>
676
+ );
677
+ })}
678
+ </div>
679
+ )}
680
+
681
+ {/* ── TEXT TYPE ────────────────────────────────────── */}
682
+ {question.type === 'text' && (
683
+ <div>
684
+ <textarea
685
+ rows={4}
686
+ value={selectedValue ?? ''}
687
+ onChange={e => onSelect(e.target.value)}
688
+ placeholder={question.placeholder || 'Type your response here...'}
689
+ /* STYLE: Design the textarea to match the mockup.
690
+ Include focus state styling (border color, ring, etc.) */
691
+ />
692
+
693
+ {/* Character Counter — show remaining characters if maxCharacterCount is set */}
694
+ {question.maxCharacterCount && (
695
+ <div>
696
+ {/* STYLE: Design a character counter (e.g., "250 characters remaining") */}
697
+ {Math.max(
698
+ 0,
699
+ question.maxCharacterCount - (typeof selectedValue === 'string' ? selectedValue.length : 0)
700
+ )}{' '}
701
+ characters remaining
702
+ </div>
703
+ )}
704
+ </div>
705
+ )}
706
+
707
+ {/* Validation Error — display when the SDK flags a required question as unanswered */}
708
+ {validationError && (
709
+ /* STYLE: Design a visible error message.
710
+ Must be clearly noticeable (e.g., red text, bordered box, icon).
711
+ Do NOT use subtle styling — users must see this immediately. */
712
+ <div>
713
+ <p>{validationError}</p>
714
+ </div>
715
+ )}
716
+ </section>
717
+ );
718
+ }
719
+ ```
720
+
721
+ ---
722
+
723
+ ### Logic Skeleton: `RatingScale.tsx` — Rating Input
724
+
725
+ ```tsx
726
+ type RatingScaleProps = {
727
+ questionId: string;
728
+ options: { label: string; value: string | number; color?: string }[];
729
+ selectedValue?: string | number;
730
+ onSelect: (value: string | number) => void;
731
+ };
732
+
733
+ export default function RatingScale({ questionId, options, selectedValue, onSelect }: RatingScaleProps) {
734
+ return (
735
+ <div>
736
+ {/* STYLE: Design the rating scale layout to match the mockup.
737
+ Common patterns: horizontal badge row, numbered circles, star rating, slider.
738
+ Each option.color (if present) should be used as the badge/indicator background color. */}
739
+ {options.map(option => {
740
+ const isSelected = selectedValue === option.value;
741
+ return (
742
+ <button
743
+ key={option.value}
744
+ type="button"
745
+ onClick={() => onSelect(option.value)}
746
+ /* STYLE: Design selected vs. unselected states.
747
+ If option.color is available, use it: style={{ backgroundColor: option.color }}
748
+ Must be clearly distinguishable which option is selected. */
749
+ >
750
+ {option.label}
751
+ </button>
752
+ );
753
+ })}
754
+ </div>
755
+ );
756
+ }
757
+ ```
758
+
759
+ ---
760
+
761
+ ### Logic Skeleton: `LanguageSelector.tsx`
762
+
763
+ ```tsx
764
+ import type { SurveyLanguage } from '@explorer02/cfm-survey-sdk';
765
+
766
+ type LanguageSelectorProps = {
767
+ languages: SurveyLanguage[];
768
+ selectedLanguage: string;
769
+ onChange: (languageCode: string) => void;
770
+ };
771
+
772
+ export default function LanguageSelector({ languages, selectedLanguage, onChange }: LanguageSelectorProps) {
773
+ // Don't render if there's only one language
774
+ if (!languages || languages.length <= 1) return null;
775
+
776
+ return (
777
+ /* STYLE: Design a language selector matching the mockup.
778
+ Common patterns: dropdown, pill buttons, flag icons.
779
+ Position according to the mockup (e.g., top-right corner, header area). */
780
+ <div>
781
+ <select
782
+ value={selectedLanguage}
783
+ onChange={e => onChange(e.target.value)}
784
+ /* STYLE: Style the select element or replace with a custom dropdown component. */
785
+ >
786
+ {languages.map(lang => (
787
+ <option key={lang.code} value={lang.code}>{lang.name}</option>
788
+ ))}
789
+ </select>
790
+ </div>
791
+ );
792
+ }
793
+ ```
794
+
795
+ ---
796
+
797
+ ### Logic Skeleton: `ProgressBar.tsx`
798
+
799
+ ```tsx
800
+ type ProgressBarProps = {
801
+ progressPercentage: number;
802
+ };
803
+
804
+ export default function ProgressBar({ progressPercentage }: ProgressBarProps) {
805
+ return (
806
+ /* STYLE: Design a progress indicator matching the mockup.
807
+ Common patterns: horizontal bar, circular/radial progress, step indicator, percentage text.
808
+ Use progressPercentage (0–100) to control the fill width/amount.
809
+ Add a smooth transition animation for width changes. */
810
+ <div>
811
+ <div style={{ width: `${progressPercentage}%` }}>
812
+ {/* Progress fill */}
813
+ </div>
814
+ </div>
815
+ );
816
+ }
817
+ ```
818
+
819
+ ---
820
+
821
+ ### Logic Skeleton: `Header.tsx` and `Footer.tsx`
822
+
823
+ These are **fully custom layout components** — there is no SDK logic here. Build them entirely from the client's mockup/brand:
824
+
825
+ - **Header**: May include logo (use Next.js `<Image>` with `priority`), survey title, brand graphics.
826
+ - **Footer**: May include legal links (Privacy Policy, Imprint), copyright text, brand logo.
827
+
828
+ If the mockup doesn't show a header or footer, you may omit these components.
829
+
830
+ ---
831
+
832
+ ## 5. Critical Constraints & Rules
833
+
834
+ These are **non-negotiable** requirements that must be followed in every build:
835
+
836
+ ### 5a. HTML Element IDs for Scroll Navigation
837
+
838
+ The SDK internally uses `document.getElementById(question.id)` to find question elements in the DOM for:
839
+ - **Scroll-to-error**: When validation fails, the SDK scrolls to the first unanswered required question.
840
+ - **Page transition scroll**: When navigating to a new page, the SDK scrolls to the first question.
841
+
842
+ **Rule**: Every question wrapper element MUST have `id={question.id}`:
843
+ ```tsx
844
+ // ✅ CORRECT — SDK can find this element
845
+ <section id={question.id}>...</section>
846
+
847
+ // ❌ WRONG — SDK cannot find the element, scroll will fail silently
848
+ <section>...</section>
849
+ <section id={`question-${question.id}`}>...</section> // Modified ID, won't match
850
+ ```
851
+
852
+ ### 5b. Import Rules
853
+
854
+ | Import | Source | Used In |
855
+ |--------|--------|---------|
856
+ | `useSurveySDK` | `@explorer02/cfm-survey-sdk` | `SurveyPage.tsx` only |
857
+ | `type SurveyQuestion` | `@explorer02/cfm-survey-sdk` | `Question.tsx` component props |
858
+ | `type SurveyLanguage` | `@explorer02/cfm-survey-sdk` | `LanguageSelector.tsx` component props |
859
+
860
+ **Never import internal SDK modules**. Only use the public exports listed above.
861
+
862
+ ### 5c. `'use client'` Directive
863
+
864
+ The `SurveyPage.tsx` component MUST have `'use client';` as the very first line. This is required because:
865
+ - `useSurveySDK()` is a React hook (client-only).
866
+ - `useState` for language selection is client-only.
867
+
868
+ Child components (`Question`, `Header`, `Footer`, etc.) do NOT need `'use client'` because they receive data as props from the parent client component.
869
+
870
+ ### 5d. `<Suspense>` Boundary
871
+
872
+ The main `page.tsx` must wrap `<SurveyPage />` in a `<Suspense>` boundary. This prevents hydration mismatches and provides a loading fallback while the client component initialises.
873
+
874
+ ### 5e. Placeholder Constants
875
+
876
+ Define placeholder values as a **constant object outside the component** to avoid unnecessary re-renders:
877
+
878
+ ```tsx
879
+ // ✅ CORRECT — stable reference, defined outside component
880
+ const SURVEY_PLACEHOLDERS = { FIRST_NAME: 'John', LAST_NAME: 'Doe' };
881
+
882
+ export default function SurveyPage() {
883
+ const { ... } = useSurveySDK({ options: { placeholders: SURVEY_PLACEHOLDERS } });
884
+ }
885
+
886
+ // ❌ WRONG — new object created every render, triggers infinite re-fetch
887
+ export default function SurveyPage() {
888
+ const { ... } = useSurveySDK({ options: { placeholders: { FIRST_NAME: 'John' } } });
889
+ }
890
+ ```
891
+
892
+ ### 5f. Action Dispatching Pattern
893
+
894
+ Always use `onAction()` for ALL user interactions. Never call internal SDK functions directly:
895
+
896
+ ```tsx
897
+ // ✅ CORRECT
898
+ onAction({ type: 'CHANGE', payload: { questionId: question.id, value: newValue } })
899
+ onAction({ type: 'NEXT' })
900
+ onAction({ type: 'PREVIOUS' })
901
+
902
+ // ❌ WRONG — bypasses SDK validation, logging, and analytics
903
+ setValues(prev => ({ ...prev, [question.id]: newValue }))
904
+ setCurrentPageIndex(prev => prev + 1)
905
+ ```
906
+
907
+ ---
908
+
909
+ ## 6. UI Fidelity & Styling Rules
910
+
911
+ ### Styling Framework
912
+
913
+ **Default**: Use **Tailwind CSS** utility classes for all styling. The `create-next-app --tailwind` setup in Phase 2 configures this automatically.
914
+
915
+ **Alternative**: If the client explicitly requests a different styling approach (vanilla CSS, CSS Modules, styled-components, etc.), you may use that instead. The SDK has **zero CSS dependencies** — it works with any styling solution.
916
+
917
+ ---
918
+
919
+ ### 6a. Design Analysis Checklist (When Client Provides Screenshots)
920
+
921
+ When the client shares UI mockup images, **systematically extract every design detail** before writing any code. Go through this checklist:
922
+
923
+ #### Colors
924
+ - [ ] **Primary brand color** — The dominant accent color (buttons, progress bar, selected states)
925
+ - [ ] **Secondary color** — If used for secondary buttons, links, or accents
926
+ - [ ] **Background color** — Page background (white, off-white, dark, gradient?)
927
+ - [ ] **Card/surface color** — Background for question cards or content areas
928
+ - [ ] **Text colors** — Primary text, secondary/muted text, heading text
929
+ - [ ] **Border colors** — Default borders, active/selected borders
930
+ - [ ] **Error color** — Validation error messages and indicators
931
+ - [ ] **Selected state colors** — Background tint and border for selected options
932
+
933
+ #### Typography
934
+ - [ ] **Font family** — Identify the typeface (use Google Fonts if not a system font)
935
+ - [ ] **Heading sizes** — H1, H2, question title sizes
936
+ - [ ] **Body text size** — Default paragraph and option label sizes
937
+ - [ ] **Font weights** — Regular, medium, semibold, bold usage
938
+ - [ ] **Line heights** — Tight, normal, or relaxed spacing
939
+
940
+ #### Layout & Spacing
941
+ - [ ] **Page max-width** — Content area width (narrow, medium, wide, full-bleed)
942
+ - [ ] **Header height and structure** — Fixed? Contains logo? Background color?
943
+ - [ ] **Content padding** — Horizontal and vertical spacing around the main content
944
+ - [ ] **Question spacing** — Gap between consecutive questions
945
+ - [ ] **Option spacing** — Gap between radio options or rating badges
946
+ - [ ] **Footer position** — Sticky? Fixed at bottom? Below content?
947
+
948
+ #### Component Styles
949
+ - [ ] **Card design** — Border radius, shadow, padding, background
950
+ - [ ] **Button design** — Border radius, padding, font size, hover/active/disabled states
951
+ - [ ] **Radio/option cards** — Shape, border style, selected highlight
952
+ - [ ] **Rating scale style** — Badges, circles, numbered grid, stars?
953
+ - [ ] **Progress bar style** — Bar thickness, border radius, animation
954
+ - [ ] **Input field style** — Border, border radius, focus ring
955
+
956
+ #### Interactive States
957
+ - [ ] **Hover effects** — Color changes, shadows, scale transforms
958
+ - [ ] **Selected state** — How selected options differ from unselected
959
+ - [ ] **Disabled state** — How the submit button looks while submitting
960
+ - [ ] **Error state** — How validation errors are displayed (inline, toast, bordered box)
961
+ - [ ] **Transitions** — Smooth transitions on state changes (duration, easing)
962
+
963
+ After completing this checklist, define the extracted values as **CSS custom properties** in `globals.css`:
964
+
965
+ ```css
966
+ @import "tailwindcss";
967
+
968
+ :root {
969
+ --brand-color: /* extracted primary color */;
970
+ --brand-bg-light: /* light tint of primary for selected backgrounds */;
971
+ --bg-page: /* page background */;
972
+ --bg-card: /* card/surface background */;
973
+ --text-primary: /* primary text color */;
974
+ --text-secondary: /* secondary/muted text */;
975
+ --border-default: /* default border color */;
976
+ --border-active: /* selected/active border color */;
977
+ --radius-card: /* card border radius */;
978
+ --radius-button: /* button border radius */;
979
+ }
980
+ ```
981
+
982
+ ---
983
+
984
+ ### 6b. When the Client Provides a Color Scheme or Brand Guidelines
985
+
986
+ Apply the primary color to:
987
+ - Progress bar fill
988
+ - Selected radio button indicators
989
+ - Selected rating scale highlights
990
+ - Primary action button (Next/Submit) background
991
+ - Focus ring on text inputs
992
+ - Active border on radio option cards
993
+
994
+ Apply a light tint of the primary color to:
995
+ - Selected radio card backgrounds
996
+ - Selected rating scale cell backgrounds
997
+
998
+ ---
999
+
1000
+ ### 6c. No-Mockup Default Design
1001
+
1002
+ When the client provides **only a text prompt with no screenshots, mockup, or brand guidelines**, use this clean, modern default design system:
1003
+
1004
+ | Property | Default Value |
1005
+ |----------|---------------|
1006
+ | **Background** | White (`#ffffff`) |
1007
+ | **Text color** | Dark gray (`#1a1a1a`) |
1008
+ | **Secondary text** | Medium gray (`#6b7280`) |
1009
+ | **Brand/accent color** | Ask the client; if none given, use a professional blue (`#2563eb`) |
1010
+ | **Font family** | System font stack: `system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif` |
1011
+ | **Content max-width** | `max-w-3xl` (48rem / 768px) |
1012
+ | **Card style** | White background, 1px `#e5e7eb` border, `0.75rem` border radius, `1.5rem` padding |
1013
+ | **Button style** | Brand color background, white text, `0.5rem` border radius, medium font weight |
1014
+ | **Radio options** | Card-style with border, subtle hover bg, brand-color border + light tint bg when selected |
1015
+ | **Rating scale** | Horizontal row of numbered badges, brand-color highlight on selected |
1016
+ | **Progress bar** | 4px height, gray-100 track, brand-color fill, rounded-full, smooth width transition |
1017
+ | **Spacing** | `2rem` between questions, `1rem` between options |
1018
+ | **Transitions** | `transition-all duration-200` on interactive elements |
1019
+
1020
+ This creates a neutral, professional design that works for any brand. The agent should **still ask the client for their brand color** — it's the single most impactful customisation.
1021
+
1022
+ ---
1023
+
1024
+ ### 6d. General Styling Standards (Apply to All Builds)
1025
+
1026
+ - Ensure full **responsive design** (mobile-first with `sm:`, `md:`, `lg:` breakpoints).
1027
+ - Add **smooth transitions** on interactive elements.
1028
+ - Use **`sr-only`** class to hide native radio inputs while keeping them accessible.
1029
+ - Rating badges should display the option's `color` property using inline `style={{ backgroundColor: option.color }}` when available.
1030
+ - Text areas should show a **character count** using `question.maxCharacterCount`.
1031
+ - Validation errors should be **visually prominent** (not subtle gray text).
1032
+
1033
+ ### 6e. Logo Handling
1034
+
1035
+ If the client provides a logo:
1036
+ 1. Save it to the `public/` directory (e.g., `public/logo.svg` or `public/logo.png`).
1037
+ 2. Use Next.js `<Image>` component with `priority` attribute for above-the-fold rendering.
1038
+ 3. Set appropriate `width` and `height` props.
1039
+
1040
+ ---
1041
+
1042
+ ## 7. Configuration & Build Requirements
1043
+
1044
+ ### 7a. Required Dependencies
1045
+
1046
+ ```json
1047
+ {
1048
+ "dependencies": {
1049
+ "@explorer02/cfm-survey-sdk": "latest",
1050
+ "@tanstack/react-query": "^5.0.0",
1051
+ "next": "^15.0.0",
1052
+ "react": "^19.0.0",
1053
+ "react-dom": "^19.0.0"
1054
+ },
1055
+ "devDependencies": {
1056
+ "@tailwindcss/postcss": "^4.0.0",
1057
+ "@types/node": "^22.0.0",
1058
+ "@types/react": "^19.0.0",
1059
+ "@types/react-dom": "^19.0.0",
1060
+ "eslint": "^9.0.0",
1061
+ "eslint-config-next": "^15.0.0",
1062
+ "postcss": "^8.0.0",
1063
+ "tailwindcss": "^4.0.0",
1064
+ "typescript": "^5.0.0"
1065
+ }
1066
+ }
1067
+ ```
1068
+
1069
+ ### 7b. `next.config.js` — MANDATORY Configuration
1070
+
1071
+ ```javascript
1072
+ /** @type {import('next').NextConfig} */
1073
+ const nextConfig = {
1074
+ reactStrictMode: true,
1075
+ transpilePackages: ["@explorer02/cfm-survey-sdk"],
1076
+ };
1077
+
1078
+ module.exports = nextConfig;
1079
+ ```
1080
+
1081
+ > **Why `transpilePackages` is required**: In this monorepo workspace, it allows Next.js to watch the local SDK files directly and hot-reload changes in real-time. For clients, since the SDK compiles to modern ES2022 JavaScript, transpiling allows Next.js's SWC compiler to tree-shake the code and down-transpile it to fit any older browser targets specified by the client application.
1082
+
1083
+ ### 7c. `layout.tsx` — Root Layout
1084
+
1085
+ ```tsx
1086
+ import type { Metadata } from "next";
1087
+ import "./globals.css";
1088
+
1089
+ export const metadata: Metadata = {
1090
+ title: "Customer Survey", // ← Replace with client's survey title
1091
+ description: "Customer feedback survey",
1092
+ };
1093
+
1094
+ export default function RootLayout({
1095
+ children,
1096
+ }: Readonly<{ children: React.ReactNode }>) {
1097
+ return (
1098
+ <html lang="en">
1099
+ <body>{children}</body>
1100
+ </html>
1101
+ );
1102
+ }
1103
+ ```
1104
+
1105
+ ---
1106
+
1107
+ ## 8. Deployment Phase
1108
+
1109
+ ### Pre-Deployment Checklist
1110
+
1111
+ Before deploying, verify:
1112
+ - [ ] `npm run build` completes with zero errors
1113
+ - [ ] `next.config.js` has `transpilePackages: ["@explorer02/cfm-survey-sdk"]`
1114
+ - [ ] Logo files (if any) are in the `public/` directory
1115
+ - [ ] All components use `id={question.id}` on question wrappers
1116
+ - [ ] UI Verification Checklist (Phase 6) has been completed
1117
+
1118
+ ### Deployment Command
1119
+
1120
+ Based on the `deployToVercel` flag inside `./survey-config.json` (or user approval in chat):
1121
+
1122
+ ```bash
1123
+ npx cfm-sdk deploy
1124
+ ```
1125
+
1126
+ This command handles the full Vercel deployment pipeline:
1127
+ 1. **Node.js version check** — Ensures v18+ is installed.
1128
+ 2. **Vercel CLI check** — Installs Vercel CLI globally if missing (with user consent), or falls back to `npx`.
1129
+ 3. **Vercel authentication** — Checks for `VERCEL_TOKEN` env variable or prompts interactive login.
1130
+ 4. **Production deployment** — Runs `vercel --prod --yes` and outputs the live URL.
1131
+
1132
+ If the deployment command is not available (e.g., SDK not installed globally), you can deploy manually:
1133
+
1134
+ ```bash
1135
+ npx vercel --prod --yes
1136
+ ```
1137
+
1138
+ ---
1139
+
1140
+ ## 9. Reference: Styled Code Templates (Reference Only)
1141
+
1142
+ > ⚠️ **WARNING — DO NOT COPY-PASTE STYLING FROM THIS SECTION**
1143
+ >
1144
+ > The styled code below is a **reference implementation** from one specific client (Telekom). It is included **only** to show how the SDK data wiring connects to a real, working UI. The Tailwind classes, colors (`#e20074`), layout choices, and component designs in this section are **NOT universal** — they are specific to one brand.
1145
+ >
1146
+ > **What you MUST do instead**:
1147
+ > 1. Use the **Logic Skeletons in Section 4** for the SDK integration structure.
1148
+ > 2. Design **all visuals from scratch** based on the client's mockup or prompt.
1149
+ > 3. Refer to this section ONLY to understand how SDK data flows into JSX — never for styling decisions.
1150
+
1151
+ ### `src/app/globals.css`
1152
+ ```css
1153
+ @import "tailwindcss";
1154
+
1155
+ :root {
1156
+ --brand-color: #e20074;
1157
+ --brand-bg-light: #fdf2f8;
1158
+ }
1159
+
1160
+ body {
1161
+ margin: 0;
1162
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1163
+ color: #262626;
1164
+ background-color: #ffffff;
1165
+ }
1166
+ ```
1167
+
1168
+ ### `src/app/layout.tsx`
1169
+ ```tsx
1170
+ import type { Metadata } from "next";
1171
+ import "./globals.css";
1172
+
1173
+ export const metadata: Metadata = {
1174
+ title: "Customer Survey",
1175
+ description: "Customer feedback survey",
1176
+ };
1177
+
1178
+ export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
1179
+ return (
1180
+ <html lang="en">
1181
+ <body>{children}</body>
1182
+ </html>
1183
+ );
1184
+ }
1185
+ ```
1186
+
1187
+ ### `src/app/page.tsx`
1188
+ ```tsx
1189
+ import { Suspense } from "react";
1190
+ import SurveyPage from "@/components/SurveyPage";
1191
+
1192
+ export default function Page() {
1193
+ return (
1194
+ <Suspense fallback={<div className="flex min-h-screen items-center justify-center"><p>Loading...</p></div>}>
1195
+ <SurveyPage />
1196
+ </Suspense>
1197
+ );
1198
+ }
1199
+ ```
1200
+
1201
+ ### `next.config.js`
1202
+ ```javascript
1203
+ /** @type {import('next').NextConfig} */
1204
+ const nextConfig = {
1205
+ reactStrictMode: true,
1206
+ transpilePackages: ["@explorer02/cfm-survey-sdk"],
1207
+ };
1208
+ module.exports = nextConfig;
1209
+ ```
1210
+
1211
+ ---
1212
+
1213
+ ## Appendix A: Other Frameworks (Vite, Remix, CRA)
1214
+
1215
+ The SDK's `useSurveySDK()` hook is a **standard React hook** — it works in any React-based framework, not just Next.js. Here are the key differences when using other frameworks:
1216
+
1217
+ ### Vite + React
1218
+
1219
+ ```bash
1220
+ # Initialise
1221
+ npx -y create-vite@latest ./ --template react-ts
1222
+
1223
+ # Install dependencies
1224
+ npm install @explorer02/cfm-survey-sdk @tanstack/react-query
1225
+ ```
1226
+
1227
+ **Key differences from Next.js**:
1228
+ - ❌ **No `transpilePackages` needed** — Vite handles TypeScript transpilation natively.
1229
+ - ❌ **No `'use client'` directive needed** — Vite doesn't use Server Components.
1230
+ - ❌ **No `<Suspense>` boundary needed** — No Server Component hydration concerns.
1231
+ - ✅ **Still needs `useSurveySDK()`**, `id={question.id}`, `SURVEY_PLACEHOLDERS` outside component, and `onAction()` dispatcher — all SDK constraints still apply.
1232
+
1233
+ ### Remix
1234
+
1235
+ ```bash
1236
+ npx -y create-remix@latest ./
1237
+ npm install @explorer02/cfm-survey-sdk @tanstack/react-query
1238
+ ```
1239
+
1240
+ **Key differences from Next.js**:
1241
+ - ❌ **No `transpilePackages` needed** — Remix uses Vite/esbuild under the hood.
1242
+ - ✅ **`'use client'` IS needed** in Remix v2 if using Server Components (depends on version).
1243
+ - ✅ All SDK constraints still apply.
1244
+
1245
+ ### Create React App (CRA)
1246
+
1247
+ ```bash
1248
+ npx -y create-react-app ./ --template typescript
1249
+ npm install @explorer02/cfm-survey-sdk @tanstack/react-query
1250
+ ```
1251
+
1252
+ **Key differences from Next.js**:
1253
+ - ❌ **No `transpilePackages` needed** — CRA's webpack config handles this.
1254
+ - ❌ **No `'use client'` directive** — CRA doesn't have Server Components.
1255
+ - ❌ **No `<Suspense>` boundary needed** — No SSR concerns.
1256
+ - ✅ All SDK constraints still apply.
1257
+
1258
+ ### Universal SDK Constraints (Apply to ALL Frameworks)
1259
+
1260
+ Regardless of framework, these rules always apply:
1261
+ 1. `id={question.id}` on question wrappers — for scroll navigation.
1262
+ 2. `dangerouslySetInnerHTML={{ __html: question.text }}` — for HTML in question text.
1263
+ 3. `SURVEY_PLACEHOLDERS` defined outside the component — to prevent infinite re-renders.
1264
+ 4. `onAction()` for all user interactions — never bypass the dispatcher.
1265
+ 5. Import only from `@explorer02/cfm-survey-sdk` — never from internal paths.
1266
+
1267
+ ---
1268
+
1269
+ ## Troubleshooting Guide
1270
+
1271
+ | Symptom | Cause | Fix |
1272
+ |---------|-------|-----|
1273
+ | `SyntaxError: Unexpected token 'export'` | Missing `transpilePackages` in `next.config.js` | Add `transpilePackages: ["@explorer02/cfm-survey-sdk"]` |
1274
+ | Scroll-to-error doesn't work | Missing `id={question.id}` on question wrapper | Add `id={question.id}` to the outermost element of each question |
1275
+ | Survey shows "No survey data" | SDK cannot reach the API endpoint | Check network connectivity; the SDK fetches from `https://custom-p0.feedbook.me/api/feedback/survey/cfm` |
1276
+ | Infinite re-renders | Placeholders object defined inside component | Move `SURVEY_PLACEHOLDERS` outside the component body |
1277
+ | `type SurveyQuestion` import error | Importing from wrong path | Import from `@explorer02/cfm-survey-sdk`, not internal paths |
1278
+ | Tailwind classes not applying | Missing `@import "tailwindcss"` in CSS | Add `@import "tailwindcss";` to `globals.css` |
1279
+ | Build error: "Cannot find module" | Missing dependencies | Run `npm install @explorer02/cfm-survey-sdk @tanstack/react-query` |
1280
+ | Hydration mismatch errors | Missing `<Suspense>` boundary in `page.tsx` | Wrap `<SurveyPage />` in `<Suspense>` in the entry page |
1281
+ | Survey looks identical to another client's | Agent copied styling from Section 9 reference | Delete all copied styles; redesign from scratch using Section 4 skeletons + client mockup |