@descope/core-js-sdk 0.0.41-alpha.5 → 0.0.41-alpha.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/cjs/index.cjs.js +2 -0
- package/dist/cjs/index.cjs.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/index.d.ts +352 -63
- package/dist/index.esm.js +1 -1
- package/dist/index.esm.js.map +1 -1
- package/package.json +39 -18
- package/dist/index.cjs.js +0 -2
- package/dist/index.cjs.js.map +0 -1
- package/dist/index.umd.js +0 -2
- package/dist/index.umd.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,168 @@
|
|
|
1
|
-
declare type
|
|
1
|
+
declare type JSONSerializable = string | number | boolean | null | Array<JSONSerializable>;
|
|
2
|
+
declare type FlowInput = Record<string, JSONSerializable>;
|
|
3
|
+
|
|
4
|
+
declare type SdkFn$1 = (...args: any[]) => Promise<SdkResponse<ResponseData>>;
|
|
5
|
+
declare type DeviceInfo = {
|
|
6
|
+
webAuthnSupport?: boolean;
|
|
7
|
+
};
|
|
8
|
+
declare type LocalUser = {
|
|
9
|
+
authMethod?: AuthMethod;
|
|
10
|
+
oauthProvider?: string;
|
|
11
|
+
loginId?: string;
|
|
12
|
+
};
|
|
13
|
+
declare type AuthMethod = 'otp' | 'magiclink' | 'social' | 'sso' | 'webauthn' | 'totp';
|
|
14
|
+
/** User base details from Descope API */
|
|
2
15
|
declare type User = {
|
|
3
16
|
email?: string;
|
|
4
17
|
name?: string;
|
|
5
18
|
phone?: string;
|
|
6
19
|
};
|
|
20
|
+
/** User extended details from Descope API */
|
|
21
|
+
declare type UserResponse = User & {
|
|
22
|
+
loginIds: string[];
|
|
23
|
+
userId: string;
|
|
24
|
+
verifiedEmail?: boolean;
|
|
25
|
+
verifiedPhone?: boolean;
|
|
26
|
+
picture?: string;
|
|
27
|
+
};
|
|
28
|
+
/** Login options to be added to the different authentication methods */
|
|
29
|
+
declare type LoginOptions = {
|
|
30
|
+
stepup?: boolean;
|
|
31
|
+
mfa?: boolean;
|
|
32
|
+
customClaims?: Record<string, any>;
|
|
33
|
+
};
|
|
34
|
+
/** Authentication info result from the various JWT validations */
|
|
35
|
+
declare type JWTResponse = {
|
|
36
|
+
sessionJwt: string;
|
|
37
|
+
refreshJwt?: string;
|
|
38
|
+
cookieDomain?: string;
|
|
39
|
+
cookiePath?: string;
|
|
40
|
+
cookieMaxAge?: number;
|
|
41
|
+
cookieExpiration?: number;
|
|
42
|
+
user?: UserResponse;
|
|
43
|
+
firstSeen?: boolean;
|
|
44
|
+
};
|
|
45
|
+
/** Authentication info result from exchanging access keys for a session */
|
|
46
|
+
declare type ExchangeAccessKeyResponse = {
|
|
47
|
+
keyId: string;
|
|
48
|
+
sessionJwt: string;
|
|
49
|
+
expiration: number;
|
|
50
|
+
};
|
|
51
|
+
/** The response returned from the various start webauthn functions */
|
|
52
|
+
declare type WebAuthnStartResponse = {
|
|
53
|
+
transactionId: string;
|
|
54
|
+
options: string;
|
|
55
|
+
create: boolean;
|
|
56
|
+
};
|
|
57
|
+
/** Enchanted link response */
|
|
58
|
+
declare type EnchantedLinkResponse = {
|
|
59
|
+
/** Pending reference URL to poll while waiting for user to click magic link */
|
|
60
|
+
pendingRef: string;
|
|
61
|
+
/** Link id, on which link the user should click */
|
|
62
|
+
linkId: string;
|
|
63
|
+
};
|
|
64
|
+
/** URL response to redirect user in case of OAuth or SSO */
|
|
65
|
+
declare type URLResponse = {
|
|
66
|
+
url: string;
|
|
67
|
+
};
|
|
68
|
+
/** TOTP response with the TOTP details */
|
|
69
|
+
declare type TOTPResponse = {
|
|
70
|
+
provisioningURL: string;
|
|
71
|
+
image: string;
|
|
72
|
+
key: string;
|
|
73
|
+
};
|
|
74
|
+
/** All delivery methods currently supported */
|
|
7
75
|
declare enum DeliveryMethods {
|
|
8
76
|
email = "email",
|
|
9
77
|
sms = "sms",
|
|
10
78
|
whatsapp = "whatsapp"
|
|
11
79
|
}
|
|
12
|
-
|
|
13
|
-
|
|
80
|
+
/** All flow execution statuses
|
|
81
|
+
* - waiting - flow execution is waiting for user interaction
|
|
82
|
+
* - running - flow execution is currently running
|
|
83
|
+
* - completed - flow execution completed successfully
|
|
84
|
+
* - failed - flow execution failed
|
|
85
|
+
*/
|
|
86
|
+
declare enum FlowStatus {
|
|
87
|
+
waiting = "waiting",
|
|
88
|
+
running = "running",
|
|
89
|
+
completed = "completed",
|
|
90
|
+
failed = "failed"
|
|
91
|
+
}
|
|
92
|
+
/** All flow response action
|
|
93
|
+
* - screen - next action is to render screen
|
|
94
|
+
* - poll - next action is poll for next after timeout
|
|
95
|
+
* - redirect - next action is to redirect (redirection details in 'redirect' attribute)
|
|
96
|
+
* - webauthnCreate/webauthnGet - next action is to prompt webauthn (details in 'webauthn' attribute)
|
|
97
|
+
* - none - no next action
|
|
98
|
+
*/
|
|
99
|
+
declare type FlowAction = 'screen' | 'poll' | 'redirect' | 'webauthnCreate' | 'webauthnGet' | 'none';
|
|
100
|
+
/** Flow response with flow execution details */
|
|
101
|
+
declare type FlowResponse = {
|
|
102
|
+
executionId: string;
|
|
103
|
+
stepId: string;
|
|
104
|
+
status: FlowStatus;
|
|
105
|
+
action: FlowAction;
|
|
106
|
+
screen?: {
|
|
107
|
+
id: string;
|
|
108
|
+
state: Record<string, any>;
|
|
109
|
+
};
|
|
110
|
+
redirect?: {
|
|
111
|
+
url: string;
|
|
112
|
+
};
|
|
113
|
+
webauthn?: {
|
|
114
|
+
transactionId: string;
|
|
115
|
+
options: string;
|
|
116
|
+
create: boolean;
|
|
117
|
+
};
|
|
118
|
+
error?: {
|
|
119
|
+
code: string;
|
|
120
|
+
description: string;
|
|
121
|
+
message: string;
|
|
122
|
+
};
|
|
123
|
+
authInfo?: JWTResponse;
|
|
124
|
+
};
|
|
125
|
+
declare type Options = {
|
|
126
|
+
redirectUrl?: string;
|
|
127
|
+
tenant?: string;
|
|
128
|
+
deviceInfo?: DeviceInfo;
|
|
129
|
+
lastUser?: LocalUser;
|
|
130
|
+
};
|
|
131
|
+
declare type ResponseData = Record<string, any>;
|
|
132
|
+
/**
|
|
133
|
+
* Response from our SDK calls which includes the result (ok, code, error).
|
|
134
|
+
* The relevant data is provided in the more specific interfaces extending SdkResponse.
|
|
135
|
+
*/
|
|
136
|
+
declare type SdkResponse<T extends ResponseData> = {
|
|
14
137
|
code?: number;
|
|
15
138
|
ok: boolean;
|
|
16
139
|
response?: Response;
|
|
17
140
|
error?: {
|
|
18
141
|
message: string;
|
|
19
|
-
|
|
142
|
+
errorCode: string;
|
|
143
|
+
errorDescription?: string;
|
|
144
|
+
retryAfter?: string;
|
|
20
145
|
};
|
|
21
|
-
data?:
|
|
146
|
+
data?: T;
|
|
22
147
|
};
|
|
23
|
-
|
|
148
|
+
/** Different delivery method */
|
|
149
|
+
declare type Deliveries<T extends SdkFn$1> = Record<keyof typeof DeliveryMethods, T>;
|
|
150
|
+
/** Logger type that supports the given levels (debug, log, error) */
|
|
151
|
+
declare type Logger = Pick<Console, 'debug' | 'log' | 'error' | 'warn'>;
|
|
24
152
|
|
|
153
|
+
declare type EnchantedLinkSignInFn = (loginId: string, uri: string) => Promise<SdkResponse<EnchantedLinkResponse>>;
|
|
154
|
+
declare type EnchantedLinkSignUpFn = (loginId: string, uri: string, user?: User) => Promise<SdkResponse<EnchantedLinkResponse>>;
|
|
155
|
+
/** Polling configuration for session waiting */
|
|
156
|
+
declare type WaitForSessionConfig = {
|
|
157
|
+
pollingIntervalMs: number;
|
|
158
|
+
timeoutMs: number;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
declare type SignInFn = (loginId: string, uri: string) => Promise<SdkResponse<never>>;
|
|
162
|
+
declare type SignUpFn = (loginId: string, uri: string, user?: User) => Promise<SdkResponse<never>>;
|
|
163
|
+
declare type UpdatePhoneFn = (loginId: string, phone: string) => Promise<SdkResponse<never>>;
|
|
164
|
+
|
|
165
|
+
/** Request configuration including headers, query params and token */
|
|
25
166
|
declare type HttpClientReqConfig = {
|
|
26
167
|
headers?: HeadersInit;
|
|
27
168
|
queryParams?: {
|
|
@@ -29,19 +170,38 @@ declare type HttpClientReqConfig = {
|
|
|
29
170
|
};
|
|
30
171
|
token?: string;
|
|
31
172
|
};
|
|
173
|
+
/** HTTP methods we use in the client */
|
|
174
|
+
declare enum HTTPMethods {
|
|
175
|
+
get = "GET",
|
|
176
|
+
delete = "DELETE",
|
|
177
|
+
post = "POST",
|
|
178
|
+
put = "PUT"
|
|
179
|
+
}
|
|
180
|
+
/** HTTP Client type that implements the HTTP method calls. Descopers can provide their own HTTP client although required only in rare cases. */
|
|
32
181
|
declare type HttpClient = {
|
|
33
182
|
get: (path: string, config?: HttpClientReqConfig) => Promise<Response>;
|
|
34
183
|
post: (path: string, body?: any, config?: HttpClientReqConfig) => Promise<Response>;
|
|
35
184
|
put: (path: string, body?: any, config?: HttpClientReqConfig) => Promise<Response>;
|
|
36
185
|
delete: (path: string, body?: any, config?: HttpClientReqConfig) => Promise<Response>;
|
|
186
|
+
hooks?: Hooks;
|
|
37
187
|
};
|
|
38
|
-
|
|
39
|
-
declare type
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
188
|
+
/** For before-request hook allows overriding parts of the request */
|
|
189
|
+
declare type RequestConfig = {
|
|
190
|
+
path: string;
|
|
191
|
+
headers?: HeadersInit;
|
|
192
|
+
queryParams?: {
|
|
193
|
+
[key: string]: string;
|
|
194
|
+
};
|
|
195
|
+
body?: any;
|
|
196
|
+
method: HTTPMethods;
|
|
197
|
+
token?: string;
|
|
198
|
+
};
|
|
199
|
+
declare type BeforeRequest = (config: RequestConfig) => RequestConfig;
|
|
200
|
+
declare type AfterRequest = (req: RequestConfig, res: Response) => void | Promise<void>;
|
|
201
|
+
/** Hooks before and after the request is made */
|
|
202
|
+
declare type Hooks = {
|
|
203
|
+
beforeRequest?: BeforeRequest;
|
|
204
|
+
afterRequest?: AfterRequest;
|
|
45
205
|
};
|
|
46
206
|
|
|
47
207
|
declare enum OAuthProviders {
|
|
@@ -50,118 +210,247 @@ declare enum OAuthProviders {
|
|
|
50
210
|
google = "google",
|
|
51
211
|
microsoft = "microsoft",
|
|
52
212
|
gitlab = "gitlab",
|
|
53
|
-
apple = "apple"
|
|
213
|
+
apple = "apple",
|
|
214
|
+
discord = "discord",
|
|
215
|
+
linkedin = "linkedin"
|
|
54
216
|
}
|
|
55
217
|
|
|
56
|
-
|
|
218
|
+
/** Transform the Promise Response to our internal SdkResponse implementation
|
|
219
|
+
* @param response The Response promise from fetch
|
|
220
|
+
* @param transform Optionally transform the response JSON to another type
|
|
221
|
+
*/
|
|
222
|
+
declare function transformResponse<T extends ResponseData, S extends ResponseData = T>(response: Promise<Response>, transform?: (data: T) => S): Promise<SdkResponse<S>>;
|
|
223
|
+
|
|
224
|
+
declare type IsObject<T> = T extends Array<any> ? false : T extends Function ? false : T extends object ? true : false;
|
|
225
|
+
declare type Tail<T extends ReadonlyArray<string>> = T extends readonly [head: any, ...tail: infer Tail_] ? Tail_ : never;
|
|
226
|
+
declare type Head<T extends ReadonlyArray<string>> = T extends readonly [] ? never : T[0];
|
|
227
|
+
declare type SdkResponseType<F extends SdkFn<ResponseData>> = F extends SdkFn<infer U> ? U : never;
|
|
228
|
+
declare type SdkFnWrapperInternal<F extends SdkFn<ResponseData>, R extends ResponseData> = (fn: (...args: Parameters<F>) => ReturnType<F>) => (...args: Parameters<F>) => Promise<SdkResponse<R extends Record<string, never> ? SdkResponseType<F> : SdkResponseType<F> & R>>;
|
|
229
|
+
declare type PrependDot<T extends string> = [T] extends [never] ? '' : `.${T}`;
|
|
230
|
+
declare type SdkFnsPaths<T extends object> = keyof T extends infer K ? K extends string & keyof T ? IsObject<T> extends false ? never : T[K] extends SdkFn<ResponseData> ? K : IsObject<T[K]> extends false ? never : T[K] extends object ? `${K}${PrependDot<SdkFnsPaths<T[K]>>}` : never : never : never;
|
|
231
|
+
declare type ReplacePaths<Obj extends object, Paths extends ReadonlyArray<string>, WrapperData extends Record<string, any>> = Head<Paths> extends never ? Obj : Tail<Paths> extends ReadonlyArray<string> ? ReplacePaths<ReplacePath<Obj, Head<Paths>, WrapperData>, Tail<Paths>, WrapperData> : ReplacePath<Obj, Head<Paths>, WrapperData>;
|
|
232
|
+
declare type ReplacePath<Obj, Path extends string, WrapperData extends Record<string, any>> = Path extends `${infer Head}.${infer Tail}` ? {
|
|
233
|
+
[Key in keyof Obj]: Key extends Head ? ReplacePath<Obj[Key], Tail, WrapperData> : Obj[Key];
|
|
234
|
+
} : {
|
|
235
|
+
[Key in keyof Obj]: Key extends Path ? Obj[Key] extends SdkFn<ResponseData> ? ReturnType<SdkFnWrapperInternal<Obj[Key], WrapperData>> : Obj[Key] : Obj[Key];
|
|
236
|
+
};
|
|
237
|
+
declare type SdkFn<T extends ResponseData> = (...args: any) => Promise<SdkResponse<T>>;
|
|
238
|
+
declare type SdkFnWrapper<Z extends ResponseData> = <A extends any[], R extends ResponseData>(fn: (...args: A) => Promise<SdkResponse<R>>) => (...args: A) => Promise<SdkResponse<Z extends Record<string, never> ? R : Z & R>>;
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* A wrapper function that allows to wrap multiple Sdk function
|
|
242
|
+
* @param obj: The Sdk instance you want to wrap
|
|
243
|
+
* @param paths: A readonly list of paths of the functions you want to wrap
|
|
244
|
+
* @param wrapper: Your wrapper function, it should gets an Sdk function and return a new Sdk function
|
|
245
|
+
* @returns a mutated instance of the Sdk with updated type definitions based on your wrapper return type
|
|
246
|
+
*
|
|
247
|
+
* Usage example:
|
|
248
|
+
*
|
|
249
|
+
* // Assuming this is our SDK instance
|
|
250
|
+
* const sdk = {
|
|
251
|
+
* me: (token) => {...}
|
|
252
|
+
* flow: {
|
|
253
|
+
* start: (...params) => {...}
|
|
254
|
+
* next: (...params) => {...}
|
|
255
|
+
* }
|
|
256
|
+
* ...
|
|
257
|
+
* }
|
|
258
|
+
*
|
|
259
|
+
* // This is our wrapper
|
|
260
|
+
* const wrapper = (sdkFn) => async (...args) => {
|
|
261
|
+
* const sdkResponse = await sdkFn(...args)
|
|
262
|
+
*
|
|
263
|
+
* // Modify return value
|
|
264
|
+
* return {...sdkResponse, data: {...sdkResponse.data, myCustomAttribute: 'hello'}}
|
|
265
|
+
* }
|
|
266
|
+
*
|
|
267
|
+
* // And those are the paths we want to wrap
|
|
268
|
+
* const paths = ['flow.start', 'flow.next'] as const // You MUST add as const!
|
|
269
|
+
*
|
|
270
|
+
* // We can wrap our SDK functions with the wrapper we created in this way
|
|
271
|
+
* const newlyTypedSdk = wrapWith(sdk, paths, wrapper)
|
|
272
|
+
*
|
|
273
|
+
* Now the 2 wrapped functions will have the updated type based on the wrapper return value
|
|
274
|
+
*/
|
|
275
|
+
declare const wrapWith: <Obj extends object, Paths extends readonly SdkFnsPaths<Obj>[], WrapperData extends ResponseData>(obj: Obj, paths: Paths, wrapper: SdkFnWrapper<WrapperData>) => ReplacePaths<Obj, Paths, WrapperData>;
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Add hooks to an existing core-sdk config
|
|
279
|
+
*/
|
|
280
|
+
declare const addHooksToConfig: <Config extends Omit<{
|
|
281
|
+
projectId: string;
|
|
282
|
+
logger?: Logger;
|
|
283
|
+
baseUrl?: string;
|
|
284
|
+
hooks?: Hooks;
|
|
285
|
+
cookiePolicy?: RequestCredentials;
|
|
286
|
+
baseHeaders?: HeadersInit;
|
|
287
|
+
}, "hooks"> & {
|
|
288
|
+
hooks?: {
|
|
289
|
+
beforeRequest?: BeforeRequest | BeforeRequest[];
|
|
290
|
+
afterRequest?: AfterRequest | AfterRequest[];
|
|
291
|
+
};
|
|
292
|
+
}>(config: Config, hooks: Config["hooks"]) => Config;
|
|
293
|
+
|
|
294
|
+
declare const _default$1: {
|
|
295
|
+
TOO_MANY_REQUESTS: number;
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
/** Descope SDK client with delivery methods enum.
|
|
299
|
+
*
|
|
300
|
+
* Please see full documentation at {@link https://docs.descope.com/guides Descope Docs}
|
|
301
|
+
* @example Usage
|
|
302
|
+
*
|
|
303
|
+
* ```js
|
|
304
|
+
* import descopeSdk from '@descope/core-js-sdk';
|
|
305
|
+
*
|
|
306
|
+
* const myProjectId = 'xxx';
|
|
307
|
+
* const sdk = descopeSdk({ projectId: myProjectId });
|
|
308
|
+
*
|
|
309
|
+
* const userLoginId = 'loginId';
|
|
310
|
+
* sdk.otp.signIn.email(userLoginId);
|
|
311
|
+
* const jwtResponse = sdk.otp.verify.email(userIdentifier, codeFromEmail);
|
|
312
|
+
* ```
|
|
313
|
+
*/
|
|
314
|
+
declare const _default: ((config: Omit<{
|
|
57
315
|
projectId: string;
|
|
58
316
|
logger?: Logger;
|
|
59
317
|
baseUrl?: string;
|
|
318
|
+
hooks?: Hooks;
|
|
319
|
+
cookiePolicy?: RequestCredentials;
|
|
320
|
+
baseHeaders?: HeadersInit;
|
|
321
|
+
}, "hooks"> & {
|
|
322
|
+
hooks?: {
|
|
323
|
+
beforeRequest?: BeforeRequest | BeforeRequest[];
|
|
324
|
+
afterRequest?: AfterRequest | AfterRequest[];
|
|
325
|
+
};
|
|
60
326
|
}) => {
|
|
327
|
+
accessKey: {
|
|
328
|
+
exchange: (accessKey: string) => Promise<SdkResponse<ExchangeAccessKeyResponse>>;
|
|
329
|
+
};
|
|
61
330
|
otp: {
|
|
62
|
-
verify: Deliveries<(
|
|
63
|
-
signIn: Deliveries<(
|
|
64
|
-
signUp: Deliveries<(
|
|
65
|
-
signUpOrIn: Deliveries<(
|
|
331
|
+
verify: Deliveries<(loginId: string, code: string) => Promise<SdkResponse<JWTResponse>>>;
|
|
332
|
+
signIn: Deliveries<(loginId: string) => Promise<SdkResponse<never>>>;
|
|
333
|
+
signUp: Deliveries<(loginId: string, user?: User) => Promise<SdkResponse<never>>>;
|
|
334
|
+
signUpOrIn: Deliveries<(loginId: string) => Promise<SdkResponse<never>>>;
|
|
66
335
|
update: {
|
|
67
|
-
email: (
|
|
68
|
-
phone: Deliveries<(
|
|
336
|
+
email: (loginId: string, email: string, token?: string) => Promise<SdkResponse<never>>;
|
|
337
|
+
phone: Deliveries<(loginId: string, phone: string) => Promise<SdkResponse<never>>>;
|
|
69
338
|
};
|
|
70
339
|
};
|
|
71
340
|
magicLink: {
|
|
72
|
-
verify: (token: string) => Promise<SdkResponse
|
|
341
|
+
verify: (token: string) => Promise<SdkResponse<JWTResponse>>;
|
|
73
342
|
signIn: Deliveries<SignInFn>;
|
|
74
343
|
signUp: Deliveries<SignUpFn>;
|
|
75
344
|
signUpOrIn: Deliveries<SignInFn>;
|
|
76
345
|
update: {
|
|
77
|
-
email: (
|
|
346
|
+
email: (loginId: string, email: string, uri: string, token?: string) => Promise<SdkResponse<never>>;
|
|
78
347
|
phone: Deliveries<UpdatePhoneFn>;
|
|
79
348
|
};
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
};
|
|
349
|
+
};
|
|
350
|
+
enchantedLink: {
|
|
351
|
+
verify: (token: string) => Promise<SdkResponse<never>>;
|
|
352
|
+
signIn: EnchantedLinkSignInFn;
|
|
353
|
+
signUpOrIn: EnchantedLinkSignInFn;
|
|
354
|
+
signUp: EnchantedLinkSignUpFn;
|
|
355
|
+
waitForSession: (pendingRef: string, config?: WaitForSessionConfig) => Promise<SdkResponse<JWTResponse>>;
|
|
356
|
+
update: {
|
|
357
|
+
email: (loginId: string, email: string, uri: string, token?: string) => Promise<SdkResponse<EnchantedLinkResponse>>;
|
|
90
358
|
};
|
|
91
359
|
};
|
|
92
360
|
oauth: {
|
|
93
|
-
exchange: (code: string) => Promise<SdkResponse>;
|
|
94
361
|
start: {
|
|
95
362
|
facebook: <B extends {
|
|
96
363
|
redirect: boolean;
|
|
97
|
-
}>(config?: B) => Promise<B extends {
|
|
364
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
98
365
|
redirect: true;
|
|
99
|
-
} ? undefined : SdkResponse
|
|
366
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
100
367
|
github: <B extends {
|
|
101
368
|
redirect: boolean;
|
|
102
|
-
}>(config?: B) => Promise<B extends {
|
|
369
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
103
370
|
redirect: true;
|
|
104
|
-
} ? undefined : SdkResponse
|
|
371
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
105
372
|
google: <B extends {
|
|
106
373
|
redirect: boolean;
|
|
107
|
-
}>(config?: B) => Promise<B extends {
|
|
374
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
108
375
|
redirect: true;
|
|
109
|
-
} ? undefined : SdkResponse
|
|
376
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
110
377
|
microsoft: <B extends {
|
|
111
378
|
redirect: boolean;
|
|
112
|
-
}>(config?: B) => Promise<B extends {
|
|
379
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
113
380
|
redirect: true;
|
|
114
|
-
} ? undefined : SdkResponse
|
|
381
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
115
382
|
gitlab: <B extends {
|
|
116
383
|
redirect: boolean;
|
|
117
|
-
}>(config?: B) => Promise<B extends {
|
|
384
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
118
385
|
redirect: true;
|
|
119
|
-
} ? undefined : SdkResponse
|
|
386
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
120
387
|
apple: <B extends {
|
|
121
388
|
redirect: boolean;
|
|
122
|
-
}>(config?: B) => Promise<B extends {
|
|
389
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
390
|
+
redirect: true;
|
|
391
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
392
|
+
discord: <B extends {
|
|
393
|
+
redirect: boolean;
|
|
394
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
123
395
|
redirect: true;
|
|
124
|
-
} ? undefined : SdkResponse
|
|
396
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
397
|
+
linkedin: <B extends {
|
|
398
|
+
redirect: boolean;
|
|
399
|
+
}>(redirectURL?: string, config?: B) => Promise<B extends {
|
|
400
|
+
redirect: true;
|
|
401
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
125
402
|
};
|
|
403
|
+
exchange: (code: string) => Promise<SdkResponse<JWTResponse>>;
|
|
126
404
|
};
|
|
127
405
|
saml: {
|
|
128
|
-
exchange: (code: string) => Promise<SdkResponse>;
|
|
129
406
|
start: <B_1 extends {
|
|
130
407
|
redirect: boolean;
|
|
131
408
|
}>(tenantNameOrEmail: string, config?: B_1) => Promise<B_1 extends {
|
|
132
409
|
redirect: true;
|
|
133
|
-
} ? undefined : SdkResponse
|
|
410
|
+
} ? undefined : SdkResponse<URLResponse>>;
|
|
411
|
+
exchange: (code: string) => Promise<SdkResponse<JWTResponse>>;
|
|
134
412
|
};
|
|
135
413
|
totp: {
|
|
136
|
-
signUp: (
|
|
137
|
-
verify: (
|
|
138
|
-
update: (
|
|
414
|
+
signUp: (loginId: string, user?: User) => Promise<SdkResponse<TOTPResponse>>;
|
|
415
|
+
verify: (loginId: string, code: string, loginOptions?: LoginOptions, token?: string) => Promise<SdkResponse<JWTResponse>>;
|
|
416
|
+
update: (loginId: string, token?: string) => Promise<SdkResponse<TOTPResponse>>;
|
|
139
417
|
};
|
|
140
418
|
webauthn: {
|
|
141
419
|
signUp: {
|
|
142
|
-
start: (
|
|
143
|
-
finish: (transactionId: string, response: string) => Promise<SdkResponse
|
|
420
|
+
start: (loginId: string, origin: string, name: string) => Promise<SdkResponse<WebAuthnStartResponse>>;
|
|
421
|
+
finish: (transactionId: string, response: string) => Promise<SdkResponse<JWTResponse>>;
|
|
144
422
|
};
|
|
145
423
|
signIn: {
|
|
146
|
-
start: (
|
|
147
|
-
finish: (transactionId: string, response: string) => Promise<SdkResponse
|
|
424
|
+
start: (loginId: string, origin: string, loginOptions?: LoginOptions, token?: string) => Promise<SdkResponse<WebAuthnStartResponse>>;
|
|
425
|
+
finish: (transactionId: string, response: string) => Promise<SdkResponse<JWTResponse>>;
|
|
426
|
+
};
|
|
427
|
+
signUpOrIn: {
|
|
428
|
+
start: (loginId: string, origin: string) => Promise<SdkResponse<WebAuthnStartResponse>>;
|
|
148
429
|
};
|
|
149
|
-
|
|
150
|
-
start: (
|
|
151
|
-
finish: (transactionId: string, response: string) => Promise<SdkResponse
|
|
430
|
+
update: {
|
|
431
|
+
start: (loginId: string, origin: string, token: string) => Promise<SdkResponse<WebAuthnStartResponse>>;
|
|
432
|
+
finish: (transactionId: string, response: string) => Promise<SdkResponse<ResponseData>>;
|
|
152
433
|
};
|
|
153
434
|
};
|
|
154
435
|
flow: {
|
|
155
|
-
start: (flowId: string) => Promise<SdkResponse
|
|
156
|
-
next: (executionId: string, stepId: string,
|
|
436
|
+
start: (flowId: string, options?: Options, interactionId?: string, input?: FlowInput) => Promise<SdkResponse<FlowResponse>>;
|
|
437
|
+
next: (executionId: string, stepId: string, interactionId: string, input?: FlowInput) => Promise<SdkResponse<FlowResponse>>;
|
|
157
438
|
};
|
|
158
|
-
refresh: (token?: string) => Promise<SdkResponse
|
|
159
|
-
logout: (token?: string) => Promise<SdkResponse
|
|
439
|
+
refresh: (token?: string) => Promise<SdkResponse<JWTResponse>>;
|
|
440
|
+
logout: (token?: string) => Promise<SdkResponse<never>>;
|
|
441
|
+
logoutAll: (token?: string) => Promise<SdkResponse<never>>;
|
|
442
|
+
me: (token?: string) => Promise<SdkResponse<UserResponse>>;
|
|
160
443
|
isJwtExpired: (token: string) => boolean;
|
|
444
|
+
getJwtPermissions: (token: string, tenant?: string) => string[];
|
|
445
|
+
getJwtRoles: (token: string, tenant?: string) => string[];
|
|
161
446
|
httpClient: HttpClient;
|
|
447
|
+
}) & {
|
|
448
|
+
DeliveryMethods: typeof DeliveryMethods;
|
|
162
449
|
};
|
|
163
450
|
|
|
451
|
+
/** Type to restrict to valid delivery methods */
|
|
164
452
|
declare type DeliveryMethod = keyof typeof DeliveryMethods;
|
|
453
|
+
/** Type to restrict to valid OAuth providers */
|
|
165
454
|
declare type OAuthProvider = keyof typeof OAuthProviders;
|
|
166
455
|
|
|
167
|
-
export { DeliveryMethod, OAuthProvider, SdkResponse, _default as default };
|
|
456
|
+
export { DeliveryMethod, EnchantedLinkResponse, ExchangeAccessKeyResponse, FlowAction, FlowResponse, FlowStatus, HTTPMethods, _default$1 as HttpStatusCodes, JWTResponse, OAuthProvider, RequestConfig, ResponseData, SdkFnWrapper, SdkResponse, TOTPResponse, URLResponse, UserResponse, addHooksToConfig, _default as default, transformResponse, wrapWith };
|
package/dist/index.esm.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__awaiter as e}from"tslib";import t from"jwt-decode";import s from"lodash.get";var n={verify:"/v1/auth/code/verify",signIn:"/v1/auth/signin/otp",signUp:"/v1/auth/signup/otp",update:{email:"/v1/user/update/email/otp",phone:"/v1/user/update/phone/otp"},signUpOrIn:"/v1/auth/sign-up-or-in/otp"},i={verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/signin/magiclink",signUp:"/v1/auth/signup/magiclink",session:"/v1/auth/magiclink/session",update:{email:"/v1/user/update/email/magiclink",phone:"/v1/user/update/phone/magiclink"},signUpOrIn:"/v1/auth/sign-up-or-in/magiclink"},r={start:"/v1/oauth/authorize"},o={start:"/v1/auth/saml/authorize"},a={verify:"/v1/auth/verify/totp",signUp:"/v1/auth/signup/totp",update:"/v1/user/update/totp"},d={signUp:{start:"/v1/webauthn/signup/start",finish:"/v1/webauthn/signup/finish"},signIn:{start:"/v1/webauthn/signin/start",finish:"/v1/webauthn/signin/finish"},add:{start:"/v1/webauthn/device/add/start",finish:"/v1/webauthn/device/add/finish"}},p="/v1/auth/refresh",c="/v1/auth/logoutall",u={start:"/v1/flow/start",next:"/v1/flow/next"},l="/v1/auth/exchange";const g=()=>{const e={};return{headers(t){const s="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(s),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},h=(t,s)=>{const n=s||fetch;if(!n)throw new Error("fetch is not defined");return t?(...s)=>e(void 0,void 0,void 0,(function*(){t.log((e=>g().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(s));const i=yield n(...s);return t[i.ok?"log":"error"](yield(t=>e(void 0,void 0,void 0,(function*(){const e=yield t.text();return t.text=()=>Promise.resolve(e),t.json=()=>Promise.resolve(JSON.parse(e)),g().title("Response").url(t.url.toString()).status(`${t.status} ${t.statusText}`).headers(t.headers).body(e).build()})))(i)),i})):n},v=(...e)=>new Headers(e.reduce(((e,t)=>{const s=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return s.reduce(((t,[s,n])=>(e[s]=n,e)),e),e}),{})),m=e=>void 0===e?void 0:JSON.stringify(e);var b;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(b||(b={}));const f=(e,t="")=>({Authorization:`Basic ${btoa(`${e}:${t}`)}`}),I=({baseUrl:e,projectId:t,baseConfig:s,logger:n})=>{const i=h(n),r=({path:n,body:r,headers:o,queryParams:a,method:d,token:p})=>i((({path:e,baseUrl:t,queryParams:s})=>{const n=new URL(e,t);return s&&(n.search=new URLSearchParams(s).toString()),n})({path:n,baseUrl:e,queryParams:a}),{headers:v(f(t,p),(null==s?void 0:s.baseHeaders)||{},o),method:d,body:m(r)});return{get:(e,{headers:t,queryParams:s,token:n}={})=>r({path:e,headers:t,queryParams:s,body:void 0,method:b.get,token:n}),post:(e,t,{headers:s,queryParams:n,token:i}={})=>r({path:e,headers:s,queryParams:n,body:t,method:b.post,token:i}),put:(e,t,{headers:s,queryParams:n,token:i}={})=>r({path:e,headers:s,queryParams:n,body:t,method:b.put,token:i}),delete:(e,t,{headers:s,queryParams:n,token:i}={})=>r({path:e,headers:s,queryParams:n,body:t,method:b.delete,token:i})}},y=e=>{if("string"!=typeof e||!e)throw new Error("Invalid token provided");const{exp:s}=t(e);return(new Date).getTime()/1e3>s},j=(...e)=>e.join("/").replaceAll(/\/{2,}/g,"/"),O=t=>e(void 0,void 0,void 0,(function*(){const e=yield t,s={code:e.status,ok:e.ok,response:e},n=yield e.json();return e.ok?s.data=n:s.error=n,s}));var k,U,x;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(k||(k={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(U||(U={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(x||(x={}));const w=(e,t)=>(s=t)=>t=>!e(t)&&s.replace("{val}",t),P=(...e)=>({validate:t=>(e.forEach((e=>{const s=e(t);if(s)throw new Error(s)})),!0)}),R=e=>t=>e.test(t),$=R(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),q=R(/^\+[1-9]{1}[0-9]{3,14}$/),E=w($,'"{val}" is not a valid email'),M=w(q,'"{val}" is not a valid phone number'),S=w((T=1,e=>e.length>=T),"Minimum length is 1");var T;const A=w((e=>"string"==typeof e),"Input is not a string"),D=(...e)=>t=>(...s)=>(e.forEach(((e,t)=>P(...e).validate(s[t]))),t(...s)),z=e=>[A(`"${e}" must be a string`),S(`"${e}" must not be empty`)],L=e=>[A(`"${e}" must be a string`),E()],H=e=>[A(`"${e}" must be a string`),M()];var J;!function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(J||(J={}));const N=z("identifier"),Z=D(N,z("code")),B=D(N),C=D(N,H("phone")),F=D(N,L("email")),G=e=>({verify:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:Z(((t,i)=>O(e.post(j(n.verify,s),{code:i,externalId:t}))))})),{}),signIn:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:B((t=>O(e.post(j(n.signIn,s),{externalId:t}))))})),{}),signUp:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:B(((t,i)=>O(e.post(j(n.signUp,s),{externalId:t,user:i}))))})),{}),signUpOrIn:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:B((t=>O(e.post(j(n.signUpOrIn,s),{externalId:t}))))})),{}),update:{email:F(((t,s,i)=>O(e.post(n.update.email,{externalId:t,email:s},{token:i})))),phone:Object.keys(k).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:C(((t,i,r)=>O(e.post(j(n.update.phone,s),{externalId:t,phone:i},{token:r}))))})),{})}}),_=z("identifier"),K=z("uri"),Q=D(z("token")),V=D(_,K),W=D(z("pendingRef")),X=D(_,H("phone"),K),Y=D(_,L("email"),K),ee=t=>({verify:Q((e=>O(t.post(i.verify,{token:e})))),signIn:Object.keys(U).reduce(((e,s)=>Object.assign(Object.assign({},e),{[s]:V(((e,n)=>O(t.post(j(i.signIn,s),{externalId:e,URI:n,crossDevice:!0}))))})),{}),signUpOrIn:Object.keys(U).reduce(((e,s)=>Object.assign(Object.assign({},e),{[s]:V(((e,n)=>O(t.post(j(i.signUpOrIn,s),{externalId:e,URI:n,crossDevice:!0}))))})),{}),signUp:Object.keys(U).reduce(((e,s)=>Object.assign(Object.assign({},e),{[s]:V(((e,n,r)=>O(t.post(j(i.signUp,s),{externalId:e,URI:n,user:r,crossDevice:!0}))))})),{}),waitForSession:W(((s,n)=>new Promise((r=>{const{pollingIntervalMs:o,timeoutMs:a}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let d;const p=setInterval((()=>e(void 0,void 0,void 0,(function*(){const e=yield t.post(i.session,{pendingRef:s});e.ok&&(clearInterval(p),d&&clearTimeout(d),r(O(Promise.resolve(e))))}))),o);d=setTimeout((()=>{r({error:{message:`Session polling timeout exceeded: ${a}ms`,code:"0"},ok:!1}),clearInterval(p)}),a)})))),update:{email:Y(((e,s,n,r)=>O(t.post(i.update.email,{externalId:e,email:s,URI:n,crossDevice:!0},{token:r})))),phone:Object.keys(k).reduce(((e,s)=>Object.assign(Object.assign({},e),{[s]:X(((e,n,r,o)=>O(t.post(j(i.update.phone,s),{externalId:e,phone:n,URI:r,crossDevice:!0},{token:o}))))})),{})}}),te=e=>({verify:Q((t=>O(e.post(i.verify,{token:t})))),signIn:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:V(((t,n)=>O(e.post(j(i.signIn,s),{externalId:t,URI:n}))))})),{}),signUp:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:V(((t,n,r)=>O(e.post(j(i.signUp,s),{externalId:t,URI:n,user:r}))))})),{}),signUpOrIn:Object.keys(U).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:V(((t,n)=>O(e.post(j(i.signUpOrIn,s),{externalId:t,URI:n}))))})),{}),update:{email:Y(((t,s,n,r)=>O(e.post(i.update.email,{externalId:t,email:s,URI:n},{token:r})))),phone:Object.keys(k).reduce(((t,s)=>Object.assign(Object.assign({},t),{[s]:X(((t,n,r,o)=>O(e.post(j(i.update.phone,s),{externalId:t,phone:n,URI:r},{token:o}))))})),{})},crossDevice:ee(e)}),se=D(z("code")),ne=e=>({exchange:se((t=>O(e.get(l,{queryParams:{code:t}}))))});var ie;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple"}(ie||(ie={}));const re=t=>Object.assign({start:Object.keys(ie).reduce(((s,n)=>Object.assign(Object.assign({},s),{[n]:(s,{redirect:i=!1}={})=>e(void 0,void 0,void 0,(function*(){const e=yield t.get(r.start,{queryParams:{provider:n,redirectURL:s}});if(!i||!e.ok)return O(Promise.resolve(e));const{url:o}=yield e.json();window.location.href=o}))})),{})},ne(t)),oe=D(z("flowId")),ae=D(z("executionId"),z("stepId"),z("actionId")),de=e=>({start:oe((t=>O(e.post(u.start,{flowId:t})))),next:ae(((t,s,n,i)=>O(e.post(u.next,{executionId:t,stepId:s,actionId:n,input:i}))))}),pe=D(z("tenant")),ce=t=>Object.assign({start:pe(((s,n,{redirect:i=!1}={})=>e(void 0,void 0,void 0,(function*(){const e=yield t.get(o.start,{queryParams:{tenant:s,redirectURL:n}});if(!i||!e.ok)return O(Promise.resolve(e));const{url:r}=yield e.json();window.location.href=r}))))},ne(t)),ue=z("identifier"),le=D(ue,z("code")),ge=D(ue),he=D(ue),ve=e=>({signUp:ge(((t,s)=>O(e.post(a.signUp,{externalId:t,user:s})))),verify:le(((t,s)=>O(e.post(a.verify,{externalId:t,code:s})))),update:he(((t,s)=>O(e.post(a.update,{externalId:t},{token:s}))))}),me=z("identifier"),be=z("origin"),fe=D(me,be,z("name")),Ie=D(me,be),ye=D(me,be,z("token")),je=D(z("transactionId"),z("response")),Oe=e=>({signUp:{start:fe(((t,s,n)=>O(e.post(d.signUp.start,{user:{externalId:t,name:n},origin:s})))),finish:je(((t,s)=>O(e.post(d.signUp.finish,{transactionId:t,response:s}))))},signIn:{start:Ie(((t,s)=>O(e.post(d.signIn.start,{externalId:t,origin:s})))),finish:je(((t,s)=>O(e.post(d.signIn.finish,{transactionId:t,response:s}))))},add:{start:ye(((t,s,n)=>O(e.post(d.add.start,{externalId:t,origin:s},{token:n})))),finish:je(((t,s)=>O(e.post(d.add.finish,{transactionId:t,response:s}))))}}),ke=D(z("token"));var Ue,xe,we=D([(Ue="projectId",xe=z("projectId"),w(((e,t)=>n=>P(...t).validate(s(n,e)))(Ue,xe))())])((({projectId:e,logger:t,baseUrl:s})=>{return n=I({baseUrl:s||"https://api.descope.com",projectId:e,logger:t}),{otp:G(n),magicLink:te(n),oauth:re(n),saml:ce(n),totp:ve(n),webauthn:Oe(n),flow:de(n),refresh:e=>O(n.get(p,{token:e})),logout:e=>O(n.get(c,{token:e})),isJwtExpired:ke(y),httpClient:n};var n}));export{we as default};
|
|
1
|
+
import e from"jwt-decode";import t from"lodash.get";var n={exchange:"/v1/auth/accesskey/exchange"},s={verify:"/v1/auth/otp/verify",signIn:"/v1/auth/otp/signin",signUp:"/v1/auth/otp/signup",update:{email:"/v1/auth/otp/update/email",phone:"/v1/auth/otp/update/phone"},signUpOrIn:"/v1/auth/otp/signup-in"},o={verify:"/v1/auth/magiclink/verify",signIn:"/v1/auth/magiclink/signin",signUp:"/v1/auth/magiclink/signup",update:{email:"/v1/auth/magiclink/update/email",phone:"/v1/auth/magiclink/update/phone"},signUpOrIn:"/v1/auth/magiclink/signup-in"},i={verify:"/v1/auth/enchantedlink/verify",signIn:"/v1/auth/enchantedlink/signin",signUp:"/v1/auth/enchantedlink/signup",session:"/v1/auth/enchantedlink/pending-session",update:{email:"/v1/auth/enchantedlink/update/email"},signUpOrIn:"/v1/auth/enchantedlink/signup-in"},a={start:"/v1/auth/oauth/authorize",exchange:"/v1/auth/oauth/exchange"},r={start:"/v1/auth/saml/authorize",exchange:"/v1/auth/saml/exchange"},u={verify:"/v1/auth/totp/verify",signUp:"/v1/auth/totp/signup",update:"/v1/auth/totp/update"},d={signUp:{start:"/v1/auth/webauthn/signup/start",finish:"/v1/auth/webauthn/signup/finish"},signIn:{start:"/v1/auth/webauthn/signin/start",finish:"/v1/auth/webauthn/signin/finish"},signUpOrIn:{start:"/v1/auth/webauthn/signup-in/start"},update:{start:"v1/auth/webauthn/update/start",finish:"/v1/auth/webauthn/update/finish"}},l="/v1/auth/refresh",c="/v1/auth/logout",p="/v1/auth/logoutall",g="/v1/auth/me",h={start:"/v1/flow/start",next:"/v1/flow/next"};const v=()=>{const e={};return{headers(t){const n="function"==typeof t.entries?Object.fromEntries(t.entries()):t;return e.Headers=JSON.stringify(n),this},body(t){return e.Body=t,this},url(t){return e.Url=t.toString(),this},method(t){return e.Method=t,this},title(t){return e.Title=t,this},status(t){return e.Status=t,this},build:()=>Object.keys(e).flatMap((t=>e[t]?[`${"Title"!==t?`${t}: `:""}${e[t]}`]:[])).join("\n")}},f=(e,t)=>{const n=t||fetch;return n||null==e||e.warn("Fetch is not defined, you will not be able to send http requests, if you are running in a test, make sure fetch is defined globally"),e?async(...t)=>{if(!n)throw Error("Cannot send http request, fetch is not defined, if you are running in a test, make sure fetch is defined globally");e.log((e=>v().title("Request").url(e[0]).method(e[1].method).headers(e[1].headers).body(e[1].body).build())(t));const s=await n(...t);return e[s.ok?"log":"error"](await(async e=>{const t=await(e.clone?e.clone().text():e.text());return e.text=()=>Promise.resolve(t),e.json=()=>Promise.resolve(JSON.parse(t)),v().title("Response").url(e.url.toString()).status(`${e.status} ${e.statusText}`).headers(e.headers).body(t).build()})(s)),s}:n};var m;!function(e){e.get="GET",e.delete="DELETE",e.post="POST",e.put="PUT"}(m||(m={}));const I=(...e)=>new Headers(e.reduce(((e,t)=>{const n=(e=>Array.isArray(e)?e:e instanceof Headers?Array.from(e.entries()):e?Object.entries(e):[])(t);return n.reduce(((t,[n,s])=>(e[n]=s,e)),e),e}),{})),b=e=>void 0===e?void 0:JSON.stringify(e),k=(e,t="")=>{let n=e;return t&&(n=n+":"+t),{Authorization:`Bearer ${n}`}},y=({baseUrl:e,projectId:t,baseConfig:n,logger:s,hooks:o,cookiePolicy:i})=>{const a=f(s),r=async s=>{const r=(null==o?void 0:o.beforeRequest)?o.beforeRequest(s):s,{path:u,body:d,headers:l,queryParams:c,method:p,token:g}=r,h=await a((({path:e,baseUrl:t,queryParams:n})=>{const s=new URL(e,t);return n&&(s.search=new URLSearchParams(n).toString()),s})({path:u,baseUrl:e,queryParams:c}),{headers:I(k(t,g),{"x-descope-sdk-name":"core-js","x-descope-sdk-version":"0.0.41-alpha.50"},(null==n?void 0:n.baseHeaders)||{},l),method:p,body:b(d),credentials:i||"include"});return(null==o?void 0:o.afterRequest)&&await o.afterRequest(s,null==h?void 0:h.clone()),h};return{get:(e,{headers:t,queryParams:n,token:s}={})=>r({path:e,headers:t,queryParams:n,body:void 0,method:m.get,token:s}),post:(e,t,{headers:n,queryParams:s,token:o}={})=>r({path:e,headers:n,queryParams:s,body:t,method:m.post,token:o}),put:(e,t,{headers:n,queryParams:s,token:o}={})=>r({path:e,headers:n,queryParams:s,body:t,method:m.put,token:o}),delete:(e,t,{headers:n,queryParams:s,token:o}={})=>r({path:e,headers:n,queryParams:s,body:t,method:m.delete,token:o}),hooks:o}};var O={TOO_MANY_REQUESTS:429};function w(e,t,n){var s;let o=j(e);t&&(o=null===(s=o.tenants)||void 0===s?void 0:s[t]);const i=o[n];return Array.isArray(i)?i:[]}function j(t){if("string"!=typeof t||!t)throw new Error("Invalid token provided");return e(t)}function U(e){const{exp:t}=j(e);return(new Date).getTime()/1e3>t}function R(e,t){return w(e,t,"permissions")}function x(e,t){return w(e,t,"roles")}const P=(...e)=>e.join("/").replace(/\/{2,}/g,"/");async function q(e,t){var n;const s=await e,o={code:s.status,ok:s.ok,response:s},i=await s.clone().json();return s.ok?o.data=t?t(i):i:(o.error=i,s.status===O.TOO_MANY_REQUESTS&&Object.assign(o.error,{retryAfter:Number.parseInt(null===(n=s.headers)||void 0===n?void 0:n.get("retry-after"))||0})),o}const E=(e,t)=>(n=t)=>t=>!e(t)&&n.replace("{val}",t),$=(...e)=>({validate:t=>(e.forEach((e=>{const n=e(t);if(n)throw new Error(n)})),!0)}),S=e=>t=>e.test(t),M=S(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),T=S(/^\+[1-9]{1}[0-9]{3,14}$/),A=E(M,'"{val}" is not a valid email'),L=E(T,'"{val}" is not a valid phone number'),z=E((H=1,e=>e.length>=H),"Minimum length is 1");var H;const J=E((e=>"string"==typeof e),"Input is not a string"),N=(...e)=>t=>(...n)=>(e.forEach(((e,t)=>$(...e).validate(n[t]))),t(...n)),C=e=>[J(`"${e}" must be a string`),z(`"${e}" must not be empty`)],_=e=>[J(`"${e}" must be a string`),A()],D=e=>[J(`"${e}" must be a string`),L()],Z=N(C("accessKey")),B=e=>({exchange:Z((t=>q(e.post(n.exchange,{},{token:t}))))});var F,K,Q,Y;!function(e){e.sms="sms",e.whatsapp="whatsapp"}(F||(F={})),function(e){e.email="email",e.sms="sms",e.whatsapp="whatsapp"}(K||(K={})),function(e){e.waiting="waiting",e.running="running",e.completed="completed",e.failed="failed"}(Q||(Q={})),function(e){e.signUp="signup",e.signIn="signin",e.verify="verify"}(Y||(Y={}));const G=C("loginId"),V=C("uri"),W=N(C("token")),X=N(G,V),ee=N(C("pendingRef")),te=N(G,_("email"),V),ne=e=>({verify:W((t=>q(e.post(i.verify,{token:t})))),signIn:X(((t,n,s,o)=>q(e.post(P(i.signIn,K.email),{loginId:t,URI:n,loginOptions:s},{token:o})))),signUpOrIn:X(((t,n)=>q(e.post(P(i.signUpOrIn,K.email),{loginId:t,URI:n})))),signUp:X(((t,n,s)=>q(e.post(P(i.signUp,K.email),{loginId:t,URI:n,user:s})))),waitForSession:ee(((t,n)=>new Promise((s=>{const{pollingIntervalMs:o,timeoutMs:a}=(({pollingIntervalMs:e=1e3,timeoutMs:t=6e5}={})=>({pollingIntervalMs:Math.max(e||1e3,1e3),timeoutMs:Math.min(t||6e5,6e5)}))(n);let r;const u=setInterval((async()=>{const n=await e.post(i.session,{pendingRef:t});n.ok&&(clearInterval(u),r&&clearTimeout(r),s(q(Promise.resolve(n))))}),o);r=setTimeout((()=>{s({error:{message:`Session polling timeout exceeded: ${a}ms`,errorCode:"0"},ok:!1}),clearInterval(u)}),a)})))),update:{email:te(((t,n,s,o)=>q(e.post(i.update.email,{loginId:t,email:n,URI:s},{token:o}))))}}),se=N(C("flowId")),oe=N(C("executionId"),C("stepId"),C("interactionId")),ie=e=>({start:se(((t,n,s,o)=>q(e.post(h.start,{flowId:t,options:n,interactionId:s,input:o})))),next:oe(((t,n,s,o)=>q(e.post(h.next,{executionId:t,stepId:n,interactionId:s,input:o}))))}),ae=C("loginId"),re=C("uri"),ue=N(C("token")),de=N(ae,re),le=N(ae,D("phone"),re),ce=N(ae,_("email"),re),pe=e=>({verify:ue((t=>q(e.post(o.verify,{token:t})))),signIn:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:de(((t,s,i,a)=>q(e.post(P(o.signIn,n),{loginId:t,URI:s,loginOptions:i},{token:a}))))})),{}),signUp:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:de(((t,s,i)=>q(e.post(P(o.signUp,n),{loginId:t,URI:s,user:i}))))})),{}),signUpOrIn:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:de(((t,s)=>q(e.post(P(o.signUpOrIn,n),{loginId:t,URI:s}))))})),{}),update:{email:ce(((t,n,s,i)=>q(e.post(o.update.email,{loginId:t,email:n,URI:s},{token:i})))),phone:Object.keys(F).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:le(((t,s,i,a)=>q(e.post(P(o.update.phone,n),{loginId:t,phone:s,URI:i},{token:a}))))})),{})}});var ge;!function(e){e.facebook="facebook",e.github="github",e.google="google",e.microsoft="microsoft",e.gitlab="gitlab",e.apple="apple",e.discord="discord",e.linkedin="linkedin"}(ge||(ge={}));const he=N(C("code")),ve=e=>({start:Object.keys(ge).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:async(t,{redirect:s=!1}={},o,i)=>{const r=await e.post(a.start,o||{},{queryParams:Object.assign({provider:n},t&&{redirectURL:t}),token:i});if(!s||!r.ok)return q(Promise.resolve(r));const{url:u}=await r.json();window.location.href=u}})),{}),exchange:he((t=>q(e.post(a.exchange,{code:t}))))});var fe;!function(e){e.signUp="signup",e.signIn="signin",e.verify="verify",e.updatePhone="updatePhone"}(fe||(fe={}));const me=C("loginId"),Ie=N(me,C("code")),be=N(me),ke=N(me,D("phone")),ye=N(me,_("email")),Oe=e=>({verify:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:Ie(((t,o)=>q(e.post(P(s.verify,n),{code:o,loginId:t}))))})),{}),signIn:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be(((t,o,i)=>q(e.post(P(s.signIn,n),{loginId:t,loginOptions:o},{token:i}))))})),{}),signUp:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be(((t,o)=>q(e.post(P(s.signUp,n),{loginId:t,user:o}))))})),{}),signUpOrIn:Object.keys(K).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:be((t=>q(e.post(P(s.signUpOrIn,n),{loginId:t}))))})),{}),update:{email:ye(((t,n,o)=>q(e.post(s.update.email,{loginId:t,email:n},{token:o})))),phone:Object.keys(F).reduce(((t,n)=>Object.assign(Object.assign({},t),{[n]:ke(((t,o,i)=>q(e.post(P(s.update.phone,n),{loginId:t,phone:o},{token:i}))))})),{})}}),we=N(C("tenant")),je=N(C("code")),Ue=e=>({start:we((async(t,n,{redirect:s=!1}={},o,i)=>{const a=await e.post(r.start,o||{},{queryParams:{tenant:t,redirectURL:n},token:i});if(!s||!a.ok)return q(Promise.resolve(a));const{url:u}=await a.json();window.location.href=u})),exchange:je((t=>q(e.post(r.exchange,{code:t}))))}),Re=C("loginId"),xe=N(Re,C("code")),Pe=N(Re),qe=N(Re),Ee=e=>({signUp:Pe(((t,n)=>q(e.post(u.signUp,{loginId:t,user:n})))),verify:xe(((t,n,s,o)=>q(e.post(u.verify,{loginId:t,code:n,loginOptions:s},{token:o})))),update:qe(((t,n)=>q(e.post(u.update,{loginId:t},{token:n}))))}),$e=[J(`"${"loginId"}" must be a string`)];const Se=C("loginId"),Me=C("origin"),Te=N(Se,Me,C("name")),Ae=N(Se,Me),Le=N($e,Me),ze=N(Se,Me,C("token")),He=N(C("transactionId"),C("response")),Je=e=>({signUp:{start:Te(((t,n,s)=>q(e.post(d.signUp.start,{user:{loginId:t,name:s},origin:n})))),finish:He(((t,n)=>q(e.post(d.signUp.finish,{transactionId:t,response:n}))))},signIn:{start:Le(((t,n,s,o)=>q(e.post(d.signIn.start,{loginId:t,origin:n,loginOptions:s},{token:o})))),finish:He(((t,n)=>q(e.post(d.signIn.finish,{transactionId:t,response:n}))))},signUpOrIn:{start:Ae(((t,n)=>q(e.post(d.signUpOrIn.start,{loginId:t,origin:n}))))},update:{start:ze(((t,n,s)=>q(e.post(d.update.start,{loginId:t,origin:n},{token:s})))),finish:He(((t,n)=>q(e.post(d.update.finish,{transactionId:t,response:n}))))}}),Ne=N(C("token"));var Ce,_e;var De=N([(Ce="projectId",_e=C("projectId"),E(((e,n)=>s=>$(...n).validate(t(s,e)))(Ce,_e))())])((e=>t=>{var n,s;const o=[].concat((null===(n=t.hooks)||void 0===n?void 0:n.beforeRequest)||[]),i=[].concat((null===(s=t.hooks)||void 0===s?void 0:s.afterRequest)||[]);return e(Object.assign(Object.assign({},t),{hooks:{beforeRequest:e=>null==o?void 0:o.reduce(((e,t)=>t(e)),e),afterRequest:async(e,n)=>{(await Promise.allSettled(null==i?void 0:i.map((t=>t(e,null==n?void 0:n.clone()))))).forEach((e=>{var n;return"rejected"===e.status&&(null===(n=t.logger)||void 0===n?void 0:n.error(e.reason))}))}}}))})((({projectId:e,logger:t=console,baseUrl:n,hooks:s,cookiePolicy:o,baseHeaders:i={}})=>{return a=y({baseUrl:n||"https://api.descope.com",projectId:e,logger:t,hooks:s,cookiePolicy:o,baseConfig:{baseHeaders:i}}),{accessKey:B(a),otp:Oe(a),magicLink:pe(a),enchantedLink:ne(a),oauth:ve(a),saml:Ue(a),totp:Ee(a),webauthn:Je(a),flow:ie(a),refresh:e=>q(a.post(l,{},{token:e})),logout:e=>q(a.post(c,{},{token:e})),logoutAll:e=>q(a.post(p,{},{token:e})),me:e=>q(a.get(g,{token:e})),isJwtExpired:Ne(U),getJwtPermissions:Ne(R),getJwtRoles:Ne(x),httpClient:a};var a})));const Ze=(e,t,n)=>(t.forEach((t=>{const s=t.split(".");let o=s.shift(),i=e;for(;s.length>0;){if(i=i[o],!o||!i)throw Error(`Invalid path "${t}", "${o}" is missing or has no value`);o=s.shift()}if("function"!=typeof i[o])throw Error(`"${t}" is not a function`);const a=i[o];i[o]=n(a)})),e),Be=(e,t)=>{var n;return["beforeRequest","afterRequest"].reduce(((n,s)=>{var o;return n[s]=[].concat((null===(o=e.hooks)||void 0===o?void 0:o[s])||[]).concat((null==t?void 0:t[s])||[]),n}),null!==(n=e.hooks)&&void 0!==n?n:e.hooks={}),e};var Fe=Object.assign(De,{DeliveryMethods:K});export{O as HttpStatusCodes,Be as addHooksToConfig,Fe as default,q as transformResponse,Ze as wrapWith};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|