@wix/sdk 1.1.21 → 1.2.5

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.
Files changed (51) hide show
  1. package/build/browser/index.mjs +783 -0
  2. package/build/index.d.mts +244 -0
  3. package/build/index.d.ts +244 -0
  4. package/build/index.js +818 -0
  5. package/build/index.mjs +774 -0
  6. package/package.json +38 -24
  7. package/dist/cjs/__tests__/fixtures/constants.js +0 -9
  8. package/dist/cjs/__tests__/fixtures/constants.js.map +0 -1
  9. package/dist/cjs/auth/OAuthStrategy.js +0 -90
  10. package/dist/cjs/auth/OAuthStrategy.js.map +0 -1
  11. package/dist/cjs/auth/strategy.js +0 -2
  12. package/dist/cjs/auth/strategy.js.map +0 -1
  13. package/dist/cjs/external-types.d.js +0 -2
  14. package/dist/cjs/external-types.d.js.map +0 -1
  15. package/dist/cjs/index.js +0 -22
  16. package/dist/cjs/index.js.map +0 -1
  17. package/dist/cjs/test-types.d.js +0 -2
  18. package/dist/cjs/test-types.d.js.map +0 -1
  19. package/dist/cjs/wixClient.js +0 -111
  20. package/dist/cjs/wixClient.js.map +0 -1
  21. package/dist/cjs/wixMedia.js +0 -69
  22. package/dist/cjs/wixMedia.js.map +0 -1
  23. package/dist/esm/__tests__/fixtures/constants.js +0 -3
  24. package/dist/esm/__tests__/fixtures/constants.js.map +0 -1
  25. package/dist/esm/auth/OAuthStrategy.js +0 -86
  26. package/dist/esm/auth/OAuthStrategy.js.map +0 -1
  27. package/dist/esm/auth/strategy.js +0 -2
  28. package/dist/esm/auth/strategy.js.map +0 -1
  29. package/dist/esm/external-types.d.js +0 -2
  30. package/dist/esm/external-types.d.js.map +0 -1
  31. package/dist/esm/index.js +0 -4
  32. package/dist/esm/index.js.map +0 -1
  33. package/dist/esm/test-types.d.js +0 -2
  34. package/dist/esm/test-types.d.js.map +0 -1
  35. package/dist/esm/wixClient.js +0 -108
  36. package/dist/esm/wixClient.js.map +0 -1
  37. package/dist/esm/wixMedia.js +0 -63
  38. package/dist/esm/wixMedia.js.map +0 -1
  39. package/dist/tsconfig.tsbuildinfo +0 -1
  40. package/dist/types/__tests__/fixtures/constants.d.ts +0 -3
  41. package/dist/types/__tests__/fixtures/constants.d.ts.map +0 -1
  42. package/dist/types/auth/OAuthStrategy.d.ts +0 -18
  43. package/dist/types/auth/OAuthStrategy.d.ts.map +0 -1
  44. package/dist/types/auth/strategy.d.ts +0 -6
  45. package/dist/types/auth/strategy.d.ts.map +0 -1
  46. package/dist/types/index.d.ts +0 -4
  47. package/dist/types/index.d.ts.map +0 -1
  48. package/dist/types/wixClient.d.ts +0 -18
  49. package/dist/types/wixClient.d.ts.map +0 -1
  50. package/dist/types/wixMedia.d.ts +0 -26
  51. package/dist/types/wixMedia.d.ts.map +0 -1
@@ -0,0 +1,783 @@
1
+ // src/common.ts
2
+ var PUBLIC_METADATA_KEY = "__metadata";
3
+ var API_URL = "www.wixapis.com";
4
+
5
+ // src/helpers.ts
6
+ var getDefaultContentHeader = (options) => {
7
+ if ((options == null ? void 0 : options.method) && ["post", "put", "patch"].includes(options.method.toLocaleLowerCase()) && options.body) {
8
+ return { "Content-Type": "application/json" };
9
+ }
10
+ return {};
11
+ };
12
+ var isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
13
+
14
+ // src/bi/biHeaderGenerator.ts
15
+ var WixBIHeaderName = "x-wix-bi-gateway";
16
+ function biHeaderGenerator(apiMetadata, publicMetadata) {
17
+ var _a;
18
+ return {
19
+ [WixBIHeaderName]: objectToKeyValue({
20
+ environment: "js-sdk",
21
+ "package-name": (_a = apiMetadata.packageName) != null ? _a : publicMetadata == null ? void 0 : publicMetadata.PACKAGE_NAME,
22
+ "method-fqn": apiMetadata.methodFqn,
23
+ entity: apiMetadata.entityFqdn
24
+ })
25
+ };
26
+ }
27
+ function objectToKeyValue(input) {
28
+ return Object.entries(input).filter(([_, value]) => Boolean(value)).map(([key, value]) => `${key}=${value}`).join(",");
29
+ }
30
+
31
+ // src/rest-modules.ts
32
+ function buildRESTDescriptor(origFunc, publicMetadata, boundFetch) {
33
+ return origFunc({
34
+ request: async (factory) => {
35
+ var _a;
36
+ const requestOptions = factory({ host: API_URL });
37
+ let url = `https://${API_URL}${requestOptions.url}`;
38
+ if (requestOptions.params && requestOptions.params.toString()) {
39
+ url += `?${requestOptions.params.toString()}`;
40
+ }
41
+ try {
42
+ const biHeader = biHeaderGenerator(requestOptions, publicMetadata);
43
+ const res = await boundFetch(url, {
44
+ method: requestOptions.method,
45
+ ...requestOptions.data && {
46
+ body: JSON.stringify(requestOptions.data)
47
+ },
48
+ headers: {
49
+ ...biHeader
50
+ }
51
+ });
52
+ if (res.status !== 200) {
53
+ let dataError = null;
54
+ try {
55
+ dataError = await res.json();
56
+ } catch (e) {
57
+ }
58
+ throw errorBuilder(
59
+ res.status,
60
+ dataError == null ? void 0 : dataError.message,
61
+ dataError == null ? void 0 : dataError.details,
62
+ {
63
+ requestId: res.headers.get("X-Wix-Request-Id"),
64
+ details: dataError
65
+ }
66
+ );
67
+ }
68
+ const data = await res.json();
69
+ return {
70
+ data,
71
+ headers: res.headers,
72
+ status: res.status,
73
+ statusText: res.statusText
74
+ };
75
+ } catch (e) {
76
+ if ((_a = e.message) == null ? void 0 : _a.includes("fetch is not defined")) {
77
+ console.error("Node.js v18+ is required");
78
+ }
79
+ throw e;
80
+ }
81
+ }
82
+ });
83
+ }
84
+ var errorBuilder = (code, description, details, data) => {
85
+ return {
86
+ response: {
87
+ data: {
88
+ details: {
89
+ ...!(details == null ? void 0 : details.validationError) && {
90
+ applicationError: {
91
+ description,
92
+ code,
93
+ data
94
+ }
95
+ },
96
+ ...details
97
+ },
98
+ message: description
99
+ },
100
+ status: code
101
+ }
102
+ };
103
+ };
104
+
105
+ // src/host-modules.ts
106
+ var isHostModule = (val) => isObject(val) && val.__type === "host";
107
+ function buildHostModule(val, host) {
108
+ return val.create(host);
109
+ }
110
+
111
+ // src/wixClient.ts
112
+ function createClient(config) {
113
+ const _headers = config.headers || { Authorization: "" };
114
+ const authStrategy = config.auth || {
115
+ getAuthHeaders: () => Promise.resolve({ headers: {} })
116
+ };
117
+ const boundFetch = async (url, options) => {
118
+ const authHeaders = await authStrategy.getAuthHeaders(config.host);
119
+ const defaultContentTypeHeader = getDefaultContentHeader(options);
120
+ return fetch(url, {
121
+ ...options,
122
+ headers: {
123
+ ...defaultContentTypeHeader,
124
+ ..._headers,
125
+ ...authHeaders == null ? void 0 : authHeaders.headers,
126
+ ...options == null ? void 0 : options.headers
127
+ }
128
+ });
129
+ };
130
+ const use = (modules, metadata) => {
131
+ if (isHostModule(modules)) {
132
+ return buildHostModule(modules, config.host);
133
+ } else if (typeof modules === "function") {
134
+ return buildRESTDescriptor(
135
+ modules,
136
+ metadata != null ? metadata : {},
137
+ boundFetch
138
+ );
139
+ } else if (isObject(modules)) {
140
+ return Object.fromEntries(
141
+ Object.entries(
142
+ modules
143
+ ).map(([key, value]) => {
144
+ return [key, use(value, modules[PUBLIC_METADATA_KEY])];
145
+ })
146
+ );
147
+ } else {
148
+ return modules;
149
+ }
150
+ };
151
+ const setHeaders = (headers) => {
152
+ for (const k in headers) {
153
+ _headers[k] = headers[k];
154
+ }
155
+ };
156
+ const wrappedModules = config.modules ? use(config.modules) : {};
157
+ return {
158
+ ...wrappedModules,
159
+ auth: authStrategy,
160
+ setHeaders,
161
+ use,
162
+ fetch: (relativeUrl, options) => {
163
+ const finalUrl = new URL(relativeUrl, `https://${API_URL}`);
164
+ finalUrl.host = API_URL;
165
+ finalUrl.protocol = "https";
166
+ return boundFetch(finalUrl, options);
167
+ }
168
+ };
169
+ }
170
+
171
+ // src/wixMedia.ts
172
+ import { sdk } from "@wix/image-kit";
173
+ import { parse } from "querystring";
174
+ var URL_HASH_PREFIX = "#";
175
+ var WIX_PROTOCOL = "wix:";
176
+ var WIX_IMAGE = "image";
177
+ var WIX_IMAGE_URL = "https://static.wixstatic.com/media/";
178
+ function getScaledToFillImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
179
+ const img = getImageUrl(wixMediaIdentifier);
180
+ return sdk.getScaleToFillImageURL(
181
+ img.id,
182
+ img.height,
183
+ img.width,
184
+ targetWidth,
185
+ targetHeight,
186
+ options
187
+ );
188
+ }
189
+ function getScaledToFitImageUrl(wixMediaIdentifier, targetWidth, targetHeight, options) {
190
+ const img = getImageUrl(wixMediaIdentifier);
191
+ return sdk.getScaleToFitImageURL(
192
+ img.id,
193
+ img.height,
194
+ img.width,
195
+ targetWidth,
196
+ targetHeight,
197
+ options
198
+ );
199
+ }
200
+ function getCroppedImageUrl(wixMediaIdentifier, cropX, cropY, cropWidth, cropHeight, targetWidth, targetHeight, options) {
201
+ const img = getImageUrl(wixMediaIdentifier);
202
+ return sdk.getCropImageURL(
203
+ img.id,
204
+ img.height,
205
+ img.width,
206
+ cropX,
207
+ cropY,
208
+ cropWidth,
209
+ cropHeight,
210
+ targetWidth,
211
+ targetHeight,
212
+ options
213
+ );
214
+ }
215
+ function getImageUrl(val) {
216
+ let id, filenameOrAltText;
217
+ let height, width;
218
+ if (val.startsWith(WIX_IMAGE_URL)) {
219
+ id = val.split(WIX_IMAGE_URL).pop().split("/")[0];
220
+ width = val.split("/w_").pop().split(",")[0];
221
+ height = val.split(",h_").pop().split(",")[0];
222
+ } else {
223
+ const alignedImage = alignIfLegacy(val, WIX_IMAGE);
224
+ const { hash, pathname } = new URL(alignedImage);
225
+ ({ originHeight: height, originWidth: width } = parse(
226
+ hash.replace(URL_HASH_PREFIX, "")
227
+ ));
228
+ [id, filenameOrAltText] = pathname.replace(`${WIX_IMAGE}://v1/`, "").split("/");
229
+ }
230
+ const decodedFilenameOrAltText = decodeText(filenameOrAltText);
231
+ const res = {
232
+ id,
233
+ url: `${WIX_IMAGE_URL}${id}`,
234
+ height: Number(height),
235
+ width: Number(width)
236
+ };
237
+ if (!decodedFilenameOrAltText) {
238
+ return res;
239
+ }
240
+ return {
241
+ ...res,
242
+ altText: decodedFilenameOrAltText,
243
+ filename: decodedFilenameOrAltText
244
+ };
245
+ }
246
+ function decodeText(s) {
247
+ if (!s) {
248
+ return s;
249
+ }
250
+ return decodeURIComponent(s);
251
+ }
252
+ function alignIfLegacy(url, type) {
253
+ const { protocol } = new URL(url);
254
+ return protocol === `${type}:` ? `${WIX_PROTOCOL}${url}` : url;
255
+ }
256
+ var media = {
257
+ getCroppedImageUrl,
258
+ getScaledToFillImageUrl,
259
+ getScaledToFitImageUrl,
260
+ getImageUrl
261
+ };
262
+
263
+ // src/auth/oauth2/OAuthStrategy.ts
264
+ import { redirects } from "@wix/redirects";
265
+
266
+ // src/tokenHelpers.ts
267
+ function getCurrentDate() {
268
+ return Math.floor(Date.now() / 1e3);
269
+ }
270
+ function isTokenExpired(token) {
271
+ const currentDate = getCurrentDate();
272
+ return token.expiresAt < currentDate;
273
+ }
274
+ function createAccessToken(accessToken, expiresIn) {
275
+ const now = getCurrentDate();
276
+ return { value: accessToken, expiresAt: Number(expiresIn) + now };
277
+ }
278
+
279
+ // src/auth/oauth2/OAuthStrategy.ts
280
+ import pkceChallenge from "pkce-challenge";
281
+ import { authentication, recovery, verification } from "@wix/identity";
282
+
283
+ // src/auth/oauth2/types.ts
284
+ var LoginState = /* @__PURE__ */ ((LoginState2) => {
285
+ LoginState2["SUCCESS"] = "SUCCESS";
286
+ LoginState2["INITIAL"] = "INITIAL";
287
+ LoginState2["FAILURE"] = "FAILURE";
288
+ LoginState2["EMAIL_VERIFICATION_REQUIRED"] = "EMAIL_VERIFICATION_REQUIRED";
289
+ LoginState2["OWNER_APPROVAL_REQUIRED"] = "OWNER_APPROVAL_REQUIRED";
290
+ LoginState2["USER_CAPTCHA_REQUIRED"] = "USER_CAPTCHA_REQUIRED";
291
+ LoginState2["SILENT_CAPTCHA_REQUIRED"] = "SILENT_CAPTCHA_REQUIRED";
292
+ return LoginState2;
293
+ })(LoginState || {});
294
+ var TokenRole = /* @__PURE__ */ ((TokenRole2) => {
295
+ TokenRole2["NONE"] = "none";
296
+ TokenRole2["VISITOR"] = "visitor";
297
+ TokenRole2["MEMBER"] = "member";
298
+ return TokenRole2;
299
+ })(TokenRole || {});
300
+
301
+ // src/iframeUtils.ts
302
+ function addListener(eventTarget, name, fn) {
303
+ if (eventTarget.addEventListener) {
304
+ eventTarget.addEventListener(name, fn);
305
+ } else {
306
+ eventTarget.attachEvent("on" + name, fn);
307
+ }
308
+ }
309
+ function removeListener(eventTarget, name, fn) {
310
+ if (eventTarget.removeEventListener) {
311
+ eventTarget.removeEventListener(name, fn);
312
+ } else {
313
+ eventTarget.detachEvent("on" + name, fn);
314
+ }
315
+ }
316
+ function loadFrame(src) {
317
+ const iframe = document.createElement("iframe");
318
+ iframe.style.display = "none";
319
+ iframe.src = src;
320
+ return document.body.appendChild(iframe);
321
+ }
322
+ function addPostMessageListener(state) {
323
+ let responseHandler;
324
+ let timeoutId;
325
+ const msgReceivedOrTimeout = new Promise((resolve, reject) => {
326
+ responseHandler = (e) => {
327
+ if (!e.data || e.data.state !== state) {
328
+ return;
329
+ }
330
+ resolve(e.data);
331
+ };
332
+ addListener(window, "message", responseHandler);
333
+ timeoutId = setTimeout(() => {
334
+ reject(new Error("OAuth flow timed out"));
335
+ }, 12e4);
336
+ });
337
+ return msgReceivedOrTimeout.finally(() => {
338
+ clearTimeout(timeoutId);
339
+ removeListener(window, "message", responseHandler);
340
+ });
341
+ }
342
+
343
+ // src/auth/oauth2/constants.ts
344
+ var MISSING_CAPTCHA = "-19971";
345
+ var INVALID_CAPTCHA = "-19970";
346
+ var EMAIL_EXISTS = "-19995";
347
+ var INVALID_PASSWORD = "-19976";
348
+ var RESET_PASSWORD = "-19973";
349
+
350
+ // src/auth/oauth2/OAuthStrategy.ts
351
+ var moduleWithTokens = { redirects, authentication, recovery, verification };
352
+ var WIX_RECAPTCHA_ID = "6LdoPaUfAAAAAJphvHoUoOob7mx0KDlXyXlgrx5v";
353
+ function OAuthStrategy(config) {
354
+ const _tokens = config.tokens || {
355
+ accessToken: { value: "", expiresAt: 0 },
356
+ refreshToken: { value: "", role: "none" /* NONE */ }
357
+ };
358
+ const setTokens = (tokens) => {
359
+ _tokens.accessToken = tokens.accessToken;
360
+ _tokens.refreshToken = tokens.refreshToken;
361
+ };
362
+ let _state = {
363
+ stateKind: "initial",
364
+ loginState: "INITIAL" /* INITIAL */
365
+ };
366
+ const getAuthHeaders = async () => {
367
+ var _a;
368
+ if (!((_a = _tokens.accessToken) == null ? void 0 : _a.value) || isTokenExpired(_tokens.accessToken)) {
369
+ const tokens = await generateVisitorTokens({
370
+ refreshToken: _tokens.refreshToken
371
+ });
372
+ setTokens(tokens);
373
+ }
374
+ return Promise.resolve({
375
+ headers: { Authorization: _tokens.accessToken.value }
376
+ });
377
+ };
378
+ const wixClientWithTokens = createClient({
379
+ modules: moduleWithTokens,
380
+ auth: { getAuthHeaders }
381
+ });
382
+ const generateVisitorTokens = async (tokens) => {
383
+ var _a, _b, _c;
384
+ if (((_a = tokens == null ? void 0 : tokens.accessToken) == null ? void 0 : _a.value) && ((_b = tokens == null ? void 0 : tokens.refreshToken) == null ? void 0 : _b.value) && !isTokenExpired(tokens.accessToken)) {
385
+ return tokens;
386
+ }
387
+ if ((_c = tokens == null ? void 0 : tokens.refreshToken) == null ? void 0 : _c.value) {
388
+ try {
389
+ const newTokens = await renewToken(tokens.refreshToken);
390
+ return newTokens;
391
+ } catch (e) {
392
+ }
393
+ }
394
+ const tokensResponse = await fetchTokens({
395
+ clientId: config.clientId,
396
+ grantType: "anonymous"
397
+ });
398
+ return {
399
+ accessToken: createAccessToken(
400
+ tokensResponse.access_token,
401
+ tokensResponse.expires_in
402
+ ),
403
+ refreshToken: {
404
+ value: tokensResponse.refresh_token,
405
+ role: "visitor" /* VISITOR */
406
+ }
407
+ };
408
+ };
409
+ const renewToken = async (refreshToken) => {
410
+ const tokensResponse = await fetchTokens({
411
+ refreshToken: refreshToken.value,
412
+ grantType: "refresh_token"
413
+ });
414
+ const accessToken = createAccessToken(
415
+ tokensResponse.access_token,
416
+ tokensResponse.expires_in
417
+ );
418
+ return {
419
+ accessToken,
420
+ refreshToken
421
+ };
422
+ };
423
+ const generatePKCE = () => {
424
+ const pkceState = pkceChallenge();
425
+ return {
426
+ codeChallenge: pkceState.code_challenge,
427
+ codeVerifier: pkceState.code_verifier,
428
+ state: pkceChallenge().code_challenge
429
+ };
430
+ };
431
+ const generateOAuthData = (redirectUri, originalUri) => {
432
+ const state = { redirectUri };
433
+ const pkceState = generatePKCE();
434
+ return {
435
+ ...state,
436
+ originalUri: originalUri != null ? originalUri : "",
437
+ codeChallenge: pkceState.codeChallenge,
438
+ codeVerifier: pkceState.codeVerifier,
439
+ state: pkceChallenge().code_challenge
440
+ };
441
+ };
442
+ const getAuthorizationUrlWithOptions = async (oauthData, responseMode, prompt, sessionToken) => {
443
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
444
+ auth: {
445
+ authRequest: {
446
+ redirectUri: oauthData.redirectUri,
447
+ ...oauthData.redirectUri && {
448
+ redirectUri: oauthData.redirectUri
449
+ },
450
+ clientId: config.clientId,
451
+ codeChallenge: oauthData.codeChallenge,
452
+ codeChallengeMethod: "S256",
453
+ responseMode,
454
+ responseType: "code",
455
+ scope: "offline_access",
456
+ state: oauthData.state,
457
+ ...sessionToken && { sessionToken }
458
+ },
459
+ prompt: redirects.Prompt[prompt]
460
+ }
461
+ });
462
+ return { authUrl: redirectSession.fullUrl };
463
+ };
464
+ const getAuthUrl = async (oauthData, opts = {
465
+ prompt: "login"
466
+ }) => {
467
+ var _a;
468
+ return getAuthorizationUrlWithOptions(
469
+ oauthData,
470
+ "fragment",
471
+ (_a = opts.prompt) != null ? _a : "login"
472
+ );
473
+ };
474
+ const parseFromUrl = () => {
475
+ const params = new URLSearchParams(window.location.hash.substring(1));
476
+ const code = params.get("code");
477
+ const state = params.get("state");
478
+ const error = params.get("error");
479
+ const errorDescription = params.get("error_description");
480
+ return { code, state, ...error && { error, errorDescription } };
481
+ };
482
+ const getMemberTokens = async (code, state, oauthData) => {
483
+ if (!code || !state) {
484
+ throw new Error("Missing code or _state");
485
+ } else if (state !== oauthData.state) {
486
+ throw new Error("Invalid _state");
487
+ }
488
+ try {
489
+ const tokensResponse = await fetchTokens({
490
+ clientId: config.clientId,
491
+ grantType: "authorization_code",
492
+ ...oauthData.redirectUri && { redirectUri: oauthData.redirectUri },
493
+ code,
494
+ codeVerifier: oauthData.codeVerifier
495
+ });
496
+ return {
497
+ accessToken: createAccessToken(
498
+ tokensResponse.access_token,
499
+ tokensResponse.expires_in
500
+ ),
501
+ refreshToken: {
502
+ value: tokensResponse.refresh_token,
503
+ role: "member" /* MEMBER */
504
+ }
505
+ };
506
+ } catch (e) {
507
+ throw new Error("Failed to get member tokens");
508
+ }
509
+ };
510
+ const logout = async (originalUrl) => {
511
+ const { redirectSession } = await wixClientWithTokens.redirects.createRedirectSession({
512
+ logout: { clientId: config.clientId },
513
+ callbacks: {
514
+ postFlowUrl: originalUrl
515
+ }
516
+ });
517
+ _tokens.accessToken = { value: "", expiresAt: 0 };
518
+ _tokens.refreshToken = { value: "", role: "none" /* NONE */ };
519
+ return { logoutUrl: redirectSession.fullUrl };
520
+ };
521
+ const handleState = (response) => {
522
+ if (response.state === authentication.StateType.SUCCESS) {
523
+ return {
524
+ loginState: "SUCCESS" /* SUCCESS */,
525
+ stateKind: "success",
526
+ data: { sessionToken: response.sessionToken }
527
+ };
528
+ } else if (response.state === authentication.StateType.REQUIRE_OWNER_APPROVAL) {
529
+ return {
530
+ loginState: "OWNER_APPROVAL_REQUIRED" /* OWNER_APPROVAL_REQUIRED */,
531
+ stateKind: "ownerApprovalRequired"
532
+ };
533
+ } else if (response.state === authentication.StateType.REQUIRE_EMAIL_VERIFICATION) {
534
+ _state = {
535
+ loginState: "EMAIL_VERIFICATION_REQUIRED" /* EMAIL_VERIFICATION_REQUIRED */,
536
+ stateKind: "emailVerificationRequired",
537
+ data: { stateToken: response.stateToken }
538
+ };
539
+ return _state;
540
+ }
541
+ return {
542
+ stateKind: "failure",
543
+ loginState: "FAILURE" /* FAILURE */,
544
+ error: "Unknown _state"
545
+ };
546
+ };
547
+ const register = async (params) => {
548
+ var _a, _b, _c, _d, _e, _f, _g;
549
+ try {
550
+ const res = await wixClientWithTokens.authentication.registerV2(
551
+ {
552
+ email: params.email
553
+ },
554
+ {
555
+ password: params.password,
556
+ profile: params.profile,
557
+ ...params.captchaTokens && {
558
+ captchaTokens: [
559
+ {
560
+ Recaptcha: (_a = params.captchaTokens) == null ? void 0 : _a.recaptchaToken,
561
+ InvisibleRecaptcha: (_b = params.captchaTokens) == null ? void 0 : _b.invisibleRecaptchaToken
562
+ }
563
+ ]
564
+ }
565
+ }
566
+ );
567
+ return handleState(res);
568
+ } catch (e) {
569
+ const emailValidation = (_d = (_c = e.details.validationError) == null ? void 0 : _c.fieldViolations) == null ? void 0 : _d.find(
570
+ (v) => v.data.type === "EMAIL"
571
+ );
572
+ if (emailValidation) {
573
+ return {
574
+ stateKind: "failure",
575
+ loginState: "FAILURE" /* FAILURE */,
576
+ error: emailValidation.description,
577
+ errorCode: "invalidEmail"
578
+ };
579
+ }
580
+ if (((_e = e.details.applicationError) == null ? void 0 : _e.code) === MISSING_CAPTCHA) {
581
+ return {
582
+ stateKind: "failure",
583
+ loginState: "FAILURE" /* FAILURE */,
584
+ error: e.message,
585
+ errorCode: "missingCaptchaToken"
586
+ };
587
+ }
588
+ if (((_f = e.details.applicationError) == null ? void 0 : _f.code) === EMAIL_EXISTS) {
589
+ return {
590
+ stateKind: "failure",
591
+ loginState: "FAILURE" /* FAILURE */,
592
+ error: e.message,
593
+ errorCode: "emailAlreadyExists"
594
+ };
595
+ }
596
+ if (((_g = e.details.applicationError) == null ? void 0 : _g.code) === INVALID_CAPTCHA) {
597
+ return {
598
+ stateKind: "failure",
599
+ loginState: "FAILURE" /* FAILURE */,
600
+ error: e.message,
601
+ errorCode: "invalidCaptchaToken"
602
+ };
603
+ }
604
+ return {
605
+ stateKind: "failure",
606
+ loginState: "FAILURE" /* FAILURE */,
607
+ error: e.message
608
+ };
609
+ }
610
+ };
611
+ const login = async (params) => {
612
+ var _a, _b, _c, _d;
613
+ try {
614
+ const res = await wixClientWithTokens.authentication.loginV2(
615
+ {
616
+ email: params.email
617
+ },
618
+ {
619
+ password: params.password,
620
+ ...params.captchaTokens && {
621
+ captchaTokens: [
622
+ {
623
+ Recaptcha: (_a = params.captchaTokens) == null ? void 0 : _a.recaptchaToken,
624
+ InvisibleRecaptcha: (_b = params.captchaTokens) == null ? void 0 : _b.invisibleRecaptchaToken
625
+ }
626
+ ]
627
+ }
628
+ }
629
+ );
630
+ return handleState(res);
631
+ } catch (e) {
632
+ return {
633
+ stateKind: "failure",
634
+ loginState: "FAILURE" /* FAILURE */,
635
+ error: e.message,
636
+ errorCode: ((_c = e.details.applicationError) == null ? void 0 : _c.code) === MISSING_CAPTCHA ? "missingCaptchaToken" : ((_d = e.details.applicationError) == null ? void 0 : _d.code) === INVALID_CAPTCHA ? "invalidCaptchaToken" : e.details.applicationError.code === INVALID_PASSWORD ? "invalidPassword" : e.details.applicationError.code === RESET_PASSWORD ? "resetPassword" : "invalidEmail"
637
+ };
638
+ }
639
+ };
640
+ const processVerification = async (nextInputs) => {
641
+ var _a;
642
+ if (_state.stateKind === "emailVerificationRequired") {
643
+ const code = (_a = nextInputs.verificationCode) != null ? _a : nextInputs.code;
644
+ const res = await wixClientWithTokens.verification.verifyDuringAuthentication(
645
+ code,
646
+ { stateToken: _state.data.stateToken }
647
+ );
648
+ return handleState(res);
649
+ }
650
+ return {
651
+ stateKind: "failure",
652
+ loginState: "FAILURE" /* FAILURE */,
653
+ error: "Unknown _state"
654
+ };
655
+ };
656
+ const getMemberTokensForDirectLogin = async (sessionToken) => {
657
+ const oauthPKCE = generatePKCE();
658
+ const { authUrl } = await getAuthorizationUrlWithOptions(
659
+ oauthPKCE,
660
+ "web_message",
661
+ "none",
662
+ sessionToken
663
+ );
664
+ const iframePromise = addPostMessageListener(oauthPKCE.state);
665
+ const iframeEl = loadFrame(authUrl);
666
+ return iframePromise.then((res) => {
667
+ return getMemberTokens(res.code, res.state, oauthPKCE);
668
+ }).finally(() => {
669
+ var _a;
670
+ if (document.body.contains(iframeEl)) {
671
+ (_a = iframeEl.parentElement) == null ? void 0 : _a.removeChild(iframeEl);
672
+ }
673
+ });
674
+ };
675
+ const sendPasswordResetEmail = async (email, redirectUri) => {
676
+ await wixClientWithTokens.recovery.sendRecoveryEmail(email, {
677
+ redirect: { url: redirectUri, clientId: config.clientId }
678
+ });
679
+ };
680
+ const getRecaptchaScriptUrl = () => {
681
+ return `https://www.google.com/recaptcha/enterprise.js?render=${WIX_RECAPTCHA_ID}`;
682
+ };
683
+ const getRecaptchaToken = async () => {
684
+ return new Promise((resolve) => {
685
+ grecaptcha.enterprise.ready(() => {
686
+ grecaptcha.enterprise.execute(WIX_RECAPTCHA_ID, { action: "submit" }).then((token) => {
687
+ resolve(token);
688
+ });
689
+ });
690
+ });
691
+ };
692
+ const loggedIn = () => {
693
+ return _tokens.refreshToken.role === "member" /* MEMBER */;
694
+ };
695
+ return {
696
+ generateVisitorTokens,
697
+ renewToken,
698
+ parseFromUrl,
699
+ getAuthUrl,
700
+ getMemberTokens,
701
+ generateOAuthData,
702
+ getAuthHeaders,
703
+ setTokens,
704
+ getTokens: () => _tokens,
705
+ loggedIn,
706
+ logout,
707
+ register,
708
+ proceed: (nextInputs) => {
709
+ const { code, ...restProps } = nextInputs;
710
+ return processVerification({
711
+ verificationCode: code,
712
+ ...restProps
713
+ });
714
+ },
715
+ processVerification,
716
+ login,
717
+ complete: getMemberTokensForDirectLogin,
718
+ getMemberTokensForDirectLogin,
719
+ sendResetPasswordMail: sendPasswordResetEmail,
720
+ sendPasswordResetEmail,
721
+ getRecaptchaScriptUrl,
722
+ getRecaptchaToken
723
+ };
724
+ }
725
+ var fetchTokens = async (payload) => {
726
+ const res = await fetch(`https://${API_URL}/oauth2/token`, {
727
+ method: "POST",
728
+ body: JSON.stringify(payload),
729
+ headers: {
730
+ ...biHeaderGenerator({
731
+ entityFqdn: "wix.identity.oauth.v1.refresh_token",
732
+ methodFqn: "wix.identity.oauth2.v1.Oauth2Ng.Token",
733
+ packageName: "@wix/sdk"
734
+ }),
735
+ "Content-Type": "application/json"
736
+ }
737
+ });
738
+ if (res.status !== 200) {
739
+ throw new Error("something went wrong");
740
+ }
741
+ const json = await res.json();
742
+ return json;
743
+ };
744
+
745
+ // src/auth/ApiKeyAuthStrategy.ts
746
+ function ApiKeyStrategy({
747
+ siteId,
748
+ accountId,
749
+ apiKey
750
+ }) {
751
+ const headers = { Authorization: apiKey };
752
+ if (siteId) {
753
+ headers["wix-site-id"] = siteId;
754
+ }
755
+ if (accountId) {
756
+ headers["wix-account-id"] = accountId;
757
+ }
758
+ return {
759
+ setSiteId(_siteId) {
760
+ headers["wix-site-id"] = _siteId;
761
+ },
762
+ setAccountId(_accountId) {
763
+ headers["wix-account-id"] = _accountId;
764
+ },
765
+ async getAuthHeaders() {
766
+ return {
767
+ headers
768
+ };
769
+ }
770
+ };
771
+ }
772
+
773
+ // src/index.ts
774
+ export * from "@wix/sdk-types";
775
+ export {
776
+ ApiKeyStrategy,
777
+ LoginState,
778
+ OAuthStrategy,
779
+ TokenRole,
780
+ createClient,
781
+ decodeText,
782
+ media
783
+ };