@recovr/sdk 0.0.0-stage → 1.1.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.
Files changed (89) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +21 -0
  3. package/README.md +307 -2
  4. package/dist/cjs/client.d.ts +36 -0
  5. package/dist/cjs/client.js +100 -0
  6. package/dist/cjs/errors.d.ts +31 -0
  7. package/dist/cjs/errors.js +69 -0
  8. package/dist/cjs/generated/client/client.gen.d.ts +2 -0
  9. package/dist/cjs/generated/client/client.gen.js +220 -0
  10. package/dist/cjs/generated/client/index.d.ts +10 -0
  11. package/dist/cjs/generated/client/index.js +17 -0
  12. package/dist/cjs/generated/client/types.gen.d.ts +120 -0
  13. package/dist/cjs/generated/client/types.gen.js +3 -0
  14. package/dist/cjs/generated/client/utils.gen.d.ts +37 -0
  15. package/dist/cjs/generated/client/utils.gen.js +239 -0
  16. package/dist/cjs/generated/client.gen.d.ts +12 -0
  17. package/dist/cjs/generated/client.gen.js +6 -0
  18. package/dist/cjs/generated/core/auth.gen.d.ts +25 -0
  19. package/dist/cjs/generated/core/auth.gen.js +18 -0
  20. package/dist/cjs/generated/core/bodySerializer.gen.d.ts +25 -0
  21. package/dist/cjs/generated/core/bodySerializer.gen.js +60 -0
  22. package/dist/cjs/generated/core/params.gen.d.ts +43 -0
  23. package/dist/cjs/generated/core/params.gen.js +112 -0
  24. package/dist/cjs/generated/core/pathSerializer.gen.d.ts +33 -0
  25. package/dist/cjs/generated/core/pathSerializer.gen.js +115 -0
  26. package/dist/cjs/generated/core/queryKeySerializer.gen.d.ts +18 -0
  27. package/dist/cjs/generated/core/queryKeySerializer.gen.js +98 -0
  28. package/dist/cjs/generated/core/serverSentEvents.gen.d.ts +71 -0
  29. package/dist/cjs/generated/core/serverSentEvents.gen.js +135 -0
  30. package/dist/cjs/generated/core/types.gen.d.ts +83 -0
  31. package/dist/cjs/generated/core/types.gen.js +3 -0
  32. package/dist/cjs/generated/core/utils.gen.d.ts +19 -0
  33. package/dist/cjs/generated/core/utils.gen.js +93 -0
  34. package/dist/cjs/generated/index.d.ts +2 -0
  35. package/dist/cjs/generated/index.js +6 -0
  36. package/dist/cjs/generated/sdk.gen.d.ts +603 -0
  37. package/dist/cjs/generated/sdk.gen.js +2315 -0
  38. package/dist/cjs/generated/types.gen.d.ts +7658 -0
  39. package/dist/cjs/generated/types.gen.js +3 -0
  40. package/dist/cjs/index.d.ts +4 -0
  41. package/dist/cjs/index.js +11 -0
  42. package/dist/cjs/package.json +3 -0
  43. package/dist/cjs/paginate.d.ts +24 -0
  44. package/dist/cjs/paginate.js +18 -0
  45. package/dist/esm/client.d.ts +36 -0
  46. package/dist/esm/client.js +95 -0
  47. package/dist/esm/errors.d.ts +31 -0
  48. package/dist/esm/errors.js +64 -0
  49. package/dist/esm/generated/client/client.gen.d.ts +2 -0
  50. package/dist/esm/generated/client/client.gen.js +216 -0
  51. package/dist/esm/generated/client/index.d.ts +10 -0
  52. package/dist/esm/generated/client/index.js +6 -0
  53. package/dist/esm/generated/client/types.gen.d.ts +120 -0
  54. package/dist/esm/generated/client/types.gen.js +2 -0
  55. package/dist/esm/generated/client/utils.gen.d.ts +37 -0
  56. package/dist/esm/generated/client/utils.gen.js +228 -0
  57. package/dist/esm/generated/client.gen.d.ts +12 -0
  58. package/dist/esm/generated/client.gen.js +3 -0
  59. package/dist/esm/generated/core/auth.gen.d.ts +25 -0
  60. package/dist/esm/generated/core/auth.gen.js +14 -0
  61. package/dist/esm/generated/core/bodySerializer.gen.d.ts +25 -0
  62. package/dist/esm/generated/core/bodySerializer.gen.js +57 -0
  63. package/dist/esm/generated/core/params.gen.d.ts +43 -0
  64. package/dist/esm/generated/core/params.gen.js +109 -0
  65. package/dist/esm/generated/core/pathSerializer.gen.d.ts +33 -0
  66. package/dist/esm/generated/core/pathSerializer.gen.js +106 -0
  67. package/dist/esm/generated/core/queryKeySerializer.gen.d.ts +18 -0
  68. package/dist/esm/generated/core/queryKeySerializer.gen.js +92 -0
  69. package/dist/esm/generated/core/serverSentEvents.gen.d.ts +71 -0
  70. package/dist/esm/generated/core/serverSentEvents.gen.js +132 -0
  71. package/dist/esm/generated/core/types.gen.d.ts +83 -0
  72. package/dist/esm/generated/core/types.gen.js +2 -0
  73. package/dist/esm/generated/core/utils.gen.d.ts +19 -0
  74. package/dist/esm/generated/core/utils.gen.js +87 -0
  75. package/dist/esm/generated/index.d.ts +2 -0
  76. package/dist/esm/generated/index.js +2 -0
  77. package/dist/esm/generated/sdk.gen.d.ts +603 -0
  78. package/dist/esm/generated/sdk.gen.js +2311 -0
  79. package/dist/esm/generated/types.gen.d.ts +7658 -0
  80. package/dist/esm/generated/types.gen.js +2 -0
  81. package/dist/esm/index.d.ts +4 -0
  82. package/dist/esm/index.js +3 -0
  83. package/dist/esm/paginate.d.ts +24 -0
  84. package/dist/esm/paginate.js +15 -0
  85. package/examples/add-lead.ts +45 -0
  86. package/examples/add-note.ts +34 -0
  87. package/examples/export-health-scores.ts +38 -0
  88. package/examples/set-suspension.ts +38 -0
  89. package/package.json +59 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+
5
+ Brings the SDK up to date with the API reference. Nothing in 1.0.0 changed, so upgrading needs no code changes.
6
+
7
+ New methods:
8
+
9
+ - Inbox: `listConversations`, `getConversation`, `listConversationMessages`, `replyToConversation` and `listChannels`.
10
+ - Inbox actions: `markConversationRead`, `markConversationUnread`, `archiveConversation`, `unarchiveConversation`, `markConversationNoReplyNeeded`, `undoConversationNoReplyNeeded` and `linkConversationToClient`; new messages with `sendClientMessage`; `getChannel`. Conversations and messages carry `channel_id`, and their lists filter by it (and messages by `direction` and `status`).
11
+ - Leads: `createLead`, `listLeads`, `getLead`, `listLeadSources`, `archiveLead`, `unarchiveLead`, `archiveClientLeads`, `unarchiveClientLeads`, `listPossibleDuplicates` and `markNotDuplicate`.
12
+ - Reports: `getSummary`, `listActivity` and `getActionsReport`.
13
+ - Custom fields: `listCustomFields`, `getClientCustomFields` and `setClientCustomField`.
14
+ - Labels: `createClientLabel`, `updateClientLabel`, `archiveClientLabel` and `restoreClientLabel`.
15
+ - Timeline: `getClientTimeline`.
16
+ - Attendance: `listClientSessions`, `getClientAttendance`, `getClientMilestones`, `listSessions` and `getClassTimetable`.
17
+ - Reminders: `listReminders` (the location's reminders, across clients), `getReminder` and `assignReminder`.
18
+ - Team: `inviteTeamMember`, `updateTeamMember`, `resendTeamMemberInvite`, `cancelTeamMemberInvite` and `removeTeamMember`, which need the new `team:manage` scope.
19
+ - Next Up: `listNextUp`, `getClientNextUp`, `markNextUpItemDone`, `skipNextUpItem`, `snoozeNextUpItem`, `approveNextUpItem`, `rejectNextUpItem`, `recheckNextUpItem`, `settleNextUpItem` and `openNextUpBatch`.
20
+
21
+ Types:
22
+
23
+ - `KnownAttendanceTrend` lists the `attendance_trend` values in use today. The field stays a string, so a value added later still parses.
24
+ - `KnownNextUpItemKind`, `KnownNextUpApprovalType` and `KnownNextUpOperation` do the same for a Next Up item's `kind`, `approval.type` and `operations`.
25
+ - `TeamMember` gains `role` and `status`, so `listTeamMembers` says each person's role and whether they're still an invite.
26
+ - Fuller descriptions on many fields and parameters, shown in your editor.
27
+
28
+ ## 1.0.0
29
+
30
+ First release: account, clients, client actions, notes, interactions, reminders and forms.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Recovr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,308 @@
1
- # Temporary Holding Version
1
+ # @recovr/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript client for the [Recovr API](https://retention-backend.recovr.com/v1/docs). Read your location's clients, health scores and attendance, form submissions, inbox and reports, and add notes, reminders, leads, replies and client actions from your own tools.
4
+
5
+ Works in Node 20+, Deno, Bun and Cloudflare Workers, and in browsers with an OAuth token. ESM and CommonJS, fully typed.
6
+
7
+ ```sh
8
+ npm install @recovr/sdk
9
+ ```
10
+
11
+ ## Connect
12
+
13
+ There are two kinds of token. Each belongs to one location, and both are passed the same way.
14
+
15
+ **Personal access token**, for your own gym's scripts and integrations. An owner or manager creates one in Recovr under **Account → API**. It starts with `rcvr_sk_` and is a secret, like a password: keep it in your server's environment, and never put it in code that runs in a browser or app, where anyone can read it.
16
+
17
+ ```ts
18
+ import { createRecovrClient } from "@recovr/sdk";
19
+
20
+ const recovr = createRecovrClient({ token: process.env.RECOVR_TOKEN! });
21
+ ```
22
+
23
+ **OAuth**, for apps that other gyms connect, and for anything that runs in a browser. Email support@recovr.com to register your app, then use the authorization code flow with PKCE (details in the [reference](https://retention-backend.recovr.com/v1/docs)). Pass the access token, and refresh it when it expires. A confidential (server-side) app authenticates to the token endpoint with HTTP Basic auth, never `client_secret` in the body; a public app sends `client_id` in the body instead:
24
+
25
+ ```ts
26
+ let refreshToken = savedRefreshToken;
27
+
28
+ const recovr = createRecovrClient({
29
+ token: accessToken,
30
+ onTokenExpired: async () => {
31
+ const response = await fetch("https://retention-backend.recovr.com/api/auth/oauth2/token", {
32
+ method: "POST",
33
+ headers: {
34
+ authorization: `Basic ${btoa(`${CLIENT_ID}:${CLIENT_SECRET}`)}`,
35
+ "content-type": "application/x-www-form-urlencoded",
36
+ },
37
+ body: new URLSearchParams({
38
+ grant_type: "refresh_token",
39
+ refresh_token: refreshToken,
40
+ resource: "https://retention-backend.recovr.com/v1",
41
+ }),
42
+ });
43
+ if (!response.ok) throw new Error(`Refresh failed: ${response.status}`);
44
+ const tokens = await response.json();
45
+ refreshToken = tokens.refresh_token; // each refresh returns a new one: keep it
46
+ return tokens.access_token; // the failed request is retried once with this
47
+ },
48
+ });
49
+ ```
50
+
51
+ Options: `token`, `baseUrl` (defaults to `https://retention-backend.recovr.com/v1`), `fetch`, `onTokenExpired`.
52
+
53
+ ## Make requests
54
+
55
+ Each endpoint in the reference is a method with the same name. Path, query and body are typed from the API contract. Methods resolve to `{ data, response }`, where `data` is the response body.
56
+
57
+ ```ts
58
+ const { data } = await recovr.getClient({ path: { id: 123 } });
59
+ console.log(data.data.name, data.data.health_score);
60
+
61
+ await recovr.createClientNote({
62
+ path: { id: 123 },
63
+ body: { content: "Called about their goals for next term" },
64
+ });
65
+ ```
66
+
67
+ ## Read and answer the inbox
68
+
69
+ List the conversations that need a reply, read one, and reply on its own channel (SMS, email, WhatsApp, Instagram, Messenger). Reading needs `conversations:read`; replying needs `messages:send`, which doesn't include reading. A reply reaches a real person, so keep the automatic `Idempotency-Key` and never resend after a timeout without reading the messages first.
70
+
71
+ ```ts
72
+ import { paginate } from "@recovr/sdk";
73
+
74
+ for await (const conversation of paginate(recovr.listConversations, { query: { needs_reply: "true" } })) {
75
+ const { data } = await recovr.listConversationMessages({ path: { id: conversation.id }, query: { limit: 20 } });
76
+ console.log(conversation.contact_name, data.data[0]?.text);
77
+ }
78
+
79
+ await recovr.replyToConversation({ path: { id: 9876 }, body: { text: "Hi Sam, yes, we can pause it from Monday." } });
80
+ ```
81
+
82
+ Tidy the inbox as staff do, with `conversations:write`: `markConversationRead`, `markConversationUnread`, `archiveConversation`, `unarchiveConversation`, `markConversationNoReplyNeeded` (undo with `undoConversationNoReplyNeeded`), and `linkConversationToClient` for a message from a number Recovr didn't match. Each answers with the conversation as it is afterwards.
83
+
84
+ ```ts
85
+ await recovr.markConversationNoReplyNeeded({ path: { id: 9876 } });
86
+ await recovr.linkConversationToClient({ path: { id: 9877 }, body: { client_id: 12345 } });
87
+ ```
88
+
89
+ Start a text or email to a client who has no conversation yet, or on another channel, with `sendClientMessage` (`messages:send`, the same checks as a reply). Name the channel by kind (`sms` or `email`) or by an id from `listChannels`. On WhatsApp, Instagram or Messenger, reply in the client's conversation instead.
90
+
91
+ ```ts
92
+ await recovr.sendClientMessage({ path: { id: 12345 }, body: { text: "Hi Sam, we missed you this week.", channel: "sms" } });
93
+ ```
94
+
95
+ `recovr.listChannels()` lists the location's channels and whether each can send (`channels:read`); `getChannel` reads one. Every conversation and message names its channel as `channel_id`, and `listConversations` and `listConversationMessages` filter by it.
96
+
97
+ ## Work Next Up
98
+
99
+ `listNextUp` returns today's Next Up list, ranked as the app's Next Up page ranks it: moments (a client to reach out to, and why now), reminders that are due, and approvals (a draft or booking change Recovr AI is holding for a person). Each item's `id` is good for that day, and its `operations` list what it takes now: mark it done, skip it for yourself, snooze the client, or approve or reject an approval. Reading needs `next_up:read` and never uses AI credits; the model-written `why` and an approval's message text also need `conversations:read`. Acting needs `next_up:write`, and approving a held draft sends it, so that also needs `messages:send`.
100
+
101
+ ```ts
102
+ const { data: list } = await recovr.listNextUp({ query: { assigned_to: 42 } });
103
+ for (const item of list.data) {
104
+ console.log(item.rank, item.client_name, item.kind === "moment" ? item.headline : item.reminder?.due_at);
105
+ }
106
+
107
+ await recovr.markNextUpItemDone({ path: { item_id: list.data[0].id } });
108
+ await recovr.snoozeNextUpItem({ path: { item_id: list.data[1].id }, body: { days: 7 } });
109
+
110
+ const { data: forClient } = await recovr.getClientNextUp({ path: { id: 12345 } });
111
+
112
+ // Approvals: send a held draft with your own words, or reject a booking change.
113
+ const { data: approvals } = await recovr.listNextUp({ query: { kinds: "approval" } });
114
+ for (const item of approvals.data) {
115
+ if (item.approval?.type === "held_draft" && item.operations.includes("approve")) {
116
+ await recovr.approveNextUpItem({ path: { item_id: item.id }, body: { text: "Hi Jo, paused from Monday." } });
117
+ } else if (item.operations.includes("reject")) {
118
+ await recovr.rejectNextUpItem({ path: { item_id: item.id } });
119
+ }
120
+ }
121
+
122
+ // Once you've worked through a batch of moments, open the next.
123
+ if (list.batch && list.batch.remaining > 0) await recovr.openNextUpBatch({ body: { after: list.batch.number } });
124
+ ```
125
+
126
+ ## Read attendance and classes
127
+
128
+ Attendance is read-only: the booking platform owns bookings. A client's sessions, attendance counts and milestones need `clients:read`; the location's classes and the class timetable need `sessions:read` (and `clients:read` too to see who booked). Days are the location's calendar days.
129
+
130
+ ```ts
131
+ const { data: sessions } = await recovr.listClientSessions({ path: { id: 12345 }, query: { from: "2026-11-01", to: "2026-11-30" } });
132
+ const { data: attendance } = await recovr.getClientAttendance({ path: { id: 12345 } }); // the last 30 days
133
+ const { data: milestones } = await recovr.getClientMilestones({ path: { id: 12345 } });
134
+
135
+ const { data: today } = await recovr.listSessions(); // today's classes and their bookings
136
+ const { data: timetable } = await recovr.getClassTimetable({ query: { from: "2026-12-02", to: "2026-12-08" } });
137
+ ```
138
+
139
+ ## Read a client's timeline
140
+
141
+ `getClientTimeline` returns everything that happened with a client, newest first, as their profile's timeline shows it. Filter by `type` (`message`, `call`, `note`, `session`, `label_added` and more). It needs `clients:read`; an entry's `content` also needs the permission that guards it elsewhere (`conversations:read` for messages, `notes:read` for notes, calls, logged contact and reminders, `forms:read` for form submissions), and is left out without it.
142
+
143
+ ```ts
144
+ import { paginate } from "@recovr/sdk";
145
+
146
+ for await (const entry of paginate(recovr.getClientTimeline, { path: { id: 12345 }, query: { type: "message,note" } })) {
147
+ console.log(entry.occurred_at, entry.title, entry.content ?? "");
148
+ }
149
+ ```
150
+
151
+ ## Add a lead
152
+
153
+ Send leads from a quiz, a website form or another system. Recovr matches the person to an existing client by email (or phone and first name), or adds them as a new lead, and starts your Lead received workflows once. Pass your own id as `external_id`: sending it again adds nothing. Needs `clients:write` and `contact_details:read`.
154
+
155
+ ```ts
156
+ const { data } = await recovr.createLead({
157
+ body: {
158
+ external_id: "quiz-result-88123",
159
+ first_name: "Sam",
160
+ last_name: "Taylor",
161
+ email: "sam.taylor@example.com",
162
+ phone: "+61 412 345 678",
163
+ source_label: "Website quiz",
164
+ fields: { "What's your main goal?": "Build strength" },
165
+ },
166
+ });
167
+ console.log(data.data.client_id, data.data.created ? "added" : "already added");
168
+ ```
169
+
170
+ Read and work the Leads list with `leads:read` and `leads:write`. A lead is one enquiry; its `status` (`new`, `visited`, `member`) follows what the person did next, so there is nothing to set. The lead's `client_id` is the client to assign, label or add notes to.
171
+
172
+ ```ts
173
+ for await (const lead of paginate(recovr.listLeads, { query: { status: "new", source: "meta_lead_form" } })) {
174
+ console.log(lead.name, lead.campaign_name, lead.submitted_at);
175
+ }
176
+
177
+ await recovr.archiveLead({ path: { id: 90412 } });
178
+ ```
179
+
180
+ `recovr.listLeadSources()` lists the sources, forms and campaigns the location's leads came from, to filter by.
181
+
182
+ ## Custom fields and labels
183
+
184
+ Read the location's custom fields and set a client's value (`clients:read`, `clients:write`). A `select` field takes one of its `options`; `null` clears a value.
185
+
186
+ ```ts
187
+ const { data: fields } = await recovr.listCustomFields();
188
+ const shirtSize = fields.data.find((field) => field.key === "shirt_size")!;
189
+ await recovr.setClientCustomField({ path: { id: 12345, field_id: shirtSize.id }, body: { value: "M" } });
190
+ ```
191
+
192
+ Label a challenge's finishers: create the label once (an existing label of that name comes back instead), add it to each client, then list everyone who has it. Creating, renaming, archiving and restoring labels needs `labels:manage`; archiving takes a label off every client.
193
+
194
+ ```ts
195
+ const { data: label } = await recovr.createClientLabel({ body: { name: "Challenge finisher" } });
196
+ await recovr.addClientLabel({ path: { id: 12345 }, body: { label_id: label.data.id } });
197
+
198
+ for await (const client of paginate(recovr.listClients, { query: { label_ids: String(label.data.id) } })) {
199
+ console.log(client.name);
200
+ }
201
+ ```
202
+
203
+ ## Read form submissions
204
+
205
+ Poll a form's submissions with `after_id`, the highest submission `id` you've stored (`0` the first time). They come oldest first and none is skipped, so the last `id` is all you need to keep. Needs `forms:read`.
206
+
207
+ ```ts
208
+ for await (const submission of paginate(recovr.listFormSubmissions, { path: { id: formId }, query: { after_id: lastId } })) {
209
+ console.log(submission.submitted_at, submission.answers);
210
+ lastId = submission.id;
211
+ }
212
+ ```
213
+
214
+ ## Manage the team
215
+
216
+ `listTeamMembers` lists the team with each person's role and whether they're still an invite (`clients:read`). With `team:manage`, which only an owner's or Manager's token can use, invite someone with a role, resend or cancel an invite, change a role, or remove someone. A token never changes its own person's access or gives a role above theirs, and ownership is handed over in the app.
217
+
218
+ ```ts
219
+ const { data: invited } = await recovr.inviteTeamMember({
220
+ body: { email: "sam.lee@example.com", first_name: "Sam", last_name: "Lee", role: "team_member" },
221
+ });
222
+ await recovr.resendTeamMemberInvite({ path: { id: invited.data.id } });
223
+ await recovr.updateTeamMember({ path: { id: 42 }, body: { role: "manager" } });
224
+ await recovr.removeTeamMember({ path: { id: 57 } });
225
+ ```
226
+
227
+ ## Pagination
228
+
229
+ `paginate` follows `next_cursor` for you and yields one item at a time:
230
+
231
+ ```ts
232
+ import { paginate } from "@recovr/sdk";
233
+
234
+ for await (const client of paginate(recovr.listClients, { query: { risk_level: "high-risk", limit: 200 } })) {
235
+ console.log(client.name, client.health_score);
236
+ }
237
+ ```
238
+
239
+ ## Dashboards and KPIs
240
+
241
+ `getSummary` returns the counts Recovr's reports show: active members, trials, holds and each risk band. `listActivity` lists what the team did, by team member, and `getActionsReport` totals it as the app's Actions Report does. Team member ids match `listTeamMembers`. The API reference's Definitions section explains how each number is counted.
242
+
243
+ ```ts
244
+ const { data: summary } = await recovr.getSummary();
245
+ console.log(summary.data.active_members, summary.data.high_risk);
246
+
247
+ for await (const action of paginate(recovr.listActivity, { query: { from: "2026-10-01", to: "2026-10-31", type: "call,message" } })) {
248
+ console.log(action.occurred_at, action.team_member?.name, action.type);
249
+ }
250
+
251
+ const { data: report } = await recovr.getActionsReport({ query: { from: "2026-10-01", to: "2026-10-31", group_by: "week" } });
252
+ ```
253
+
254
+ ## Errors
255
+
256
+ Error responses throw `RecovrApiError`. Branch on `code`, which is stable; `message` is for people.
257
+
258
+ ```ts
259
+ import { RecovrApiError } from "@recovr/sdk";
260
+
261
+ try {
262
+ await recovr.getClient({ path: { id: 123 } });
263
+ } catch (error) {
264
+ if (error instanceof RecovrApiError && error.code === "not_found") {
265
+ // …
266
+ }
267
+ throw error;
268
+ }
269
+ ```
270
+
271
+ It also has `status`, `requestId` (the response's `X-Request-Id`: quote it to support) and `retryAfter` (seconds, on `429 rate_limited`). Each token can make 600 requests a minute.
272
+
273
+ ## Idempotency
274
+
275
+ The SDK adds an `Idempotency-Key` to every `POST` and `PATCH`. That automatic key covers the SDK's own retry after a token refresh, and nothing else: a new call gets a new key. When your code retries a write (after a timeout, say, or in a later run), pass your own key, such as your record's ID, so the retry can't apply it twice:
276
+
277
+ ```ts
278
+ await recovr.createClientNote({
279
+ path: { id: 123 },
280
+ body: { content: "Signed up for the 6-week challenge" },
281
+ headers: { "Idempotency-Key": `crm-note-${note.id}` },
282
+ });
283
+ ```
284
+
285
+ A retry with the same key returns the first response, errors included. After a `5xx` the change may have been made before the failure, so the same key returns the same error: check whether the change was made, then send it with a new key. If the first request didn't finish recording its result, the same key returns `409 idempotency_outcome_unknown` rather than running the change again: check the record, then use a new key if you still need it. A refusal is kept too (a `404`, a `409`, or a `400` the endpoint itself returned), so after correcting a request the API refused, send it with a new key; only a request that never reached the endpoint (`400` validation, `401`, `403`) isn't kept. The SDK doesn't retry `5xx` responses itself.
286
+
287
+ ## Examples
288
+
289
+ The package includes four runnable scripts in `examples/`:
290
+
291
+ - `export-health-scores.ts`: a nightly CSV of every client's status, health score, risk level and last visit.
292
+ - `add-note.ts`: add a note from your own system, found by the booking platform's client ID, safe to re-run.
293
+ - `add-lead.ts`: add a lead from a quiz or form tool, safe to re-run.
294
+ - `set-suspension.ts`: record a suspended client's reason and expected return date.
295
+
296
+ ```sh
297
+ RECOVR_TOKEN=rcvr_sk_… npx tsx node_modules/@recovr/sdk/examples/export-health-scores.ts health-scores.csv
298
+ ```
299
+
300
+ ## Reference
301
+
302
+ Every endpoint, field and error code, with an SDK sample and example responses for each: [retention-backend.recovr.com/v1/docs](https://retention-backend.recovr.com/v1/docs). The same guide and endpoint list for AI coding assistants is at [/v1/llms.txt](https://retention-backend.recovr.com/v1/llms.txt).
303
+
304
+ Using Recovr from Claude, ChatGPT or Codex rather than from code? Connect the [Recovr MCP server](https://retention.recovr.com/mcp).
305
+
306
+ Changes by version are in [CHANGELOG.md](./CHANGELOG.md).
307
+
308
+ Within v1, the API only adds things. Breaking changes go to a new version with notice.
@@ -0,0 +1,36 @@
1
+ import { type Client } from "./generated/client/index.js";
2
+ import { RecovrSdk } from "./generated/sdk.gen.js";
3
+ export declare const DEFAULT_BASE_URL = "https://retention-backend.recovr.com/v1";
4
+ export interface RecovrClientOptions {
5
+ /**
6
+ * A personal access token (`rcvr_sk_…`) or an OAuth access token. Both are sent as
7
+ * `Authorization: Bearer <token>`. Keep personal access tokens on a server: never ship one in
8
+ * a browser or mobile app.
9
+ */
10
+ token: string;
11
+ /** Defaults to production, `https://retention-backend.recovr.com/v1`. */
12
+ baseUrl?: string;
13
+ /** A fetch implementation. Defaults to the global `fetch` (Node 20+, browsers, Deno, Bun, Workers). */
14
+ fetch?: typeof globalThis.fetch;
15
+ /**
16
+ * Called once when a request comes back 401, e.g. when an OAuth access token has expired.
17
+ * Return a fresh access token (typically from your refresh-token grant) and the request is
18
+ * retried once with it; return nothing to let the 401 surface as a `RecovrApiError`.
19
+ * Concurrent 401s share one call.
20
+ */
21
+ onTokenExpired?: () => string | null | undefined | Promise<string | null | undefined>;
22
+ }
23
+ /**
24
+ * The Recovr API client. Every operation in the reference is a method, named by its
25
+ * operationId: `recovr.listClients(...)`, `recovr.createClientNote(...)`. Methods are bound, so
26
+ * they can be passed around (e.g. to `paginate`).
27
+ *
28
+ * Methods resolve to `{ data, request, response }` and throw `RecovrApiError` for error
29
+ * responses.
30
+ */
31
+ export declare class RecovrClient extends RecovrSdk {
32
+ /** The underlying Hey API fetch client, for interceptors or one-off configuration. */
33
+ readonly http: Client;
34
+ constructor(options: RecovrClientOptions);
35
+ }
36
+ export declare function createRecovrClient(options: RecovrClientOptions): RecovrClient;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecovrClient = exports.DEFAULT_BASE_URL = void 0;
4
+ exports.createRecovrClient = createRecovrClient;
5
+ const index_js_1 = require("./generated/client/index.js");
6
+ const sdk_gen_js_1 = require("./generated/sdk.gen.js");
7
+ const errors_js_1 = require("./errors.js");
8
+ exports.DEFAULT_BASE_URL = "https://retention-backend.recovr.com/v1";
9
+ /** POST and PATCH get an `Idempotency-Key` so a retry can never apply the same write twice. */
10
+ const IDEMPOTENT_METHODS = new Set(["POST", "PATCH"]);
11
+ /**
12
+ * The Recovr API client. Every operation in the reference is a method, named by its
13
+ * operationId: `recovr.listClients(...)`, `recovr.createClientNote(...)`. Methods are bound, so
14
+ * they can be passed around (e.g. to `paginate`).
15
+ *
16
+ * Methods resolve to `{ data, request, response }` and throw `RecovrApiError` for error
17
+ * responses.
18
+ */
19
+ class RecovrClient extends sdk_gen_js_1.RecovrSdk {
20
+ /** The underlying Hey API fetch client, for interceptors or one-off configuration. */
21
+ http;
22
+ constructor(options) {
23
+ const http = createHttpClient(options);
24
+ super({ client: http });
25
+ this.http = http;
26
+ bindMethods(this);
27
+ }
28
+ }
29
+ exports.RecovrClient = RecovrClient;
30
+ function createRecovrClient(options) {
31
+ return new RecovrClient(options);
32
+ }
33
+ function createHttpClient(options) {
34
+ if (!options?.token)
35
+ throw new TypeError("createRecovrClient: `token` is required");
36
+ const http = (0, index_js_1.createClient)((0, index_js_1.createConfig)({
37
+ baseUrl: (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, ""),
38
+ fetch: createRecovrFetch(options),
39
+ throwOnError: true,
40
+ }));
41
+ http.interceptors.error.use((error, response) => (response ? (0, errors_js_1.toRecovrApiError)(error, response) : error));
42
+ return http;
43
+ }
44
+ /**
45
+ * Adds auth and idempotency keys, and retries once on 401 with a token from `onTokenExpired`.
46
+ * Done at the fetch layer so it covers every generated operation the same way.
47
+ */
48
+ function createRecovrFetch(options) {
49
+ let token = options.token;
50
+ let refreshing = null;
51
+ const baseFetch = options.fetch ?? globalThis.fetch;
52
+ if (typeof baseFetch !== "function") {
53
+ throw new TypeError("createRecovrClient: no global fetch available; pass `fetch`");
54
+ }
55
+ const refresh = () => {
56
+ refreshing ??= Promise.resolve()
57
+ .then(() => options.onTokenExpired?.())
58
+ .finally(() => {
59
+ refreshing = null;
60
+ });
61
+ return refreshing;
62
+ };
63
+ return async (input, init) => {
64
+ const request = new Request(input, init);
65
+ if (IDEMPOTENT_METHODS.has(request.method.toUpperCase()) && !request.headers.has("idempotency-key")) {
66
+ request.headers.set("Idempotency-Key", globalThis.crypto.randomUUID());
67
+ }
68
+ const sentToken = token;
69
+ const callerSetAuth = request.headers.has("authorization") || request.headers.has("x-api-key");
70
+ if (!callerSetAuth)
71
+ request.headers.set("Authorization", `Bearer ${sentToken}`);
72
+ // Keep a copy of the body before it is consumed, in case the request has to be retried.
73
+ const retry = options.onTokenExpired && !callerSetAuth ? request.clone() : null;
74
+ const response = await baseFetch(request);
75
+ if (response.status !== 401 || !retry)
76
+ return response;
77
+ // Another request may already have refreshed the token while this one was in flight.
78
+ const fresh = token !== sentToken ? token : await refresh();
79
+ if (!fresh)
80
+ return response;
81
+ token = fresh;
82
+ retry.headers.set("Authorization", `Bearer ${fresh}`);
83
+ // The retry keeps the original Idempotency-Key, so it can't apply a write twice.
84
+ return baseFetch(retry);
85
+ };
86
+ }
87
+ function bindMethods(instance) {
88
+ const seen = new Set();
89
+ for (let proto = Object.getPrototypeOf(instance); proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
90
+ for (const name of Object.getOwnPropertyNames(proto)) {
91
+ if (name === "constructor" || seen.has(name))
92
+ continue;
93
+ seen.add(name);
94
+ const value = instance[name];
95
+ if (typeof value === "function") {
96
+ Object.defineProperty(instance, name, { value: value.bind(instance), configurable: true, writable: true });
97
+ }
98
+ }
99
+ }
100
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * An error response from the Recovr API.
3
+ *
4
+ * `code` is stable and safe to branch on (`not_found`, `forbidden`, `rate_limited`…); `message`
5
+ * is written for people and may change.
6
+ */
7
+ export declare class RecovrApiError extends Error {
8
+ readonly name = "RecovrApiError";
9
+ /** HTTP status, e.g. 404. */
10
+ readonly status: number;
11
+ /** Stable machine-readable code from `{ error: { code } }`. */
12
+ readonly code: string;
13
+ /** The `x-request-id` of the failed request, when the API returned one. Quote it to support. */
14
+ readonly requestId: string | undefined;
15
+ /** Seconds to wait before retrying, from `Retry-After` (sent with 429). */
16
+ readonly retryAfter: number | undefined;
17
+ /** Extra structured detail some errors carry in `error.details`. */
18
+ readonly details: Record<string, unknown> | undefined;
19
+ /** The parsed response body, for anything not covered above. */
20
+ readonly body: unknown;
21
+ constructor(init: {
22
+ status: number;
23
+ code: string;
24
+ message: string;
25
+ requestId?: string;
26
+ retryAfter?: number;
27
+ details?: Record<string, unknown>;
28
+ body?: unknown;
29
+ });
30
+ }
31
+ export declare function toRecovrApiError(body: unknown, response: Response): RecovrApiError;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RecovrApiError = void 0;
4
+ exports.toRecovrApiError = toRecovrApiError;
5
+ /**
6
+ * An error response from the Recovr API.
7
+ *
8
+ * `code` is stable and safe to branch on (`not_found`, `forbidden`, `rate_limited`…); `message`
9
+ * is written for people and may change.
10
+ */
11
+ class RecovrApiError extends Error {
12
+ name = "RecovrApiError";
13
+ /** HTTP status, e.g. 404. */
14
+ status;
15
+ /** Stable machine-readable code from `{ error: { code } }`. */
16
+ code;
17
+ /** The `x-request-id` of the failed request, when the API returned one. Quote it to support. */
18
+ requestId;
19
+ /** Seconds to wait before retrying, from `Retry-After` (sent with 429). */
20
+ retryAfter;
21
+ /** Extra structured detail some errors carry in `error.details`. */
22
+ details;
23
+ /** The parsed response body, for anything not covered above. */
24
+ body;
25
+ constructor(init) {
26
+ super(init.message);
27
+ this.status = init.status;
28
+ this.code = init.code;
29
+ this.requestId = init.requestId;
30
+ this.retryAfter = init.retryAfter;
31
+ this.details = init.details;
32
+ this.body = init.body;
33
+ }
34
+ }
35
+ exports.RecovrApiError = RecovrApiError;
36
+ /** Used only when a response doesn't carry the `{ error: { code, message } }` envelope (e.g. a proxy error page). */
37
+ const CODE_BY_STATUS = {
38
+ 400: "invalid_request",
39
+ 401: "unauthorized",
40
+ 403: "forbidden",
41
+ 404: "not_found",
42
+ 409: "conflict",
43
+ 413: "payload_too_large",
44
+ 422: "invalid_request",
45
+ 429: "rate_limited",
46
+ 500: "internal_error",
47
+ 502: "unavailable",
48
+ 503: "unavailable",
49
+ 504: "unavailable",
50
+ };
51
+ function toRecovrApiError(body, response) {
52
+ const envelope = body?.error;
53
+ const code = typeof envelope?.code === "string" ? envelope.code : (CODE_BY_STATUS[response.status] ?? `http_${response.status}`);
54
+ const message = typeof envelope?.message === "string"
55
+ ? envelope.message
56
+ : typeof body === "string" && body.trim()
57
+ ? body.trim().slice(0, 500)
58
+ : `Recovr API request failed with status ${response.status}`;
59
+ const retryAfterHeader = Number(response.headers.get("retry-after"));
60
+ return new RecovrApiError({
61
+ status: response.status,
62
+ code,
63
+ message,
64
+ requestId: response.headers.get("x-request-id") ?? undefined,
65
+ retryAfter: Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader : undefined,
66
+ details: envelope?.details && typeof envelope.details === "object" ? envelope.details : undefined,
67
+ body,
68
+ });
69
+ }
@@ -0,0 +1,2 @@
1
+ import type { Client, Config } from './types.gen.js';
2
+ export declare const createClient: (config?: Config) => Client;