-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathcodegen.js
More file actions
728 lines (637 loc) · 23.4 KB
/
codegen.js
File metadata and controls
728 lines (637 loc) · 23.4 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
const fs = require("fs");
const path = require("path");
const SOURCE_DIRECTORY = path.resolve(__dirname, "../src");
const PUBLIC_API_SWAGGER_PATH = path.resolve(
`${SOURCE_DIRECTORY}/__inputs__`,
"public_api.swagger.json",
);
const AUTH_PROXY_SWAGGER_PATH = path.resolve(
`${SOURCE_DIRECTORY}/__inputs__`,
"auth_proxy.swagger.json",
);
const TARGET_SDK_CLIENT_PATH = path.resolve(
`${SOURCE_DIRECTORY}/__generated__`,
"sdk-client-base.ts",
);
const COMMENT_HEADER = "/* @generated by codegen. DO NOT EDIT BY HAND */";
const VERSIONED_ACTIVITY_TYPES = {
ACTIVITY_TYPE_CREATE_AUTHENTICATORS: [
"ACTIVITY_TYPE_CREATE_AUTHENTICATORS_V2",
"v1CreateAuthenticatorsIntentV2",
"v1CreateAuthenticatorsResult",
],
ACTIVITY_TYPE_CREATE_API_KEYS: [
"ACTIVITY_TYPE_CREATE_API_KEYS_V2",
"v1CreateApiKeysIntentV2",
"v1CreateApiKeysResult",
],
ACTIVITY_TYPE_CREATE_POLICY: [
"ACTIVITY_TYPE_CREATE_POLICY_V3",
"v1CreatePolicyIntentV3",
"v1CreatePolicyResult",
],
ACTIVITY_TYPE_CREATE_PRIVATE_KEYS: [
"ACTIVITY_TYPE_CREATE_PRIVATE_KEYS_V2",
"v1CreatePrivateKeysIntentV2",
"v1CreatePrivateKeysResultV2",
],
ACTIVITY_TYPE_CREATE_SUB_ORGANIZATION: [
"ACTIVITY_TYPE_CREATE_SUB_ORGANIZATION_V7",
"v1CreateSubOrganizationIntentV7",
"v1CreateSubOrganizationResultV7",
],
ACTIVITY_TYPE_CREATE_USERS: [
"ACTIVITY_TYPE_CREATE_USERS_V3",
"v1CreateUsersIntentV3",
"v1CreateUsersResult",
],
ACTIVITY_TYPE_SIGN_RAW_PAYLOAD: [
"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
"v1SignRawPayloadIntentV2",
"v1SignRawPayloadResult",
],
ACTIVITY_TYPE_SIGN_TRANSACTION: [
"ACTIVITY_TYPE_SIGN_TRANSACTION_V2",
"v1SignTransactionIntentV2",
"v1SignTransactionResult",
],
ACTIVITY_TYPE_EMAIL_AUTH: [
"ACTIVITY_TYPE_EMAIL_AUTH_V3",
"v1EmailAuthIntentV3",
"v1EmailAuthResult",
],
ACTIVITY_TYPE_CREATE_READ_WRITE_SESSION: [
"ACTIVITY_TYPE_CREATE_READ_WRITE_SESSION_V2",
"v1CreateReadWriteSessionIntentV2",
"v1CreateReadWriteSessionResult",
],
ACTIVITY_TYPE_UPDATE_POLICY: [
"ACTIVITY_TYPE_UPDATE_POLICY_V2",
"v1UpdatePolicyIntentV2",
"v1UpdatePolicyResultV2",
],
ACTIVITY_TYPE_INIT_OTP_AUTH: [
"ACTIVITY_TYPE_INIT_OTP_AUTH_V3",
"v1InitOtpAuthIntentV3",
"v1InitOtpAuthResultV2",
],
ACTIVITY_TYPE_INIT_USER_EMAIL_RECOVERY: [
"ACTIVITY_TYPE_INIT_USER_EMAIL_RECOVERY_V2",
"v1InitUserEmailRecoveryIntentV2",
"v1InitUserEmailRecoveryResult",
],
ACTIVITY_TYPE_INIT_OTP: [
"ACTIVITY_TYPE_INIT_OTP_V2",
"v1InitOtpIntentV2",
"v1InitOtpResult",
],
};
const METHODS_WITH_ONLY_OPTIONAL_PARAMETERS = [
"getActivities",
"getApiKeys",
"getOrganization",
"getPolicies",
"getPrivateKeys",
"getSubOrgIds",
"getUsers",
"getWallets",
"getWhoami",
"listPrivateKeys",
"listUserTags",
];
const CAPTCHA_PROTECTED_METHODS = [
"proxyInitOtp",
"proxySignup",
"proxyInitOtpV2",
"proxySignupV2",
];
/**
* @param {string} methodName
* @returns {string}
*/
function methodTypeFromMethodName(methodName) {
if (["approveActivity", "rejectActivity"].includes(methodName)) {
return "activityDecision";
}
if (methodName.startsWith("nOOP")) {
return "noop";
}
// TODO: filter out unnecessary client methods, whether here or from the source
if (
methodName.startsWith("get") ||
methodName.startsWith("list") ||
methodName.startsWith("test")
) {
return "query";
}
return "activity";
}
// Helper that takes in swagger definitions and returns a map containing the latest version of a field.
// The intent is to consolidate a field with multiple versions (e.g. v1CreateSubOrganizationResult, v1CreateSubOrganizationResultV2...)
// in order to get just the latest (v1CreateSubOrganizationResultV4).
function extractLatestVersions(definitions) {
const latestVersions = {};
// Regex to separate the version prefix, base activity details, and (optional) activity version
// Captures: (v1)(BaseName)(V2) where V2 is optional
// The base name must start with uppercase and can contain letters/numbers, but cannot end with V followed by digits
const keyVersionRegex = /^(v\d+)([A-Z][a-zA-Z0-9]*?)(V\d+)?$/;
Object.keys(definitions).forEach((key) => {
const match = key.match(keyVersionRegex);
if (match) {
const fullName = match[0];
const baseName = match[2]; // Field without any version-related prefixes or suffixes
const versionSuffix = match[3]; // Version (optional)
const formattedKeyName =
baseName.charAt(0).toLowerCase() +
baseName.slice(1) +
(versionSuffix || ""); // Reconstruct the original key with version
// Determine if this version is newer or if no version was previously stored
if (
!latestVersions[baseName] ||
versionSuffix > (latestVersions[baseName].versionSuffix || "")
) {
latestVersions[baseName] = {
fullName,
formattedKeyName,
versionSuffix,
};
}
}
});
return latestVersions;
}
const generateSDKClientFromSwagger = async (
swaggerSpec,
authProxySwaggerSpec,
targetPath,
) => {
const namespace = swaggerSpec.tags?.find((item) => item.name != null)?.name;
const authProxyNamespace = authProxySwaggerSpec.tags?.find(
(item) => item.name != null,
)?.name;
/** @type {Array<string>} */
const codeBuffer = [];
/** @type {Array<string>} */
const imports = [];
imports.push(
'import { GrpcStatus, StorageBase, TActivityResponse, TActivityStatus, TERMINAL_ACTIVITY_STATUSES, TSignedRequest, TStamper, TurnkeyHttpClientConfig, TurnkeyRequestError } from "../__types__";',
);
imports.push('import { VERSION } from "../__generated__/version";');
imports.push('import type * as SdkTypes from "@turnkey/sdk-types";');
imports.push(
'import { TurnkeyError, TurnkeyErrorCodes } from "@turnkey/sdk-types";',
);
imports.push('import { StamperType } from "../__types__";');
codeBuffer.push(`
export class TurnkeySDKClientBase {
config: TurnkeyHttpClientConfig;
// Store stampers
private apiKeyStamper?: TStamper | undefined;
private passkeyStamper?: TStamper | undefined;
private walletStamper?: TStamper | undefined;
public defaultStamperType: StamperType | undefined;
// Storage manager
private storageManager?: StorageBase | undefined;
constructor(config: TurnkeyHttpClientConfig) {
this.config = config;
if (config.apiKeyStamper) {
this.apiKeyStamper = config.apiKeyStamper;
}
if (config.passkeyStamper) {
this.passkeyStamper = config.passkeyStamper;
}
if (config.walletStamper) {
this.walletStamper = config.walletStamper;
}
if (config.storageManager) {
this.storageManager = config.storageManager;
}
if (config.defaultStamperType) {
this.defaultStamperType = config.defaultStamperType;
} else{
// Set default stamper type based on available stampers
if (this.apiKeyStamper) {
this.defaultStamperType = StamperType.ApiKey;
} else if (this.passkeyStamper) {
this.defaultStamperType = StamperType.Passkey;
} else if (this.walletStamper) {
this.defaultStamperType = StamperType.Wallet;
} else {
this.defaultStamperType = undefined;
}
}
}
private getStamper(stampWith?: StamperType): TStamper | undefined {
if (!stampWith) {
// Use default stamper type if none specified
stampWith = this.defaultStamperType;
}
switch (stampWith) {
case StamperType.ApiKey:
return this.apiKeyStamper;
case StamperType.Passkey:
return this.passkeyStamper;
case StamperType.Wallet:
return this.walletStamper;
default:
return this.apiKeyStamper;
}
}
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* Poll for activity completion until terminal status or max retries.
* @internal
*/
private async pollForCompletion(
activityId: string,
stampWith?: StamperType
): Promise<TActivityResponse> {
const pollingDuration = this.config.activityPoller?.intervalMs ?? 1000;
const maxRetries = this.config.activityPoller?.numRetries ?? 3;
let attempts = 0;
let activityData: TActivityResponse;
do {
await this.sleep(pollingDuration);
activityData = await this.getActivity({ activityId }, stampWith) as TActivityResponse;
attempts++;
} while (
!TERMINAL_ACTIVITY_STATUSES.includes(activityData.activity.status as TActivityStatus) &&
attempts < maxRetries
);
return activityData;
}
/**
* Extract and flatten result fields from a completed activity response.
* @internal
*/
private handleActivityResponse<TResponseType>(
activityData: TActivityResponse,
resultKey?: string
): TResponseType {
const { result, status } = activityData.activity;
if (status === "ACTIVITY_STATUS_COMPLETED" && result) {
// If a specific resultKey was provided, use it
if (resultKey && result[resultKey as keyof SdkTypes.v1Result]) {
return {
...result[resultKey as keyof SdkTypes.v1Result],
...activityData
} as TResponseType;
}
// Otherwise, try to find any result field and flatten it
for (const key of Object.keys(result)) {
if (key.endsWith('Result') && result[key as keyof SdkTypes.v1Result]) {
return {
...result[key as keyof SdkTypes.v1Result],
...activityData
} as TResponseType;
}
}
}
return activityData as TResponseType;
}
async request<TBodyType, TResponseType>(
url: string,
body: TBodyType,
stampWith?: StamperType
): Promise<TResponseType> {
const fullUrl = this.config.apiBaseUrl + url;
const stringifiedBody = JSON.stringify(body);
var headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Client-Version": VERSION
}
// Use the specified stamper for this request
const activeStamper = this.getStamper(stampWith);
if (activeStamper) {
const stamp = await activeStamper.stamp(stringifiedBody);
headers[stamp.stampHeaderName] = stamp.stampHeaderValue
}
const response = await fetch(fullUrl, {
method: "POST",
headers: headers,
body: stringifiedBody,
redirect: "follow"
});
if (!response.ok) {
let res: GrpcStatus;
try {
res = await response.json();
} catch (_) {
throw new Error(\`\${response.status} \${response.statusText}\`);
}
throw new TurnkeyRequestError(res);
}
const data = await response.json();
return data as TResponseType;
}
async activity<TBodyType, TResponseType>(
url: string,
body: TBodyType,
resultKey: string,
stampWith?: StamperType
): Promise<TResponseType> {
// Make the initial request
let activityData = await this.request<TBodyType, TActivityResponse>(url, body, stampWith);
// Poll if not in terminal status
if (!TERMINAL_ACTIVITY_STATUSES.includes(activityData.activity.status as TActivityStatus)) {
activityData = await this.pollForCompletion(activityData.activity.id, stampWith);
}
return this.handleActivityResponse<TResponseType>(activityData, resultKey);
}
async activityDecision<TBodyType, TResponseType>(
url: string,
body: TBodyType,
stampWith?: StamperType
): Promise<TResponseType> {
// Use the specified stamper for this request
const activityData = await this.request(url, body, stampWith) as TActivityResponse;
return {
...activityData["activity"]["result"],
...activityData
} as TResponseType;
}
async authProxyRequest<TBodyType, TResponseType>(
url: string,
body: TBodyType,
captchaToken?: string
): Promise<TResponseType> {
if (!this.config.authProxyUrl || !this.config.authProxyConfigId) {
throw new TurnkeyError("Auth Proxy URL or ID is not configured.", TurnkeyErrorCodes.INVALID_CONFIGURATION);
}
const fullUrl = this.config.authProxyUrl + url;
const stringifiedBody = JSON.stringify(body);
var headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Auth-Proxy-Config-ID": this.config.authProxyConfigId,
}
if (captchaToken) {
headers["X-Captcha-Token"] = captchaToken;
}
const response = await fetch(fullUrl, {
method: "POST",
headers: headers,
body: stringifiedBody,
});
if (!response.ok) {
let res: GrpcStatus;
try {
res = await response.json();
} catch (_) {
throw new Error(\`\${response.status} \${response.statusText}\`);
}
throw new TurnkeyRequestError(res);
}
const data = await response.json();
return data as TResponseType;
}
/**
* Submit a pre-signed request to Turnkey.
*
* Use this method to execute any TSignedRequest returned by the SDK's
* stamping methods (stampCreateApiKeys, stampGetPolicies, stampGetWallets, etc.).
*
* Works for both query and activity requests:
* - For queries: returns the response directly
* - For activities: automatically polls until completion and extracts the result
*
* @param signedRequest - A TSignedRequest object returned by a stamping method
* @param options - Optional configuration for the request
* @param options.resultKey - For activity requests, the key to extract from the result (e.g., "createApiKeysResultV2")
* @returns The parsed response, with activity result fields flattened if applicable
*/
async sendSignedRequest<TResponseType>(
signedRequest: TSignedRequest,
options?: { resultKey?: string }
): Promise<TResponseType> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Client-Version": VERSION,
[signedRequest.stamp.stampHeaderName]: signedRequest.stamp.stampHeaderValue,
};
const response = await fetch(signedRequest.url, {
method: "POST",
headers,
body: signedRequest.body,
});
if (!response.ok) {
let res: GrpcStatus;
try {
res = await response.json();
} catch (_) {
throw new Error(\`\${response.status} \${response.statusText}\`);
}
throw new TurnkeyRequestError(res);
}
const data = await response.json();
// Check if this is an activity response that needs polling
if (data.activity) {
let activityData = data as TActivityResponse;
// Poll if not in terminal status
if (!TERMINAL_ACTIVITY_STATUSES.includes(activityData.activity.status as TActivityStatus)) {
activityData = await this.pollForCompletion(activityData.activity.id);
}
return this.handleActivityResponse<TResponseType>(activityData, options?.resultKey);
}
return data as TResponseType;
}`);
const latestVersions = extractLatestVersions(swaggerSpec.definitions);
for (const endpointPath in swaggerSpec.paths) {
const methodMap = swaggerSpec.paths[endpointPath];
const operation = methodMap.post;
const operationId = operation.operationId;
const operationNameWithoutNamespace = operationId.replace(
new RegExp(`${namespace}_`),
"",
);
if (operationNameWithoutNamespace === "NOOPCodegenAnchor") {
continue;
}
const methodName = `${
operationNameWithoutNamespace.charAt(0).toLowerCase() +
operationNameWithoutNamespace.slice(1)
}`;
const methodType = methodTypeFromMethodName(methodName);
const inputType = `T${operationNameWithoutNamespace}Body`;
const responseType = `T${operationNameWithoutNamespace}Response`;
const unversionedActivityType = `ACTIVITY_TYPE_${operationNameWithoutNamespace
.replace(/([a-z])([A-Z])/g, "$1_$2")
.toUpperCase()}`;
const versionedActivityType =
VERSIONED_ACTIVITY_TYPES[unversionedActivityType]?.[0];
// for query methods, we use flat body structure
if (methodType === "query") {
codeBuffer.push(
`\n\t${methodName} = async (input: SdkTypes.${inputType}${
METHODS_WITH_ONLY_OPTIONAL_PARAMETERS.includes(methodName)
? " = {}"
: ""
}, stampWith?: StamperType): Promise<SdkTypes.${responseType}> => {
const session = await this.storageManager?.getActiveSession();
return this.request("${endpointPath}", {
...input,
organizationId: input.organizationId ?? session?.organizationId ?? this.config.organizationId
}, stampWith);
}`,
);
} else if (methodType === "activity") {
// For activity methods
const resultKey = operationNameWithoutNamespace + "Result";
if (!resultKey || !latestVersions[resultKey]) {
throw new Error(
`No latest version found for activity result key: ${resultKey}`,
);
}
const versionedMethodName = latestVersions[resultKey].formattedKeyName;
codeBuffer.push(
`\n\t${methodName} = async (input: SdkTypes.${inputType}, stampWith?: StamperType): Promise<SdkTypes.${responseType}> => {
const { organizationId, timestampMs, ...rest } = input;
const session = await this.storageManager?.getActiveSession();
return this.activity("${endpointPath}", {
parameters: rest,
organizationId: organizationId ?? (session?.organizationId ?? this.config.organizationId),
timestampMs: timestampMs ?? String(Date.now()),
type: "${versionedActivityType ?? unversionedActivityType + (latestVersions[resultKey].versionSuffix ? "_" + latestVersions[resultKey].versionSuffix : "")}"
}, "${versionedMethodName}", stampWith);
}`,
);
} else if (methodType === "activityDecision") {
// For activityDecision methods
codeBuffer.push(
`\n\t${methodName} = async (input: SdkTypes.${inputType}, stampWith?: StamperType): Promise<SdkTypes.${responseType}> => {
const { organizationId, timestampMs, ...rest } = input;
const session = await this.storageManager?.getActiveSession();
return this.activityDecision("${endpointPath}",
{
parameters: rest,
organizationId: organizationId ?? (session?.organizationId ?? this.config.organizationId),
timestampMs: timestampMs ?? String(Date.now()),
type: "ACTIVITY_TYPE_${operationNameWithoutNamespace
.replace(/([a-z])([A-Z])/g, "$1_$2")
.toUpperCase()}"
}, stampWith);
}`,
);
}
// generate a stamping method for each method
if (methodType === "noop") {
// we skip stamp method generation for noop methods
continue;
} else if (methodType === "query") {
// for query methods, we use flat body structure
codeBuffer.push(
`\n\tstamp${operationNameWithoutNamespace} = async (input: SdkTypes.${inputType}, stampWith?: StamperType): Promise<TSignedRequest | undefined> => {
const activeStamper = this.getStamper(stampWith);
if (!activeStamper) {
return undefined;
}
const session = await this.storageManager?.getActiveSession();
const fullUrl = this.config.apiBaseUrl + "${endpointPath}";
const body = {
...input,
organizationId: input.organizationId ?? session?.organizationId ?? this.config.organizationId
};
const stringifiedBody = JSON.stringify(body);
const stamp = await activeStamper.stamp(stringifiedBody);
return {
body: stringifiedBody,
stamp: stamp,
url: fullUrl,
};
}`,
);
} else {
// for activity and activityDecision methods, both use the same stamp structure
const resultKey = operationNameWithoutNamespace + "Result";
codeBuffer.push(
`\n\tstamp${operationNameWithoutNamespace} = async (input: SdkTypes.${inputType}, stampWith?: StamperType): Promise<TSignedRequest | undefined> => {
const activeStamper = this.getStamper(stampWith);
if (!activeStamper) {
return undefined;
}
const { organizationId, timestampMs, ...parameters } = input;
const session = await this.storageManager?.getActiveSession();
const fullUrl = this.config.apiBaseUrl + "${endpointPath}";
const bodyWithType = {
parameters,
organizationId: organizationId ?? (session?.organizationId ?? this.config.organizationId),
timestampMs: timestampMs ?? String(Date.now()),
type: "${versionedActivityType ?? unversionedActivityType + (latestVersions[resultKey]?.versionSuffix ? "_" + latestVersions[resultKey].versionSuffix : "")}"
};
const stringifiedBody = JSON.stringify(bodyWithType);
const stamp = await activeStamper.stamp(stringifiedBody);
return {
body: stringifiedBody,
stamp: stamp,
url: fullUrl,
};
}`,
);
}
}
for (const endpointPath in authProxySwaggerSpec.paths) {
const methodMap = authProxySwaggerSpec.paths[endpointPath];
const operation = methodMap.post;
const operationId = operation.operationId;
const operationNameWithoutNamespace = operationId.replace(
new RegExp(`${authProxyNamespace}_`),
"",
);
const methodName = `proxy${
operationNameWithoutNamespace.charAt(0).toUpperCase() +
operationNameWithoutNamespace.slice(1)
}`;
const inputType = `ProxyT${operationNameWithoutNamespace}Body`;
const responseType = `ProxyT${operationNameWithoutNamespace}Response`;
if (CAPTCHA_PROTECTED_METHODS.includes(methodName)) {
codeBuffer.push(
`\n\t${methodName} = async (input: SdkTypes.${inputType}${
METHODS_WITH_ONLY_OPTIONAL_PARAMETERS.includes(methodName)
? " = {}"
: ""
}, captchaToken?: string): Promise<SdkTypes.${responseType}> => {
return this.authProxyRequest("${endpointPath}", input, captchaToken);
}`,
);
} else {
codeBuffer.push(
`\n\t${methodName} = async (input: SdkTypes.${inputType}${
METHODS_WITH_ONLY_OPTIONAL_PARAMETERS.includes(methodName)
? " = {}"
: ""
}): Promise<SdkTypes.${responseType}> => {
return this.authProxyRequest("${endpointPath}", input);
}`,
);
}
}
// End of the TurnkeySDKClient Class Definition
codeBuffer.push(`}`);
await fs.promises.writeFile(
targetPath,
[COMMENT_HEADER].concat(imports).concat(codeBuffer).join("\n\n"),
);
};
// Main Runner
main().catch((error) => {
console.error(error);
process.exit(1);
});
async function main() {
const swaggerSpecFile = await fs.promises.readFile(
PUBLIC_API_SWAGGER_PATH,
"utf-8",
);
const authProxySwaggerSpecFile = await fs.promises.readFile(
AUTH_PROXY_SWAGGER_PATH,
"utf-8",
);
const swaggerSpec = JSON.parse(swaggerSpecFile);
const authProxySwaggerSpec = JSON.parse(authProxySwaggerSpecFile);
await generateSDKClientFromSwagger(
swaggerSpec,
authProxySwaggerSpec,
TARGET_SDK_CLIENT_PATH,
);
}