@the-seeker/changes-react-native 0.0.0-stage → 0.1.1
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/README.md +136 -2
- package/dist/core/cache.d.ts +14 -0
- package/dist/core/cache.js +34 -0
- package/dist/core/client.d.ts +163 -0
- package/dist/core/client.js +98 -0
- package/dist/core/decide.d.ts +16 -0
- package/dist/core/decide.js +57 -0
- package/dist/core/rating.d.ts +7 -0
- package/dist/core/rating.js +18 -0
- package/dist/core/storage.d.ts +20 -0
- package/dist/core/storage.js +73 -0
- package/dist/core/types.d.ts +332 -0
- package/dist/core/types.js +126 -0
- package/dist/core/versions.d.ts +2 -0
- package/dist/core/versions.js +20 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +44 -0
- package/dist/native/Blocks.d.ts +7 -0
- package/dist/native/Blocks.js +45 -0
- package/dist/native/ChangelogButton.d.ts +6 -0
- package/dist/native/ChangelogButton.js +16 -0
- package/dist/native/ChangelogScreen.d.ts +6 -0
- package/dist/native/ChangelogScreen.js +52 -0
- package/dist/native/CommentComposer.d.ts +11 -0
- package/dist/native/CommentComposer.js +40 -0
- package/dist/native/CommentItem.d.ts +15 -0
- package/dist/native/CommentItem.js +35 -0
- package/dist/native/CommentsThread.d.ts +9 -0
- package/dist/native/CommentsThread.js +24 -0
- package/dist/native/Provider.d.ts +11 -0
- package/dist/native/Provider.js +67 -0
- package/dist/native/ReleaseView.d.ts +11 -0
- package/dist/native/ReleaseView.js +37 -0
- package/dist/native/WhatsNewSheet.d.ts +6 -0
- package/dist/native/WhatsNewSheet.js +52 -0
- package/dist/native/community.d.ts +18 -0
- package/dist/native/community.js +39 -0
- package/dist/native/context.d.ts +125 -0
- package/dist/native/context.js +26 -0
- package/dist/native/default-texts.d.ts +89 -0
- package/dist/native/default-texts.js +92 -0
- package/dist/native/format.d.ts +5 -0
- package/dist/native/format.js +34 -0
- package/dist/native/messages.d.ts +44 -0
- package/dist/native/messages.js +83 -0
- package/dist/native/primitives.d.ts +39 -0
- package/dist/native/primitives.js +78 -0
- package/dist/native/rating-plan.d.ts +31 -0
- package/dist/native/rating-plan.js +101 -0
- package/dist/native/resolve.d.ts +21 -0
- package/dist/native/resolve.js +73 -0
- package/dist/native/session.d.ts +48 -0
- package/dist/native/session.js +83 -0
- package/dist/native/styles-community.d.ts +1447 -0
- package/dist/native/styles-community.js +117 -0
- package/dist/native/styles-scale.d.ts +66 -0
- package/dist/native/styles-scale.js +22 -0
- package/dist/native/styles.d.ts +2584 -0
- package/dist/native/styles.js +161 -0
- package/dist/native/tokens.d.ts +51 -0
- package/dist/native/tokens.js +90 -0
- package/dist/native/use-actions.d.ts +55 -0
- package/dist/native/use-actions.js +59 -0
- package/dist/native/use-comments.d.ts +40 -0
- package/dist/native/use-comments.js +83 -0
- package/dist/native/use-controller.d.ts +103 -0
- package/dist/native/use-controller.js +147 -0
- package/dist/native/use-session.d.ts +268 -0
- package/dist/native/use-session.js +86 -0
- package/package.json +52 -4
package/README.md
CHANGED
|
@@ -1,3 +1,137 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @the-seeker/changes-react-native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
제품 문서: https://docs.theseeker.io/changes/react-native
|
|
4
|
+
|
|
5
|
+
TheSeeker CRM 체인지로그를 React Native·Expo 앱에 붙이는 SDK입니다. 업데이트 뒤 첫 실행에 What's New 시트를 한 번 띄우고, 체인지로그 화면·읽지 않은 소식 배지·릴리스 투표·댓글(답글·신고·개발자 배지)·스토어 평가 버튼을 제공합니다. 순수 JS라 네이티브 모듈·prebuild 없이 Expo Go에서도 동작합니다.
|
|
6
|
+
|
|
7
|
+
## 설치
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx expo install @the-seeker/changes-react-native @react-native-async-storage/async-storage expo-application
|
|
11
|
+
# 선택: 앱 안 평가 프롬프트
|
|
12
|
+
npx expo install expo-store-review
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
요구 버전: `react >= 18`, `react-native >= 0.74`. `@react-native-async-storage/async-storage`, `expo-application`, `expo-store-review`는 **선택 peer**입니다. SDK는 이 패키지들을 import하지 않고 앱이 넘긴 어댑터만 사용하므로, 설치하지 않아도 Metro 번들이 깨지지 않습니다.
|
|
16
|
+
|
|
17
|
+
## 1. CRM 설정
|
|
18
|
+
|
|
19
|
+
CRM → 체인지로그 → **설정**에서:
|
|
20
|
+
|
|
21
|
+
- **허용 앱**에 iOS bundle identifier / Android applicationId를 추가합니다(예: `com.example.app`). 등록하지 않은 앱은 `403 APP_NOT_ALLOWED`를 받고 UI가 나타나지 않습니다(`onError("APP_NOT_ALLOWED")`).
|
|
22
|
+
- 평가 버튼을 쓰려면 App Store ID(숫자)와 Android 패키지명을 입력하고 평가 표시 방식(`항상`/`좋아요 뒤`/`끔`)을 고릅니다.
|
|
23
|
+
- 공개 키(`chg_…`)는 **설치** 탭에서 복사합니다.
|
|
24
|
+
|
|
25
|
+
## 2. Provider 추가
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
29
|
+
import * as Application from "expo-application";
|
|
30
|
+
import * as StoreReview from "expo-store-review"; // 선택
|
|
31
|
+
import { ChangesProvider } from "@the-seeker/changes-react-native";
|
|
32
|
+
|
|
33
|
+
export default function App() {
|
|
34
|
+
return (
|
|
35
|
+
<ChangesProvider
|
|
36
|
+
changesKey="chg_..."
|
|
37
|
+
appId="com.example.app"
|
|
38
|
+
appVersion={Application.nativeApplicationVersion}
|
|
39
|
+
storage={AsyncStorage}
|
|
40
|
+
storeReview={StoreReview}
|
|
41
|
+
user={{ userId: user?.id }}
|
|
42
|
+
>
|
|
43
|
+
<RootNavigator />
|
|
44
|
+
</ChangesProvider>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
| Prop | 설명 |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `changesKey` | 공개 키 `chg_…` |
|
|
52
|
+
| `appId` | iOS/Android 앱 ID. 플랫폼마다 다르면 `Platform.select(...)` |
|
|
53
|
+
| `appVersion` | 설치된 앱 버전. `Application.nativeApplicationVersion`(expo-application) 또는 `react-native-device-info`의 `getVersion()`. 없으면 웹 방식(기준 릴리스 이후 새 글)으로 판단합니다 |
|
|
54
|
+
| `storage` | `{ getItem, setItem }`(동기·비동기). `AsyncStorage`를 그대로 넘깁니다. **마운트 때 한 번만 읽습니다.** 없으면 메모리에 저장하고 개발 빌드에서 한 번 경고합니다(앱을 다시 켜면 표시 상태·설치 ID가 초기화됨) |
|
|
55
|
+
| `storeReview` | `{ isAvailableAsync, requestReview }`. `import * as StoreReview from "expo-store-review"` |
|
|
56
|
+
| `useNativeReview` | `true`면 평가 버튼이 먼저 앱 안 평가 프롬프트를 띄우고, 실패하면 스토어 페이지를 엽니다(기본 `false`) |
|
|
57
|
+
| `user` | `{ userId?, name? }`. `userId`가 있으면 투표·댓글이 기기 대신 사용자 기준으로 묶입니다. `name`은 CRM에서 작성자 이름 허용을 켰을 때만 쓰입니다 |
|
|
58
|
+
| `locale` | SDK 화면 문구 언어. `"auto"`(기본, 기기 언어) · `"ko"` · `"en"` |
|
|
59
|
+
| `contentLocale` | 릴리스 제목·본문 번역 언어(BCP-47, 예: `"ja"`, `"zh-Hant"`, `"pt-BR"`). CRM 릴리스에 그 언어 번역이 있으면 번역을, 없으면 기본 제목·본문을 받습니다. 생략하면 항상 기본 제목·본문입니다. 값이 바뀌면 릴리스를 다시 불러옵니다 |
|
|
60
|
+
| `showOnFirstLaunch` | 첫 설치에도 최신 릴리스를 보여 줌(기본 `false`) |
|
|
61
|
+
| `forceShow` | 디버그용: 상태와 무관하게 최신 릴리스를 표시 |
|
|
62
|
+
| `autoPresent` | 내장 What's New 시트를 자동으로 띄움(기본 `true`). `false`면 `pendingWhatsNew`로 직접 그립니다(아래 "직접 그리는 시트") |
|
|
63
|
+
| `baseUrl` | 기본 `https://crm.theseeker.io` |
|
|
64
|
+
| `onError` | 로드·쓰기 실패 코드(`APP_NOT_ALLOWED`, `NETWORK_ERROR` 등) |
|
|
65
|
+
|
|
66
|
+
설정을 불러오지 못하거나 프로젝트가 꺼져 있으면 children만 렌더합니다.
|
|
67
|
+
|
|
68
|
+
## 3. What's New 표시 규칙 (show-once)
|
|
69
|
+
|
|
70
|
+
- **첫 설치**: 현재 버전과 최신 릴리스만 기록하고 아무것도 띄우지 않습니다(`showOnFirstLaunch`로 변경).
|
|
71
|
+
- **업데이트 후 첫 실행**: `appVersion`이 기록된 버전보다 높으면, 그 사이에 나온 릴리스 중 가장 최신 것을 **한 번** 띄웁니다.
|
|
72
|
+
- **노트가 아직 없음**: 아무것도 띄우지 않고 기록도 바꾸지 않아, 다음 실행에서 다시 확인합니다.
|
|
73
|
+
- **다운그레이드**: 띄우지 않고 가장 높았던 버전을 유지합니다.
|
|
74
|
+
- 시트가 **실제로 화면에 나타난 뒤**(`Modal onShow`)에만 표시 완료로 기록하고 조회 이벤트를 보냅니다.
|
|
75
|
+
|
|
76
|
+
설정 화면의 "새로운 소식" 행에서는 `showWhatsNew()`로 최신 릴리스를 다시 열 수 있습니다.
|
|
77
|
+
|
|
78
|
+
### 직접 그리는 시트
|
|
79
|
+
|
|
80
|
+
앱 디자인으로 시트를 그리려면 `autoPresent={false}`로 두고 `pendingWhatsNew`를 읽습니다. 시트가 실제로 화면에 나타난 뒤 `markPresented(release)`와 `trackView(release)`를 함께 호출해야 표시 완료 기록과 조회 수가 내장 시트와 같게 남습니다.
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
const { pendingWhatsNew, markPresented, trackView } = useChanges();
|
|
84
|
+
|
|
85
|
+
<MySheet
|
|
86
|
+
release={pendingWhatsNew}
|
|
87
|
+
onShown={(release) => {
|
|
88
|
+
markPresented(release);
|
|
89
|
+
trackView(release);
|
|
90
|
+
}}
|
|
91
|
+
/>;
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## 4. 컴포넌트와 훅
|
|
95
|
+
|
|
96
|
+
```tsx
|
|
97
|
+
import { ChangelogButton, ChangelogScreen, useChanges } from "@the-seeker/changes-react-native";
|
|
98
|
+
|
|
99
|
+
<ChangelogButton /> // 읽지 않은 소식 배지 + 내장 체인지로그 모달 열기
|
|
100
|
+
<ChangelogScreen /> // 앱 내비게이터에 직접 넣는 전체 체인지로그 화면
|
|
101
|
+
|
|
102
|
+
const { unseenCount, openChangelog, showWhatsNew, vote, openRating, comments } = useChanges();
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`useChanges()`는 웹 SDK(`@the-seeker/changes-react`)와 같은 모양에 `trackView`를 더한 것입니다: `status`, `stale`, `config`, `t`, `releases`, `latest`, `unseenCount`, `pendingWhatsNew`, `vote`, `sendFeedback`, `openChangelog`/`closeChangelog`, `markPresented`, `trackView`, `openRating`, `comments.{list,post,vote,report}`, `guidelinesAccepted`/`acceptGuidelines`.
|
|
106
|
+
|
|
107
|
+
- 시트 구성: 제목 · 버전 · 날짜 → 노트 → `↑ n | ↓` 투표 → 평가 버튼(설정한 방식대로) → `댓글 N · 댓글 보기` → **계속**.
|
|
108
|
+
- 댓글은 1단 답글까지, 개발자 답글에는 배지가 붙습니다. 첫 댓글 전에 커뮤니티 이용 안내 동의가 필요할 수 있습니다(CRM 설정).
|
|
109
|
+
- 다크 모드는 기기 설정(`useColorScheme`)을 따르고, 강조색은 CRM의 앱 강조색을 씁니다.
|
|
110
|
+
|
|
111
|
+
## 5. 평가 버튼
|
|
112
|
+
|
|
113
|
+
평가 버튼은 항상 `Linking.openURL`로 동작합니다.
|
|
114
|
+
|
|
115
|
+
- iOS: `https://apps.apple.com/app/id<ID>?action=write-review`
|
|
116
|
+
- Android: `market://details?id=<패키지>` → 열 수 없으면 `https://play.google.com/store/apps/details?id=<패키지>`
|
|
117
|
+
- 웹(react-native-web): CRM의 리뷰 URL → App Store/Play URL
|
|
118
|
+
|
|
119
|
+
`storeReview` + `useNativeReview`를 주면 먼저 앱 안 평가 프롬프트를 시도합니다. Apple·Google은 프롬프트 노출 횟수를 제한하므로, 프롬프트가 조용히 생략될 수 있음을 감안하세요.
|
|
120
|
+
|
|
121
|
+
## 6. 오프라인과 캐시
|
|
122
|
+
|
|
123
|
+
릴리스 목록은 `ETag`로 캐시합니다(`If-None-Match` → `304`). 네트워크가 없으면 7일 이내 캐시를 보여 주고 `stale: true`로 알립니다(체인지로그 화면에 오프라인 안내가 표시됨). 투표·댓글 같은 쓰기는 큐에 쌓지 않습니다.
|
|
124
|
+
|
|
125
|
+
## 7. 플랫폼
|
|
126
|
+
|
|
127
|
+
- iOS·Android: `X-TheSeeker-App: <appId>` 헤더로 인증합니다(Origin 없음).
|
|
128
|
+
- react-native-web: 웹 호출로 동작합니다. 앱 헤더를 보내지 않으므로 CRM **허용 도메인**에 사이트 도메인을 등록하세요.
|
|
129
|
+
- 설치 ID는 SDK가 만든 무작위 값입니다(IDFA/IDFV 아님). IP는 서버에서 키 해시로만 저장되고 30일 뒤 지워집니다.
|
|
130
|
+
|
|
131
|
+
## 개발
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
pnpm install && pnpm typecheck && pnpm test && pnpm build
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`src/core/*`는 `@the-seeker/changes-react`의 코어를 바이트 단위로 복사한 것입니다(루트 `src/__tests__/changes-sdk-core-parity.test.ts`가 검증). 코어는 웹 패키지에서 고친 뒤 복사하세요.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ChangesClient } from "./client";
|
|
2
|
+
import type { Result, Releases } from "./types";
|
|
3
|
+
import type { ChangesStorage } from "./storage";
|
|
4
|
+
export type CacheOptions = Readonly<{
|
|
5
|
+
client: Pick<ChangesClient, "listReleases">;
|
|
6
|
+
storage: ChangesStorage;
|
|
7
|
+
key: string;
|
|
8
|
+
now: number;
|
|
9
|
+
maxAgeMs?: number;
|
|
10
|
+
}>;
|
|
11
|
+
export type CacheResult = Result<Releases> & Readonly<{
|
|
12
|
+
stale?: boolean;
|
|
13
|
+
}>;
|
|
14
|
+
export declare function loadReleasesWithCache(options: CacheOptions): Promise<CacheResult>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.loadReleasesWithCache = loadReleasesWithCache;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const types_1 = require("./types");
|
|
6
|
+
const storage_1 = require("./storage");
|
|
7
|
+
const cacheSchema = zod_1.z.object({ etag: zod_1.z.string().nullable(), savedAt: zod_1.z.number().finite(), body: types_1.releasesSchema });
|
|
8
|
+
async function loadReleasesWithCache(options) {
|
|
9
|
+
const { client, storage, key, now, maxAgeMs = 7 * 86400000 } = options;
|
|
10
|
+
const cacheKey = (0, storage_1.storageKeys)(key).releases;
|
|
11
|
+
const parsed = cacheSchema.safeParse((0, storage_1.parseStoredJson)(await storage.getItem(cacheKey)));
|
|
12
|
+
const cache = parsed.success ? parsed.data : null;
|
|
13
|
+
const result = await client.listReleases(cache?.etag ? { etag: cache.etag } : {});
|
|
14
|
+
if (!result.ok) {
|
|
15
|
+
const age = cache === null ? Infinity : now - cache.savedAt;
|
|
16
|
+
return result.code === "NETWORK_ERROR" && cache !== null && age >= 0 && age < maxAgeMs
|
|
17
|
+
? { ok: true, body: cache.body, stale: true }
|
|
18
|
+
: result;
|
|
19
|
+
}
|
|
20
|
+
switch (result.status) {
|
|
21
|
+
case 200:
|
|
22
|
+
await storage.setItem(cacheKey, JSON.stringify({ etag: result.etag, savedAt: now, body: result.body }));
|
|
23
|
+
return { ok: true, body: result.body, stale: false };
|
|
24
|
+
case 304:
|
|
25
|
+
if (cache === null)
|
|
26
|
+
return { ok: false, code: "INVALID_RESPONSE" };
|
|
27
|
+
await storage.setItem(cacheKey, JSON.stringify({ ...cache, etag: result.etag ?? cache.etag, savedAt: now }));
|
|
28
|
+
return { ok: true, body: cache.body, stale: false };
|
|
29
|
+
default: {
|
|
30
|
+
const exhaustive = result;
|
|
31
|
+
return exhaustive;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import type { Platform, User, Voter, ClientInfo, Failure, Result, Releases } from "./types";
|
|
2
|
+
export type FetchInit = Readonly<{
|
|
3
|
+
method: "GET" | "POST";
|
|
4
|
+
headers: Readonly<Record<string, string>>;
|
|
5
|
+
body?: string;
|
|
6
|
+
}>;
|
|
7
|
+
export type FetchResponse = Readonly<{
|
|
8
|
+
status: number;
|
|
9
|
+
headers: {
|
|
10
|
+
get(name: string): string | null;
|
|
11
|
+
};
|
|
12
|
+
json(): Promise<unknown>;
|
|
13
|
+
}>;
|
|
14
|
+
export type FetchImpl = (url: string, init: FetchInit) => Promise<FetchResponse>;
|
|
15
|
+
export type ChangesClientOptions = Readonly<{
|
|
16
|
+
key: string;
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
platform: Platform;
|
|
19
|
+
appVersion?: string;
|
|
20
|
+
/** BCP-47 tag (`ja`, `zh-Hant`) choosing the release title/body translation; omitted means the base text. */
|
|
21
|
+
locale?: string;
|
|
22
|
+
appId?: string;
|
|
23
|
+
appHeader?: string;
|
|
24
|
+
user?: User;
|
|
25
|
+
fetchImpl: FetchImpl;
|
|
26
|
+
}>;
|
|
27
|
+
export type ListOptions = Readonly<{
|
|
28
|
+
cursor?: string;
|
|
29
|
+
limit?: number;
|
|
30
|
+
voter?: string;
|
|
31
|
+
etag?: string;
|
|
32
|
+
}>;
|
|
33
|
+
export type ReleasesResult = Readonly<{
|
|
34
|
+
ok: true;
|
|
35
|
+
status: 200;
|
|
36
|
+
etag: string | null;
|
|
37
|
+
body: Releases;
|
|
38
|
+
}> | Readonly<{
|
|
39
|
+
ok: true;
|
|
40
|
+
status: 304;
|
|
41
|
+
etag: string | null;
|
|
42
|
+
}> | Failure;
|
|
43
|
+
type ReleaseWrite = Readonly<{
|
|
44
|
+
releaseId: string;
|
|
45
|
+
voter: Voter;
|
|
46
|
+
}>;
|
|
47
|
+
type CommentWrite = Readonly<{
|
|
48
|
+
commentId: string;
|
|
49
|
+
voter: Voter;
|
|
50
|
+
}>;
|
|
51
|
+
type VoteValue = -1 | 0 | 1;
|
|
52
|
+
export type FeedbackInput = ReleaseWrite & Readonly<{
|
|
53
|
+
message: string;
|
|
54
|
+
pageUrl?: string;
|
|
55
|
+
email?: string;
|
|
56
|
+
client?: ClientInfo;
|
|
57
|
+
}>;
|
|
58
|
+
export type CommentInput = ReleaseWrite & Readonly<{
|
|
59
|
+
parentId?: string;
|
|
60
|
+
body: string;
|
|
61
|
+
guidelinesAccepted?: boolean;
|
|
62
|
+
client?: ClientInfo;
|
|
63
|
+
}>;
|
|
64
|
+
export type ReportInput = CommentWrite & Readonly<{
|
|
65
|
+
reason: "spam" | "abuse" | "off_topic" | "other";
|
|
66
|
+
note?: string;
|
|
67
|
+
}>;
|
|
68
|
+
export declare function createChangesClient(options: ChangesClientOptions): {
|
|
69
|
+
getConfig: () => Promise<Result<Readonly<{
|
|
70
|
+
enabled: boolean;
|
|
71
|
+
defaultLocale: "ko" | "en";
|
|
72
|
+
app: Readonly<{
|
|
73
|
+
name: string;
|
|
74
|
+
subtitle: string | null;
|
|
75
|
+
description: string | null;
|
|
76
|
+
iconUrl: string | null;
|
|
77
|
+
websiteUrl: string | null;
|
|
78
|
+
accentColor: string;
|
|
79
|
+
contactEmail: string | null;
|
|
80
|
+
appStoreUrl: string | null;
|
|
81
|
+
playStoreUrl: string | null;
|
|
82
|
+
}>;
|
|
83
|
+
page: Readonly<{
|
|
84
|
+
enabled: boolean;
|
|
85
|
+
url: string;
|
|
86
|
+
}>;
|
|
87
|
+
community: Readonly<{
|
|
88
|
+
votesEnabled: boolean;
|
|
89
|
+
commentsEnabled: boolean;
|
|
90
|
+
requireGuidelinesAck: boolean;
|
|
91
|
+
allowAuthorNames: boolean;
|
|
92
|
+
}>;
|
|
93
|
+
rating: Readonly<{
|
|
94
|
+
mode: "off" | "always" | "after_upvote";
|
|
95
|
+
iosAppStoreId: string | null;
|
|
96
|
+
androidPackage: string | null;
|
|
97
|
+
reviewUrl: string | null;
|
|
98
|
+
}>;
|
|
99
|
+
texts: Readonly<Record<string, Readonly<Record<string, string>>>>;
|
|
100
|
+
}>>>;
|
|
101
|
+
listReleases(input?: ListOptions): Promise<ReleasesResult>;
|
|
102
|
+
vote: (input: ReleaseWrite & Readonly<{
|
|
103
|
+
value: VoteValue;
|
|
104
|
+
}>) => Promise<Result<Readonly<{
|
|
105
|
+
upvotes: number;
|
|
106
|
+
downvotes: number;
|
|
107
|
+
myVote: 0 | 1 | -1;
|
|
108
|
+
}>>>;
|
|
109
|
+
track: (input: ReleaseWrite & Readonly<{
|
|
110
|
+
type: "view" | "rating_click";
|
|
111
|
+
}>) => Promise<Result<Readonly<Record<string, never>>>>;
|
|
112
|
+
sendFeedback: (input: FeedbackInput) => Promise<Result<Readonly<{
|
|
113
|
+
id: string;
|
|
114
|
+
}>>>;
|
|
115
|
+
listComments: (input: Omit<ListOptions, "etag"> & Readonly<{
|
|
116
|
+
releaseId: string;
|
|
117
|
+
}>) => Promise<Result<Readonly<{
|
|
118
|
+
items: readonly Readonly<{
|
|
119
|
+
upvotes: number;
|
|
120
|
+
downvotes: number;
|
|
121
|
+
myVote: 0 | 1 | -1;
|
|
122
|
+
id: string;
|
|
123
|
+
authorName: string;
|
|
124
|
+
isDeveloper: boolean;
|
|
125
|
+
body: string;
|
|
126
|
+
createdAt: string;
|
|
127
|
+
replies: readonly Readonly<{
|
|
128
|
+
upvotes: number;
|
|
129
|
+
downvotes: number;
|
|
130
|
+
myVote: 0 | 1 | -1;
|
|
131
|
+
id: string;
|
|
132
|
+
authorName: string;
|
|
133
|
+
isDeveloper: boolean;
|
|
134
|
+
body: string;
|
|
135
|
+
createdAt: string;
|
|
136
|
+
}>[];
|
|
137
|
+
}>[];
|
|
138
|
+
nextCursor: string | null;
|
|
139
|
+
total: number;
|
|
140
|
+
}>>>;
|
|
141
|
+
postComment: (input: CommentInput) => Promise<Result<Readonly<{
|
|
142
|
+
comment: Readonly<{
|
|
143
|
+
upvotes: number;
|
|
144
|
+
downvotes: number;
|
|
145
|
+
myVote: 0 | 1 | -1;
|
|
146
|
+
id: string;
|
|
147
|
+
authorName: string;
|
|
148
|
+
isDeveloper: boolean;
|
|
149
|
+
body: string;
|
|
150
|
+
createdAt: string;
|
|
151
|
+
}>;
|
|
152
|
+
}>>>;
|
|
153
|
+
voteComment: (input: CommentWrite & Readonly<{
|
|
154
|
+
value: VoteValue;
|
|
155
|
+
}>) => Promise<Result<Readonly<{
|
|
156
|
+
upvotes: number;
|
|
157
|
+
downvotes: number;
|
|
158
|
+
myVote: 0 | 1 | -1;
|
|
159
|
+
}>>>;
|
|
160
|
+
reportComment: (input: ReportInput) => Promise<Result<Readonly<Record<string, never>>>>;
|
|
161
|
+
};
|
|
162
|
+
export type ChangesClient = ReturnType<typeof createChangesClient>;
|
|
163
|
+
export {};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createChangesClient = createChangesClient;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const types_1 = require("./types");
|
|
6
|
+
const emptySchema = zod_1.z.object({}).readonly();
|
|
7
|
+
const errorSchema = zod_1.z.object({ error: types_1.errorCodeSchema });
|
|
8
|
+
function httpFailure(status, raw) {
|
|
9
|
+
const parsed = errorSchema.safeParse(raw);
|
|
10
|
+
if (parsed.success)
|
|
11
|
+
return { ok: false, code: parsed.data.error };
|
|
12
|
+
switch (status) {
|
|
13
|
+
case 400:
|
|
14
|
+
return { ok: false, code: "BAD_REQUEST" };
|
|
15
|
+
case 413:
|
|
16
|
+
return { ok: false, code: "PAYLOAD_TOO_LARGE" };
|
|
17
|
+
case 429:
|
|
18
|
+
return { ok: false, code: "RATE_LIMITED" };
|
|
19
|
+
default:
|
|
20
|
+
return { ok: false, code: "HTTP_ERROR" };
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function createChangesClient(options) {
|
|
24
|
+
const { key, platform, fetchImpl, user } = options;
|
|
25
|
+
const baseUrl = (options.baseUrl ?? "https://crm.theseeker.io").replace(/\/+$/, "");
|
|
26
|
+
const appHeaders = options.appId && platform !== "web" ? { "X-TheSeeker-App": options.appHeader ?? options.appId } : {};
|
|
27
|
+
const identity = (voter) => ({ ...voter, ...user });
|
|
28
|
+
const url = (path, query = {}) => {
|
|
29
|
+
const values = { key, ...query };
|
|
30
|
+
const pairs = Object.entries(values).filter((entry) => entry[1] !== undefined);
|
|
31
|
+
return `${baseUrl}/api/changes/${path}?${pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&")}`;
|
|
32
|
+
};
|
|
33
|
+
// Transport boundary: arbitrary rejected values must become a result, not escape to host apps.
|
|
34
|
+
async function request(path, init) {
|
|
35
|
+
try {
|
|
36
|
+
return { ok: true, response: await fetchImpl(path, init) };
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return { ok: false, code: "NETWORK_ERROR" };
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function parse(response, schema) {
|
|
43
|
+
let raw;
|
|
44
|
+
try {
|
|
45
|
+
raw = await response.json();
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return response.status >= 200 && response.status < 300
|
|
49
|
+
? { ok: false, code: "INVALID_RESPONSE" }
|
|
50
|
+
: httpFailure(response.status, null);
|
|
51
|
+
}
|
|
52
|
+
if (response.status < 200 || response.status >= 300)
|
|
53
|
+
return httpFailure(response.status, raw);
|
|
54
|
+
const parsed = schema.safeParse(raw);
|
|
55
|
+
return parsed.success ? { ok: true, body: parsed.data } : { ok: false, code: "INVALID_RESPONSE" };
|
|
56
|
+
}
|
|
57
|
+
async function get(path, schema, query = {}) {
|
|
58
|
+
const result = await request(url(path, query), { method: "GET", headers: appHeaders });
|
|
59
|
+
return result.ok ? parse(result.response, schema) : result;
|
|
60
|
+
}
|
|
61
|
+
async function post(path, schema, body) {
|
|
62
|
+
const result = await request(`${baseUrl}/api/changes/${path}`, {
|
|
63
|
+
method: "POST",
|
|
64
|
+
headers: { ...appHeaders, "Content-Type": "application/json" },
|
|
65
|
+
body: JSON.stringify({ ...body, key, voter: identity(body.voter) }),
|
|
66
|
+
});
|
|
67
|
+
return result.ok ? parse(result.response, schema) : result;
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
getConfig: () => get("config", types_1.configSchema),
|
|
71
|
+
async listReleases(input = {}) {
|
|
72
|
+
const result = await request(url("releases", {
|
|
73
|
+
platform,
|
|
74
|
+
appVersion: options.appVersion,
|
|
75
|
+
locale: options.locale,
|
|
76
|
+
userId: user?.userId,
|
|
77
|
+
cursor: input.cursor,
|
|
78
|
+
limit: input.limit,
|
|
79
|
+
voter: input.voter,
|
|
80
|
+
}), { method: "GET", headers: { ...appHeaders, ...(input.etag ? { "If-None-Match": input.etag } : {}) } });
|
|
81
|
+
if (!result.ok)
|
|
82
|
+
return result;
|
|
83
|
+
const { response } = result;
|
|
84
|
+
const etag = response.headers.get("ETag");
|
|
85
|
+
if (response.status === 304)
|
|
86
|
+
return { ok: true, status: 304, etag };
|
|
87
|
+
const parsed = await parse(response, types_1.releasesSchema);
|
|
88
|
+
return parsed.ok ? { ok: true, status: 200, etag, body: parsed.body } : parsed;
|
|
89
|
+
},
|
|
90
|
+
vote: (input) => post("vote", types_1.voteSchema, input),
|
|
91
|
+
track: (input) => post("event", emptySchema, input),
|
|
92
|
+
sendFeedback: (input) => post("feedback", zod_1.z.object({ id: zod_1.z.string() }).readonly(), input),
|
|
93
|
+
listComments: (input) => get("comments", types_1.commentsSchema, { ...input, userId: user?.userId }),
|
|
94
|
+
postComment: (input) => post("comments", zod_1.z.object({ comment: types_1.commentSchema }).readonly(), input),
|
|
95
|
+
voteComment: (input) => post("comments/vote", types_1.voteSchema, input),
|
|
96
|
+
reportComment: (input) => post("comments/report", emptySchema, input),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ChangesState, Release } from "./types";
|
|
2
|
+
export type DecisionInput = Readonly<{
|
|
3
|
+
releases: readonly Release[];
|
|
4
|
+
state: ChangesState | null;
|
|
5
|
+
appVersion?: string | null;
|
|
6
|
+
showOnFirstLaunch?: boolean;
|
|
7
|
+
forceShow?: boolean;
|
|
8
|
+
now: string;
|
|
9
|
+
}>;
|
|
10
|
+
export declare function decideWhatsNew(input: DecisionInput): Readonly<{
|
|
11
|
+
release: Release | null;
|
|
12
|
+
nextState: ChangesState;
|
|
13
|
+
}>;
|
|
14
|
+
export declare function markPresented(state: ChangesState, release: Release, appVersion?: string | null): ChangesState;
|
|
15
|
+
export declare function markListOpened(state: ChangesState, now: string): ChangesState;
|
|
16
|
+
export declare function unseenCount(releases: readonly Release[], state: ChangesState): number;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.decideWhatsNew = decideWhatsNew;
|
|
4
|
+
exports.markPresented = markPresented;
|
|
5
|
+
exports.markListOpened = markListOpened;
|
|
6
|
+
exports.unseenCount = unseenCount;
|
|
7
|
+
const versions_1 = require("./versions");
|
|
8
|
+
function decideWhatsNew(input) {
|
|
9
|
+
const { state, appVersion, now } = input;
|
|
10
|
+
const releases = [...input.releases].sort((a, b) => b.publishedAt.localeCompare(a.publishedAt) || b.id.localeCompare(a.id));
|
|
11
|
+
const latest = releases[0] ?? null;
|
|
12
|
+
const nextState = state ?? {
|
|
13
|
+
v: 1,
|
|
14
|
+
lastVersion: appVersion ?? null,
|
|
15
|
+
baselineReleaseId: latest?.id ?? null,
|
|
16
|
+
presentedIds: [],
|
|
17
|
+
firstSeenAt: now,
|
|
18
|
+
listOpenedAt: null,
|
|
19
|
+
};
|
|
20
|
+
if (input.forceShow)
|
|
21
|
+
return { release: latest, nextState };
|
|
22
|
+
if (state === null)
|
|
23
|
+
return { release: input.showOnFirstLaunch ? latest : null, nextState };
|
|
24
|
+
const candidates = releases.filter((release) => !state.presentedIds.includes(release.id));
|
|
25
|
+
if (appVersion) {
|
|
26
|
+
const lastVersion = state.lastVersion;
|
|
27
|
+
// State saved before the host passed appVersion: adopt it as the baseline so later upgrades still present.
|
|
28
|
+
if (lastVersion === null)
|
|
29
|
+
return { release: null, nextState: { ...nextState, lastVersion: appVersion } };
|
|
30
|
+
if ((0, versions_1.compareVersions)(appVersion, lastVersion) <= 0)
|
|
31
|
+
return { release: null, nextState };
|
|
32
|
+
const release = candidates.find((candidate) => candidate.version !== null &&
|
|
33
|
+
(0, versions_1.compareVersions)(candidate.version, appVersion) <= 0 &&
|
|
34
|
+
(0, versions_1.compareVersions)(candidate.version, lastVersion) > 0) ?? null;
|
|
35
|
+
return { release, nextState };
|
|
36
|
+
}
|
|
37
|
+
const baseline = releases.find((release) => release.id === state.baselineReleaseId);
|
|
38
|
+
const cutoff = baseline?.publishedAt ?? state.firstSeenAt;
|
|
39
|
+
return { release: candidates.find((candidate) => candidate.publishedAt > cutoff) ?? null, nextState };
|
|
40
|
+
}
|
|
41
|
+
function markPresented(state, release, appVersion) {
|
|
42
|
+
const lastVersion = appVersion && (state.lastVersion === null || (0, versions_1.compareVersions)(appVersion, state.lastVersion) > 0)
|
|
43
|
+
? appVersion
|
|
44
|
+
: state.lastVersion;
|
|
45
|
+
return {
|
|
46
|
+
...state,
|
|
47
|
+
lastVersion,
|
|
48
|
+
presentedIds: [...state.presentedIds.filter((id) => id !== release.id), release.id].slice(-50),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function markListOpened(state, now) {
|
|
52
|
+
return { ...state, listOpenedAt: now };
|
|
53
|
+
}
|
|
54
|
+
function unseenCount(releases, state) {
|
|
55
|
+
const cutoff = state.listOpenedAt && state.listOpenedAt > state.firstSeenAt ? state.listOpenedAt : state.firstSeenAt;
|
|
56
|
+
return releases.filter((release) => release.publishedAt > cutoff).length;
|
|
57
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function iosStoreUrl(id: string): string;
|
|
2
|
+
export declare function iosReviewUrl(id: string): string;
|
|
3
|
+
export declare function playStoreUrl(pkg: string): string;
|
|
4
|
+
export declare function androidReviewUrls(pkg: string): {
|
|
5
|
+
readonly market: string;
|
|
6
|
+
readonly web: string;
|
|
7
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.iosStoreUrl = iosStoreUrl;
|
|
4
|
+
exports.iosReviewUrl = iosReviewUrl;
|
|
5
|
+
exports.playStoreUrl = playStoreUrl;
|
|
6
|
+
exports.androidReviewUrls = androidReviewUrls;
|
|
7
|
+
function iosStoreUrl(id) {
|
|
8
|
+
return `https://apps.apple.com/app/id${encodeURIComponent(id)}`;
|
|
9
|
+
}
|
|
10
|
+
function iosReviewUrl(id) {
|
|
11
|
+
return `${iosStoreUrl(id)}?action=write-review`;
|
|
12
|
+
}
|
|
13
|
+
function playStoreUrl(pkg) {
|
|
14
|
+
return `https://play.google.com/store/apps/details?id=${encodeURIComponent(pkg)}`;
|
|
15
|
+
}
|
|
16
|
+
function androidReviewUrls(pkg) {
|
|
17
|
+
return { market: `market://details?id=${encodeURIComponent(pkg)}`, web: playStoreUrl(pkg) };
|
|
18
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ChangesState } from "./types";
|
|
2
|
+
export interface ChangesStorage {
|
|
3
|
+
getItem(key: string): string | null | Promise<string | null>;
|
|
4
|
+
setItem(key: string, value: string): void | Promise<void>;
|
|
5
|
+
}
|
|
6
|
+
export declare function createMemoryStorage(): {
|
|
7
|
+
getItem: (key: string) => string | null;
|
|
8
|
+
setItem: (key: string, value: string) => void;
|
|
9
|
+
};
|
|
10
|
+
export declare function storageKeys(key: string): {
|
|
11
|
+
readonly install: `${string}:install`;
|
|
12
|
+
readonly state: `${string}:state`;
|
|
13
|
+
readonly votes: `${string}:votes`;
|
|
14
|
+
readonly guidelines: `${string}:guidelines`;
|
|
15
|
+
readonly releases: `${string}:releases`;
|
|
16
|
+
};
|
|
17
|
+
export declare function parseStoredJson(raw: string | null): unknown;
|
|
18
|
+
export declare function getOrCreateInstallId(storage: ChangesStorage, key: string, randomBytes: (length: number) => Uint8Array): Promise<string>;
|
|
19
|
+
export declare function readState(storage: ChangesStorage, key: string): Promise<ChangesState | null>;
|
|
20
|
+
export declare function writeState(storage: ChangesStorage, key: string, state: ChangesState): Promise<void>;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createMemoryStorage = createMemoryStorage;
|
|
4
|
+
exports.storageKeys = storageKeys;
|
|
5
|
+
exports.parseStoredJson = parseStoredJson;
|
|
6
|
+
exports.getOrCreateInstallId = getOrCreateInstallId;
|
|
7
|
+
exports.readState = readState;
|
|
8
|
+
exports.writeState = writeState;
|
|
9
|
+
const types_1 = require("./types");
|
|
10
|
+
function createMemoryStorage() {
|
|
11
|
+
const values = new Map();
|
|
12
|
+
return {
|
|
13
|
+
getItem: (key) => values.get(key) ?? null,
|
|
14
|
+
setItem: (key, value) => {
|
|
15
|
+
values.set(key, value);
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function storageKeys(key) {
|
|
20
|
+
const prefix = `theseeker:changes:v1:${key}`;
|
|
21
|
+
return {
|
|
22
|
+
install: `${prefix}:install`,
|
|
23
|
+
state: `${prefix}:state`,
|
|
24
|
+
votes: `${prefix}:votes`,
|
|
25
|
+
guidelines: `${prefix}:guidelines`,
|
|
26
|
+
releases: `${prefix}:releases`,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function parseStoredJson(raw) {
|
|
30
|
+
if (raw === null)
|
|
31
|
+
return null;
|
|
32
|
+
try {
|
|
33
|
+
const value = JSON.parse(raw);
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error instanceof SyntaxError)
|
|
38
|
+
return null;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function getOrCreateInstallId(storage, key, randomBytes) {
|
|
43
|
+
const installKey = storageKeys(key).install;
|
|
44
|
+
const existing = await storage.getItem(installKey);
|
|
45
|
+
if (existing !== null && /^[A-Za-z0-9_-]{16,64}$/.test(existing))
|
|
46
|
+
return existing;
|
|
47
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
48
|
+
const bytes = randomBytes(16);
|
|
49
|
+
if (bytes.length !== 16)
|
|
50
|
+
throw new RangeError("randomBytes must return 16 bytes");
|
|
51
|
+
let bits = 0;
|
|
52
|
+
let buffer = 0;
|
|
53
|
+
let id = "";
|
|
54
|
+
for (const byte of bytes) {
|
|
55
|
+
buffer = (buffer << 8) | byte;
|
|
56
|
+
bits += 8;
|
|
57
|
+
while (bits >= 6) {
|
|
58
|
+
bits -= 6;
|
|
59
|
+
id += alphabet[(buffer >>> bits) & 63];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (bits > 0)
|
|
63
|
+
id += alphabet[(buffer << (6 - bits)) & 63];
|
|
64
|
+
await storage.setItem(installKey, id);
|
|
65
|
+
return id;
|
|
66
|
+
}
|
|
67
|
+
async function readState(storage, key) {
|
|
68
|
+
const parsed = types_1.stateSchema.safeParse(parseStoredJson(await storage.getItem(storageKeys(key).state)));
|
|
69
|
+
return parsed.success ? parsed.data : null;
|
|
70
|
+
}
|
|
71
|
+
async function writeState(storage, key, state) {
|
|
72
|
+
await storage.setItem(storageKeys(key).state, JSON.stringify(state));
|
|
73
|
+
}
|