@issuecat/react-native 0.0.0-stage → 1.5.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 +21 -0
- package/README.md +97 -2
- package/package.json +26 -4
- package/src/auto-replay.ts +36 -0
- package/src/index.ts +8 -0
- package/src/issuecat-inbox.ts +59 -0
- package/src/issuecat-push.ts +53 -0
- package/src/issuecat-replay.ts +263 -0
- package/src/issuecat-report.ts +164 -0
- package/src/issuecat-usage.ts +377 -0
- package/src/issuecat.tsx +753 -0
|
@@ -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 NonNullable<RequestInit["body"]>, // DOM(BodyInit)·React Native(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,377 @@
|
|
|
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
|
+
// 앱 오류는 저절로 남습니다: 잡히지 않은 오류·처리 안 된 Promise 거절·앱이 꺼지는 오류를 $error로(앱 판·OS·기기·지금 화면과 함께) — 손님 코드에 더할 것이 없습니다.
|
|
6
|
+
// 순정: @sentry/react-native(MIT)의 reactNativeErrorHandlersIntegration — ErrorUtils 전역 처리기를 감싸 원래 처리기로 넘기고, 앱이 꺼지는 오류는 보내 본 뒤(못 보내면
|
|
7
|
+
// 기기에 두었다가 다음에 켤 때) 원래 처리기를 부르고, Promise 거절은 Hermes의 enablePromiseRejectionTracker로 받는다. 네이티브 크래시(Swift·Objective-C·Java·C++)는
|
|
8
|
+
// JS가 못 잡는다 — 설치 안내의 「네이티브 크래시」(Sentry 모바일 SDK에 Issuecat DSN 한 줄)로 받는다.
|
|
9
|
+
type Props = Record<string, unknown>;
|
|
10
|
+
type Wire = { n: string; t: number; p: string; x?: Props; i: string; s: string; u: string | null; a?: string };
|
|
11
|
+
type Storage = { getItem(key: string): Promise<string | null>; setItem(key: string, value: string): Promise<void> };
|
|
12
|
+
|
|
13
|
+
export type IssuecatUsageOptions = {
|
|
14
|
+
origin: string; // Issuecat 주소
|
|
15
|
+
installKey: string; // 서비스 설정의 설치키(공개해도 되는 값)
|
|
16
|
+
app: string; // 앱 이름표: 소문자·숫자·.-_ 64자까지 (예: my-app-ios)
|
|
17
|
+
userAgent: string; // 앱 이름이 든 값 (예: "MyApp/1.2.3 (iOS)"). okhttp·curl 같은 기본 이름표는 로봇으로 셉니다
|
|
18
|
+
storage?: Storage; // 기기 번호와 못 보낸 줄을 저장할 곳. React Native는 AsyncStorage
|
|
19
|
+
deviceStorage?: Storage; // 기기 번호만 따로 둘 곳(선택) — iOS 키체인(expo-secure-store)을 주면 앱을 지웠다 깔아도·TestFlight 판과 App Store 판을 바꿔도 같은 기기입니다. storage에 있던 번호는 옮겨 씁니다
|
|
20
|
+
test?: boolean; // true면 이 기기의 행동·녹화가 설치 확인 시험 기록으로(고객 숫자에 안 섞이고 check의 test로). 개발 판에서만: __DEV__. 상담창을 Issuecat.configure({ test: true })로 열었으면 안 켜도 같이 시험
|
|
21
|
+
release?: string; // 앱 판(예: "1.4.2") — 앱 오류·숨은 문제의 「이 판부터」에 실립니다
|
|
22
|
+
pre?: string | boolean; // 시험판이면(TestFlight·애플 심사·내부 테스트·개발 빌드) "testflight"·"dev" 같은 값 — Issuecat이 이 기기를 손님 숫자에서 뺍니다(「우리 팀 포함」으로 다시 봄). JS만으로는 TestFlight를 못 알아봐 앱이 넘깁니다(안내 「시험판 빼기」). 정식판은 안 줍니다
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** 작업 알리기의 선택 값: key 같은 이름을 나란히 돌릴 때 가르는 값 · step 실패한 단계(안 주면 마지막으로 알린 단계) · message·error 실패 글 · reason error|abandoned|other · timeoutMs 이만큼 신호가 없으면 끝나지 않은 작업(기본 30분) */
|
|
26
|
+
export type IssuecatOperationOptions = { key?: string | number; step?: string; message?: string; error?: unknown; reason?: "error" | "abandoned" | "other"; timeoutMs?: number };
|
|
27
|
+
|
|
28
|
+
/** 서버 요청 하나($api). status는 받은 HTTP 코드 — 응답을 못 받았으면 0과 error(까닭) */
|
|
29
|
+
export type IssuecatUsageRequest = {
|
|
30
|
+
method?: string; // GET·POST …
|
|
31
|
+
path: string; // 요청 주소의 경로만(쿼리 없이). 예: "/v1/orders"
|
|
32
|
+
status: number;
|
|
33
|
+
ms?: number; // 걸린 시간
|
|
34
|
+
host?: string; // 다른 회사 서버(결제·지도 등)로 간 요청만 그 호스트. 내 서버면 비웁니다
|
|
35
|
+
error?: string; // status 0일 때 까닭(예: "Network request failed")
|
|
36
|
+
aborted?: boolean; // 앱이 스스로 취소한 요청 — 문제로 세지 않습니다
|
|
37
|
+
expected?: boolean; // 일부러 낸 거절(로그인 안 한 사람의 401 등) — 기록만 남고 문제로 세지 않습니다
|
|
38
|
+
res?: string; // (선택) 실패한 응답 글 — 고객이 본 말
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const uuid = () =>
|
|
42
|
+
"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
43
|
+
const r = (Math.random() * 16) | 0;
|
|
44
|
+
return (c === "x" ? r : (r & 3) | 8).toString(16);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/** 녹화 양 「오류가 난 방문만」을 깨우는 행동: $error · 5xx·인터넷 없음으로 끝난 $api · 실패한 작업 */
|
|
48
|
+
function isTrouble(name: string, props?: Props): boolean {
|
|
49
|
+
const x = (props ?? {}) as Record<string, unknown>;
|
|
50
|
+
if (name === "$error") return true;
|
|
51
|
+
if (name === "$op") return x.phase === "fail";
|
|
52
|
+
if (name !== "$api") return false;
|
|
53
|
+
if (x.error != null) return true;
|
|
54
|
+
const status = typeof x.status === "number" ? x.status : null;
|
|
55
|
+
return status === null ? x.ok === false : status === 0 || status >= 500;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function createIssuecatUsage(opts: IssuecatUsageOptions) {
|
|
59
|
+
const origin = opts.origin.replace(/\/+$/, "");
|
|
60
|
+
const url = `${origin}/v1/ingest/t/${opts.installKey}/e`;
|
|
61
|
+
let session = uuid(); // 앱을 켤 때마다 새 방문
|
|
62
|
+
let device: string | null = null; // 기기 번호: 처음 한 번 만들어 저장
|
|
63
|
+
let user: string | null = null;
|
|
64
|
+
let current = ""; // 지금 화면 이름 — 서버 요청·오류에 같이 실립니다
|
|
65
|
+
let stopped = false;
|
|
66
|
+
let pending: Wire[] = [];
|
|
67
|
+
let lastError = { key: "", at: 0 }; // 같은 오류가 두 처리기(손님이 따로 건 것 + 이 파일)로 두 번 오면 한 번만
|
|
68
|
+
// 못 보낸 줄은 기기에 남아 앱을 다시 켜도 보냅니다(줄마다 그때의 방문·사람이 박혀 있습니다)
|
|
69
|
+
const loaded = opts.storage?.getItem(OLD_STORAGE.pending).then((saved) => {
|
|
70
|
+
try { if (saved) pending = [...(JSON.parse(saved) as Wire[]), ...pending]; } catch { /* 깨진 값은 버립니다 */ }
|
|
71
|
+
});
|
|
72
|
+
void deviceId(); // 기기 번호를 미리 읽어 줄마다 박습니다(로그아웃하면 바뀝니다)
|
|
73
|
+
const save = () => { void opts.storage?.setItem(OLD_STORAGE.pending, JSON.stringify(pending)); };
|
|
74
|
+
|
|
75
|
+
async function deviceId(): Promise<string> {
|
|
76
|
+
if (device) return device;
|
|
77
|
+
const kept = await opts.deviceStorage?.getItem(OLD_STORAGE.device).catch(() => null);
|
|
78
|
+
const saved = kept || (await opts.storage?.getItem(OLD_STORAGE.device));
|
|
79
|
+
device = saved || uuid();
|
|
80
|
+
if (!saved) await opts.storage?.setItem(OLD_STORAGE.device, device);
|
|
81
|
+
if (!kept) await opts.deviceStorage?.setItem(OLD_STORAGE.device, device).catch(() => undefined);
|
|
82
|
+
return device;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 행동 하나를 쌓습니다. path는 화면 이름(예: "/home", "/마이/설정") — 안 주면 지금 화면. */
|
|
86
|
+
function track(name: string, path = current, props?: Props) {
|
|
87
|
+
if (stopped) return;
|
|
88
|
+
// i: 행동 번호(다시 보내도 한 번만 저장) · s·u·a: 지금의 방문·사람·기기 — 로그아웃 뒤에 보내도 이 줄의 사람은 그대로입니다
|
|
89
|
+
pending.push({ n: name, t: Date.now(), p: path, ...(props ? { x: props } : {}), i: uuid(), s: session, u: user, ...(device ? { a: device } : {}) });
|
|
90
|
+
save();
|
|
91
|
+
if (isTrouble(name, props)) trouble();
|
|
92
|
+
}
|
|
93
|
+
/** 문제가 났다고 화면 녹화(issuecat-replay.ts)에 알립니다 — 녹화 양 「오류가 난 방문만」이면 이 방문을 앞 30초부터 보냅니다. $error·실패한 $api(5xx·인터넷 없음)·실패한 작업은 저절로 알립니다. */
|
|
94
|
+
function trouble() {
|
|
95
|
+
for (const f of (globalThis as { __issuecatTrouble?: Array<() => void> }).__issuecatTrouble ?? []) { try { f(); } catch { /* 녹화 쪽 실패는 무시 */ } }
|
|
96
|
+
}
|
|
97
|
+
/** 화면을 열 때. 이 뒤의 행동·서버 요청·오류는 이 화면에서 난 것으로 실립니다. 상담창(issuecat.tsx)도 넣었다면 신고의 「앱 화면」으로도 붙습니다(globalThis로 나눕니다). */
|
|
98
|
+
const screen = (path: string, title?: string) => {
|
|
99
|
+
current = path;
|
|
100
|
+
(globalThis as { __issuecatScreen?: string }).__issuecatScreen = String(path).slice(0, 200);
|
|
101
|
+
track("$pageview", path, title ? { title } : undefined);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** 로그인한 사람을 알립니다. 이 뒤에 쌓는 줄의 u에 실립니다. 같은 사람을 다시 알리면 건너뜁니다(상담창 SDK와 둘 다 불러도 $identify는 한 번). */
|
|
105
|
+
function identify(userId: string, traits?: { email?: string; name?: string }) {
|
|
106
|
+
if (user === userId) return;
|
|
107
|
+
user = userId;
|
|
108
|
+
track("$identify", "", { user_id: userId, ...traits });
|
|
109
|
+
}
|
|
110
|
+
/** 로그아웃: 웹과 같이 새 고객(새 기기 번호·새 방문)으로 시작합니다. 앞 사람의 쌓인 줄은 그 사람·방문 그대로 나갑니다. 이미 로그아웃한 뒤면 건너뜁니다 */
|
|
111
|
+
const reset = () => {
|
|
112
|
+
if (!user) return;
|
|
113
|
+
track("$logout", ""); // 로그아웃 줄은 나가는 사람·방문으로 남습니다
|
|
114
|
+
user = null;
|
|
115
|
+
session = uuid();
|
|
116
|
+
device = uuid();
|
|
117
|
+
void opts.storage?.setItem(OLD_STORAGE.device, device);
|
|
118
|
+
void opts.deviceStorage?.setItem(OLD_STORAGE.device, device).catch(() => undefined);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
/** 서버 요청 하나를 남깁니다($api) — 답답한 곳 「서버 요청 문제」·서버 요청 성적표·숨은 문제에 들어갑니다. */
|
|
122
|
+
function request(r: IssuecatUsageRequest) {
|
|
123
|
+
const { method, ...rest } = r;
|
|
124
|
+
track("$api", current, { ...rest, method: (method ?? "GET").toUpperCase(), ok: r.status >= 200 && r.status < 300 });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 앱에서 난 오류를 남깁니다($error) — 숨은 문제·답답한 곳 「화면 오류」에 들어갑니다. kind는 "error"·"unhandledrejection"·"fatal"(앱이 꺼짐)·"captured"(잡아서 처리한 오류).
|
|
129
|
+
* 잡히지 않은 오류·Promise 거절·앱이 꺼지는 오류는 이 파일이 저절로 부릅니다. try/catch로 잡은 오류를 남기려면 catch에서 error(err, "captured").
|
|
130
|
+
*/
|
|
131
|
+
function error(err: unknown, kind = "error") {
|
|
132
|
+
const e = err instanceof Error ? err : null;
|
|
133
|
+
const message = e ? `${e.name}: ${e.message}` : typeof err === "string" ? err : safeText(err);
|
|
134
|
+
const stack = e?.stack ?? "";
|
|
135
|
+
const key = `${message}|${stack.slice(0, 300)}`;
|
|
136
|
+
if (key === lastError.key && Date.now() - lastError.at < 2000) return;
|
|
137
|
+
lastError = { key, at: Date.now() };
|
|
138
|
+
const top = topFrame(stack);
|
|
139
|
+
track("$error", current, { kind, message, ...(stack ? { stack: stack.slice(0, 8000) } : {}), ...(top ?? {}), ...appEnv(), ...(release() ? { release: release() } : {}) });
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* fetch를 감싸 서버 요청을 저절로 남깁니다. ownHosts는 내 서버 호스트(예: ["api.myapp.com"]) — 그 밖의 호스트로 간 요청은 host 칸이 붙어
|
|
144
|
+
* 「바깥 주소」로 따로 보입니다. Issuecat으로 가는 요청은 남기지 않습니다. 요청·응답 본문은 보내지 않고, 실패한 응답(400 이상)의 글만 res로 보냅니다.
|
|
145
|
+
*/
|
|
146
|
+
function wrapFetch(f: typeof fetch, ownHosts: string[] = []): typeof fetch {
|
|
147
|
+
return async (input, init) => {
|
|
148
|
+
const started = Date.now();
|
|
149
|
+
const raw = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
150
|
+
let target: URL | null = null;
|
|
151
|
+
try { target = new URL(raw); } catch { /* 상대 주소 등 — 남기지 않습니다 */ }
|
|
152
|
+
const skip = !target || raw.startsWith(origin);
|
|
153
|
+
const method = init?.method ?? (typeof input === "object" && "method" in input ? input.method : "GET");
|
|
154
|
+
const where = target && !(ownHosts.length === 0 || ownHosts.includes(target.host)) ? { host: target.host } : {};
|
|
155
|
+
try {
|
|
156
|
+
const res = await f(input, init);
|
|
157
|
+
if (!skip) {
|
|
158
|
+
const body = res.status >= 400 ? await res.clone().text().catch(() => undefined) : undefined;
|
|
159
|
+
request({ method, path: target!.pathname, status: res.status, ms: Date.now() - started, ...where, ...(body ? { res: body } : {}) });
|
|
160
|
+
}
|
|
161
|
+
return res;
|
|
162
|
+
} catch (err) {
|
|
163
|
+
const aborted = err instanceof Error && err.name === "AbortError";
|
|
164
|
+
if (!skip) request({ method, path: target!.pathname, status: 0, ms: Date.now() - started, error: String(err), ...where, ...(aborted ? { aborted: true } : {}) });
|
|
165
|
+
throw err;
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 잡히지 않은 오류·Promise 거절을 저절로 남깁니다(앱 전체에 한 번 — 이용 기록을 둘 만들어도 처리기는 하나)
|
|
171
|
+
catchAppErrors(error, () => flush());
|
|
172
|
+
|
|
173
|
+
/** 이 기기·이 방문의 번호 — 신고 보내기(issuecat-report.ts)의 visit에 주면 신고에서 신고 전 행동으로 이어집니다. */
|
|
174
|
+
const ids = async () => ({ device: await deviceId(), session });
|
|
175
|
+
|
|
176
|
+
/** 쌓인 행동을 보냅니다. 응답 코드를 돌려줍니다(0은 인터넷 없음, null은 보낼 것 없음). */
|
|
177
|
+
// 보내기는 한 번에 하나씩 차례로 — 앱이 꺼지는 오류는 앞서 시작한 보내기까지 기다린 뒤 제 줄을 보냅니다
|
|
178
|
+
let queue: Promise<unknown> = Promise.resolve();
|
|
179
|
+
function flush(): Promise<number | null> {
|
|
180
|
+
const run = queue.then(flushOnce, flushOnce);
|
|
181
|
+
queue = run.catch(() => null);
|
|
182
|
+
return run;
|
|
183
|
+
}
|
|
184
|
+
async function flushOnce(): Promise<number | null> {
|
|
185
|
+
await loaded;
|
|
186
|
+
if (stopped || pending.length === 0) return null;
|
|
187
|
+
// 보내는 동안에도 줄은 기기에 남겨 둡니다(앱이 그 사이 꺼져도 다음에 켤 때 같은 행동 번호로 다시 — 서버가 한 번만 저장)
|
|
188
|
+
const batch = pending.slice(0, 500);
|
|
189
|
+
const drop = () => { const out = new Set(batch); pending = pending.filter((x) => !out.has(x)); save(); };
|
|
190
|
+
let status = 0;
|
|
191
|
+
try {
|
|
192
|
+
const res = await fetch(url, {
|
|
193
|
+
method: "POST",
|
|
194
|
+
headers: { "content-type": "application/json", "user-agent": opts.userAgent },
|
|
195
|
+
body: JSON.stringify({ v: 1, app: opts.app, a: await deviceId(), s: session, w: session, u: user, sent: Date.now(), ...(release() ? { rel: release() } : {}), ...(opts.test || linkedTestOn() ? { test: true } : {}), ...(opts.pre ? { pre: opts.pre } : {}), e: batch }),
|
|
196
|
+
});
|
|
197
|
+
status = res.status;
|
|
198
|
+
} catch {
|
|
199
|
+
/* 인터넷 없음 */
|
|
200
|
+
}
|
|
201
|
+
if (status === 401 || status === 403) {
|
|
202
|
+
stopped = true; // 모르는 설치키·꺼진 서비스: 더 보내도 같습니다
|
|
203
|
+
pending = [];
|
|
204
|
+
save();
|
|
205
|
+
} else if (!(status === 0 || status === 408 || status === 429 || status >= 500)) drop(); // 2xx는 성공, 400·413은 이 묶음을 받을 수 없어서 버립니다
|
|
206
|
+
// 0·408·429·5xx는 그대로 두었다가 나중에 같은 행동 번호로 다시
|
|
207
|
+
return status;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function release(): string | undefined {
|
|
211
|
+
return opts.release || undefined;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// 상담창 SDK(issuecat.tsx)의 로그인·로그아웃을 따라갑니다 — 두 파일이 서로를 가져오지 않습니다(globalThis로 나눕니다).
|
|
215
|
+
// 상담창이 먼저 로그인을 알렸으면 지금 그 사람을 집습니다.
|
|
216
|
+
const follow = (u: LinkedUser) => {
|
|
217
|
+
if (u) identify(u.id, { ...(u.email ? { email: u.email } : {}), ...(u.name ? { name: u.name } : {}) });
|
|
218
|
+
else reset();
|
|
219
|
+
};
|
|
220
|
+
linkedListeners().push(follow);
|
|
221
|
+
const now = linkedUserNow();
|
|
222
|
+
if (now) follow(now);
|
|
223
|
+
|
|
224
|
+
// session: 지금 방문 번호(화면 녹화 issuecat-replay.ts가 같이 씁니다). 로그아웃하면 바뀌어서 읽을 때마다 지금 값을 줍니다
|
|
225
|
+
/**
|
|
226
|
+
* 오래 걸리는 작업(영상 만들기·파일 내보내기 등)의 시작·단계·실패·끝남을 남깁니다($op) — 같은 단계 실패와, 정한 시간(기본 30분, timeoutMs) 동안 신호가 없는
|
|
227
|
+
* 「끝나지 않은 작업」이 숨은 문제에 들어갑니다(서버 요청이 모두 200이어도). 단계를 알리는 동안은 오래 걸려도 정상입니다.
|
|
228
|
+
* 같은 이름의 작업을 나란히 돌리면 key로 가릅니다(같은 기기·이름·key는 방문을 넘어 한 작업으로 이어 봅니다).
|
|
229
|
+
*/
|
|
230
|
+
function operation(phase: "start" | "step" | "fail" | "ok", name: string, o: IssuecatOperationOptions = {}, step?: string) {
|
|
231
|
+
const st = step ?? o.step;
|
|
232
|
+
const msg = o.error instanceof Error ? o.error.message : o.message ?? (typeof o.error === "string" ? o.error : undefined);
|
|
233
|
+
track("$op", current, {
|
|
234
|
+
op: String(name).slice(0, 80), phase,
|
|
235
|
+
...(o.key != null ? { key: String(o.key).slice(0, 128) } : {}),
|
|
236
|
+
...(st ? { step: String(st).slice(0, 80) } : {}),
|
|
237
|
+
...(phase === "fail" && msg ? { message: String(msg).slice(0, 300) } : {}),
|
|
238
|
+
...(phase === "fail" && o.reason ? { reason: o.reason } : {}),
|
|
239
|
+
...(o.timeoutMs && o.timeoutMs > 0 ? { timeout_ms: Math.round(o.timeoutMs) } : {}),
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
const startOperation = (name: string, o?: IssuecatOperationOptions) => operation("start", name, o);
|
|
243
|
+
const operationStep = (name: string, step: string, o?: IssuecatOperationOptions) => operation("step", name, o, step);
|
|
244
|
+
const failOperation = (name: string, o?: IssuecatOperationOptions) => operation("fail", name, o);
|
|
245
|
+
const succeedOperation = (name: string, o?: IssuecatOperationOptions) => operation("ok", name, o);
|
|
246
|
+
|
|
247
|
+
return { track, screen, identify, reset, request, error, wrapFetch, ids, flush, startOperation, operationStep, failOperation, succeedOperation, trouble, get session() { return session; } };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// 상담창 SDK(issuecat.tsx)와 나누는 globalThis 칸: 지금 사람, 듣는 목록, configure({ test })의 시험 표시
|
|
251
|
+
type LinkedUser = { id: string; name?: string; email?: string } | null;
|
|
252
|
+
type Link = { __issuecatUser?: LinkedUser; __issuecatUserListeners?: Array<(u: LinkedUser) => void>; __issuecatTest?: boolean };
|
|
253
|
+
|
|
254
|
+
// ---- 앱 오류 저절로 잡기 (순정: @sentry/react-native reactNativeErrorHandlersIntegration, MIT — 맨 위 머리말)
|
|
255
|
+
|
|
256
|
+
type ErrorUtilsLike = { getGlobalHandler(): ((e: unknown, isFatal?: boolean) => void) | undefined; setGlobalHandler(h: (e: unknown, isFatal?: boolean) => void): void };
|
|
257
|
+
type HermesLike = { hasPromise?: () => boolean; enablePromiseRejectionTracker?: (o: { allRejections: boolean; onUnhandled: (id: number, reason: unknown) => void; onHandled: (id: number) => void }) => void };
|
|
258
|
+
type Catch = { ErrorUtils?: ErrorUtilsLike; HermesInternal?: HermesLike; __DEV__?: boolean; __issuecatCatch?: { record: (e: unknown, kind: string) => void; flush: () => Promise<unknown> } };
|
|
259
|
+
|
|
260
|
+
type ExceptionsManagerLike = { handleException?: (e: unknown, isFatal: boolean) => void };
|
|
261
|
+
|
|
262
|
+
/** 전역 처리기를 한 번만 걸고, 그 뒤에 만든 이용 기록이 있으면 받는 쪽만 그것으로 바꿉니다 */
|
|
263
|
+
function catchAppErrors(record: (e: unknown, kind: string) => void, flush: () => Promise<unknown>) {
|
|
264
|
+
const g = globalThis as Catch;
|
|
265
|
+
const first = !g.__issuecatCatch;
|
|
266
|
+
g.__issuecatCatch = { record, flush };
|
|
267
|
+
if (!first) return;
|
|
268
|
+
let closing = false; // 앱이 꺼지는 오류를 보내는 중
|
|
269
|
+
let forwarding = false; // 전역 처리기가 원래 처리기(→ ExceptionsManager)로 넘기는 중 — 같은 오류를 두 번 받지 않게
|
|
270
|
+
/** 오류 하나: 남기고, 앱이 꺼지는 오류면 보내 본 뒤(2초까지 — Sentry RN과 같은 값) 원래 처리로. 못 보낸 줄은 기기에 남아 다음에 켤 때 나갑니다 */
|
|
271
|
+
const handle = (err: unknown, isFatal: boolean, next: () => void) => {
|
|
272
|
+
const to = g.__issuecatCatch!;
|
|
273
|
+
if (closing) { try { to.record(err, isFatal ? "fatal" : "error"); } catch { /* 앱을 막지 않게 */ } return; } // 꺼지는 중에 온 오류는 남기기만 — 먼저 넘기면 첫 줄을 보내기 전에 앱이 닫힌다
|
|
274
|
+
try { to.record(err, isFatal ? "fatal" : "error"); } catch { /* 기록이 앱 처리를 막지 않게 */ }
|
|
275
|
+
if (!isFatal) return next();
|
|
276
|
+
closing = true;
|
|
277
|
+
void Promise.race([to.flush().catch(() => null), new Promise<void>((r) => setTimeout(() => r(), 2000))]).then(() => { closing = false; next(); });
|
|
278
|
+
};
|
|
279
|
+
const eu = g.ErrorUtils;
|
|
280
|
+
if (eu?.getGlobalHandler && eu.setGlobalHandler) {
|
|
281
|
+
const previous = eu.getGlobalHandler();
|
|
282
|
+
eu.setGlobalHandler((err, isFatal) => handle(err, !!isFatal, () => {
|
|
283
|
+
forwarding = true;
|
|
284
|
+
try { previous?.(err, isFatal); } finally { forwarding = false; }
|
|
285
|
+
}));
|
|
286
|
+
}
|
|
287
|
+
// React 19(RN 0.78+)는 오류 경계 밖의 그리기 오류를 ErrorUtils를 거치지 않고 ExceptionsManager.handleException으로 바로 보낸다 — 그것도 감싼다(Sentry RN과 같은 길)
|
|
288
|
+
try {
|
|
289
|
+
const mod = typeof require === "function" ? (require("react-native/Libraries/Core/ExceptionsManager") as ExceptionsManagerLike & { default?: ExceptionsManagerLike }) : null;
|
|
290
|
+
const em = mod ? mod.default ?? mod : null;
|
|
291
|
+
const original = em?.handleException;
|
|
292
|
+
if (em && original) {
|
|
293
|
+
em.handleException = (err: unknown, isFatal: boolean) => {
|
|
294
|
+
if (forwarding) return original.call(em, err, isFatal);
|
|
295
|
+
handle(err, isFatal, () => original.call(em, err, isFatal));
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
} catch { /* react-native가 없는 곳(시험)·모양이 다른 판 */ }
|
|
299
|
+
// 처리 안 된 Promise 거절 — Hermes(React Native 0.70+·Expo 기본 엔진). 개발 판에서는 RN이 띄우던 노란 경고를 그대로 찍습니다
|
|
300
|
+
const hermes = g.HermesInternal;
|
|
301
|
+
if (hermes?.enablePromiseRejectionTracker && hermes.hasPromise?.() !== false) {
|
|
302
|
+
hermes.enablePromiseRejectionTracker({
|
|
303
|
+
allRejections: true,
|
|
304
|
+
onUnhandled: (_id, reason) => {
|
|
305
|
+
try { g.__issuecatCatch!.record(reason, "unhandledrejection"); } catch { /* 위와 같음 */ }
|
|
306
|
+
if (g.__DEV__) console.warn("Possible unhandled promise rejection:", reason);
|
|
307
|
+
},
|
|
308
|
+
onHandled: () => {},
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** 스택 맨 위 자리(Hermes·JSC: 「at 함수 (address at 파일:줄:칸)」·「함수@파일:줄:칸」) → source·line·col */
|
|
314
|
+
function topFrame(stack: string): { source: string; line: number; col: number } | null {
|
|
315
|
+
for (const l of stack.split("\n").slice(0, 40)) {
|
|
316
|
+
const m = /(?:\(|@|\bat )(?:address at )?([^()@\s][^()@]*?):(\d+):(\d+)\)?\s*$/.exec(l.trim());
|
|
317
|
+
// 기기 안 파일 경로(앱 폴더 이름이 설치마다 다름)는 파일 이름만 — 개발 판의 주소(http://…/index.bundle?…)는 그대로
|
|
318
|
+
if (m) return { source: m[1].trim().replace(/^\/.*\//, ""), line: Number(m[2]), col: Number(m[3]) };
|
|
319
|
+
}
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function safeText(v: unknown): string {
|
|
324
|
+
if (v && typeof v === "object" && "message" in v) return String((v as { message: unknown }).message);
|
|
325
|
+
try { return JSON.stringify(v) ?? String(v); } catch { return String(v); }
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 오류 줄에 실을 OS·기기(앱 판은 release 칸). react-native는 위에서 가져오지 않는다 — 이 파일은 시험(node)에서도 읽힌다. Metro는 아래 require를 묶을 때 푼다 */
|
|
329
|
+
declare const require: ((m: string) => unknown) | undefined;
|
|
330
|
+
let envCache: Record<string, string> | null = null;
|
|
331
|
+
function appEnv(): Record<string, string> {
|
|
332
|
+
if (!envCache) {
|
|
333
|
+
envCache = {};
|
|
334
|
+
try {
|
|
335
|
+
const rn = typeof require === "function" ? (require("react-native") as { Platform?: { OS: string; Version: string | number; constants?: Record<string, unknown> } }) : null;
|
|
336
|
+
const pf = rn?.Platform;
|
|
337
|
+
if (pf) {
|
|
338
|
+
const c = pf.constants ?? {};
|
|
339
|
+
if (pf.OS === "ios") {
|
|
340
|
+
envCache.os = `iOS ${String(c.osVersion ?? pf.Version)}`;
|
|
341
|
+
envCache.device = c.interfaceIdiom === "pad" ? "iPad" : c.interfaceIdiom === "tv" ? "Apple TV" : "iPhone";
|
|
342
|
+
} else if (pf.OS === "android") {
|
|
343
|
+
envCache.os = `Android ${String(c.Release ?? pf.Version)}`;
|
|
344
|
+
if (typeof c.Model === "string" && c.Model) envCache.device = c.Model; // Sentry 모바일 SDK의 device.model과 같은 값(예: SM-S918N)
|
|
345
|
+
} else envCache.os = pf.OS;
|
|
346
|
+
}
|
|
347
|
+
} catch { /* react-native가 없는 곳(시험) */ }
|
|
348
|
+
}
|
|
349
|
+
return { ...envCache };
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ---- 옛 코드 호환 — 앞 판(옛 이름 Cuelen·문제콕) 앱 코드·파일과 섞여도 돌게 하는 이름을 여기 모읍니다.
|
|
353
|
+
|
|
354
|
+
/** 저장 자리 이름 — 앞 판이 쓰던 값 그대로입니다. 바꾸면 기기 번호·못 보낸 줄을 잃습니다. */
|
|
355
|
+
const OLD_STORAGE = { pending: "munjaekok.pending", device: "munjaekok.device" } as const;
|
|
356
|
+
|
|
357
|
+
/** 앞 판 상담창 파일(cuelen.tsx·앞 판 issuecat.tsx)이 쓰는 globalThis 칸 — 새 칸과 같은 목록을 가리키게 하고(어느 파일이 먼저 떠도), 값은 둘 중 있는 것을 읽습니다 */
|
|
358
|
+
type OldLink = { __cuelenUser?: LinkedUser; __cuelenUserListeners?: Array<(u: LinkedUser) => void>; __cuelenTest?: boolean };
|
|
359
|
+
function linkedListeners(): Array<(u: LinkedUser) => void> {
|
|
360
|
+
const g = globalThis as Link & OldLink;
|
|
361
|
+
const list = g.__issuecatUserListeners ?? g.__cuelenUserListeners ?? [];
|
|
362
|
+
g.__issuecatUserListeners = g.__cuelenUserListeners = list;
|
|
363
|
+
return list;
|
|
364
|
+
}
|
|
365
|
+
function linkedUserNow(): LinkedUser {
|
|
366
|
+
const g = globalThis as Link & OldLink;
|
|
367
|
+
return g.__issuecatUser ?? g.__cuelenUser ?? null;
|
|
368
|
+
}
|
|
369
|
+
function linkedTestOn(): boolean {
|
|
370
|
+
const g = globalThis as Link & OldLink;
|
|
371
|
+
return g.__issuecatTest === true || g.__cuelenTest === true;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// 옛 이름(Munjaekok) — 앞 판을 이 파일로 바꿔 넣어도 앱 코드가 그대로 돕니다
|
|
375
|
+
export const createMunjaekok = createIssuecatUsage;
|
|
376
|
+
export type MunjaekokOptions = IssuecatUsageOptions;
|
|
377
|
+
export type MunjaekokRequest = IssuecatUsageRequest;
|