@issuecat/react-native 0.0.0-stage → 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JOJI COMPANY
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # @issuecat/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
+ 앱 안에서 고객이 문의·문제 신고를 보내고 운영자의 답을 받는 Issuecat 문의 창입니다. 창은 Issuecat이 웹으로 제공하므로, 앱은 한 줄로 열기만 합니다. React Native와 Expo(Expo Go 포함)에서 됩니다. 타입이 들어 있습니다.
4
+
5
+ ## 설치
6
+
7
+ ```sh
8
+ npm install @issuecat/react-native
9
+ npm install react-native-webview @react-native-async-storage/async-storage react-native-view-shot
10
+ ```
11
+
12
+ Expo는 두 번째 줄을 `npx expo install react-native-webview @react-native-async-storage/async-storage react-native-view-shot`로 합니다. `react-native-view-shot`은 문의에 앱 화면 그림을 붙일 때만 필요합니다.
13
+
14
+ npm 저장소에 닿지 못할 때(사내망 등)는 프로젝트 폴더의 `.npmrc`에 Issuecat이 같은 판을 직접 내주는 주소를 한 줄 적고 설치합니다.
15
+
16
+ ```
17
+ @issuecat:registry=https://issuecat.com/npm/
18
+ ```
19
+
20
+ ## 사용
21
+
22
+ ```tsx
23
+ import { Button } from "react-native";
24
+ import { captureScreen } from "react-native-view-shot";
25
+ import { Issuecat, IssuecatHost } from "@issuecat/react-native";
26
+
27
+ // 앱이 켜질 때 한 번
28
+ Issuecat.configure({
29
+ installKey: "INSTALL_KEY",
30
+ capture: () => captureScreen({ format: "jpg", quality: 0.7, result: "base64" }),
31
+ });
32
+
33
+ export default function App() {
34
+ return (
35
+ <>
36
+ <Button title="문의하기" onPress={() => Issuecat.open()} />
37
+ <IssuecatHost />
38
+ </>
39
+ );
40
+ }
41
+ ```
42
+
43
+ 설치키는 Issuecat 운영 화면의 설정에서 확인합니다. 자세한 설치 순서(로그인한 사람 잇기·답 푸시·시험 문의 확인)는 https://issuecat.com/install/mobile/react-native 에 있습니다.
44
+
45
+ ## 들어 있는 것
46
+
47
+ | 내보내기 | 하는 일 |
48
+ | --- | --- |
49
+ | `Issuecat`, `IssuecatHost` | 문의 창 열기 |
50
+ | `createIssuecatUsage` | 앱 이용 기록 보내기 |
51
+ | `createIssuecatReplay` | (선택) 앱 화면 녹화 |
52
+ | `createIssuecatReport` | 앱이 문제 신고 창을 직접 그릴 때 신고 보내기 |
53
+ | `createInbox` | 앱이 직접 그릴 때 운영자 답 읽기·답장 |
54
+ | `createPush` | 답 푸시용 기기 토큰 등록 |
55
+
56
+ 보통은 `Issuecat`과 `IssuecatHost`만 씁니다. 나머지는 필요할 때 가져다 씁니다.
57
+
58
+ ## 새 판 받기
59
+
60
+ ```sh
61
+ npm install @issuecat/react-native@latest
62
+ ```
63
+
64
+ ## 라이선스
65
+
66
+ MIT. © JOJI COMPANY
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
1
  {
2
2
  "name": "@issuecat/react-native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Issuecat in-app inquiry window and usage tracking for React Native and Expo",
5
+ "main": "./src/index.ts",
6
+ "types": "./src/index.ts",
7
+ "react-native": "./src/index.ts",
8
+ "source": "./src/index.ts",
9
+ "files": ["src", "README.md", "LICENSE"],
10
+ "sideEffects": false,
11
+ "license": "MIT",
12
+ "author": "JOJI COMPANY",
13
+ "homepage": "https://issuecat.com/install/mobile/react-native",
14
+ "repository": { "type": "git", "url": "git+https://github.com/issuecat/issuecat-react-native.git" },
15
+ "publishConfig": { "access": "public" },
16
+ "keywords": ["react-native", "expo", "issuecat", "support", "feedback", "chat"],
17
+ "peerDependencies": {
18
+ "@react-native-async-storage/async-storage": ">=1.17.0",
19
+ "react": ">=18",
20
+ "react-native": ">=0.72",
21
+ "react-native-view-shot": ">=3.0.0",
22
+ "react-native-webview": ">=13.0.0"
23
+ },
24
+ "peerDependenciesMeta": {
25
+ "react-native-view-shot": { "optional": true }
26
+ }
27
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./issuecat";
2
+ export { default } from "./issuecat";
3
+ export * from "./issuecat-usage";
4
+ export * from "./issuecat-replay";
5
+ export * from "./issuecat-report";
6
+ export * from "./issuecat-inbox";
7
+ export * from "./issuecat-push";
@@ -0,0 +1,59 @@
1
+ // 받는 곳: https://issuecat.com/sdk/issuecat-inbox.ts 옛 파일 이름 munjaekokInbox.ts: 앞 판 파일을 이 파일로 바꿔 넣으면(파일 이름은 그대로 둬도) 앱 코드는 그대로 돕니다. 두 파일을 같이 두지는 않습니다.
2
+ // 상담창을 앱이 직접 그릴 때만 씁니다 — 보통은 issuecat.tsx 한 파일이 이 일을 합니다.
3
+ // Issuecat 답 받기 — 앱이 보낸 신고의 운영자 답을 읽고, 답장하고, 새 답 수를 묻습니다. fetch만 씁니다(React Native · Expo · 웹).
4
+ // 신고를 보낼 때 받은(또는 만든) reportId·threadKey를 앱 저장소에 두고 여기에 넘깁니다. threadKey는 그 대화 하나만 여는 비밀입니다.
5
+
6
+ export type InboxMessage = { id: string; author: "operator" | "user"; body: string; createdAt: string };
7
+ export type InboxThread = {
8
+ reportId: string;
9
+ summary: string;
10
+ status: "new" | "open" | "resolved"; // 접수됨 · 확인 중 · 해결됨
11
+ messages: InboxMessage[];
12
+ unread: number; // 이번에 열기 전까지 안 읽은 운영자 답 수(열면 읽은 것이 됩니다)
13
+ };
14
+ export type SavedThread = { reportId: string; threadKey: string; threadUrl?: string };
15
+
16
+ /** 대화 열쇠 하나를 새로 만듭니다(영문·숫자 64자). 신고마다 한 번 만들어 reportId와 같이 저장하고, 다시 보낼 때도 같은 값을 줍니다.
17
+ * React Native에는 crypto.getRandomValues가 없을 수 있습니다 — 앱 맨 위에서 `import "react-native-get-random-values"`를 한 번 부릅니다(Expo는 expo-crypto도 됩니다). */
18
+ export function newThreadKey(): string {
19
+ const bytes = new Uint8Array(32);
20
+ // RN 타입(@react-native/typescript-config)에는 crypto가 없어서 globalThis로 부릅니다 — 웹·Node 타입에서도 그대로 됩니다
21
+ (globalThis as unknown as { crypto: { getRandomValues(a: Uint8Array): Uint8Array } }).crypto.getRandomValues(bytes);
22
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
23
+ }
24
+
25
+ export function createInbox(opts: { origin: string; installKey: string; userAgent: string }) {
26
+ const base = opts.origin.replace(/\/$/, "");
27
+ const call = async (path: string, init: { method?: string; threadKey?: string; body?: unknown } = {}): Promise<any> => {
28
+ const res = await fetch(`${base}${path}`, {
29
+ method: init.method ?? "GET",
30
+ headers: {
31
+ "content-type": "application/json",
32
+ "user-agent": opts.userAgent,
33
+ "x-issuecat-key": opts.installKey,
34
+ ...(init.threadKey ? { "x-issuecat-thread": init.threadKey } : {}),
35
+ },
36
+ body: init.body === undefined ? undefined : JSON.stringify(init.body),
37
+ });
38
+ // 404: 열쇠·번호가 틀렸거나 신고가 지워졌습니다 · 429: 잠시 뒤 다시
39
+ if (!res.ok) throw Object.assign(new Error(`issuecat ${res.status}`), { status: res.status });
40
+ return res.json();
41
+ };
42
+ return {
43
+ /** 대화 한 개를 읽습니다. 읽으면 그 대화의 새 답 수가 0이 됩니다. */
44
+ thread: (t: SavedThread): Promise<InboxThread> =>
45
+ call(`/v1/ingest/threads/${encodeURIComponent(t.reportId)}`, { threadKey: t.threadKey }),
46
+ /** 고객 답장을 보냅니다. messageId는 글마다 한 번 만들어 다시 보낼 때 같은 값을 줍니다(두 번 안 쌓입니다). */
47
+ reply: (t: SavedThread, text: string, messageId = `m-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`): Promise<unknown> =>
48
+ call(`/v1/ingest/threads/${encodeURIComponent(t.reportId)}/messages`, {
49
+ method: "POST",
50
+ body: { installKey: opts.installKey, threadKey: t.threadKey, body: text, messageId },
51
+ }),
52
+ /** 여러 신고의 새 답 수를 한 번에 묻습니다(읽음으로 바꾸지 않습니다). 앱이 켜질 때·앞으로 올 때 불러 배지를 그립니다. */
53
+ unread: (list: SavedThread[]): Promise<{ unread: Record<string, number>; total: number }> =>
54
+ call("/v1/ingest/threads/unread", {
55
+ method: "POST",
56
+ body: { installKey: opts.installKey, threads: list.map((t) => ({ reportId: t.reportId, threadKey: t.threadKey })) },
57
+ }),
58
+ };
59
+ }
@@ -0,0 +1,53 @@
1
+ // 받는 곳: https://issuecat.com/sdk/issuecat-push.ts 옛 이름 isMunjaekokPush(파일 munjaekokPush.ts): 앞 판 파일을 이 파일로 바꿔 넣으면(파일 이름은 그대로 둬도) 앱 코드는 그대로 돕니다(맨 아래 별칭). 두 파일을 같이 두지는 않습니다.
2
+ // 상담창을 앱이 직접 그릴 때만 씁니다 — 보통은 issuecat.tsx 한 파일이 이 일을 합니다.
3
+ // Issuecat 답 푸시 — 운영자가 답하면 Issuecat이 내 앱으로 「답이 왔어요」 푸시를 보냅니다. 앱은 기기 토큰을 대화에 등록하기만 합니다. fetch만 씁니다.
4
+ // 서비스 설정 「앱 고객에게 푸시」에 내 푸시 열쇠(FCM 서비스 계정 JSON, 네이티브 APNs 토큰을 쓰면 APNs 키 .p8)를 먼저 올립니다.
5
+
6
+ /** apns: 네이티브 APNs 토큰(iOS) · fcm: Firebase 토큰(Android, 그리고 iOS도 Firebase로 받는 앱) */
7
+ export type PushProvider = "apns" | "fcm";
8
+ /** issuecat-inbox.ts의 SavedThread와 같은 꼴(신고를 보낼 때 저장한 것) */
9
+ export type PushThread = { reportId: string; threadKey: string };
10
+
11
+ export function createPush(opts: { origin: string; installKey: string; userAgent: string }) {
12
+ const base = opts.origin.replace(/\/$/, "");
13
+ const post = async (path: string, body: Record<string, unknown>): Promise<any> => {
14
+ const res = await fetch(`${base}${path}`, {
15
+ method: "POST",
16
+ headers: { "content-type": "application/json", "user-agent": opts.userAgent },
17
+ body: JSON.stringify({ installKey: opts.installKey, ...body }),
18
+ });
19
+ // 404: 열쇠·번호가 틀렸거나 신고가 지워졌습니다 — 그 대화는 목록에서 뺍니다 · 400: 토큰 꼴이 틀립니다
20
+ if (!res.ok) throw Object.assign(new Error(`issuecat ${res.status}`), { status: res.status });
21
+ return res.json();
22
+ };
23
+ return {
24
+ /** 이 기기를 대화들에 등록합니다. 신고를 보낸 뒤, 그리고 토큰을 새로 받을 때마다 저장한 대화 모두로 부릅니다.
25
+ * false면 이 서비스에 그 종류의 열쇠가 아직 없습니다(등록은 됐습니다). */
26
+ async register(token: string, provider: PushProvider, threads: PushThread[]): Promise<boolean> {
27
+ let ready = false;
28
+ for (const t of threads) {
29
+ ready = (await post(`/v1/ingest/threads/${encodeURIComponent(t.reportId)}/push`, { threadKey: t.threadKey, provider, token })).ready === true;
30
+ }
31
+ return ready;
32
+ },
33
+ /** 이 기기를 이 서비스의 모든 대화에서 뺍니다(로그아웃·알림 끄기). */
34
+ unregister: (token: string): Promise<{ removed: number }> => post("/v1/ingest/threads/push/remove", { token }),
35
+ };
36
+ }
37
+
38
+ /** 받은 푸시의 자료(data·userInfo)가 Issuecat 답 푸시인가 — 내 앱의 다른 푸시와 가를 때 */
39
+ export const isIssuecatPush = (data: Record<string, unknown> | undefined | null): boolean => (data?.issuecat ?? data?.[OLD_PUSH_MARK]) === "reply";
40
+
41
+ /** 누르면 열 대화 화면 주소(Linking.openURL·웹뷰). threadId는 신고 번호입니다 — 직접 그리는 앱은 그 번호로 inbox.thread를 부릅니다. */
42
+ export const threadUrlOf = (data: Record<string, unknown> | undefined | null): string | null =>
43
+ isIssuecatPush(data) && typeof data?.threadUrl === "string" ? data.threadUrl : null;
44
+ export const threadIdOf = (data: Record<string, unknown> | undefined | null): string | null =>
45
+ isIssuecatPush(data) && typeof data?.threadId === "string" ? data.threadId : null;
46
+
47
+ // ---- 옛 코드 호환 — 앞 판(옛 이름 Munjaekok) 앱 코드와 섞여도 돌게 하는 이름을 여기 모읍니다.
48
+
49
+ /** 앞 판 서버가 보낸 답 푸시의 표시 칸 이름 — 그 칸으로 온 푸시도 받습니다 */
50
+ const OLD_PUSH_MARK = "munjaekok";
51
+
52
+ // 옛 이름(Munjaekok) — 앞 판을 이 파일로 바꿔 넣어도 앱 코드가 그대로 돕니다
53
+ export const isMunjaekokPush = isIssuecatPush;
@@ -0,0 +1,120 @@
1
+ // 받는 곳: https://issuecat.com/sdk/issuecat-replay.ts 옛 이름 createMunjaekokReplay(파일 munjaekok-replay.ts): 앞 판 파일을 이 파일로 바꿔 넣으면(파일 이름은 그대로 둬도) 앱 코드는 그대로 돕니다(맨 아래 별칭). 두 파일을 같이 두지는 않습니다.
2
+ // Issuecat 앱 화면 녹화 — React Native(Expo 포함)용. 화면이 바뀌면 1초에 한 장까지 화면 그림(JPEG)을 찍어 5초마다 보냅니다.
3
+ // 화면을 찍는 일은 자바스크립트만으로는 안 돼서 react-native-view-shot의 captureScreen을 넘겨받습니다(Expo Go에도 들어 있습니다).
4
+ // 행동 보내기(issuecat-usage.ts)와 같은 방문 번호로 보내야 운영 화면에서 한 방문의 녹화와 한 일이 같이 보입니다.
5
+ type Frame = Record<string, unknown> & { timestamp: number };
6
+
7
+ export type IssuecatReplayOptions = {
8
+ origin: string; // Issuecat 주소
9
+ installKey: string; // 서비스 설정의 설치키
10
+ app: string; // 앱 이름표(행동 보내기와 같게)
11
+ userAgent: string; // 앱 이름이 든 값
12
+ session: () => string; // 방문 번호 — 행동 보내기의 usage.session
13
+ size: () => { width: number; height: number }; // 화면 크기(점) — Dimensions.get("window")
14
+ shoot: () => Promise<string>; // 화면 그림 한 장(JPEG base64) — captureScreen({ format: "jpg", quality: 0.3, result: "base64", … })
15
+ intervalMs?: number; // 찍는 간격(기본 1000)
16
+ };
17
+
18
+ export function createIssuecatReplay(opts: IssuecatReplayOptions) {
19
+ const url = `${opts.origin.replace(/\/+$/, "")}/v1/ingest/t/${opts.installKey}/r`;
20
+ let pending: Frame[] = [];
21
+ let seq = 0;
22
+ let stopped = false;
23
+ let paused = 0;
24
+ let busy = false;
25
+ let last = "";
26
+ let lastW = 0;
27
+ let lastH = 0;
28
+ let screenName = "";
29
+ let visit = ""; // 쌓인 장의 방문 번호 — 로그아웃으로 방문이 바뀌면 앞 장은 앞 방문으로 보내고 새 방문은 첫 장부터 다시 찍습니다
30
+ let timers: Array<ReturnType<typeof setInterval>> = [];
31
+
32
+ /** 한 장 찍어 쌓습니다. 앞 장과 같거나 쉬는 중이면 안 쌓습니다. */
33
+ async function capture() {
34
+ if (stopped || paused > 0 || busy) return;
35
+ busy = true;
36
+ try {
37
+ const { width, height } = opts.size();
38
+ const t = Date.now();
39
+ const b64 = await opts.shoot();
40
+ roll();
41
+ if (paused > 0 || !b64 || (b64 === last && width === lastW && height === lastH)) return; // 화면이 안 바뀌었습니다
42
+ if (width !== lastW || height !== lastH) pending.push({ type: 4, timestamp: t, data: { width, height, href: screenName } });
43
+ last = b64; lastW = width; lastH = height;
44
+ const shot = { id: 1, x: 0, y: 0, width, height, type: "screenshot", base64: `data:image/jpeg;base64,${b64}` };
45
+ pending.push({ type: 2, timestamp: t, data: { wireframes: [shot] } });
46
+ } catch {
47
+ /* 이번 장은 못 찍었습니다 */
48
+ } finally {
49
+ busy = false;
50
+ }
51
+ }
52
+
53
+ /** 손가락이 닿고 뗀 자리(점). 맨 바깥 View의 onTouchStart·onTouchEnd에서 부릅니다. */
54
+ function touch(began: boolean, x: number, y: number) {
55
+ if (stopped || paused > 0) return;
56
+ roll();
57
+ pending.push({ type: 3, timestamp: Date.now(), data: { source: 2, type: began ? 7 : 9, id: 0, x, y } });
58
+ }
59
+
60
+ function roll() {
61
+ const now = opts.session();
62
+ if (now === visit) return;
63
+ if (pending.length && visit) void post(pending, seq, visit);
64
+ pending = [];
65
+ seq = 0;
66
+ last = ""; lastW = 0; lastH = 0;
67
+ visit = now;
68
+ }
69
+
70
+ let fullVisit = ""; // 녹화 상한(402)을 받은 방문 — 그 방문 동안은 안 보냅니다
71
+
72
+ async function post(events: Frame[], q: number, session: string): Promise<number> {
73
+ if (!session || session === fullVisit) return 0;
74
+ const times = events.map((e) => e.timestamp);
75
+ const query = new URLSearchParams({ s: session, w: session, q: String(q), a: String(Math.min(...times)), b: String(Math.max(...times)), app: opts.app });
76
+ let status = 0;
77
+ try {
78
+ const res = await fetch(`${url}?${query}`, { method: "POST", headers: { "content-type": "application/json", "user-agent": opts.userAgent }, body: JSON.stringify(events) });
79
+ status = res.status;
80
+ } catch {
81
+ /* 인터넷 없음 */
82
+ }
83
+ if (status === 401 || status === 403) stop(); // 모르는 설치키·꺼진 서비스: 더 보내도 같습니다
84
+ else if (status === 402) { fullVisit = session; if (visit === session) pending = []; } // 이달 녹화 상한: 이 방문 동안은 녹화를 보내지 않습니다(다음 방문은 다시 해 봅니다)
85
+ else if (status === 0 || status === 408 || status === 429 || status >= 500) setTimeout(() => { if (!stopped) void post(events, q, session); }, 10_000); // 같은 방문·같은 순번으로 다시
86
+ return status; // 2xx는 받음, 400·413은 이 조각을 받을 수 없어서 버립니다
87
+ }
88
+
89
+ /** 쌓인 장을 보냅니다(5초마다 저절로, 앱이 뒤로 갈 때 불러도 됩니다). 응답 코드(null은 보낼 것 없음). */
90
+ async function flush(): Promise<number | null> {
91
+ if (stopped || pending.length === 0) return null;
92
+ const events = pending;
93
+ pending = [];
94
+ return post(events, seq++, visit); // 조각 순번: 같은 순번을 다시 보내도 한 번만 저장됩니다
95
+ }
96
+
97
+ function start() {
98
+ if (timers.length || stopped) return;
99
+ timers = [setInterval(() => void capture(), opts.intervalMs ?? 1000), setInterval(() => void flush(), 5000)];
100
+ }
101
+ function stop() {
102
+ stopped = true;
103
+ timers.forEach(clearInterval);
104
+ timers = [];
105
+ pending = [];
106
+ }
107
+ /** 비밀번호·카드번호·API 키 칸이 있는 화면에서는 그 화면을 연 동안 찍기를 쉽니다(쉰 동안은 녹화에 앞 장이 그대로 보입니다). */
108
+ const pause = () => { paused += 1; };
109
+ const resume = () => { paused = Math.max(0, paused - 1); };
110
+ /** 지금 화면 이름(행동의 화면 이름과 같게) */
111
+ const screen = (name: string) => { screenName = name; };
112
+
113
+ return { start, stop, capture, touch, flush, pause, resume, screen };
114
+ }
115
+
116
+ // ---- 옛 코드 호환 — 앞 판(옛 이름 Munjaekok) 앱 코드와 섞여도 돌게 하는 이름을 여기 모읍니다.
117
+
118
+ // 옛 이름(Munjaekok) — 앞 판을 이 파일로 바꿔 넣어도 앱 코드가 그대로 돕니다
119
+ export const createMunjaekokReplay = createIssuecatReplay;
120
+ export type MunjaekokReplayOptions = IssuecatReplayOptions;
@@ -0,0 +1,164 @@
1
+ // 받는 곳: https://issuecat.com/sdk/issuecat-report.ts 옛 이름 createMunjaekokReport(파일 munjaekokReport.ts): 앞 판 파일을 이 파일로 바꿔 넣으면(파일 이름은 그대로 둬도) 앱 코드는 그대로 돕니다(맨 아래 별칭). 두 파일을 같이 두지는 않습니다.
2
+ // 상담창을 앱이 직접 그릴 때만 씁니다 — 보통은 issuecat.tsx 한 파일이 이 일을 합니다.
3
+ // Issuecat 신고 보내기 — React Native(Expo 포함)용. 앱 안의 「문제 신고」 단추가 부르는 파일 하나, 라이브러리 없음.
4
+ // 화면 캡처는 앱이 고른 도구(예: react-native-view-shot의 captureScreen)를 snapshot()에 넘깁니다.
5
+
6
+ export type IssuecatReportOptions = {
7
+ origin: string; // Issuecat 주소
8
+ installKey: string; // 서비스 설정의 설치키(공개해도 되는 값)
9
+ app: string; // 앱 이름표 — 행동 보내기(issuecat-usage.ts)와 같은 값 (예: my-app-ios)
10
+ userAgent: string; // 앱 이름이 든 값 (예: "MyApp/1.2.3 (iOS)")
11
+ appVersion?: string; // 예: "1.2.3"
12
+ os?: string; // 예: "iOS 18.5" — React Native는 `${Platform.OS} ${Platform.Version}`
13
+ device?: string; // 예: "iPhone17,1" (expo-device의 modelName 등, 없으면 비웁니다)
14
+ language?: string; // 예: "ko-KR"
15
+ screenSize?: { width: number; height: number; pixelRatio?: number }; // Dimensions.get("window")·PixelRatio.get()
16
+ visit?: () => Promise<{ device: string; session: string }> | { device: string; session: string }; // usage.ids — 신고에서 신고 전 행동으로 이어집니다
17
+ };
18
+
19
+ /** 신고 보내기 결과 */
20
+ export type IssuecatReportOutcome = {
21
+ status: number; // 201 접수 · 200 이미 받음 · 0 인터넷 없음 · 그 밖에는 서버가 준 HTTP 코드
22
+ reportId: string;
23
+ error: string | null; // 서버가 몸으로 준 오류 이름("rate_limited"·"quota_exceeded"·"unauthorized"·"domain_mismatch" …)
24
+ retryAfter: number | null; // 서버가 기다리라고 한 초(429의 Retry-After)
25
+ accepted: boolean; // 접수됐습니다(201 또는 200)
26
+ shouldRetry: boolean; // 조금 뒤 같은 reportId로 다시 보내 볼 만한가(인터넷 없음·5xx·429 rate_limited)
27
+ retryDelay(attempt: number): number; // 다시 보내기까지 기다릴 초(attempt는 0부터)
28
+ threadKey: string | null; // 이 신고의 대화 열쇠 — 운영자 답을 읽고 답장하는 비밀. reportId와 같이 저장합니다(안내 「답 받기」)
29
+ threadUrl: string | null; // 그 대화를 보여 주는 웹 화면 주소(접수됐을 때만). 열쇠가 들어 있으니 남에게 보내지 않습니다
30
+ };
31
+
32
+ /** 다시 보내는 것은 이 횟수까지만 합니다(그 뒤에는 고객에게 「잠시 뒤 다시 해 주세요」). */
33
+ export const MAX_RETRIES = 5;
34
+
35
+ /** 응답에서 결과를 만듭니다(네트워크 없이 시험하려고 따로 뒀습니다). */
36
+ export function outcomeOf(status: number, body: string | null, retryAfterHeader: string | null, reportId: string, threadKey: string | null = null): IssuecatReportOutcome {
37
+ let json: Record<string, unknown> | null = null;
38
+ if (body) { try { json = JSON.parse(body); } catch { /* 몸이 JSON이 아님 */ } }
39
+ const error = status >= 400 && typeof json?.error === "string" ? json.error : null;
40
+ const accepted = status === 201 || status === 200;
41
+ const n = retryAfterHeader == null ? NaN : parseInt(retryAfterHeader.trim(), 10);
42
+ const retryAfter = Number.isFinite(n) ? n : null;
43
+ return {
44
+ status, reportId, error, retryAfter, accepted,
45
+ // 앱이 만든 열쇠를 보냈으면 그 값, 빼고 보냈으면 서버가 만들어 201에만 실어 준 값
46
+ threadKey: accepted && typeof json?.threadKey === "string" ? json.threadKey : threadKey,
47
+ threadUrl: accepted && typeof json?.threadUrl === "string" ? json.threadUrl : null,
48
+ // 429 quota_exceeded(서비스가 받을 수 있는 신고 수에 닿음)와 400·401·403·413은 다시 보내도 소용없습니다
49
+ shouldRetry: status === 0 || status >= 500 || (status === 429 && error !== "quota_exceeded"),
50
+ // Retry-After가 있으면 그만큼(최대 20% 더), 없으면 5·15·45·135초… 최대 300초(최대 20% 일찍) — 같은 앱의 고객들이 같은 때 몰리지 않게 흩습니다
51
+ retryDelay: (attempt) => retryAfter != null
52
+ ? retryAfter * (1 + Math.random() * 0.2)
53
+ : Math.min(300, 5 * 3 ** Math.max(0, attempt)) * (0.8 + Math.random() * 0.2),
54
+ };
55
+ }
56
+
57
+ /**
58
+ * 신고의 pageUrl — 「앱이름표://화면이름」. 주소 앞에는 영문 소문자·숫자·`.`·`+`·`-`만 쓸 수 있어서 앱 이름표의 다른 글자(밑줄·공백·대문자)는
59
+ * `-`·소문자로 바꿉니다. 화면 이름의 한글·공백은 %꼴로 바꿉니다(안 그러면 서버가 주소로 못 읽어 비웁니다). 앱 이름표 그대로는 context의 app에 갑니다.
60
+ */
61
+ export function pageUrl(app: string, screen: string): string {
62
+ let scheme = app.toLowerCase().replace(/[^a-z0-9.+-]/g, "-").replace(/^-+|-+$/g, "");
63
+ if (!scheme) scheme = "app";
64
+ else if (!/^[a-z]/.test(scheme)) scheme = `app-${scheme}`;
65
+ const path = screen.split("/").filter(Boolean).map((s) => encodeURIComponent(s)).join("/");
66
+ return `${scheme}://${path}`;
67
+ }
68
+
69
+ /**
70
+ * 지금 화면을 JPEG(base64 글)로 담습니다 — 「문제 신고」 단추를 누른 직후, 신고 글을 쓰는 창이 뜨기 전에 부릅니다.
71
+ * capture는 앱의 캡처 도구를 부르는 함수입니다. 400KB를 넘으면 품질과 크기를 줄여 맞추고, 담지 못하면 null — 화면 없이 보냅니다.
72
+ */
73
+ export async function snapshot(capture: (o: { quality: number; scale: number }) => Promise<string>, maxBytes = 400_000): Promise<string | null> {
74
+ for (const scale of [1, 0.5, 0.25]) {
75
+ for (const quality of [0.7, 0.5, 0.3]) {
76
+ try {
77
+ const b64 = (await capture({ quality, scale })).replace(/^data:image\/\w+;base64,/, "");
78
+ if (Math.floor((b64.length * 3) / 4) <= maxBytes) return b64;
79
+ } catch {
80
+ return null; // 캡처 도구가 실패했습니다(권한·화면 없음)
81
+ }
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+
87
+ export function createIssuecatReport(opts: IssuecatReportOptions) {
88
+ const endpoint = `${opts.origin.replace(/\/+$/, "")}/v1/ingest/reports`;
89
+
90
+ /**
91
+ * 신고 하나를 보냅니다. screenshot은 snapshot()이 준 base64 JPEG, screen은 지금 화면 이름(예: "/checkout", "/마이/설정").
92
+ * reportId는 신고마다 한 번만 만듭니다 — 다시 보낼 때 같은 값을 주면 신고가 두 번 생기지 않습니다.
93
+ * threadKey(대화 열쇠, 선택)도 reportId와 같이 한 번 만들어(issuecat-inbox.ts의 newThreadKey()) 다시 보낼 때 같은 값을 줍니다 — 안내 「답 받기」.
94
+ */
95
+ async function send(r: { summary: string; screenshot?: string | null; screen?: string; email?: string; context?: Record<string, string>; reportId?: string; threadKey?: string; files?: string[] }): Promise<IssuecatReportOutcome> {
96
+ const reportId = r.reportId ?? newReportId();
97
+ const info: Record<string, string> = { app: opts.app };
98
+ if (opts.device) info.device = opts.device;
99
+ if (opts.os) info.os = opts.os;
100
+ if (opts.appVersion) info.appVersion = opts.appVersion;
101
+ const environment: Record<string, unknown> = { userAgent: opts.userAgent, ...(opts.os ? { platform: opts.os } : {}), ...(opts.language ? { language: opts.language } : {}) };
102
+ if (opts.screenSize) {
103
+ const { width, height, pixelRatio } = opts.screenSize;
104
+ environment.viewport = { width: Math.round(width), height: Math.round(height) };
105
+ environment.screen = { width: Math.round(width), height: Math.round(height), ...(pixelRatio ? { pixelRatio } : {}) };
106
+ }
107
+ const ids = opts.visit ? await opts.visit() : null;
108
+ const body = {
109
+ installKey: opts.installKey, reportId, ...(r.threadKey ? { threadKey: r.threadKey } : {}), summary: r.summary,
110
+ pageUrl: pageUrl(opts.app, r.screen ?? ""), // 화면 이름 → my-app-ios://checkout
111
+ capturedAt: new Date().toISOString(),
112
+ environment, context: { ...info, ...r.context }, events: [], // 앱이 정한 값이 먼저입니다
113
+ ...(r.email ? { reporterEmail: r.email } : {}),
114
+ ...(r.screenshot ? { attachment: { mime: "image/jpeg", dataBase64: r.screenshot } } : {}),
115
+ ...(r.files?.length ? { files: r.files } : {}), // attach()가 준 번호들
116
+ ...(ids ? { visit: { anonId: ids.device, sessionId: ids.session, windowId: ids.session } } : {}),
117
+ };
118
+ try {
119
+ const res = await fetch(endpoint, {
120
+ method: "POST",
121
+ headers: { "content-type": "application/json", "user-agent": opts.userAgent },
122
+ body: JSON.stringify(body),
123
+ });
124
+ return outcomeOf(res.status, await res.text().catch(() => null), res.headers.get("retry-after"), reportId, r.threadKey ?? null);
125
+ } catch {
126
+ return outcomeOf(0, null, null, reportId, r.threadKey ?? null); // 인터넷 없음
127
+ }
128
+ }
129
+
130
+ /**
131
+ * 파일 하나를 먼저 올리고 번호를 받습니다(send의 files에 넣습니다 — 사진·파일 합쳐 10개, 파일 하나 40MB). 몸은 파일 그대로, 이름은 헤더. 종류는 가리지 않습니다.
132
+ * 40MB를 넘으면(413) 또는 실패하면 null. durationMs는 영상 길이(운영 화면 배지에만 씁니다).
133
+ */
134
+ async function attach(f: { name: string; body: Blob | ArrayBuffer | Uint8Array; mime?: string; durationMs?: number }): Promise<string | null> {
135
+ try {
136
+ const res = await fetch(endpoint.replace(/\/v1\/ingest\/reports$/, "/v1/ingest/files"), {
137
+ method: "POST",
138
+ headers: { "content-type": f.mime || "application/octet-stream", "x-issuecat-key": opts.installKey, "x-issuecat-file": encodeURIComponent(f.name), "user-agent": opts.userAgent, ...(f.durationMs ? { "x-issuecat-duration": String(Math.round(f.durationMs)) } : {}) },
139
+ body: f.body as BodyInit,
140
+ });
141
+ if (res.status !== 201) return null;
142
+ const json = (await res.json().catch(() => null)) as { fileId?: unknown } | null;
143
+ return typeof json?.fileId === "string" ? json.fileId : null;
144
+ } catch {
145
+ return null; // 인터넷 없음
146
+ }
147
+ }
148
+
149
+ return { send, attach };
150
+ }
151
+
152
+ /** 신고 번호(영문·숫자와 `._-` 80자까지) */
153
+ export const newReportId = () =>
154
+ "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
155
+ const r = (Math.random() * 16) | 0;
156
+ return (c === "x" ? r : (r & 3) | 8).toString(16);
157
+ });
158
+
159
+ // ---- 옛 코드 호환 — 앞 판(옛 이름 Munjaekok) 앱 코드와 섞여도 돌게 하는 이름을 여기 모읍니다.
160
+
161
+ // 옛 이름(Munjaekok) — 앞 판을 이 파일로 바꿔 넣어도 앱 코드가 그대로 돕니다
162
+ export const createMunjaekokReport = createIssuecatReport;
163
+ export type MunjaekokReportOptions = IssuecatReportOptions;
164
+ export type MunjaekokOutcome = IssuecatReportOutcome;
@@ -0,0 +1,201 @@
1
+ // Issuecat 이용 기록 보내기 — React Native(Expo 포함)용. 파일 하나, 라이브러리 없음.
2
+ // 받는 곳: https://issuecat.com/sdk/issuecat-usage.ts · 안내: https://issuecat.com/install/mobile/react-native.md
3
+ // 옛 이름 createMunjaekok(파일 munjaekok.ts): 앞 판 파일을 이 파일로 바꿔 넣으면(파일 이름은 그대로 둬도) 앱 코드는 고치지 않아도 그대로 돕니다(맨 아래 「옛 코드 호환」). 옛 파일은 지우거나 이 내용으로 덮습니다.
4
+ // 상담창(issuecat.tsx)도 넣었다면 Issuecat.identify·Issuecat.reset 한 번으로 여기도 같이 바뀝니다(이 파일의 identify·reset을 따로 안 불러도 됩니다).
5
+ type Props = Record<string, unknown>;
6
+ type Wire = { n: string; t: number; p: string; x?: Props; i: string; s: string; u: string | null; a?: string };
7
+ type Storage = { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };
8
+
9
+ export type IssuecatUsageOptions = {
10
+ origin: string; // Issuecat 주소
11
+ installKey: string; // 서비스 설정의 설치키(공개해도 되는 값)
12
+ app: string; // 앱 이름표: 소문자·숫자·.-_ 64자까지 (예: my-app-ios)
13
+ userAgent: string; // 앱 이름이 든 값 (예: "MyApp/1.2.3 (iOS)"). okhttp·curl 같은 기본 이름표는 로봇으로 셉니다
14
+ storage?: Storage; // 기기 번호와 못 보낸 줄을 저장할 곳. React Native는 AsyncStorage
15
+ test?: boolean; // true면 이 기기의 행동·녹화가 설치 확인 시험 기록으로(고객 숫자에 안 섞이고 check의 test로). 개발 판에서만: __DEV__. 상담창을 Issuecat.configure({ test: true })로 열었으면 안 켜도 같이 시험
16
+ };
17
+
18
+ /** 서버 요청 하나($api). status는 받은 HTTP 코드 — 응답을 못 받았으면 0과 error(까닭) */
19
+ export type IssuecatUsageRequest = {
20
+ method?: string; // GET·POST …
21
+ path: string; // 요청 주소의 경로만(쿼리 없이). 예: "/v1/orders"
22
+ status: number;
23
+ ms?: number; // 걸린 시간
24
+ host?: string; // 다른 회사 서버(결제·지도 등)로 간 요청만 그 호스트. 내 서버면 비웁니다
25
+ error?: string; // status 0일 때 까닭(예: "Network request failed")
26
+ aborted?: boolean; // 앱이 스스로 취소한 요청 — 문제로 세지 않습니다
27
+ expected?: boolean; // 일부러 낸 거절(로그인 안 한 사람의 401 등) — 기록만 남고 문제로 세지 않습니다
28
+ res?: string; // (선택) 실패한 응답 글 — 고객이 본 말
29
+ };
30
+
31
+ const uuid = () =>
32
+ "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
33
+ const r = (Math.random() * 16) | 0;
34
+ return (c === "x" ? r : (r & 3) | 8).toString(16);
35
+ });
36
+
37
+ export function createIssuecatUsage(opts: IssuecatUsageOptions) {
38
+ const origin = opts.origin.replace(/\/+$/, "");
39
+ const url = `${origin}/v1/ingest/t/${opts.installKey}/e`;
40
+ let session = uuid(); // 앱을 켤 때마다 새 방문
41
+ let device: string | null = null; // 기기 번호: 처음 한 번 만들어 저장
42
+ let user: string | null = null;
43
+ let current = ""; // 지금 화면 이름 — 서버 요청·오류에 같이 실립니다
44
+ let stopped = false;
45
+ let pending: Wire[] = [];
46
+ // 못 보낸 줄은 기기에 남아 앱을 다시 켜도 보냅니다(줄마다 그때의 방문·사람이 박혀 있습니다)
47
+ const loaded = opts.storage?.getItem(OLD_STORAGE.pending).then((saved) => {
48
+ try { if (saved) pending = [...(JSON.parse(saved) as Wire[]), ...pending]; } catch { /* 깨진 값은 버립니다 */ }
49
+ });
50
+ void deviceId(); // 기기 번호를 미리 읽어 줄마다 박습니다(로그아웃하면 바뀝니다)
51
+ const save = () => { void opts.storage?.setItem(OLD_STORAGE.pending, JSON.stringify(pending)); };
52
+
53
+ async function deviceId(): Promise<string> {
54
+ if (device) return device;
55
+ const saved = await opts.storage?.getItem(OLD_STORAGE.device);
56
+ device = saved || uuid();
57
+ if (!saved) await opts.storage?.setItem(OLD_STORAGE.device, device);
58
+ return device;
59
+ }
60
+
61
+ /** 행동 하나를 쌓습니다. path는 화면 이름(예: "/home", "/마이/설정") — 안 주면 지금 화면. */
62
+ function track(name: string, path = current, props?: Props) {
63
+ if (stopped) return;
64
+ // i: 행동 번호(다시 보내도 한 번만 저장) · s·u·a: 지금의 방문·사람·기기 — 로그아웃 뒤에 보내도 이 줄의 사람은 그대로입니다
65
+ pending.push({ n: name, t: Date.now(), p: path, ...(props ? { x: props } : {}), i: uuid(), s: session, u: user, ...(device ? { a: device } : {}) });
66
+ save();
67
+ }
68
+ /** 화면을 열 때. 이 뒤의 행동·서버 요청·오류는 이 화면에서 난 것으로 실립니다. */
69
+ const screen = (path: string, title?: string) => { current = path; track("$pageview", path, title ? { title } : undefined); };
70
+
71
+ /** 로그인한 사람을 알립니다. 이 뒤에 쌓는 줄의 u에 실립니다. 같은 사람을 다시 알리면 건너뜁니다(상담창 SDK와 둘 다 불러도 $identify는 한 번). */
72
+ function identify(userId: string, traits?: { email?: string; name?: string }) {
73
+ if (user === userId) return;
74
+ user = userId;
75
+ track("$identify", "", { user_id: userId, ...traits });
76
+ }
77
+ /** 로그아웃: 웹과 같이 새 고객(새 기기 번호·새 방문)으로 시작합니다. 앞 사람의 쌓인 줄은 그 사람·방문 그대로 나갑니다. 이미 로그아웃한 뒤면 건너뜁니다 */
78
+ const reset = () => {
79
+ if (!user) return;
80
+ track("$logout", ""); // 로그아웃 줄은 나가는 사람·방문으로 남습니다
81
+ user = null;
82
+ session = uuid();
83
+ device = uuid();
84
+ void opts.storage?.setItem(OLD_STORAGE.device, device);
85
+ };
86
+
87
+ /** 서버 요청 하나를 남깁니다($api) — 답답한 곳 「서버 요청 문제」·서버 요청 성적표·숨은 문제에 들어갑니다. */
88
+ function request(r: IssuecatUsageRequest) {
89
+ const { method, ...rest } = r;
90
+ track("$api", current, { ...rest, method: (method ?? "GET").toUpperCase(), ok: r.status >= 200 && r.status < 300 });
91
+ }
92
+
93
+ /** 앱에서 난 오류를 남깁니다($error) — 답답한 곳 「화면 오류」·숨은 문제에 들어갑니다. kind는 "error"·"unhandledrejection"·"fatal" 같은 갈래. */
94
+ function error(err: unknown, kind = "error") {
95
+ const e = err instanceof Error ? err : null;
96
+ track("$error", current, { kind, message: e ? `${e.name}: ${e.message}` : String(err), ...(e?.stack ? { stack: e.stack } : {}) });
97
+ }
98
+
99
+ /**
100
+ * fetch를 감싸 서버 요청을 저절로 남깁니다. ownHosts는 내 서버 호스트(예: ["api.myapp.com"]) — 그 밖의 호스트로 간 요청은 host 칸이 붙어
101
+ * 「바깥 주소」로 따로 보입니다. Issuecat으로 가는 요청은 남기지 않습니다. 요청·응답 본문은 보내지 않고, 실패한 응답(400 이상)의 글만 res로 보냅니다.
102
+ */
103
+ function wrapFetch(f: typeof fetch, ownHosts: string[] = []): typeof fetch {
104
+ return async (input, init) => {
105
+ const started = Date.now();
106
+ const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
107
+ let target: URL | null = null;
108
+ try { target = new URL(raw); } catch { /* 상대 주소 등 — 남기지 않습니다 */ }
109
+ const skip = !target || raw.startsWith(origin);
110
+ const method = init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET");
111
+ const where = target && !(ownHosts.length === 0 || ownHosts.includes(target.host)) ? { host: target.host } : {};
112
+ try {
113
+ const res = await f(input, init);
114
+ if (!skip) {
115
+ const body = res.status >= 400 ? await res.clone().text().catch(() => undefined) : undefined;
116
+ request({ method, path: target!.pathname, status: res.status, ms: Date.now() - started, ...where, ...(body ? { res: body } : {}) });
117
+ }
118
+ return res;
119
+ } catch (err) {
120
+ const aborted = err instanceof Error && err.name === "AbortError";
121
+ if (!skip) request({ method, path: target!.pathname, status: 0, ms: Date.now() - started, error: String(err), ...where, ...(aborted ? { aborted: true } : {}) });
122
+ throw err;
123
+ }
124
+ };
125
+ }
126
+
127
+ /** 이 기기·이 방문의 번호 — 신고 보내기(issuecat-report.ts)의 visit에 주면 신고에서 신고 전 행동으로 이어집니다. */
128
+ const ids = async () => ({ device: await deviceId(), session });
129
+
130
+ /** 쌓인 행동을 보냅니다. 응답 코드를 돌려줍니다(0은 인터넷 없음, null은 보낼 것 없음). */
131
+ async function flush(): Promise<number | null> {
132
+ await loaded;
133
+ if (stopped || pending.length === 0) return null;
134
+ const batch = pending.splice(0, 500);
135
+ save();
136
+ let status = 0;
137
+ try {
138
+ const res = await fetch(url, {
139
+ method: "POST",
140
+ headers: { "content-type": "application/json", "user-agent": opts.userAgent },
141
+ body: JSON.stringify({ v: 1, app: opts.app, a: await deviceId(), s: session, w: session, u: user, sent: Date.now(), ...(opts.test || linkedTestOn() ? { test: true } : {}), e: batch }),
142
+ });
143
+ status = res.status;
144
+ } catch {
145
+ /* 인터넷 없음 */
146
+ }
147
+ if (status === 401 || status === 403) {
148
+ stopped = true; // 모르는 설치키·꺼진 서비스: 더 보내도 같습니다
149
+ pending = [];
150
+ save();
151
+ } else if (status === 0 || status === 408 || status === 429 || status >= 500) {
152
+ pending = [...batch, ...pending]; // 나중에 같은 행동 번호로 다시
153
+ save();
154
+ } // 2xx는 성공, 400·413은 이 묶음을 받을 수 없어서 버립니다
155
+ return status;
156
+ }
157
+
158
+ // 상담창 SDK(issuecat.tsx)의 로그인·로그아웃을 따라갑니다 — 두 파일이 서로를 가져오지 않습니다(globalThis로 나눕니다).
159
+ // 상담창이 먼저 로그인을 알렸으면 지금 그 사람을 집습니다.
160
+ const follow = (u: LinkedUser) => {
161
+ if (u) identify(u.id, { ...(u.email ? { email: u.email } : {}), ...(u.name ? { name: u.name } : {}) });
162
+ else reset();
163
+ };
164
+ linkedListeners().push(follow);
165
+ const now = linkedUserNow();
166
+ if (now) follow(now);
167
+
168
+ // session: 지금 방문 번호(화면 녹화 issuecat-replay.ts가 같이 씁니다). 로그아웃하면 바뀌어서 읽을 때마다 지금 값을 줍니다
169
+ return { track, screen, identify, reset, request, error, wrapFetch, ids, flush, get session() { return session; } };
170
+ }
171
+
172
+ // 상담창 SDK(issuecat.tsx)와 나누는 globalThis 칸: 지금 사람, 듣는 목록, configure({ test })의 시험 표시
173
+ type LinkedUser = { id: string; name?: string; email?: string } | null;
174
+ type Link = { __issuecatUser?: LinkedUser; __issuecatUserListeners?: Array<(u: LinkedUser) => void>; __issuecatTest?: boolean };
175
+
176
+ // ---- 옛 코드 호환 — 앞 판(옛 이름 Cuelen·문제콕) 앱 코드·파일과 섞여도 돌게 하는 이름을 여기 모읍니다.
177
+
178
+ /** 저장 자리 이름 — 앞 판이 쓰던 값 그대로입니다. 바꾸면 기기 번호·못 보낸 줄을 잃습니다. */
179
+ const OLD_STORAGE = { pending: "munjaekok.pending", device: "munjaekok.device" } as const;
180
+
181
+ /** 앞 판 상담창 파일(cuelen.tsx·앞 판 issuecat.tsx)이 쓰는 globalThis 칸 — 새 칸과 같은 목록을 가리키게 하고(어느 파일이 먼저 떠도), 값은 둘 중 있는 것을 읽습니다 */
182
+ type OldLink = { __cuelenUser?: LinkedUser; __cuelenUserListeners?: Array<(u: LinkedUser) => void>; __cuelenTest?: boolean };
183
+ function linkedListeners(): Array<(u: LinkedUser) => void> {
184
+ const g = globalThis as Link & OldLink;
185
+ const list = g.__issuecatUserListeners ?? g.__cuelenUserListeners ?? [];
186
+ g.__issuecatUserListeners = g.__cuelenUserListeners = list;
187
+ return list;
188
+ }
189
+ function linkedUserNow(): LinkedUser {
190
+ const g = globalThis as Link & OldLink;
191
+ return g.__issuecatUser ?? g.__cuelenUser ?? null;
192
+ }
193
+ function linkedTestOn(): boolean {
194
+ const g = globalThis as Link & OldLink;
195
+ return g.__issuecatTest === true || g.__cuelenTest === true;
196
+ }
197
+
198
+ // 옛 이름(Munjaekok) — 앞 판을 이 파일로 바꿔 넣어도 앱 코드가 그대로 돕니다
199
+ export const createMunjaekok = createIssuecatUsage;
200
+ export type MunjaekokOptions = IssuecatUsageOptions;
201
+ export type MunjaekokRequest = IssuecatUsageRequest;
@@ -0,0 +1,551 @@
1
+ // Issuecat 문의 창 — 앱에 이 파일 하나를 넣고 한 줄로 엽니다. (React Native 0.7x+ · Expo 둘 다)
2
+ // 필요한 것: react-native-webview, @react-native-async-storage/async-storage
3
+ //
4
+ // Issuecat.configure({ installKey: "INSTALL_KEY" }) // 앱이 켜질 때 한 번
5
+ // <IssuecatHost /> // 앱 맨 바깥에 한 번 둔다(창이 뜰 자리)
6
+ // Issuecat.open() // 「문의하기」 단추에서
7
+ //
8
+ // 화면(첫 화면·문의하기·문제 신고하기, 서비스 이름·색, 지난 문의, 답장)은 Issuecat이 웹에서 그대로 줍니다 — 운영 화면에서 바꾸면 앱을 다시 내지 않아도 바뀝니다.
9
+ // 이 파일은 그 화면을 화면 전체 웹뷰로 띄우고, 앱 화면 그림·대화 열쇠·안 읽은 답 수·푸시 토큰만 주고받습니다.
10
+ // 앱 화면 그림: RN은 화면을 찍는 기본 길이 없어 configure의 capture로 받습니다(예: react-native-view-shot의 captureScreen).
11
+ // capture를 안 주거나 false면 그림 없이 보내고 화면의 「지금 화면」 줄도 감춥니다.
12
+ // 사진 붙이기(클립, 한 번에 10장): configure의 pickPhotos로 앱의 사진 고르기를 넘기면 그것을 씁니다(예: expo-image-picker — 안내 참고).
13
+ // 안 주면 react-native-webview의 기본 파일 고르기가 엽니다. Android는 react-native-webview 17.0.1 이상이면 카메라 허락을 보고 고르기를 엽니다.
14
+ // iOS 기본 고르기는 카메라가 있는 기기에서 늘 「사진 찍기」 줄을 넣어, Info.plist에 NSCameraUsageDescription이 없는 앱은 그 줄을 누르면 iOS가 앱을 닫습니다 —
15
+ // 그 키를 넣거나 pickPhotos를 주세요.
16
+ // 망이 끊겨 못 보낸 문의·답장은 AsyncStorage에 두었다가 앱이 앞에 올 때 대신 보냅니다.
17
+ // 받는 곳: https://issuecat.com/sdk/issuecat.tsx · 안내: https://issuecat.com/install/mobile/react-native.md
18
+ // 보낼 곳: configure에 baseURL을 빼면 Issuecat 운영 주소(https://issuecat.com)로 보냅니다 — 시험 서버·자기 서버를 쓰면 baseURL을 꼭 적으세요(위 주소들도 운영 주소 기준).
19
+ // 이용 기록(issuecat-usage.ts)도 넣었다면 Issuecat.identify·Issuecat.reset 한 번으로 그쪽도 같이 바뀝니다.
20
+ // react-native-webview 13.x·14.x 타입 둘 다에서 strict 타입 검사가 통과합니다. Issuecat.open()은 Promise라 단추에서는 `void Issuecat.open()`으로 부릅니다.
21
+ import AsyncStorage from "@react-native-async-storage/async-storage";
22
+ import React, { useEffect, useRef, useState } from "react";
23
+ import { AppState, Linking, Modal, Platform, StatusBar, useColorScheme, View } from "react-native";
24
+ import { WebView, type WebViewMessageEvent } from "react-native-webview";
25
+
26
+ // react-native-webview 13·14의 `class WebView<P = undefined> extends Component<WebViewProps & P>`는 strict에서 속성이 never가 된다 —
27
+ // 빈 덧속성({})으로 고정한 같은 부품을 쓴다(실행은 같은 WebView).
28
+ const IssuecatWebView = WebView<{}>;
29
+ type IssuecatWebViewRef = WebView<{}>;
30
+
31
+ export const ISSUECAT_VERSION = "1.1.0";
32
+
33
+ type Thread = { reportId: string; threadKey: string };
34
+ type Options = {
35
+ installKey: string;
36
+ baseURL?: string;
37
+ /** 운영 화면 「받은 곳」에 보일 앱 이름표(없으면 "react-native") */
38
+ app?: string;
39
+ /** 앱 판 — 신고 맥락에 실린다(예: DeviceInfo.getVersion()) */
40
+ appVersion?: string;
41
+ /** 지금 앱 화면을 JPEG base64(머리 없이)로. 예: () => captureScreen({ format: "jpg", quality: 0.7, result: "base64" }). false나 없음 = 그림 없음 */
42
+ capture?: (() => Promise<string | null>) | false;
43
+ /** 클립 단추의 사진 고르기(선택): max장까지 골라 JPEG base64(머리 없이) 목록으로 돌려줍니다. 고르지 않으면 빈 목록.
44
+ * 주면 웹뷰 기본 파일 고르기 대신 이것을 씁니다 — iOS 기본 고르기의 「사진 찍기」 줄(카메라 허락 글이 없으면 앱이 닫힘)을 피하려면 줍니다. */
45
+ pickPhotos?: (max: number) => Promise<string[]>;
46
+ /** true면 이 앱이 보내는 문의가 신고함에 「시험」으로 들어갑니다 — 운영자 알림·손님 숫자에 안 섞입니다. 설치를 확인하는 동안만 켜고 내놓을 판에서는 뺍니다(예: test: __DEV__).
47
+ * 이용 기록(issuecat-usage.ts)도 넣었다면 그쪽 행동·녹화도 같이 시험 기록으로 갑니다(check의 test) */
48
+ test?: boolean;
49
+ /** 문의 창 강조색(앱 색): 색 하나(예 "#0b6ef6" — 밝은·어두운 화면 같이) 또는 { light, dark }. 안 주면 운영 화면 서비스 설정의 색 */
50
+ accent?: string | { light?: string; dark?: string };
51
+ /** 창의 말("ko"·"en"). 앱이 쓰는 말을 넘깁니다(예: i18n 라이브러리의 지금 언어). 안 주면 휴대폰 언어를 따릅니다 */
52
+ locale?: string;
53
+ };
54
+
55
+ let opts: Options | null = null;
56
+ let user: { id: string; name?: string; email?: string; hash?: string } | null = null;
57
+ let extraContext: Record<string, string> = {};
58
+ let pushToken: { token: string; platform: "apns" | "fcm" } | null = null;
59
+ let unreadCallback: ((n: number) => void) | null = null;
60
+ let pushReadyCallback: ((ready: boolean) => void) | null = null;
61
+ let warnedNotReady = false;
62
+ let openState: { url: string; shot: string | null } | null = null;
63
+ let setHost: ((s: typeof openState) => void) | null = null;
64
+ let sendToScreen: ((m: object) => void) | null = null;
65
+ let appStateSub: { remove(): void } | null = null;
66
+
67
+ const base = () => (opts?.baseURL ?? "https://issuecat.com").replace(/\/+$/, "");
68
+ // 대화 열쇠 자리: 로그인한 사람마다 따로(<대화 자리>.<설치키>.u.<아이디>), 로그인 없이 쓰는 앱은 설치키 하나 — reset을 못 부른 채(세션 만료 등)
69
+ // 다른 사람이 identify돼도 그 사람 것만 보인다. 자리 이름은 맨 아래 「옛 코드 호환」의 OLD_STORAGE(앞 판 값 그대로)
70
+ const legacyKey = () => `${OLD_STORAGE.threads}.${opts?.installKey ?? ""}`;
71
+ const storeKey = (u: { id: string } | null = user) => (u ? `${legacyKey()}.u.${encodeURIComponent(u.id)}` : legacyKey());
72
+ const outboxKey = () => `${OLD_STORAGE.outbox}.${opts?.installKey ?? ""}`;
73
+ type Pending = { id: string; path: string; body: string; who?: string };
74
+
75
+ /** 로그인하면 이 기기의 익명 대화를 그 사람에게(Intercom 리드 → 사용자·Chatwoot setUser처럼): 로그인 없이 보낸 대화(<대화 자리>.<설치키>)를
76
+ * 그 사람 자리로 옮기고 익명 자리는 비운다 — 한 번 사람에게 간 대화는 익명 자리로 돌아가지 않아 로그아웃 뒤·다음 사람에게는 안 보인다.
77
+ * 앞 판(사람 구분 없이 <대화 자리>.<설치키> 하나)이 남긴 목록도 이 길로 처음 identify하는 사람(앱이 되살린 로그인)에게 간다.
78
+ * 서버에도 「이 대화들은 이 사람」을 알린다(운영 화면 신고자) — 못 알렸으면 <대화 자리>.claim.<자리> 표시를 남겨 다음 identify 때 다시.
79
+ * identify를 안 쓰는 앱은 설치키 하나를 지금처럼 이 기기의 목록으로 쓴다. */
80
+ async function carryAnon() {
81
+ if (!opts || !user) return;
82
+ const u = user;
83
+ const key = storeKey(u);
84
+ const pending = `${OLD_STORAGE.threads}.claim.${key}`;
85
+ const anon = await threads(legacyKey());
86
+ if (anon.length) {
87
+ // 그 사람 자리에 다 써진 뒤에만 익명 자리를 비운다 — 쓰다 실패하면(저장소 가득) 익명 자리를 그대로 두고 다음 identify 때 다시
88
+ try { for (const t of [...anon].reverse()) await saveThread(t, key); } catch { return; }
89
+ await AsyncStorage.removeItem(legacyKey());
90
+ await AsyncStorage.setItem(pending, "1");
91
+ }
92
+ if (!(await AsyncStorage.getItem(pending))) return;
93
+ const r = await post("/v1/ingest/threads/claim", { installKey: opts.installKey, user: u, threads: (await threads(key)).slice(0, 50) });
94
+ if (r && r.ok === true) await AsyncStorage.removeItem(pending);
95
+ }
96
+
97
+ /** 기기 사이 잇기: identify에 확인 값(hash)이 있으면 그 사람의 모든 문의(다른 기기에서 보낸 것 포함)를 받아 이 기기 목록에 더한다.
98
+ * 이 기기가 쥔 대화는 그 사람에게 이어 다른 기기에서도 보이게 한다. 확인 값이 틀리면(401) 아무것도 안 바뀐다 — 이 기기 목록만. */
99
+ async function syncPerson() {
100
+ if (!opts || !user?.hash) return;
101
+ const key = storeKey(user);
102
+ const r = await post("/v1/ingest/threads/mine", { installKey: opts.installKey, user: { id: user.id, hash: user.hash }, threads: (await threads(key)).slice(0, 50) });
103
+ if (!r || !Array.isArray(r.threads) || key !== storeKey()) return; // 그사이 사람이 바뀌었으면 버린다
104
+ let added = false;
105
+ for (const x of [...r.threads].reverse()) {
106
+ if (!x || typeof x.reportId !== "string" || typeof x.threadKey !== "string" || !x.reportId || !x.threadKey) continue;
107
+ const t = { reportId: x.reportId, threadKey: x.threadKey };
108
+ if (await rememberPerson(t, key)) {
109
+ attachPush(t);
110
+ added = true;
111
+ }
112
+ }
113
+ if (added) void refreshUnread();
114
+ }
115
+
116
+ // 두었다 보내기: 화면이 망 문제로 못 보낸 요청(queued). 같은 신고·답장 번호라 화면이 먼저 보냈어도 서버는 한 번만 받는다.
117
+ async function outbox(): Promise<Pending[]> {
118
+ try {
119
+ const v = JSON.parse((await AsyncStorage.getItem(outboxKey())) ?? "[]");
120
+ return Array.isArray(v) ? v.filter((x) => x && typeof x.id === "string" && typeof x.path === "string" && typeof x.body === "string") : [];
121
+ } catch {
122
+ return [];
123
+ }
124
+ }
125
+ async function outboxSave(list: Pending[]) {
126
+ if (list.length) await AsyncStorage.setItem(outboxKey(), JSON.stringify(list));
127
+ else await AsyncStorage.removeItem(outboxKey());
128
+ }
129
+ let flushing = false;
130
+ /** 창이 닫혀 있을 때 오래된 것부터 보낸다. 다시 보내도 안 받는 것(4xx, 408·429 빼고)은 버린다. */
131
+ async function flushOutbox() {
132
+ if (flushing || !opts || openState) return;
133
+ flushing = true;
134
+ try {
135
+ for (;;) {
136
+ const p = (await outbox())[0];
137
+ if (!p) break;
138
+ let code = 0;
139
+ let out: any = null;
140
+ try {
141
+ const r = await fetch(base() + p.path, { method: "POST", headers: { "content-type": "application/json" }, body: p.body });
142
+ code = r.status;
143
+ out = await r.json().catch(() => null);
144
+ } catch {
145
+ code = 0;
146
+ }
147
+ if (code === 0 || code >= 500 || code === 408 || code === 429) break; // 망·서버 사정: 다음에 앞에 올 때
148
+ await outboxSave((await outbox()).filter((x) => x.id !== p.id));
149
+ if (code >= 200 && code < 300 && p.path === "/v1/ingest/reports") {
150
+ try {
151
+ const sent = JSON.parse(p.body);
152
+ const key = (out && typeof out.threadKey === "string" && out.threadKey) || sent.threadKey;
153
+ if (typeof sent.reportId === "string" && typeof key === "string") {
154
+ const t = { reportId: sent.reportId, threadKey: key };
155
+ const owner = typeof p.who === "string" ? p.who : storeKey(); // 쓴 사람 자리에
156
+ await saveThread(t, owner);
157
+ if (owner === storeKey()) attachPush(t);
158
+ }
159
+ } catch {}
160
+ }
161
+ }
162
+ } finally {
163
+ flushing = false;
164
+ }
165
+ }
166
+
167
+ /** 다른 기기에서 보낸 대화(확인 값으로 서버가 다시 만들어 준 열쇠)는 메모리에만 — AsyncStorage에 남기지 않고 앱이 켜질 때·앞에 올 때 다시 받는다 */
168
+ let personThreads: Thread[] = [];
169
+ let personKey = "";
170
+ /** 받은 대화를 메모리에 더한다(열쇠가 바뀌었으면 새 값으로) — 새로 더한 것만 true */
171
+ async function rememberPerson(t: Thread, key = storeKey()): Promise<boolean> {
172
+ if (personKey !== key) {
173
+ personThreads = [];
174
+ personKey = key;
175
+ }
176
+ if ((await threads(key)).some((x) => x.reportId === t.reportId)) return false;
177
+ const i = personThreads.findIndex((x) => x.reportId === t.reportId);
178
+ if (i >= 0) {
179
+ if (personThreads[i].threadKey !== t.threadKey) personThreads[i] = t;
180
+ return false;
181
+ }
182
+ personThreads.push(t);
183
+ return true;
184
+ }
185
+ /** 이 기기에서 보낸 대화(저장) + 받은 대화(메모리) */
186
+ async function allThreads(): Promise<Thread[]> {
187
+ const key = storeKey();
188
+ const own = await threads(key);
189
+ if (personKey !== key || !personThreads.length) return own;
190
+ const ids = new Set(own.map((t) => t.reportId));
191
+ return [...own, ...personThreads.filter((t) => !ids.has(t.reportId))];
192
+ }
193
+
194
+ /** 대화 열쇠: AsyncStorage — 앱을 지우면 사라집니다(iOS도 같음). */
195
+ async function threads(key = storeKey()): Promise<Thread[]> {
196
+ try {
197
+ const v = JSON.parse((await AsyncStorage.getItem(key)) ?? "[]");
198
+ return Array.isArray(v) ? v.filter((t) => t && typeof t.reportId === "string" && typeof t.threadKey === "string") : [];
199
+ } catch {
200
+ return [];
201
+ }
202
+ }
203
+ async function saveThread(t: Thread, key = storeKey()) {
204
+ const list = [t, ...(await threads(key)).filter((x) => x.reportId !== t.reportId)].slice(0, 200);
205
+ await AsyncStorage.setItem(key, JSON.stringify(list));
206
+ }
207
+
208
+ async function post(path: string, body: object): Promise<any> {
209
+ try {
210
+ const r = await fetch(base() + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
211
+ return await r.json();
212
+ } catch {
213
+ return null;
214
+ }
215
+ }
216
+
217
+ function attachPush(t: Thread) {
218
+ if (!pushToken || !opts) return;
219
+ const p = pushToken;
220
+ void post(`/v1/ingest/threads/${encodeURIComponent(t.reportId)}/push`, { installKey: opts.installKey, threadKey: t.threadKey, provider: p.platform, token: p.token }).then((r) => {
221
+ if (!r || typeof r.ready !== "boolean") return;
222
+ if (!r.ready && !warnedNotReady) {
223
+ warnedNotReady = true;
224
+ console.warn(`[Issuecat] 푸시 열쇠가 아직 없어요(ready:false) — 토큰은 등록됐지만 답 푸시는 안 가요. 운영자가 「설정」 → 「알림」 탭 → 「앱 고객 푸시」 → 「앱 고객에게 푸시」에 ${p.platform === "apns" ? "APNs 키(.p8)" : "FCM 서비스 계정 JSON"}을 올리면 가요.`);
225
+ }
226
+ pushReadyCallback?.(r.ready);
227
+ });
228
+ }
229
+
230
+ // 이용 기록(issuecat-usage.ts)과 로그인 잇기: 두 파일이 서로를 가져오지 않는다(하나만 넣어도 된다). 같은 자바스크립트 안의 globalThis로 지금 사람과 듣는 목록을 나눈다.
231
+ type LinkedUser = { id: string; name?: string; email?: string } | null;
232
+ const link = globalThis as { __issuecatUser?: LinkedUser; __issuecatUserListeners?: Array<(u: LinkedUser) => void> };
233
+ function announceUser() {
234
+ // 확인 값(hash)은 이용 기록 쪽에 넘기지 않는다 — 문의 창만 쓴다
235
+ link.__issuecatUser = user ? { id: user.id, ...(user.name ? { name: user.name } : {}), ...(user.email ? { email: user.email } : {}) } : null;
236
+ setOldLinkedUser(link.__issuecatUser);
237
+ for (const f of linkedListeners()) {
238
+ try { f(link.__issuecatUser); } catch { /* 이용 기록 쪽 오류가 문의 창을 막지 않게 */ }
239
+ }
240
+ }
241
+
242
+ /**
243
+ * 닫혀 있을 때의 안 읽은 수: 저장한 열쇠로 묻는다. 앱이 앞에 있는 동안은 푸시가 없어도 새 답을 알아채게
244
+ * 15초에서 시작해 바뀐 게 없으면 두 배씩 2분까지 늘려 다시 묻는다(앞으로 올 때·창을 닫을 때·답이 오면 15초로). 뒤로 가면 멈춘다.
245
+ */
246
+ let pollTimer: ReturnType<typeof setTimeout> | null = null;
247
+ let pollGap = 15_000;
248
+ let lastTotal: number | null = null;
249
+ function stopPolling() {
250
+ if (pollTimer) clearTimeout(pollTimer);
251
+ pollTimer = null;
252
+ }
253
+ async function refreshUnread(fromTimer = false) {
254
+ if (!fromTimer) pollGap = 15_000;
255
+ stopPolling();
256
+ const cb = unreadCallback;
257
+ if (!cb || !opts || openState) return;
258
+ const saved = await allThreads();
259
+ if (!saved.length) return cb(0);
260
+ const r = await post("/v1/ingest/threads/unread", { installKey: opts.installKey, threads: saved.slice(0, 50) });
261
+ const n = r && typeof r.total === "number" ? r.total : null;
262
+ if (n !== null) cb(n);
263
+ if (n !== null && lastTotal !== null && n !== lastTotal) pollGap = 15_000;
264
+ else if (fromTimer) pollGap = Math.min(pollGap * 2, 120_000);
265
+ if (n !== null) lastTotal = n;
266
+ stopPolling();
267
+ if (AppState.currentState === "active" && !openState && unreadCallback) pollTimer = setTimeout(() => void refreshUnread(true), pollGap);
268
+ }
269
+
270
+ function context(): Record<string, string> {
271
+ const c: Record<string, string> = { os: `${Platform.OS === "ios" ? "iOS" : "Android"} ${Platform.Version}` };
272
+ if (opts?.appVersion) c.appVersion = opts.appVersion;
273
+ return { ...c, ...extraContext };
274
+ }
275
+
276
+ function b64url(s: string): string {
277
+ // UTF-8 → base64url (Hermes에는 Buffer가 없다)
278
+ const bytes = unescape(encodeURIComponent(s));
279
+ const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
280
+ let out = "";
281
+ for (let i = 0; i < bytes.length; i += 3) {
282
+ const n = (bytes.charCodeAt(i) << 16) | ((bytes.charCodeAt(i + 1) || 0) << 8) | (bytes.charCodeAt(i + 2) || 0);
283
+ out += abc[(n >> 18) & 63] + abc[(n >> 12) & 63] + (i + 1 < bytes.length ? abc[(n >> 6) & 63] : "") + (i + 2 < bytes.length ? abc[n & 63] : "");
284
+ }
285
+ return out;
286
+ }
287
+
288
+ export const Issuecat = {
289
+ /** 설치키와 주소. 앱이 켜질 때 한 번. */
290
+ configure(o: Options) {
291
+ opts = o;
292
+ (globalThis as { __issuecatTest?: boolean }).__issuecatTest = o.test === true; // 이용 기록(issuecat-usage.ts)에 시험 표시를 나눈다
293
+ setOldTestFlag(o.test === true);
294
+ appStateSub?.remove();
295
+ appStateSub = AppState.addEventListener("change", (s) => { if (s === "active") { void refreshUnread(); void flushOutbox(); void syncPerson(); } else stopPolling(); });
296
+ void carryAnon().then(syncPerson); // configure 전에 identify한 사람
297
+ void flushOutbox();
298
+ },
299
+ /** 손님 정보(선택) — 운영 화면 「신고자」에 보입니다. 로그아웃은 reset(). 로그인 전에 보낸 문의는 이 사람의 것으로 이어집니다(지난 문의·새 답 수·신고자). */
300
+ /** 이용 기록(issuecat-usage.ts)을 같은 앱에 넣었으면 그쪽 identify도 같이 됩니다 — 따로 안 불러도 됩니다(둘 다 불러도 한 번만 셉니다). */
301
+ /** hash(선택): 내 서버가 서비스 비밀 키로 만든 확인 값(HMAC-SHA256(id)의 16진수). 주면 그 사람이 다른 기기에서 보낸 문의도 이 기기에 이어집니다.
302
+ * 비밀 키는 앱에 넣지 않습니다 — 로그인할 때 내 서버에서 받은 값을 그대로 넘깁니다. */
303
+ identify(u: { id: string; name?: string; email?: string; hash?: string }) {
304
+ const changed = user?.id !== u.id;
305
+ user = { ...u };
306
+ announceUser();
307
+ void (async () => {
308
+ await carryAnon();
309
+ await syncPerson();
310
+ sendToScreen?.({ type: "config", user, context: context(), threads: await allThreads() });
311
+ if (changed) void refreshUnread();
312
+ })();
313
+ },
314
+ /** 신고에 같이 실을 앱 정보(선택) */
315
+ setContext(c: Record<string, string>) {
316
+ extraContext = { ...c };
317
+ sendToScreen?.({ type: "config", context: context() });
318
+ },
319
+ /**
320
+ * 문의 창을 엽니다. thread: 답 알림을 눌렀을 때 그 신고 번호(푸시의 threadId)를 주면 그 대화가 바로 열립니다.
321
+ * kind: "inquiry"(문의하기 — 운영자와 대화) · "report"(문제 신고하기 — 지금 화면부터)를 주면 그 갈래로 바로 엽니다 — Issuecat.open({ kind: "report" }).
322
+ * 운영자가 꺼 둔 갈래를 부르면 켜진 갈래로 열립니다. 안 주면 첫 화면(손님이 고름).
323
+ * view: "threads"면 지난 문의부터(앱 메뉴 「내 문의」 — 지난 문의가 없으면 첫 화면). 창이 이미 열려 있으면 그 자리로 옮깁니다.
324
+ * 여는 중(앱 화면 찍기를 기다리는 동안)에 또 불러도 창은 하나입니다 — 같은 Promise를 돌려줍니다.
325
+ */
326
+ open(o: { thread?: string; kind?: "inquiry" | "report"; view?: "threads" } = {}): Promise<void> {
327
+ if (!opening) opening = openNow(o).finally(() => { opening = null; });
328
+ return opening;
329
+ },
330
+ /** 안 읽은 답 수. 창이 열려 있으면 바뀔 때마다, 닫혀 있으면 앱이 앞에 있는 동안 서버에 물어 부릅니다(15초에서 2분까지 점점 느리게, 앞으로 올 때 바로 — 지금 값도 한 번). */
331
+ onUnread(cb: (count: number) => void) {
332
+ unreadCallback = cb;
333
+ void refreshUnread();
334
+ },
335
+ /** 답 푸시 토큰. platform: 네이티브 APNs 토큰이면 "apns", Firebase면 "fcm". 쥐고 있다가 보낸 문의마다 겁니다. */
336
+ /** 운영자가 그 열쇠를 아직 안 올렸으면 서버가 ready:false로 답합니다(등록은 됨, 푸시는 안 감) — onPushReady에 false가 오고 한 번 console.warn을 찍습니다. */
337
+ async registerPush(o: { token: string; platform: "apns" | "fcm" }) {
338
+ pushToken = { ...o };
339
+ (await allThreads()).forEach(attachPush);
340
+ },
341
+ /** (선택) 토큰을 대화에 걸 때마다 서버 답: true = 푸시 준비됨, false = 운영자가 그 종류(apns·fcm)의 푸시 열쇠를 아직 안 올림. */
342
+ onPushReady(cb: (ready: boolean) => void) {
343
+ pushReadyCallback = cb;
344
+ },
345
+ /** 로그아웃 때: 손님 정보·이 기기의 대화 열쇠·안 읽은 수를 지우고, 푸시 토큰을 이 서비스의 대화에서 뺍니다. */
346
+ /** 이용 기록(issuecat-usage.ts)을 같은 앱에 넣었으면 그쪽 reset도 같이 됩니다. */
347
+ async reset() {
348
+ // 로그아웃하는 사람의 대화 열쇠와 로그인 없이 보낸 것(앞 판과 같이 이 기기에서 지운다), 다른 기기에서 받은 열쇠(메모리)
349
+ personThreads = [];
350
+ personKey = "";
351
+ await AsyncStorage.removeItem(storeKey());
352
+ await AsyncStorage.removeItem(legacyKey());
353
+ user = null;
354
+ announceUser();
355
+ if (pushToken && opts) void post("/v1/ingest/threads/push/remove", { installKey: opts.installKey, token: pushToken.token });
356
+ clearWebStorage = true; // 화면이 제 저장소(localStorage)에 둔 대화 목록은 다음에 열 때 지운다
357
+ close();
358
+ unreadCallback?.(0);
359
+ },
360
+ /** 예전에 직접 그린 화면(issuecat-report 등)으로 받은 대화 열쇠를 넘깁니다 — 「지난 문의」에 이어 보입니다. */
361
+ async importThreads(list: Thread[]) {
362
+ for (const t of [...list].reverse()) { await saveThread(t); attachPush(t); }
363
+ void refreshUnread();
364
+ },
365
+ /** 받은 푸시(data)가 Issuecat 답이면 그 신고 번호 — Issuecat.open({ thread })에 줍니다. */
366
+ threadId(data: Record<string, unknown> | undefined): string | null {
367
+ return data && (data.issuecat ?? data[OLD_PUSH_MARK]) === "reply" && typeof data.threadId === "string" ? data.threadId : null;
368
+ },
369
+ };
370
+
371
+ let clearWebStorage = false;
372
+ let opening: Promise<void> | null = null;
373
+ const originOf = (u: string) => { const m = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]*)/i.exec(u); return m ? m[1].toLowerCase() : ""; };
374
+ const ours = (u: string) => originOf(u) === originOf(base());
375
+ const openOutside = (u: string) => { if (/^(https?:|mailto:|tel:)/i.test(u)) void Linking.openURL(u); };
376
+
377
+ async function openNow(o: { thread?: string; kind?: "inquiry" | "report"; view?: "threads" }) {
378
+ if (!opts) throw new Error("Issuecat.configure({ installKey })를 먼저 부르세요");
379
+ if (!setHost) throw new Error("<IssuecatHost />를 앱 맨 바깥에 두세요");
380
+ const saved = await allThreads();
381
+ if (openState) {
382
+ // 이미 열려 있으면 그 자리로 옮긴다
383
+ if (o.thread) sendToScreen?.({ type: "config", threads: saved, thread: o.thread });
384
+ else if (o.kind) sendToScreen?.({ type: "config", kind: o.kind });
385
+ else if (o.view) sendToScreen?.({ type: "config", view: o.view });
386
+ return;
387
+ }
388
+ let shot: string | null = null;
389
+ try { shot = opts.capture ? await opts.capture() : null; } catch { shot = null; } // 문의 창이 덮기 전의 앱 화면
390
+ const cfg: Record<string, unknown> = { v: 1, sdk: `react-native/${ISSUECAT_VERSION}`, app: opts.app ?? "react-native", context: context() };
391
+ if (!opts.capture) cfg.capture = false; // 찍을 길이 없으면 화면 줄을 감춘다
392
+ if (opts.test === true) cfg.test = true; // 시험 문의
393
+ if (opts.pickPhotos) cfg.pick = true; // 사진 고르기는 앱이(pick-photos → photos)
394
+ if (user) cfg.user = user;
395
+ if (saved.length) cfg.threads = saved;
396
+ if (o.thread) cfg.thread = o.thread;
397
+ if (o.kind) cfg.kind = o.kind;
398
+ if (o.view) cfg.view = o.view;
399
+ if (opts.accent) cfg.accent = opts.accent; // 앱 색
400
+ if (opts.locale) cfg.locale = opts.locale; // 창의 말
401
+ openState = { url: `${base()}/inquiry?k=${encodeURIComponent(opts.installKey)}#cfg=${b64url(JSON.stringify(cfg))}`, shot };
402
+ setHost(openState);
403
+ }
404
+ function close() {
405
+ openState = null;
406
+ setHost?.(null);
407
+ void flushOutbox();
408
+ void refreshUnread();
409
+ }
410
+
411
+ // 다리 이름 IssuecatBridge는 iOS·Android 네이티브 SDK 몫 — RN은 화면이 ReactNativeWebView.postMessage로 보낸다
412
+ const CLEAR_JS = `try{Object.keys(localStorage).forEach(function(k){if(k.indexOf("mkThreads:")===0)localStorage.removeItem(k)})}catch(e){}true;`;
413
+
414
+ /** 창이 뜰 자리. 앱 맨 바깥(내비게이션 바깥)에 한 번 둡니다. */
415
+ export function IssuecatHost() {
416
+ const [state, setState] = useState<typeof openState>(null);
417
+ const web = useRef<IssuecatWebViewRef>(null);
418
+ const [failed, setFailed] = useState(false);
419
+ const dark = useColorScheme() === "dark";
420
+ const clearOnce = useRef(false);
421
+
422
+ useEffect(() => {
423
+ setHost = (s) => { setFailed(false); clearOnce.current = clearWebStorage; clearWebStorage = false; setState(s); };
424
+ return () => { setHost = null; };
425
+ }, []);
426
+ useEffect(() => {
427
+ sendToScreen = state ? (m) => web.current?.injectJavaScript(`${receiveJS(JSON.stringify(m))};true;`) : null;
428
+ }, [state]);
429
+
430
+ const onMessage = async (e: WebViewMessageEvent) => {
431
+ let m: any;
432
+ try { m = JSON.parse(e.nativeEvent.data); } catch { return; }
433
+ if (!m || (m.issuecat !== 1 && m[OLD_MESSAGE_MARK] !== 1)) return;
434
+ if (m.type === "capture-request") {
435
+ sendToScreen?.(state?.shot ? { type: "capture", id: m.id, jpeg: state.shot } : { type: "capture", id: m.id, none: true });
436
+ } else if (m.type === "sent" && m.reportId && m.threadKey) {
437
+ const t = { reportId: String(m.reportId), threadKey: String(m.threadKey) };
438
+ await saveThread(t);
439
+ attachPush(t);
440
+ } else if (m.type === "threads" && Array.isArray(m.threads)) {
441
+ // 창이 받아 온 대화(다른 기기에서 보낸 것·옛 길의 것) — 쥐어 두면 창이 닫혀 있을 때도 새 답 수에 든다.
442
+ // 다른 기기에서 보낸 것(from "person")은 메모리에만, 옛 길의 것은 저장
443
+ const person = m.from === "person";
444
+ const have = new Set((await threads()).map((t) => t.reportId));
445
+ for (const x of [...m.threads].reverse()) {
446
+ if (!x || typeof x.reportId !== "string" || typeof x.threadKey !== "string" || !x.reportId || !x.threadKey) continue;
447
+ const t = { reportId: x.reportId, threadKey: x.threadKey };
448
+ if (person) {
449
+ if (await rememberPerson(t)) attachPush(t);
450
+ } else if (!have.has(x.reportId)) {
451
+ await saveThread(t);
452
+ attachPush(t);
453
+ }
454
+ }
455
+ } else if (m.type === "unread" && typeof m.count === "number") {
456
+ unreadCallback?.(m.count);
457
+ } else if (m.type === "close") {
458
+ close();
459
+ } else if (m.type === "queued" && typeof m.id === "string" && typeof m.path === "string" && m.path.startsWith("/v1/ingest/") && typeof m.body === "string") {
460
+ await outboxSave([...(await outbox()).filter((x) => x.id !== m.id), { id: m.id, path: m.path, body: m.body, who: storeKey() }]);
461
+ } else if (m.type === "dequeued" && typeof m.id === "string") {
462
+ await outboxSave((await outbox()).filter((x) => x.id !== m.id));
463
+ } else if (m.type === "pick-photos" && typeof m.id === "string") {
464
+ // 클립 단추: 앱의 사진 고르기 → 고른 그림(JPEG base64)을 화면에. 실패·취소는 빈 목록
465
+ const max = typeof m.max === "number" && m.max > 0 ? Math.min(m.max, 10) : 10;
466
+ let jpegs: string[] = [];
467
+ try { jpegs = opts?.pickPhotos ? (await opts.pickPhotos(max)).filter((j) => typeof j === "string" && j).slice(0, max) : []; } catch { jpegs = []; }
468
+ sendToScreen?.({ type: "photos", id: m.id, jpegs });
469
+ } else if (m.type === "open-url" && typeof m.url === "string" && /^https?:\/\//.test(m.url)) {
470
+ void Linking.openURL(m.url); // 창 아래 Issuecat 표시 등: 문의 창 안에서 넘어가지 않게 바깥 브라우저로
471
+ }
472
+ };
473
+
474
+ // 연결 실패 안내 한 줄 — 언어는 웹뷰의 navigator.language로(문의 화면과 같은 길)
475
+ const offline = `<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="color-scheme" content="light dark">
476
+ <body style="margin:0;height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;box-sizing:border-box;font:15px -apple-system,sans-serif;text-align:center">
477
+ <p id="m" style="margin:0;line-height:1.6">연결할 수 없어요. 인터넷 연결을 확인하고 다시 열어 주세요.</p><div style="display:flex;gap:10px">
478
+ <button id="r" onclick="ReactNativeWebView.postMessage(JSON.stringify({issuecat:1,type:'retry'}))" style="font:inherit;height:44px;padding:0 20px;border-radius:22px">다시 시도</button>
479
+ <button id="c" onclick="ReactNativeWebView.postMessage(JSON.stringify({issuecat:1,type:'close'}))" style="font:inherit;height:44px;padding:0 20px;border-radius:22px">닫기</button></div>
480
+ <script>if(!/^ko/i.test(navigator.language||"")){document.documentElement.lang="en";m.textContent="Can't connect. Check your connection and try again.";r.textContent="Retry";c.textContent="Close"}</script></body>`;
481
+
482
+ return (
483
+ <Modal visible={!!state} animationType="slide" presentationStyle="fullScreen" onRequestClose={() => (failed ? close() : sendToScreen?.({ type: "back" }))}>
484
+ {/* 안전 영역·키보드는 화면(viewport-fit=cover, env(safe-area-inset-*), visualViewport)이 맡는다 */}
485
+ <View style={{ flex: 1, backgroundColor: dark ? "#0f1115" : "#f6f7f9" }}>
486
+ {Platform.OS === "android" ? <StatusBar barStyle={dark ? "light-content" : "dark-content"} /> : null}
487
+ {state ? (
488
+ <IssuecatWebView
489
+ ref={web}
490
+ source={failed ? { html: offline } : { uri: state.url }}
491
+ originWhitelist={["*"]}
492
+ javaScriptEnabled
493
+ domStorageEnabled
494
+ injectedJavaScriptBeforeContentLoaded={clearOnce.current ? CLEAR_JS : "true;"}
495
+ contentInsetAdjustmentBehavior="never"
496
+ hideKeyboardAccessoryView
497
+ automaticallyAdjustContentInsets={false}
498
+ bounces={false}
499
+ style={{ flex: 1, backgroundColor: "transparent" }}
500
+ onMessage={(e) => {
501
+ try { if (JSON.parse(e.nativeEvent.data).type === "retry") return setFailed(false); } catch {}
502
+ void onMessage(e);
503
+ }}
504
+ onError={() => setFailed(true)}
505
+ onHttpError={(e) => { if (e.nativeEvent.statusCode >= 500) setFailed(true); }}
506
+ onShouldStartLoadWithRequest={(r) => {
507
+ // 우리 주소 밖 고리(답 속 링크 등)는 브라우저로 — 주소 앞부분이 아니라 출처(scheme+host+port)로 견준다(issuecat.com.다른곳.example 같은 주소 막기)
508
+ if (ours(r.url) || r.url.startsWith("about:") || r.url.startsWith("data:")) return true;
509
+ openOutside(r.url);
510
+ return false;
511
+ }}
512
+ // 새 창(target=_blank — 답 속 링크)은 열지 않고 브라우저로. 문의 창은 그대로
513
+ onOpenWindow={(e) => openOutside(e.nativeEvent.targetUrl)}
514
+ />
515
+ ) : null}
516
+ </View>
517
+ </Modal>
518
+ );
519
+ }
520
+
521
+ /** 앱 → 화면: 화면의 window.issuecatReceive로. 없으면(앞 판 화면) 옛 이름 window.Cuelen.receive로 — 있는 것 하나에만 보낸다 */
522
+ function receiveJS(json: string): string {
523
+ return `(window.issuecatReceive||(window.${OLD_SCREEN_OBJECT}&&window.${OLD_SCREEN_OBJECT}.receive)||function(){})(${json})`;
524
+ }
525
+
526
+ // ---- 옛 코드 호환 — 앞 판(옛 이름 Cuelen·문제콕) 앱 코드·파일과 섞여도 돌게 하는 이름을 여기 모읍니다.
527
+
528
+ /** 저장 자리(AsyncStorage) — 앞 판이 쓰던 값 그대로입니다. 바꾸면 저장한 대화 열쇠·못 보낸 문의를 잃어요. */
529
+ const OLD_STORAGE = { threads: "cuelen.threads", outbox: "cuelen.outbox" } as const;
530
+ /** 앞 판 문의 화면의 메시지 칸·받는 곳 — 메시지는 어느 칸이든 받는다 */
531
+ const OLD_MESSAGE_MARK = "cuelen";
532
+ /** 앞 판 서버가 보낸 답 푸시의 표시 칸 이름 — 그 칸으로 온 푸시도 받는다 */
533
+ const OLD_PUSH_MARK = "munjaekok";
534
+ const OLD_SCREEN_OBJECT = "Cuelen";
535
+
536
+ /** 앞 판 이용 기록 파일(munjaekok.ts·앞 판 issuecat-usage.ts)이 쓰는 globalThis 칸 — 새 칸과 같은 목록·같은 값을 가리키게 한다(어느 파일이 먼저 떠도) */
537
+ type OldLink = { __cuelenUser?: LinkedUser; __cuelenUserListeners?: Array<(u: LinkedUser) => void>; __cuelenTest?: boolean };
538
+ function linkedListeners(): Array<(u: LinkedUser) => void> {
539
+ const g = globalThis as typeof link & OldLink;
540
+ const list = g.__issuecatUserListeners ?? g.__cuelenUserListeners ?? [];
541
+ g.__issuecatUserListeners = g.__cuelenUserListeners = list;
542
+ return list;
543
+ }
544
+ function setOldLinkedUser(u: LinkedUser) { (globalThis as OldLink).__cuelenUser = u; }
545
+ function setOldTestFlag(on: boolean) { (globalThis as OldLink).__cuelenTest = on; }
546
+
547
+ // 옛 이름(Cuelen) — 앞 판 cuelen.tsx를 이 파일로 바꿔 넣어도(이름은 그대로 cuelen.tsx로 둬도) 앱의 Cuelen·<CuelenHost /> 코드가 그대로 돕니다
548
+ export const Cuelen = Issuecat;
549
+ export const CuelenHost = IssuecatHost;
550
+ export const CUELEN_VERSION = ISSUECAT_VERSION;
551
+ export default Issuecat;