@leisuresaas/react-native 0.6.3-dev.4 → 0.6.3

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 CHANGED
@@ -1,34 +1,33 @@
1
1
  # @leisuresaas/react-native
2
2
 
3
- React Native SDK for LeisureSaas **frontend-only** surfaces:
3
+ LeisureSaas **前端** React Native / Expo SDK:
4
4
 
5
- - OAuth / Hosted UI / Magic login
6
- - Public Ads & App Config (`pk_live_` → `/v1/public/*`)
7
- - Drive User Plane (`pk_live_` + Bearer → `/v1/user/storage/*`)
8
- - Local push helpers (`buildEnablePushRegistration` — **no HTTP**)
5
+ - 平台 OAuth / Hosted UI / Magic
6
+ - 产品账号与无头 Google/Apple(peer 原生模块)
7
+ - Public Ads、App Config、Drive(`pk_live_`)
8
+ - 本地 Push helper(**不发**登记 HTTP)
9
9
 
10
- **Does not** ship Integration Key (`ik_`) clients or product BFF path constants.
11
- Business APIs (billing, entitlement, device-token register) → **your BFF** + [`sdk/go`](../go).
10
+ **不**内置 Integration Key。业务 API → 你们的 BFF + [`sdk/go`](../go)。
12
11
 
13
- **AI**:见 **[AGENTS.md](AGENTS.md)** · 架构:[plan/services/sdk-react-native/ARCHITECTURE.md](../../plan/services/sdk-react-native/ARCHITECTURE.md)
12
+ **AI**:见 [AGENTS.md](AGENTS.md)。
14
13
 
15
- ## Install
14
+ ## 安装
16
15
 
17
16
  ```bash
18
17
  npm install @leisuresaas/react-native
19
18
  ```
20
19
 
21
20
  `metro.config.js`:`transpilePackages: ["@leisuresaas/react-native"]`。
22
- Peers:`expo`, `expo-auth-session`, `expo-secure-store`, `expo-web-browser`, `react`, `react-native`;Push 可选 `expo-notifications`。
21
+ Peers:`expo`、`expo-auth-session`、`expo-secure-store`、`expo-web-browser`、`react`、`react-native`;社交可选 `@react-native-google-signin/google-signin`、`expo-apple-authentication`;Push 可选 `expo-notifications`。
23
22
 
24
- ## Quick start
23
+ ## 快速开始
25
24
 
26
25
  ```tsx
27
26
  import {
28
27
  AuthProvider,
29
28
  AdsProvider,
30
29
  AppUpdateProvider,
31
- buildEnablePushRegistration,
30
+ signInWithGoogle,
32
31
  useAuth,
33
32
  } from "@leisuresaas/react-native";
34
33
 
@@ -47,9 +46,15 @@ import {
47
46
  </AuthProvider>
48
47
  ```
49
48
 
50
- 站内广告:素材 `link_url` 填 `app:/billing`(可带 query)。点击仍走 `click_url`;在 `AdsProvider` 上传 `onInAppNavigate={(path) => router.push(path)}`。未传时站内点击不会打开浏览器。
49
+ 产品社交(自绘按钮):
51
50
 
52
- ### Push(产品 BFF 登记)
51
+ ```ts
52
+ await signInWithGoogle({ gatewayUrl, publishableKey, /* ios/android client ids 可本地传入 */ });
53
+ ```
54
+
55
+ Admin → Social login 必须配置,否则换产品会话失败。Publishable Key 白名单含本 App 的 bundle / package。
56
+
57
+ ## Push(产品 BFF 登记)
53
58
 
54
59
  ```ts
55
60
  const reg = await buildEnablePushRegistration();
@@ -63,27 +68,23 @@ await apiFetch(accessToken, "/v1/notifications/device-tokens", {
63
68
  environment: reg.environment,
64
69
  }),
65
70
  });
66
- // 注销:DELETE /v1/notifications/device-tokens/{token}(产品路径)
67
71
  ```
68
72
 
69
- 需要 Dev Client / Store build + 原生 FCM/APNs(不要 Expo Go / `ExponentPushToken`)。
73
+ 需 Dev Client / Store build(不要 Expo Go)。
70
74
 
71
- ## Env
75
+ ## 环境变量
72
76
 
73
77
  | Variable | Use |
74
78
  |----------|-----|
75
- | `EXPO_PUBLIC_OAUTH_ISSUER` | OAuth / Hosted UI only |
76
- | `EXPO_PUBLIC_GATEWAY_URL` | Public Ads / App Config / Drive |
79
+ | `EXPO_PUBLIC_OAUTH_ISSUER` | OAuth / Hosted UI |
80
+ | `EXPO_PUBLIC_GATEWAY_URL` | Public API |
77
81
  | `EXPO_PUBLIC_PUBLISHABLE_KEY` | `pk_live_` |
78
82
 
79
83
  **Never** put Integration Keys in `EXPO_PUBLIC_*`.
80
84
 
81
85
  ## Breaking 0.5 → 0.6
82
86
 
83
- - Removed `LeisureSaasClient` / `createLeisureSaasClient` (bff + gateway/`ik_` modes)
84
- - `AdsProvider` no longer takes `client`
85
- - No SDK HTTP for push register — use `buildEnablePushRegistration` + product API
86
- - Platform paths: `/v1/public/*`, `/v1/user/*` (not `/api/v1/…`)
87
+ 见 [AGENTS.md](AGENTS.md) §5。
87
88
 
88
89
  ## License
89
90
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leisuresaas/react-native",
3
- "version": "0.6.3-dev.4",
3
+ "version": "0.6.3",
4
4
  "description": "React Native SDK for LeisureSaas: OAuth, Public Ads/App Config, Drive User Plane (publishable keys). Frontend-only — no Integration Key.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,7 +28,9 @@
28
28
  "prepublishOnly": "npm run typecheck"
29
29
  },
30
30
  "peerDependencies": {
31
+ "@react-native-google-signin/google-signin": ">=13.0.0",
31
32
  "expo": ">=52.0.0",
33
+ "expo-apple-authentication": ">=7.0.0",
32
34
  "expo-auth-session": ">=6.0.0",
33
35
  "expo-linking": ">=7.0.0",
34
36
  "expo-notifications": ">=0.29.0",
@@ -38,6 +40,12 @@
38
40
  "react-native": ">=0.76.0"
39
41
  },
40
42
  "peerDependenciesMeta": {
43
+ "@react-native-google-signin/google-signin": {
44
+ "optional": true
45
+ },
46
+ "expo-apple-authentication": {
47
+ "optional": true
48
+ },
41
49
  "expo-notifications": {
42
50
  "optional": true
43
51
  }
package/src/drive.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { LeisureSaasHttpError } from "./errors";
1
+ import { PlatformError } from "./errors";
2
2
  import { appBundleId } from "./ads/bundle-id";
3
3
  import { mobilePlatform } from "./platform";
4
4
  import { applyPublishableKeyHeaders } from "./publishable-key";
@@ -48,7 +48,7 @@ function driveHeaders(ctx: DriveRequestContext): Record<string, string> {
48
48
  const platform = resolvePlatform(ctx);
49
49
  const token = ctx.accessToken.trim();
50
50
  if (!token) {
51
- throw new LeisureSaasHttpError(401, "accessToken is required for Drive User Plane");
51
+ throw PlatformError.fromHttp(401, "accessToken is required for Drive User Plane");
52
52
  }
53
53
  const headers: Record<string, string> = {
54
54
  Accept: "application/json",
@@ -86,7 +86,7 @@ async function driveRequest<T>(
86
86
  const res = await fetch(url, { method, headers, body: payload });
87
87
  const text = await res.text();
88
88
  if (!res.ok) {
89
- throw new LeisureSaasHttpError(res.status, text.trim());
89
+ throw PlatformError.fromHttp(res.status, text.trim());
90
90
  }
91
91
  if (res.status === 204 || !text) {
92
92
  return {} as T;
@@ -107,7 +107,7 @@ export async function getFsStorageUsage(ctx: DriveRequestContext): Promise<FsSto
107
107
 
108
108
  export async function getFsNode(ctx: DriveRequestContext, id: string): Promise<FsNode> {
109
109
  const nodeId = id.trim();
110
- if (!nodeId) throw new LeisureSaasHttpError(400, "id is required");
110
+ if (!nodeId) throw PlatformError.fromHttp(400, "id is required");
111
111
  return driveRequest<FsNode>(ctx, "GET", `/fs/nodes/${encodeURIComponent(nodeId)}`);
112
112
  }
113
113
 
@@ -122,7 +122,7 @@ export async function createFsFolder(
122
122
 
123
123
  export async function renameFsNode(ctx: DriveRequestContext, id: string, name: string): Promise<FsNode> {
124
124
  const nodeId = id.trim();
125
- if (!nodeId) throw new LeisureSaasHttpError(400, "id is required");
125
+ if (!nodeId) throw PlatformError.fromHttp(400, "id is required");
126
126
  return driveRequest<FsNode>(ctx, "PATCH", `/fs/nodes/${encodeURIComponent(nodeId)}`, { name });
127
127
  }
128
128
 
@@ -132,7 +132,7 @@ export async function moveFsNode(
132
132
  parentId = "",
133
133
  ): Promise<FsNode> {
134
134
  const nodeId = id.trim();
135
- if (!nodeId) throw new LeisureSaasHttpError(400, "id is required");
135
+ if (!nodeId) throw PlatformError.fromHttp(400, "id is required");
136
136
  const body: Record<string, string> = {};
137
137
  if (parentId.trim()) body.parent_id = parentId.trim();
138
138
  return driveRequest<FsNode>(ctx, "POST", `/fs/nodes/${encodeURIComponent(nodeId)}/move`, body);
@@ -144,7 +144,7 @@ export async function deleteFsNode(
144
144
  recursive = false,
145
145
  ): Promise<void> {
146
146
  const nodeId = id.trim();
147
- if (!nodeId) throw new LeisureSaasHttpError(400, "id is required");
147
+ if (!nodeId) throw PlatformError.fromHttp(400, "id is required");
148
148
  let path = `/fs/nodes/${encodeURIComponent(nodeId)}`;
149
149
  if (recursive) path += "?recursive=true";
150
150
  await driveRequest(ctx, "DELETE", path);
@@ -166,7 +166,7 @@ export async function createFsUploadSession(
166
166
 
167
167
  export async function finishFsUploadSession(ctx: DriveRequestContext, nodeId: string): Promise<FsNode> {
168
168
  const id = nodeId.trim();
169
- if (!id) throw new LeisureSaasHttpError(400, "node id is required");
169
+ if (!id) throw PlatformError.fromHttp(400, "node id is required");
170
170
  return driveRequest<FsNode>(ctx, "POST", `/fs/files/upload-session/${encodeURIComponent(id)}/finish`, {});
171
171
  }
172
172
 
@@ -176,7 +176,7 @@ export async function createFsContentURL(
176
176
  input?: { intent?: FsContentURLIntent; ttlSeconds?: number },
177
177
  ): Promise<FsContentURLResult> {
178
178
  const nodeId = id.trim();
179
- if (!nodeId) throw new LeisureSaasHttpError(400, "id is required");
179
+ if (!nodeId) throw PlatformError.fromHttp(400, "id is required");
180
180
  const body: Record<string, unknown> = {};
181
181
  if (input?.intent) body.intent = input.intent;
182
182
  if (input?.ttlSeconds && input.ttlSeconds > 0) body.ttl_seconds = input.ttlSeconds;
@@ -268,10 +268,10 @@ export async function putFsUploadURL(
268
268
  resolve();
269
269
  return;
270
270
  }
271
- reject(new LeisureSaasHttpError(xhr.status, (xhr.responseText || "upload PUT failed").trim()));
271
+ reject(PlatformError.fromHttp(xhr.status, (xhr.responseText || "upload PUT failed").trim()));
272
272
  };
273
- xhr.onerror = () => reject(new LeisureSaasHttpError(0, "upload PUT network error"));
274
- xhr.onabort = () => reject(new LeisureSaasHttpError(0, "upload PUT aborted"));
273
+ xhr.onerror = () => reject(PlatformError.fromHttp(0, "upload PUT network error"));
274
+ xhr.onabort = () => reject(PlatformError.fromHttp(0, "upload PUT aborted"));
275
275
  progress.report(0, { phase: "put" });
276
276
  xhr.send(asUploadBody(body) as XMLHttpRequestBodyInit);
277
277
  });
@@ -287,14 +287,14 @@ export async function putFsUploadURL(
287
287
  redirect: "manual",
288
288
  });
289
289
  if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
290
- throw new LeisureSaasHttpError(
290
+ throw PlatformError.fromHttp(
291
291
  res.status || 0,
292
292
  "upload PUT redirected; set object_store public/client endpoint to the final S3 API host with no redirects",
293
293
  );
294
294
  }
295
295
  if (!res.ok) {
296
296
  const text = await res.text().catch(() => "");
297
- throw new LeisureSaasHttpError(res.status, text.trim() || "upload PUT failed");
297
+ throw PlatformError.fromHttp(res.status, text.trim() || "upload PUT failed");
298
298
  }
299
299
  progress.report(total > 0 ? total : 1, { complete: true, phase: "storing" });
300
300
  }
@@ -316,10 +316,10 @@ export async function uploadFsFile(
316
316
  },
317
317
  ): Promise<FsNode> {
318
318
  if (input.size <= 0) {
319
- throw new LeisureSaasHttpError(400, "size must be positive");
319
+ throw PlatformError.fromHttp(400, "size must be positive");
320
320
  }
321
321
  if (input.size > DRIVE_UPLOAD_MAX_AUTO_PUT_BYTES) {
322
- throw new LeisureSaasHttpError(
322
+ throw PlatformError.fromHttp(
323
323
  400,
324
324
  `body exceeds max auto-PUT size (${DRIVE_UPLOAD_MAX_AUTO_PUT_BYTES} bytes)`,
325
325
  );
package/src/errors.ts CHANGED
@@ -1,11 +1,137 @@
1
- export class LeisureSaasHttpError extends Error {
1
+ /**
2
+ * Platform API errors: parse gateway/service JSON
3
+ * `{ code, message, domain?, reason? }` into a typed Error.
4
+ */
5
+
6
+ export const ErrorReason = {
7
+ PermissionDenied: "PERMISSION_DENIED",
8
+ InvalidArgument: "INVALID_ARGUMENT",
9
+ NotFound: "NOT_FOUND",
10
+ RateLimited: "RATE_LIMITED",
11
+ PublishableKeyRequired: "PUBLISHABLE_KEY_REQUIRED",
12
+ PublishableKeyInvalid: "PUBLISHABLE_KEY_INVALID",
13
+ PublishableKeyDisabled: "PUBLISHABLE_KEY_DISABLED",
14
+ OAuthEmailAlreadyExists: "OAUTH_EMAIL_ALREADY_EXISTS",
15
+ OAuthGoogleTokenInvalid: "OAUTH_GOOGLE_TOKEN_INVALID",
16
+ OAuthAppleTokenInvalid: "OAUTH_APPLE_TOKEN_INVALID",
17
+ SocialLoginDisabled: "SOCIAL_LOGIN_DISABLED",
18
+ InvalidCredentials: "INVALID_CREDENTIALS",
19
+ EmailAlreadyExists: "EMAIL_ALREADY_EXISTS",
20
+ EmailNotVerified: "EMAIL_NOT_VERIFIED",
21
+ Network: "NETWORK",
22
+ Unknown: "UNKNOWN",
23
+ } as const;
24
+
25
+ export type ErrorReasonCode = (typeof ErrorReason)[keyof typeof ErrorReason];
26
+
27
+ type PlatformErrorInit = {
28
+ reason: string;
29
+ code: string;
30
+ statusCode: number;
31
+ message: string;
32
+ domain?: string;
33
+ rawBody?: string;
34
+ };
35
+
36
+ /**
37
+ * Typed failure from platform HTTP APIs.
38
+ * Prefer `isReason(err, ErrorReason.…)` over parsing `rawBody`.
39
+ */
40
+ export class PlatformError extends Error {
41
+ readonly reason: string;
42
+ readonly code: string;
2
43
  readonly statusCode: number;
3
- readonly body: string;
44
+ readonly domain?: string;
45
+ readonly rawBody: string;
46
+
47
+ constructor(init: PlatformErrorInit) {
48
+ super(init.message || init.reason || `HTTP ${init.statusCode}`);
49
+ this.name = "PlatformError";
50
+ this.reason = init.reason;
51
+ this.code = init.code;
52
+ this.statusCode = init.statusCode;
53
+ this.domain = init.domain;
54
+ this.rawBody = init.rawBody ?? "";
55
+ }
56
+
57
+ /** Raw response body (compat with older HttpError wrappers). */
58
+ get body(): string {
59
+ return this.rawBody;
60
+ }
61
+
62
+ static fromHttp(statusCode: number, body: string): PlatformError {
63
+ const raw = (body ?? "").trim();
64
+ let code = "";
65
+ let message = raw;
66
+ let domain: string | undefined;
67
+ let reason = "";
68
+
69
+ if (raw) {
70
+ try {
71
+ const json = JSON.parse(raw) as {
72
+ code?: string;
73
+ message?: string;
74
+ domain?: string;
75
+ reason?: string;
76
+ error?: { code?: string; message?: string; domain?: string; reason?: string };
77
+ };
78
+ const nested = json.error;
79
+ code = String(json.code ?? nested?.code ?? "").trim();
80
+ message = String(json.message ?? nested?.message ?? raw).trim() || raw;
81
+ domain = String(json.domain ?? nested?.domain ?? "").trim() || undefined;
82
+ reason = String(json.reason ?? nested?.reason ?? "").trim();
83
+ } catch {
84
+ /* keep raw message */
85
+ }
86
+ }
4
87
 
88
+ if (!reason) {
89
+ reason = statusCode > 0 ? ErrorReason.Unknown : ErrorReason.Network;
90
+ }
91
+ if (!code) {
92
+ code = statusCode > 0 ? "unknown" : "unavailable";
93
+ }
94
+ if (!message) {
95
+ message = statusCode > 0 ? `HTTP ${statusCode}` : "network error";
96
+ }
97
+
98
+ return new PlatformError({
99
+ reason,
100
+ code,
101
+ statusCode,
102
+ message,
103
+ domain,
104
+ rawBody: raw,
105
+ });
106
+ }
107
+ }
108
+
109
+ /**
110
+ * @deprecated Use {@link PlatformError}. Kept for instanceof / constructor compat.
111
+ */
112
+ export class LeisureSaasHttpError extends PlatformError {
5
113
  constructor(statusCode: number, body: string) {
6
- super(body || `HTTP ${statusCode}`);
114
+ const parsed = PlatformError.fromHttp(statusCode, body);
115
+ super({
116
+ reason: parsed.reason,
117
+ code: parsed.code,
118
+ statusCode: parsed.statusCode,
119
+ message: parsed.message,
120
+ domain: parsed.domain,
121
+ rawBody: parsed.rawBody,
122
+ });
7
123
  this.name = "LeisureSaasHttpError";
8
- this.statusCode = statusCode;
9
- this.body = body;
10
124
  }
11
125
  }
126
+
127
+ export function isPlatformError(err: unknown): err is PlatformError {
128
+ return err instanceof PlatformError;
129
+ }
130
+
131
+ export function isReason(err: unknown, reason: string): boolean {
132
+ return isPlatformError(err) && err.reason === reason;
133
+ }
134
+
135
+ export function throwHttpError(statusCode: number, body: string): never {
136
+ throw PlatformError.fromHttp(statusCode, body);
137
+ }
package/src/index.ts CHANGED
@@ -101,6 +101,21 @@ export { getPublicAdsFeed, recordPublicAdEvents } from "./public-ads";
101
101
  export type { PublicAdsRequestContext } from "./public-ads";
102
102
  export { getPublicAppConfig } from "./public-app-config";
103
103
  export type { AppConfigResponse, PublicAppConfigRequestContext } from "./public-app-config";
104
+ export {
105
+ getSocialLoginStatus,
106
+ prepareSocialLogin,
107
+ signInWithApple,
108
+ signInWithGoogle,
109
+ SocialLoginCancelled,
110
+ SocialLoginNeedsLink,
111
+ SocialLoginNotEnabled,
112
+ SocialLoginUnsupported,
113
+ } from "./social-login";
114
+ export type {
115
+ SignInWithAppleOptions,
116
+ SignInWithGoogleOptions,
117
+ SocialLoginStatus,
118
+ } from "./social-login";
104
119
  export {
105
120
  DRIVE_UPLOAD_MAX_AUTO_PUT_BYTES,
106
121
  listFsNodes,
@@ -155,7 +170,14 @@ export {
155
170
  export type { OAuthTokenResponse } from "./auth-session";
156
171
  export { buildEnablePushRegistration, fetchNativeDevicePushToken } from "./push";
157
172
  export { devAppleSignedTransaction, devDeviceToken, devGooglePurchaseToken } from "./dev";
158
- export { LeisureSaasHttpError } from "./errors";
173
+ export {
174
+ PlatformError,
175
+ LeisureSaasHttpError,
176
+ ErrorReason,
177
+ isPlatformError,
178
+ isReason,
179
+ } from "./errors";
180
+ export type { ErrorReasonCode } from "./errors";
159
181
  export { mobilePlatform, adsSurfaceKey, adsSurfaceHeaders } from "./platform";
160
182
  export { appBundleId } from "./ads/bundle-id";
161
183
  export type {
@@ -1,4 +1,4 @@
1
- import { LeisureSaasHttpError } from "./errors";
1
+ import { PlatformError } from "./errors";
2
2
  import { resolveGatewayUrlFromEnv } from "./gateway-url";
3
3
 
4
4
  const DISCOVERY_PLATFORM_API_KEY = "leisuresaas_platform_api_base";
@@ -23,7 +23,7 @@ export async function fetchPlatformApiBase(issuer: string): Promise<string> {
23
23
  });
24
24
  const text = await res.text();
25
25
  if (!res.ok) {
26
- throw new LeisureSaasHttpError(res.status, text.trim());
26
+ throw PlatformError.fromHttp(res.status, text.trim());
27
27
  }
28
28
  let doc: Record<string, unknown>;
29
29
  try {
package/src/public-ads.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { LeisureSaasHttpError } from "./errors";
1
+ import { PlatformError } from "./errors";
2
2
  import { adsSurfaceKey } from "./platform";
3
3
  import { applyPublishableKeyHeaders } from "./publishable-key";
4
4
  import type { AdEventInput, AdsFeedResponse, MobilePlatform } from "./types";
@@ -60,7 +60,7 @@ async function publicAdsRequest<T>(
60
60
  const res = await fetch(url, { method, headers, body: payload });
61
61
  const text = await res.text();
62
62
  if (!res.ok) {
63
- throw new LeisureSaasHttpError(res.status, text.trim());
63
+ throw PlatformError.fromHttp(res.status, text.trim());
64
64
  }
65
65
  if (!text) {
66
66
  return {} as T;
@@ -1,4 +1,4 @@
1
- import { LeisureSaasHttpError } from "./errors";
1
+ import { PlatformError } from "./errors";
2
2
  import { mobilePlatform } from "./platform";
3
3
  import { applyPublishableKeyHeaders } from "./publishable-key";
4
4
  import type { MobilePlatform } from "./types";
@@ -98,7 +98,7 @@ export async function getPublicAppConfig(
98
98
  const res = await fetch(url, { method: "GET", headers });
99
99
  const text = await res.text();
100
100
  if (!res.ok) {
101
- throw new LeisureSaasHttpError(res.status, text.trim());
101
+ throw PlatformError.fromHttp(res.status, text.trim());
102
102
  }
103
103
  const body = JSON.parse(text) as AppConfigResponse;
104
104
  const links = body.links ?? { support_url: "", terms_url: "", privacy_url: "" };
@@ -2,7 +2,7 @@ import * as AuthSession from "expo-auth-session";
2
2
  import * as WebBrowser from "expo-web-browser";
3
3
 
4
4
  import { exchangeAuthorizationCode } from "./auth-session";
5
- import { LeisureSaasHttpError } from "./errors";
5
+ import { PlatformError } from "./errors";
6
6
  import { mobilePlatform } from "./platform";
7
7
  import { applyPublishableKeyHeaders } from "./publishable-key";
8
8
  import type { MobilePlatform } from "./types";
@@ -76,7 +76,7 @@ async function publicAuthRequest<T>(
76
76
  });
77
77
  const text = await res.text();
78
78
  if (!res.ok) {
79
- throw new LeisureSaasHttpError(res.status, text.trim());
79
+ throw PlatformError.fromHttp(res.status, text.trim());
80
80
  }
81
81
  if (!text) {
82
82
  return {} as T;
@@ -87,7 +87,7 @@ async function publicAuthRequest<T>(
87
87
  function tokensFromJSON(data: TokenJSON): AuthTokens {
88
88
  const accessToken = data.access_token?.trim() ?? "";
89
89
  if (!accessToken) {
90
- throw new LeisureSaasHttpError(502, "missing access_token");
90
+ throw PlatformError.fromHttp(502, "missing access_token");
91
91
  }
92
92
  return {
93
93
  accessToken,
@@ -225,7 +225,7 @@ export async function startPlatformAuthorize(
225
225
  });
226
226
  const url = resp.authorization_url?.trim() ?? "";
227
227
  if (!url) {
228
- throw new LeisureSaasHttpError(502, "missing authorization_url");
228
+ throw PlatformError.fromHttp(502, "missing authorization_url");
229
229
  }
230
230
  return url;
231
231
  }
@@ -283,7 +283,7 @@ export async function loginWithPlatformAccount(
283
283
  const challenge = request.codeChallenge?.trim() ?? "";
284
284
  const verifier = request.codeVerifier?.trim() ?? "";
285
285
  if (!challenge || !verifier) {
286
- throw new LeisureSaasHttpError(500, "pkce challenge was not created");
286
+ throw PlatformError.fromHttp(500, "pkce challenge was not created");
287
287
  }
288
288
 
289
289
  const authorizationURL = await startPlatformAuthorize(ctx, {
@@ -291,12 +291,12 @@ export async function loginWithPlatformAccount(
291
291
  });
292
292
  const result = await WebBrowser.openAuthSessionAsync(authorizationURL, input.redirectUri);
293
293
  if (result.type !== "success") {
294
- throw new LeisureSaasHttpError(401, "platform login cancelled");
294
+ throw PlatformError.fromHttp(401, "platform login cancelled");
295
295
  }
296
296
  const redirected = new URL(result.url);
297
297
  const code = redirected.searchParams.get("code")?.trim() ?? "";
298
298
  if (!code) {
299
- throw new LeisureSaasHttpError(401, "platform login returned no code");
299
+ throw PlatformError.fromHttp(401, "platform login returned no code");
300
300
  }
301
301
  const authorize = new URL(authorizationURL);
302
302
  const clientId = authorize.searchParams.get("client_id")?.trim() ?? "";
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Headless Google / Apple sign-in for React Native.
3
+ * No LeisureSaas UI — call from the product's own Pressable handlers.
4
+ *
5
+ * Optional peers:
6
+ * - `@react-native-google-signin/google-signin` (Google)
7
+ * - `expo-apple-authentication` (Apple, iOS)
8
+ */
9
+
10
+ import { Platform } from "react-native";
11
+
12
+ import { getPublicAppConfig } from "./public-app-config";
13
+ import {
14
+ loginWithApple,
15
+ loginWithGoogle,
16
+ type AuthTokens,
17
+ type PublicAuthContext,
18
+ } from "./public-auth";
19
+ import { ErrorReason, isPlatformError, isReason } from "./errors";
20
+ import { appBundleId } from "./ads/bundle-id";
21
+
22
+
23
+ export class SocialLoginNotEnabled extends Error {
24
+ readonly provider: "google" | "apple";
25
+ constructor(provider: "google" | "apple", message?: string) {
26
+ super(message ?? `${provider} sign-in is not enabled`);
27
+ this.name = "SocialLoginNotEnabled";
28
+ this.provider = provider;
29
+ }
30
+ }
31
+
32
+ export class SocialLoginCancelled extends Error {
33
+ readonly provider: "google" | "apple";
34
+ constructor(provider: "google" | "apple", message?: string) {
35
+ super(message ?? `${provider} sign-in cancelled`);
36
+ this.name = "SocialLoginCancelled";
37
+ this.provider = provider;
38
+ }
39
+ }
40
+
41
+ export class SocialLoginUnsupported extends Error {
42
+ constructor(message: string) {
43
+ super(message);
44
+ this.name = "SocialLoginUnsupported";
45
+ }
46
+ }
47
+
48
+ export class SocialLoginNeedsLink extends Error {
49
+ readonly provider: "google" | "apple";
50
+ readonly pending: {
51
+ identityToken?: string;
52
+ authorizationCode?: string;
53
+ fullName?: string;
54
+ };
55
+ constructor(
56
+ provider: "google" | "apple",
57
+ pending: SocialLoginNeedsLink["pending"] = {},
58
+ message?: string,
59
+ ) {
60
+ super(message ?? "Email already registered; provide password to link");
61
+ this.name = "SocialLoginNeedsLink";
62
+ this.provider = provider;
63
+ this.pending = pending;
64
+ }
65
+ }
66
+
67
+ function isOAuthEmailAlreadyExistsError(err: unknown): boolean {
68
+ if (isReason(err, ErrorReason.OAuthEmailAlreadyExists)) {
69
+ return true;
70
+ }
71
+ if (!isPlatformError(err)) {
72
+ return false;
73
+ }
74
+ return err.rawBody.includes("OAUTH_EMAIL_ALREADY_EXISTS");
75
+ }
76
+
77
+ export type SocialLoginStatus = {
78
+ google: { enabled: boolean; webClientId: string; iosClientId: string };
79
+ apple: { enabled: boolean; servicesId: string; bundleIds: string[] };
80
+ };
81
+
82
+ let statusCache: { key: string; at: number; value: SocialLoginStatus } | null = null;
83
+ const STATUS_TTL_MS = 60_000;
84
+
85
+ function cacheKey(ctx: PublicAuthContext): string {
86
+ return `${ctx.gatewayUrl}|${ctx.publishableKey}|${ctx.platform ?? ""}|${ctx.bundleId ?? ""}`;
87
+ }
88
+
89
+ export async function getSocialLoginStatus(
90
+ ctx: PublicAuthContext,
91
+ opts: { fresh?: boolean; locale?: string; appVersion?: string } = {},
92
+ ): Promise<SocialLoginStatus> {
93
+ const key = cacheKey(ctx);
94
+ if (!opts.fresh && statusCache && statusCache.key === key && Date.now() - statusCache.at < STATUS_TTL_MS) {
95
+ return statusCache.value;
96
+ }
97
+ const cfg = await getPublicAppConfig(
98
+ {
99
+ gatewayUrl: ctx.gatewayUrl,
100
+ publishableKey: ctx.publishableKey,
101
+ platform: ctx.platform,
102
+ bundleId: ctx.bundleId,
103
+ origin: ctx.origin,
104
+ locale: opts.locale,
105
+ },
106
+ {
107
+ fresh: opts.fresh,
108
+ appVersion: opts.appVersion ?? "0.0.0",
109
+ },
110
+ );
111
+ const g = cfg.social_login?.google;
112
+ const a = cfg.social_login?.apple;
113
+ const value: SocialLoginStatus = {
114
+ google: {
115
+ enabled: Boolean(g?.enabled && g.web_client_id?.trim()),
116
+ webClientId: g?.web_client_id?.trim() ?? "",
117
+ iosClientId: g?.ios_client_id?.trim() ?? "",
118
+ },
119
+ apple: {
120
+ enabled: Boolean(a?.enabled && (a.services_id?.trim() || (a.bundle_ids?.length ?? 0) > 0)),
121
+ servicesId: a?.services_id?.trim() ?? "",
122
+ bundleIds: Array.isArray(a?.bundle_ids) ? a!.bundle_ids!.map((x) => String(x).trim()).filter(Boolean) : [],
123
+ },
124
+ };
125
+ statusCache = { key, at: Date.now(), value };
126
+ return value;
127
+ }
128
+
129
+ /** Prefetch App Config (no native UI). */
130
+ export async function prepareSocialLogin(
131
+ ctx: PublicAuthContext,
132
+ opts: { locale?: string; appVersion?: string } = {},
133
+ ): Promise<SocialLoginStatus> {
134
+ return getSocialLoginStatus(ctx, opts);
135
+ }
136
+
137
+ async function loadGoogleSigninModule(): Promise<{
138
+ GoogleSignin: {
139
+ configure: (opts: { webClientId: string; iosClientId?: string; offlineAccess?: boolean }) => void;
140
+ hasPlayServices: (opts?: { showPlayServicesUpdateDialog?: boolean }) => Promise<boolean>;
141
+ signIn: () => Promise<{ data?: { idToken?: string | null } | null; type?: string } | { idToken?: string | null }>;
142
+ };
143
+ statusCodes?: { SIGN_IN_CANCELLED?: string | number; IN_PROGRESS?: string | number };
144
+ }> {
145
+ try {
146
+ // Optional peer — resolved at runtime by the app.
147
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
148
+ return require("@react-native-google-signin/google-signin") as never;
149
+ } catch {
150
+ throw new SocialLoginUnsupported(
151
+ "Install peer @react-native-google-signin/google-signin to use signInWithGoogle",
152
+ );
153
+ }
154
+ }
155
+
156
+ async function loadAppleAuthModule(): Promise<{
157
+ isAvailableAsync: () => Promise<boolean>;
158
+ signInAsync: (opts: { requestedScopes: number[] }) => Promise<{
159
+ identityToken: string | null;
160
+ authorizationCode: string | null;
161
+ fullName?: { givenName?: string | null; familyName?: string | null } | null;
162
+ }>;
163
+ AppleAuthenticationScope: { FULL_NAME: number; EMAIL: number };
164
+ }> {
165
+ try {
166
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
167
+ return require("expo-apple-authentication") as never;
168
+ } catch {
169
+ throw new SocialLoginUnsupported(
170
+ "Install peer expo-apple-authentication to use signInWithApple",
171
+ );
172
+ }
173
+ }
174
+
175
+ export type SignInWithGoogleOptions = {
176
+ password?: string;
177
+ locale?: string;
178
+ appVersion?: string;
179
+ };
180
+
181
+ export async function signInWithGoogle(
182
+ ctx: PublicAuthContext,
183
+ opts: SignInWithGoogleOptions = {},
184
+ ): Promise<AuthTokens> {
185
+ const status = await getSocialLoginStatus(ctx, { locale: opts.locale, appVersion: opts.appVersion });
186
+ if (!status.google.enabled || !status.google.webClientId) {
187
+ throw new SocialLoginNotEnabled("google");
188
+ }
189
+
190
+ const mod = await loadGoogleSigninModule();
191
+ const { GoogleSignin, statusCodes } = mod;
192
+ GoogleSignin.configure({
193
+ webClientId: status.google.webClientId,
194
+ iosClientId: status.google.iosClientId || undefined,
195
+ offlineAccess: false,
196
+ });
197
+
198
+ if (Platform.OS === "android") {
199
+ await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true });
200
+ }
201
+
202
+ let idToken = "";
203
+ try {
204
+ const result = (await GoogleSignin.signIn()) as {
205
+ type?: string;
206
+ data?: { idToken?: string | null } | null;
207
+ idToken?: string | null;
208
+ };
209
+ if (result.type === "cancelled" || result.type === "noSavedCredentialFound") {
210
+ throw new SocialLoginCancelled("google");
211
+ }
212
+ idToken = (result.data?.idToken ?? result.idToken)?.trim() ?? "";
213
+ } catch (err) {
214
+ if (err instanceof SocialLoginCancelled) {
215
+ throw err;
216
+ }
217
+ const code = (err as { code?: string | number })?.code;
218
+ if (statusCodes?.SIGN_IN_CANCELLED != null && code === statusCodes.SIGN_IN_CANCELLED) {
219
+ throw new SocialLoginCancelled("google");
220
+ }
221
+ throw err;
222
+ }
223
+ if (!idToken) {
224
+ throw new Error("Google id_token missing");
225
+ }
226
+
227
+ try {
228
+ return await loginWithGoogle(ctx, {
229
+ idToken,
230
+ password: opts.password,
231
+ locale: opts.locale,
232
+ });
233
+ } catch (err) {
234
+ if (isOAuthEmailAlreadyExistsError(err)) {
235
+ throw new SocialLoginNeedsLink("google");
236
+ }
237
+ throw err;
238
+ }
239
+ }
240
+
241
+ export type SignInWithAppleOptions = {
242
+ password?: string;
243
+ locale?: string;
244
+ appVersion?: string;
245
+ identityToken?: string;
246
+ authorizationCode?: string;
247
+ fullName?: string;
248
+ };
249
+
250
+ export async function signInWithApple(
251
+ ctx: PublicAuthContext,
252
+ opts: SignInWithAppleOptions = {},
253
+ ): Promise<AuthTokens> {
254
+ if (Platform.OS !== "ios" && !opts.identityToken) {
255
+ throw new SocialLoginUnsupported("signInWithApple native UI is only available on iOS");
256
+ }
257
+
258
+ const status = await getSocialLoginStatus(ctx, { locale: opts.locale, appVersion: opts.appVersion });
259
+ if (!status.apple.enabled) {
260
+ throw new SocialLoginNotEnabled("apple");
261
+ }
262
+
263
+ const bundle = (ctx.bundleId?.trim() || appBundleId() || "").trim();
264
+ if (bundle && status.apple.bundleIds.length > 0 && !status.apple.bundleIds.includes(bundle)) {
265
+ // Soft warning path: still attempt; server validates aud.
266
+ }
267
+
268
+ let identityToken = opts.identityToken?.trim() ?? "";
269
+ let authorizationCode = opts.authorizationCode?.trim() ?? "";
270
+ let fullName = opts.fullName?.trim() ?? "";
271
+
272
+ if (!identityToken) {
273
+ const AppleAuthentication = await loadAppleAuthModule();
274
+ const available = await AppleAuthentication.isAvailableAsync();
275
+ if (!available) {
276
+ throw new SocialLoginUnsupported("Sign in with Apple is not available on this device");
277
+ }
278
+ try {
279
+ const cred = await AppleAuthentication.signInAsync({
280
+ requestedScopes: [
281
+ AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
282
+ AppleAuthentication.AppleAuthenticationScope.EMAIL,
283
+ ],
284
+ });
285
+ identityToken = cred.identityToken?.trim() ?? "";
286
+ authorizationCode = cred.authorizationCode?.trim() ?? "";
287
+ const first = cred.fullName?.givenName?.trim() ?? "";
288
+ const last = cred.fullName?.familyName?.trim() ?? "";
289
+ fullName = [first, last].filter(Boolean).join(" ");
290
+ } catch (err) {
291
+ const code = (err as { code?: string })?.code;
292
+ if (code === "ERR_REQUEST_CANCELED" || code === "ERR_CANCELED") {
293
+ throw new SocialLoginCancelled("apple");
294
+ }
295
+ throw err;
296
+ }
297
+ }
298
+
299
+ if (!identityToken) {
300
+ throw new Error("Apple identity token missing");
301
+ }
302
+
303
+ try {
304
+ return await loginWithApple(ctx, {
305
+ identityToken,
306
+ authorizationCode: authorizationCode || undefined,
307
+ fullName: fullName || undefined,
308
+ password: opts.password,
309
+ locale: opts.locale,
310
+ });
311
+ } catch (err) {
312
+ if (isOAuthEmailAlreadyExistsError(err)) {
313
+ throw new SocialLoginNeedsLink("apple", { identityToken, authorizationCode, fullName });
314
+ }
315
+ throw err;
316
+ }
317
+ }