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.
@@ -0,0 +1,1242 @@
1
+ interface ClientOptions {
2
+ /**
3
+ * UUID of the Location this app operates against. Mutable via
4
+ * setLocation(). Optional: signing in and discovering reachable locations
5
+ * (client.locations.list()) need no Location at all - set this once you
6
+ * know which one to work in.
7
+ */
8
+ locationId?: string;
9
+ /**
10
+ * Persist the session in localStorage (default true). Set false for
11
+ * memory-only sessions: tokens never touch disk, users re-authenticate
12
+ * on every page load.
13
+ */
14
+ persistSession?: boolean;
15
+ /** Storage for the auth session. Overrides persistSession when given. */
16
+ storage?: SessionStorageAdapter;
17
+ /** Custom fetch implementation (tests, non-browser runtimes) */
18
+ fetch?: typeof fetch;
19
+ /**
20
+ * Dated API version sent as `HyphaBase-Version` on every request.
21
+ * Defaults to the version this SDK release targets; pin an older one to
22
+ * keep response shapes while you migrate.
23
+ */
24
+ apiVersion?: string;
25
+ }
26
+ interface Session {
27
+ accessToken: string;
28
+ refreshToken: string;
29
+ /** ISO-8601 expiry of the access token */
30
+ expiresAt: string;
31
+ user: EndUser;
32
+ /**
33
+ * Every Location this sign-in reaches - from sign-in/sign-up's response,
34
+ * not a separate call. Empty means the identity has no Location grant
35
+ * yet. Use this to pick a Location instead of client.locations.list(),
36
+ * which answers what the *key* can reach, not what this specific user is
37
+ * granted.
38
+ */
39
+ locationIds: string[];
40
+ }
41
+ interface EndUser {
42
+ id: string;
43
+ name: string;
44
+ email: string;
45
+ [key: string]: unknown;
46
+ }
47
+ interface SessionStorageAdapter {
48
+ get(): Session | null;
49
+ set(session: Session): void;
50
+ clear(): void;
51
+ }
52
+ /** The authenticated request pipeline modules are built on. */
53
+ type RequestFn = <T = unknown>(path: string, options?: RequestOptions) => Promise<T>;
54
+ interface RequestOptions {
55
+ method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
56
+ /** JSON-serialized, or sent as-is when a FormData (file uploads). */
57
+ body?: unknown;
58
+ /**
59
+ * Attach the user's access token (default true). false sends the
60
+ * publishable key. "optional" sends the session when there is one and
61
+ * falls back to the key — for endpoints that answer both a signed-out
62
+ * app and a signed-in user, and answer them differently.
63
+ */
64
+ auth?: boolean | "optional";
65
+ /** Return the raw response text instead of parsed JSON (CSV downloads). */
66
+ raw?: boolean;
67
+ /**
68
+ * `Idempotency-Key` for writes. Generated per call by default, so a
69
+ * retry (the SDK's own, or yours passing the same key) applies the
70
+ * write once. `false` sends none.
71
+ */
72
+ idempotencyKey?: string | false;
73
+ }
74
+ declare class HyphaBaseError extends Error {
75
+ readonly status: number;
76
+ readonly body: {
77
+ message?: string;
78
+ errors?: Record<string, string[]>;
79
+ required_permission?: string;
80
+ error?: {
81
+ type?: string;
82
+ };
83
+ } | null;
84
+ /**
85
+ * The permission/scope the API said was missing (403s only). The
86
+ * message already explains which credential to fix - this field is for
87
+ * programmatic handling (hide a panel, show an upgrade prompt, ...).
88
+ */
89
+ readonly requiredPermission: string | null;
90
+ /**
91
+ * The machine-readable `error.type` some refusals carry, e.g.
92
+ * `email_unverified`. Null when the response named none.
93
+ */
94
+ readonly errorType: string | null;
95
+ constructor(status: number, body: {
96
+ message?: string;
97
+ errors?: Record<string, string[]>;
98
+ required_permission?: string;
99
+ error?: {
100
+ type?: string;
101
+ };
102
+ } | null);
103
+ /**
104
+ * The application requires verified email and this person has not
105
+ * verified theirs. Show a "check your inbox" screen and offer
106
+ * auth.resendVerification().
107
+ */
108
+ get isEmailUnverified(): boolean;
109
+ get isPermissionError(): boolean;
110
+ }
111
+
112
+ interface AuthDeps {
113
+ baseUrl: string;
114
+ publishableKey: string;
115
+ /**
116
+ * Mutable: setLocation() moves the whole client between locations.
117
+ * Undefined until a location is chosen - sign-in/sign-up/refresh/sign-out
118
+ * all authenticate against the Environment the key names, not a Location.
119
+ */
120
+ locationId: string | undefined;
121
+ storage: SessionStorageAdapter;
122
+ fetchImpl: typeof fetch;
123
+ /** Dated API version pinned on every request (`HyphaBase-Version`). */
124
+ apiVersion: string;
125
+ }
126
+ declare class AuthModule {
127
+ private readonly deps;
128
+ private refreshing;
129
+ constructor(deps: AuthDeps);
130
+ /**
131
+ * Follow the client onto another location. Sign-in and refresh both go
132
+ * to one location's database, so this has to move with setLocation() or
133
+ * a post-switch sign-in would target the previous location.
134
+ */
135
+ setLocation(locationId: string): void;
136
+ /**
137
+ * Register a new end user (requires the application to have end-user
138
+ * sign-up enabled). Signs the user in on success.
139
+ */
140
+ signUp(params: {
141
+ name: string;
142
+ email: string;
143
+ password: string;
144
+ }): Promise<Session>;
145
+ /**
146
+ * Sign in with email + password. The publishable key names which
147
+ * application this is and becomes a ceiling on which locations the
148
+ * session can reach - the API re-checks it on every later request, so
149
+ * revoking the key's access kills sessions it already issued too.
150
+ */
151
+ signIn(params: {
152
+ email: string;
153
+ password: string;
154
+ }): Promise<Session>;
155
+ /** Revoke the current session server-side and clear it locally. */
156
+ signOut(): Promise<void>;
157
+ /**
158
+ * Email the user a single-use password-reset token (valid 60 minutes).
159
+ * Resolves whether or not the address has an account - the API never
160
+ * says which. Your app hosts the form that takes the token.
161
+ */
162
+ forgotPassword(params: {
163
+ email: string;
164
+ }): Promise<void>;
165
+ /**
166
+ * Set a new password with the emailed token. Every existing session for
167
+ * the user is revoked, including one stored here - sign in again.
168
+ */
169
+ resetPassword(params: {
170
+ email: string;
171
+ token: string;
172
+ password: string;
173
+ }): Promise<void>;
174
+ /** Redeem the emailed verification token (sent at sign-up and by resendVerification). */
175
+ verifyEmail(params: {
176
+ email: string;
177
+ token: string;
178
+ }): Promise<void>;
179
+ /**
180
+ * Email the signed-in user a fresh verification token. When the
181
+ * application requires verification, this and the rest of the auth
182
+ * surface still answer for an unverified user (error type
183
+ * `email_unverified` elsewhere).
184
+ */
185
+ resendVerification(): Promise<void>;
186
+ /** Forget the stored session locally, without calling the API (for when the server already ended it). */
187
+ clearSession(): void;
188
+ /** The stored session, if any (may be expired - see getValidSession). */
189
+ getSession(): Session | null;
190
+ getUser(): EndUser | null;
191
+ /**
192
+ * A session whose access token is safe to use right now, refreshing
193
+ * first when it is expired or about to expire. Null when signed out or
194
+ * the refresh token is no longer valid.
195
+ */
196
+ getValidSession(): Promise<Session | null>;
197
+ /**
198
+ * Swap the refresh token for a new pair. Concurrent callers share one
199
+ * in-flight refresh (rotation makes parallel refreshes self-defeating:
200
+ * the second would replay a consumed token and revoke the family).
201
+ */
202
+ refreshSession(): Promise<Session | null>;
203
+ private doRefresh;
204
+ private storeSession;
205
+ private post;
206
+ }
207
+
208
+ /** A client record — the business's customer (guest, patient, ...). */
209
+ interface Client {
210
+ id: string;
211
+ first_name: string;
212
+ last_name: string;
213
+ name: string;
214
+ email: string;
215
+ phone: string;
216
+ locations?: unknown[];
217
+ traits?: ClientTrait[];
218
+ created_at: string;
219
+ updated_at: string;
220
+ [key: string]: unknown;
221
+ }
222
+ interface ClientInput {
223
+ first_name: string;
224
+ last_name: string;
225
+ email: string;
226
+ phone: string;
227
+ /** Location UUIDs to grant; defaults to the key/user's context server-side */
228
+ location_ids?: string[];
229
+ }
230
+ interface ClientNote {
231
+ id: string;
232
+ category: string;
233
+ content: string;
234
+ visibility: "internal" | "public";
235
+ created_at: string;
236
+ updated_at: string;
237
+ [key: string]: unknown;
238
+ }
239
+ interface ClientNoteInput {
240
+ category: string;
241
+ content: string;
242
+ visibility: "internal" | "public";
243
+ }
244
+ interface ClientTrait {
245
+ id: string;
246
+ name: string;
247
+ icon: string;
248
+ color: string;
249
+ description?: string | null;
250
+ [key: string]: unknown;
251
+ }
252
+ interface ClientTraitInput {
253
+ name: string;
254
+ icon: string;
255
+ color: string;
256
+ description?: string | null;
257
+ }
258
+ interface ClientAddress {
259
+ id: string;
260
+ label?: string | null;
261
+ address_line_1: string;
262
+ address_line_2?: string | null;
263
+ city: string;
264
+ state: string;
265
+ postal_code: string;
266
+ country: string;
267
+ is_primary?: boolean;
268
+ [key: string]: unknown;
269
+ }
270
+ interface ClientAddressInput {
271
+ label?: string | null;
272
+ address_line_1: string;
273
+ address_line_2?: string | null;
274
+ city: string;
275
+ state: string;
276
+ postal_code: string;
277
+ /** ISO 3166-1 alpha-2 */
278
+ country: string;
279
+ is_primary?: boolean;
280
+ }
281
+ /** A status definition for this location (e.g. Active, VIP, Archived). */
282
+ interface ClientStatus {
283
+ id: string;
284
+ name: string;
285
+ description?: string | null;
286
+ sort_order?: number | null;
287
+ [key: string]: unknown;
288
+ }
289
+ interface ClientStatusInput {
290
+ name: string;
291
+ description?: string | null;
292
+ sort_order?: number | null;
293
+ }
294
+ interface ImportExportOperation {
295
+ id: string;
296
+ type: string;
297
+ status: string;
298
+ created_at: string;
299
+ [key: string]: unknown;
300
+ }
301
+ interface ListClientsParams {
302
+ search?: string;
303
+ page?: number;
304
+ perPage?: number;
305
+ }
306
+ interface Paginated<T> {
307
+ data: T[];
308
+ meta: {
309
+ current_page: number;
310
+ last_page: number;
311
+ per_page: number;
312
+ total: number;
313
+ };
314
+ }
315
+ /** list/get/create/update/delete over one nested collection. */
316
+ interface SubResource<TRecord, TInput> {
317
+ list(): Promise<{
318
+ data: TRecord[];
319
+ }>;
320
+ get(id: string): Promise<TRecord>;
321
+ create(input: TInput): Promise<TRecord>;
322
+ update(id: string, input: Partial<TInput>): Promise<TRecord>;
323
+ delete(id: string): Promise<void>;
324
+ }
325
+ /**
326
+ * Typed access to the full Clients module. Every method rides the same
327
+ * authenticated pipeline as client.request().
328
+ */
329
+ declare class ClientsModule {
330
+ private readonly request;
331
+ /** Status definitions for the location (Active, VIP, ...). */
332
+ readonly statuses: SubResource<ClientStatus, ClientStatusInput>;
333
+ constructor(request: RequestFn);
334
+ list(params?: ListClientsParams): Promise<Paginated<Client>>;
335
+ get(id: string): Promise<Client>;
336
+ create(input: ClientInput): Promise<Client>;
337
+ update(id: string, input: Partial<ClientInput>): Promise<Client>;
338
+ /** Soft delete (restorable). */
339
+ delete(id: string): Promise<void>;
340
+ restore(id: string): Promise<Client>;
341
+ /** Permanent delete - cannot be restored. */
342
+ forceDelete(id: string): Promise<void>;
343
+ /** Notes on one client. */
344
+ notes(clientId: string): SubResource<ClientNote, ClientNoteInput>;
345
+ /** Traits (tags) on one client. */
346
+ traits(clientId: string): SubResource<ClientTrait, ClientTraitInput>;
347
+ /** Addresses of one client. */
348
+ addresses(clientId: string): SubResource<ClientAddress, ClientAddressInput>;
349
+ /** Per-location status assignments on one client. */
350
+ locationStatuses(clientId: string): {
351
+ list: () => Promise<{
352
+ data: unknown[];
353
+ }>;
354
+ assign: (locationId: string, clientStatusId: string) => Promise<unknown>;
355
+ remove: (locationId: string) => Promise<void>;
356
+ };
357
+ /** Bulk import/export and its background operations. */
358
+ readonly importExport: {
359
+ /** CSV template as text. */
360
+ downloadTemplate: () => Promise<string>;
361
+ /** Start a CSV import. */
362
+ import: (file: Blob | File, locationIds?: string[]) => Promise<ImportExportOperation>;
363
+ /** Start an export (filters optional). */
364
+ export: (params?: {
365
+ search?: string;
366
+ date_from?: string;
367
+ date_to?: string;
368
+ client_status_id?: string;
369
+ location_id?: string;
370
+ }) => Promise<ImportExportOperation>;
371
+ operations: {
372
+ list: () => Promise<{
373
+ data: ImportExportOperation[];
374
+ }>;
375
+ get: (id: string) => Promise<ImportExportOperation>;
376
+ /** Finished export file as text (CSV). */
377
+ download: (id: string) => Promise<string>;
378
+ cancel: (id: string) => Promise<unknown>;
379
+ clear: () => Promise<void>;
380
+ };
381
+ };
382
+ }
383
+
384
+ /** An employee (stylist, clinician, ...) - a per-location user. */
385
+ interface Employee {
386
+ id: string;
387
+ name: string;
388
+ email: string;
389
+ phone?: string | null;
390
+ is_active?: boolean;
391
+ locations?: unknown[];
392
+ roles?: {
393
+ id: string;
394
+ name: string;
395
+ }[];
396
+ created_at?: string;
397
+ updated_at?: string;
398
+ [key: string]: unknown;
399
+ }
400
+ interface EmployeeInput {
401
+ name: string;
402
+ email: string;
403
+ phone?: string | null;
404
+ /** Required on create */
405
+ password?: string;
406
+ location_ids?: string[];
407
+ role_ids?: string[];
408
+ }
409
+ /**
410
+ * Typed access to the Employees module. Every method rides the same
411
+ * authenticated pipeline as client.request().
412
+ */
413
+ declare class EmployeesModule {
414
+ private readonly request;
415
+ constructor(request: RequestFn);
416
+ list(): Promise<{
417
+ data: Employee[];
418
+ }>;
419
+ get(id: string): Promise<Employee>;
420
+ create(input: EmployeeInput): Promise<Employee>;
421
+ /** Partial update - only the fields you send change (last write wins). */
422
+ update(id: string, input: Partial<EmployeeInput>): Promise<Employee>;
423
+ delete(id: string): Promise<void>;
424
+ deactivate(id: string): Promise<Employee>;
425
+ reactivate(id: string): Promise<Employee>;
426
+ }
427
+
428
+ /**
429
+ * Custom Data (M4): developer-defined collections in the environment's
430
+ * own data database. Schema administration (`collections`) needs a
431
+ * secret key with `data.collections.manage`; records (`collection()`)
432
+ * need `data.records.*`. Server-side only in this release - an end-user
433
+ * session is refused.
434
+ */
435
+ type FieldType = "string" | "text" | "integer" | "number" | "boolean" | "date" | "datetime" | "enum" | "uuid" | "json" | "reference" | "file";
436
+ interface FieldDefinition {
437
+ name: string;
438
+ type: FieldType;
439
+ required?: boolean;
440
+ default?: unknown;
441
+ unique?: boolean;
442
+ indexed?: boolean;
443
+ /** string: 1–1024, default 255 */
444
+ max_length?: number;
445
+ /** number: [digits, decimals], default [18, 4] */
446
+ precision?: [number, number];
447
+ /** enum: 1–64 distinct values */
448
+ values?: string[];
449
+ /** reference: the target collection's slug */
450
+ collection?: string;
451
+ /** reference: what happens to this field when the target is deleted */
452
+ on_delete?: "restrict" | "set_null";
453
+ /** integer / number bounds */
454
+ min?: number;
455
+ max?: number;
456
+ }
457
+ interface CollectionField extends FieldDefinition {
458
+ /** `none` | `building` | `ready` | `failed` - poll while `building`. */
459
+ index_status: "none" | "building" | "ready" | "failed";
460
+ }
461
+ interface Collection {
462
+ id: string;
463
+ slug: string;
464
+ name: string;
465
+ version: number;
466
+ status: "active" | "deleting" | "deleted";
467
+ record_count: number;
468
+ fields: CollectionField[];
469
+ created_at: string;
470
+ updated_at: string;
471
+ }
472
+ interface CollectionInput {
473
+ slug: string;
474
+ name?: string;
475
+ fields: FieldDefinition[];
476
+ }
477
+ /** One schema operation; applied in order, each logged on its own. */
478
+ type SchemaOperation = ({
479
+ op: "add_field";
480
+ } & FieldDefinition) | {
481
+ op: "rename_field";
482
+ name: string;
483
+ to: string;
484
+ } | {
485
+ op: "hide_field";
486
+ name: string;
487
+ } | {
488
+ op: "set_required";
489
+ name: string;
490
+ required: boolean;
491
+ } | {
492
+ op: "set_default";
493
+ name: string;
494
+ default: unknown;
495
+ } | {
496
+ op: "add_index";
497
+ name: string;
498
+ unique?: boolean;
499
+ } | {
500
+ op: "drop_index";
501
+ name: string;
502
+ } | {
503
+ op: "rename_collection";
504
+ name: string;
505
+ };
506
+ interface SchemaChange {
507
+ id: string;
508
+ kind: string;
509
+ payload: Record<string, unknown>;
510
+ status: "pending" | "applied" | "failed";
511
+ error: string | null;
512
+ applied_at: string | null;
513
+ created_at: string;
514
+ }
515
+ declare class CollectionsModule {
516
+ private readonly request;
517
+ constructor(request: RequestFn);
518
+ list(): Promise<{
519
+ data: Collection[];
520
+ }>;
521
+ get(slug: string): Promise<{
522
+ data: Collection;
523
+ }>;
524
+ /** Creates the collection and its table. Field types are fixed for life. */
525
+ create(input: CollectionInput): Promise<{
526
+ data: Collection;
527
+ }>;
528
+ /**
529
+ * Change the schema. A failure reports the operation that failed
530
+ * (`errors["operations.N.…"]`) and leaves the earlier ones applied.
531
+ */
532
+ update(slug: string, operations: SchemaOperation[]): Promise<{
533
+ data: Collection;
534
+ }>;
535
+ /** Soft-deletes: the table is kept 30 days and can be restored. Refused while referenced. */
536
+ delete(slug: string): Promise<void>;
537
+ restore(slug: string): Promise<{
538
+ data: Collection;
539
+ }>;
540
+ changes(slug: string): Promise<{
541
+ data: SchemaChange[];
542
+ }>;
543
+ /**
544
+ * Poll until every index of the collection is built (or one failed).
545
+ */
546
+ waitUntilReady(slug: string, { intervalMs, timeoutMs }?: {
547
+ intervalMs?: number;
548
+ timeoutMs?: number;
549
+ }): Promise<Collection>;
550
+ }
551
+ /** The fields the API sets on every record. */
552
+ interface RecordBase {
553
+ id: string;
554
+ created_at: string;
555
+ updated_at: string;
556
+ /** Present only when listing with `include_deleted`. */
557
+ deleted_at?: string;
558
+ }
559
+ type FilterValue = string | number | boolean | null;
560
+ /** `{ status: "active" }` or `{ budget: { gte: 100, lt: 500 } }`. */
561
+ type FilterOperators = {
562
+ eq?: FilterValue;
563
+ neq?: FilterValue;
564
+ gt?: FilterValue;
565
+ gte?: FilterValue;
566
+ lt?: FilterValue;
567
+ lte?: FilterValue;
568
+ in?: FilterValue[];
569
+ /** string / text fields only; case-insensitive */
570
+ contains?: string;
571
+ is_null?: boolean;
572
+ };
573
+ interface ListRecordsParams<T> {
574
+ filter?: Partial<Record<keyof T & string, FilterValue | FilterOperators>>;
575
+ /** Up to two keys; prefix `-` for descending: `"-created_at,name"`. */
576
+ sort?: string;
577
+ /** 1–100 */
578
+ limit?: number;
579
+ cursor?: string | null;
580
+ /** Project to these fields (`id` always included). */
581
+ select?: Array<keyof T & string>;
582
+ include_deleted?: boolean;
583
+ }
584
+ interface RecordPage<T> {
585
+ data: Array<T & RecordBase>;
586
+ meta: {
587
+ next_cursor: string | null;
588
+ };
589
+ }
590
+ /**
591
+ * Records of one collection. `T` is the developer's field shape; the API
592
+ * adds `id`, `created_at`, `updated_at`. Payloads are flat.
593
+ */
594
+ declare class RecordsModule<T extends Record<string, unknown> = Record<string, unknown>> {
595
+ private readonly request;
596
+ private readonly slug;
597
+ constructor(request: RequestFn, slug: string);
598
+ private path;
599
+ list(params?: ListRecordsParams<T>): Promise<RecordPage<T>>;
600
+ /** Every page of a query, one request at a time. */
601
+ iterate(params?: ListRecordsParams<T>): AsyncGenerator<T & RecordBase>;
602
+ get(id: string): Promise<{
603
+ data: T & RecordBase;
604
+ }>;
605
+ create(input: Partial<T>): Promise<{
606
+ data: T & RecordBase;
607
+ }>;
608
+ /** Up to 100 records in one request, all or none; errors are keyed `records.N.field`. */
609
+ createMany(inputs: Array<Partial<T>>): Promise<{
610
+ data: Array<T & RecordBase>;
611
+ }>;
612
+ /** Partial: only the fields sent change; `null` clears a field. */
613
+ update(id: string, input: Partial<T>): Promise<{
614
+ data: T & RecordBase;
615
+ }>;
616
+ /** Soft delete. 409 while `restrict` references point at it. */
617
+ delete(id: string): Promise<void>;
618
+ restore(id: string): Promise<{
619
+ data: T & RecordBase;
620
+ }>;
621
+ }
622
+ declare class DataModule {
623
+ private readonly request;
624
+ /** Schema administration. */
625
+ readonly collections: CollectionsModule;
626
+ constructor(request: RequestFn);
627
+ /** Records of one collection, typed with your field shape. */
628
+ collection<T extends Record<string, unknown> = Record<string, unknown>>(slug: string): RecordsModule<T>;
629
+ }
630
+
631
+ /**
632
+ * Files (M5): the environment's file catalog. Bytes go straight to
633
+ * storage through a short-lived upload URL and come back through an
634
+ * expiring download URL; the API only ever sees metadata. Secret key,
635
+ * server-side.
636
+ */
637
+ interface FileRecord {
638
+ id: string;
639
+ name: string;
640
+ content_type: string;
641
+ size: number;
642
+ status: "pending_upload" | "ready";
643
+ scan_status: "pending" | "clean" | "infected" | "failed";
644
+ scanned_at: string | null;
645
+ checksum_sha256: string | null;
646
+ metadata: Record<string, unknown>;
647
+ created_at: string;
648
+ updated_at: string;
649
+ deleted_at: string | null;
650
+ /** Present on GET /{id}: every record this file is attached to. */
651
+ attachments?: FileAttachment[];
652
+ /** Present when listing with `attached_to`: this record's link. */
653
+ attachment?: FileAttachment;
654
+ }
655
+ interface FileAttachment {
656
+ id: string;
657
+ file_id: string;
658
+ target_type: string;
659
+ target_id: string;
660
+ location_id: string | null;
661
+ label: string | null;
662
+ created_at: string | null;
663
+ }
664
+ interface UploadInstructions {
665
+ url: string;
666
+ method: "PUT";
667
+ headers: Record<string, string>;
668
+ expires_at: string;
669
+ }
670
+ interface UploadOptions {
671
+ name: string;
672
+ contentType: string;
673
+ /** Required when `data` is a stream or anything whose length can't be read. */
674
+ size?: number;
675
+ metadata?: Record<string, unknown>;
676
+ }
677
+ interface ListFilesParams {
678
+ /** `clients:<id>` - only files attached to that record. */
679
+ /** Files attached to one record, as `<type>:<id>`, e.g. `` `clients:${client.id}` ``. A bare id is rejected (422). */
680
+ attached_to?: `${string}:${string}`;
681
+ /** With attached_to: the location whose database holds the record. */
682
+ location_id?: string;
683
+ status?: FileRecord["status"];
684
+ scan_status?: FileRecord["scan_status"];
685
+ include_deleted?: boolean;
686
+ limit?: number;
687
+ cursor?: string;
688
+ }
689
+ interface FilePage {
690
+ data: FileRecord[];
691
+ meta: {
692
+ next_cursor: string | null;
693
+ };
694
+ }
695
+ interface DownloadUrl {
696
+ url: string;
697
+ expires_at: string;
698
+ }
699
+ type UploadData = Blob | ArrayBuffer | Uint8Array | string;
700
+ declare class FilesModule {
701
+ private readonly request;
702
+ private readonly fetchImpl;
703
+ constructor(request: RequestFn, fetchImpl: typeof fetch);
704
+ /**
705
+ * Announce, upload, complete - in one call. Returns the file as the API
706
+ * sees it right after completion (`scan_status` usually `pending`; see
707
+ * `waitUntilScanned`).
708
+ */
709
+ upload(data: UploadData, options: UploadOptions): Promise<FileRecord>;
710
+ /** Step one of a manual upload: where to PUT the bytes. */
711
+ announce(input: {
712
+ name: string;
713
+ content_type: string;
714
+ size: number;
715
+ metadata?: Record<string, unknown>;
716
+ }): Promise<{
717
+ data: FileRecord;
718
+ upload: UploadInstructions;
719
+ }>;
720
+ /** Step three of a manual upload: the bytes are in place. */
721
+ complete(id: string): Promise<FileRecord>;
722
+ get(id: string): Promise<FileRecord>;
723
+ list(params?: ListFilesParams): Promise<FilePage>;
724
+ /** An expiring download URL (default 10 minutes, up to an hour). */
725
+ url(id: string, options?: {
726
+ expiresIn?: number;
727
+ }): Promise<DownloadUrl>;
728
+ update(id: string, input: {
729
+ name?: string;
730
+ metadata?: Record<string, unknown> | null;
731
+ }): Promise<FileRecord>;
732
+ delete(id: string): Promise<void>;
733
+ /**
734
+ * Attach a file to a module record (a client, …) in the location whose
735
+ * database holds it. Attaching twice returns the existing link.
736
+ */
737
+ attach(id: string, input: {
738
+ targetType: string;
739
+ targetId: string;
740
+ locationId: string;
741
+ label?: string;
742
+ }): Promise<FileAttachment>;
743
+ detach(id: string, attachmentId: string): Promise<void>;
744
+ restore(id: string): Promise<FileRecord>;
745
+ /**
746
+ * Poll until the virus scan has a verdict. Resolves with the file
747
+ * (`scan_status` clean, infected or failed); rejects on timeout.
748
+ */
749
+ waitUntilScanned(id: string, options?: {
750
+ intervalMs?: number;
751
+ timeoutMs?: number;
752
+ }): Promise<FileRecord>;
753
+ }
754
+
755
+ /**
756
+ * A location this credential can reach. `id` is what goes in
757
+ * `X-Location-Id`, and it is also what `location_id` means in a request
758
+ * body — one id, one meaning.
759
+ */
760
+ interface ReachableLocation {
761
+ id: string;
762
+ name: string;
763
+ region?: string | null;
764
+ is_active?: boolean;
765
+ /** `ready` once its database exists; poll while `pending`. */
766
+ provisioning_status?: string;
767
+ /**
768
+ * Whether the signed-in user may work at this location, as opposed to
769
+ * the credential merely covering it. Null when nobody is signed in —
770
+ * which is not the same as false, and a picker should not treat it so.
771
+ */
772
+ granted?: boolean | null;
773
+ [key: string]: unknown;
774
+ }
775
+ /**
776
+ * Discovery, so an app can find out which locations it may operate against
777
+ * instead of having the uuid hardcoded. It sits above any single location,
778
+ * so it never requires one to be current.
779
+ *
780
+ * The session is sent when there is one, because a signed-in user gets a
781
+ * strictly better answer — the same list, plus `granted` per row. A
782
+ * signed-out app still gets the list from the key alone, which is what a
783
+ * login screen's picker needs.
784
+ */
785
+ declare class LocationsModule {
786
+ private readonly request;
787
+ constructor(request: RequestFn);
788
+ list(): Promise<{
789
+ data: ReachableLocation[];
790
+ }>;
791
+ }
792
+
793
+ /**
794
+ * The location this client is pointed at, and its operational detail.
795
+ *
796
+ * `id` is the same uuid you passed as `locationId` when constructing the
797
+ * client - a location is a database, and this is that database describing
798
+ * itself. There is no second id space.
799
+ */
800
+ interface Location {
801
+ id: string;
802
+ name: string;
803
+ address?: string | null;
804
+ address_2?: string | null;
805
+ city?: string | null;
806
+ state?: string | null;
807
+ postal_code?: string | null;
808
+ country?: string | null;
809
+ /** IANA name, e.g. "America/Chicago". */
810
+ timezone?: string | null;
811
+ invoice_preference?: "per_instance" | "per_plan" | null;
812
+ require_refund_approval?: boolean;
813
+ created_at?: string;
814
+ updated_at?: string;
815
+ [key: string]: unknown;
816
+ }
817
+ interface LocationInput {
818
+ name: string;
819
+ address?: string | null;
820
+ address_2?: string | null;
821
+ city?: string | null;
822
+ state?: string | null;
823
+ postal_code?: string | null;
824
+ country?: string | null;
825
+ timezone?: string | null;
826
+ invoice_preference?: "per_instance" | "per_plan" | null;
827
+ require_refund_approval?: boolean | null;
828
+ }
829
+ interface Role {
830
+ id: string;
831
+ name: string;
832
+ permissions: string[];
833
+ [key: string]: unknown;
834
+ }
835
+ /**
836
+ * Typed access to the Organizations module: the location's own details,
837
+ * roles, and the Industry Language terms that drive per-business
838
+ * terminology.
839
+ */
840
+ declare class OrganizationsModule {
841
+ private readonly request;
842
+ constructor(request: RequestFn);
843
+ /**
844
+ * There is no `create` or `delete` here. A location is a database, and
845
+ * it comes into existence by being provisioned from the dashboard - a
846
+ * second premises means a second location, with its own client.
847
+ */
848
+ readonly locations: {
849
+ list: () => Promise<{
850
+ data: Location[];
851
+ }>;
852
+ get: (id: string) => Promise<Location>;
853
+ update: (id: string, input: Partial<LocationInput>) => Promise<Location>;
854
+ };
855
+ /** All registered terms with ids, defaults, and any current override. */
856
+ languageTerms(): Promise<{
857
+ data: {
858
+ id: string;
859
+ key: string;
860
+ module: string;
861
+ default_label: string;
862
+ default_label_plural: string | null;
863
+ override?: {
864
+ id: string;
865
+ custom_label: string;
866
+ custom_label_plural: string | null;
867
+ } | null;
868
+ }[];
869
+ }>;
870
+ /** Per-location terminology overrides (client -> Guest, ...). */
871
+ readonly languageOverrides: {
872
+ create: (termId: string, customLabel: string, customLabelPlural?: string | null) => Promise<unknown>;
873
+ update: (overrideId: string, customLabel: string, customLabelPlural?: string | null) => Promise<unknown>;
874
+ delete: (overrideId: string) => Promise<void>;
875
+ };
876
+ readonly roles: {
877
+ list: () => Promise<{
878
+ data: Role[];
879
+ }>;
880
+ create: (input: {
881
+ name: string;
882
+ permissions?: string[];
883
+ }) => Promise<Role>;
884
+ get: (id: string) => Promise<Role>;
885
+ /** Partial update - only the fields you send change. */
886
+ update: (id: string, input: {
887
+ name?: string;
888
+ permissions?: string[];
889
+ }) => Promise<Role>;
890
+ };
891
+ /**
892
+ * Resolved Industry Language terms for the current location - a flat
893
+ * key -> label map ("client" -> "Guest", "client.plural" -> "Guests").
894
+ * Drive every UI label from this so each business sees its own words.
895
+ */
896
+ language(): Promise<Record<string, string>>;
897
+ }
898
+
899
+ /** The signed-in end user's own record, as the API returns it. */
900
+ interface Profile {
901
+ user: {
902
+ id: string;
903
+ name: string;
904
+ email: string;
905
+ phone?: string | null;
906
+ [key: string]: unknown;
907
+ };
908
+ permissions: string[];
909
+ [key: string]: unknown;
910
+ }
911
+ interface ProfileInput {
912
+ /** Required, as on the API (it is a full update of these fields). */
913
+ name: string;
914
+ /** Required too: send the current address to keep it. Must be unique among the application's users. */
915
+ email: string;
916
+ phone?: string | null;
917
+ /** A location id this person may reach. */
918
+ default_location_id?: string | null;
919
+ }
920
+ /**
921
+ * The signed-in end user: who they are, their details, their password and
922
+ * what they may do. Every call uses the stored session and the current
923
+ * location, like any other module.
924
+ */
925
+ declare class ProfileModule {
926
+ private readonly request;
927
+ private readonly onSessionRevoked;
928
+ constructor(request: RequestFn, onSessionRevoked: () => void);
929
+ /** The current user and the permissions they hold at the current location. */
930
+ get(): Promise<Profile>;
931
+ /** Update the user's own details. The API requires both `name` and `email`; send the current email to keep it. */
932
+ update(input: ProfileInput): Promise<Profile>;
933
+ /**
934
+ * Change the password. The API ends every session the person holds,
935
+ * including this one, so the local session is dropped: sign in again with
936
+ * the new password.
937
+ */
938
+ changePassword(params: {
939
+ current_password: string;
940
+ password: string;
941
+ }): Promise<void>;
942
+ /** What the credential may do at the current location. */
943
+ permissions(): Promise<{
944
+ permissions: string[];
945
+ roles_updated_at?: string | null;
946
+ [key: string]: unknown;
947
+ }>;
948
+ }
949
+
950
+ /** A schedule plan: one-time or recurring, generating instances. */
951
+ interface SchedulePlan {
952
+ id: string;
953
+ client_id: string;
954
+ location_id: string;
955
+ type: "recurring" | "one_time";
956
+ start_date: string;
957
+ end_date?: string | null;
958
+ start_time: string;
959
+ end_time: string;
960
+ is_active?: boolean;
961
+ [key: string]: unknown;
962
+ }
963
+ interface SchedulePlanInput {
964
+ client_id: string;
965
+ /** Business location id (GET organizations/locations) */
966
+ location_id: string;
967
+ type: "recurring" | "one_time";
968
+ recurrence_interval?: "daily" | "weekly" | "biweekly" | "monthly" | "custom";
969
+ start_date: string;
970
+ end_date?: string | null;
971
+ /** HH:MM */
972
+ start_time: string;
973
+ /** HH:MM */
974
+ end_time: string;
975
+ /** Pausing a plan cancels its upcoming instances. */
976
+ is_active?: boolean;
977
+ services?: {
978
+ service_id: string;
979
+ quantity?: number;
980
+ price?: number;
981
+ }[];
982
+ }
983
+ /** A concrete appointment generated from (or added to) a plan. */
984
+ interface ScheduleInstance {
985
+ id: string;
986
+ schedule_plan_id: string;
987
+ client_id: string;
988
+ location_id: string;
989
+ scheduled_date: string;
990
+ start_time: string;
991
+ end_time: string;
992
+ status?: string;
993
+ [key: string]: unknown;
994
+ }
995
+ /** Typed access to the Schedules module: plans, instances, availability. */
996
+ declare class SchedulesModule {
997
+ private readonly request;
998
+ constructor(request: RequestFn);
999
+ readonly plans: {
1000
+ list: () => Promise<{
1001
+ data: SchedulePlan[];
1002
+ }>;
1003
+ get: (id: string) => Promise<SchedulePlan>;
1004
+ /**
1005
+ * Create a plan. Its instances are generated server-side — one for a
1006
+ * `one_time` plan, or every occurrence up to three months out for a
1007
+ * recurring one. Do not also POST an instance for the same slot.
1008
+ */
1009
+ create: (input: SchedulePlanInput) => Promise<SchedulePlan>;
1010
+ update: (id: string, input: Partial<SchedulePlanInput>) => Promise<SchedulePlan>;
1011
+ delete: (id: string) => Promise<void>;
1012
+ restore: (id: string) => Promise<SchedulePlan>;
1013
+ };
1014
+ readonly instances: {
1015
+ list: () => Promise<{
1016
+ data: ScheduleInstance[];
1017
+ }>;
1018
+ get: (id: string) => Promise<ScheduleInstance>;
1019
+ create: (input: {
1020
+ schedule_plan_id: string;
1021
+ client_id: string;
1022
+ location_id: string;
1023
+ scheduled_date: string;
1024
+ start_time: string;
1025
+ end_time: string;
1026
+ notes?: string;
1027
+ service_ids?: string[];
1028
+ }) => Promise<ScheduleInstance>;
1029
+ reschedule: (id: string, input: {
1030
+ scheduled_date: string;
1031
+ start_time: string;
1032
+ end_time: string;
1033
+ reason?: string;
1034
+ }) => Promise<unknown>;
1035
+ cancel: (id: string, reason?: string) => Promise<unknown>;
1036
+ skip: (id: string, reason?: string) => Promise<unknown>;
1037
+ delete: (id: string) => Promise<void>;
1038
+ };
1039
+ checkAvailability(input: Record<string, unknown>): Promise<unknown>;
1040
+ }
1041
+
1042
+ /** A service the business offers (haircut, consultation, ...). */
1043
+ interface Service {
1044
+ id: string;
1045
+ name: string;
1046
+ description?: string | null;
1047
+ price: number | string;
1048
+ taxable?: boolean;
1049
+ service_group_id?: string | null;
1050
+ tax_category_id?: string | null;
1051
+ duration_minutes?: number | null;
1052
+ buffer_time_minutes?: number | null;
1053
+ capacity_cost?: number;
1054
+ created_at?: string;
1055
+ updated_at?: string;
1056
+ [key: string]: unknown;
1057
+ }
1058
+ interface ServiceInput {
1059
+ name: string;
1060
+ description?: string | null;
1061
+ price: number;
1062
+ taxable?: boolean;
1063
+ tax_category_id?: string | null;
1064
+ service_group_id?: string | null;
1065
+ /** Minutes the service takes (1-1440). Defaults to 60. */
1066
+ duration_minutes?: number;
1067
+ /** Minutes held free after it (0-1440) */
1068
+ buffer_time_minutes?: number | null;
1069
+ /** How much capacity it uses up when booked. Defaults to 1. */
1070
+ capacity_cost?: number;
1071
+ /** Business location ids (GET organizations/locations), not the platform id */
1072
+ location_ids?: string[];
1073
+ }
1074
+ interface ServiceGroup {
1075
+ id: string;
1076
+ name: string;
1077
+ description?: string | null;
1078
+ [key: string]: unknown;
1079
+ }
1080
+ interface ServiceGroupInput {
1081
+ name: string;
1082
+ description?: string | null;
1083
+ /**
1084
+ * Required, at least one. Business location ids (GET
1085
+ * organizations/locations), not the platform id used in X-Location-Id.
1086
+ * A service's own locations must be a subset of its group's.
1087
+ */
1088
+ location_ids: string[];
1089
+ }
1090
+ /** Typed access to the Services module. */
1091
+ declare class ServicesModule {
1092
+ private readonly request;
1093
+ constructor(request: RequestFn);
1094
+ list(): Promise<{
1095
+ data: Service[];
1096
+ }>;
1097
+ get(id: string): Promise<Service>;
1098
+ create(input: ServiceInput): Promise<Service>;
1099
+ /** Partial update - only the fields you send change (last write wins). */
1100
+ update(id: string, input: Partial<ServiceInput>): Promise<Service>;
1101
+ delete(id: string): Promise<void>;
1102
+ readonly groups: {
1103
+ list: () => Promise<{
1104
+ data: ServiceGroup[];
1105
+ }>;
1106
+ get: (id: string) => Promise<ServiceGroup>;
1107
+ create: (input: ServiceGroupInput) => Promise<ServiceGroup>;
1108
+ /** `location_ids` is required here too — a name-only PATCH is rejected. */
1109
+ update: (id: string, input: ServiceGroupInput) => Promise<ServiceGroup>;
1110
+ delete: (id: string) => Promise<void>;
1111
+ };
1112
+ }
1113
+
1114
+ declare class HyphaBaseClient {
1115
+ private readonly baseUrl;
1116
+ private readonly apiKey;
1117
+ private readonly options;
1118
+ /** End-user authentication: sign up, sign in, sessions, refresh. */
1119
+ readonly auth: AuthModule;
1120
+ /** The signed-in end user: profile, password, permissions. */
1121
+ readonly profile: ProfileModule;
1122
+ /** The Clients module: the business's customers. */
1123
+ readonly clients: ClientsModule;
1124
+ /** The Employees module: per-location staff. */
1125
+ readonly employees: EmployeesModule;
1126
+ /** The Organizations module: locations, roles, language terms. */
1127
+ readonly organizations: OrganizationsModule;
1128
+ /** The Services module: the business's service catalog. */
1129
+ readonly services: ServicesModule;
1130
+ /** The Schedules module: plans, appointments, availability. */
1131
+ readonly schedules: SchedulesModule;
1132
+ /** Which locations this credential can reach. See setLocation(). */
1133
+ readonly locations: LocationsModule;
1134
+ /** Custom Data: your own collections and records (secret key, server-side). */
1135
+ readonly data: DataModule;
1136
+ /** Files: upload, download URLs, delete (secret key, server-side). */
1137
+ readonly files: FilesModule;
1138
+ private readonly fetchImpl;
1139
+ private readonly isSecretKey;
1140
+ constructor(baseUrl: string, apiKey: string, options?: ClientOptions);
1141
+ /**
1142
+ * Point this client at a different location.
1143
+ *
1144
+ * A location is its own database, so this changes which data every
1145
+ * subsequent call reads and writes. The existing session carries over
1146
+ * unchanged - sign-in authenticates against the key's Environment, not a
1147
+ * Location, so one session already covers every Location the identity is
1148
+ * granted inside that environment (a request against one this session
1149
+ * isn't granted for gets a 403, not a silent wrong-database read).
1150
+ */
1151
+ setLocation(locationId: string): void;
1152
+ /**
1153
+ * Authenticated request to any HyphaBase endpoint. Attaches the
1154
+ * user's access token (refreshing it when needed) plus location
1155
+ * context; retries once through a refresh on an unexpected 401.
1156
+ * Future modules (clients, employees, ...) build on this.
1157
+ */
1158
+ request<T = unknown>(path: string, options?: RequestOptions): Promise<T>;
1159
+ }
1160
+
1161
+ /**
1162
+ * The dated API version this SDK release is built against. Sent as the
1163
+ * `HyphaBase-Version` header on every request so a client keeps the
1164
+ * response shapes it was written for when the API moves on (Stripe-style
1165
+ * versioning); override with `apiVersion` in the client options.
1166
+ */
1167
+ declare const API_VERSION = "2026-08-01";
1168
+
1169
+ /**
1170
+ * Webhook signature verification - the receiving side of HyphaBase
1171
+ * webhooks. The API signs every delivery Stripe-style:
1172
+ *
1173
+ * HyphaBase-Signature: t=<unix seconds>,v1=<hex hmac-sha256 of "{t}.{rawBody}">
1174
+ *
1175
+ * keyed by the endpoint's full `whsec_` secret. Verify over the RAW body
1176
+ * (before JSON-parsing), compare in constant time, and reject stale
1177
+ * timestamps. Works anywhere WebCrypto exists (Node 18+, Deno, Bun,
1178
+ * Cloudflare Workers, browsers).
1179
+ */
1180
+ declare const WEBHOOK_SIGNATURE_HEADER = "HyphaBase-Signature";
1181
+ /** Seconds a delivery's timestamp may differ from now before it is refused. */
1182
+ declare const DEFAULT_WEBHOOK_TOLERANCE = 300;
1183
+ interface WebhookEvent<T = Record<string, unknown>> {
1184
+ id: string;
1185
+ type: string;
1186
+ created: string;
1187
+ api_version: string;
1188
+ data: {
1189
+ object: T;
1190
+ };
1191
+ [extra: string]: unknown;
1192
+ }
1193
+ declare class WebhookSignatureError extends Error {
1194
+ readonly reason: "malformed" | "timestamp" | "mismatch";
1195
+ constructor(message: string, reason: "malformed" | "timestamp" | "mismatch");
1196
+ }
1197
+ interface VerifyWebhookOptions {
1198
+ /** The raw request body, exactly as received. */
1199
+ payload: string | Uint8Array;
1200
+ /** The HyphaBase-Signature header value. */
1201
+ header: string | null | undefined;
1202
+ /** The endpoint's whsec_ secret. */
1203
+ secret: string;
1204
+ /** Allowed clock skew in seconds (default 300). */
1205
+ tolerance?: number;
1206
+ /** Override "now" (unix seconds) - tests. */
1207
+ now?: number;
1208
+ }
1209
+ /**
1210
+ * Throws a WebhookSignatureError when the signature is malformed, stale
1211
+ * or does not match; resolves otherwise.
1212
+ */
1213
+ declare function verifyWebhookSignature(options: VerifyWebhookOptions): Promise<void>;
1214
+ /**
1215
+ * Verify, then parse: the typed event, or a WebhookSignatureError.
1216
+ */
1217
+ declare function constructWebhookEvent<T = Record<string, unknown>>(options: VerifyWebhookOptions): Promise<WebhookEvent<T>>;
1218
+
1219
+ /**
1220
+ * Memory-only session store: tokens never touch disk, at the cost of
1221
+ * re-authenticating on every page load (persistSession: false).
1222
+ */
1223
+ declare function memoryStorage(): SessionStorageAdapter;
1224
+
1225
+ /**
1226
+ * Create an HyphaBase client.
1227
+ *
1228
+ * ```ts
1229
+ * import { createClient } from "hyphabase";
1230
+ *
1231
+ * const hyphabase = createClient(
1232
+ * "https://api.hyphabase.com",
1233
+ * "pk_live_...", // publishable key - safe for the browser
1234
+ * { locationId: "..." },
1235
+ * );
1236
+ *
1237
+ * await hyphabase.auth.signIn({ email, password });
1238
+ * ```
1239
+ */
1240
+ declare function createClient(url: string, apiKey: string, options?: ClientOptions): HyphaBaseClient;
1241
+
1242
+ export { API_VERSION, AuthModule, type Client, type ClientAddress, type ClientAddressInput, type ClientInput, type ClientNote, type ClientNoteInput, type ClientOptions, type ClientStatus, type ClientStatusInput, type ClientTrait, type ClientTraitInput, ClientsModule, type Collection, type CollectionField, type CollectionInput, CollectionsModule, DEFAULT_WEBHOOK_TOLERANCE, DataModule, type DownloadUrl, type Employee, type EmployeeInput, EmployeesModule, type EndUser, type FieldDefinition, type FieldType, type FileAttachment, type FilePage, type FileRecord, FilesModule, type FilterOperators, type FilterValue, HyphaBaseClient, HyphaBaseError, type ImportExportOperation, type ListClientsParams, type ListFilesParams, type ListRecordsParams, type Location, type LocationInput, LocationsModule, OrganizationsModule, type Paginated, type Profile, type ProfileInput, ProfileModule, type ReachableLocation, type RecordBase, type RecordPage, RecordsModule, type RequestFn, type RequestOptions, type Role, type ScheduleInstance, type SchedulePlan, type SchedulePlanInput, SchedulesModule, type SchemaChange, type SchemaOperation, type Service, type ServiceGroup, type ServiceGroupInput, type ServiceInput, ServicesModule, type Session, type SessionStorageAdapter, type SubResource, type UploadInstructions, type UploadOptions, type VerifyWebhookOptions, WEBHOOK_SIGNATURE_HEADER, type WebhookEvent, WebhookSignatureError, constructWebhookEvent, createClient, memoryStorage, verifyWebhookSignature };