@the-seeker/feedback-react-native 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +215 -2
  2. package/dist/core/client.d.ts +57 -0
  3. package/dist/core/client.js +113 -0
  4. package/dist/core/config.d.ts +59 -0
  5. package/dist/core/config.js +112 -0
  6. package/dist/core/request.d.ts +53 -0
  7. package/dist/core/request.js +86 -0
  8. package/dist/core/survey.d.ts +12 -0
  9. package/dist/core/survey.js +26 -0
  10. package/dist/core/texts.d.ts +104 -0
  11. package/dist/core/texts.js +140 -0
  12. package/dist/core/theme.d.ts +6 -0
  13. package/dist/core/theme.js +55 -0
  14. package/dist/index.d.ts +14 -0
  15. package/dist/index.js +32 -0
  16. package/dist/ui/Attachments.d.ts +9 -0
  17. package/dist/ui/Attachments.js +27 -0
  18. package/dist/ui/FeedbackForm.d.ts +8 -0
  19. package/dist/ui/FeedbackForm.js +90 -0
  20. package/dist/ui/FeedbackSheet.d.ts +2 -0
  21. package/dist/ui/FeedbackSheet.js +32 -0
  22. package/dist/ui/Inline.d.ts +6 -0
  23. package/dist/ui/Inline.js +16 -0
  24. package/dist/ui/Launcher.d.ts +1 -0
  25. package/dist/ui/Launcher.js +14 -0
  26. package/dist/ui/Provider.d.ts +21 -0
  27. package/dist/ui/Provider.js +131 -0
  28. package/dist/ui/SurveyPrompt.d.ts +2 -0
  29. package/dist/ui/SurveyPrompt.js +52 -0
  30. package/dist/ui/context.d.ts +79 -0
  31. package/dist/ui/context.js +28 -0
  32. package/dist/ui/device.d.ts +10 -0
  33. package/dist/ui/device.js +22 -0
  34. package/dist/ui/forms.d.ts +32 -0
  35. package/dist/ui/forms.js +62 -0
  36. package/dist/ui/primitives.d.ts +33 -0
  37. package/dist/ui/primitives.js +55 -0
  38. package/dist/ui/prop-state.d.ts +9 -0
  39. package/dist/ui/prop-state.js +27 -0
  40. package/dist/ui/storage.d.ts +15 -0
  41. package/dist/ui/storage.js +35 -0
  42. package/dist/ui/styles.d.ts +697 -0
  43. package/dist/ui/styles.js +177 -0
  44. package/dist/ui/tokens.d.ts +16 -0
  45. package/dist/ui/tokens.js +62 -0
  46. package/dist/ui/useSurvey.d.ts +12 -0
  47. package/dist/ui/useSurvey.js +52 -0
  48. package/package.json +34 -4
package/README.md CHANGED
@@ -1,3 +1,216 @@
1
- # Temporary Holding Version
1
+ # @the-seeker/feedback-react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TheSeeker CRM 피드백 위젯을 React Native·Expo 앱에 붙이는 SDK입니다. 순수 JS라 네이티브 모듈·prebuild 없이 Expo Go에서도 동작합니다. 웹 위젯과 같은 설정(문구·테마·표시 방식·설문)을 CRM에서 그대로 가져옵니다.
4
+
5
+ 자세한 설치 가이드: https://docs.theseeker.io/feedback/app-install
6
+
7
+ ## 설치
8
+
9
+ ```bash
10
+ npx expo install @the-seeker/feedback-react-native
11
+ ```
12
+
13
+ Expo가 아닌 React Native 앱은 `npm i @the-seeker/feedback-react-native`. 요구 버전: `react >= 18`, `react-native >= 0.74`.
14
+
15
+ ## 1. CRM에 앱 등록 (필수)
16
+
17
+ CRM → 피드백 → **위젯 설정 → 허용 앱**에 앱 ID를 추가하세요. 앱 ID는 iOS bundle identifier 또는 Android applicationId입니다(예: `com.example.app`). 두 플랫폼의 ID가 다르면 둘 다 등록하고 `appId={Platform.select({ ios: "com.example.app", default: "com.example.android" })}`처럼 플랫폼별 값을 넘기세요.
18
+
19
+ - 등록하지 않은 앱 ID로 요청하면 서버가 `403 APP_NOT_ALLOWED`를 돌려주고, 피드백 UI는 나타나지 않습니다(`onError("APP_NOT_ALLOWED")`).
20
+ - 위젯 키(`fbw_…`)는 같은 화면의 **설치** 탭에서 복사합니다.
21
+
22
+ ## 2. Provider 추가
23
+
24
+ Provider는 앱 최상단(루트 화면 바로 바깥)에 둡니다. 런처 버튼과 설문 카드는 Provider의 부모 뷰를 기준으로 화면 하단에 떠 있습니다.
25
+
26
+ ```tsx
27
+ import { TheSeekerFeedbackProvider } from "@the-seeker/feedback-react-native";
28
+
29
+ export default function App() {
30
+ return (
31
+ <TheSeekerFeedbackProvider widgetKey="fbw_..." appId="com.example.app" userId={user?.id} screen="/home">
32
+ <RootNavigator />
33
+ </TheSeekerFeedbackProvider>
34
+ );
35
+ }
36
+ ```
37
+
38
+ 설정을 불러오지 못하면(네트워크 오류, 미등록 앱, 꺼진 위젯) children만 그대로 렌더하고 `onError(code)`를 호출합니다. 개발 빌드에서는 `console.warn`도 남깁니다.
39
+
40
+ ### Props
41
+
42
+ | Prop | 타입 | 기본값 | 설명 |
43
+ | --- | --- | --- | --- |
44
+ | `widgetKey` | `string` | 필수 | 위젯 공개 키 |
45
+ | `appId` | `string` | 필수 | 허용 앱에 등록한 앱 ID. `X-TheSeeker-App` 헤더와 `pageUrl`(`app://<appId>/<screen>`)에 쓰입니다 |
46
+ | `baseUrl` | `string` | `"https://crm.theseeker.io"` | CRM 주소 |
47
+ | `userId` | `string \| number \| null` | `null` | 제출에 붙는 사용자 ID(`uid`, 최대 128자) |
48
+ | `locale` | `"ko" \| "en" \| "auto"` | `"ko"` | `auto`는 기기 언어가 `en*`이면 영어, 아니면 한국어 |
49
+ | `screen` | `string` | `"/"` | 현재 화면 경로. 설문 경로 패턴과 `pageUrl`에 쓰입니다 |
50
+ | `launcher` | `boolean` | `true` | `false`면 표시 방식이 launcher여도 플로팅 버튼을 숨깁니다 |
51
+ | `pickImages` | `() => Promise<ImageAsset[]>` | 없음 | 있으면(그리고 위젯의 이미지 첨부가 켜져 있으면) 폼에 첨부 버튼이 생깁니다 |
52
+ | `storage` | `{ getItem, setItem }` | 메모리 | 설문 재노출 쿨다운 저장소(동기·비동기 모두 가능) |
53
+ | `client` | `ClientMetadata` | `Platform`에서 생성 | `{ platform, osVersion?, appVersion?, deviceModel?, deviceType? }` |
54
+ | `onSubmitted` | `(id, kind) => void` | 없음 | 제출 성공. `kind`는 `"feedback" \| "nps" \| "csat"` |
55
+ | `onError` | `(code) => void` | 없음 | 설정 로드 실패 또는 제출 실패 코드 |
56
+
57
+ `appVersion`·`deviceModel`은 SDK가 알 수 없으니 필요하면 `expo-application`·`expo-device` 값으로 `client`를 직접 넘기세요.
58
+
59
+ ```tsx
60
+ import * as Application from "expo-application";
61
+ import * as Device from "expo-device";
62
+
63
+ const client = {
64
+ platform: Platform.OS === "ios" ? "ios" : "android",
65
+ osVersion: Device.osVersion ?? undefined,
66
+ appVersion: Application.nativeApplicationVersion ?? undefined,
67
+ deviceModel: Device.modelName ?? undefined,
68
+ deviceType: Device.deviceType === Device.DeviceType.TABLET ? "tablet" : "phone",
69
+ } as const;
70
+ ```
71
+
72
+ ## 3. 훅 API
73
+
74
+ ```tsx
75
+ import { useTheSeekerFeedback } from "@the-seeker/feedback-react-native";
76
+
77
+ function HelpButton() {
78
+ const feedback = useTheSeekerFeedback();
79
+ return <Button title="의견 보내기" onPress={feedback.open} disabled={!feedback.ready} />;
80
+ }
81
+ ```
82
+
83
+ | 필드 | 설명 |
84
+ | --- | --- |
85
+ | `ready` | 위젯 설정을 불러왔으면 `true` |
86
+ | `config` | 파싱된 위젯 설정(`WidgetConfig \| null`) |
87
+ | `open()` / `close()` | 피드백 바텀 시트 열기·닫기(설정 로드 전에는 열리지 않음) |
88
+ | `setScreen(path)` | 현재 화면 경로 변경. 설문 조건을 다시 평가합니다 |
89
+ | `setUser(id)` | 사용자 ID 변경(`null`로 해제) |
90
+ | `setContact(value)` | 연락처 미리 채우기. 폼과 `submit`의 기본값이 됩니다 |
91
+ | `setLocale(locale)` | `"ko" \| "en" \| "auto"` |
92
+ | `submit({ message, contact?, images? })` | UI 없이 직접 제출 → `{ ok: true, id } \| { ok: false, code }` |
93
+
94
+ `setScreen`·`setUser`·`setLocale`로 바꾼 값은 같은 이름의 prop이 바뀌면 prop 값으로 돌아갑니다. Provider 밖에서 훅을 부르면 `TheSeekerFeedbackContextError`를 던집니다.
95
+
96
+ `submit` 실패 코드: `WIDGET_NOT_FOUND`(설정 로드 전·실패), `VALIDATION_ERROR`(빈 메시지 등), `IMAGES_DISABLED`, `TOO_MANY_IMAGES`, `IMAGE_TOO_LARGE`, `INVALID_IMAGE`, `RATE_LIMITED`, `APP_NOT_ALLOWED`, `NETWORK_ERROR`.
97
+
98
+ ## 4. 표시 방식
99
+
100
+ CRM 위젯 설정의 **표시 방식**을 따릅니다.
101
+
102
+ | 표시 방식 | 앱에서의 동작 |
103
+ | --- | --- |
104
+ | launcher | 화면 하단 플로팅 버튼(위치·버튼 문구 설정 반영, 영어는 영어 버튼 문구) → 바텀 시트 폼 |
105
+ | inline | 자동 UI 없음. `<TheSeekerFeedbackInline />`을 원하는 화면에 배치 |
106
+ | manual | 버튼 없음. `open()`으로 바텀 시트를 엽니다 |
107
+
108
+ `open()`과 `<TheSeekerFeedbackInline style={...} />`은 어느 방식에서든 쓸 수 있습니다. 테마(라이트·다크·자동), 강조색, 외형 색상·모서리 반경도 CRM 설정을 따르며, 자동은 기기 다크 모드를 따릅니다.
109
+
110
+ ## 5. 화면 경로와 설문
111
+
112
+ CRM에서 만든 NPS·CSAT 설문은 웹 위젯과 같은 규칙으로 뜹니다: 경로 패턴(`/home*`)이 `screen`과 맞고, 쿨다운이 지났고, 표본 비율에 들면 `delaySeconds` 뒤 하단 카드로 표시됩니다. 화면이 바뀔 때마다 다시 평가하며, 한 Provider 수명 동안 설문당 한 번만 뜹니다.
113
+
114
+ expo-router:
115
+
116
+ ```tsx
117
+ // app/_layout.tsx
118
+ import { Stack, usePathname } from "expo-router";
119
+
120
+ export default function RootLayout() {
121
+ const pathname = usePathname();
122
+ return (
123
+ <TheSeekerFeedbackProvider widgetKey="fbw_..." appId="com.example.app" screen={pathname}>
124
+ <Stack />
125
+ </TheSeekerFeedbackProvider>
126
+ );
127
+ }
128
+ ```
129
+
130
+ React Navigation:
131
+
132
+ ```tsx
133
+ function Navigation() {
134
+ const { setScreen } = useTheSeekerFeedback();
135
+ const ref = useNavigationContainerRef();
136
+ return (
137
+ <NavigationContainer ref={ref} onStateChange={() => setScreen(`/${ref.getCurrentRoute()?.name ?? ""}`)}>
138
+ {/* … */}
139
+ </NavigationContainer>
140
+ );
141
+ }
142
+ ```
143
+
144
+ 제출 데이터의 `pageUrl`은 `app://<appId>/<screen>`(예: `app://com.example.app/home`)입니다.
145
+
146
+ ## 6. 이미지 첨부 어댑터 (expo-image-picker)
147
+
148
+ ```tsx
149
+ import * as ImagePicker from "expo-image-picker";
150
+ import type { PickImages } from "@the-seeker/feedback-react-native";
151
+
152
+ const pickImages: PickImages = async () => {
153
+ const result = await ImagePicker.launchImageLibraryAsync({
154
+ mediaTypes: ["images"],
155
+ allowsMultipleSelection: true,
156
+ selectionLimit: 4,
157
+ quality: 0.8,
158
+ });
159
+ if (result.canceled) return [];
160
+ return result.assets.map((asset, index) => ({
161
+ uri: asset.uri,
162
+ mimeType: asset.mimeType ?? "image/jpeg",
163
+ fileName: asset.fileName ?? `image-${index + 1}.jpg`,
164
+ fileSize: asset.fileSize,
165
+ }));
166
+ };
167
+
168
+ <TheSeekerFeedbackProvider pickImages={pickImages} /* … */ />;
169
+ ```
170
+
171
+ PNG·JPEG·WebP·GIF, 최대 4장, 장당 2MB까지 첨부됩니다. 형식이 맞지 않거나 큰 이미지는 폼이 안내 문구와 함께 제외합니다. HEIC 사진이나 큰 사진은 `expo-image-manipulator`로 JPEG 변환·축소한 뒤 넘기세요.
172
+
173
+ ## 7. storage 어댑터
174
+
175
+ 기본 저장소는 메모리라 앱을 다시 시작하면 설문 쿨다운이 초기화됩니다. 쿨다운을 유지하려면 영구 저장소를 넘기세요. 키는 `tsfb:survey:<설문 ID>`, 값은 표시·닫기·응답 시각(ms)입니다.
176
+
177
+ ```tsx
178
+ import AsyncStorage from "@react-native-async-storage/async-storage";
179
+
180
+ <TheSeekerFeedbackProvider storage={AsyncStorage} /* … */ />;
181
+ ```
182
+
183
+ ```ts
184
+ // mmkv: an existing react-native-mmkv instance
185
+ const storage = {
186
+ getItem: (key: string) => mmkv.getString(key) ?? null,
187
+ setItem: (key: string, value: string) => mmkv.set(key, value),
188
+ };
189
+ ```
190
+
191
+ ## 테스트 ID (Detox·Maestro)
192
+
193
+ `theseeker-feedback-launcher`, `theseeker-feedback-message`, `theseeker-feedback-contact`, `theseeker-feedback-attach`, `theseeker-feedback-remove-<n>`, `theseeker-feedback-submit`, `theseeker-feedback-thanks`, `theseeker-feedback-scrim`, `theseeker-feedback-inline`, `theseeker-survey`, `theseeker-survey-score-<n>`, `theseeker-survey-follow-up`, `theseeker-survey-send`, `theseeker-survey-close`.
194
+
195
+ ---
196
+
197
+ ## English
198
+
199
+ Pure-JS React Native / Expo SDK for the TheSeeker CRM feedback widget. No native modules; works in Expo Go. Full guide: https://docs.theseeker.io/feedback/app-install
200
+
201
+ 1. **Install**: `npx expo install @the-seeker/feedback-react-native` (peer deps: `react >= 18`, `react-native >= 0.74`).
202
+ 2. **Register your app ID** (iOS bundle identifier / Android applicationId) in CRM → Feedback → Widget settings → **Allowed apps**. Unregistered IDs get `403 APP_NOT_ALLOWED` and no UI renders.
203
+ 3. **Wrap your app** near the root:
204
+
205
+ ```tsx
206
+ <TheSeekerFeedbackProvider widgetKey="fbw_..." appId="com.example.app" locale="en" screen={pathname}>
207
+ <App />
208
+ </TheSeekerFeedbackProvider>
209
+ ```
210
+
211
+ - Props: `widgetKey`, `appId` (required); `baseUrl`, `userId`, `locale` (`"ko" | "en" | "auto"`, default `"ko"`), `screen` (default `"/"`), `launcher` (default `true`), `pickImages`, `storage` (default in-memory), `client`, `onSubmitted(id, kind)`, `onError(code)`.
212
+ - Hook: `useTheSeekerFeedback()` returns `{ ready, config, open, close, setScreen, setUser, setContact, setLocale, submit }`; `submit({ message, contact?, images? })` resolves to `{ ok: true, id } | { ok: false, code }`. It throws `TheSeekerFeedbackContextError` outside the provider.
213
+ - Display modes follow the CRM setting: `launcher` (floating button → bottom sheet), `inline` (place `<TheSeekerFeedbackInline />` yourself), `manual` (call `open()`).
214
+ - Surveys (NPS/CSAT) use the web widget rules: path pattern vs `screen`, cooldown read from `storage` (`tsfb:survey:<id>`), sample rate, then `delaySeconds`; at most once per provider lifetime.
215
+ - Images: pass a `pickImages` adapter (see the expo-image-picker example above). PNG, JPEG, WebP or GIF, up to 4 images, 2 MB each.
216
+ - Submissions are sent with `X-TheSeeker-App: <appId>` and `pageUrl = app://<appId>/<screen>`.
@@ -0,0 +1,57 @@
1
+ import type { WidgetConfig } from "./config";
2
+ import type { FeedbackErrorCode, FeedbackPayload, ImageAsset } from "./request";
3
+ export type NativeFilePart = Readonly<{
4
+ uri: string;
5
+ type: string;
6
+ name: string;
7
+ }>;
8
+ export interface FormDataLike {
9
+ append(name: string, value: string | NativeFilePart): void;
10
+ }
11
+ export interface XhrLike {
12
+ open(method: string, url: string): void;
13
+ setRequestHeader(name: string, value: string): void;
14
+ send(body: FormDataLike): void;
15
+ onload: (() => void) | null;
16
+ onerror: (() => void) | null;
17
+ ontimeout: (() => void) | null;
18
+ readonly status: number;
19
+ readonly responseText: string;
20
+ timeout: number;
21
+ }
22
+ type ClientResponse = {
23
+ readonly status: number;
24
+ json(): Promise<unknown>;
25
+ };
26
+ export type FetchInit = Readonly<{
27
+ method: "GET" | "POST";
28
+ headers: Readonly<Record<string, string>>;
29
+ body?: string | FormDataLike;
30
+ }>;
31
+ export type FetchImpl = (url: string, init: FetchInit) => Promise<ClientResponse>;
32
+ export type FeedbackClientOptions = Readonly<{
33
+ baseUrl?: string;
34
+ widgetKey: string;
35
+ appId: string;
36
+ fetchImpl?: FetchImpl;
37
+ FormDataImpl?: new () => FormDataLike;
38
+ XMLHttpRequestImpl?: new () => XhrLike;
39
+ }>;
40
+ export type Failure = Readonly<{
41
+ ok: false;
42
+ code: FeedbackErrorCode;
43
+ }>;
44
+ export type ConfigResult = Readonly<{
45
+ ok: true;
46
+ config: WidgetConfig;
47
+ }> | Failure;
48
+ export type SubmitResult = Readonly<{
49
+ ok: true;
50
+ id: string;
51
+ }> | Failure;
52
+ export interface FeedbackClient {
53
+ fetchConfig(): Promise<ConfigResult>;
54
+ submit(payload: FeedbackPayload, images?: readonly ImageAsset[]): Promise<SubmitResult>;
55
+ }
56
+ export declare function createFeedbackClient(options: FeedbackClientOptions): FeedbackClient;
57
+ export {};
@@ -0,0 +1,113 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createFeedbackClient = createFeedbackClient;
4
+ const zod_1 = require("zod");
5
+ const config_1 = require("./config");
6
+ const request_1 = require("./request");
7
+ const errorSchema = zod_1.z.object({
8
+ error: zod_1.z.enum([
9
+ "APP_NOT_ALLOWED",
10
+ "ORIGIN_NOT_ALLOWED",
11
+ "RATE_LIMITED",
12
+ "VALIDATION_ERROR",
13
+ "IMAGES_DISABLED",
14
+ "TOO_MANY_IMAGES",
15
+ "IMAGE_TOO_LARGE",
16
+ "INVALID_IMAGE",
17
+ "WIDGET_NOT_FOUND",
18
+ "NETWORK_ERROR",
19
+ ]),
20
+ });
21
+ const successSchema = zod_1.z.object({ id: zod_1.z.string().min(1) });
22
+ function responseError(body, status) {
23
+ const parsed = errorSchema.safeParse(body);
24
+ if (parsed.success)
25
+ return { ok: false, code: parsed.data.error };
26
+ switch (status) {
27
+ case 429:
28
+ return { ok: false, code: "RATE_LIMITED" };
29
+ case 413:
30
+ return { ok: false, code: "IMAGE_TOO_LARGE" };
31
+ case 404:
32
+ return { ok: false, code: "WIDGET_NOT_FOUND" };
33
+ default:
34
+ return { ok: false, code: "VALIDATION_ERROR" };
35
+ }
36
+ }
37
+ async function parseSubmitResponse(response) {
38
+ const raw = await response.json();
39
+ if (response.status !== 201)
40
+ return responseError(raw, response.status);
41
+ const parsed = successSchema.safeParse(raw);
42
+ return parsed.success ? { ok: true, id: parsed.data.id } : { ok: false, code: "VALIDATION_ERROR" };
43
+ }
44
+ function createFeedbackClient(options) {
45
+ const { widgetKey, appId, baseUrl = "https://crm.theseeker.io", fetchImpl = fetch, FormDataImpl = FormData, XMLHttpRequestImpl = globalThis.XMLHttpRequest, } = options;
46
+ return {
47
+ async fetchConfig() {
48
+ try {
49
+ const response = await fetchImpl((0, request_1.configUrl)(baseUrl, widgetKey), { method: "GET", headers: (0, request_1.appHeaders)(appId) });
50
+ const body = await response.json();
51
+ if (response.status !== 200)
52
+ return responseError(body, response.status);
53
+ const config = (0, config_1.parseWidgetConfig)(body);
54
+ return config === null ? { ok: false, code: "WIDGET_NOT_FOUND" } : { ok: true, config };
55
+ }
56
+ catch (error) {
57
+ if (error instanceof Error)
58
+ return { ok: false, code: "NETWORK_ERROR" };
59
+ throw error;
60
+ }
61
+ },
62
+ async submit(payload, images = []) {
63
+ const validation = (0, request_1.validateImages)(images);
64
+ if (validation !== "ok")
65
+ return { ok: false, code: validation };
66
+ try {
67
+ const url = `${baseUrl.replace(/\/+$/, "")}/api/feedback/widget`;
68
+ let body = JSON.stringify(payload);
69
+ let headers = { ...(0, request_1.appHeaders)(appId), "Content-Type": "application/json" };
70
+ if (images.length > 0) {
71
+ const form = new FormDataImpl();
72
+ form.append("payload", JSON.stringify(payload));
73
+ for (const image of images)
74
+ form.append("image", { uri: image.uri, type: image.mimeType, name: image.fileName });
75
+ if (XMLHttpRequestImpl !== undefined) {
76
+ const response = await new Promise((resolve, reject) => {
77
+ const xhr = new XMLHttpRequestImpl();
78
+ Object.assign(xhr, {
79
+ onload: () => resolve({
80
+ status: xhr.status,
81
+ json: async () => {
82
+ const raw = JSON.parse(xhr.responseText);
83
+ return raw;
84
+ },
85
+ }),
86
+ onerror: () => reject(new TypeError("Multipart upload failed")),
87
+ ontimeout: () => reject(new TypeError("Multipart upload timed out")),
88
+ });
89
+ xhr.open("POST", url);
90
+ xhr.timeout = 30000;
91
+ xhr.setRequestHeader("X-TheSeeker-App", appId);
92
+ xhr.send(form);
93
+ });
94
+ return await parseSubmitResponse(response);
95
+ }
96
+ body = form;
97
+ headers = { ...(0, request_1.appHeaders)(appId) };
98
+ }
99
+ const response = await fetchImpl(url, {
100
+ method: "POST",
101
+ headers,
102
+ body,
103
+ });
104
+ return await parseSubmitResponse(response);
105
+ }
106
+ catch (error) {
107
+ if (error instanceof Error)
108
+ return { ok: false, code: "NETWORK_ERROR" };
109
+ throw error;
110
+ }
111
+ },
112
+ };
113
+ }
@@ -0,0 +1,59 @@
1
+ import type { FormTexts, Locale } from "./texts";
2
+ export declare const ACCENTS: {
3
+ readonly neutral: "#111827";
4
+ readonly blue: "#2563eb";
5
+ readonly green: "#16a34a";
6
+ readonly violet: "#7c3aed";
7
+ readonly orange: "#ea580c";
8
+ readonly rose: "#e11d48";
9
+ };
10
+ export declare const RADII: {
11
+ readonly panel: 14;
12
+ readonly field: 10;
13
+ readonly button: 24;
14
+ };
15
+ export type Theme = "light" | "dark" | "system" | "auto";
16
+ export type Scheme = "light" | "dark";
17
+ export type ContactMode = "email" | "text" | "hidden";
18
+ export type PaletteColors = Readonly<{
19
+ accent: string;
20
+ accentText: string;
21
+ background: string;
22
+ text: string;
23
+ mutedText: string;
24
+ border: string;
25
+ }>;
26
+ export type Radii = Readonly<{
27
+ panel: number;
28
+ field: number;
29
+ button: number;
30
+ }>;
31
+ export type Appearance = Readonly<{
32
+ light: Partial<PaletteColors>;
33
+ dark: Partial<PaletteColors>;
34
+ radius: Radii;
35
+ font: "default" | "inherit";
36
+ }>;
37
+ export type Survey = Readonly<{
38
+ id: string;
39
+ type: "nps" | "csat";
40
+ question: string;
41
+ followUp: string | null;
42
+ delaySeconds: number;
43
+ pathPattern: string | null;
44
+ sampleRate: number;
45
+ cooldownDays: number;
46
+ }>;
47
+ export type WidgetConfig = Readonly<{
48
+ position: "bottom-right" | "bottom-left";
49
+ labels: Readonly<Record<Locale, string>>;
50
+ accentName: keyof typeof ACCENTS;
51
+ appearance: Appearance;
52
+ theme: Theme;
53
+ contactMode: ContactMode;
54
+ texts: Readonly<Record<Locale, FormTexts>>;
55
+ mode: "launcher" | "inline" | "manual";
56
+ images: boolean;
57
+ survey: Survey | null;
58
+ }>;
59
+ export declare function parseWidgetConfig(input: unknown): WidgetConfig | null;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RADII = exports.ACCENTS = void 0;
4
+ exports.parseWidgetConfig = parseWidgetConfig;
5
+ const zod_1 = require("zod");
6
+ const texts_1 = require("./texts");
7
+ exports.ACCENTS = {
8
+ neutral: "#111827",
9
+ blue: "#2563eb",
10
+ green: "#16a34a",
11
+ violet: "#7c3aed",
12
+ orange: "#ea580c",
13
+ rose: "#e11d48",
14
+ };
15
+ exports.RADII = { panel: 14, field: 10, button: 24 };
16
+ const nonNegative = zod_1.z.number().finite().nonnegative().catch(0);
17
+ const surveySchema = zod_1.z
18
+ .object({
19
+ id: zod_1.z.string(),
20
+ type: zod_1.z.enum(["nps", "csat"]),
21
+ question: zod_1.z.string(),
22
+ followUpQuestion: zod_1.z.string().catch(""),
23
+ pathPattern: zod_1.z.string().catch(""),
24
+ delaySeconds: nonNegative,
25
+ sampleRate: nonNegative,
26
+ cooldownDays: nonNegative,
27
+ })
28
+ .nullable()
29
+ .catch(null);
30
+ const color = zod_1.z
31
+ .string()
32
+ .regex(/^#[0-9a-f]{6}$/i)
33
+ .optional()
34
+ .catch(undefined);
35
+ const paletteSchema = zod_1.z
36
+ .object({ accent: color, accentText: color, background: color, text: color, mutedText: color, border: color })
37
+ .catch({});
38
+ const radiusSchema = zod_1.z
39
+ .object({
40
+ panel: zod_1.z.number().int().min(0).max(32).catch(exports.RADII.panel),
41
+ field: zod_1.z.number().int().min(0).max(24).catch(exports.RADII.field),
42
+ button: zod_1.z.number().int().min(0).max(24).catch(exports.RADII.button),
43
+ })
44
+ .catch(exports.RADII);
45
+ const appearanceSchema = zod_1.z
46
+ .object({
47
+ light: paletteSchema,
48
+ dark: paletteSchema,
49
+ radius: radiusSchema,
50
+ font: zod_1.z.enum(["default", "inherit"]).catch("default"),
51
+ })
52
+ .catch({ light: {}, dark: {}, radius: exports.RADII, font: "default" });
53
+ const label = zod_1.z.string().trim().catch("");
54
+ const rawSchema = zod_1.z.object({
55
+ enabled: zod_1.z.literal(true),
56
+ position: zod_1.z.enum(["bottom-right", "bottom-left"]).catch("bottom-right"),
57
+ accent: zod_1.z.enum(["neutral", "blue", "green", "violet", "orange", "rose"]).catch("neutral"),
58
+ appearance: appearanceSchema,
59
+ theme: zod_1.z.enum(["light", "dark", "system", "auto"]).catch("light"),
60
+ contactMode: zod_1.z.enum(["email", "text", "hidden"]).catch("email"),
61
+ texts: zod_1.z.unknown().optional(),
62
+ localizedTexts: zod_1.z
63
+ .object({ en: zod_1.z.object({ buttonLabel: label }).passthrough().catch({ buttonLabel: "" }) })
64
+ .catch({ en: { buttonLabel: "" } }),
65
+ buttonLabel: label,
66
+ displayMode: zod_1.z.enum(["launcher", "inline", "manual"]).catch("launcher"),
67
+ imageUploadEnabled: zod_1.z.unknown().optional(),
68
+ survey: surveySchema,
69
+ });
70
+ function parsePalette(raw) {
71
+ return Object.fromEntries(Object.entries(raw).filter((entry) => typeof entry[1] === "string"));
72
+ }
73
+ function parseWidgetConfig(input) {
74
+ const parsed = rawSchema.safeParse(input);
75
+ if (!parsed.success)
76
+ return null;
77
+ const raw = parsed.data;
78
+ const survey = raw.survey;
79
+ return {
80
+ position: raw.position,
81
+ labels: {
82
+ ko: raw.buttonLabel || texts_1.DEFAULT_TEXTS.ko.launcher,
83
+ en: raw.localizedTexts.en.buttonLabel || texts_1.DEFAULT_TEXTS.en.launcher,
84
+ },
85
+ accentName: raw.accent,
86
+ appearance: {
87
+ ...raw.appearance,
88
+ light: parsePalette(raw.appearance.light),
89
+ dark: parsePalette(raw.appearance.dark),
90
+ },
91
+ theme: raw.theme,
92
+ contactMode: raw.contactMode,
93
+ texts: {
94
+ ko: (0, texts_1.parseTexts)(raw.texts, raw.contactMode, "ko"),
95
+ en: (0, texts_1.parseTexts)(raw.localizedTexts.en, raw.contactMode, "en"),
96
+ },
97
+ mode: raw.displayMode,
98
+ images: raw.imageUploadEnabled !== false,
99
+ survey: survey === null
100
+ ? null
101
+ : {
102
+ id: survey.id,
103
+ type: survey.type,
104
+ question: survey.question,
105
+ followUp: survey.followUpQuestion.trim() ? survey.followUpQuestion : null,
106
+ delaySeconds: survey.delaySeconds,
107
+ pathPattern: survey.pathPattern || null,
108
+ sampleRate: survey.sampleRate,
109
+ cooldownDays: survey.cooldownDays,
110
+ },
111
+ };
112
+ }
@@ -0,0 +1,53 @@
1
+ import type { ContactMode } from "./config";
2
+ import type { ResolvedTexts } from "./texts";
3
+ export type ClientMetadata = Readonly<{
4
+ platform: "ios" | "android";
5
+ osVersion?: string;
6
+ appVersion?: string;
7
+ deviceModel?: string;
8
+ deviceType?: "phone" | "tablet";
9
+ }>;
10
+ export type ImageAsset = Readonly<{
11
+ uri: string;
12
+ mimeType: string;
13
+ fileName: string;
14
+ fileSize?: number;
15
+ }>;
16
+ export type FeedbackErrorCode = "APP_NOT_ALLOWED" | "ORIGIN_NOT_ALLOWED" | "RATE_LIMITED" | "VALIDATION_ERROR" | "IMAGES_DISABLED" | "TOO_MANY_IMAGES" | "IMAGE_TOO_LARGE" | "INVALID_IMAGE" | "WIDGET_NOT_FOUND" | "NETWORK_ERROR";
17
+ export type FeedbackPayload = Readonly<{
18
+ key: string;
19
+ content: string;
20
+ pageUrl: string;
21
+ contactEmail?: string;
22
+ contact?: string;
23
+ uid?: string;
24
+ client?: ClientMetadata;
25
+ }> & ({
26
+ readonly kind: "feedback";
27
+ } | {
28
+ readonly kind: "nps" | "csat";
29
+ readonly score: number;
30
+ readonly surveyId: string;
31
+ });
32
+ export type FeedbackInput = Readonly<{
33
+ key: string;
34
+ appId: string;
35
+ screen: string;
36
+ message: string;
37
+ contact?: string | null;
38
+ contactMode?: ContactMode;
39
+ uid?: string | number | null;
40
+ client?: ClientMetadata;
41
+ }>;
42
+ export type SurveyInput = FeedbackInput & Readonly<{
43
+ kind: "nps" | "csat";
44
+ score: number;
45
+ surveyId: string;
46
+ }>;
47
+ export declare function configUrl(baseUrl: string, key: string): string;
48
+ export declare function appHeaders(appId: string): Readonly<Record<string, string>>;
49
+ export declare function screenPageUrl(appId: string, screen: string): string;
50
+ export declare function buildFeedbackPayload(input: FeedbackInput): FeedbackPayload;
51
+ export declare function buildSurveyPayload(input: SurveyInput): FeedbackPayload;
52
+ export declare function validateImages(assets: readonly ImageAsset[]): "ok" | "TOO_MANY_IMAGES" | "IMAGE_TOO_LARGE" | "INVALID_IMAGE";
53
+ export declare function errorMessageKey(code: FeedbackErrorCode): keyof ResolvedTexts;