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