-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
3644 lines (3385 loc) · 138 KB
/
Copy pathindex.ts
File metadata and controls
3644 lines (3385 loc) · 138 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { QueryAST, SortNode, AggregationNode, isFilterAST } from '@objectstack/spec/data';
import {
BatchUpdateRequest,
BatchUpdateResponse,
UpdateManyRequest,
DeleteManyRequest,
BatchOptions,
MetadataCacheRequest,
MetadataCacheResponse,
StandardErrorCode,
ErrorCategory,
GetDiscoveryResponse,
GetMetaTypesResponse,
GetMetaItemsResponse,
LoginRequest,
SessionResponse,
GetPresignedUrlRequest,
PresignedUrlResponse,
CompleteUploadRequest,
FileUploadResponse,
InitiateChunkedUploadRequest,
InitiateChunkedUploadResponse,
UploadChunkResponse,
CompleteChunkedUploadRequest,
CompleteChunkedUploadResponse,
UploadProgress,
CheckPermissionRequest,
CheckPermissionResponse,
GetObjectPermissionsResponse,
GetEffectivePermissionsResponse,
RealtimeConnectRequest,
RealtimeConnectResponse,
RealtimeSubscribeRequest,
RealtimeSubscribeResponse,
SetPresenceRequest,
GetPresenceResponse,
GetWorkflowConfigResponse,
GetWorkflowStateResponse,
WorkflowTransitionRequest,
WorkflowTransitionResponse,
ListViewsResponse,
GetViewResponse,
CreateViewRequest,
CreateViewResponse,
UpdateViewRequest,
UpdateViewResponse,
DeleteViewResponse,
RegisterDeviceRequest,
RegisterDeviceResponse,
UnregisterDeviceResponse,
GetNotificationPreferencesResponse,
UpdateNotificationPreferencesRequest,
UpdateNotificationPreferencesResponse,
ListNotificationsResponse,
MarkNotificationsReadResponse,
MarkAllNotificationsReadResponse,
AiNlqRequest,
AiNlqResponse,
AiSuggestRequest,
AiSuggestResponse,
AiInsightsRequest,
AiInsightsResponse,
GetLocalesResponse,
GetTranslationsResponse,
GetFieldLabelsResponse,
RegisterRequest,
WellKnownCapabilities,
ApiRoutes,
ImportRequest,
ImportResponse,
CreateImportJobRequest,
CreateImportJobResponse,
ImportJobProgress,
ImportJobResults,
ImportJobSummary,
ListImportJobsRequest,
ListImportJobsResponse,
UndoImportJobResponse,
} from '@objectstack/spec/api';
import type {
ApprovalRequestRow,
ApprovalActionRow,
ApprovalStatus,
ApprovalDecisionResult,
} from '@objectstack/spec/contracts';
import { Logger, createLogger } from '@objectstack/core/logger';
import { RealtimeAPI } from './realtime-api';
/**
* Route types that the client can resolve.
* Covers all keys from `ApiRoutes` (the discovery schema) plus
* client-specific virtual routes (`views`, `permissions`).
*/
export type ApiRouteType = keyof ApiRoutes | 'views' | 'permissions';
export interface ClientConfig {
baseUrl: string;
token?: string;
/**
* Custom fetch implementation (e.g. node-fetch or for Next.js caching)
*/
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
/**
* Logger instance for debugging
*/
logger?: Logger;
/**
* Enable debug logging
*/
debug?: boolean;
/**
* Active project id (UUID of `sys_environment`). When present, the
* client injects an `X-Environment-Id` header on every request so the
* server's tenant router can resolve the physical data-plane database.
*
* @see docs/adr/0002-project-database-isolation.md
*/
environmentId?: string;
/**
* Active UI locale (BCP-47, e.g. `'zh-CN'`). When set, the client sends
* it as an `Accept-Language` header on every request so the server
* resolves metadata translations (object/field labels, view headers,
* action text) for the *in-app* language rather than the browser default.
*
* Apps should keep this in sync with their language switcher via
* {@link ObjectStackClient.setLocale} so switching language re-fetches
* localized metadata without a page refresh (issue #1319).
*/
locale?: string;
}
/**
* Discovery Result
* Re-export from @objectstack/spec/api for convenience
*/
export type DiscoveryResult = GetDiscoveryResponse;
/**
* @deprecated Use `data.query()` with standard QueryAST parameters instead.
* This interface uses legacy parameter names (filter/sort/top/skip) that
* require translation to QueryAST. Prefer QueryAST fields directly:
* - filter → where
* - select → fields
* - sort → orderBy
* - skip → offset
* - top → limit
*/
export interface QueryOptions {
select?: string[]; // Simplified Selection
/** @canonical Preferred filter parameter (singular). */
filter?: Record<string, any> | unknown[]; // Map or AST
/** @deprecated Use `filter` (singular). Kept for backward compatibility. */
filters?: Record<string, any> | unknown[]; // Map or AST
sort?: string | string[] | SortNode[]; // 'name' or ['-created_at'] or AST
top?: number;
skip?: number;
// Advanced features
aggregations?: AggregationNode[];
groupBy?: string[];
}
/**
* Canonical query options using Spec protocol field names.
* This is the recommended interface for `data.find()` queries.
*
* Canonical field mapping (QueryAST-aligned):
* - `where` — filter conditions (replaces legacy `filter`/`filters`)
* - `fields` — field selection (replaces legacy `select`)
* - `orderBy` — sort definition (replaces legacy `sort`)
* - `limit` — max records (replaces legacy `top`)
* - `offset` — skip records (replaces legacy `skip`)
* - `expand` — relation loading (replaces legacy `populate`)
*/
export interface QueryOptionsV2 {
/** Filter conditions (WHERE clause). Accepts MongoDB-style $op object or FilterCondition AST. */
where?: Record<string, any> | unknown[];
/** Fields to retrieve (SELECT clause). */
fields?: string[];
/** Sort definition (ORDER BY clause). */
orderBy?: string | string[] | SortNode[];
/** Maximum number of records to return (LIMIT). */
limit?: number;
/** Number of records to skip (OFFSET). */
offset?: number;
/** Relations to expand (JOIN / eager-load). */
expand?: Record<string, any> | string[];
/** Aggregation functions. */
aggregations?: AggregationNode[];
/** Group by fields. */
groupBy?: string[];
}
export interface PaginatedResult<T = any> {
/** Spec-compliant: array of matching records */
records: T[];
/** Total number of matching records (if requested) */
total?: number;
/** The object name */
object?: string;
/** Whether more records are available */
hasMore?: boolean;
}
/** Spec: GetDataResponseSchema */
export interface GetDataResult<T = any> {
object: string;
id: string;
record: T;
}
/** Spec: CreateDataResponseSchema */
export interface CreateDataResult<T = any> {
object: string;
id: string;
record: T;
}
/** Spec: UpdateDataResponseSchema */
export interface UpdateDataResult<T = any> {
object: string;
id: string;
record: T;
}
/** Spec: DeleteDataResponseSchema */
export interface DeleteDataResult {
object: string;
id: string;
deleted: boolean;
}
export interface StandardError {
code: StandardErrorCode;
message: string;
category: ErrorCategory;
httpStatus: number;
retryable: boolean;
details?: Record<string, any>;
}
export class ObjectStackClient {
private baseUrl: string;
private token?: string;
private environmentId?: string;
private locale?: string;
private fetchImpl: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
private discoveryInfo?: DiscoveryResult;
private logger: Logger;
private realtimeAPI: RealtimeAPI;
constructor(config: ClientConfig) {
this.baseUrl = config.baseUrl.replace(/\/$/, ''); // Remove trailing slash
this.token = config.token;
this.environmentId = config.environmentId;
this.locale = config.locale;
this.fetchImpl = config.fetch || globalThis.fetch.bind(globalThis);
// Initialize logger
this.logger = config.logger || createLogger({
level: config.debug ? 'debug' : 'info',
format: 'pretty'
});
// Initialize realtime API
this.realtimeAPI = new RealtimeAPI(this.baseUrl, this.token);
this.logger.debug('ObjectStack client created', { baseUrl: this.baseUrl });
}
/**
* Initialize the client by discovering server capabilities.
*/
async connect() {
this.logger.debug('Connecting to ObjectStack server', { baseUrl: this.baseUrl });
try {
let data: DiscoveryResult | undefined;
// 1. Try Protocol-standard Discovery Path /api/v1/discovery (primary)
try {
const discoveryUrl = `${this.baseUrl}/api/v1/discovery`;
this.logger.debug('Probing protocol-standard discovery endpoint', { url: discoveryUrl });
const res = await this.fetchImpl(discoveryUrl);
if (res.ok) {
const body = await res.json();
data = body.data || body;
this.logger.debug('Discovered via /api/v1/discovery');
}
} catch (e) {
this.logger.debug('Protocol-standard discovery probe failed', { error: (e as Error).message });
}
// 2. Fallback to Standard Discovery (.well-known)
if (!data) {
let wellKnownUrl: string;
try {
// If baseUrl is absolute, get origin
const url = new URL(this.baseUrl);
wellKnownUrl = `${url.origin}/.well-known/objectstack`;
} catch {
// If baseUrl is relative, use absolute path from root
wellKnownUrl = '/.well-known/objectstack';
}
this.logger.debug('Falling back to .well-known discovery', { url: wellKnownUrl });
const res = await this.fetchImpl(wellKnownUrl);
if (!res.ok) {
throw new Error(`Failed to connect to ${wellKnownUrl}: ${res.statusText}`);
}
const body = await res.json();
data = body.data || body;
}
if (!data) {
throw new Error('Connection failed: No discovery data returned');
}
this.discoveryInfo = data;
this.logger.info('Connected to ObjectStack server', {
version: data.version,
apiName: data.apiName,
services: data.services
});
return data as DiscoveryResult;
} catch (e) {
this.logger.error('Failed to connect to ObjectStack server', e as Error, { baseUrl: this.baseUrl });
throw e;
}
}
/**
* Well-known capability flags discovered from the server.
* Returns undefined if the client has not yet connected or the server
* did not include capabilities in its discovery response.
*
* The server may return capabilities in hierarchical format
* `{ key: { enabled: boolean } }` or flat boolean format `{ key: boolean }`.
* This getter normalizes both to flat `WellKnownCapabilities`.
*/
get capabilities(): WellKnownCapabilities | undefined {
const raw = this.discoveryInfo?.capabilities;
if (!raw) return undefined;
// Normalize: hierarchical { enabled: boolean } → flat boolean
const result: Record<string, boolean> = {};
for (const [key, value] of Object.entries(raw)) {
result[key] = typeof value === 'object' && value !== null ? !!(value as any).enabled : !!value;
}
return result as unknown as WellKnownCapabilities;
}
/**
* Metadata Operations
*/
meta = {
/**
* Get all available metadata types
* Returns types like 'object', 'plugin', 'view', etc.
*/
getTypes: async (): Promise<GetMetaTypesResponse> => {
const route = this.getRoute('metadata');
const res = await this.fetch(`${this.baseUrl}${route}`);
return this.unwrapResponse<GetMetaTypesResponse>(res);
},
/**
* Get all items of a specific metadata type
* @param type - Metadata type name (e.g., 'object', 'plugin')
* @param options - Optional filters (e.g., packageId to scope by package)
*/
getItems: async (type: string, options?: { packageId?: string }): Promise<GetMetaItemsResponse> => {
const route = this.getRoute('metadata');
const params = new URLSearchParams();
if (options?.packageId) params.set('package', options.packageId);
const qs = params.toString();
const url = `${this.baseUrl}${route}/${type}${qs ? `?${qs}` : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse<GetMetaItemsResponse>(res);
},
/**
* Get a specific metadata item by type and name
* @param type - Metadata type (e.g., 'object', 'plugin')
* @param name - Item name (snake_case identifier)
* @param options - Optional filters (e.g., packageId to scope by package)
*/
getItem: async (type: string, name: string, options?: { packageId?: string }) => {
const route = this.getRoute('metadata');
const params = new URLSearchParams();
if (options?.packageId) params.set('package', options.packageId);
const qs = params.toString();
const url = `${this.baseUrl}${route}/${type}/${name}${qs ? `?${qs}` : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse(res);
},
/**
* Save a metadata item
* @param type - Metadata type (e.g., 'object', 'plugin')
* @param name - Item name
* @param item - The metadata content to save
*/
saveItem: async (type: string, name: string, item: any) => {
const route = this.getRoute('metadata');
const res = await this.fetch(`${this.baseUrl}${route}/${type}/${name}`, {
method: 'PUT',
body: JSON.stringify(item)
});
return this.unwrapResponse(res);
},
/**
* Delete a metadata item
* @param type - Metadata type (e.g., 'object', 'plugin')
* @param name - Item name (snake_case identifier)
*/
deleteItem: async (type: string, name: string): Promise<{ type: string; name: string; deleted: boolean }> => {
const route = this.getRoute('metadata');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(type)}/${encodeURIComponent(name)}`, {
method: 'DELETE',
});
return this.unwrapResponse(res);
},
/**
* Get the durable change-log for a specific metadata item.
* Returns events recorded in `sys_metadata_history` for every
* overlay put/delete, ordered by `event_seq` ascending. Non-overlay
* metadata types return an empty list.
*/
getHistory: async (
type: string,
name: string,
options?: { sinceSeq?: number; limit?: number },
): Promise<{ events: Array<{
seq: number;
op: string;
ref: { org?: string; type: string; name: string };
hash: string | null;
parentHash: string | null;
actor: string;
message?: string;
ts: string;
source: string;
}> }> => {
const route = this.getRoute('metadata');
const params = new URLSearchParams();
if (options?.sinceSeq !== undefined) params.set('sinceSeq', String(options.sinceSeq));
if (options?.limit !== undefined) params.set('limit', String(options.limit));
const qs = params.toString();
const url = `${this.baseUrl}${route}/${encodeURIComponent(type)}/${encodeURIComponent(name)}/history${qs ? `?${qs}` : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse(res);
},
/**
* Get object metadata with cache support
* Supports ETag-based conditional requests for efficient caching
*/
getCached: async (name: string, cacheOptions?: MetadataCacheRequest): Promise<MetadataCacheResponse> => {
const route = this.getRoute('metadata');
const headers: Record<string, string> = {};
if (cacheOptions?.ifNoneMatch) {
headers['If-None-Match'] = cacheOptions.ifNoneMatch;
}
if (cacheOptions?.ifModifiedSince) {
headers['If-Modified-Since'] = cacheOptions.ifModifiedSince;
}
const res = await this.fetch(`${this.baseUrl}${route}/object/${name}`, {
headers
});
// Check for 304 Not Modified
if (res.status === 304) {
return {
notModified: true,
etag: cacheOptions?.ifNoneMatch ? {
value: cacheOptions.ifNoneMatch.replace(/^W\/|"/g, ''),
weak: cacheOptions.ifNoneMatch.startsWith('W/')
} : undefined
};
}
const data = await res.json();
const etag = res.headers.get('ETag');
const lastModified = res.headers.get('Last-Modified');
return {
data,
etag: etag ? {
value: etag.replace(/^W\/|"/g, ''),
weak: etag.startsWith('W/')
} : undefined,
lastModified: lastModified || undefined,
notModified: false
};
},
getView: async (object: string, type: 'list' | 'form' = 'list') => {
const route = this.getRoute('ui');
const res = await this.fetch(`${this.baseUrl}${route}/view/${object}?type=${type}`);
return this.unwrapResponse(res);
}
};
/**
* Analytics Services
*/
analytics = {
query: async (payload: any) => {
const route = this.getRoute('analytics');
const res = await this.fetch(`${this.baseUrl}${route}/query`, {
method: 'POST',
body: JSON.stringify(payload)
});
return res.json();
},
meta: async (cube: string) => {
const route = this.getRoute('analytics');
const res = await this.fetch(`${this.baseUrl}${route}/meta/${cube}`);
return res.json();
},
explain: async (payload: any) => {
const route = this.getRoute('analytics');
const res = await this.fetch(`${this.baseUrl}${route}/explain`, {
method: 'POST',
body: JSON.stringify(payload)
});
return res.json();
}
};
/**
* Package Management Services
*
* Manages the lifecycle of installed packages.
* A package (ManifestSchema) is the unit of installation.
* An app (AppSchema) is a UI navigation definition within a package.
* A package may contain 0, 1, or many apps, or be a pure functionality plugin.
*
* Endpoints:
* - GET /packages → list installed packages
* - GET /packages/:id → get package details
* - POST /packages → install a package
* - DELETE /packages/:id → uninstall a package
* - PATCH /packages/:id/enable → enable a package
* - PATCH /packages/:id/disable → disable a package
*/
packages = {
/**
* List all installed packages with optional filters.
*/
list: async (filters?: { status?: string; type?: string; enabled?: boolean }) => {
const route = this.getRoute('packages');
const params = new URLSearchParams();
if (filters?.status) params.set('status', filters.status);
if (filters?.type) params.set('type', filters.type);
if (filters?.enabled !== undefined) params.set('enabled', String(filters.enabled));
const qs = params.toString();
const url = `${this.baseUrl}${route}${qs ? '?' + qs : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse<{ packages: any[]; total: number }>(res);
},
/**
* Get a specific installed package by its ID (reverse domain identifier).
*/
get: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}`);
return this.unwrapResponse<{ package: any }>(res);
},
/**
* Install a new package from its manifest.
*
* By default the server rejects a manifest whose `id` is already
* installed with **409 Conflict** (duplicate-id guard) instead of
* silently overwriting the existing package. Intentional upgrade /
* re-install flows opt back in with `overwrite: true`.
*/
install: async (
manifest: any,
options?: { settings?: Record<string, any>; enableOnInstall?: boolean; overwrite?: boolean },
) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}`, {
method: 'POST',
body: JSON.stringify({
manifest,
settings: options?.settings,
enableOnInstall: options?.enableOnInstall,
...(options?.overwrite !== undefined ? { overwrite: options.overwrite } : {}),
}),
});
return this.unwrapResponse<{ package: any; message?: string }>(res);
},
/**
* Uninstall a package by its ID.
*/
uninstall: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}`, {
method: 'DELETE',
});
return this.unwrapResponse<{ id: string; success: boolean; message?: string }>(res);
},
/**
* Enable a disabled package.
*/
enable: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}/enable`, {
method: 'PATCH',
});
return this.unwrapResponse<{ package: any; message?: string }>(res);
},
/**
* Disable an installed package.
*/
disable: async (id: string) => {
const route = this.getRoute('packages');
const res = await this.fetch(`${this.baseUrl}${route}/${encodeURIComponent(id)}/disable`, {
method: 'PATCH',
});
return this.unwrapResponse<{ package: any; message?: string }>(res);
},
};
/**
* Environment Management Services
*
* Environments are the v4.1+ isolation primitive — each project owns a
* physically separate data-plane database. All Studio-level switching goes
* through this API.
*
* Endpoints:
* - GET /api/v1/cloud/environments → list environments
* - GET /api/v1/cloud/environments/:id → get one (with database info)
* - POST /api/v1/cloud/environments → provision a new project
* - PATCH /api/v1/cloud/environments/:id → update (displayName, plan, status, …)
* - POST /api/v1/cloud/environments/:id/activate → set as session's active project
* - POST /api/v1/cloud/environments/:id/credentials/rotate → rotate credential
*
* @see docs/adr/0002-project-database-isolation.md
*/
projects = {
/**
* List environments visible to the current session. Optionally filter
* by organization (control-plane query — not routed through a data-plane DB).
*/
list: async (filters?: { organization_id?: string; env_type?: string; status?: string }) => {
const params = new URLSearchParams();
if (filters?.organization_id) params.set('organizationId', filters.organization_id);
if (filters?.env_type) params.set('envType', filters.env_type);
if (filters?.status) params.set('status', filters.status);
const qs = params.toString();
const url = `${this.baseUrl}/api/v1/cloud/environments${qs ? '?' + qs : ''}`;
const res = await this.fetch(url);
return this.unwrapResponse<{ projects: any[]; total: number }>(res);
},
/**
* Get a single project (joined with its database and membership row).
*/
get: async (id: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}`);
return this.unwrapResponse<{
project: any;
database?: any;
credential?: any;
membership?: any;
organization?: any;
}>(res);
},
/**
* Provision a new project. Delegates to
* `ProjectProvisioningService.provisionProject` on the server.
*/
create: async (req: {
organization_id: string;
slug?: string;
display_name: string;
env_type?: string;
project_type?: string;
plan?: string;
region?: string;
driver?: string;
is_default?: boolean;
is_system?: boolean;
storage_limit_mb?: number;
clone_from_environment_id?: string;
template_id?: string;
metadata?: Record<string, unknown>;
}) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments`, {
method: 'POST',
body: JSON.stringify(req),
});
return this.unwrapResponse<{ project: any; database: any }>(res);
},
/**
* Update a project (display_name, plan, status, is_default, metadata).
*/
update: async (id: string, patch: Record<string, unknown>) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}`, {
method: 'PATCH',
body: JSON.stringify(patch),
});
return this.unwrapResponse<{ project: any }>(res);
},
/**
* Cascade-delete a project: cleans up credential/member/package_installation
* rows, releases the physical database via the provisioning adapter, and
* removes the `sys_environment` row. Default projects require `force: true`.
*/
delete: async (id: string, opts?: { force?: boolean }) => {
const qs = opts?.force ? '?force=1' : '';
const res = await this.fetch(
`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}${qs}`,
{ method: 'DELETE' },
);
return this.unwrapResponse<{ deleted: boolean; environmentId: string; warnings: string[] }>(res);
},
/**
* Activate this project for the current session. The server writes
* `active_environment_id` on the better-auth session; subsequent requests
* are routed to this project's database.
*/
activate: async (id: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/activate`, {
method: 'POST',
});
return this.unwrapResponse<{ project: any; sessionUpdated: boolean }>(res);
},
/**
* Rotate the active database credential for this project.
*/
rotateCredential: async (id: string, plaintext: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/credentials/rotate`, {
method: 'POST',
body: JSON.stringify({ plaintext }),
});
return this.unwrapResponse<{ credential: any }>(res);
},
/**
* Update the hostname bound to this project. Validates format and
* uniqueness server-side; invalidates the dispatcher's routing cache.
*/
updateHostname: async (id: string, hostname: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/hostname`, {
method: 'POST',
body: JSON.stringify({ hostname }),
});
return this.unwrapResponse<{ project: any }>(res);
},
/**
* Update the visibility of this project ('private' | 'public').
* `private` (default) hides the project from /pub/v1 enumeration but
* still allows anonymous artifact downloads when the URL includes an
* exact `?commit=<id>` (share-by-link). `public` lists the project and
* freely exposes all revisions.
*/
updateVisibility: async (id: string, visibility: 'private' | 'public') => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}`, {
method: 'PATCH',
body: JSON.stringify({ visibility }),
});
return this.unwrapResponse<{ project: any }>(res);
},
/**
* List published artifact revisions for a project. Each revision has
* an immutable commitId (content-addressable) and storage_key.
* Optional `branch` filter narrows to a single logical branch
* (default branch `main` also matches rows with NULL `branch`).
*/
listRevisions: async (id: string, opts?: { limit?: number; cursor?: string; branch?: string }) => {
const params = new URLSearchParams();
if (opts?.limit) params.set('limit', String(opts.limit));
if (opts?.cursor) params.set('cursor', opts.cursor);
if (opts?.branch) params.set('branch', opts.branch);
const qs = params.toString();
const res = await this.fetch(
`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/revisions${qs ? `?${qs}` : ''}`,
);
return this.unwrapResponse<{
items: Array<{
commitId: string;
checksum: string;
storageKey: string;
sizeBytes: number;
builtAt: string;
publishedAt: string;
publishedBy: string | null;
note: string | null;
isCurrent: boolean;
branch: string;
isBranchHead: boolean;
}>;
nextCursor: string | null;
branch: string | null;
}>(res);
},
/**
* List logical branches for a project. Each branch has a head commit
* (latest published revision on that branch) and a count of revisions.
* Branches without a head row (e.g. all rows demoted) are omitted.
*/
listBranches: async (id: string) => {
const res = await this.fetch(
`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/branches`,
);
return this.unwrapResponse<{
environmentId: string;
branches: Array<{
branch: string;
headCommitId: string;
headRevisionId: string;
revisionCount: number;
headPublishedAt: string | null;
headNote: string | null;
isCurrent: boolean;
}>;
}>(res);
},
/**
* Rename a branch. Updates every revision row in `from` to `to`.
* 409 if `to` already has rows.
*/
renameBranch: async (id: string, from: string, to: string) => {
const res = await this.fetch(
`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/branches/${encodeURIComponent(from)}/rename`,
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ newName: to }),
},
);
return this.unwrapResponse<{ environmentId: string; from: string; to: string; renamed: number }>(res);
},
/**
* Delete (demote) a branch. Soft-removal — clears `is_branch_head` on
* every row in this branch; the revisions themselves remain. The
* `main` branch and any branch carrying the active revision cannot be
* deleted.
*/
deleteBranch: async (id: string, name: string) => {
const res = await this.fetch(
`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/branches/${encodeURIComponent(name)}`,
{ method: 'DELETE' },
);
return this.unwrapResponse<{ environmentId: string; branch: string; demoted: number; totalRevisions: number }>(res);
},
/**
* Retry provisioning for a project stuck in `failed` (or
* `provisioning`) state. The server re-runs the driver handshake; on
* success the project flips to `active`, on failure it stays
* `failed` with `metadata.provisioningError` updated.
*/
retryProvisioning: async (id: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(id)}/retry`, {
method: 'POST',
});
return this.unwrapResponse<{ project: any }>(res);
},
/**
* List ObjectQL drivers registered on the server. Useful for populating a
* driver selector when provisioning a new project (memory / turso /
* future sql drivers). Returned `name` is the short alias (e.g. `memory`,
* `turso`); `driverId` is the full FQN (e.g. `com.objectstack.driver.memory`).
*/
listDrivers: async () => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/drivers`);
return this.unwrapResponse<{ drivers: Array<{ name: string; driverId: string }>; total: number }>(res);
},
/**
* List available project templates. Templates are seeded into the project
* database once at provisioning time when `template_id` is supplied.
*/
listTemplates: async () => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/templates`);
return this.unwrapResponse<{ templates: Array<{ id: string; label: string; description: string; category?: string }>; total: number }>(res);
},
/**
* Per-project package installation management (Power Apps "solution" model).
* Install records are stored in the environment's own database.
*/
packages: {
/** List all packages installed in a specific project. */
list: async (envId: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages`);
return this.unwrapResponse<{ packages: any[]; total: number }>(res);
},
/** Install a package into the project. */
install: async (envId: string, body: {
packageId: string;
version?: string;
settings?: Record<string, unknown>;
enableOnInstall?: boolean;
}) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages`, {
method: 'POST',
body: JSON.stringify(body),
});
return this.unwrapResponse<{ package: any }>(res);
},
/** Get a single installation record. */
get: async (envId: string, pkgId: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}`);
return this.unwrapResponse<{ package: any }>(res);
},
/** Enable a previously disabled package. */
enable: async (envId: string, pkgId: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}/enable`, {
method: 'PATCH',
});
return this.unwrapResponse<{ package: any }>(res);
},
/** Disable an installed package (metadata will not be loaded). */
disable: async (envId: string, pkgId: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}/disable`, {
method: 'PATCH',
});
return this.unwrapResponse<{ package: any }>(res);
},
/** Uninstall a package from the project. Forbidden for scope=platform packages. */
uninstall: async (envId: string, pkgId: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}`, {
method: 'DELETE',
});
return this.unwrapResponse<{ id: string; success: boolean }>(res);
},
/** Upgrade an installed package to a newer version. */
upgrade: async (envId: string, pkgId: string, targetVersion?: string) => {
const res = await this.fetch(`${this.baseUrl}/api/v1/cloud/environments/${encodeURIComponent(envId)}/packages/${encodeURIComponent(pkgId)}/upgrade`, {
method: 'POST',
body: JSON.stringify({ targetVersion }),
});
return this.unwrapResponse<{ package: any }>(res);
},
},
};
/**
* Project-scoped client factory.
*
* Returns a thin wrapper around the data / meta / packages namespaces that
* prefixes every request with `/api/v1/environments/:environmentId/...`. Use this
* when the server has `enableProjectScoping: true` in its REST API config.
*
* Backward compatibility: `client.data.*`, `client.meta.*`, and
* `client.packages.*` continue to work unchanged; they hit unscoped routes
* and rely on hostname / `X-Environment-Id` header / session resolution.
*
* @example
* ```ts
* const scoped = client.project('00000000-0000-0000-0000-000000000001');
* const tasks = await scoped.data.find('task', { top: 10 });
* const objects = await scoped.meta.getItems('object');
* ```
*/
project(environmentId: string): ScopedProjectClient {
if (!environmentId) {
throw new Error('[ObjectStack] project(id): environmentId is required');
}
return new ScopedProjectClient(this, environmentId);
}
// ── Internal accessors exposed to ScopedProjectClient ────────────────
// The scoped client lives in the same module so using module-level access
// works; TypeScript requires these to be accessible, so we expose them via