@fytkit/sdk 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +65 -1
- package/dist/index.d.ts +262 -3
- package/dist/index.js +114 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,13 @@ All notable changes to `@fytkit/sdk` are documented in this file.
|
|
|
4
4
|
Format: [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/).
|
|
5
5
|
Versioning: [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## [0.6.0](https://github.com/cbarlow1993/fytkit-web/compare/@fytkit/sdk@0.5.0...@fytkit/sdk@0.6.0) (2026-07-05)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
### Features
|
|
11
|
+
|
|
12
|
+
* mobile settings/profile APIs — security, preferences, profile fields, billing (+ SDK) ([#118](https://github.com/cbarlow1993/fytkit-web/issues/118)) ([4f607ca](https://github.com/cbarlow1993/fytkit-web/commit/4f607ca2e18e2e46c23617c538a7795051c1359f))
|
|
13
|
+
|
|
7
14
|
## [0.5.0](https://github.com/cbarlow1993/fytkit-web/compare/@fytkit/sdk@0.4.0...@fytkit/sdk@0.5.0) (2026-07-05)
|
|
8
15
|
|
|
9
16
|
|
package/README.md
CHANGED
|
@@ -77,11 +77,75 @@ const { data: prs } = await fytkit.progression.listPrHistory({ exerciseId });
|
|
|
77
77
|
const { data: summary } = await fytkit.progress.getSummary({ period: "12w" });
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
+
## Two-factor sign-in
|
|
81
|
+
|
|
82
|
+
`auth.signIn` returns a discriminated result. When the trainee has 2FA
|
|
83
|
+
enabled, complete the challenge with whichever method they choose:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
const result = await fytkit.auth.signIn({ email, password });
|
|
87
|
+
|
|
88
|
+
if (result.kind === "two_factor_required") {
|
|
89
|
+
const { challenge } = result; // challenge.availableMethods: "totp" | "backup_code" | "email_otp"
|
|
90
|
+
|
|
91
|
+
// TOTP from their authenticator app…
|
|
92
|
+
const session = await fytkit.auth.verifyTotp({ challenge, code: "123456" });
|
|
93
|
+
|
|
94
|
+
// …or a one-time backup code:
|
|
95
|
+
// await fytkit.auth.verifyBackupCode({ challenge, code });
|
|
96
|
+
|
|
97
|
+
// …or an emailed code:
|
|
98
|
+
// await fytkit.auth.requestEmailOtp({ challenge });
|
|
99
|
+
// await fytkit.auth.verifyEmailOtp({ challenge, code });
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Each verify method caches the issued session exactly like a plain sign-in
|
|
104
|
+
(`signed_in` fires on `onAuthStateChange`).
|
|
105
|
+
|
|
106
|
+
## 2FA enrollment & account security
|
|
107
|
+
|
|
108
|
+
All of these require a signed-in session:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
// Enroll: render totpUri as a QR code; show backupCodes exactly once.
|
|
112
|
+
const { totpUri, backupCodes } = await fytkit.auth.enableTotp({ password });
|
|
113
|
+
await fytkit.auth.verifyTotpSetup({ code: "123456" }); // SDK swaps the rotated token for you
|
|
114
|
+
|
|
115
|
+
const status = await fytkit.auth.getSecurityStatus(); // { twoFactorEnabled, totpEnabled, hasBackupCodes }
|
|
116
|
+
await fytkit.auth.regenerateBackupCodes({ password });
|
|
117
|
+
await fytkit.auth.disableTwoFactor({ password });
|
|
118
|
+
|
|
119
|
+
// Password change (verifies the current password server-side). With
|
|
120
|
+
// revokeOtherSessions the SDK adopts the rotated token transparently.
|
|
121
|
+
await fytkit.auth.changePassword({ currentPassword, newPassword, revokeOtherSessions: true });
|
|
122
|
+
|
|
123
|
+
// Email change — a confirmation link is emailed to the new address;
|
|
124
|
+
// nothing changes until the trainee opens it.
|
|
125
|
+
await fytkit.auth.changeEmail({ newEmail });
|
|
126
|
+
|
|
127
|
+
// Devices: revokeId is an opaque id (never the bearer token).
|
|
128
|
+
const sessions = await fytkit.auth.listSessions();
|
|
129
|
+
await fytkit.auth.revokeSession({ revokeId: sessions.find((s) => !s.isCurrent)!.revokeId });
|
|
130
|
+
await fytkit.auth.revokeOtherSessions(); // "sign out of all other devices"
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Notification preferences
|
|
134
|
+
|
|
135
|
+
Per-member toggles stored server-side (defaults apply until first write):
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
const { data: prefs } = await fytkit.preferences.getNotifications();
|
|
139
|
+
await fytkit.preferences.updateNotifications({ streakAlerts: false }); // partial patch
|
|
140
|
+
```
|
|
141
|
+
|
|
80
142
|
## What's included in this preview
|
|
81
143
|
|
|
82
144
|
- `auth.signUp` / `signIn` / `signOut` / `getSession` / `onAuthStateChange`
|
|
83
145
|
- `auth.requestPasswordReset` / `confirmPasswordReset` / `confirmEmail`
|
|
84
|
-
-
|
|
146
|
+
- Two-factor: `auth.verifyTotp` / `verifyBackupCode` / `requestEmailOtp` / `verifyEmailOtp` (sign-in), `enableTotp` / `verifyTotpSetup` / `disableTwoFactor` / `regenerateBackupCodes` / `getSecurityStatus` (management)
|
|
147
|
+
- Account security: `auth.changePassword` / `changeEmail` / `listSessions` / `revokeSession` / `revokeOtherSessions`
|
|
148
|
+
- Data namespaces: `workouts`, `programs`, `recipes`, `nutrition`, `nutritionLog`, `profile`, `preferences`, `articles`, `enrollments`, `sessionLogs`, `progression`, `progress`, `bodyMetrics`, `media`, `appConfig`, `subscription`
|
|
85
149
|
- Workout tracking: program session logs and ad-hoc workout logs (`sessionLogs.create` with `workoutId`), set logging, per-workout history (`sessionLogs.list({ workoutId })`)
|
|
86
150
|
- Progress: `progress.getSummary` / `getAdherence` / `getStreak` (stored streaks), `progression.getPrSummary` / `listPrHistory` (stored PR history) / `getHistory`, `bodyMetrics.list` / `record` / `delete`
|
|
87
151
|
- Automatic header injection (`X-Fytkit-Client-Id`, `Authorization: Bearer …`)
|
package/dist/index.d.ts
CHANGED
|
@@ -101,6 +101,53 @@ export declare interface FytkitClient {
|
|
|
101
101
|
confirmEmail: (input: {
|
|
102
102
|
token: string;
|
|
103
103
|
}) => Promise<void>;
|
|
104
|
+
verifyTotp: (input: {
|
|
105
|
+
challenge: TwoFactorChallenge;
|
|
106
|
+
code: string;
|
|
107
|
+
}) => Promise<Session>;
|
|
108
|
+
verifyBackupCode: (input: {
|
|
109
|
+
challenge: TwoFactorChallenge;
|
|
110
|
+
code: string;
|
|
111
|
+
}) => Promise<Session>;
|
|
112
|
+
requestEmailOtp: (input: {
|
|
113
|
+
challenge: TwoFactorChallenge;
|
|
114
|
+
}) => Promise<void>;
|
|
115
|
+
verifyEmailOtp: (input: {
|
|
116
|
+
challenge: TwoFactorChallenge;
|
|
117
|
+
code: string;
|
|
118
|
+
}) => Promise<Session>;
|
|
119
|
+
getSecurityStatus: () => Promise<SecurityStatus>;
|
|
120
|
+
enableTotp: (input: {
|
|
121
|
+
password: string;
|
|
122
|
+
}) => Promise<TotpEnrollment>;
|
|
123
|
+
/** Completes TOTP enrolment. The server rotates the session on first
|
|
124
|
+
* verification; the SDK swaps its stored token transparently. */
|
|
125
|
+
verifyTotpSetup: (input: {
|
|
126
|
+
code: string;
|
|
127
|
+
}) => Promise<void>;
|
|
128
|
+
disableTwoFactor: (input: {
|
|
129
|
+
password: string;
|
|
130
|
+
}) => Promise<void>;
|
|
131
|
+
regenerateBackupCodes: (input: {
|
|
132
|
+
password: string;
|
|
133
|
+
}) => Promise<readonly string[]>;
|
|
134
|
+
/** With `revokeOtherSessions: true` every other device is signed out and
|
|
135
|
+
* the calling session is rotated — the SDK swaps its stored token. */
|
|
136
|
+
changePassword: (input: {
|
|
137
|
+
currentPassword: string;
|
|
138
|
+
newPassword: string;
|
|
139
|
+
revokeOtherSessions?: boolean;
|
|
140
|
+
}) => Promise<void>;
|
|
141
|
+
/** Starts the verified email-change flow — a confirmation link is emailed
|
|
142
|
+
* to the new address; nothing changes until it is opened. */
|
|
143
|
+
changeEmail: (input: {
|
|
144
|
+
newEmail: string;
|
|
145
|
+
}) => Promise<void>;
|
|
146
|
+
listSessions: () => Promise<readonly SessionInfo[]>;
|
|
147
|
+
revokeSession: (input: {
|
|
148
|
+
revokeId: string;
|
|
149
|
+
}) => Promise<void>;
|
|
150
|
+
revokeOtherSessions: () => Promise<void>;
|
|
104
151
|
};
|
|
105
152
|
readonly workouts: PublicApi["workout"];
|
|
106
153
|
readonly programs: PublicApi["program"];
|
|
@@ -115,6 +162,9 @@ export declare interface FytkitClient {
|
|
|
115
162
|
readonly media: PublicApi["media"];
|
|
116
163
|
readonly appConfig: PublicApi["appConfig"];
|
|
117
164
|
readonly subscription: PublicApi["subscription"];
|
|
165
|
+
readonly profile: PublicApi["profile"];
|
|
166
|
+
readonly nutritionLog: PublicApi["nutritionLog"];
|
|
167
|
+
readonly preferences: PublicApi["preferences"];
|
|
118
168
|
}
|
|
119
169
|
|
|
120
170
|
/** Constructor options for createFytkitClient. */
|
|
@@ -585,6 +635,125 @@ declare const publicRouter: {
|
|
|
585
635
|
hasBackupCodes: ZodBoolean;
|
|
586
636
|
}, $strip>;
|
|
587
637
|
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
638
|
+
changePassword: DecoratedProcedure<MergedInitialContext< {
|
|
639
|
+
headers: Headers;
|
|
640
|
+
} & Record<never, never>, {
|
|
641
|
+
headers: Headers;
|
|
642
|
+
} & Record<never, never>, {
|
|
643
|
+
headers: Headers;
|
|
644
|
+
}>, MergedCurrentContext< {
|
|
645
|
+
headers: Headers;
|
|
646
|
+
}, {
|
|
647
|
+
trainerId: string;
|
|
648
|
+
appId: string;
|
|
649
|
+
clientId: string | undefined;
|
|
650
|
+
hasActiveSubscription: boolean;
|
|
651
|
+
clientEntitlements: ClientEntitlements;
|
|
652
|
+
authMode: "dev-app";
|
|
653
|
+
appAllowedOrigins: readonly string[];
|
|
654
|
+
}>, ZodObject< {
|
|
655
|
+
currentPassword: ZodString;
|
|
656
|
+
newPassword: ZodString;
|
|
657
|
+
revokeOtherSessions: ZodOptional<ZodBoolean>;
|
|
658
|
+
}, $strip>, ZodObject< {
|
|
659
|
+
data: ZodObject< {
|
|
660
|
+
success: ZodLiteral<true>;
|
|
661
|
+
accessToken: ZodString;
|
|
662
|
+
}, $strip>;
|
|
663
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
664
|
+
changeEmail: DecoratedProcedure<MergedInitialContext< {
|
|
665
|
+
headers: Headers;
|
|
666
|
+
} & Record<never, never>, {
|
|
667
|
+
headers: Headers;
|
|
668
|
+
} & Record<never, never>, {
|
|
669
|
+
headers: Headers;
|
|
670
|
+
}>, MergedCurrentContext< {
|
|
671
|
+
headers: Headers;
|
|
672
|
+
}, {
|
|
673
|
+
trainerId: string;
|
|
674
|
+
appId: string;
|
|
675
|
+
clientId: string | undefined;
|
|
676
|
+
hasActiveSubscription: boolean;
|
|
677
|
+
clientEntitlements: ClientEntitlements;
|
|
678
|
+
authMode: "dev-app";
|
|
679
|
+
appAllowedOrigins: readonly string[];
|
|
680
|
+
}>, ZodObject< {
|
|
681
|
+
newEmail: ZodString;
|
|
682
|
+
}, $strip>, ZodObject< {
|
|
683
|
+
data: ZodObject< {
|
|
684
|
+
ok: ZodLiteral<true>;
|
|
685
|
+
}, $strip>;
|
|
686
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
687
|
+
listSessions: DecoratedProcedure<MergedInitialContext< {
|
|
688
|
+
headers: Headers;
|
|
689
|
+
} & Record<never, never>, {
|
|
690
|
+
headers: Headers;
|
|
691
|
+
} & Record<never, never>, {
|
|
692
|
+
headers: Headers;
|
|
693
|
+
}>, MergedCurrentContext< {
|
|
694
|
+
headers: Headers;
|
|
695
|
+
}, {
|
|
696
|
+
trainerId: string;
|
|
697
|
+
appId: string;
|
|
698
|
+
clientId: string | undefined;
|
|
699
|
+
hasActiveSubscription: boolean;
|
|
700
|
+
clientEntitlements: ClientEntitlements;
|
|
701
|
+
authMode: "dev-app";
|
|
702
|
+
appAllowedOrigins: readonly string[];
|
|
703
|
+
}>, ZodOptional<ZodObject< {}, $strip>>, ZodObject< {
|
|
704
|
+
data: ZodArray<ZodObject< {
|
|
705
|
+
revokeId: ZodString;
|
|
706
|
+
createdAt: ZodDate;
|
|
707
|
+
expiresAt: ZodDate;
|
|
708
|
+
ipAddress: ZodNullable<ZodString>;
|
|
709
|
+
userAgent: ZodNullable<ZodString>;
|
|
710
|
+
isCurrent: ZodBoolean;
|
|
711
|
+
}, $strip>>;
|
|
712
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
713
|
+
revokeSession: DecoratedProcedure<MergedInitialContext< {
|
|
714
|
+
headers: Headers;
|
|
715
|
+
} & Record<never, never>, {
|
|
716
|
+
headers: Headers;
|
|
717
|
+
} & Record<never, never>, {
|
|
718
|
+
headers: Headers;
|
|
719
|
+
}>, MergedCurrentContext< {
|
|
720
|
+
headers: Headers;
|
|
721
|
+
}, {
|
|
722
|
+
trainerId: string;
|
|
723
|
+
appId: string;
|
|
724
|
+
clientId: string | undefined;
|
|
725
|
+
hasActiveSubscription: boolean;
|
|
726
|
+
clientEntitlements: ClientEntitlements;
|
|
727
|
+
authMode: "dev-app";
|
|
728
|
+
appAllowedOrigins: readonly string[];
|
|
729
|
+
}>, ZodObject< {
|
|
730
|
+
revokeId: ZodString;
|
|
731
|
+
}, $strip>, ZodObject< {
|
|
732
|
+
data: ZodObject< {
|
|
733
|
+
success: ZodLiteral<true>;
|
|
734
|
+
}, $strip>;
|
|
735
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
736
|
+
revokeOtherSessions: DecoratedProcedure<MergedInitialContext< {
|
|
737
|
+
headers: Headers;
|
|
738
|
+
} & Record<never, never>, {
|
|
739
|
+
headers: Headers;
|
|
740
|
+
} & Record<never, never>, {
|
|
741
|
+
headers: Headers;
|
|
742
|
+
}>, MergedCurrentContext< {
|
|
743
|
+
headers: Headers;
|
|
744
|
+
}, {
|
|
745
|
+
trainerId: string;
|
|
746
|
+
appId: string;
|
|
747
|
+
clientId: string | undefined;
|
|
748
|
+
hasActiveSubscription: boolean;
|
|
749
|
+
clientEntitlements: ClientEntitlements;
|
|
750
|
+
authMode: "dev-app";
|
|
751
|
+
appAllowedOrigins: readonly string[];
|
|
752
|
+
}>, ZodOptional<ZodObject< {}, $strip>>, ZodObject< {
|
|
753
|
+
data: ZodObject< {
|
|
754
|
+
success: ZodLiteral<true>;
|
|
755
|
+
}, $strip>;
|
|
756
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
588
757
|
};
|
|
589
758
|
workout: {
|
|
590
759
|
list: DecoratedProcedure<MergedInitialContext< {
|
|
@@ -1099,6 +1268,10 @@ declare const publicRouter: {
|
|
|
1099
1268
|
get_strong: "get_strong";
|
|
1100
1269
|
stay_consistent: "stay_consistent";
|
|
1101
1270
|
}>>;
|
|
1271
|
+
dateOfBirth: ZodNullable<ZodString>;
|
|
1272
|
+
heightCm: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
1273
|
+
sessionsPerWeek: ZodNullable<ZodNumber>;
|
|
1274
|
+
bodyweightKg: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
1102
1275
|
macroTargets: ZodNullable<ZodObject< {
|
|
1103
1276
|
calories: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
1104
1277
|
protein: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
@@ -1129,6 +1302,9 @@ declare const publicRouter: {
|
|
|
1129
1302
|
get_strong: "get_strong";
|
|
1130
1303
|
stay_consistent: "stay_consistent";
|
|
1131
1304
|
}>>>;
|
|
1305
|
+
dateOfBirth: ZodOptional<ZodNullable<ZodString>>;
|
|
1306
|
+
heightCm: ZodOptional<ZodNullable<ZodNumber>>;
|
|
1307
|
+
sessionsPerWeek: ZodOptional<ZodNullable<ZodNumber>>;
|
|
1132
1308
|
}, $strip>, ZodObject< {
|
|
1133
1309
|
data: ZodObject< {
|
|
1134
1310
|
id: ZodString;
|
|
@@ -1146,6 +1322,10 @@ declare const publicRouter: {
|
|
|
1146
1322
|
get_strong: "get_strong";
|
|
1147
1323
|
stay_consistent: "stay_consistent";
|
|
1148
1324
|
}>>;
|
|
1325
|
+
dateOfBirth: ZodNullable<ZodString>;
|
|
1326
|
+
heightCm: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
1327
|
+
sessionsPerWeek: ZodNullable<ZodNumber>;
|
|
1328
|
+
bodyweightKg: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
1149
1329
|
macroTargets: ZodNullable<ZodObject< {
|
|
1150
1330
|
calories: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
1151
1331
|
protein: ZodNullable<ZodCoercedNumber<unknown>>;
|
|
@@ -1155,6 +1335,48 @@ declare const publicRouter: {
|
|
|
1155
1335
|
}, $strip>;
|
|
1156
1336
|
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
1157
1337
|
};
|
|
1338
|
+
preferences: {
|
|
1339
|
+
getNotifications: DecoratedProcedure<MergedInitialContext< {
|
|
1340
|
+
headers: Headers;
|
|
1341
|
+
} & Record<never, never>, {
|
|
1342
|
+
headers: Headers;
|
|
1343
|
+
} & Record<never, never>, {
|
|
1344
|
+
headers: Headers;
|
|
1345
|
+
}>, MergedCurrentContext< {
|
|
1346
|
+
headers: Headers;
|
|
1347
|
+
}, ApiKeyContext>, Schema<unknown, unknown>, ZodObject< {
|
|
1348
|
+
data: ZodObject< {
|
|
1349
|
+
workoutReminders: ZodBoolean;
|
|
1350
|
+
streakAlerts: ZodBoolean;
|
|
1351
|
+
newPrograms: ZodBoolean;
|
|
1352
|
+
emailWeeklyRecap: ZodBoolean;
|
|
1353
|
+
emailProductNews: ZodBoolean;
|
|
1354
|
+
}, $strip>;
|
|
1355
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
1356
|
+
updateNotifications: DecoratedProcedure<MergedInitialContext< {
|
|
1357
|
+
headers: Headers;
|
|
1358
|
+
} & Record<never, never>, {
|
|
1359
|
+
headers: Headers;
|
|
1360
|
+
} & Record<never, never>, {
|
|
1361
|
+
headers: Headers;
|
|
1362
|
+
}>, MergedCurrentContext< {
|
|
1363
|
+
headers: Headers;
|
|
1364
|
+
}, ApiKeyContext>, ZodObject< {
|
|
1365
|
+
workoutReminders: ZodOptional<ZodBoolean>;
|
|
1366
|
+
streakAlerts: ZodOptional<ZodBoolean>;
|
|
1367
|
+
newPrograms: ZodOptional<ZodBoolean>;
|
|
1368
|
+
emailWeeklyRecap: ZodOptional<ZodBoolean>;
|
|
1369
|
+
emailProductNews: ZodOptional<ZodBoolean>;
|
|
1370
|
+
}, $strip>, ZodObject< {
|
|
1371
|
+
data: ZodObject< {
|
|
1372
|
+
workoutReminders: ZodBoolean;
|
|
1373
|
+
streakAlerts: ZodBoolean;
|
|
1374
|
+
newPrograms: ZodBoolean;
|
|
1375
|
+
emailWeeklyRecap: ZodBoolean;
|
|
1376
|
+
emailProductNews: ZodBoolean;
|
|
1377
|
+
}, $strip>;
|
|
1378
|
+
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
1379
|
+
};
|
|
1158
1380
|
article: {
|
|
1159
1381
|
list: DecoratedProcedure<MergedInitialContext< {
|
|
1160
1382
|
headers: Headers;
|
|
@@ -2314,6 +2536,9 @@ declare const publicRouter: {
|
|
|
2314
2536
|
failed: "failed";
|
|
2315
2537
|
}>;
|
|
2316
2538
|
buildVersion: ZodNullable<ZodString>;
|
|
2539
|
+
helpUrl: ZodNullable<ZodString>;
|
|
2540
|
+
termsUrl: ZodNullable<ZodString>;
|
|
2541
|
+
privacyUrl: ZodNullable<ZodString>;
|
|
2317
2542
|
}, $strip>;
|
|
2318
2543
|
}, $strip>, Record<never, never>, Record<never, never>>;
|
|
2319
2544
|
};
|
|
@@ -2376,6 +2601,11 @@ declare const publicRouter: {
|
|
|
2376
2601
|
cancelled: "cancelled";
|
|
2377
2602
|
past_due: "past_due";
|
|
2378
2603
|
}>;
|
|
2604
|
+
interval: ZodNullable<ZodEnum< {
|
|
2605
|
+
monthly: "monthly";
|
|
2606
|
+
annual: "annual";
|
|
2607
|
+
}>>;
|
|
2608
|
+
priceCents: ZodNullable<ZodNumber>;
|
|
2379
2609
|
startedAt: ZodNullable<ZodDate>;
|
|
2380
2610
|
expiresAt: ZodNullable<ZodDate>;
|
|
2381
2611
|
}, $strip>>;
|
|
@@ -2426,6 +2656,13 @@ declare const publicRouter: {
|
|
|
2426
2656
|
};
|
|
2427
2657
|
};
|
|
2428
2658
|
|
|
2659
|
+
/** Which second factors the signed-in user has configured. */
|
|
2660
|
+
export declare interface SecurityStatus {
|
|
2661
|
+
readonly twoFactorEnabled: boolean;
|
|
2662
|
+
readonly totpEnabled: boolean;
|
|
2663
|
+
readonly hasBackupCodes: boolean;
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2429
2666
|
/** Cached session in storage. `expiresAt` is an ISO-8601 string from the server. */
|
|
2430
2667
|
export declare interface Session {
|
|
2431
2668
|
readonly accessToken: string;
|
|
@@ -2436,6 +2673,19 @@ export declare interface Session {
|
|
|
2436
2673
|
};
|
|
2437
2674
|
}
|
|
2438
2675
|
|
|
2676
|
+
/**
|
|
2677
|
+
* One signed-in device/session from `auth.listSessions`. `revokeId` is an
|
|
2678
|
+
* opaque identifier (never the bearer token) — pass it to `auth.revokeSession`.
|
|
2679
|
+
*/
|
|
2680
|
+
export declare interface SessionInfo {
|
|
2681
|
+
readonly revokeId: string;
|
|
2682
|
+
readonly createdAt: Date;
|
|
2683
|
+
readonly expiresAt: Date;
|
|
2684
|
+
readonly ipAddress: string | null;
|
|
2685
|
+
readonly userAgent: string | null;
|
|
2686
|
+
readonly isCurrent: boolean;
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2439
2689
|
/**
|
|
2440
2690
|
* The discriminated return value from `auth.signIn()`. When the trainee has
|
|
2441
2691
|
* no second factor configured, `kind` is `"signed_in"` and the session is
|
|
@@ -2459,9 +2709,18 @@ export declare interface TokenStorage {
|
|
|
2459
2709
|
}
|
|
2460
2710
|
|
|
2461
2711
|
/**
|
|
2462
|
-
*
|
|
2463
|
-
*
|
|
2464
|
-
*
|
|
2712
|
+
* Returned by `auth.enableTotp`. Render `totpUri` as a QR code (or expose it
|
|
2713
|
+
* as a link) and show `backupCodes` exactly once — the server stores them
|
|
2714
|
+
* encrypted and cannot display them again.
|
|
2715
|
+
*/
|
|
2716
|
+
export declare interface TotpEnrollment {
|
|
2717
|
+
readonly totpUri: string;
|
|
2718
|
+
readonly backupCodes: readonly string[];
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
/**
|
|
2722
|
+
* Carries everything a caller needs to drive step-2 of a two-factor sign-in
|
|
2723
|
+
* via `auth.verifyTotp`, `auth.verifyBackupCode`, or the email-OTP helpers.
|
|
2465
2724
|
*/
|
|
2466
2725
|
export declare interface TwoFactorChallenge {
|
|
2467
2726
|
readonly token: TwoFactorToken;
|
package/dist/index.js
CHANGED
|
@@ -168,6 +168,89 @@ function createAuthNamespace(opts) {
|
|
|
168
168
|
const confirmEmail = async (input) => {
|
|
169
169
|
await call(() => opts.transport.client.auth.confirmEmail(input));
|
|
170
170
|
};
|
|
171
|
+
const verifyTotp = async (input) => {
|
|
172
|
+
const result = await call(
|
|
173
|
+
() => opts.transport.client.auth.verifyTotp({ token: input.challenge.token, code: input.code })
|
|
174
|
+
);
|
|
175
|
+
const { user, session } = result.data;
|
|
176
|
+
return applySession(
|
|
177
|
+
{ accessToken: session.accessToken, expiresAt: session.expiresAt, user },
|
|
178
|
+
"signed_in"
|
|
179
|
+
);
|
|
180
|
+
};
|
|
181
|
+
const verifyBackupCode = async (input) => {
|
|
182
|
+
const result = await call(
|
|
183
|
+
() => opts.transport.client.auth.verifyBackupCode({
|
|
184
|
+
token: input.challenge.token,
|
|
185
|
+
code: input.code
|
|
186
|
+
})
|
|
187
|
+
);
|
|
188
|
+
const { user, session } = result.data;
|
|
189
|
+
return applySession(
|
|
190
|
+
{ accessToken: session.accessToken, expiresAt: session.expiresAt, user },
|
|
191
|
+
"signed_in"
|
|
192
|
+
);
|
|
193
|
+
};
|
|
194
|
+
const requestEmailOtp = async (input) => {
|
|
195
|
+
await call(() => opts.transport.client.auth.requestEmailOtp({ token: input.challenge.token }));
|
|
196
|
+
};
|
|
197
|
+
const verifyEmailOtp = async (input) => {
|
|
198
|
+
const result = await call(
|
|
199
|
+
() => opts.transport.client.auth.verifyEmailOtp({ token: input.challenge.token, code: input.code })
|
|
200
|
+
);
|
|
201
|
+
const { user, session } = result.data;
|
|
202
|
+
return applySession(
|
|
203
|
+
{ accessToken: session.accessToken, expiresAt: session.expiresAt, user },
|
|
204
|
+
"signed_in"
|
|
205
|
+
);
|
|
206
|
+
};
|
|
207
|
+
function adoptRotatedToken(accessToken) {
|
|
208
|
+
const current = cached;
|
|
209
|
+
if (!current || !accessToken || accessToken === current.accessToken) return;
|
|
210
|
+
applySession({ ...current, accessToken }, "session_refreshed");
|
|
211
|
+
}
|
|
212
|
+
const getSecurityStatus = async () => {
|
|
213
|
+
const result = await call(() => opts.transport.client.auth.getSecurityStatus());
|
|
214
|
+
return result.data;
|
|
215
|
+
};
|
|
216
|
+
const enableTotp = async (input) => {
|
|
217
|
+
const result = await call(() => opts.transport.client.auth.enableTotp(input));
|
|
218
|
+
return result.data;
|
|
219
|
+
};
|
|
220
|
+
const verifyTotpSetup = async (input) => {
|
|
221
|
+
const result = await call(() => opts.transport.client.auth.verifyTotpSetup(input));
|
|
222
|
+
adoptRotatedToken(result.data.accessToken);
|
|
223
|
+
};
|
|
224
|
+
const disableTwoFactor = async (input) => {
|
|
225
|
+
await call(() => opts.transport.client.auth.disableTwoFactor(input));
|
|
226
|
+
};
|
|
227
|
+
const regenerateBackupCodes = async (input) => {
|
|
228
|
+
const result = await call(() => opts.transport.client.auth.regenerateBackupCodes(input));
|
|
229
|
+
return result.data.backupCodes;
|
|
230
|
+
};
|
|
231
|
+
const changePassword = async (input) => {
|
|
232
|
+
const result = await call(
|
|
233
|
+
() => opts.transport.client.auth.changePassword({
|
|
234
|
+
currentPassword: input.currentPassword,
|
|
235
|
+
newPassword: input.newPassword,
|
|
236
|
+
revokeOtherSessions: input.revokeOtherSessions
|
|
237
|
+
})
|
|
238
|
+
);
|
|
239
|
+
adoptRotatedToken(result.data.accessToken);
|
|
240
|
+
};
|
|
241
|
+
const changeEmail = async (input) => {
|
|
242
|
+
await call(() => opts.transport.client.auth.changeEmail(input));
|
|
243
|
+
};
|
|
244
|
+
const listSessions = async () => {
|
|
245
|
+
const result = await call(() => opts.transport.client.auth.listSessions());
|
|
246
|
+
return result.data;
|
|
247
|
+
};
|
|
248
|
+
const revokeSession = async (input) => {
|
|
249
|
+
await call(() => opts.transport.client.auth.revokeSession(input));
|
|
250
|
+
};
|
|
251
|
+
const revokeOtherSessions = async () => {
|
|
252
|
+
await call(() => opts.transport.client.auth.revokeOtherSessions());
|
|
253
|
+
};
|
|
171
254
|
const _refresh = async () => {
|
|
172
255
|
let current = cached;
|
|
173
256
|
if (!current) {
|
|
@@ -204,6 +287,20 @@ function createAuthNamespace(opts) {
|
|
|
204
287
|
requestPasswordReset,
|
|
205
288
|
confirmPasswordReset,
|
|
206
289
|
confirmEmail,
|
|
290
|
+
verifyTotp,
|
|
291
|
+
verifyBackupCode,
|
|
292
|
+
requestEmailOtp,
|
|
293
|
+
verifyEmailOtp,
|
|
294
|
+
getSecurityStatus,
|
|
295
|
+
enableTotp,
|
|
296
|
+
verifyTotpSetup,
|
|
297
|
+
disableTwoFactor,
|
|
298
|
+
regenerateBackupCodes,
|
|
299
|
+
changePassword,
|
|
300
|
+
changeEmail,
|
|
301
|
+
listSessions,
|
|
302
|
+
revokeSession,
|
|
303
|
+
revokeOtherSessions,
|
|
207
304
|
_refresh,
|
|
208
305
|
_signOutLocal
|
|
209
306
|
};
|
|
@@ -248,7 +345,8 @@ function createDataNamespaces(transport) {
|
|
|
248
345
|
appConfig: wrapSlice(c.appConfig),
|
|
249
346
|
subscription: wrapSlice(c.subscription),
|
|
250
347
|
profile: wrapSlice(c.profile),
|
|
251
|
-
nutritionLog: wrapSlice(c.nutritionLog)
|
|
348
|
+
nutritionLog: wrapSlice(c.nutritionLog),
|
|
349
|
+
preferences: wrapSlice(c.preferences)
|
|
252
350
|
};
|
|
253
351
|
}
|
|
254
352
|
|
|
@@ -419,7 +517,21 @@ function createFytkitClient(options) {
|
|
|
419
517
|
onAuthStateChange: authInstance.onAuthStateChange,
|
|
420
518
|
requestPasswordReset: authInstance.requestPasswordReset,
|
|
421
519
|
confirmPasswordReset: authInstance.confirmPasswordReset,
|
|
422
|
-
confirmEmail: authInstance.confirmEmail
|
|
520
|
+
confirmEmail: authInstance.confirmEmail,
|
|
521
|
+
verifyTotp: authInstance.verifyTotp,
|
|
522
|
+
verifyBackupCode: authInstance.verifyBackupCode,
|
|
523
|
+
requestEmailOtp: authInstance.requestEmailOtp,
|
|
524
|
+
verifyEmailOtp: authInstance.verifyEmailOtp,
|
|
525
|
+
getSecurityStatus: authInstance.getSecurityStatus,
|
|
526
|
+
enableTotp: authInstance.enableTotp,
|
|
527
|
+
verifyTotpSetup: authInstance.verifyTotpSetup,
|
|
528
|
+
disableTwoFactor: authInstance.disableTwoFactor,
|
|
529
|
+
regenerateBackupCodes: authInstance.regenerateBackupCodes,
|
|
530
|
+
changePassword: authInstance.changePassword,
|
|
531
|
+
changeEmail: authInstance.changeEmail,
|
|
532
|
+
listSessions: authInstance.listSessions,
|
|
533
|
+
revokeSession: authInstance.revokeSession,
|
|
534
|
+
revokeOtherSessions: authInstance.revokeOtherSessions
|
|
423
535
|
},
|
|
424
536
|
...data
|
|
425
537
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/error.ts","../src/events.ts","../src/auth.ts","../src/data.ts","../src/storage.ts","../src/transport.ts","../src/index.ts"],"names":["cached"],"mappings":";;;;AAUA,SAAS,WAAW,IAAA,EAA0C;AAC5D,EAAA,IAAI,CAAC,IAAA,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ORPCError } from \"@orpc/client\";\nimport type { FytkitError } from \"./types\";\n\ninterface MaybeIssuesData {\n issues?: readonly unknown[];\n}\ninterface MaybeRetryAfterData {\n retryAfterMs?: number;\n}\n\nfunction pickIssues(data: unknown): readonly unknown[] | null {\n if (!data || typeof data !== \"object\") return null;\n const issues = (data as MaybeIssuesData).issues;\n return Array.isArray(issues) ? issues : null;\n}\n\nfunction pickRetryAfter(data: unknown): number {\n if (!data || typeof data !== \"object\") return 0;\n const raw = (data as MaybeRetryAfterData).retryAfterMs;\n return typeof raw === \"number\" && raw >= 0 ? raw : 0;\n}\n\n/**\n * Map any error thrown by `@orpc/client` (or the underlying fetch) into the\n * SDK's `FytkitError` discriminated union. The SDK never re-throws raw orpc\n * or network errors at the public surface.\n */\nexport function normalizeError(err: unknown): FytkitError {\n // Network failures from fetch surface as TypeError.\n if (err instanceof TypeError) return { kind: \"network\" };\n\n if (err instanceof ORPCError) {\n const code = err.code;\n const status = err.status;\n const data: unknown = err.data;\n const message = err.message;\n\n switch (code) {\n case \"UNAUTHORIZED\":\n // Carry the server's reason (e.g. \"Invalid credentials\" on a failed\n // sign-in) so the consumer can show it instead of a generic\n // 'session expired' copy. The synthetic no-session case in auth.ts\n // is built directly and stays message-less.\n return { kind: \"auth_required\", message };\n case \"FORBIDDEN\":\n return { kind: \"forbidden\", reason: message || \"Forbidden\" };\n case \"CONFLICT\":\n return { kind: \"conflict\", message: message || \"Conflict\" };\n case \"NOT_FOUND\":\n return { kind: \"not_found\" };\n case \"TOO_MANY_REQUESTS\":\n return { kind: \"rate_limited\", retryAfter: pickRetryAfter(data) };\n case \"BAD_REQUEST\":\n case \"UNPROCESSABLE_CONTENT\": {\n const issues = pickIssues(data);\n if (issues) return { kind: \"validation\", issues };\n // No structured issues — still carry the server's explanation so it\n // isn't dropped into a bare status code.\n return { kind: \"server\", status, message };\n }\n default:\n return { kind: \"server\", status, message };\n }\n }\n\n return { kind: \"server\", status: 0 };\n}\n","export interface EventBus<T> {\n readonly on: (listener: (value: T) => void) => () => void;\n readonly emit: (value: T) => void;\n}\n\nexport function createEventBus<T>(): EventBus<T> {\n const listeners = new Set<(value: T) => void>();\n return {\n on: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n emit: (value) => {\n for (const listener of listeners) {\n try {\n listener(value);\n } catch (err) {\n // A buggy listener must not break siblings or the calling flow.\n console.error(\"[fytkit-sdk] event listener threw\", err);\n }\n }\n },\n };\n}\n","import { normalizeError } from \"./error\";\nimport { createEventBus } from \"./events\";\nimport type { Transport } from \"./transport\";\nimport type { AuthState, FytkitError, Session, SignInResult, TokenStorage, TwoFactorToken } from \"./types\";\n\nexport interface AuthNamespaceOptions {\n readonly transport: Transport;\n readonly storage: TokenStorage;\n /** Called after the SDK signs out for any reason (manual, refresh failure). */\n readonly onSignedOut?: () => void;\n}\n\nexport interface AuthNamespace {\n readonly signUp: (input: { email: string; password: string; name: string }) => Promise<Session>;\n readonly signIn: (input: { email: string; password: string }) => Promise<SignInResult>;\n readonly signOut: () => Promise<void>;\n readonly getSession: () => Session | null;\n readonly onAuthStateChange: (listener: (state: AuthState) => void) => () => void;\n readonly requestPasswordReset: (input: { email: string }) => Promise<void>;\n readonly confirmPasswordReset: (input: { token: string; password: string }) => Promise<void>;\n readonly confirmEmail: (input: { token: string }) => Promise<void>;\n /** Internal: force a refresh now. Wired by transport's 401 retry path. */\n readonly _refresh: () => Promise<Session>;\n /** Internal: clear cached session + emit signed_out. */\n readonly _signOutLocal: () => void;\n}\n\n/**\n * Schedule a proactive refresh this many ms before `expiresAt`. The\n * server-side access-token TTL is ~15 min so a 60-second lead time gives\n * us enough headroom to refresh transparently without burning sessions\n * needlessly while keeping the user signed-in across long-running tabs.\n */\nconst PROACTIVE_REFRESH_LEAD_MS = 60_000;\n\n/**\n * The auth namespace owns the cached session. It is the single writer to\n * `storage`; everything else reads via `getSession`. Calls that mutate\n * the session also emit on the event bus and (re)schedule the proactive\n * refresh timer against the new expiry.\n */\nexport function createAuthNamespace(opts: AuthNamespaceOptions): AuthNamespace {\n const bus = createEventBus<AuthState>();\n let cached: Session | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n // Forward declaration so scheduleRefresh can call the same _refresh body\n // the public surface exposes. Assigned at the bottom of the factory.\n let refreshFn: () => Promise<Session> = () => {\n throw new Error(\"refreshFn called before initialization\");\n };\n\n function clearTimer(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n // `setTimeout` clamps any delay > 2^31-1 ms (~24.8 days) to 1 ms and\n // prints a Node deprecation warning. Sessions with an exotic far-future\n // expiry (test fixtures, mis-configured server) would otherwise fire the\n // timer instantly; cap the delay to the safe upper bound so the timer\n // simply re-arms on its next firing.\n const MAX_TIMEOUT_MS = 2_147_483_647;\n\n function scheduleRefresh(session: Session): void {\n clearTimer();\n const expiresMs = new Date(session.expiresAt).getTime();\n if (Number.isNaN(expiresMs)) return; // bad date — bail; reactive 401 path will handle it\n const rawDelay = expiresMs - Date.now() - PROACTIVE_REFRESH_LEAD_MS;\n const delay = Math.min(MAX_TIMEOUT_MS, Math.max(0, rawDelay));\n timer = setTimeout(() => {\n timer = null;\n void refreshFn().catch(() => {\n // refreshFn already handles sign-out on failure.\n });\n }, delay);\n }\n\n function applySession(session: Session, event: \"signed_in\" | \"session_refreshed\"): Session {\n cached = session;\n void opts.storage.set(session);\n bus.emit({ type: event, session });\n scheduleRefresh(session);\n return session;\n }\n\n function clearSession(emit = true): void {\n cached = null;\n clearTimer();\n void opts.storage.remove();\n if (emit) bus.emit({ type: \"signed_out\" });\n opts.onSignedOut?.();\n }\n\n async function call<T>(thunk: () => Promise<T>): Promise<T> {\n try {\n return await thunk();\n } catch (err) {\n throw normalizeError(err);\n }\n }\n\n // Best-effort hydrate at construction. If the storage already holds a\n // session (warm reload, second tab), restore it and arm the timer.\n void Promise.resolve(opts.storage.get()).then((s) => {\n if (s) {\n cached = s;\n scheduleRefresh(s);\n }\n });\n\n const signUp: AuthNamespace[\"signUp\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.signUp(input));\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n };\n\n const signIn: AuthNamespace[\"signIn\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.signIn(input));\n if (result.data.kind === \"two_factor_required\") {\n // Mint the branded token exactly once at the network boundary.\n const token = result.data.twoFactorToken as TwoFactorToken;\n return {\n kind: \"two_factor_required\",\n challenge: { token, availableMethods: result.data.availableMethods },\n };\n }\n if (result.data.kind === \"signed_in\") {\n const { user, session } = result.data;\n const cached = applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n return { kind: \"signed_in\", session: cached };\n }\n // Exhaustiveness guard — a future server-side variant must not silently fall through.\n const _exhaustive: never = result.data;\n throw _exhaustive;\n };\n\n const signOut: AuthNamespace[\"signOut\"] = async () => {\n const current = cached;\n if (!current) return;\n try {\n await opts.transport.client.auth.signOut({ token: current.accessToken });\n } catch (err) {\n // Even if the server rejects (e.g. token already revoked), clear\n // the local cache so the user is signed out client-side.\n void err;\n }\n clearSession();\n };\n\n const getSession: AuthNamespace[\"getSession\"] = () => cached;\n const onAuthStateChange: AuthNamespace[\"onAuthStateChange\"] = (listener) => bus.on(listener);\n\n const requestPasswordReset: AuthNamespace[\"requestPasswordReset\"] = async (input) => {\n await call(() => opts.transport.client.auth.requestPasswordReset(input));\n };\n const confirmPasswordReset: AuthNamespace[\"confirmPasswordReset\"] = async (input) => {\n await call(() => opts.transport.client.auth.confirmPasswordReset(input));\n };\n const confirmEmail: AuthNamespace[\"confirmEmail\"] = async (input) => {\n await call(() => opts.transport.client.auth.confirmEmail(input));\n };\n\n const _refresh: AuthNamespace[\"_refresh\"] = async () => {\n // Re-read storage as a fallback so a session written after\n // construction (e.g. on tab restore or in tests) is honoured.\n let current = cached;\n if (!current) {\n const fromStorage = await Promise.resolve(opts.storage.get());\n if (fromStorage) {\n cached = fromStorage;\n current = fromStorage;\n }\n }\n if (!current) {\n const err: FytkitError = { kind: \"auth_required\" };\n throw err;\n }\n try {\n const result = await opts.transport.client.auth.refresh({ token: current.accessToken });\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"session_refreshed\",\n );\n } catch (err) {\n clearSession();\n throw normalizeError(err);\n }\n };\n\n const _signOutLocal: AuthNamespace[\"_signOutLocal\"] = () => clearSession();\n\n refreshFn = _refresh;\n\n return {\n signUp,\n signIn,\n signOut,\n getSession,\n onAuthStateChange,\n requestPasswordReset,\n confirmPasswordReset,\n confirmEmail,\n _refresh,\n _signOutLocal,\n };\n}\n","import { normalizeError } from \"./error\";\nimport type { Transport } from \"./transport\";\n\n/**\n * Wrap every method on a public-router slice so thrown ORPCErrors become\n * normalised FytkitErrors at the SDK boundary.\n *\n * The slice we receive is an `@orpc/client` Proxy whose own keys are not\n * enumerable — every property lookup is intercepted lazily. We mirror that\n * shape by returning a Proxy of our own that wraps each function on first\n * access and caches the result. This way the SDK never needs to know the\n * method names ahead of time, and the typed shape from the server router\n * flows through unchanged.\n */\nfunction wrapSlice<T extends object>(slice: T): T {\n const cache = new Map<string | symbol, unknown>();\n return new Proxy(slice, {\n get(target, prop, receiver) {\n if (cache.has(prop)) return cache.get(prop);\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== \"function\") {\n // Allow nested namespaces to flow through unchanged (the orpc\n // proxy returns another proxy here, not a plain object).\n return value;\n }\n const wrapped = async (...args: unknown[]) => {\n try {\n return await (value as (...a: unknown[]) => Promise<unknown>)(...args);\n } catch (err) {\n throw normalizeError(err);\n }\n };\n cache.set(prop, wrapped);\n return wrapped;\n },\n }) as T;\n}\n\nexport interface DataNamespaces {\n readonly workouts: Transport[\"client\"][\"workout\"];\n readonly programs: Transport[\"client\"][\"program\"];\n readonly recipes: Transport[\"client\"][\"recipe\"];\n readonly nutrition: Transport[\"client\"][\"nutrition\"];\n readonly articles: Transport[\"client\"][\"article\"];\n readonly enrollments: Transport[\"client\"][\"enrollment\"];\n readonly sessionLogs: Transport[\"client\"][\"sessionLog\"];\n readonly progression: Transport[\"client\"][\"progression\"];\n readonly bodyMetrics: Transport[\"client\"][\"bodyMetric\"];\n readonly progress: Transport[\"client\"][\"progress\"];\n readonly media: Transport[\"client\"][\"media\"];\n readonly appConfig: Transport[\"client\"][\"appConfig\"];\n readonly subscription: Transport[\"client\"][\"subscription\"];\n readonly profile: Transport[\"client\"][\"profile\"];\n readonly nutritionLog: Transport[\"client\"][\"nutritionLog\"];\n}\n\nexport function createDataNamespaces(transport: Transport): DataNamespaces {\n const c = transport.client;\n return {\n workouts: wrapSlice(c.workout),\n programs: wrapSlice(c.program),\n recipes: wrapSlice(c.recipe),\n nutrition: wrapSlice(c.nutrition),\n articles: wrapSlice(c.article),\n enrollments: wrapSlice(c.enrollment),\n sessionLogs: wrapSlice(c.sessionLog),\n progression: wrapSlice(c.progression),\n bodyMetrics: wrapSlice(c.bodyMetric),\n progress: wrapSlice(c.progress),\n media: wrapSlice(c.media),\n appConfig: wrapSlice(c.appConfig),\n subscription: wrapSlice(c.subscription),\n profile: wrapSlice(c.profile),\n nutritionLog: wrapSlice(c.nutritionLog),\n };\n}\n","import type { Session, TokenStorage } from \"./types\";\n\nconst STORAGE_KEY_PREFIX = \"fytkit:\";\nconst STORAGE_KEY_SUFFIX = \":tokens\";\n\nfunction keyFor(clientId: string): string {\n return `${STORAGE_KEY_PREFIX}${clientId}${STORAGE_KEY_SUFFIX}`;\n}\n\nfunction isValidSession(value: unknown): value is Session {\n if (!value || typeof value !== \"object\") return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.accessToken === \"string\" &&\n typeof v.expiresAt === \"string\" &&\n typeof v.user === \"object\" &&\n v.user !== null &&\n typeof (v.user as { id?: unknown }).id === \"string\" &&\n typeof (v.user as { email?: unknown }).email === \"string\"\n );\n}\n\n/**\n * Default web storage. Reads/writes JSON under `fytkit:{clientId}:tokens`.\n * Silently no-ops when localStorage throws (Safari private mode, SSR).\n */\nexport function createLocalStorageAdapter(clientId: string): TokenStorage {\n const key = keyFor(clientId);\n return {\n get: () => {\n try {\n const raw = globalThis.localStorage?.getItem(key);\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n return isValidSession(parsed) ? parsed : null;\n } catch {\n return null;\n }\n },\n set: (session: Session) => {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(session));\n } catch {\n // Quota / private-mode / SSR — swallow and let the caller treat the\n // session as in-memory-only for this tab.\n }\n },\n remove: () => {\n try {\n globalThis.localStorage?.removeItem(key);\n } catch {\n // see set() rationale\n }\n },\n };\n}\n\n/** In-memory storage. Useful for tests and SSR. */\nexport function createMemoryStorageAdapter(): TokenStorage {\n let current: Session | null = null;\n return {\n get: () => current,\n set: (session: Session) => {\n current = session;\n },\n remove: () => {\n current = null;\n },\n };\n}\n","import type { PublicApi } from \"@fytkit/types\";\nimport { createORPCClient } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\nimport type { Session } from \"./types\";\n\nexport interface CreateTransportOptions {\n readonly baseUrl: string;\n readonly clientId: string;\n readonly getSession: () => Session | null;\n readonly fetch?: typeof fetch;\n}\n\nexport interface Transport {\n readonly client: PublicApi;\n /** Internal: hook for attachRefreshInterceptor to install a fetch wrapper. */\n readonly _setFetchInterceptor: (interceptor: FetchInterceptor) => void;\n}\n\ntype FetchInterceptor = (\n request: Request,\n next: (req: Request) => Promise<Response>,\n) => Promise<Response>;\n\nexport function createTransport(options: CreateTransportOptions): Transport {\n let interceptor: FetchInterceptor | null = null;\n const baseFetch: typeof fetch = options.fetch ?? fetch.bind(globalThis);\n\n // The fetch handed to RPCLink resolves the interceptor lazily so callers\n // can install one after construction (see attachRefreshInterceptor).\n const wrappedFetch: typeof fetch = (input, init) => {\n const request = input instanceof Request ? input : new Request(input, init);\n const next = (req: Request) => baseFetch(req);\n if (!interceptor) return next(request);\n return interceptor(request, next);\n };\n\n const link = new RPCLink({\n url: () => `${options.baseUrl}/rpc`,\n headers: () => {\n const session = options.getSession();\n const headers: Record<string, string> = {\n \"X-Fytkit-Client-Id\": options.clientId,\n };\n if (session) {\n headers.Authorization = `Bearer ${session.accessToken}`;\n }\n return headers;\n },\n fetch: wrappedFetch,\n });\n\n const client: PublicApi = createORPCClient(link);\n return {\n client,\n _setFetchInterceptor: (i) => {\n interceptor = i;\n },\n };\n}\n\n/** Internal marker header — set on the refresh call so we never recurse. */\nconst REFRESH_HEADER = \"X-Fytkit-Refresh\";\n\n/**\n * Detect whether a request targets the refresh procedure. The RPCLink\n * routes per-procedure calls under a URL whose pathname ends with the\n * procedure path (joined as `/segment/segment`), so we look for the\n * `auth/refresh` suffix. We use endsWith so trailing query strings or\n * link-level prefixes do not break detection.\n */\nfunction isRefreshRequest(request: Request): boolean {\n if (request.headers.get(REFRESH_HEADER) === \"1\") return true;\n try {\n const path = new URL(request.url).pathname;\n return path.endsWith(\"/auth/refresh\");\n } catch {\n return false;\n }\n}\n\nexport interface AttachRefreshInterceptorOptions {\n readonly transport: Transport;\n readonly auth: {\n readonly _refresh: () => Promise<Session>;\n readonly _signOutLocal: () => void;\n readonly getSession: () => Session | null;\n };\n}\n\n/**\n * Install a fetch interceptor that, on a 401 response, calls auth._refresh\n * once and retries the original request. Concurrent 401s de-duplicate\n * onto a single in-flight refresh promise. A 401 from refresh itself or\n * from the retry triggers a local sign-out and propagates the original\n * 401 to the caller (after which orpc throws ORPCError(\"UNAUTHORIZED\")).\n */\nexport function attachRefreshInterceptor(opts: AttachRefreshInterceptorOptions): void {\n let inflight: Promise<Session> | null = null;\n\n const refreshOnce = (): Promise<Session> => {\n if (!inflight) {\n inflight = opts.auth._refresh().finally(() => {\n inflight = null;\n });\n }\n return inflight;\n };\n\n opts.transport._setFetchInterceptor(async (request, next) => {\n // Refresh calls must never trigger a recursive refresh.\n if (isRefreshRequest(request)) {\n return next(request);\n }\n\n // Capture the request body now, before we pass `request` to `next` —\n // once fetch consumes a Request body it can no longer be cloned.\n const buffered = await request.clone().arrayBuffer();\n\n const firstResponse = await next(request);\n if (firstResponse.status !== 401) return firstResponse;\n\n try {\n await refreshOnce();\n } catch {\n // _refresh already called clearSession + emitted signed_out.\n return firstResponse;\n }\n\n // Rebuild headers so the new Authorization header replaces the stale\n // one — the RPCLink only re-evaluates its own `headers()` once per call,\n // so we patch the bearer ourselves here.\n const replayedHeaders = new Headers(request.headers);\n const session = opts.auth.getSession();\n if (session) {\n replayedHeaders.set(\"Authorization\", `Bearer ${session.accessToken}`);\n } else {\n replayedHeaders.delete(\"Authorization\");\n }\n const replayed = new Request(request.url, {\n method: request.method,\n headers: replayedHeaders,\n body: buffered.byteLength > 0 ? buffered : undefined,\n credentials: request.credentials,\n mode: request.mode,\n cache: request.cache,\n redirect: request.redirect,\n referrer: request.referrer,\n integrity: request.integrity,\n });\n\n const retried = await next(replayed);\n if (retried.status === 401) {\n // Refresh succeeded server-side but the server still rejects — the\n // session is dead. Sign out locally and let orpc surface the 401.\n opts.auth._signOutLocal();\n }\n return retried;\n });\n}\n","import { createAuthNamespace } from \"./auth\";\nimport { createDataNamespaces } from \"./data\";\nimport { createLocalStorageAdapter, createMemoryStorageAdapter } from \"./storage\";\nimport { attachRefreshInterceptor, createTransport } from \"./transport\";\nimport type { FytkitClient, FytkitClientOptions } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://api.fytkit.com\";\n\nexport function createFytkitClient(options: FytkitClientOptions): FytkitClient {\n if (!options || typeof options.clientId !== \"string\" || options.clientId.length === 0) {\n throw new Error(\"createFytkitClient: `clientId` is required\");\n }\n\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const storage = options.storage ?? createLocalStorageAdapter(options.clientId);\n\n // `auth` is declared after `transport` because `createAuthNamespace`\n // needs the transport to make its RPC calls. The transport in turn needs\n // a `getSession` that reads the auth cache — we resolve the cycle with a\n // late-bound reference: the closure below reads `auth` lazily, which is\n // safe because no request can fire before construction finishes.\n let auth: ReturnType<typeof createAuthNamespace> | null = null;\n\n const transport = createTransport({\n baseUrl,\n clientId: options.clientId,\n getSession: () => auth?.getSession() ?? null,\n fetch: options.fetch,\n });\n\n const authInstance = createAuthNamespace({ transport, storage });\n auth = authInstance;\n attachRefreshInterceptor({ transport, auth: authInstance });\n\n const data = createDataNamespaces(transport);\n\n return {\n auth: {\n signUp: authInstance.signUp,\n signIn: authInstance.signIn,\n signOut: authInstance.signOut,\n getSession: authInstance.getSession,\n onAuthStateChange: authInstance.onAuthStateChange,\n requestPasswordReset: authInstance.requestPasswordReset,\n confirmPasswordReset: authInstance.confirmPasswordReset,\n confirmEmail: authInstance.confirmEmail,\n },\n ...data,\n };\n}\n\n// Public re-exports.\nexport { createLocalStorageAdapter, createMemoryStorageAdapter };\nexport type {\n AuthState,\n FytkitClient,\n FytkitClientOptions,\n FytkitError,\n Session,\n SignInResult,\n TokenStorage,\n TwoFactorChallenge,\n TwoFactorMethod,\n TwoFactorToken,\n} from \"./types\";\n// `PublicApi` is the inferred router type that backs every namespace\n// on `FytkitClient` (e.g. `client.workouts` is `PublicApi[\"workout\"]`).\n// Re-exported so consumers can write generics over the router shape —\n// previously this surfaced as an `ae-forgotten-export` warning on\n// `FytkitClient` in the api-extractor report. The api-extractor will\n// still warn about `PublicRouter`/`publicRouter` being unexported —\n// that is intentional, those are implementation-detail names from the\n// generated snapshot that should not be part of the consumer surface.\nexport type { PublicApi } from \"@fytkit/types\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/error.ts","../src/events.ts","../src/auth.ts","../src/data.ts","../src/storage.ts","../src/transport.ts","../src/index.ts"],"names":["cached"],"mappings":";;;;AAUA,SAAS,WAAW,IAAA,EAA0C;AAC5D,EAAA,IAAI,CAAC,IAAA,IAAQ,OAAO,IAAA,KAAS,UAAU,OAAO,IAAA;AAC9C,EAAA,MAAM,SAAU,IAAA,CAAyB,MAAA;AACzC,EAAA,OAAO,KAAA,CAAM,OAAA,CAAQ,MAAM,CAA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S,CAAA;AAC/D,EAAA,IAAA,GAAO,YAAA;AACP,EAAA,wBAAA,CAAyB,EAAE,SAAA,EAAW,IAAA,EAAM,YAAA,EAAc,CAAA;AAE1D,EAAA,MAAM,IAAA,GAAO,qBAAqB,SAAS,CAAA;AAE3C,EAAA,OAAO;AAAA,IACL,IAAA,EAAM;AAAA,MACJ,QAAQ,YAAA,CAAa,MAAA;AAAA,MACrB,QAAQ,YAAA,CAAa,MAAA;AAAA,MACrB,SAAS,YAAA,CAAa,OAAA;AAAA,MACtB,YAAY,YAAA,CAAa,UAAA;AAAA,MACzB,mBAAmB,YAAA,CAAa,iBAAA;AAAA,MAChC,sBAAsB,YAAA,CAAa,oBAAA;AAAA,MACnC,sBAAsB,YAAA,CAAa,oBAAA;AAAA,MACnC,cAAc,YAAA,CAAa,YAAA;AAAA,MAC3B,YAAY,YAAA,CAAa,UAAA;AAAA,MACzB,kBAAkB,YAAA,CAAa,gBAAA;AAAA,MAC/B,iBAAiB,YAAA,CAAa,eAAA;AAAA,MAC9B,gBAAgB,YAAA,CAAa,cAAA;AAAA,MAC7B,mBAAmB,YAAA,CAAa,iBAAA;AAAA,MAChC,YAAY,YAAA,CAAa,UAAA;AAAA,MACzB,iBAAiB,YAAA,CAAa,eAAA;AAAA,MAC9B,kBAAkB,YAAA,CAAa,gBAAA;AAAA,MAC/B,uBAAuB,YAAA,CAAa,qBAAA;AAAA,MACpC,gBAAgB,YAAA,CAAa,cAAA;AAAA,MAC7B,aAAa,YAAA,CAAa,WAAA;AAAA,MAC1B,cAAc,YAAA,CAAa,YAAA;AAAA,MAC3B,eAAe,YAAA,CAAa,aAAA;AAAA,MAC5B,qBAAqB,YAAA,CAAa;AAAA,KACpC;AAAA,IACA,GAAG;AAAA,GACL;AACF","file":"index.js","sourcesContent":["import { ORPCError } from \"@orpc/client\";\nimport type { FytkitError } from \"./types\";\n\ninterface MaybeIssuesData {\n issues?: readonly unknown[];\n}\ninterface MaybeRetryAfterData {\n retryAfterMs?: number;\n}\n\nfunction pickIssues(data: unknown): readonly unknown[] | null {\n if (!data || typeof data !== \"object\") return null;\n const issues = (data as MaybeIssuesData).issues;\n return Array.isArray(issues) ? issues : null;\n}\n\nfunction pickRetryAfter(data: unknown): number {\n if (!data || typeof data !== \"object\") return 0;\n const raw = (data as MaybeRetryAfterData).retryAfterMs;\n return typeof raw === \"number\" && raw >= 0 ? raw : 0;\n}\n\n/**\n * Map any error thrown by `@orpc/client` (or the underlying fetch) into the\n * SDK's `FytkitError` discriminated union. The SDK never re-throws raw orpc\n * or network errors at the public surface.\n */\nexport function normalizeError(err: unknown): FytkitError {\n // Network failures from fetch surface as TypeError.\n if (err instanceof TypeError) return { kind: \"network\" };\n\n if (err instanceof ORPCError) {\n const code = err.code;\n const status = err.status;\n const data: unknown = err.data;\n const message = err.message;\n\n switch (code) {\n case \"UNAUTHORIZED\":\n // Carry the server's reason (e.g. \"Invalid credentials\" on a failed\n // sign-in) so the consumer can show it instead of a generic\n // 'session expired' copy. The synthetic no-session case in auth.ts\n // is built directly and stays message-less.\n return { kind: \"auth_required\", message };\n case \"FORBIDDEN\":\n return { kind: \"forbidden\", reason: message || \"Forbidden\" };\n case \"CONFLICT\":\n return { kind: \"conflict\", message: message || \"Conflict\" };\n case \"NOT_FOUND\":\n return { kind: \"not_found\" };\n case \"TOO_MANY_REQUESTS\":\n return { kind: \"rate_limited\", retryAfter: pickRetryAfter(data) };\n case \"BAD_REQUEST\":\n case \"UNPROCESSABLE_CONTENT\": {\n const issues = pickIssues(data);\n if (issues) return { kind: \"validation\", issues };\n // No structured issues — still carry the server's explanation so it\n // isn't dropped into a bare status code.\n return { kind: \"server\", status, message };\n }\n default:\n return { kind: \"server\", status, message };\n }\n }\n\n return { kind: \"server\", status: 0 };\n}\n","export interface EventBus<T> {\n readonly on: (listener: (value: T) => void) => () => void;\n readonly emit: (value: T) => void;\n}\n\nexport function createEventBus<T>(): EventBus<T> {\n const listeners = new Set<(value: T) => void>();\n return {\n on: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n emit: (value) => {\n for (const listener of listeners) {\n try {\n listener(value);\n } catch (err) {\n // A buggy listener must not break siblings or the calling flow.\n console.error(\"[fytkit-sdk] event listener threw\", err);\n }\n }\n },\n };\n}\n","import { normalizeError } from \"./error\";\nimport { createEventBus } from \"./events\";\nimport type { Transport } from \"./transport\";\nimport type {\n AuthState,\n FytkitError,\n SecurityStatus,\n Session,\n SessionInfo,\n SignInResult,\n TokenStorage,\n TotpEnrollment,\n TwoFactorChallenge,\n TwoFactorToken,\n} from \"./types\";\n\nexport interface AuthNamespaceOptions {\n readonly transport: Transport;\n readonly storage: TokenStorage;\n /** Called after the SDK signs out for any reason (manual, refresh failure). */\n readonly onSignedOut?: () => void;\n}\n\nexport interface AuthNamespace {\n readonly signUp: (input: { email: string; password: string; name: string }) => Promise<Session>;\n readonly signIn: (input: { email: string; password: string }) => Promise<SignInResult>;\n readonly signOut: () => Promise<void>;\n readonly getSession: () => Session | null;\n readonly onAuthStateChange: (listener: (state: AuthState) => void) => () => void;\n readonly requestPasswordReset: (input: { email: string }) => Promise<void>;\n readonly confirmPasswordReset: (input: { token: string; password: string }) => Promise<void>;\n readonly confirmEmail: (input: { token: string }) => Promise<void>;\n readonly verifyTotp: (input: {\n challenge: TwoFactorChallenge;\n code: string;\n }) => Promise<Session>;\n readonly verifyBackupCode: (input: {\n challenge: TwoFactorChallenge;\n code: string;\n }) => Promise<Session>;\n readonly requestEmailOtp: (input: { challenge: TwoFactorChallenge }) => Promise<void>;\n readonly verifyEmailOtp: (input: {\n challenge: TwoFactorChallenge;\n code: string;\n }) => Promise<Session>;\n readonly getSecurityStatus: () => Promise<SecurityStatus>;\n readonly enableTotp: (input: { password: string }) => Promise<TotpEnrollment>;\n readonly verifyTotpSetup: (input: { code: string }) => Promise<void>;\n readonly disableTwoFactor: (input: { password: string }) => Promise<void>;\n readonly regenerateBackupCodes: (input: { password: string }) => Promise<readonly string[]>;\n readonly changePassword: (input: {\n currentPassword: string;\n newPassword: string;\n revokeOtherSessions?: boolean;\n }) => Promise<void>;\n readonly changeEmail: (input: { newEmail: string }) => Promise<void>;\n readonly listSessions: () => Promise<readonly SessionInfo[]>;\n readonly revokeSession: (input: { revokeId: string }) => Promise<void>;\n readonly revokeOtherSessions: () => Promise<void>;\n /** Internal: force a refresh now. Wired by transport's 401 retry path. */\n readonly _refresh: () => Promise<Session>;\n /** Internal: clear cached session + emit signed_out. */\n readonly _signOutLocal: () => void;\n}\n\n/**\n * Schedule a proactive refresh this many ms before `expiresAt`. The\n * server-side access-token TTL is ~15 min so a 60-second lead time gives\n * us enough headroom to refresh transparently without burning sessions\n * needlessly while keeping the user signed-in across long-running tabs.\n */\nconst PROACTIVE_REFRESH_LEAD_MS = 60_000;\n\n/**\n * The auth namespace owns the cached session. It is the single writer to\n * `storage`; everything else reads via `getSession`. Calls that mutate\n * the session also emit on the event bus and (re)schedule the proactive\n * refresh timer against the new expiry.\n */\nexport function createAuthNamespace(opts: AuthNamespaceOptions): AuthNamespace {\n const bus = createEventBus<AuthState>();\n let cached: Session | null = null;\n let timer: ReturnType<typeof setTimeout> | null = null;\n // Forward declaration so scheduleRefresh can call the same _refresh body\n // the public surface exposes. Assigned at the bottom of the factory.\n let refreshFn: () => Promise<Session> = () => {\n throw new Error(\"refreshFn called before initialization\");\n };\n\n function clearTimer(): void {\n if (timer !== null) {\n clearTimeout(timer);\n timer = null;\n }\n }\n\n // `setTimeout` clamps any delay > 2^31-1 ms (~24.8 days) to 1 ms and\n // prints a Node deprecation warning. Sessions with an exotic far-future\n // expiry (test fixtures, mis-configured server) would otherwise fire the\n // timer instantly; cap the delay to the safe upper bound so the timer\n // simply re-arms on its next firing.\n const MAX_TIMEOUT_MS = 2_147_483_647;\n\n function scheduleRefresh(session: Session): void {\n clearTimer();\n const expiresMs = new Date(session.expiresAt).getTime();\n if (Number.isNaN(expiresMs)) return; // bad date — bail; reactive 401 path will handle it\n const rawDelay = expiresMs - Date.now() - PROACTIVE_REFRESH_LEAD_MS;\n const delay = Math.min(MAX_TIMEOUT_MS, Math.max(0, rawDelay));\n timer = setTimeout(() => {\n timer = null;\n void refreshFn().catch(() => {\n // refreshFn already handles sign-out on failure.\n });\n }, delay);\n }\n\n function applySession(session: Session, event: \"signed_in\" | \"session_refreshed\"): Session {\n cached = session;\n void opts.storage.set(session);\n bus.emit({ type: event, session });\n scheduleRefresh(session);\n return session;\n }\n\n function clearSession(emit = true): void {\n cached = null;\n clearTimer();\n void opts.storage.remove();\n if (emit) bus.emit({ type: \"signed_out\" });\n opts.onSignedOut?.();\n }\n\n async function call<T>(thunk: () => Promise<T>): Promise<T> {\n try {\n return await thunk();\n } catch (err) {\n throw normalizeError(err);\n }\n }\n\n // Best-effort hydrate at construction. If the storage already holds a\n // session (warm reload, second tab), restore it and arm the timer.\n void Promise.resolve(opts.storage.get()).then((s) => {\n if (s) {\n cached = s;\n scheduleRefresh(s);\n }\n });\n\n const signUp: AuthNamespace[\"signUp\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.signUp(input));\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n };\n\n const signIn: AuthNamespace[\"signIn\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.signIn(input));\n if (result.data.kind === \"two_factor_required\") {\n // Mint the branded token exactly once at the network boundary.\n const token = result.data.twoFactorToken as TwoFactorToken;\n return {\n kind: \"two_factor_required\",\n challenge: { token, availableMethods: result.data.availableMethods },\n };\n }\n if (result.data.kind === \"signed_in\") {\n const { user, session } = result.data;\n const cached = applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n return { kind: \"signed_in\", session: cached };\n }\n // Exhaustiveness guard — a future server-side variant must not silently fall through.\n const _exhaustive: never = result.data;\n throw _exhaustive;\n };\n\n const signOut: AuthNamespace[\"signOut\"] = async () => {\n const current = cached;\n if (!current) return;\n try {\n await opts.transport.client.auth.signOut({ token: current.accessToken });\n } catch (err) {\n // Even if the server rejects (e.g. token already revoked), clear\n // the local cache so the user is signed out client-side.\n void err;\n }\n clearSession();\n };\n\n const getSession: AuthNamespace[\"getSession\"] = () => cached;\n const onAuthStateChange: AuthNamespace[\"onAuthStateChange\"] = (listener) => bus.on(listener);\n\n const requestPasswordReset: AuthNamespace[\"requestPasswordReset\"] = async (input) => {\n await call(() => opts.transport.client.auth.requestPasswordReset(input));\n };\n const confirmPasswordReset: AuthNamespace[\"confirmPasswordReset\"] = async (input) => {\n await call(() => opts.transport.client.auth.confirmPasswordReset(input));\n };\n const confirmEmail: AuthNamespace[\"confirmEmail\"] = async (input) => {\n await call(() => opts.transport.client.auth.confirmEmail(input));\n };\n\n // --- Two-factor sign-in completion -----------------------------------------\n //\n // Each consumes the challenge minted by `signIn` and, on success, caches the\n // issued session exactly like the signed_in branch of `signIn`.\n\n const verifyTotp: AuthNamespace[\"verifyTotp\"] = async (input) => {\n const result = await call(() =>\n opts.transport.client.auth.verifyTotp({ token: input.challenge.token, code: input.code }),\n );\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n };\n\n const verifyBackupCode: AuthNamespace[\"verifyBackupCode\"] = async (input) => {\n const result = await call(() =>\n opts.transport.client.auth.verifyBackupCode({\n token: input.challenge.token,\n code: input.code,\n }),\n );\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n };\n\n const requestEmailOtp: AuthNamespace[\"requestEmailOtp\"] = async (input) => {\n await call(() => opts.transport.client.auth.requestEmailOtp({ token: input.challenge.token }));\n };\n\n const verifyEmailOtp: AuthNamespace[\"verifyEmailOtp\"] = async (input) => {\n const result = await call(() =>\n opts.transport.client.auth.verifyEmailOtp({ token: input.challenge.token, code: input.code }),\n );\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"signed_in\",\n );\n };\n\n /**\n * The server rotated the calling session and returned the replacement token\n * (TOTP-setup verification and password change with revokeOtherSessions do\n * this). Swap the cached token immediately — the old bearer is already dead,\n * so any request between now and the swap would 401. `expiresAt` is carried\n * over from the old session; it is at worst *earlier* than the new session's\n * real expiry, so the proactive refresh timer fires early and corrects it.\n */\n function adoptRotatedToken(accessToken: string): void {\n const current = cached;\n if (!current || !accessToken || accessToken === current.accessToken) return;\n applySession({ ...current, accessToken }, \"session_refreshed\");\n }\n\n const getSecurityStatus: AuthNamespace[\"getSecurityStatus\"] = async () => {\n const result = await call(() => opts.transport.client.auth.getSecurityStatus());\n return result.data;\n };\n\n const enableTotp: AuthNamespace[\"enableTotp\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.enableTotp(input));\n return result.data;\n };\n\n const verifyTotpSetup: AuthNamespace[\"verifyTotpSetup\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.verifyTotpSetup(input));\n adoptRotatedToken(result.data.accessToken);\n };\n\n const disableTwoFactor: AuthNamespace[\"disableTwoFactor\"] = async (input) => {\n await call(() => opts.transport.client.auth.disableTwoFactor(input));\n };\n\n const regenerateBackupCodes: AuthNamespace[\"regenerateBackupCodes\"] = async (input) => {\n const result = await call(() => opts.transport.client.auth.regenerateBackupCodes(input));\n return result.data.backupCodes;\n };\n\n // --- Account security -------------------------------------------------------\n\n const changePassword: AuthNamespace[\"changePassword\"] = async (input) => {\n const result = await call(() =>\n opts.transport.client.auth.changePassword({\n currentPassword: input.currentPassword,\n newPassword: input.newPassword,\n revokeOtherSessions: input.revokeOtherSessions,\n }),\n );\n adoptRotatedToken(result.data.accessToken);\n };\n\n const changeEmail: AuthNamespace[\"changeEmail\"] = async (input) => {\n await call(() => opts.transport.client.auth.changeEmail(input));\n };\n\n const listSessions: AuthNamespace[\"listSessions\"] = async () => {\n const result = await call(() => opts.transport.client.auth.listSessions());\n return result.data;\n };\n\n const revokeSession: AuthNamespace[\"revokeSession\"] = async (input) => {\n await call(() => opts.transport.client.auth.revokeSession(input));\n };\n\n const revokeOtherSessions: AuthNamespace[\"revokeOtherSessions\"] = async () => {\n await call(() => opts.transport.client.auth.revokeOtherSessions());\n };\n\n const _refresh: AuthNamespace[\"_refresh\"] = async () => {\n // Re-read storage as a fallback so a session written after\n // construction (e.g. on tab restore or in tests) is honoured.\n let current = cached;\n if (!current) {\n const fromStorage = await Promise.resolve(opts.storage.get());\n if (fromStorage) {\n cached = fromStorage;\n current = fromStorage;\n }\n }\n if (!current) {\n const err: FytkitError = { kind: \"auth_required\" };\n throw err;\n }\n try {\n const result = await opts.transport.client.auth.refresh({ token: current.accessToken });\n const { user, session } = result.data;\n return applySession(\n { accessToken: session.accessToken, expiresAt: session.expiresAt, user },\n \"session_refreshed\",\n );\n } catch (err) {\n clearSession();\n throw normalizeError(err);\n }\n };\n\n const _signOutLocal: AuthNamespace[\"_signOutLocal\"] = () => clearSession();\n\n refreshFn = _refresh;\n\n return {\n signUp,\n signIn,\n signOut,\n getSession,\n onAuthStateChange,\n requestPasswordReset,\n confirmPasswordReset,\n confirmEmail,\n verifyTotp,\n verifyBackupCode,\n requestEmailOtp,\n verifyEmailOtp,\n getSecurityStatus,\n enableTotp,\n verifyTotpSetup,\n disableTwoFactor,\n regenerateBackupCodes,\n changePassword,\n changeEmail,\n listSessions,\n revokeSession,\n revokeOtherSessions,\n _refresh,\n _signOutLocal,\n };\n}\n","import { normalizeError } from \"./error\";\nimport type { Transport } from \"./transport\";\n\n/**\n * Wrap every method on a public-router slice so thrown ORPCErrors become\n * normalised FytkitErrors at the SDK boundary.\n *\n * The slice we receive is an `@orpc/client` Proxy whose own keys are not\n * enumerable — every property lookup is intercepted lazily. We mirror that\n * shape by returning a Proxy of our own that wraps each function on first\n * access and caches the result. This way the SDK never needs to know the\n * method names ahead of time, and the typed shape from the server router\n * flows through unchanged.\n */\nfunction wrapSlice<T extends object>(slice: T): T {\n const cache = new Map<string | symbol, unknown>();\n return new Proxy(slice, {\n get(target, prop, receiver) {\n if (cache.has(prop)) return cache.get(prop);\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== \"function\") {\n // Allow nested namespaces to flow through unchanged (the orpc\n // proxy returns another proxy here, not a plain object).\n return value;\n }\n const wrapped = async (...args: unknown[]) => {\n try {\n return await (value as (...a: unknown[]) => Promise<unknown>)(...args);\n } catch (err) {\n throw normalizeError(err);\n }\n };\n cache.set(prop, wrapped);\n return wrapped;\n },\n }) as T;\n}\n\nexport interface DataNamespaces {\n readonly workouts: Transport[\"client\"][\"workout\"];\n readonly programs: Transport[\"client\"][\"program\"];\n readonly recipes: Transport[\"client\"][\"recipe\"];\n readonly nutrition: Transport[\"client\"][\"nutrition\"];\n readonly articles: Transport[\"client\"][\"article\"];\n readonly enrollments: Transport[\"client\"][\"enrollment\"];\n readonly sessionLogs: Transport[\"client\"][\"sessionLog\"];\n readonly progression: Transport[\"client\"][\"progression\"];\n readonly bodyMetrics: Transport[\"client\"][\"bodyMetric\"];\n readonly progress: Transport[\"client\"][\"progress\"];\n readonly media: Transport[\"client\"][\"media\"];\n readonly appConfig: Transport[\"client\"][\"appConfig\"];\n readonly subscription: Transport[\"client\"][\"subscription\"];\n readonly profile: Transport[\"client\"][\"profile\"];\n readonly nutritionLog: Transport[\"client\"][\"nutritionLog\"];\n readonly preferences: Transport[\"client\"][\"preferences\"];\n}\n\nexport function createDataNamespaces(transport: Transport): DataNamespaces {\n const c = transport.client;\n return {\n workouts: wrapSlice(c.workout),\n programs: wrapSlice(c.program),\n recipes: wrapSlice(c.recipe),\n nutrition: wrapSlice(c.nutrition),\n articles: wrapSlice(c.article),\n enrollments: wrapSlice(c.enrollment),\n sessionLogs: wrapSlice(c.sessionLog),\n progression: wrapSlice(c.progression),\n bodyMetrics: wrapSlice(c.bodyMetric),\n progress: wrapSlice(c.progress),\n media: wrapSlice(c.media),\n appConfig: wrapSlice(c.appConfig),\n subscription: wrapSlice(c.subscription),\n profile: wrapSlice(c.profile),\n nutritionLog: wrapSlice(c.nutritionLog),\n preferences: wrapSlice(c.preferences),\n };\n}\n","import type { Session, TokenStorage } from \"./types\";\n\nconst STORAGE_KEY_PREFIX = \"fytkit:\";\nconst STORAGE_KEY_SUFFIX = \":tokens\";\n\nfunction keyFor(clientId: string): string {\n return `${STORAGE_KEY_PREFIX}${clientId}${STORAGE_KEY_SUFFIX}`;\n}\n\nfunction isValidSession(value: unknown): value is Session {\n if (!value || typeof value !== \"object\") return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.accessToken === \"string\" &&\n typeof v.expiresAt === \"string\" &&\n typeof v.user === \"object\" &&\n v.user !== null &&\n typeof (v.user as { id?: unknown }).id === \"string\" &&\n typeof (v.user as { email?: unknown }).email === \"string\"\n );\n}\n\n/**\n * Default web storage. Reads/writes JSON under `fytkit:{clientId}:tokens`.\n * Silently no-ops when localStorage throws (Safari private mode, SSR).\n */\nexport function createLocalStorageAdapter(clientId: string): TokenStorage {\n const key = keyFor(clientId);\n return {\n get: () => {\n try {\n const raw = globalThis.localStorage?.getItem(key);\n if (!raw) return null;\n const parsed: unknown = JSON.parse(raw);\n return isValidSession(parsed) ? parsed : null;\n } catch {\n return null;\n }\n },\n set: (session: Session) => {\n try {\n globalThis.localStorage?.setItem(key, JSON.stringify(session));\n } catch {\n // Quota / private-mode / SSR — swallow and let the caller treat the\n // session as in-memory-only for this tab.\n }\n },\n remove: () => {\n try {\n globalThis.localStorage?.removeItem(key);\n } catch {\n // see set() rationale\n }\n },\n };\n}\n\n/** In-memory storage. Useful for tests and SSR. */\nexport function createMemoryStorageAdapter(): TokenStorage {\n let current: Session | null = null;\n return {\n get: () => current,\n set: (session: Session) => {\n current = session;\n },\n remove: () => {\n current = null;\n },\n };\n}\n","import type { PublicApi } from \"@fytkit/types\";\nimport { createORPCClient } from \"@orpc/client\";\nimport { RPCLink } from \"@orpc/client/fetch\";\nimport type { Session } from \"./types\";\n\nexport interface CreateTransportOptions {\n readonly baseUrl: string;\n readonly clientId: string;\n readonly getSession: () => Session | null;\n readonly fetch?: typeof fetch;\n}\n\nexport interface Transport {\n readonly client: PublicApi;\n /** Internal: hook for attachRefreshInterceptor to install a fetch wrapper. */\n readonly _setFetchInterceptor: (interceptor: FetchInterceptor) => void;\n}\n\ntype FetchInterceptor = (\n request: Request,\n next: (req: Request) => Promise<Response>,\n) => Promise<Response>;\n\nexport function createTransport(options: CreateTransportOptions): Transport {\n let interceptor: FetchInterceptor | null = null;\n const baseFetch: typeof fetch = options.fetch ?? fetch.bind(globalThis);\n\n // The fetch handed to RPCLink resolves the interceptor lazily so callers\n // can install one after construction (see attachRefreshInterceptor).\n const wrappedFetch: typeof fetch = (input, init) => {\n const request = input instanceof Request ? input : new Request(input, init);\n const next = (req: Request) => baseFetch(req);\n if (!interceptor) return next(request);\n return interceptor(request, next);\n };\n\n const link = new RPCLink({\n url: () => `${options.baseUrl}/rpc`,\n headers: () => {\n const session = options.getSession();\n const headers: Record<string, string> = {\n \"X-Fytkit-Client-Id\": options.clientId,\n };\n if (session) {\n headers.Authorization = `Bearer ${session.accessToken}`;\n }\n return headers;\n },\n fetch: wrappedFetch,\n });\n\n const client: PublicApi = createORPCClient(link);\n return {\n client,\n _setFetchInterceptor: (i) => {\n interceptor = i;\n },\n };\n}\n\n/** Internal marker header — set on the refresh call so we never recurse. */\nconst REFRESH_HEADER = \"X-Fytkit-Refresh\";\n\n/**\n * Detect whether a request targets the refresh procedure. The RPCLink\n * routes per-procedure calls under a URL whose pathname ends with the\n * procedure path (joined as `/segment/segment`), so we look for the\n * `auth/refresh` suffix. We use endsWith so trailing query strings or\n * link-level prefixes do not break detection.\n */\nfunction isRefreshRequest(request: Request): boolean {\n if (request.headers.get(REFRESH_HEADER) === \"1\") return true;\n try {\n const path = new URL(request.url).pathname;\n return path.endsWith(\"/auth/refresh\");\n } catch {\n return false;\n }\n}\n\nexport interface AttachRefreshInterceptorOptions {\n readonly transport: Transport;\n readonly auth: {\n readonly _refresh: () => Promise<Session>;\n readonly _signOutLocal: () => void;\n readonly getSession: () => Session | null;\n };\n}\n\n/**\n * Install a fetch interceptor that, on a 401 response, calls auth._refresh\n * once and retries the original request. Concurrent 401s de-duplicate\n * onto a single in-flight refresh promise. A 401 from refresh itself or\n * from the retry triggers a local sign-out and propagates the original\n * 401 to the caller (after which orpc throws ORPCError(\"UNAUTHORIZED\")).\n */\nexport function attachRefreshInterceptor(opts: AttachRefreshInterceptorOptions): void {\n let inflight: Promise<Session> | null = null;\n\n const refreshOnce = (): Promise<Session> => {\n if (!inflight) {\n inflight = opts.auth._refresh().finally(() => {\n inflight = null;\n });\n }\n return inflight;\n };\n\n opts.transport._setFetchInterceptor(async (request, next) => {\n // Refresh calls must never trigger a recursive refresh.\n if (isRefreshRequest(request)) {\n return next(request);\n }\n\n // Capture the request body now, before we pass `request` to `next` —\n // once fetch consumes a Request body it can no longer be cloned.\n const buffered = await request.clone().arrayBuffer();\n\n const firstResponse = await next(request);\n if (firstResponse.status !== 401) return firstResponse;\n\n try {\n await refreshOnce();\n } catch {\n // _refresh already called clearSession + emitted signed_out.\n return firstResponse;\n }\n\n // Rebuild headers so the new Authorization header replaces the stale\n // one — the RPCLink only re-evaluates its own `headers()` once per call,\n // so we patch the bearer ourselves here.\n const replayedHeaders = new Headers(request.headers);\n const session = opts.auth.getSession();\n if (session) {\n replayedHeaders.set(\"Authorization\", `Bearer ${session.accessToken}`);\n } else {\n replayedHeaders.delete(\"Authorization\");\n }\n const replayed = new Request(request.url, {\n method: request.method,\n headers: replayedHeaders,\n body: buffered.byteLength > 0 ? buffered : undefined,\n credentials: request.credentials,\n mode: request.mode,\n cache: request.cache,\n redirect: request.redirect,\n referrer: request.referrer,\n integrity: request.integrity,\n });\n\n const retried = await next(replayed);\n if (retried.status === 401) {\n // Refresh succeeded server-side but the server still rejects — the\n // session is dead. Sign out locally and let orpc surface the 401.\n opts.auth._signOutLocal();\n }\n return retried;\n });\n}\n","import { createAuthNamespace } from \"./auth\";\nimport { createDataNamespaces } from \"./data\";\nimport { createLocalStorageAdapter, createMemoryStorageAdapter } from \"./storage\";\nimport { attachRefreshInterceptor, createTransport } from \"./transport\";\nimport type { FytkitClient, FytkitClientOptions } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://api.fytkit.com\";\n\nexport function createFytkitClient(options: FytkitClientOptions): FytkitClient {\n if (!options || typeof options.clientId !== \"string\" || options.clientId.length === 0) {\n throw new Error(\"createFytkitClient: `clientId` is required\");\n }\n\n const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n const storage = options.storage ?? createLocalStorageAdapter(options.clientId);\n\n // `auth` is declared after `transport` because `createAuthNamespace`\n // needs the transport to make its RPC calls. The transport in turn needs\n // a `getSession` that reads the auth cache — we resolve the cycle with a\n // late-bound reference: the closure below reads `auth` lazily, which is\n // safe because no request can fire before construction finishes.\n let auth: ReturnType<typeof createAuthNamespace> | null = null;\n\n const transport = createTransport({\n baseUrl,\n clientId: options.clientId,\n getSession: () => auth?.getSession() ?? null,\n fetch: options.fetch,\n });\n\n const authInstance = createAuthNamespace({ transport, storage });\n auth = authInstance;\n attachRefreshInterceptor({ transport, auth: authInstance });\n\n const data = createDataNamespaces(transport);\n\n return {\n auth: {\n signUp: authInstance.signUp,\n signIn: authInstance.signIn,\n signOut: authInstance.signOut,\n getSession: authInstance.getSession,\n onAuthStateChange: authInstance.onAuthStateChange,\n requestPasswordReset: authInstance.requestPasswordReset,\n confirmPasswordReset: authInstance.confirmPasswordReset,\n confirmEmail: authInstance.confirmEmail,\n verifyTotp: authInstance.verifyTotp,\n verifyBackupCode: authInstance.verifyBackupCode,\n requestEmailOtp: authInstance.requestEmailOtp,\n verifyEmailOtp: authInstance.verifyEmailOtp,\n getSecurityStatus: authInstance.getSecurityStatus,\n enableTotp: authInstance.enableTotp,\n verifyTotpSetup: authInstance.verifyTotpSetup,\n disableTwoFactor: authInstance.disableTwoFactor,\n regenerateBackupCodes: authInstance.regenerateBackupCodes,\n changePassword: authInstance.changePassword,\n changeEmail: authInstance.changeEmail,\n listSessions: authInstance.listSessions,\n revokeSession: authInstance.revokeSession,\n revokeOtherSessions: authInstance.revokeOtherSessions,\n },\n ...data,\n };\n}\n\n// Public re-exports.\nexport { createLocalStorageAdapter, createMemoryStorageAdapter };\nexport type {\n AuthState,\n FytkitClient,\n FytkitClientOptions,\n FytkitError,\n SecurityStatus,\n Session,\n SessionInfo,\n SignInResult,\n TokenStorage,\n TotpEnrollment,\n TwoFactorChallenge,\n TwoFactorMethod,\n TwoFactorToken,\n} from \"./types\";\n// `PublicApi` is the inferred router type that backs every namespace\n// on `FytkitClient` (e.g. `client.workouts` is `PublicApi[\"workout\"]`).\n// Re-exported so consumers can write generics over the router shape —\n// previously this surfaced as an `ae-forgotten-export` warning on\n// `FytkitClient` in the api-extractor report. The api-extractor will\n// still warn about `PublicRouter`/`publicRouter` being unexported —\n// that is intentional, those are implementation-detail names from the\n// generated snapshot that should not be part of the consumer surface.\nexport type { PublicApi } from \"@fytkit/types\";\n"]}
|