@leisuresaas/react-native 0.6.3-dev.6 → 0.6.4-dev.2

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.6",
3
+ "version": "0.6.4-dev.2",
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": {
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,146 @@
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
+ // Workspaces, seats and billing (returned by the product BFF).
22
+ TenantForbidden: "TENANT_FORBIDDEN",
23
+ TenantInviteInvalid: "TENANT_INVITE_INVALID",
24
+ InviteTargetMismatch: "INVITE_TARGET_MISMATCH",
25
+ ProductSeatNotFound: "PRODUCT_SEAT_NOT_FOUND",
26
+ OwnerProductSeatProtected: "OWNER_PRODUCT_SEAT_PROTECTED",
27
+ FallbackPlanMissing: "FALLBACK_PLAN_MISSING",
28
+ WorkspaceHasMembers: "WORKSPACE_HAS_MEMBERS",
29
+ SubscriptionActiveOtherSource: "SUBSCRIPTION_ACTIVE_OTHER_SOURCE",
30
+ Network: "NETWORK",
31
+ Unknown: "UNKNOWN",
32
+ } as const;
33
+
34
+ export type ErrorReasonCode = (typeof ErrorReason)[keyof typeof ErrorReason];
35
+
36
+ type PlatformErrorInit = {
37
+ reason: string;
38
+ code: string;
39
+ statusCode: number;
40
+ message: string;
41
+ domain?: string;
42
+ rawBody?: string;
43
+ };
44
+
45
+ /**
46
+ * Typed failure from platform HTTP APIs.
47
+ * Prefer `isReason(err, ErrorReason.…)` over parsing `rawBody`.
48
+ */
49
+ export class PlatformError extends Error {
50
+ readonly reason: string;
51
+ readonly code: string;
2
52
  readonly statusCode: number;
3
- readonly body: string;
53
+ readonly domain?: string;
54
+ readonly rawBody: string;
55
+
56
+ constructor(init: PlatformErrorInit) {
57
+ super(init.message || init.reason || `HTTP ${init.statusCode}`);
58
+ this.name = "PlatformError";
59
+ this.reason = init.reason;
60
+ this.code = init.code;
61
+ this.statusCode = init.statusCode;
62
+ this.domain = init.domain;
63
+ this.rawBody = init.rawBody ?? "";
64
+ }
65
+
66
+ /** Raw response body (compat with older HttpError wrappers). */
67
+ get body(): string {
68
+ return this.rawBody;
69
+ }
70
+
71
+ static fromHttp(statusCode: number, body: string): PlatformError {
72
+ const raw = (body ?? "").trim();
73
+ let code = "";
74
+ let message = raw;
75
+ let domain: string | undefined;
76
+ let reason = "";
77
+
78
+ if (raw) {
79
+ try {
80
+ const json = JSON.parse(raw) as {
81
+ code?: string;
82
+ message?: string;
83
+ domain?: string;
84
+ reason?: string;
85
+ error?: { code?: string; message?: string; domain?: string; reason?: string };
86
+ };
87
+ const nested = json.error;
88
+ code = String(json.code ?? nested?.code ?? "").trim();
89
+ message = String(json.message ?? nested?.message ?? raw).trim() || raw;
90
+ domain = String(json.domain ?? nested?.domain ?? "").trim() || undefined;
91
+ reason = String(json.reason ?? nested?.reason ?? "").trim();
92
+ } catch {
93
+ /* keep raw message */
94
+ }
95
+ }
4
96
 
97
+ if (!reason) {
98
+ reason = statusCode > 0 ? ErrorReason.Unknown : ErrorReason.Network;
99
+ }
100
+ if (!code) {
101
+ code = statusCode > 0 ? "unknown" : "unavailable";
102
+ }
103
+ if (!message) {
104
+ message = statusCode > 0 ? `HTTP ${statusCode}` : "network error";
105
+ }
106
+
107
+ return new PlatformError({
108
+ reason,
109
+ code,
110
+ statusCode,
111
+ message,
112
+ domain,
113
+ rawBody: raw,
114
+ });
115
+ }
116
+ }
117
+
118
+ /**
119
+ * @deprecated Use {@link PlatformError}. Kept for instanceof / constructor compat.
120
+ */
121
+ export class LeisureSaasHttpError extends PlatformError {
5
122
  constructor(statusCode: number, body: string) {
6
- super(body || `HTTP ${statusCode}`);
123
+ const parsed = PlatformError.fromHttp(statusCode, body);
124
+ super({
125
+ reason: parsed.reason,
126
+ code: parsed.code,
127
+ statusCode: parsed.statusCode,
128
+ message: parsed.message,
129
+ domain: parsed.domain,
130
+ rawBody: parsed.rawBody,
131
+ });
7
132
  this.name = "LeisureSaasHttpError";
8
- this.statusCode = statusCode;
9
- this.body = body;
10
133
  }
11
134
  }
135
+
136
+ export function isPlatformError(err: unknown): err is PlatformError {
137
+ return err instanceof PlatformError;
138
+ }
139
+
140
+ export function isReason(err: unknown, reason: string): boolean {
141
+ return isPlatformError(err) && err.reason === reason;
142
+ }
143
+
144
+ export function throwHttpError(statusCode: number, body: string): never {
145
+ throw PlatformError.fromHttp(statusCode, body);
146
+ }
package/src/index.ts CHANGED
@@ -170,7 +170,14 @@ export {
170
170
  export type { OAuthTokenResponse } from "./auth-session";
171
171
  export { buildEnablePushRegistration, fetchNativeDevicePushToken } from "./push";
172
172
  export { devAppleSignedTransaction, devDeviceToken, devGooglePurchaseToken } from "./dev";
173
- 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";
174
181
  export { mobilePlatform, adsSurfaceKey, adsSurfaceHeaders } from "./platform";
175
182
  export { appBundleId } from "./ads/bundle-id";
176
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() ?? "";
@@ -16,9 +16,10 @@ import {
16
16
  type AuthTokens,
17
17
  type PublicAuthContext,
18
18
  } from "./public-auth";
19
- import { LeisureSaasHttpError } from "./errors";
19
+ import { ErrorReason, isPlatformError, isReason } from "./errors";
20
20
  import { appBundleId } from "./ads/bundle-id";
21
21
 
22
+
22
23
  export class SocialLoginNotEnabled extends Error {
23
24
  readonly provider: "google" | "apple";
24
25
  constructor(provider: "google" | "apple", message?: string) {
@@ -64,15 +65,13 @@ export class SocialLoginNeedsLink extends Error {
64
65
  }
65
66
 
66
67
  function isOAuthEmailAlreadyExistsError(err: unknown): boolean {
67
- if (!(err instanceof LeisureSaasHttpError)) {
68
- return false;
68
+ if (isReason(err, ErrorReason.OAuthEmailAlreadyExists)) {
69
+ return true;
69
70
  }
70
- try {
71
- const body = JSON.parse(err.body) as { reason?: string; error?: { reason?: string } };
72
- return (body.reason ?? body.error?.reason) === "OAUTH_EMAIL_ALREADY_EXISTS";
73
- } catch {
74
- return err.body.includes("OAUTH_EMAIL_ALREADY_EXISTS");
71
+ if (!isPlatformError(err)) {
72
+ return false;
75
73
  }
74
+ return err.rawBody.includes("OAUTH_EMAIL_ALREADY_EXISTS");
76
75
  }
77
76
 
78
77
  export type SocialLoginStatus = {