-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
1880 lines (1741 loc) · 62.2 KB
/
Copy pathApp.tsx
File metadata and controls
1880 lines (1741 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Alert,
Image,
Linking,
NativeModules,
Platform,
Pressable,
StatusBar,
StyleSheet,
Text,
View,
} from 'react-native';
import { WebView, type WebViewMessageEvent } from 'react-native-webview';
import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context';
import {
addNativeSttListener,
isNativeSttAvailable,
setNativeSttAec,
startNativeStt,
stopNativeStt,
} from './src/nativeStt';
import {
addNativeTtsListener,
playNativeTts,
stopNativeTts,
} from './src/nativeTts';
import {
startNativeBrowserAuthSession,
type NativeAuthProvider,
} from './src/nativeAuth';
import { validateRnApiNamespace } from './src/apiNamespace';
type RuntimeEnvMap = Record<string, string | undefined>;
type NativeRuntimeConfig = {
webAppBaseUrl?: string;
defaultWsUrl?: string;
apiNamespace?: string;
clientVersion?: string;
clientBuild?: string;
deviceLocaleTag?: string;
devicePreferredLanguages?: string[];
};
type VersionPolicyAction = 'force_update' | 'recommend_update' | 'none';
type VersionGateState =
| { status: 'checking' }
| { status: 'ready' }
| {
status: 'force_update';
updateUrl: string;
title: string;
message: string;
updateButtonLabel: string;
clientVersion: string;
latestVersion: string;
};
type VersionPolicyResponse = {
action: VersionPolicyAction;
platform?: string;
policyPlatform?: string;
locale?: string;
updateUrl?: string;
title?: string;
message?: string;
latestVersion?: string;
clientVersion?: string;
updateButtonLabel?: string;
laterButtonLabel?: string;
};
type IOSSettingsManager = {
settings?: {
AppleLocale?: string;
AppleLanguages?: string[];
};
};
type AndroidI18nManager = {
localeIdentifier?: string;
};
function readRuntimeEnvValue(keys: string[]): string {
const env = (globalThis as { process?: { env?: RuntimeEnvMap } }).process?.env;
if (!env) return '';
for (const key of keys) {
const value = env[key];
if (typeof value === 'string' && value.trim().length > 0) {
return value.trim();
}
}
return '';
}
function readNativeRuntimeConfig(): NativeRuntimeConfig {
const runtimeConfigModule = (NativeModules as {
NativeRuntimeConfigModule?: {
runtimeConfig?: NativeRuntimeConfig;
};
NativeSTTModule?: {
runtimeConfig?: NativeRuntimeConfig;
};
}).NativeRuntimeConfigModule;
const runtimeConfig = runtimeConfigModule?.runtimeConfig ?? (NativeModules.NativeSTTModule as
| {
runtimeConfig?: NativeRuntimeConfig;
}
| undefined)?.runtimeConfig;
if (!runtimeConfig || typeof runtimeConfig !== 'object') {
return {};
}
return runtimeConfig;
}
function normalizeConfiguredUrl(
raw: string,
allowedProtocols: string[],
options?: { trimTrailingSlash?: boolean },
): string {
if (!raw) return '';
try {
const parsed = new URL(raw);
if (!allowedProtocols.includes(parsed.protocol)) return '';
if (options?.trimTrailingSlash) {
return raw.replace(/\/+$/, '');
}
return raw;
} catch {
return '';
}
}
function resolveConfiguredUrl(
keys: string[],
allowedProtocols: string[],
options?: { trimTrailingSlash?: boolean },
): string {
return normalizeConfiguredUrl(readRuntimeEnvValue(keys), allowedProtocols, options);
}
function isLoopbackHost(host: string): boolean {
const normalized = host.trim().toLowerCase();
return normalized === '127.0.0.1' || normalized === 'localhost' || normalized === '::1';
}
function isLoopbackUrl(raw: string): boolean {
if (!raw) return false;
try {
return isLoopbackHost(new URL(raw).hostname);
} catch {
return /(127\.0\.0\.1|localhost|::1)/i.test(raw);
}
}
function formatWebViewLoadError(description: string, currentWebUrl: string): string {
const normalizedDescription = description.trim() || 'webview_load_failed';
if (!currentWebUrl || !isLoopbackUrl(currentWebUrl)) {
return normalizedDescription;
}
return `${normalizedDescription} (현재 앱 URL이 ${currentWebUrl} 입니다. 실기기에서는 127.0.0.1/localhost에 접속할 수 없습니다. scripts/devbox profile --profile device 후 --device-app-env prod 또는 dev로 설치해 주세요.)`;
}
const RN_RUNTIME_OS = Platform.OS;
const NATIVE_RUNTIME_CONFIG = readNativeRuntimeConfig();
const WEB_APP_BASE_URL = resolveConfiguredUrl(
['NEXT_PUBLIC_SITE_URL', 'RN_WEB_APP_BASE_URL'],
['http:', 'https:'],
{ trimTrailingSlash: true },
) || normalizeConfiguredUrl(
NATIVE_RUNTIME_CONFIG.webAppBaseUrl || '',
['http:', 'https:'],
{ trimTrailingSlash: true },
) || 'https://mingle-app-xi.vercel.app';
const DEFAULT_WS_URL = resolveConfiguredUrl(
['NEXT_PUBLIC_WS_URL', 'RN_DEFAULT_WS_URL'],
['ws:', 'wss:'],
) || normalizeConfiguredUrl(
NATIVE_RUNTIME_CONFIG.defaultWsUrl || '',
['ws:', 'wss:'],
) || 'wss://mingle.up.railway.app';
const DEFAULT_SONIOX_MANUAL_FINALIZE_SILENCE_MS = 1000;
const MIN_SONIOX_MANUAL_FINALIZE_SILENCE_MS = 500;
const MAX_SONIOX_MANUAL_FINALIZE_SILENCE_MS = 3000;
function normalizeSonioxManualFinalizeSilenceMs(value: unknown): number {
const parsed = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(parsed)) {
return DEFAULT_SONIOX_MANUAL_FINALIZE_SILENCE_MS;
}
return Math.max(
MIN_SONIOX_MANUAL_FINALIZE_SILENCE_MS,
Math.min(MAX_SONIOX_MANUAL_FINALIZE_SILENCE_MS, Math.floor(parsed)),
);
}
const STARTUP_SPLASH_BACKGROUND = '#F3C35A';
const STARTUP_SPLASH_LOGO = require('./ios/mingle/Images.xcassets/LaunchLogo.imageset/launch-logo.png');
const {
expectedApiNamespace: EXPECTED_API_NAMESPACE,
configuredApiNamespace: CONFIGURED_API_NAMESPACE,
validatedApiNamespace: VALIDATED_API_NAMESPACE,
} = validateRnApiNamespace({
runtimeOs: RN_RUNTIME_OS,
configuredApiNamespace: readRuntimeEnvValue(['NEXT_PUBLIC_API_NAMESPACE', 'RN_API_NAMESPACE'])
|| (NATIVE_RUNTIME_CONFIG.apiNamespace || '').trim(),
});
const missingRuntimeConfig: string[] = [];
if (!WEB_APP_BASE_URL) {
missingRuntimeConfig.push('NEXT_PUBLIC_SITE_URL');
}
if (!DEFAULT_WS_URL) {
missingRuntimeConfig.push('NEXT_PUBLIC_WS_URL');
}
if (EXPECTED_API_NAMESPACE && !CONFIGURED_API_NAMESPACE) {
missingRuntimeConfig.push(`NEXT_PUBLIC_API_NAMESPACE (expected: ${EXPECTED_API_NAMESPACE})`);
} else if (EXPECTED_API_NAMESPACE && !VALIDATED_API_NAMESPACE) {
missingRuntimeConfig.push(`NEXT_PUBLIC_API_NAMESPACE must match current platform namespace: ${EXPECTED_API_NAMESPACE}`);
}
const REQUIRED_CONFIG_ERROR = missingRuntimeConfig.length > 0
? `Missing or invalid env: ${missingRuntimeConfig.join(', ')}`
: null;
const NATIVE_STT_EVENT = 'mingle:native-stt';
const NATIVE_TTS_EVENT = 'mingle:native-tts';
const NATIVE_UI_EVENT = 'mingle:native-ui';
const NATIVE_AUTH_EVENT = 'mingle:native-auth';
const IOS_SAFE_BROWSER_USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1';
const WEB_SUPPORTED_LOCALES = new Set([
'ko',
'en',
'ja',
'zh-CN',
'zh-TW',
'fr',
'de',
'es',
'pt',
'it',
'ru',
'ar',
'hi',
'th',
'vi',
]);
const WEB_LOCALE_ALIASES: Record<string, string> = {
ko: 'ko',
en: 'en',
ja: 'ja',
fr: 'fr',
de: 'de',
es: 'es',
pt: 'pt',
it: 'it',
ru: 'ru',
ar: 'ar',
hi: 'hi',
th: 'th',
vi: 'vi',
zh: 'zh-CN',
'zh-cn': 'zh-CN',
'zh-hans': 'zh-CN',
'zh-sg': 'zh-CN',
'zh-tw': 'zh-TW',
'zh-hant': 'zh-TW',
'zh-hk': 'zh-TW',
'zh-mo': 'zh-TW',
};
const WEB_SUPPORTED_LOCALE_SEGMENTS = new Set(Array.from(WEB_SUPPORTED_LOCALES).map(locale => locale.toLowerCase()));
type SafeAreaPalette = {
topColor: string;
topOverlayColor: string;
bottomColor: string;
webViewColor: string;
statusBarStyle: 'dark-content' | 'light-content';
topEdgeMode: 'fill' | 'overlay' | 'transparent';
bottomEdgeMode: 'fill' | 'transparent';
};
const DEFAULT_SAFE_AREA_PALETTE: SafeAreaPalette = {
topColor: '#ffffff',
topOverlayColor: 'transparent',
bottomColor: '#ffffff',
webViewColor: '#ffffff',
statusBarStyle: 'dark-content',
topEdgeMode: 'overlay',
bottomEdgeMode: 'fill',
};
const AUTH_LOGIN_SAFE_AREA_PALETTE: SafeAreaPalette = {
topColor: '#fbbc32',
topOverlayColor: 'transparent',
bottomColor: '#1c1c1e',
webViewColor: '#1c1c1e',
statusBarStyle: 'light-content',
topEdgeMode: 'transparent',
bottomEdgeMode: 'transparent',
};
type VersionPolicyLocale =
| 'ko'
| 'en'
| 'ja'
| 'zh-CN'
| 'zh-TW'
| 'fr'
| 'de'
| 'es'
| 'pt'
| 'it'
| 'ru'
| 'ar'
| 'hi'
| 'th'
| 'vi';
const VERSION_POLICY_SUPPORTED_LOCALES = new Set<VersionPolicyLocale>([
'ko',
'en',
'ja',
'zh-CN',
'zh-TW',
'fr',
'de',
'es',
'pt',
'it',
'ru',
'ar',
'hi',
'th',
'vi',
]);
const IOS_VERSION_POLICY_TIMEOUT_MS = 8000;
const VERSION_POLICY_LOCALE_ALIASES: Record<string, VersionPolicyLocale> = {
ko: 'ko',
en: 'en',
ja: 'ja',
fr: 'fr',
de: 'de',
es: 'es',
pt: 'pt',
it: 'it',
ru: 'ru',
ar: 'ar',
hi: 'hi',
th: 'th',
vi: 'vi',
zh: 'zh-CN',
'zh-cn': 'zh-CN',
'zh-hans': 'zh-CN',
'zh-sg': 'zh-CN',
'zh-tw': 'zh-TW',
'zh-hant': 'zh-TW',
'zh-hk': 'zh-TW',
'zh-mo': 'zh-TW',
};
const VERSION_POLICY_FALLBACK_COPY: Record<VersionPolicyLocale, {
checkingTitle: string;
checkingMessage: string;
forceTitle: string;
forceMessage: string;
recommendTitle: string;
recommendMessage: string;
updateLabel: string;
laterLabel: string;
updateNowA11y: string;
webViewLoadFailedTitle: string;
unknownVersionLabel: string;
}> = {
ko: {
checkingTitle: '버전 확인 중',
checkingMessage: '최신 업데이트 정책을 확인하고 있습니다.',
forceTitle: '업데이트 필요',
forceMessage: '현재 버전은 더 이상 지원되지 않습니다. 최신 버전으로 업데이트해 주세요.',
recommendTitle: '업데이트 권장',
recommendMessage: '새 버전 업데이트를 권장합니다.',
updateLabel: '업데이트',
laterLabel: '나중에',
updateNowA11y: '지금 업데이트',
webViewLoadFailedTitle: 'WebView 로드 실패',
unknownVersionLabel: '알 수 없음',
},
en: {
checkingTitle: 'Checking version',
checkingMessage: 'Checking the latest update policy.',
forceTitle: 'Update Required',
forceMessage: 'This version is no longer supported. Please update to the latest version.',
recommendTitle: 'Update Recommended',
recommendMessage: 'A new version is available. We recommend updating for a better experience.',
updateLabel: 'Update',
laterLabel: 'Later',
updateNowA11y: 'Update now',
webViewLoadFailedTitle: 'WebView Load Failed',
unknownVersionLabel: 'unknown',
},
ja: {
checkingTitle: 'バージョン確認中',
checkingMessage: '最新のアップデートポリシーを確認しています。',
forceTitle: 'アップデートが必要です',
forceMessage: 'このバージョンはサポートされていません。最新バージョンにアップデートしてください。',
recommendTitle: 'アップデート推奨',
recommendMessage: '新しいバージョンが利用可能です。アップデートをお勧めします。',
updateLabel: 'アップデート',
laterLabel: 'あとで',
updateNowA11y: '今すぐアップデート',
webViewLoadFailedTitle: 'WebView の読み込みに失敗しました',
unknownVersionLabel: '不明',
},
'zh-CN': {
checkingTitle: '正在检查版本',
checkingMessage: '正在检查最新更新策略。',
forceTitle: '更新必需',
forceMessage: '当前版本已不再受支持。请更新到最新版本。',
recommendTitle: '建议更新',
recommendMessage: '新版本已发布,建议更新以获得更稳定的体验。',
updateLabel: '更新',
laterLabel: '稍后',
updateNowA11y: '立即更新',
webViewLoadFailedTitle: 'WebView 加载失败',
unknownVersionLabel: '未知',
},
'zh-TW': {
checkingTitle: '正在檢查版本',
checkingMessage: '正在檢查最新更新政策。',
forceTitle: '必須更新',
forceMessage: '目前版本已不再支援。請更新至最新版本。',
recommendTitle: '建議更新',
recommendMessage: '新版本已推出,建議更新以獲得更穩定的體驗。',
updateLabel: '更新',
laterLabel: '稍後',
updateNowA11y: '立即更新',
webViewLoadFailedTitle: 'WebView 載入失敗',
unknownVersionLabel: '未知',
},
fr: {
checkingTitle: 'Vérification de la version',
checkingMessage: 'Vérification de la politique de mise à jour la plus récente.',
forceTitle: 'Mise à jour requise',
forceMessage: 'Cette version n\'est plus prise en charge. Veuillez mettre à jour vers la dernière version.',
recommendTitle: 'Mise à jour recommandée',
recommendMessage: 'Une nouvelle version est disponible. Nous recommandons la mise à jour.',
updateLabel: 'Mettre à jour',
laterLabel: 'Plus tard',
updateNowA11y: 'Mettre à jour maintenant',
webViewLoadFailedTitle: 'Échec du chargement de WebView',
unknownVersionLabel: 'inconnu',
},
de: {
checkingTitle: 'Version wird überprüft',
checkingMessage: 'Die neuesten Update-Richtlinien werden geprüft.',
forceTitle: 'Update erforderlich',
forceMessage: 'Diese Version wird nicht mehr unterstützt. Bitte aktualisieren Sie auf die neueste Version.',
recommendTitle: 'Update empfohlen',
recommendMessage: 'Eine neue Version ist verfügbar. Wir empfehlen ein Update.',
updateLabel: 'Aktualisieren',
laterLabel: 'Später',
updateNowA11y: 'Jetzt aktualisieren',
webViewLoadFailedTitle: 'WebView-Laden fehlgeschlagen',
unknownVersionLabel: 'unbekannt',
},
es: {
checkingTitle: 'Comprobando versión',
checkingMessage: 'Estamos comprobando la política de actualización más reciente.',
forceTitle: 'Actualización obligatoria',
forceMessage: 'Esta versión ya no es compatible. Actualiza a la última versión.',
recommendTitle: 'Actualización recomendada',
recommendMessage: 'Hay una nueva versión disponible. Recomendamos actualizar.',
updateLabel: 'Actualizar',
laterLabel: 'Más tarde',
updateNowA11y: 'Actualizar ahora',
webViewLoadFailedTitle: 'Error al cargar WebView',
unknownVersionLabel: 'desconocida',
},
pt: {
checkingTitle: 'Verificando versão',
checkingMessage: 'Estamos verificando a política de atualização mais recente.',
forceTitle: 'Atualização obrigatória',
forceMessage: 'Esta versão não é mais compatível. Atualize para a versão mais recente.',
recommendTitle: 'Atualização recomendada',
recommendMessage: 'Há uma nova versão disponível. Recomendamos atualizar.',
updateLabel: 'Atualizar',
laterLabel: 'Mais tarde',
updateNowA11y: 'Atualizar agora',
webViewLoadFailedTitle: 'Falha ao carregar o WebView',
unknownVersionLabel: 'desconhecida',
},
it: {
checkingTitle: 'Verifica versione in corso',
checkingMessage: 'Stiamo verificando la policy di aggiornamento più recente.',
forceTitle: 'Aggiornamento obbligatorio',
forceMessage: 'Questa versione non è più supportata. Aggiorna all\'ultima versione.',
recommendTitle: 'Aggiornamento consigliato',
recommendMessage: 'È disponibile una nuova versione. Ti consigliamo di aggiornare.',
updateLabel: 'Aggiorna',
laterLabel: 'Più tardi',
updateNowA11y: 'Aggiorna ora',
webViewLoadFailedTitle: 'Caricamento WebView non riuscito',
unknownVersionLabel: 'sconosciuta',
},
ru: {
checkingTitle: 'Проверка версии',
checkingMessage: 'Проверяем актуальную политику обновлений.',
forceTitle: 'Требуется обновление',
forceMessage: 'Эта версия больше не поддерживается. Обновите приложение до последней версии.',
recommendTitle: 'Рекомендуется обновление',
recommendMessage: 'Доступна новая версия. Рекомендуем обновить приложение.',
updateLabel: 'Обновить',
laterLabel: 'Позже',
updateNowA11y: 'Обновить сейчас',
webViewLoadFailedTitle: 'Не удалось загрузить WebView',
unknownVersionLabel: 'неизвестно',
},
ar: {
checkingTitle: 'جارٍ التحقق من الإصدار',
checkingMessage: 'جارٍ التحقق من سياسة التحديث الأحدث.',
forceTitle: 'التحديث مطلوب',
forceMessage: 'هذا الإصدار لم يعد مدعومًا. يرجى التحديث إلى أحدث إصدار.',
recommendTitle: 'يوصى بالتحديث',
recommendMessage: 'يتوفر إصدار جديد. نوصي بالتحديث.',
updateLabel: 'تحديث',
laterLabel: 'لاحقًا',
updateNowA11y: 'حدّث الآن',
webViewLoadFailedTitle: 'فشل تحميل WebView',
unknownVersionLabel: 'غير معروف',
},
hi: {
checkingTitle: 'संस्करण जाँचा जा रहा है',
checkingMessage: 'नवीनतम अपडेट नीति की जाँच की जा रही है।',
forceTitle: 'अपडेट आवश्यक',
forceMessage: 'यह संस्करण अब समर्थित नहीं है। कृपया नवीनतम संस्करण में अपडेट करें।',
recommendTitle: 'अपडेट की अनुशंसा',
recommendMessage: 'नया संस्करण उपलब्ध है। अपडेट करने की सलाह दी जाती है।',
updateLabel: 'अपडेट करें',
laterLabel: 'बाद में',
updateNowA11y: 'अभी अपडेट करें',
webViewLoadFailedTitle: 'WebView लोड विफल',
unknownVersionLabel: 'अज्ञात',
},
th: {
checkingTitle: 'กำลังตรวจสอบเวอร์ชัน',
checkingMessage: 'กำลังตรวจสอบนโยบายอัปเดตล่าสุด',
forceTitle: 'จำเป็นต้องอัปเดต',
forceMessage: 'เวอร์ชันนี้ไม่รองรับแล้ว กรุณาอัปเดตเป็นเวอร์ชันล่าสุด',
recommendTitle: 'แนะนำให้อัปเดต',
recommendMessage: 'มีเวอร์ชันใหม่พร้อมใช้งาน แนะนำให้อัปเดต',
updateLabel: 'อัปเดต',
laterLabel: 'ภายหลัง',
updateNowA11y: 'อัปเดตตอนนี้',
webViewLoadFailedTitle: 'โหลด WebView ไม่สำเร็จ',
unknownVersionLabel: 'ไม่ทราบ',
},
vi: {
checkingTitle: 'Đang kiểm tra phiên bản',
checkingMessage: 'Đang kiểm tra chính sách cập nhật mới nhất.',
forceTitle: 'Cần cập nhật',
forceMessage: 'Phiên bản này không còn được hỗ trợ. Vui lòng cập nhật lên phiên bản mới nhất.',
recommendTitle: 'Khuyến nghị cập nhật',
recommendMessage: 'Đã có phiên bản mới. Chúng tôi khuyên bạn nên cập nhật.',
updateLabel: 'Cập nhật',
laterLabel: 'Để sau',
updateNowA11y: 'Cập nhật ngay',
webViewLoadFailedTitle: 'Tải WebView thất bại',
unknownVersionLabel: 'không rõ',
},
};
type NativeSttStartPayload = {
wsUrl?: string;
sttModel?: string;
languages?: string[];
aecEnabled?: boolean;
sonioxLanguageHints?: string[];
sonioxManualFinalizeSilenceMs?: number;
};
type NativeSttStopPayload = {
pendingText?: string;
pendingLanguage?: string;
};
type NativeSttCommand =
| {
type: 'native_stt_start';
payload?: NativeSttStartPayload;
}
| {
type: 'native_stt_stop';
payload?: NativeSttStopPayload;
};
type NativeTtsCommand =
| {
type: 'native_tts_play';
payload: {
utteranceId: string;
playbackId?: string;
audioBase64: string;
contentType?: string;
};
}
| {
type: 'native_tts_stop';
payload?: {
reason?: string;
};
};
type NativeSttAecCommand = {
type: 'native_stt_set_aec';
payload: { enabled: boolean };
};
type NativeAuthStartCommand = {
type: 'native_auth_start';
payload: {
provider: NativeAuthProvider;
callbackUrl?: string;
startUrl: string;
};
};
type NativeAuthAckCommand = {
type: 'native_auth_ack';
payload?: {
provider?: NativeAuthProvider;
outcome?: 'success' | 'error';
bridgeToken?: string;
};
};
type NativeAuthResetCommand = {
type: 'native_auth_reset';
};
type WebViewCommand =
| NativeSttCommand
| NativeTtsCommand
| NativeSttAecCommand
| NativeAuthStartCommand
| NativeAuthAckCommand
| NativeAuthResetCommand;
type NativeSttEvent =
| { type: 'status'; status: string }
| { type: 'message'; raw: string }
| { type: 'error'; message: string }
| { type: 'close'; reason: string };
type NativeUiEvent = {
type: 'scroll_to_top';
source: string;
};
type NativeAuthEvent =
| {
type: 'status';
provider: NativeAuthProvider;
status: 'opening';
}
| {
type: 'success';
provider: NativeAuthProvider;
callbackUrl: string;
bridgeToken: string;
}
| {
type: 'error';
provider: NativeAuthProvider;
message: string;
};
type RecommendUpdatePrompt = {
title: string;
message: string;
updateUrl: string;
updateLabel: string;
laterLabel: string;
};
function normalizeClientVersion(raw: string): string {
return raw.trim().replace(/^v/i, '');
}
function buildVersionPolicyUrl(baseUrl: string, apiNamespace: string): string {
const normalizedNamespace = apiNamespace.trim().replace(/^\/+/, '').replace(/\/+$/, '');
if (!normalizedNamespace) {
return `${baseUrl}/api/client/version-policy`;
}
return `${baseUrl}/api/${normalizedNamespace}/client/version-policy`;
}
function resolveVersionPolicyClientPlatform(runtimeOs: string): 'ios' | 'android' {
if (runtimeOs === 'android') return 'android';
return 'ios';
}
function resolveIosTopTapOverlayHeight(rawStatusBarHeight: unknown): number {
const numeric = typeof rawStatusBarHeight === 'number'
? rawStatusBarHeight
: Number(rawStatusBarHeight);
if (!Number.isFinite(numeric) || numeric <= 0) return 24;
// iOS 상단 탭은 상태바/노치 영역 기준으로만 처리합니다.
return Math.max(20, Math.min(64, Math.ceil(numeric)));
}
function resolveDeviceLocaleTag(): string {
if (Platform.OS === 'ios') {
const runtimeLocaleTag = NATIVE_RUNTIME_CONFIG.deviceLocaleTag;
if (typeof runtimeLocaleTag === 'string' && runtimeLocaleTag.trim()) {
return runtimeLocaleTag.trim();
}
const runtimePreferredLanguages = NATIVE_RUNTIME_CONFIG.devicePreferredLanguages;
if (Array.isArray(runtimePreferredLanguages)) {
for (const language of runtimePreferredLanguages) {
if (typeof language === 'string' && language.trim()) {
return language.trim();
}
}
}
const settingsManager = (NativeModules as {
SettingsManager?: IOSSettingsManager;
}).SettingsManager;
const appleLanguages = settingsManager?.settings?.AppleLanguages;
if (Array.isArray(appleLanguages)) {
for (const language of appleLanguages) {
if (typeof language === 'string' && language.trim()) {
return language.trim();
}
}
}
// AppleLocale can reflect regional format settings rather than UI language.
// Prefer AppleLanguages first so locale follows the device language priority.
const appleLocale = settingsManager?.settings?.AppleLocale;
if (typeof appleLocale === 'string' && appleLocale.trim()) {
return appleLocale.trim();
}
}
if (Platform.OS === 'android') {
const localeIdentifier = (NativeModules.I18nManager as AndroidI18nManager | undefined)?.localeIdentifier;
if (typeof localeIdentifier === 'string' && localeIdentifier.trim()) {
return localeIdentifier.trim();
}
}
try {
return Intl.DateTimeFormat().resolvedOptions().locale || 'ko';
} catch {
return 'ko';
}
}
function resolveWebLocaleSegment(rawLocaleTag: string): string {
const normalized = rawLocaleTag.trim().replace(/_/g, '-').toLowerCase();
if (!normalized) return 'ko';
const directMatch = WEB_LOCALE_ALIASES[normalized];
if (directMatch && WEB_SUPPORTED_LOCALES.has(directMatch)) {
return directMatch;
}
if (normalized.startsWith('zh-')) {
if (normalized.includes('-tw') || normalized.includes('-hant') || normalized.includes('-hk') || normalized.includes('-mo')) {
return 'zh-TW';
}
return 'zh-CN';
}
const base = normalized.split('-')[0] || '';
const baseMatch = WEB_LOCALE_ALIASES[base];
if (baseMatch && WEB_SUPPORTED_LOCALES.has(baseMatch)) {
return baseMatch;
}
return 'ko';
}
function resolveVersionPolicyLocale(rawLocaleTag: string): VersionPolicyLocale {
const normalized = rawLocaleTag.trim().replace(/_/g, '-').toLowerCase();
if (!normalized) return 'en';
const directMatch = VERSION_POLICY_LOCALE_ALIASES[normalized];
if (directMatch && VERSION_POLICY_SUPPORTED_LOCALES.has(directMatch)) {
return directMatch;
}
if (normalized.startsWith('zh-')) {
if (normalized.includes('-tw') || normalized.includes('-hant') || normalized.includes('-hk') || normalized.includes('-mo')) {
return 'zh-TW';
}
return 'zh-CN';
}
const base = normalized.split('-')[0] || '';
const baseMatch = VERSION_POLICY_LOCALE_ALIASES[base];
if (baseMatch && VERSION_POLICY_SUPPORTED_LOCALES.has(baseMatch)) {
return baseMatch;
}
return 'en';
}
function getVersionPolicyFallbackCopy(locale: VersionPolicyLocale) {
return VERSION_POLICY_FALLBACK_COPY[locale];
}
function isAuthLikePathname(pathname: string): boolean {
const segments = pathname
.split('/')
.map(segment => segment.trim())
.filter(Boolean);
if (segments.length === 0) return false;
const first = segments[0].toLowerCase();
if (segments[0] === 'auth') {
return true;
}
if (segments.length >= 2 && WEB_SUPPORTED_LOCALE_SEGMENTS.has(first) && segments[1] === 'auth') {
return true;
}
return false;
}
function isAllowedNativeAuthStartPath(pathname: string): boolean {
const normalized = pathname.trim();
if (!normalized.startsWith('/')) return false;
if (normalized.startsWith('/api/native-auth/start')) return true;
const segments = normalized
.split('/')
.map(segment => segment.trim())
.filter(Boolean);
if (segments.length !== 3) return false;
const locale = segments[0]?.toLowerCase() || '';
if (!WEB_SUPPORTED_LOCALE_SEGMENTS.has(locale)) return false;
return segments[1] === 'auth' && segments[2] === 'native';
}
function resolveSafeAreaPaletteForUrl(rawUrl: string): SafeAreaPalette {
const candidate = rawUrl.trim();
if (!candidate) return DEFAULT_SAFE_AREA_PALETTE;
try {
const parsed = new URL(candidate);
if (isAuthLikePathname(parsed.pathname)) {
return AUTH_LOGIN_SAFE_AREA_PALETTE;
}
} catch {
return DEFAULT_SAFE_AREA_PALETTE;
}
return DEFAULT_SAFE_AREA_PALETTE;
}
function resolveTrustedOrigin(rawUrl: string): string {
const candidate = rawUrl.trim();
if (!candidate) return '';
try {
const parsed = new URL(candidate);
if (!parsed.host) return '';
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return '';
return parsed.origin;
} catch {
return '';
}
}
function AppInner(): React.JSX.Element {
const webViewRef = useRef<WebView>(null);
const isPageReadyRef = useRef(false);
const safeAreaInsets = useSafeAreaInsets();
const nativeAvailable = useMemo(() => isNativeSttAvailable(), []);
const [loadError, setLoadError] = useState<string | null>(REQUIRED_CONFIG_ERROR);
const [versionGate, setVersionGate] = useState<VersionGateState>(() => (
(Platform.OS === 'ios' || Platform.OS === 'android') && WEB_APP_BASE_URL && !REQUIRED_CONFIG_ERROR
? { status: 'checking' }
: { status: 'ready' }
));
const recommendPromptShownRef = useRef(false);
const pendingRecommendPromptRef = useRef<RecommendUpdatePrompt | null>(null);
const nativeStatusRef = useRef('idle');
const currentTtsPlaybackRef = useRef<{ utteranceId: string; playbackId: string } | null>(null);
const nativeAuthInFlightRef = useRef<NativeAuthProvider | null>(null);
const pendingAuthEventRef = useRef<NativeAuthEvent | null>(null);
const authDispatchRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const authDispatchRetryCountRef = useRef(0);
const [iosTopTapOverlayHeight, setIosTopTapOverlayHeight] = useState(() => {
if (Platform.OS !== 'ios') return 36;
const manager = (NativeModules as {
StatusBarManager?: { HEIGHT?: number };
}).StatusBarManager;
return resolveIosTopTapOverlayHeight(manager?.HEIGHT);
});
const deviceLocaleTag = useMemo(() => resolveDeviceLocaleTag(), []);
const webLocale = useMemo(() => resolveWebLocaleSegment(deviceLocaleTag), [deviceLocaleTag]);
const versionPolicyLocale = useMemo(() => resolveVersionPolicyLocale(deviceLocaleTag), [deviceLocaleTag]);
const versionPolicyFallback = useMemo(
() => getVersionPolicyFallbackCopy(versionPolicyLocale),
[versionPolicyLocale],
);
const webUrl = useMemo(() => {
if (!WEB_APP_BASE_URL || REQUIRED_CONFIG_ERROR) return '';
const apiNamespaceQuery = VALIDATED_API_NAMESPACE
? `&apiNamespace=${encodeURIComponent(VALIDATED_API_NAMESPACE)}`
: '';
const debugParams = __DEV__ ? '&sttDebug=1&ttsDebug=1' : '';
const nativeSttQuery = nativeAvailable ? '1' : '0';
return `${WEB_APP_BASE_URL}/${webLocale}?nativeStt=${nativeSttQuery}&nativeUi=1&nativeAuth=1${apiNamespaceQuery}${debugParams}`;
}, [nativeAvailable, webLocale]);
const trustedNativeAuthOrigin = useMemo(() => resolveTrustedOrigin(WEB_APP_BASE_URL), []);
const [safeAreaPalette, setSafeAreaPalette] = useState<SafeAreaPalette>(() => resolveSafeAreaPaletteForUrl(webUrl));
const initialLoadSettledRef = useRef(false);
const [startupSplashVisible, setStartupSplashVisible] = useState(() => Boolean(webUrl));
const updateSafeAreaPalette = useCallback((candidateUrl?: string) => {
const nextPalette = resolveSafeAreaPaletteForUrl(candidateUrl || webUrl);
setSafeAreaPalette((current) => {
if (
current.topColor === nextPalette.topColor
&& current.topOverlayColor === nextPalette.topOverlayColor
&& current.bottomColor === nextPalette.bottomColor
&& current.webViewColor === nextPalette.webViewColor
&& current.statusBarStyle === nextPalette.statusBarStyle
&& current.topEdgeMode === nextPalette.topEdgeMode
&& current.bottomEdgeMode === nextPalette.bottomEdgeMode
) {
return current;
}
return nextPalette;
});
}, [webUrl]);
const iosTopSafeAreaHeight = Platform.OS === 'ios'
? (safeAreaInsets.top > 0 ? safeAreaInsets.top : iosTopTapOverlayHeight)
: 0;
const shouldRenderTopSafeAreaFill = Platform.OS === 'ios' && safeAreaPalette.topEdgeMode === 'fill';
const shouldRenderTopSafeAreaOverlay = Platform.OS === 'ios' && safeAreaPalette.topEdgeMode === 'overlay';
const shouldRenderBottomSafeAreaFill = Platform.OS === 'ios' && safeAreaPalette.bottomEdgeMode === 'fill';
useEffect(() => {
updateSafeAreaPalette(webUrl);
}, [updateSafeAreaPalette, webUrl]);
const presentRecommendPrompt = useCallback((prompt: RecommendUpdatePrompt) => {
if (prompt.updateUrl) {
Alert.alert(
prompt.title,
prompt.message,
[
{ text: prompt.laterLabel, style: 'cancel' },
{
text: prompt.updateLabel,
onPress: () => {
void Linking.openURL(prompt.updateUrl);
},
},
],
);
return;
}
Alert.alert(prompt.title, prompt.message);
}, []);
const flushPendingRecommendPrompt = useCallback(() => {
if (!isPageReadyRef.current) return;
const pendingPrompt = pendingRecommendPromptRef.current;
if (!pendingPrompt) return;
pendingRecommendPromptRef.current = null;
presentRecommendPrompt(pendingPrompt);
}, [presentRecommendPrompt]);
useEffect(() => {
if ((Platform.OS !== 'ios' && Platform.OS !== 'android') || !WEB_APP_BASE_URL || REQUIRED_CONFIG_ERROR) {
return;
}
let active = true;
let settled = false;
const abortController = typeof AbortController !== 'undefined' ? new AbortController() : null;
const nativeRuntimeConfig = readNativeRuntimeConfig();
const envClientVersion = readRuntimeEnvValue(['RN_CLIENT_VERSION']);
const envClientBuild = readRuntimeEnvValue(['RN_CLIENT_BUILD']);
const clientVersion = normalizeClientVersion(
envClientVersion
|| nativeRuntimeConfig?.clientVersion
|| '',
);
const clientBuild = envClientBuild || nativeRuntimeConfig?.clientBuild || '';
const fallbackToReady = (reason: string, details?: string) => {
if (!active || settled) return;
settled = true;
if (__DEV__) {
console.log(`[VersionPolicy] bypass (${reason})${details ? `: ${details}` : ''}`);