hyphabase 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +321 -0
- package/dist/index.cjs +1056 -0
- package/dist/index.d.cts +1242 -0
- package/dist/index.d.ts +1242 -0
- package/dist/index.js +1008 -0
- package/package.json +49 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1008 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var HyphaBaseError = class extends Error {
|
|
3
|
+
constructor(status, body) {
|
|
4
|
+
super(body?.message ?? `HyphaBase request failed (${status})`);
|
|
5
|
+
this.status = status;
|
|
6
|
+
this.body = body;
|
|
7
|
+
this.name = "HyphaBaseError";
|
|
8
|
+
this.requiredPermission = body?.required_permission ?? null;
|
|
9
|
+
this.errorType = body?.error?.type ?? null;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The application requires verified email and this person has not
|
|
13
|
+
* verified theirs. Show a "check your inbox" screen and offer
|
|
14
|
+
* auth.resendVerification().
|
|
15
|
+
*/
|
|
16
|
+
get isEmailUnverified() {
|
|
17
|
+
return this.status === 403 && this.errorType === "email_unverified";
|
|
18
|
+
}
|
|
19
|
+
get isPermissionError() {
|
|
20
|
+
return this.status === 403;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// src/auth.ts
|
|
25
|
+
var EXPIRY_MARGIN_MS = 3e4;
|
|
26
|
+
var AuthModule = class {
|
|
27
|
+
constructor(deps) {
|
|
28
|
+
this.deps = deps;
|
|
29
|
+
this.refreshing = null;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Follow the client onto another location. Sign-in and refresh both go
|
|
33
|
+
* to one location's database, so this has to move with setLocation() or
|
|
34
|
+
* a post-switch sign-in would target the previous location.
|
|
35
|
+
*/
|
|
36
|
+
setLocation(locationId) {
|
|
37
|
+
this.deps.locationId = locationId;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Register a new end user (requires the application to have end-user
|
|
41
|
+
* sign-up enabled). Signs the user in on success.
|
|
42
|
+
*/
|
|
43
|
+
async signUp(params) {
|
|
44
|
+
const pair = await this.post("/api/auth/signup", params, {
|
|
45
|
+
Authorization: `Bearer ${this.deps.publishableKey}`
|
|
46
|
+
});
|
|
47
|
+
return this.storeSession(pair);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Sign in with email + password. The publishable key names which
|
|
51
|
+
* application this is and becomes a ceiling on which locations the
|
|
52
|
+
* session can reach - the API re-checks it on every later request, so
|
|
53
|
+
* revoking the key's access kills sessions it already issued too.
|
|
54
|
+
*/
|
|
55
|
+
async signIn(params) {
|
|
56
|
+
const pair = await this.post(
|
|
57
|
+
"/api/auth/login",
|
|
58
|
+
{ ...params, device_name: "hyphabase" },
|
|
59
|
+
{ Authorization: `Bearer ${this.deps.publishableKey}` }
|
|
60
|
+
);
|
|
61
|
+
return this.storeSession(pair);
|
|
62
|
+
}
|
|
63
|
+
/** Revoke the current session server-side and clear it locally. */
|
|
64
|
+
async signOut() {
|
|
65
|
+
const session = this.getSession();
|
|
66
|
+
this.deps.storage.clear();
|
|
67
|
+
if (!session) return;
|
|
68
|
+
try {
|
|
69
|
+
await this.post("/api/auth/logout", void 0, {
|
|
70
|
+
Authorization: `Bearer ${session.accessToken}`
|
|
71
|
+
});
|
|
72
|
+
} catch {
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Email the user a single-use password-reset token (valid 60 minutes).
|
|
77
|
+
* Resolves whether or not the address has an account - the API never
|
|
78
|
+
* says which. Your app hosts the form that takes the token.
|
|
79
|
+
*/
|
|
80
|
+
async forgotPassword(params) {
|
|
81
|
+
await this.post("/api/auth/password/forgot", params, {
|
|
82
|
+
Authorization: `Bearer ${this.deps.publishableKey}`
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Set a new password with the emailed token. Every existing session for
|
|
87
|
+
* the user is revoked, including one stored here - sign in again.
|
|
88
|
+
*/
|
|
89
|
+
async resetPassword(params) {
|
|
90
|
+
await this.post(
|
|
91
|
+
"/api/auth/password/reset",
|
|
92
|
+
{ ...params, password_confirmation: params.password },
|
|
93
|
+
{ Authorization: `Bearer ${this.deps.publishableKey}` }
|
|
94
|
+
);
|
|
95
|
+
this.deps.storage.clear();
|
|
96
|
+
}
|
|
97
|
+
/** Redeem the emailed verification token (sent at sign-up and by resendVerification). */
|
|
98
|
+
async verifyEmail(params) {
|
|
99
|
+
await this.post("/api/auth/email/verify", params, {
|
|
100
|
+
Authorization: `Bearer ${this.deps.publishableKey}`
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Email the signed-in user a fresh verification token. When the
|
|
105
|
+
* application requires verification, this and the rest of the auth
|
|
106
|
+
* surface still answer for an unverified user (error type
|
|
107
|
+
* `email_unverified` elsewhere).
|
|
108
|
+
*/
|
|
109
|
+
async resendVerification() {
|
|
110
|
+
const session = await this.getValidSession();
|
|
111
|
+
if (!session) throw new HyphaBaseError(401, { message: "Not signed in." });
|
|
112
|
+
await this.post("/api/auth/email/resend", void 0, {
|
|
113
|
+
Authorization: `Bearer ${session.accessToken}`
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/** Forget the stored session locally, without calling the API (for when the server already ended it). */
|
|
117
|
+
clearSession() {
|
|
118
|
+
this.deps.storage.clear();
|
|
119
|
+
}
|
|
120
|
+
/** The stored session, if any (may be expired - see getValidSession). */
|
|
121
|
+
getSession() {
|
|
122
|
+
return this.deps.storage.get();
|
|
123
|
+
}
|
|
124
|
+
getUser() {
|
|
125
|
+
return this.getSession()?.user ?? null;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* A session whose access token is safe to use right now, refreshing
|
|
129
|
+
* first when it is expired or about to expire. Null when signed out or
|
|
130
|
+
* the refresh token is no longer valid.
|
|
131
|
+
*/
|
|
132
|
+
async getValidSession() {
|
|
133
|
+
const session = this.getSession();
|
|
134
|
+
if (!session) return null;
|
|
135
|
+
const msLeft = Date.parse(session.expiresAt) - Date.now();
|
|
136
|
+
if (msLeft > EXPIRY_MARGIN_MS) return session;
|
|
137
|
+
return this.refreshSession();
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Swap the refresh token for a new pair. Concurrent callers share one
|
|
141
|
+
* in-flight refresh (rotation makes parallel refreshes self-defeating:
|
|
142
|
+
* the second would replay a consumed token and revoke the family).
|
|
143
|
+
*/
|
|
144
|
+
refreshSession() {
|
|
145
|
+
this.refreshing ?? (this.refreshing = this.doRefresh().finally(() => {
|
|
146
|
+
this.refreshing = null;
|
|
147
|
+
}));
|
|
148
|
+
return this.refreshing;
|
|
149
|
+
}
|
|
150
|
+
async doRefresh() {
|
|
151
|
+
const session = this.getSession();
|
|
152
|
+
if (!session) return null;
|
|
153
|
+
try {
|
|
154
|
+
const pair = await this.post("/api/auth/refresh", {
|
|
155
|
+
refresh_token: session.refreshToken
|
|
156
|
+
});
|
|
157
|
+
return this.storeSession({ ...pair, user: session.user, location_ids: session.locationIds });
|
|
158
|
+
} catch (err) {
|
|
159
|
+
if (err instanceof HyphaBaseError && err.status === 401) {
|
|
160
|
+
this.deps.storage.clear();
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
throw err;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
storeSession(pair) {
|
|
167
|
+
const session = {
|
|
168
|
+
accessToken: pair.token,
|
|
169
|
+
refreshToken: pair.refresh_token,
|
|
170
|
+
expiresAt: pair.expires_at,
|
|
171
|
+
user: pair.user,
|
|
172
|
+
locationIds: pair.location_ids ?? []
|
|
173
|
+
};
|
|
174
|
+
this.deps.storage.set(session);
|
|
175
|
+
return session;
|
|
176
|
+
}
|
|
177
|
+
async post(path, body, headers = {}) {
|
|
178
|
+
const res = await this.deps.fetchImpl(`${this.deps.baseUrl}${path}`, {
|
|
179
|
+
method: "POST",
|
|
180
|
+
headers: {
|
|
181
|
+
Accept: "application/json",
|
|
182
|
+
"HyphaBase-Version": this.deps.apiVersion,
|
|
183
|
+
...this.deps.locationId !== void 0 ? { "X-Location-Id": this.deps.locationId } : {},
|
|
184
|
+
...body !== void 0 ? { "Content-Type": "application/json" } : {},
|
|
185
|
+
...headers
|
|
186
|
+
},
|
|
187
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0
|
|
188
|
+
});
|
|
189
|
+
const text = await res.text();
|
|
190
|
+
let json = null;
|
|
191
|
+
try {
|
|
192
|
+
json = text ? JSON.parse(text) : null;
|
|
193
|
+
} catch {
|
|
194
|
+
json = null;
|
|
195
|
+
}
|
|
196
|
+
if (!res.ok) throw new HyphaBaseError(res.status, json);
|
|
197
|
+
return json;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
// src/clients.ts
|
|
202
|
+
var BASE = "/api/modules/clients";
|
|
203
|
+
function unwrapOperation(res) {
|
|
204
|
+
const body = res;
|
|
205
|
+
return body.data ?? body;
|
|
206
|
+
}
|
|
207
|
+
function subResource(request, base, updateMethod = "PATCH") {
|
|
208
|
+
return {
|
|
209
|
+
list: () => request(base),
|
|
210
|
+
get: async (id) => (await request(`${base}/${id}`)).data,
|
|
211
|
+
create: async (input) => (await request(base, { method: "POST", body: input })).data,
|
|
212
|
+
update: async (id, input) => (await request(`${base}/${id}`, { method: updateMethod, body: input })).data,
|
|
213
|
+
delete: async (id) => {
|
|
214
|
+
await request(`${base}/${id}`, { method: "DELETE" });
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
var ClientsModule = class {
|
|
219
|
+
constructor(request) {
|
|
220
|
+
this.request = request;
|
|
221
|
+
/** Bulk import/export and its background operations. */
|
|
222
|
+
this.importExport = {
|
|
223
|
+
/** CSV template as text. */
|
|
224
|
+
downloadTemplate: () => this.request(`${BASE}/import-export/template`, { raw: true }),
|
|
225
|
+
/** Start a CSV import. */
|
|
226
|
+
import: async (file, locationIds = []) => {
|
|
227
|
+
const form = new FormData();
|
|
228
|
+
form.append("file", file);
|
|
229
|
+
for (const id of locationIds) form.append("location_ids[]", id);
|
|
230
|
+
return unwrapOperation(await this.request(`${BASE}/import-export/import`, { method: "POST", body: form }));
|
|
231
|
+
},
|
|
232
|
+
/** Start an export (filters optional). */
|
|
233
|
+
export: async (params = {}) => unwrapOperation(await this.request(`${BASE}/import-export/export`, { method: "POST", body: params })),
|
|
234
|
+
operations: {
|
|
235
|
+
list: () => this.request(`${BASE}/import-export/operations`),
|
|
236
|
+
get: async (id) => unwrapOperation(await this.request(`${BASE}/import-export/operations/${id}`)),
|
|
237
|
+
/** Finished export file as text (CSV). */
|
|
238
|
+
download: (id) => this.request(`${BASE}/import-export/operations/${id}/download`, {
|
|
239
|
+
raw: true
|
|
240
|
+
}),
|
|
241
|
+
cancel: (id) => this.request(`${BASE}/import-export/operations/${id}/cancel`, { method: "POST" }),
|
|
242
|
+
clear: async () => {
|
|
243
|
+
await this.request(`${BASE}/import-export/operations/clear`, { method: "DELETE" });
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
this.statuses = subResource(request, `${BASE}/client-statuses`, "PUT");
|
|
248
|
+
}
|
|
249
|
+
list(params = {}) {
|
|
250
|
+
const query = new URLSearchParams();
|
|
251
|
+
if (params.search) query.set("search", params.search);
|
|
252
|
+
if (params.page) query.set("page", String(params.page));
|
|
253
|
+
if (params.perPage) query.set("per_page", String(params.perPage));
|
|
254
|
+
const qs = query.toString();
|
|
255
|
+
return this.request(`${BASE}${qs ? `?${qs}` : ""}`);
|
|
256
|
+
}
|
|
257
|
+
async get(id) {
|
|
258
|
+
return (await this.request(`${BASE}/${id}`)).data;
|
|
259
|
+
}
|
|
260
|
+
async create(input) {
|
|
261
|
+
return (await this.request(BASE, { method: "POST", body: input })).data;
|
|
262
|
+
}
|
|
263
|
+
async update(id, input) {
|
|
264
|
+
return (await this.request(`${BASE}/${id}`, { method: "PATCH", body: input })).data;
|
|
265
|
+
}
|
|
266
|
+
/** Soft delete (restorable). */
|
|
267
|
+
async delete(id) {
|
|
268
|
+
await this.request(`${BASE}/${id}`, { method: "DELETE" });
|
|
269
|
+
}
|
|
270
|
+
async restore(id) {
|
|
271
|
+
return (await this.request(`${BASE}/${id}/restore`, { method: "POST" })).data;
|
|
272
|
+
}
|
|
273
|
+
/** Permanent delete - cannot be restored. */
|
|
274
|
+
async forceDelete(id) {
|
|
275
|
+
await this.request(`${BASE}/${id}/force`, { method: "DELETE" });
|
|
276
|
+
}
|
|
277
|
+
/** Notes on one client. */
|
|
278
|
+
notes(clientId) {
|
|
279
|
+
return subResource(this.request, `${BASE}/${clientId}/notes`);
|
|
280
|
+
}
|
|
281
|
+
/** Traits (tags) on one client. */
|
|
282
|
+
traits(clientId) {
|
|
283
|
+
return subResource(this.request, `${BASE}/${clientId}/traits`);
|
|
284
|
+
}
|
|
285
|
+
/** Addresses of one client. */
|
|
286
|
+
addresses(clientId) {
|
|
287
|
+
return subResource(this.request, `${BASE}/${clientId}/addresses`);
|
|
288
|
+
}
|
|
289
|
+
/** Per-location status assignments on one client. */
|
|
290
|
+
locationStatuses(clientId) {
|
|
291
|
+
const base = `${BASE}/${clientId}/statuses`;
|
|
292
|
+
const request = this.request;
|
|
293
|
+
return {
|
|
294
|
+
list: () => request(base),
|
|
295
|
+
assign: (locationId, clientStatusId) => request(base, {
|
|
296
|
+
method: "POST",
|
|
297
|
+
body: { location_id: locationId, client_status_id: clientStatusId }
|
|
298
|
+
}),
|
|
299
|
+
remove: async (locationId) => {
|
|
300
|
+
await request(`${base}/${locationId}`, { method: "DELETE" });
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
// src/employees.ts
|
|
307
|
+
var BASE2 = "/api/modules/employees/users";
|
|
308
|
+
var EmployeesModule = class {
|
|
309
|
+
constructor(request) {
|
|
310
|
+
this.request = request;
|
|
311
|
+
}
|
|
312
|
+
list() {
|
|
313
|
+
return this.request(BASE2);
|
|
314
|
+
}
|
|
315
|
+
async get(id) {
|
|
316
|
+
return (await this.request(`${BASE2}/${id}`)).data;
|
|
317
|
+
}
|
|
318
|
+
async create(input) {
|
|
319
|
+
return (await this.request(BASE2, { method: "POST", body: input })).data;
|
|
320
|
+
}
|
|
321
|
+
/** Partial update - only the fields you send change (last write wins). */
|
|
322
|
+
async update(id, input) {
|
|
323
|
+
return (await this.request(`${BASE2}/${id}`, { method: "PATCH", body: input })).data;
|
|
324
|
+
}
|
|
325
|
+
async delete(id) {
|
|
326
|
+
await this.request(`${BASE2}/${id}`, { method: "DELETE" });
|
|
327
|
+
}
|
|
328
|
+
async deactivate(id) {
|
|
329
|
+
return (await this.request(`${BASE2}/${id}/deactivate`, { method: "POST" })).data;
|
|
330
|
+
}
|
|
331
|
+
async reactivate(id) {
|
|
332
|
+
return (await this.request(`${BASE2}/${id}/reactivate`, { method: "POST" })).data;
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
// src/data.ts
|
|
337
|
+
var CollectionsModule = class {
|
|
338
|
+
constructor(request) {
|
|
339
|
+
this.request = request;
|
|
340
|
+
}
|
|
341
|
+
list() {
|
|
342
|
+
return this.request("/api/modules/data/collections");
|
|
343
|
+
}
|
|
344
|
+
get(slug) {
|
|
345
|
+
return this.request(`/api/modules/data/collections/${encodeURIComponent(slug)}`);
|
|
346
|
+
}
|
|
347
|
+
/** Creates the collection and its table. Field types are fixed for life. */
|
|
348
|
+
create(input) {
|
|
349
|
+
return this.request("/api/modules/data/collections", { method: "POST", body: input });
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Change the schema. A failure reports the operation that failed
|
|
353
|
+
* (`errors["operations.N.…"]`) and leaves the earlier ones applied.
|
|
354
|
+
*/
|
|
355
|
+
update(slug, operations) {
|
|
356
|
+
return this.request(`/api/modules/data/collections/${encodeURIComponent(slug)}`, {
|
|
357
|
+
method: "PATCH",
|
|
358
|
+
body: { operations }
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
/** Soft-deletes: the table is kept 30 days and can be restored. Refused while referenced. */
|
|
362
|
+
delete(slug) {
|
|
363
|
+
return this.request(`/api/modules/data/collections/${encodeURIComponent(slug)}`, { method: "DELETE" });
|
|
364
|
+
}
|
|
365
|
+
restore(slug) {
|
|
366
|
+
return this.request(`/api/modules/data/collections/${encodeURIComponent(slug)}/restore`, { method: "POST" });
|
|
367
|
+
}
|
|
368
|
+
changes(slug) {
|
|
369
|
+
return this.request(`/api/modules/data/collections/${encodeURIComponent(slug)}/changes`);
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Poll until every index of the collection is built (or one failed).
|
|
373
|
+
*/
|
|
374
|
+
async waitUntilReady(slug, { intervalMs = 2e3, timeoutMs = 6e5 } = {}) {
|
|
375
|
+
const deadline = Date.now() + timeoutMs;
|
|
376
|
+
for (; ; ) {
|
|
377
|
+
const { data } = await this.get(slug);
|
|
378
|
+
const building = data.fields.some((f) => f.index_status === "building");
|
|
379
|
+
const failed = data.fields.find((f) => f.index_status === "failed");
|
|
380
|
+
if (failed) throw new Error(`Index build failed for field "${failed.name}" of "${slug}".`);
|
|
381
|
+
if (!building) return data;
|
|
382
|
+
if (Date.now() >= deadline) throw new Error(`Timed out waiting for "${slug}" indexes to build.`);
|
|
383
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
var RecordsModule = class {
|
|
388
|
+
constructor(request, slug) {
|
|
389
|
+
this.request = request;
|
|
390
|
+
this.slug = slug;
|
|
391
|
+
}
|
|
392
|
+
path(id) {
|
|
393
|
+
const base = `/api/modules/data/${encodeURIComponent(this.slug)}/records`;
|
|
394
|
+
return id === void 0 ? base : `${base}/${encodeURIComponent(id)}`;
|
|
395
|
+
}
|
|
396
|
+
list(params = {}) {
|
|
397
|
+
const query = new URLSearchParams();
|
|
398
|
+
for (const [field, spec] of Object.entries(params.filter ?? {})) {
|
|
399
|
+
if (spec === void 0) continue;
|
|
400
|
+
if (spec !== null && typeof spec === "object") {
|
|
401
|
+
for (const [op, value] of Object.entries(spec)) {
|
|
402
|
+
if (value === void 0) continue;
|
|
403
|
+
query.set(`filter[${field}][${op}]`, Array.isArray(value) ? value.join(",") : String(value));
|
|
404
|
+
}
|
|
405
|
+
} else {
|
|
406
|
+
query.set(`filter[${field}]`, String(spec));
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (params.sort) query.set("sort", params.sort);
|
|
410
|
+
if (params.limit !== void 0) query.set("limit", String(params.limit));
|
|
411
|
+
if (params.cursor) query.set("cursor", params.cursor);
|
|
412
|
+
if (params.select?.length) query.set("select", params.select.join(","));
|
|
413
|
+
if (params.include_deleted) query.set("include_deleted", "true");
|
|
414
|
+
const qs = query.toString();
|
|
415
|
+
return this.request(qs ? `${this.path()}?${qs}` : this.path());
|
|
416
|
+
}
|
|
417
|
+
/** Every page of a query, one request at a time. */
|
|
418
|
+
async *iterate(params = {}) {
|
|
419
|
+
let cursor = params.cursor;
|
|
420
|
+
do {
|
|
421
|
+
const page = await this.list({ ...params, cursor });
|
|
422
|
+
for (const record of page.data) yield record;
|
|
423
|
+
cursor = page.meta.next_cursor;
|
|
424
|
+
} while (cursor);
|
|
425
|
+
}
|
|
426
|
+
get(id) {
|
|
427
|
+
return this.request(this.path(id));
|
|
428
|
+
}
|
|
429
|
+
create(input) {
|
|
430
|
+
return this.request(this.path(), { method: "POST", body: input });
|
|
431
|
+
}
|
|
432
|
+
/** Up to 100 records in one request, all or none; errors are keyed `records.N.field`. */
|
|
433
|
+
createMany(inputs) {
|
|
434
|
+
return this.request(`${this.path()}/batch`, { method: "POST", body: { records: inputs } });
|
|
435
|
+
}
|
|
436
|
+
/** Partial: only the fields sent change; `null` clears a field. */
|
|
437
|
+
update(id, input) {
|
|
438
|
+
return this.request(this.path(id), { method: "PATCH", body: input });
|
|
439
|
+
}
|
|
440
|
+
/** Soft delete. 409 while `restrict` references point at it. */
|
|
441
|
+
delete(id) {
|
|
442
|
+
return this.request(this.path(id), { method: "DELETE" });
|
|
443
|
+
}
|
|
444
|
+
restore(id) {
|
|
445
|
+
return this.request(`${this.path(id)}/restore`, { method: "POST" });
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
var DataModule = class {
|
|
449
|
+
constructor(request) {
|
|
450
|
+
this.request = request;
|
|
451
|
+
this.collections = new CollectionsModule(request);
|
|
452
|
+
}
|
|
453
|
+
/** Records of one collection, typed with your field shape. */
|
|
454
|
+
collection(slug) {
|
|
455
|
+
return new RecordsModule(this.request, slug);
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
|
|
459
|
+
// src/files.ts
|
|
460
|
+
var FilesModule = class {
|
|
461
|
+
constructor(request, fetchImpl) {
|
|
462
|
+
this.request = request;
|
|
463
|
+
this.fetchImpl = fetchImpl;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Announce, upload, complete - in one call. Returns the file as the API
|
|
467
|
+
* sees it right after completion (`scan_status` usually `pending`; see
|
|
468
|
+
* `waitUntilScanned`).
|
|
469
|
+
*/
|
|
470
|
+
async upload(data, options) {
|
|
471
|
+
const body = toBody(data);
|
|
472
|
+
const size = options.size ?? byteLength(body);
|
|
473
|
+
const announced = await this.announce({
|
|
474
|
+
name: options.name,
|
|
475
|
+
content_type: options.contentType,
|
|
476
|
+
size,
|
|
477
|
+
metadata: options.metadata
|
|
478
|
+
});
|
|
479
|
+
const put = await this.fetchImpl(announced.upload.url, {
|
|
480
|
+
method: announced.upload.method,
|
|
481
|
+
headers: announced.upload.headers,
|
|
482
|
+
body
|
|
483
|
+
});
|
|
484
|
+
if (!put.ok) {
|
|
485
|
+
throw new HyphaBaseError(put.status, {
|
|
486
|
+
message: `The upload to storage failed with status ${put.status}.`
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
return this.complete(announced.data.id);
|
|
490
|
+
}
|
|
491
|
+
/** Step one of a manual upload: where to PUT the bytes. */
|
|
492
|
+
announce(input) {
|
|
493
|
+
return this.request("/api/modules/files/uploads", { method: "POST", body: input });
|
|
494
|
+
}
|
|
495
|
+
/** Step three of a manual upload: the bytes are in place. */
|
|
496
|
+
async complete(id) {
|
|
497
|
+
const { data } = await this.request(`/api/modules/files/${id}/complete`, {
|
|
498
|
+
method: "POST"
|
|
499
|
+
});
|
|
500
|
+
return data;
|
|
501
|
+
}
|
|
502
|
+
async get(id) {
|
|
503
|
+
const { data } = await this.request(`/api/modules/files/${id}`);
|
|
504
|
+
return data;
|
|
505
|
+
}
|
|
506
|
+
list(params = {}) {
|
|
507
|
+
const qs = new URLSearchParams();
|
|
508
|
+
for (const [key, value] of Object.entries(params)) {
|
|
509
|
+
if (value !== void 0 && value !== null) qs.set(key, String(value));
|
|
510
|
+
}
|
|
511
|
+
const query = qs.toString();
|
|
512
|
+
return this.request(query ? `/api/modules/files?${query}` : "/api/modules/files");
|
|
513
|
+
}
|
|
514
|
+
/** An expiring download URL (default 10 minutes, up to an hour). */
|
|
515
|
+
url(id, options = {}) {
|
|
516
|
+
const qs = options.expiresIn !== void 0 ? `?expires_in=${options.expiresIn}` : "";
|
|
517
|
+
return this.request(`/api/modules/files/${id}/url${qs}`);
|
|
518
|
+
}
|
|
519
|
+
async update(id, input) {
|
|
520
|
+
const { data } = await this.request(`/api/modules/files/${id}`, {
|
|
521
|
+
method: "PATCH",
|
|
522
|
+
body: input
|
|
523
|
+
});
|
|
524
|
+
return data;
|
|
525
|
+
}
|
|
526
|
+
async delete(id) {
|
|
527
|
+
await this.request(`/api/modules/files/${id}`, { method: "DELETE" });
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* Attach a file to a module record (a client, …) in the location whose
|
|
531
|
+
* database holds it. Attaching twice returns the existing link.
|
|
532
|
+
*/
|
|
533
|
+
async attach(id, input) {
|
|
534
|
+
const { data } = await this.request(`/api/modules/files/${id}/attach`, {
|
|
535
|
+
method: "POST",
|
|
536
|
+
body: { target_type: input.targetType, target_id: input.targetId, location_id: input.locationId, label: input.label }
|
|
537
|
+
});
|
|
538
|
+
return data;
|
|
539
|
+
}
|
|
540
|
+
async detach(id, attachmentId) {
|
|
541
|
+
await this.request(`/api/modules/files/${id}/attach/${attachmentId}`, { method: "DELETE" });
|
|
542
|
+
}
|
|
543
|
+
async restore(id) {
|
|
544
|
+
const { data } = await this.request(`/api/modules/files/${id}/restore`, {
|
|
545
|
+
method: "POST"
|
|
546
|
+
});
|
|
547
|
+
return data;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Poll until the virus scan has a verdict. Resolves with the file
|
|
551
|
+
* (`scan_status` clean, infected or failed); rejects on timeout.
|
|
552
|
+
*/
|
|
553
|
+
async waitUntilScanned(id, options = {}) {
|
|
554
|
+
const interval = options.intervalMs ?? 1e3;
|
|
555
|
+
const deadline = Date.now() + (options.timeoutMs ?? 6e4);
|
|
556
|
+
for (; ; ) {
|
|
557
|
+
const file = await this.get(id);
|
|
558
|
+
if (file.scan_status !== "pending") return file;
|
|
559
|
+
if (Date.now() >= deadline) {
|
|
560
|
+
throw new HyphaBaseError(408, {
|
|
561
|
+
message: `File ${id} was still being scanned after ${options.timeoutMs ?? 6e4}ms.`
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
function toBody(data) {
|
|
569
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
570
|
+
return data;
|
|
571
|
+
}
|
|
572
|
+
function byteLength(body) {
|
|
573
|
+
if (typeof body === "string") return new TextEncoder().encode(body).byteLength;
|
|
574
|
+
if (body instanceof Uint8Array) return body.byteLength;
|
|
575
|
+
return body.size;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/locations.ts
|
|
579
|
+
var LocationsModule = class {
|
|
580
|
+
constructor(request) {
|
|
581
|
+
this.request = request;
|
|
582
|
+
}
|
|
583
|
+
list() {
|
|
584
|
+
return this.request("/api/locations", { auth: "optional" });
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
|
|
588
|
+
// src/organizations.ts
|
|
589
|
+
var BASE3 = "/api/modules/organizations";
|
|
590
|
+
var OrganizationsModule = class {
|
|
591
|
+
constructor(request) {
|
|
592
|
+
this.request = request;
|
|
593
|
+
/**
|
|
594
|
+
* There is no `create` or `delete` here. A location is a database, and
|
|
595
|
+
* it comes into existence by being provisioned from the dashboard - a
|
|
596
|
+
* second premises means a second location, with its own client.
|
|
597
|
+
*/
|
|
598
|
+
this.locations = {
|
|
599
|
+
list: () => this.request(`${BASE3}/locations`),
|
|
600
|
+
get: async (id) => (await this.request(`${BASE3}/locations/${id}`)).data,
|
|
601
|
+
update: async (id, input) => (await this.request(`${BASE3}/locations/${id}`, {
|
|
602
|
+
method: "PUT",
|
|
603
|
+
body: input
|
|
604
|
+
})).data
|
|
605
|
+
};
|
|
606
|
+
/** Per-location terminology overrides (client -> Guest, ...). */
|
|
607
|
+
this.languageOverrides = {
|
|
608
|
+
create: (termId, customLabel, customLabelPlural) => this.request(`${BASE3}/language-overrides`, {
|
|
609
|
+
method: "POST",
|
|
610
|
+
body: {
|
|
611
|
+
language_term_id: termId,
|
|
612
|
+
custom_label: customLabel,
|
|
613
|
+
custom_label_plural: customLabelPlural ?? null
|
|
614
|
+
}
|
|
615
|
+
}),
|
|
616
|
+
update: (overrideId, customLabel, customLabelPlural) => this.request(`${BASE3}/language-overrides/${overrideId}`, {
|
|
617
|
+
method: "PUT",
|
|
618
|
+
body: { custom_label: customLabel, custom_label_plural: customLabelPlural ?? null }
|
|
619
|
+
}),
|
|
620
|
+
delete: async (overrideId) => {
|
|
621
|
+
await this.request(`${BASE3}/language-overrides/${overrideId}`, { method: "DELETE" });
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
this.roles = {
|
|
625
|
+
list: () => this.request(`${BASE3}/roles`),
|
|
626
|
+
create: async (input) => (await this.request(`${BASE3}/roles`, { method: "POST", body: input })).data,
|
|
627
|
+
get: async (id) => (await this.request(`${BASE3}/roles/${id}`)).data,
|
|
628
|
+
/** Partial update - only the fields you send change. */
|
|
629
|
+
update: async (id, input) => (await this.request(`${BASE3}/roles/${id}`, { method: "PATCH", body: input })).data
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
/** All registered terms with ids, defaults, and any current override. */
|
|
633
|
+
languageTerms() {
|
|
634
|
+
return this.request(`${BASE3}/language-terms`);
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Resolved Industry Language terms for the current location - a flat
|
|
638
|
+
* key -> label map ("client" -> "Guest", "client.plural" -> "Guests").
|
|
639
|
+
* Drive every UI label from this so each business sees its own words.
|
|
640
|
+
*/
|
|
641
|
+
async language() {
|
|
642
|
+
const res = await this.request(`${BASE3}/language`);
|
|
643
|
+
return res.data;
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
// src/profile.ts
|
|
648
|
+
var ProfileModule = class {
|
|
649
|
+
constructor(request, onSessionRevoked) {
|
|
650
|
+
this.request = request;
|
|
651
|
+
this.onSessionRevoked = onSessionRevoked;
|
|
652
|
+
}
|
|
653
|
+
/** The current user and the permissions they hold at the current location. */
|
|
654
|
+
get() {
|
|
655
|
+
return this.request("/api/auth/me");
|
|
656
|
+
}
|
|
657
|
+
/** Update the user's own details. The API requires both `name` and `email`; send the current email to keep it. */
|
|
658
|
+
update(input) {
|
|
659
|
+
return this.request("/api/auth/session/profile", { method: "PUT", body: input });
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Change the password. The API ends every session the person holds,
|
|
663
|
+
* including this one, so the local session is dropped: sign in again with
|
|
664
|
+
* the new password.
|
|
665
|
+
*/
|
|
666
|
+
async changePassword(params) {
|
|
667
|
+
await this.request("/api/auth/session/password", {
|
|
668
|
+
method: "PUT",
|
|
669
|
+
body: { ...params, password_confirmation: params.password }
|
|
670
|
+
});
|
|
671
|
+
this.onSessionRevoked();
|
|
672
|
+
}
|
|
673
|
+
/** What the credential may do at the current location. */
|
|
674
|
+
permissions() {
|
|
675
|
+
return this.request("/api/permissions/me");
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
// src/schedules.ts
|
|
680
|
+
var BASE4 = "/api/modules/schedules";
|
|
681
|
+
var SchedulesModule = class {
|
|
682
|
+
constructor(request) {
|
|
683
|
+
this.request = request;
|
|
684
|
+
this.plans = {
|
|
685
|
+
list: () => this.request(`${BASE4}/schedule-plans`),
|
|
686
|
+
get: async (id) => (await this.request(`${BASE4}/schedule-plans/${id}`)).data,
|
|
687
|
+
/**
|
|
688
|
+
* Create a plan. Its instances are generated server-side — one for a
|
|
689
|
+
* `one_time` plan, or every occurrence up to three months out for a
|
|
690
|
+
* recurring one. Do not also POST an instance for the same slot.
|
|
691
|
+
*/
|
|
692
|
+
create: async (input) => (await this.request(`${BASE4}/schedule-plans`, { method: "POST", body: input })).data,
|
|
693
|
+
update: async (id, input) => (await this.request(`${BASE4}/schedule-plans/${id}`, { method: "PATCH", body: input })).data,
|
|
694
|
+
delete: async (id) => {
|
|
695
|
+
await this.request(`${BASE4}/schedule-plans/${id}`, { method: "DELETE" });
|
|
696
|
+
},
|
|
697
|
+
restore: async (id) => (await this.request(`${BASE4}/schedule-plans/${id}/restore`, { method: "POST" })).data
|
|
698
|
+
};
|
|
699
|
+
this.instances = {
|
|
700
|
+
list: () => this.request(`${BASE4}/schedule-instances`),
|
|
701
|
+
get: async (id) => (await this.request(`${BASE4}/schedule-instances/${id}`)).data,
|
|
702
|
+
create: async (input) => (await this.request(`${BASE4}/schedule-instances`, { method: "POST", body: input })).data,
|
|
703
|
+
reschedule: (id, input) => this.request(`${BASE4}/schedule-instances/${id}/reschedule`, { method: "POST", body: input }),
|
|
704
|
+
cancel: (id, reason) => this.request(`${BASE4}/schedule-instances/${id}/cancel`, { method: "POST", body: reason ? { reason } : {} }),
|
|
705
|
+
skip: (id, reason) => this.request(`${BASE4}/schedule-instances/${id}/skip`, { method: "POST", body: reason ? { reason } : {} }),
|
|
706
|
+
delete: async (id) => {
|
|
707
|
+
await this.request(`${BASE4}/schedule-instances/${id}`, { method: "DELETE" });
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
checkAvailability(input) {
|
|
712
|
+
return this.request(`${BASE4}/check-availability`, { method: "POST", body: input });
|
|
713
|
+
}
|
|
714
|
+
};
|
|
715
|
+
|
|
716
|
+
// src/services.ts
|
|
717
|
+
var BASE5 = "/api/modules/services";
|
|
718
|
+
var ServicesModule = class {
|
|
719
|
+
constructor(request) {
|
|
720
|
+
this.request = request;
|
|
721
|
+
this.groups = {
|
|
722
|
+
list: () => this.request(`${BASE5}/service-groups`),
|
|
723
|
+
get: async (id) => (await this.request(`${BASE5}/service-groups/${id}`)).data,
|
|
724
|
+
create: async (input) => (await this.request(`${BASE5}/service-groups`, { method: "POST", body: input })).data,
|
|
725
|
+
/** `location_ids` is required here too — a name-only PATCH is rejected. */
|
|
726
|
+
update: async (id, input) => (await this.request(`${BASE5}/service-groups/${id}`, { method: "PATCH", body: input })).data,
|
|
727
|
+
delete: async (id) => {
|
|
728
|
+
await this.request(`${BASE5}/service-groups/${id}`, { method: "DELETE" });
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
list() {
|
|
733
|
+
return this.request(BASE5);
|
|
734
|
+
}
|
|
735
|
+
async get(id) {
|
|
736
|
+
return (await this.request(`${BASE5}/${id}`)).data;
|
|
737
|
+
}
|
|
738
|
+
async create(input) {
|
|
739
|
+
return (await this.request(BASE5, { method: "POST", body: input })).data;
|
|
740
|
+
}
|
|
741
|
+
/** Partial update - only the fields you send change (last write wins). */
|
|
742
|
+
async update(id, input) {
|
|
743
|
+
return (await this.request(`${BASE5}/${id}`, { method: "PATCH", body: input })).data;
|
|
744
|
+
}
|
|
745
|
+
async delete(id) {
|
|
746
|
+
await this.request(`${BASE5}/${id}`, { method: "DELETE" });
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
|
|
750
|
+
// src/storage.ts
|
|
751
|
+
var STORAGE_KEY = "hyphabase.session";
|
|
752
|
+
function memoryStorage() {
|
|
753
|
+
let session = null;
|
|
754
|
+
return {
|
|
755
|
+
get: () => session,
|
|
756
|
+
set(next) {
|
|
757
|
+
session = next;
|
|
758
|
+
},
|
|
759
|
+
clear() {
|
|
760
|
+
session = null;
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
function defaultStorage() {
|
|
765
|
+
let memory = null;
|
|
766
|
+
const hasLocalStorage = (() => {
|
|
767
|
+
try {
|
|
768
|
+
return typeof localStorage !== "undefined";
|
|
769
|
+
} catch {
|
|
770
|
+
return false;
|
|
771
|
+
}
|
|
772
|
+
})();
|
|
773
|
+
return {
|
|
774
|
+
get() {
|
|
775
|
+
if (!hasLocalStorage) return memory;
|
|
776
|
+
const raw = localStorage.getItem(STORAGE_KEY);
|
|
777
|
+
if (!raw) return null;
|
|
778
|
+
try {
|
|
779
|
+
return JSON.parse(raw);
|
|
780
|
+
} catch {
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
},
|
|
784
|
+
set(session) {
|
|
785
|
+
memory = session;
|
|
786
|
+
if (hasLocalStorage) localStorage.setItem(STORAGE_KEY, JSON.stringify(session));
|
|
787
|
+
},
|
|
788
|
+
clear() {
|
|
789
|
+
memory = null;
|
|
790
|
+
if (hasLocalStorage) localStorage.removeItem(STORAGE_KEY);
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// src/version.ts
|
|
796
|
+
var API_VERSION = "2026-08-01";
|
|
797
|
+
|
|
798
|
+
// src/client.ts
|
|
799
|
+
var HyphaBaseClient = class {
|
|
800
|
+
constructor(baseUrl, apiKey, options = {}) {
|
|
801
|
+
this.baseUrl = baseUrl;
|
|
802
|
+
this.apiKey = apiKey;
|
|
803
|
+
this.options = options;
|
|
804
|
+
this.isSecretKey = apiKey.startsWith("sk_");
|
|
805
|
+
if (this.isSecretKey && typeof window !== "undefined" && typeof document !== "undefined") {
|
|
806
|
+
throw new Error(
|
|
807
|
+
"hyphabase: never use a secret (sk_) key in the browser - it grants full API access to anyone who opens devtools. Use your publishable (pk_) key here and keep the sk_ key on your server."
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
this.fetchImpl = options.fetch ?? fetch.bind(globalThis);
|
|
811
|
+
this.auth = new AuthModule({
|
|
812
|
+
baseUrl: baseUrl.replace(/\/$/, ""),
|
|
813
|
+
publishableKey: apiKey,
|
|
814
|
+
locationId: options.locationId,
|
|
815
|
+
storage: options.storage ?? (options.persistSession === false ? memoryStorage() : defaultStorage()),
|
|
816
|
+
fetchImpl: this.fetchImpl,
|
|
817
|
+
apiVersion: options.apiVersion ?? API_VERSION
|
|
818
|
+
});
|
|
819
|
+
const request = this.request.bind(this);
|
|
820
|
+
this.profile = new ProfileModule(request, () => this.auth.clearSession());
|
|
821
|
+
this.clients = new ClientsModule(request);
|
|
822
|
+
this.employees = new EmployeesModule(request);
|
|
823
|
+
this.organizations = new OrganizationsModule(request);
|
|
824
|
+
this.services = new ServicesModule(request);
|
|
825
|
+
this.schedules = new SchedulesModule(request);
|
|
826
|
+
this.locations = new LocationsModule(request);
|
|
827
|
+
this.data = new DataModule(request);
|
|
828
|
+
this.files = new FilesModule(request, this.fetchImpl);
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Point this client at a different location.
|
|
832
|
+
*
|
|
833
|
+
* A location is its own database, so this changes which data every
|
|
834
|
+
* subsequent call reads and writes. The existing session carries over
|
|
835
|
+
* unchanged - sign-in authenticates against the key's Environment, not a
|
|
836
|
+
* Location, so one session already covers every Location the identity is
|
|
837
|
+
* granted inside that environment (a request against one this session
|
|
838
|
+
* isn't granted for gets a 403, not a silent wrong-database read).
|
|
839
|
+
*/
|
|
840
|
+
setLocation(locationId) {
|
|
841
|
+
this.options.locationId = locationId;
|
|
842
|
+
this.auth.setLocation(locationId);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* Authenticated request to any HyphaBase endpoint. Attaches the
|
|
846
|
+
* user's access token (refreshing it when needed) plus location
|
|
847
|
+
* context; retries once through a refresh on an unexpected 401.
|
|
848
|
+
* Future modules (clients, employees, ...) build on this.
|
|
849
|
+
*/
|
|
850
|
+
async request(path, options = {}) {
|
|
851
|
+
const method = options.method ?? "GET";
|
|
852
|
+
const idempotencyKey = options.idempotencyKey === false || method === "GET" ? void 0 : options.idempotencyKey ?? randomKey();
|
|
853
|
+
const attempt = async () => {
|
|
854
|
+
const headers = {
|
|
855
|
+
Accept: "application/json",
|
|
856
|
+
"HyphaBase-Version": this.options.apiVersion ?? API_VERSION,
|
|
857
|
+
...idempotencyKey !== void 0 ? { "Idempotency-Key": idempotencyKey } : {},
|
|
858
|
+
...this.options.locationId !== void 0 ? { "X-Location-Id": this.options.locationId } : {}
|
|
859
|
+
};
|
|
860
|
+
if (options.auth === false) {
|
|
861
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
862
|
+
} else if (options.auth === "optional") {
|
|
863
|
+
const session = await this.auth.getValidSession();
|
|
864
|
+
headers.Authorization = `Bearer ${session ? session.accessToken : this.apiKey}`;
|
|
865
|
+
} else {
|
|
866
|
+
const session = await this.auth.getValidSession();
|
|
867
|
+
if (session) {
|
|
868
|
+
headers.Authorization = `Bearer ${session.accessToken}`;
|
|
869
|
+
} else if (this.isSecretKey) {
|
|
870
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
871
|
+
} else {
|
|
872
|
+
throw new HyphaBaseError(401, { message: "Not signed in." });
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData;
|
|
876
|
+
if (options.body !== void 0 && !isFormData) headers["Content-Type"] = "application/json";
|
|
877
|
+
return this.fetchImpl(`${this.baseUrl.replace(/\/$/, "")}${path}`, {
|
|
878
|
+
method,
|
|
879
|
+
headers,
|
|
880
|
+
body: options.body === void 0 ? void 0 : isFormData ? options.body : JSON.stringify(options.body)
|
|
881
|
+
});
|
|
882
|
+
};
|
|
883
|
+
let res = await attempt();
|
|
884
|
+
if (res.status === 401 && options.auth !== false) {
|
|
885
|
+
const refreshed = await this.auth.refreshSession();
|
|
886
|
+
if (refreshed) res = await attempt();
|
|
887
|
+
}
|
|
888
|
+
const text = await res.text();
|
|
889
|
+
if (options.raw) {
|
|
890
|
+
if (!res.ok) throw new HyphaBaseError(res.status, safeParse(text));
|
|
891
|
+
return text;
|
|
892
|
+
}
|
|
893
|
+
const json = safeParse(text);
|
|
894
|
+
if (!res.ok) throw new HyphaBaseError(res.status, json);
|
|
895
|
+
return json;
|
|
896
|
+
}
|
|
897
|
+
};
|
|
898
|
+
function randomKey() {
|
|
899
|
+
const c = globalThis.crypto;
|
|
900
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
901
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
|
|
902
|
+
}
|
|
903
|
+
function safeParse(text) {
|
|
904
|
+
try {
|
|
905
|
+
return text ? JSON.parse(text) : null;
|
|
906
|
+
} catch {
|
|
907
|
+
return null;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// src/webhooks.ts
|
|
912
|
+
var WEBHOOK_SIGNATURE_HEADER = "HyphaBase-Signature";
|
|
913
|
+
var DEFAULT_WEBHOOK_TOLERANCE = 300;
|
|
914
|
+
var WebhookSignatureError = class extends Error {
|
|
915
|
+
constructor(message, reason) {
|
|
916
|
+
super(message);
|
|
917
|
+
this.reason = reason;
|
|
918
|
+
this.name = "WebhookSignatureError";
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
async function verifyWebhookSignature(options) {
|
|
922
|
+
const { payload, header, secret } = options;
|
|
923
|
+
const tolerance = options.tolerance ?? DEFAULT_WEBHOOK_TOLERANCE;
|
|
924
|
+
if (!header) throw new WebhookSignatureError("Missing HyphaBase-Signature header.", "malformed");
|
|
925
|
+
let timestamp = null;
|
|
926
|
+
const candidates = [];
|
|
927
|
+
for (const part of header.split(",")) {
|
|
928
|
+
const eq = part.indexOf("=");
|
|
929
|
+
if (eq === -1) continue;
|
|
930
|
+
const key = part.slice(0, eq).trim();
|
|
931
|
+
const value = part.slice(eq + 1).trim();
|
|
932
|
+
if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
|
|
933
|
+
else if (key === "v1" && value) candidates.push(value.toLowerCase());
|
|
934
|
+
}
|
|
935
|
+
if (timestamp === null || candidates.length === 0) {
|
|
936
|
+
throw new WebhookSignatureError("Malformed HyphaBase-Signature header.", "malformed");
|
|
937
|
+
}
|
|
938
|
+
const now = options.now ?? Math.floor(Date.now() / 1e3);
|
|
939
|
+
if (Math.abs(now - timestamp) > tolerance) {
|
|
940
|
+
throw new WebhookSignatureError(
|
|
941
|
+
`Timestamp outside the tolerance of ${tolerance}s.`,
|
|
942
|
+
"timestamp"
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
const body = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
|
|
946
|
+
const prefix = new TextEncoder().encode(`${timestamp}.`);
|
|
947
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
948
|
+
signed.set(prefix, 0);
|
|
949
|
+
signed.set(body, prefix.length);
|
|
950
|
+
const expected = await hmacSha256Hex(secret, signed);
|
|
951
|
+
for (const candidate of candidates) {
|
|
952
|
+
if (constantTimeEqual(expected, candidate)) return;
|
|
953
|
+
}
|
|
954
|
+
throw new WebhookSignatureError("Signature does not match.", "mismatch");
|
|
955
|
+
}
|
|
956
|
+
async function constructWebhookEvent(options) {
|
|
957
|
+
await verifyWebhookSignature(options);
|
|
958
|
+
const text = typeof options.payload === "string" ? options.payload : new TextDecoder().decode(options.payload);
|
|
959
|
+
return JSON.parse(text);
|
|
960
|
+
}
|
|
961
|
+
async function hmacSha256Hex(secret, data) {
|
|
962
|
+
const subtle = globalThis.crypto?.subtle;
|
|
963
|
+
if (!subtle) throw new Error("hyphabase: WebCrypto (crypto.subtle) is not available in this runtime.");
|
|
964
|
+
const key = await subtle.importKey(
|
|
965
|
+
"raw",
|
|
966
|
+
new TextEncoder().encode(secret),
|
|
967
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
968
|
+
false,
|
|
969
|
+
["sign"]
|
|
970
|
+
);
|
|
971
|
+
const signature = await subtle.sign("HMAC", key, data);
|
|
972
|
+
return Array.from(new Uint8Array(signature), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
973
|
+
}
|
|
974
|
+
function constantTimeEqual(a, b) {
|
|
975
|
+
if (a.length !== b.length) return false;
|
|
976
|
+
let diff = 0;
|
|
977
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
978
|
+
return diff === 0;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// src/index.ts
|
|
982
|
+
function createClient(url, apiKey, options = {}) {
|
|
983
|
+
return new HyphaBaseClient(url, apiKey, options);
|
|
984
|
+
}
|
|
985
|
+
export {
|
|
986
|
+
API_VERSION,
|
|
987
|
+
AuthModule,
|
|
988
|
+
ClientsModule,
|
|
989
|
+
CollectionsModule,
|
|
990
|
+
DEFAULT_WEBHOOK_TOLERANCE,
|
|
991
|
+
DataModule,
|
|
992
|
+
EmployeesModule,
|
|
993
|
+
FilesModule,
|
|
994
|
+
HyphaBaseClient,
|
|
995
|
+
HyphaBaseError,
|
|
996
|
+
LocationsModule,
|
|
997
|
+
OrganizationsModule,
|
|
998
|
+
ProfileModule,
|
|
999
|
+
RecordsModule,
|
|
1000
|
+
SchedulesModule,
|
|
1001
|
+
ServicesModule,
|
|
1002
|
+
WEBHOOK_SIGNATURE_HEADER,
|
|
1003
|
+
WebhookSignatureError,
|
|
1004
|
+
constructWebhookEvent,
|
|
1005
|
+
createClient,
|
|
1006
|
+
memoryStorage,
|
|
1007
|
+
verifyWebhookSignature
|
|
1008
|
+
};
|