-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathsdk.ts
More file actions
1563 lines (1424 loc) · 45 KB
/
sdk.ts
File metadata and controls
1563 lines (1424 loc) · 45 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
import type { Channel } from './api/channels'
import type { BuildRequestOptions as InternalBuildRequestOptions } from './build/request'
import type { DecryptResult } from './bundle/decrypt'
import type { EncryptResult } from './bundle/encrypt'
import type { ZipResult } from './bundle/zip'
import type { StarAllRepositoryResult } from './github'
import type { ProbeInternalResult } from './probe'
import type { AppOptions } from './schemas/app'
import type { OptionsUpload } from './schemas/bundle'
import type { OptionsSetChannel } from './schemas/channel'
import type {
AccountIdOptions,
AddAppOptions,
AddChannelOptions,
AddOrganizationOptions,
AppInfo,
BundleCompatibilityOptions,
BundleInfo,
CleanupOptions,
CurrentBundleOptions,
DecryptBundleOptions,
DeleteOldKeyOptions,
DeleteOrganizationOptions,
DeviceStats,
DoctorOptions,
EncryptBundleOptions,
GenerateKeyOptions,
GetStatsOptions,
ListOrganizationsOptions,
LoginOptions,
OrganizationInfo,
ProbeOptions,
RequestBuildOptions,
SaveKeyOptions,
SDKResult,
SetSettingOptions,
StarAllRepositoriesOptions,
StarRepoOptions,
UpdateAppOptions,
UpdateChannelOptions,
UpdateOrganizationOptions,
UploadOptions,
UploadResult,
ZipBundleOptions,
} from './schemas/sdk'
import type { Organization } from './utils'
import { getActiveAppVersions } from './api/versions'
import { addAppInternal } from './app/add'
import { deleteAppInternal } from './app/delete'
import { getInfoInternal } from './app/info'
import { listAppInternal } from './app/list'
import { setAppInternal } from './app/set'
import { setSettingInternal } from './app/setting'
import { requestBuildInternal } from './build/request'
import { cleanupBundleInternal } from './bundle/cleanup'
import { checkCompatibilityInternal } from './bundle/compatibility'
import { decryptZipInternal } from './bundle/decrypt'
import { deleteBundleInternal } from './bundle/delete'
import { encryptZipInternal } from './bundle/encrypt'
import { uploadBundleInternal } from './bundle/upload'
import { zipBundleInternal } from './bundle/zip'
import { addChannelInternal } from './channel/add'
import { currentBundleInternal } from './channel/currentBundle'
import { deleteChannelInternal } from './channel/delete'
import { listChannelsInternal } from './channel/list'
import { setChannelInternal } from './channel/set'
import { starAllRepositories as starAllRepositoriesInternal, starRepository } from './github'
import { createKeyInternal, deleteOldPrivateKeyInternal, saveKeyInternal } from './key'
import { loginInternal } from './login'
import { addOrganizationInternal } from './organization/add'
import { deleteOrganizationInternal } from './organization/delete'
import { listOrganizationsInternal } from './organization/list'
import { setOrganizationInternal } from './organization/set'
import { getUserIdInternal } from './user/account'
import { createSupabaseClient, findSavedKey, getConfig, getLocalConfig } from './utils'
import { parseSecurityPolicyError } from './utils/security_policy_errors'
export type DoctorInfo = Awaited<ReturnType<typeof getInfoInternal>>
type CompatibilityReport = Awaited<ReturnType<typeof checkCompatibilityInternal>>['finalCompatibility']
export type BundleCompatibilityEntry = CompatibilityReport[number]
// ============================================================================
// Re-export all SDK types from schemas
// ============================================================================
export type { UpdateProbeResult } from './app/updateProbe'
/**
* Create an SDK error result from an error, with security policy awareness.
* This parses the error to check if it's a security policy error and provides
* human-readable messages for 2FA, password policy, and API key requirements.
*/
function createErrorResult<T = void>(error: unknown): SDKResult<T> {
const errorMessage = error instanceof Error ? error.message : String(error)
const parsed = parseSecurityPolicyError(error)
return {
success: false,
error: errorMessage,
isSecurityPolicyError: parsed.isSecurityPolicyError,
securityPolicyMessage: parsed.isSecurityPolicyError ? parsed.message : undefined,
}
}
// ============================================================================
// SDK Class - Main Entry Point
// ============================================================================
/**
* Capgo SDK for programmatic access to all CLI functionality.
* Use this class to integrate Capgo operations directly into your application.
*
* @example
* ```typescript
* // Initialize SDK
* const sdk = new CapgoSDK({ apikey: 'your-api-key' })
*
* // Upload a bundle
* const result = await sdk.uploadBundle({
* appId: 'com.example.app',
* path: './dist',
* bundle: '1.0.0',
* channel: 'production'
* })
*
* if (result.success) {
* console.log('Upload successful!')
* }
* ```
*/
export class CapgoSDK {
private readonly apikey?: string
private readonly supaHost?: string
private readonly supaAnon?: string
constructor(options?: {
apikey?: string
supaHost?: string
supaAnon?: string
}) {
this.apikey = options?.apikey
this.supaHost = options?.supaHost
this.supaAnon = options?.supaAnon
}
// ==========================================================================
// App Management Methods
// ==========================================================================
/**
* Save an API key locally or in the home directory
*/
async login(options: LoginOptions): Promise<SDKResult> {
try {
await loginInternal(options.apikey, {
local: options.local ?? false,
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
}, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Run Capgo Doctor diagnostics and return the report
*/
async doctor(options?: DoctorOptions): Promise<SDKResult<DoctorInfo>> {
try {
const info = await getInfoInternal({ packageJson: options?.packageJson }, true)
return {
success: true,
data: info,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Add a new app to Capgo Cloud
*
* @example
* ```typescript
* const result = await sdk.addApp({
* appId: 'com.example.app',
* name: 'My App',
* icon: './icon.png'
* })
* ```
*/
async addApp(options: AddAppOptions): Promise<SDKResult> {
try {
const internalOptions: AppOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
name: options.name,
icon: options.icon,
}
await addAppInternal(options.appId, internalOptions, undefined, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Update an existing app in Capgo Cloud
*
* Note: This method requires CLI function refactoring to work without exit().
* Currently it will throw an error.
*
* @example
* ```typescript
* const result = await sdk.updateApp({
* appId: 'com.example.app',
* name: 'Updated App Name',
* retention: 30
* })
* ```
*/
async updateApp(options: UpdateAppOptions): Promise<SDKResult> {
try {
const internalOptions: AppOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
name: options.name,
icon: options.icon,
retention: options.retention,
}
await setAppInternal(options.appId, internalOptions, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Delete an app from Capgo Cloud
*
* @param appId - The app ID to delete
* @param skipConfirmation - Skip owner confirmation check (use with caution)
*
* @example
* ```typescript
* const result = await sdk.deleteApp('com.example.app')
* ```
*/
async deleteApp(appId: string, skipConfirmation = false): Promise<SDKResult> {
try {
const internalOptions = {
apikey: this.apikey || findSavedKey(true),
supaHost: this.supaHost,
supaAnon: this.supaAnon,
}
await deleteAppInternal(appId, internalOptions, false, skipConfirmation)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* List all apps for the authenticated account
*
* @example
* ```typescript
* const result = await sdk.listApps()
* if (result.success) {
* result.data?.forEach(app => {
* console.log(`${app.name} (${app.appId})`)
* })
* }
* ```
*/
async listApps(): Promise<SDKResult<AppInfo[]>> {
try {
const internalOptions = {
apikey: this.apikey || findSavedKey(true),
supaHost: this.supaHost,
supaAnon: this.supaAnon,
}
const apps = await listAppInternal(internalOptions, false)
const appInfos: AppInfo[] = apps.map(app => ({
appId: app.app_id,
name: app.name || 'Unknown',
iconUrl: app.icon_url || undefined,
createdAt: new Date(app.created_at || ''),
}))
return {
success: true,
data: appInfos,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Retrieve the account ID associated with the configured API key
*/
async getAccountId(options?: AccountIdOptions): Promise<SDKResult<string>> {
try {
const resolvedOptions = {
apikey: options?.apikey || this.apikey || findSavedKey(true),
supaHost: options?.supaHost || this.supaHost,
supaAnon: options?.supaAnon || this.supaAnon,
}
const userId = await getUserIdInternal(resolvedOptions, true)
return {
success: true,
data: userId,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Star the Capgo repository on GitHub
*
* @example
* ```typescript
* const result = await sdk.starRepo({ repository: 'Cap-go/capacitor-updater' })
* if (result.success) {
* console.log(`${result.data?.repository} starred`)
* }
* ```
*/
async starRepo(options?: StarRepoOptions): Promise<SDKResult<{ repository: string, alreadyStarred: boolean }>> {
try {
const { repository, alreadyStarred } = starRepository(options?.repository)
return {
success: true,
data: { repository, alreadyStarred },
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Star the Capgo-related repositories on GitHub
*
* @example
* ```typescript
* const result = await sdk.starAllRepositories()
* if (result.success) {
* for (const entry of result.data ?? []) {
* console.log(entry.repository, entry.status)
* }
* }
* ```
*/
async starAllRepositories(options?: StarAllRepositoriesOptions): Promise<SDKResult<StarAllRepositoryResult[]>> {
try {
const data = await starAllRepositoriesInternal(options)
return {
success: true,
data,
}
}
catch (error) {
return createErrorResult(error)
}
}
// ==========================================================================
// Bundle Management Methods
// ==========================================================================
async checkBundleCompatibility(options: BundleCompatibilityOptions): Promise<SDKResult<BundleCompatibilityEntry[]>> {
try {
const requestOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
channel: options.channel,
text: options.textOutput ?? false,
packageJson: options.packageJson,
nodeModules: options.nodeModules,
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
}
const compatibility = await checkCompatibilityInternal(options.appId, requestOptions, true)
return {
success: true,
data: compatibility.finalCompatibility,
}
}
catch (error) {
return createErrorResult(error)
}
}
async encryptBundle(options: EncryptBundleOptions): Promise<SDKResult<EncryptResult>> {
try {
const result = await encryptZipInternal(options.zipPath, options.checksum, {
key: options.keyPath,
keyData: options.keyData,
json: options.json,
packageJson: options.packageJson,
}, true)
return {
success: true,
data: result,
}
}
catch (error) {
return createErrorResult(error)
}
}
async decryptBundle(options: DecryptBundleOptions): Promise<SDKResult<DecryptResult>> {
try {
const result = await decryptZipInternal(options.zipPath, options.ivSessionKey, {
key: options.keyPath,
keyData: options.keyData,
checksum: options.checksum,
packageJson: options.packageJson,
}, true)
return {
success: true,
data: result,
}
}
catch (error) {
return createErrorResult(error)
}
}
async zipBundle(options: ZipBundleOptions): Promise<SDKResult<ZipResult>> {
try {
const result = await zipBundleInternal(options.appId, {
apikey: this.apikey || findSavedKey(true),
path: options.path,
bundle: options.bundle,
name: options.name,
codeCheck: options.codeCheck,
json: options.json,
keyV2: options.keyV2,
packageJson: options.packageJson,
}, true)
return {
success: true,
data: result,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Upload a bundle to Capgo Cloud
*
* @example
* ```typescript
* const result = await sdk.uploadBundle({
* appId: 'com.example.app',
* path: './dist',
* bundle: '1.0.0',
* channel: 'production',
* comment: 'New features added'
* })
* ```
*/
async uploadBundle(options: UploadOptions): Promise<UploadResult> {
try {
// Convert SDK options to internal format
const internalOptions: OptionsUpload = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
path: options.path,
bundle: options.bundle,
channel: options.channel,
external: options.external,
key: options.encrypt !== false, // default true unless explicitly false
keyV2: options.encryptionKey,
timeout: options.timeout,
tus: options.useTus,
comment: options.comment,
minUpdateVersion: options.minUpdateVersion,
autoMinUpdateVersion: options.autoMinUpdateVersion,
selfAssign: options.selfAssign,
packageJson: options.packageJsonPaths,
ignoreMetadataCheck: options.ignoreCompatibilityCheck,
codeCheck: !options.disableCodeCheck, // disable if requested, otherwise check
zip: options.useZip, // use legacy zip upload if requested
}
// Call internal upload function but suppress CLI behaviors
const uploadResponse = await uploadBundleInternal(options.appId, internalOptions, true)
return {
success: uploadResponse.success,
bundleId: uploadResponse.bundle,
checksum: uploadResponse.checksum ?? null,
encryptionMethod: uploadResponse.encryptionMethod,
sessionKey: uploadResponse.sessionKey,
ivSessionKey: uploadResponse.ivSessionKey,
storageProvider: uploadResponse.storageProvider,
skipped: uploadResponse.skipped,
reason: uploadResponse.reason,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* List bundles for an app
*
* @example
* ```typescript
* const result = await sdk.listBundles('com.example.app')
* if (result.success) {
* result.data?.forEach(bundle => {
* console.log(`${bundle.version} - ${bundle.uploadedAt}`)
* })
* }
* ```
*/
async listBundles(appId: string): Promise<SDKResult<BundleInfo[]>> {
try {
const apikey = this.apikey || findSavedKey(true)
const supabase = await createSupabaseClient(apikey, this.supaHost, this.supaAnon)
const versions = await getActiveAppVersions(supabase, appId)
const bundles: BundleInfo[] = versions.map(bundle => ({
id: bundle.id.toString(),
version: bundle.name,
uploadedAt: new Date(bundle.created_at || ''),
size: 0, // Size not available in current schema
encrypted: bundle.session_key !== null,
}))
return {
success: true,
data: bundles,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Delete a specific bundle
*
* Note: This method requires CLI function refactoring to work without exit().
*
* @example
* ```typescript
* const result = await sdk.deleteBundle('com.example.app', '1.0.0')
* ```
*/
async deleteBundle(appId: string, bundleId: string): Promise<SDKResult> {
try {
const internalOptions = {
apikey: this.apikey || findSavedKey(true),
supaHost: this.supaHost,
supaAnon: this.supaAnon,
bundle: bundleId,
}
await deleteBundleInternal(bundleId, appId, internalOptions, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Cleanup old bundles, keeping only recent versions
*
* @example
* ```typescript
* const result = await sdk.cleanupBundles({
* appId: 'com.example.app',
* keep: 5,
* force: true
* })
* ```
*/
async cleanupBundles(options: CleanupOptions): Promise<SDKResult<{ removed: number, kept: number }>> {
try {
const internalOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
bundle: options.bundle || '',
version: '',
keep: options.keep || 4,
force: options.force || false,
ignoreChannel: options.ignoreChannel || false,
}
const result = await cleanupBundleInternal(options.appId, internalOptions, true)
return {
success: true,
data: result,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Request a native build for your app with store publishing
*
* SECURITY GUARANTEE:
* Credentials provided to this method are NEVER stored on Capgo servers.
* They are used only during the build process and automatically deleted
* after completion (maximum 24 hours retention). Build outputs may optionally
* be uploaded for time-limited download links.
*
* @example
* ```typescript
* const result = await sdk.requestBuild({
* appId: 'com.example.app',
* path: './my-project',
* lane: 'ios', // Must be exactly "ios" or "android"
* credentials: {
* BUILD_CERTIFICATE_BASE64: 'base64-cert...',
* CAPGO_IOS_PROVISIONING_MAP: '{"com.example.app":{"profile":"base64...","name":"match AppStore com.example.app"}}',
* P12_PASSWORD: 'cert-password',
* APPLE_KEY_ID: 'KEY123',
* APPLE_ISSUER_ID: 'issuer-uuid',
* APPLE_KEY_CONTENT: 'base64-p8...',
* APP_STORE_CONNECT_TEAM_ID: 'team-id'
* }
* })
*
* if (result.success) {
* console.log('Job ID:', result.data.jobId)
* }
* ```
*/
async requestBuild(options: RequestBuildOptions): Promise<SDKResult<{ jobId: string, uploadUrl: string, status: string }>> {
try {
// Convert BuildCredentials object to flattened CLI-compatible format
const creds = options.credentials
const internalOptions: InternalBuildRequestOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
path: options.path,
platform: options.platform,
userId: options.userId,
// Flatten BuildCredentials to individual fields
buildCertificateBase64: creds?.BUILD_CERTIFICATE_BASE64,
p12Password: creds?.P12_PASSWORD,
appleKeyId: creds?.APPLE_KEY_ID,
appleIssuerId: creds?.APPLE_ISSUER_ID,
appleKeyContent: creds?.APPLE_KEY_CONTENT,
appStoreConnectTeamId: creds?.APP_STORE_CONNECT_TEAM_ID,
iosScheme: creds?.CAPGO_IOS_SCHEME,
iosTarget: creds?.CAPGO_IOS_TARGET,
iosDistribution: creds?.CAPGO_IOS_DISTRIBUTION as 'app_store' | 'ad_hoc' | undefined,
iosProvisioningMap: creds?.CAPGO_IOS_PROVISIONING_MAP,
androidKeystoreFile: creds?.ANDROID_KEYSTORE_FILE,
keystoreKeyAlias: creds?.KEYSTORE_KEY_ALIAS,
keystoreKeyPassword: creds?.KEYSTORE_KEY_PASSWORD,
keystoreStorePassword: creds?.KEYSTORE_STORE_PASSWORD,
playConfigJson: creds?.PLAY_CONFIG_JSON,
}
const result = await requestBuildInternal(options.appId, internalOptions, true)
if (result.success && result.jobId) {
return {
success: true,
data: {
jobId: result.jobId,
uploadUrl: result.uploadUrl || '',
status: result.status || 'unknown',
},
}
}
return {
success: false,
error: result.error || 'Unknown error during build request',
}
}
catch (error) {
return createErrorResult(error)
}
}
// ==========================================================================
// Channel Management Methods
// ==========================================================================
async getCurrentBundle(appId: string, channelId: string, options?: CurrentBundleOptions): Promise<SDKResult<string>> {
try {
const requestOptions = {
apikey: options?.apikey || this.apikey || findSavedKey(true),
quiet: true,
supaHost: options?.supaHost || this.supaHost,
supaAnon: options?.supaAnon || this.supaAnon,
}
const bundle = await currentBundleInternal(channelId, appId, requestOptions as any, true)
return {
success: true,
data: bundle,
}
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Create a new channel for app distribution
*
* @example
* ```typescript
* const result = await sdk.addChannel({
* channelId: 'production',
* appId: 'com.example.app',
* default: true
* })
* ```
*/
async addChannel(options: AddChannelOptions): Promise<SDKResult> {
try {
const internalOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
default: options.default,
selfAssign: options.selfAssign,
}
await addChannelInternal(options.channelId, options.appId, internalOptions, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Update channel settings
*
* @example
* ```typescript
* const result = await sdk.updateChannel({
* channelId: 'production',
* appId: 'com.example.app',
* bundle: '1.0.0'
* })
* ```
*/
async updateChannel(options: UpdateChannelOptions): Promise<SDKResult> {
try {
const internalOptions: OptionsSetChannel = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
bundle: options.bundle ?? undefined,
state: options.state,
downgrade: options.downgrade,
ios: options.ios,
android: options.android,
selfAssign: options.selfAssign,
disableAutoUpdate: options.disableAutoUpdate ?? undefined,
dev: options.dev,
emulator: options.emulator,
device: options.device,
prod: options.prod,
latest: false,
latestRemote: false,
packageJson: undefined,
ignoreMetadataCheck: false,
}
await setChannelInternal(options.channelId, options.appId, internalOptions, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Delete a channel
*
* @example
* ```typescript
* const result = await sdk.deleteChannel('staging', 'com.example.app')
* ```
*/
async deleteChannel(channelId: string, appId: string, deleteBundle = false): Promise<SDKResult> {
try {
const internalOptions = {
apikey: this.apikey || findSavedKey(true),
supaHost: this.supaHost,
supaAnon: this.supaAnon,
deleteBundle,
successIfNotFound: false,
}
await deleteChannelInternal(channelId, appId, internalOptions, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* List all channels for an app
*
* @example
* ```typescript
* const result = await sdk.listChannels('com.example.app')
* if (result.success) {
* result.data?.forEach(channel => {
* console.log(`${channel.name} - ${channel.isDefault ? 'default' : 'normal'}`)
* })
* }
* ```
*/
async listChannels(appId: string): Promise<SDKResult<Channel[]>> {
try {
const internalOptions = {
apikey: this.apikey || findSavedKey(true),
supaHost: this.supaHost,
supaAnon: this.supaAnon,
}
const channels = await listChannelsInternal(appId, internalOptions, true)
return {
success: true,
data: channels,
}
}
catch (error) {
return createErrorResult(error)
}
}
// ==========================================================================
// Organization Management Methods
// ==========================================================================
/**
* Generate Capgo encryption keys (private/public pair)
*/
async generateEncryptionKeys(options?: GenerateKeyOptions): Promise<SDKResult> {
try {
await createKeyInternal({
force: options?.force,
setupChannel: options?.setupChannel,
}, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Save a public encryption key into the Capacitor config
*/
async saveEncryptionKey(options?: SaveKeyOptions): Promise<SDKResult> {
try {
await saveKeyInternal({
key: options?.keyPath,
keyData: options?.keyData,
setupChannel: options?.setupChannel,
}, true)
return { success: true }
}
catch (error) {
return createErrorResult(error)
}
}
/**
* Delete legacy (v1) encryption keys from the project
*/
async deleteLegacyEncryptionKey(options?: DeleteOldKeyOptions): Promise<SDKResult<{ deleted: boolean }>> {
try {
const deleted = await deleteOldPrivateKeyInternal({
force: options?.force,
setupChannel: options?.setupChannel,
}, true)
return {
success: true,
data: { deleted },
}
}
catch (error) {
return createErrorResult(error)
}
}
async listOrganizations(options?: ListOrganizationsOptions): Promise<SDKResult<OrganizationInfo[]>> {
try {
const requestOptions = {
apikey: options?.apikey || this.apikey || findSavedKey(true),
supaHost: options?.supaHost || this.supaHost,
supaAnon: options?.supaAnon || this.supaAnon,
}
const organizations = await listOrganizationsInternal(requestOptions, true)
const data: OrganizationInfo[] = organizations.map((org: Organization) => ({
id: String((org as any).id ?? (org as any).gid ?? ''),
name: (org as any).name ?? 'Unknown',
role: (org as any).role ?? undefined,
appCount: typeof (org as any).app_count === 'number' ? (org as any).app_count : undefined,
email: (org as any).management_email ?? undefined,
createdAt: (org as any).created_at ? new Date((org as any).created_at) : undefined,
}))
return {
success: true,
data,
}
}
catch (error) {
return createErrorResult(error)
}
}
async addOrganization(options: AddOrganizationOptions): Promise<SDKResult<OrganizationInfo>> {
try {
const requestOptions = {
apikey: options.apikey || this.apikey || findSavedKey(true),
supaHost: options.supaHost || this.supaHost,
supaAnon: options.supaAnon || this.supaAnon,
name: options.name,
email: options.email,
}
const org = await addOrganizationInternal(requestOptions, true)
const info: OrganizationInfo = {
id: String((org as any).id ?? (org as any).gid ?? ''),
name: (org as any).name ?? options.name,
role: 'owner',
appCount: 0,
email: (org as any).management_email ?? options.email,
createdAt: (org as any).created_at ? new Date((org as any).created_at) : undefined,
}
return {
success: true,
data: info,
}
}
catch (error) {