@dynamic-labs-sdk/client 1.6.0 → 1.7.0

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 (90) hide show
  1. package/dist/{InvalidParamError-DyXEKMWn.cjs → InvalidParamError-CTssOe86.cjs} +105 -993
  2. package/dist/InvalidParamError-CTssOe86.cjs.map +1 -0
  3. package/dist/{InvalidParamError-BIptAjbC.native.esm.js → InvalidParamError-Crwntjl7.native.esm.js} +90 -828
  4. package/dist/InvalidParamError-Crwntjl7.native.esm.js.map +1 -0
  5. package/dist/{InvalidParamError-BZ0LHaml.esm.js → InvalidParamError-fQLJaGBW.esm.js} +90 -795
  6. package/dist/InvalidParamError-fQLJaGBW.esm.js.map +1 -0
  7. package/dist/{NotWaasWalletAccountError-CElqwdQO.cjs → NotWaasWalletAccountError-2RaDipZu.cjs} +4 -4
  8. package/dist/NotWaasWalletAccountError-2RaDipZu.cjs.map +1 -0
  9. package/dist/{NotWaasWalletAccountError-nT4jrLbp.esm.js → NotWaasWalletAccountError-BJLGGYmU.native.esm.js} +4 -4
  10. package/dist/NotWaasWalletAccountError-BJLGGYmU.native.esm.js.map +1 -0
  11. package/dist/{NotWaasWalletAccountError-BbOA5rPd.native.esm.js → NotWaasWalletAccountError-DF_S7gqo.esm.js} +4 -4
  12. package/dist/NotWaasWalletAccountError-DF_S7gqo.esm.js.map +1 -0
  13. package/dist/core.cjs +23 -23
  14. package/dist/core.cjs.map +1 -1
  15. package/dist/core.esm.js +5 -5
  16. package/dist/core.native.esm.js +5 -5
  17. package/dist/{getNetworkProviderFromNetworkId-B7DIqT2T.native.esm.js → getNetworkProviderFromNetworkId-BCSmILlH.native.esm.js} +310 -39
  18. package/dist/getNetworkProviderFromNetworkId-BCSmILlH.native.esm.js.map +1 -0
  19. package/dist/{getNetworkProviderFromNetworkId-BkAPIdRC.esm.js → getNetworkProviderFromNetworkId-BWhaD23J.esm.js} +276 -38
  20. package/dist/getNetworkProviderFromNetworkId-BWhaD23J.esm.js.map +1 -0
  21. package/dist/{getNetworkProviderFromNetworkId-DbI5MZhq.cjs → getNetworkProviderFromNetworkId-C1p9Rrg3.cjs} +351 -44
  22. package/dist/getNetworkProviderFromNetworkId-C1p9Rrg3.cjs.map +1 -0
  23. package/dist/{getSignedSessionId-BF6n8gve.cjs → getSignedSessionId-CxxYNC_8.cjs} +3 -3
  24. package/dist/{getSignedSessionId-BF6n8gve.cjs.map → getSignedSessionId-CxxYNC_8.cjs.map} +1 -1
  25. package/dist/{getSignedSessionId-1TV-x__C.native.esm.js → getSignedSessionId-DPOXdh6y.native.esm.js} +3 -3
  26. package/dist/{getSignedSessionId-1TV-x__C.native.esm.js.map → getSignedSessionId-DPOXdh6y.native.esm.js.map} +1 -1
  27. package/dist/{getSignedSessionId-y3YtxFHZ.esm.js → getSignedSessionId-c7dS4PQ9.esm.js} +3 -3
  28. package/dist/{getSignedSessionId-y3YtxFHZ.esm.js.map → getSignedSessionId-c7dS4PQ9.esm.js.map} +1 -1
  29. package/dist/getVerifiedCredentialForWalletAccount-Cahp763h.esm.js +701 -0
  30. package/dist/getVerifiedCredentialForWalletAccount-Cahp763h.esm.js.map +1 -0
  31. package/dist/getVerifiedCredentialForWalletAccount-Di8dM5Wx.cjs +887 -0
  32. package/dist/getVerifiedCredentialForWalletAccount-Di8dM5Wx.cjs.map +1 -0
  33. package/dist/getVerifiedCredentialForWalletAccount-DuNbORNW.native.esm.js +701 -0
  34. package/dist/getVerifiedCredentialForWalletAccount-DuNbORNW.native.esm.js.map +1 -0
  35. package/dist/index.cjs +76 -76
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.esm.js +14 -14
  38. package/dist/index.esm.js.map +1 -1
  39. package/dist/index.native.esm.js +14 -14
  40. package/dist/index.native.esm.js.map +1 -1
  41. package/dist/{isMfaRequiredForAction-Dy4-S3mr.esm.js → isMfaRequiredForAction-BjRvPrU6.esm.js} +2 -2
  42. package/dist/{isMfaRequiredForAction-Dy4-S3mr.esm.js.map → isMfaRequiredForAction-BjRvPrU6.esm.js.map} +1 -1
  43. package/dist/{isMfaRequiredForAction-B2vKX31S.native.esm.js → isMfaRequiredForAction-D8G5PBAd.native.esm.js} +2 -2
  44. package/dist/{isMfaRequiredForAction-B2vKX31S.native.esm.js.map → isMfaRequiredForAction-D8G5PBAd.native.esm.js.map} +1 -1
  45. package/dist/{isMfaRequiredForAction-K2Jh-3-j.cjs → isMfaRequiredForAction-hlhj0qAC.cjs} +2 -2
  46. package/dist/{isMfaRequiredForAction-K2Jh-3-j.cjs.map → isMfaRequiredForAction-hlhj0qAC.cjs.map} +1 -1
  47. package/dist/modules/apiClient/apiClient.types.d.ts +0 -12
  48. package/dist/modules/apiClient/apiClient.types.d.ts.map +1 -1
  49. package/dist/modules/apiClient/createApiClient.d.ts.map +1 -1
  50. package/dist/modules/auth/logoutReason.d.ts +1 -1
  51. package/dist/modules/auth/logoutReason.d.ts.map +1 -1
  52. package/dist/modules/auth/logoutWithReason/logoutWithReason.d.ts.map +1 -1
  53. package/dist/modules/deviceRegistration/getRegisteredDevices/getRegisteredDevices.d.ts.map +1 -1
  54. package/dist/modules/user/refreshAuth/refreshAuth.d.ts.map +1 -1
  55. package/dist/modules/waas/backupWaasKeySharesToGoogleDrive/backupWaasKeySharesToGoogleDrive.d.ts +12 -1
  56. package/dist/modules/waas/backupWaasKeySharesToGoogleDrive/backupWaasKeySharesToGoogleDrive.d.ts.map +1 -1
  57. package/dist/modules/waas/createWaasProvider/createWaasProvider.d.ts.map +1 -1
  58. package/dist/modules/waas/waas.types.d.ts +1 -0
  59. package/dist/modules/waas/waas.types.d.ts.map +1 -1
  60. package/dist/tsconfig.lib.tsbuildinfo +1 -1
  61. package/dist/waas.cjs +12 -9
  62. package/dist/waas.cjs.map +1 -1
  63. package/dist/waas.esm.js +6 -4
  64. package/dist/waas.esm.js.map +1 -1
  65. package/dist/waas.native.esm.js +6 -4
  66. package/dist/waas.native.esm.js.map +1 -1
  67. package/dist/waasCore.cjs +6 -4
  68. package/dist/waasCore.cjs.map +1 -1
  69. package/dist/waasCore.esm.js +5 -4
  70. package/dist/waasCore.esm.js.map +1 -1
  71. package/dist/waasCore.native.esm.js +5 -4
  72. package/dist/waasCore.native.esm.js.map +1 -1
  73. package/package.json +4 -2
  74. package/dist/InvalidParamError-BIptAjbC.native.esm.js.map +0 -1
  75. package/dist/InvalidParamError-BZ0LHaml.esm.js.map +0 -1
  76. package/dist/InvalidParamError-DyXEKMWn.cjs.map +0 -1
  77. package/dist/NotWaasWalletAccountError-BbOA5rPd.native.esm.js.map +0 -1
  78. package/dist/NotWaasWalletAccountError-CElqwdQO.cjs.map +0 -1
  79. package/dist/NotWaasWalletAccountError-nT4jrLbp.esm.js.map +0 -1
  80. package/dist/getNetworkProviderFromNetworkId-B7DIqT2T.native.esm.js.map +0 -1
  81. package/dist/getNetworkProviderFromNetworkId-BkAPIdRC.esm.js.map +0 -1
  82. package/dist/getNetworkProviderFromNetworkId-DbI5MZhq.cjs.map +0 -1
  83. package/dist/getVerifiedCredentialForWalletAccount-BfJ29erz.cjs +0 -346
  84. package/dist/getVerifiedCredentialForWalletAccount-BfJ29erz.cjs.map +0 -1
  85. package/dist/getVerifiedCredentialForWalletAccount-CLyC2nOl.native.esm.js +0 -269
  86. package/dist/getVerifiedCredentialForWalletAccount-CLyC2nOl.native.esm.js.map +0 -1
  87. package/dist/getVerifiedCredentialForWalletAccount-etV50QRH.esm.js +0 -269
  88. package/dist/getVerifiedCredentialForWalletAccount-etV50QRH.esm.js.map +0 -1
  89. package/dist/modules/apiClient/utils/sessionExpiryLogoutMiddleware/createSessionExpiryLogoutMiddleware.d.ts +0 -27
  90. package/dist/modules/apiClient/utils/sessionExpiryLogoutMiddleware/createSessionExpiryLogoutMiddleware.d.ts.map +0 -1
@@ -1,9 +1,8 @@
1
- import { AuthStorageEnum, Configuration, JwtVerifiedCredentialFormatEnum, SDKApi, WalletProviderEnum, isDeviceNonceSignatureRequiredForUrl } from "@dynamic-labs/sdk-api-core";
2
- import * as z from "zod/mini";
1
+ import { AuthStorageEnum, Configuration, SDKApi, isDeviceNonceSignatureRequiredForUrl } from "@dynamic-labs/sdk-api-core";
3
2
 
4
3
  //#region package.json
5
4
  var name = "@dynamic-labs-sdk/client";
6
- var version = "1.6.0";
5
+ var version = "1.7.0";
7
6
  var dependencies = {
8
7
  "@dynamic-labs-sdk/assert-package-version": "workspace:*",
9
8
  "@dynamic-labs-wallet/browser-wallet-client": "1.0.7",
@@ -914,186 +913,109 @@ const createDeviceSignatureHeadersMiddleware = (client) => {
914
913
  };
915
914
 
916
915
  //#endregion
917
- //#region src/utils/setCookie/setCookie.ts
918
- /**
919
- * Sefelly sets the cookie in the browser.
920
- * @not-instrumented
921
- */
922
- const setCookie = (cookie) => {
923
- document.cookie = cookie;
924
- };
925
-
926
- //#endregion
927
- //#region src/modules/clientEvents/clientEvents.ts
928
- /**
929
- * Adds an event listener for Dynamic client events.
930
- *
931
- * This function allows you to listen for various events emitted by the Dynamic client,
932
- * such as authentication state changes, wallet connections, and more.
933
- *
934
- * @param params.event - The event name to listen for.
935
- * @param params.listener - The callback function to execute when the event is fired.
936
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
937
- * @returns A function that can be called to remove the listener.
938
- * @not-instrumented
939
- */
940
- const onEvent = ({ event, listener }, client = getDefaultClient()) => {
941
- const { eventEmitter } = getCore(client);
942
- eventEmitter.on(event, listener);
943
- return () => {
944
- eventEmitter.off(event, listener);
945
- };
946
- };
947
- /**
948
- * Removes an event listener from Dynamic client events.
949
- *
950
- * This function unsubscribes a previously registered event listener
951
- * from the specified Dynamic client event.
952
- *
953
- * @param params.event - The event name to remove the listener from.
954
- * @param params.listener - The callback function to remove.
955
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
956
- * @not-instrumented
957
- */
958
- const offEvent = ({ event, listener }, client = getDefaultClient()) => {
959
- const { eventEmitter } = getCore(client);
960
- eventEmitter.off(event, listener);
961
- };
962
- /**
963
- * Adds a one-time event listener for Dynamic client events.
964
- *
965
- * This function listens for an event that will automatically remove itself
966
- * after being triggered once.
967
- *
968
- * @param params.event - The event name to listen for.
969
- * @param params.listener - The callback function to execute when the event is fired.
970
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
971
- * @returns A function that can be called to remove the listener before it fires.
972
- * @not-instrumented
973
- */
974
- const onceEvent = ({ event, listener }, client = getDefaultClient()) => {
975
- const { eventEmitter } = getCore(client);
976
- eventEmitter.once(event, listener);
977
- return () => {
978
- eventEmitter.off(event, listener);
979
- };
980
- };
981
- /**
982
- * Emits a Dynamic client event.
983
- *
984
- * This function triggers an event that will be received by all registered
985
- * listeners for the specified event type.
986
- *
987
- * @param params.event - The event name to emit.
988
- * @param params.args - The arguments to pass to event listeners.
989
- * @param client - The Dynamic client instance.
990
- * @not-instrumented
991
- */
992
- const emitEvent = ({ event, args }, client) => {
993
- const { eventEmitter } = getCore(client);
994
- eventEmitter.emit(event, args);
995
- };
996
-
997
- //#endregion
998
- //#region src/utils/retryOnFail/InvalidRetryOnFailCallError.ts
999
- /**
1000
- * This error is thrown when the `retryOnFail` function is called with an invalid
1001
- * number of retries (i.e. less than 0).
1002
- */
1003
- var InvalidRetryOnFailCallError = class extends BaseError {
1004
- constructor(maxRetries) {
916
+ //#region src/errors/UnauthorizedError.ts
917
+ var UnauthorizedError = class extends BaseError {
918
+ constructor({ cause }) {
1005
919
  super({
1006
- cause: null,
1007
- code: "invalid_retry_on_fail_call_error",
920
+ cause,
921
+ code: "unauthorized_error",
1008
922
  docsUrl: null,
1009
- name: "InvalidRetryOnFailCallError",
1010
- shortMessage: `Invalid retries parameter for retryOnFail call: ${maxRetries}`
923
+ name: "UnauthorizedError",
924
+ shortMessage: "Unauthorized"
1011
925
  });
1012
926
  }
1013
927
  };
1014
928
 
1015
929
  //#endregion
1016
- //#region src/utils/retryOnFail/retryOnFail.ts
930
+ //#region src/modules/apiClient/utils/unauthorizedMiddleware/createUnauthorizedMiddleware.ts
1017
931
  /** @not-instrumented */
1018
- const retryOnFail = async ({ delay = 0, fn, maxRetries }) => {
1019
- for (let retry = 0; retry <= maxRetries; retry++) try {
1020
- return await fn();
1021
- } catch (error) {
1022
- if (retry >= maxRetries) throw error;
1023
- if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
1024
- }
1025
- /**
1026
- * Reaching this point should never happen and this
1027
- * error is thrown to help us debug the issue.
1028
- */
1029
- throw new InvalidRetryOnFailCallError(maxRetries);
1030
- };
1031
-
1032
- //#endregion
1033
- //#region src/errors/InvalidWalletProviderKeyError.ts
1034
- var InvalidWalletProviderKeyError = class extends BaseError {
1035
- constructor(value) {
1036
- super({
1037
- cause: null,
1038
- code: "invalid_wallet_provider_key",
1039
- docsUrl: null,
1040
- name: "InvalidWalletProviderKeyError",
1041
- shortMessage: `Invalid wallet provider key: ${value}. Key must be in the format of <normalizedWalletNameWithChain>:<walletProviderType>[:<suffix>]`
1042
- });
932
+ const createUnauthorizedMiddleware = () => ({ post: async (context) => {
933
+ if (context.response.status === 401) {
934
+ let cause = null;
935
+ try {
936
+ const errorBody = await context.response.clone().json();
937
+ if (errorBody && "error" in errorBody && typeof errorBody.error === "string") cause = new Error(errorBody.error);
938
+ } catch {}
939
+ throw new UnauthorizedError({ cause });
1043
940
  }
1044
- };
941
+ return context.response;
942
+ } });
1045
943
 
1046
944
  //#endregion
1047
- //#region src/modules/wallets/walletProvider/splitWalletProviderKey/splitWalletProviderKey.ts
1048
- /** @not-instrumented */
1049
- const splitWalletProviderKey = (walletProviderKey) => {
1050
- const [normalizedWalletNameWithChain, walletProviderType, suffix, ...rest] = walletProviderKey.split(":");
1051
- if (!normalizedWalletNameWithChain || !Object.values(WalletProviderEnum).includes(walletProviderType) || rest.length > 0) throw new InvalidWalletProviderKeyError(walletProviderKey);
1052
- return {
1053
- normalizedWalletNameWithChain,
1054
- suffix,
1055
- walletProviderType
945
+ //#region src/modules/apiClient/createApiClient.ts
946
+ /**
947
+ * Returns a new instance of the SDK API client.
948
+ *
949
+ * This is not meant for storing, as it is very light we can create it whenever needed.
950
+ * @not-instrumented
951
+ */
952
+ const createApiClient = (options = {}, client) => {
953
+ const core = getCore(client);
954
+ const coreState = core.state.get();
955
+ const settings = {
956
+ basePath: core.apiBaseUrl,
957
+ headers: {
958
+ "Content-Type": "application/json",
959
+ [DYNAMIC_API_VERSION_HEADER]: `API/${DYNAMIC_SDK_API_VERSION}`,
960
+ [DYNAMIC_REQUEST_ID_HEADER]: randomString({ length: 50 }),
961
+ [DYNAMIC_SDK_SESSION_ID_HEADER]: core.sdkSessionId,
962
+ [DYNAMIC_SDK_VERSION_HEADER]: `${CLIENT_SDK_NAME}/${version}`,
963
+ ...core.getApiHeaders(),
964
+ ...options.headers
965
+ }
1056
966
  };
967
+ if (core.metadata?.universalLink) settings.headers["Origin"] = core.metadata.universalLink;
968
+ if (client.token) settings.headers.Authorization = `Bearer ${client.token}`;
969
+ if (client.projectSettings && isCookieEnabled(client)) settings.credentials = "include";
970
+ if (options.includeMfaToken && coreState.mfaToken) settings.headers[MFA_TOKEN_HEADER] = coreState.mfaToken;
971
+ if (options.elevatedAccessTokenScope) {
972
+ const elevatedToken = __getElevatedAccessToken_wrapped({ scope: options.elevatedAccessTokenScope }, client);
973
+ if (elevatedToken) settings.headers[ELEVATED_ACCESS_TOKEN_HEADER] = elevatedToken;
974
+ }
975
+ const sessionPublicKey = getSessionKeys(client)?.publicKey;
976
+ const isSessionPublicKeyHeaderPresent = settings.headers[SESSION_PUBLIC_KEY_HEADER] !== void 0;
977
+ if (sessionPublicKey && !isSessionPublicKeyHeaderPresent) settings.headers[SESSION_PUBLIC_KEY_HEADER] = sessionPublicKey;
978
+ return new SDKApi(new Configuration({
979
+ ...settings,
980
+ fetchApi: core.fetch,
981
+ middleware: [
982
+ createDeviceSignatureHeadersMiddleware(client),
983
+ createConvertToApiErrorMiddleware({ errorMappers: [...options.errorMappers || [], clientErrorMapper] }),
984
+ createUnauthorizedMiddleware()
985
+ ]
986
+ }));
1057
987
  };
1058
988
 
1059
989
  //#endregion
1060
- //#region src/modules/wallets/utils/normalizeAddress/normalizeAddress.ts
1061
- /** @not-instrumented */
1062
- const normalizeAddress = ({ address, chain }) => {
1063
- let normalizedAddress = address;
1064
- if (normalizedAddress?.startsWith("0x")) normalizedAddress = normalizedAddress.slice(2);
1065
- normalizedAddress = ["EVM", "FLOW"].includes(chain) ? normalizedAddress?.toLowerCase() : normalizedAddress;
1066
- return normalizedAddress;
1067
- };
1068
-
1069
- //#endregion
1070
- //#region src/modules/wallets/utils/formatWalletAccountId/formatWalletAccountId.ts
1071
- /** @not-instrumented */
1072
- const formatWalletAccountId = ({ address, chain, walletProviderKey }) => {
1073
- const { normalizedWalletNameWithChain } = splitWalletProviderKey(walletProviderKey);
1074
- return `${normalizedWalletNameWithChain}:${normalizeAddress({
1075
- address,
1076
- chain
1077
- })}`;
990
+ //#region src/utils/getNonce/fetchAndStoreNonces/fetchAndStoreNonces.ts
991
+ /**
992
+ * Fetches a batch of nonces from the API.
993
+ *
994
+ * Prefetching is critical for iOS deep link wallet providers (e.g. Phantom
995
+ * redirect). On iOS, a network request (like fetching a nonce) between a user
996
+ * action and a deeplink call will break the gesture chain, causing iOS to
997
+ * silently ignore the deeplink. By prefetching nonces ahead of time,
998
+ * `getNonce` can return synchronously from cache and the deeplink fires
999
+ * without an interrupting network round-trip.
1000
+ *
1001
+ * New nonces are **appended** to the existing pool so that unconsumed entries
1002
+ * are not discarded by a background refetch.
1003
+ * @not-instrumented
1004
+ */
1005
+ const fetchAndStoreNonces = async (client) => {
1006
+ const core = getCore(client);
1007
+ const { environmentId } = core;
1008
+ const { nonces } = await createApiClient({}, client).getNonces({
1009
+ count: NONCE_POOL_SIZE,
1010
+ environmentId
1011
+ });
1012
+ const existing = core.state.get().prefetchedNonces;
1013
+ core.state.set({
1014
+ prefetchedNonces: [...existing, ...nonces],
1015
+ prefetchedNoncesExpiration: Date.now() + NONCE_POOL_EXPIRATION_TIME
1016
+ });
1078
1017
  };
1079
1018
 
1080
- //#endregion
1081
- //#region src/modules/wallets/utils/convertUnverifiedWalletAccountToWalletAccount/convertUnverifiedWalletAccountToWalletAccount.ts
1082
- /** @not-instrumented */
1083
- const convertUnverifiedWalletAccountToWalletAccount = ({ unverifiedWalletAccount }) => ({
1084
- address: unverifiedWalletAccount.address,
1085
- addressesWithTypes: unverifiedWalletAccount.addressesWithTypes,
1086
- chain: unverifiedWalletAccount.chain,
1087
- id: formatWalletAccountId({
1088
- address: unverifiedWalletAccount.address,
1089
- chain: unverifiedWalletAccount.chain,
1090
- walletProviderKey: unverifiedWalletAccount.walletProviderKey
1091
- }),
1092
- lastSelectedAt: unverifiedWalletAccount.lastSelectedAt,
1093
- verifiedCredentialId: null,
1094
- walletProviderKey: unverifiedWalletAccount.walletProviderKey
1095
- });
1096
-
1097
1019
  //#endregion
1098
1020
  //#region src/modules/wallets/constants.ts
1099
1021
  const CHAINS_INFO_MAP = {
@@ -1197,633 +1119,6 @@ const getChainFromVerifiedCredentialChain = (verifiedCredentialChain) => {
1197
1119
  return chain;
1198
1120
  };
1199
1121
 
1200
- //#endregion
1201
- //#region src/modules/wallets/utils/normalizeWalletNameWithChain/normalizeWalletNameWithChain.ts
1202
- /**
1203
- * Format the raw wallet name and chain to get the value we can use for
1204
- * verified credentials' `walletName` field.
1205
- * @not-instrumented
1206
- */
1207
- const normalizeWalletNameWithChain = ({ displayName, chain }) => {
1208
- const sanitizedWalletName = displayName.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
1209
- const chainLowered = chain.toLocaleLowerCase();
1210
- if (sanitizedWalletName.endsWith(chainLowered)) return sanitizedWalletName;
1211
- return `${sanitizedWalletName}${chainLowered}`;
1212
- };
1213
-
1214
- //#endregion
1215
- //#region src/modules/wallets/utils/formatWalletProviderKey/formatWalletProviderKey.ts
1216
- /**
1217
- * Assembles the wallet provider key from the wallet name, chain, and wallet provider type.
1218
- *
1219
- * The suffix is optional and can be used to add a uniquely identifying string to the key, which
1220
- * might be necessary for some wallet providers (like Wallet Connect).
1221
- *
1222
- * IMPORTANT: Do NOT add a suffix unless absolutely necessary, as it will cause the wallet account
1223
- * to not be able to find its wallet provider when connecting to a new device (it won't be possible
1224
- * to determine the full key just from the Verified Credential data).
1225
- * @not-instrumented
1226
- */
1227
- const formatWalletProviderKey = ({ suffix, chain, displayName, walletProviderType }) => {
1228
- return `${normalizeWalletNameWithChain({
1229
- chain,
1230
- displayName
1231
- })}:${walletProviderType}${suffix ? `:${suffix}` : ""}`;
1232
- };
1233
-
1234
- //#endregion
1235
- //#region src/modules/wallets/walletProvider/walletProviderKeyMap/getWalletProviderKeyFromVerifiedCredential/getWalletProviderKeyFromVerifiedCredential.ts
1236
- /** @not-instrumented */
1237
- const getWalletProviderKeyFromVerifiedCredential = ({ verifiedCredential }, client) => {
1238
- const { walletProviderKeyMap } = getCore(client).state.get();
1239
- const storedWalletProviderKey = walletProviderKeyMap[verifiedCredential.id];
1240
- if (storedWalletProviderKey) return { walletProviderKey: storedWalletProviderKey };
1241
- /**
1242
- * We fallback to comprising the wallet provider key from walletName and walletProvider.
1243
- *
1244
- * Some wallet provider types (like Wallet Connect) also use a special suffix for their wallet provider
1245
- * keys, so this won't be enough for them.
1246
- * Therefore, for those specific wallet providers, the wallet account will remain without a wallet provider
1247
- * and will require reconnection.
1248
- * Read walletProvider.types.ts for more info.
1249
- */
1250
- assertDefined(verifiedCredential.walletName, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletName`);
1251
- assertDefined(verifiedCredential.walletProvider, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing walletProvider`);
1252
- assertDefined(verifiedCredential.chain, `Failed to get wallet provider for verified credential with ID ${verifiedCredential.id}: missing chain`);
1253
- return { walletProviderKey: formatWalletProviderKey({
1254
- chain: getChainFromVerifiedCredentialChain(verifiedCredential.chain),
1255
- displayName: verifiedCredential.walletName,
1256
- walletProviderType: verifiedCredential.walletProvider
1257
- }) };
1258
- };
1259
-
1260
- //#endregion
1261
- //#region src/modules/wallets/utils/convertVerifiedCredentialToWalletAccount/convertVerifiedCredentialToWalletAccount.ts
1262
- /** @not-instrumented */
1263
- const convertVerifiedCredentialToWalletAccount = ({ verifiedCredential }, client) => {
1264
- assertDefined(verifiedCredential.address, "Missing address in verified credential");
1265
- assertDefined(verifiedCredential.chain, "Missing chain in verified credential");
1266
- const chain = getChainFromVerifiedCredentialChain(verifiedCredential.chain);
1267
- const { walletProviderKey } = getWalletProviderKeyFromVerifiedCredential({ verifiedCredential }, client);
1268
- const walletAccountId = formatWalletAccountId({
1269
- address: verifiedCredential.address,
1270
- chain,
1271
- walletProviderKey
1272
- });
1273
- return {
1274
- address: verifiedCredential.address,
1275
- addressesWithTypes: verifiedCredential.walletAdditionalAddresses,
1276
- chain,
1277
- hardwareWalletVendor: verifiedCredential.walletProperties?.hardwareWallet,
1278
- id: walletAccountId,
1279
- lastSelectedAt: verifiedCredential.lastSelectedAt ?? null,
1280
- verifiedCredentialId: verifiedCredential.id,
1281
- walletProviderKey
1282
- };
1283
- };
1284
-
1285
- //#endregion
1286
- //#region src/modules/wallets/getWalletAccounts/getWalletAccountsFromState/getWalletAccountsFromState.ts
1287
- /** @not-instrumented */
1288
- const getWalletAccountsFromState = ({ unverifiedWalletAccounts, user }, client) => {
1289
- const walletAccountsMap = /* @__PURE__ */ new Map();
1290
- /**
1291
- * Handle the unverified wallet accounts before the user verified credentials
1292
- * so the later verified wallet accounts can override the unverified wallet accounts
1293
- */
1294
- unverifiedWalletAccounts.forEach((unverifiedWalletAccount) => {
1295
- const walletAccount = convertUnverifiedWalletAccountToWalletAccount({ unverifiedWalletAccount });
1296
- walletAccountsMap.set(walletAccount.id, walletAccount);
1297
- });
1298
- (user?.verifiedCredentials ?? []).filter((verified) => verified.format === JwtVerifiedCredentialFormatEnum.Blockchain).forEach((verifiedWalletAccount) => {
1299
- const walletAccount = convertVerifiedCredentialToWalletAccount({ verifiedCredential: verifiedWalletAccount }, client);
1300
- walletAccountsMap.set(walletAccount.id, walletAccount);
1301
- });
1302
- return Array.from(walletAccountsMap.values());
1303
- };
1304
-
1305
- //#endregion
1306
- //#region src/modules/wallets/getWalletAccounts/getWalletAccounts.ts
1307
- /**
1308
- * Retrieves all wallet accounts associated with the current session.
1309
- *
1310
- * This function returns both verified and unverified wallet accounts,
1311
- * combining data from user credentials and local unverified accounts.
1312
- * You can differentiate between verified and unverified wallet accounts by
1313
- * checking the `verifiedCredentialId` property.
1314
- *
1315
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
1316
- * @returns An array of wallet accounts associated with the session.
1317
- * @not-instrumented
1318
- */
1319
- const getWalletAccounts = (client = getDefaultClient()) => {
1320
- const { unverifiedWalletAccounts, user } = getCore(client).state.get();
1321
- return getWalletAccountsFromState({
1322
- unverifiedWalletAccounts,
1323
- user
1324
- }, client);
1325
- };
1326
-
1327
- //#endregion
1328
- //#region src/modules/auth/isSignedIn/isSignedIn.ts
1329
- /**
1330
- * Checks if the user is currently signed in to the Dynamic client.
1331
- *
1332
- * The client is considered to be in a signed in state if a user has
1333
- * authenticated or if the client has at least one wallet connected.
1334
- *
1335
- * @deprecated What counts as "signed in" is your app's business logic, not the
1336
- * SDK's. This helper bakes in one opinion (a user OR any connected wallet),
1337
- * which rarely matches every app and forces a dependency on us for every
1338
- * variation. Compose your own check from the underlying primitives instead —
1339
- * e.g. `Boolean(client.user) || isAnyWalletAccountConnected(client)` — and
1340
- * layer in whatever your app requires (device registration, completed
1341
- * onboarding, satisfied MFA, a required embedded wallet, …). See the
1342
- * "Check if signed in" guide:
1343
- * https://www.dynamic.xyz/docs/javascript/user-session-management
1344
- *
1345
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
1346
- * @returns True if the user is signed in, false otherwise.
1347
- * @not-instrumented
1348
- */
1349
- const isSignedIn = (client = getDefaultClient()) => Boolean(client.user || getWalletAccounts(client).length > 0);
1350
-
1351
- //#endregion
1352
- //#region src/services/storage/createStorageKeySchema/createStorageKeySchema.ts
1353
- /** @not-instrumented */
1354
- const createStorageKeySchema = (params) => {
1355
- return params;
1356
- };
1357
-
1358
- //#endregion
1359
- //#region src/modules/projectSettings/fetchProjectSettings/projectSettingsExpirationScheme.ts
1360
- /**
1361
- * The schema to track the expiration time of the project settings.
1362
- */
1363
- const projectSettingsExpirationStorageKeySchema = createStorageKeySchema({
1364
- key: "projectSettingsExpiration",
1365
- schema: z.number()
1366
- });
1367
-
1368
- //#endregion
1369
- //#region src/modules/projectSettings/fetchProjectSettings/fetchProjectSettings.ts
1370
- /**
1371
- * Expiration time of the project settings in milliseconds.
1372
- */
1373
- const PROJECT_SETTINGS_EXPIRATION_TIME = 1e3 * 60 * 5;
1374
- /**
1375
- * Fetches and updates the project settings from the API.
1376
- *
1377
- * This function retrieves the latest project configuration settings
1378
- * from Dynamic's servers, including authentication options, enabled chains,
1379
- * and security configurations. The settings are cached for performance.
1380
- *
1381
- * @param [client] - The Dynamic client instance. Only required when using multiple Dynamic clients.
1382
- * @returns A promise that resolves to the updated project settings.
1383
- * @not-instrumented
1384
- */
1385
- const fetchProjectSettings = async (client = getDefaultClient()) => {
1386
- const core = getCore(client);
1387
- const currentExpiration = await core.storage.getItem(projectSettingsExpirationStorageKeySchema);
1388
- if (Boolean(client.projectSettings) && !(currentExpiration && currentExpiration < Date.now()) && isSignedIn(client)) return client.projectSettings;
1389
- const apiClient = createApiClient({}, client);
1390
- core.logger.debug("[fetchProjectSettings] Fetching project settings...");
1391
- const doFetch = async () => apiClient.getEnvironmentSettings({
1392
- environmentId: core.environmentId,
1393
- sdkVersion: `${CLIENT_SDK_NAME}/${core.version}`
1394
- }, { credentials: "omit" });
1395
- const projectSettings = await retryOnFail({
1396
- fn: doFetch,
1397
- maxRetries: 2
1398
- });
1399
- core.state.set({ projectSettings: projectSettings ?? null });
1400
- await core.storage.setItem(projectSettingsExpirationStorageKeySchema, Date.now() + PROJECT_SETTINGS_EXPIRATION_TIME);
1401
- return projectSettings;
1402
- };
1403
-
1404
- //#endregion
1405
- //#region src/modules/sessionKeys/generateSessionKeys/generateSessionKeys.ts
1406
- /** @not-instrumented */
1407
- const generateSessionKeys = async (client) => {
1408
- const core = getCore(client);
1409
- await core.keychain.removeKey("session");
1410
- const publicKey = await core.keychain.generateKey("session");
1411
- assertDefined(publicKey, "Public key not found");
1412
- core.state.set({ sessionKeys: publicKey });
1413
- return { publicKey };
1414
- };
1415
-
1416
- //#endregion
1417
- //#region src/errors/NoWalletProviderFoundError.ts
1418
- var NoWalletProviderFoundError = class extends BaseError {
1419
- constructor({ walletProviderKey }) {
1420
- super({
1421
- cause: null,
1422
- code: "no_wallet_provider_found_error",
1423
- docsUrl: null,
1424
- name: "NoWalletProviderFoundError",
1425
- shortMessage: `No wallet provider found with key: ${walletProviderKey}`
1426
- });
1427
- }
1428
- };
1429
-
1430
- //#endregion
1431
- //#region src/services/runtimeServices/createRuntimeServiceAccessKey/createRuntimeServiceAccessKey.ts
1432
- /**
1433
- * Creates a service accessor function that manages service instantiation and caching.
1434
- * The returned function will either retrieve an existing service from the registry or
1435
- * create a new one using the provided builder function.
1436
- *
1437
- * @template - The type of service to be created/accessed
1438
- * @param key - Unique identifier for the service in the registry
1439
- * @param builder - Function that creates the service instance when called with a DynamicClient
1440
- * @not-instrumented
1441
- */
1442
- const createRuntimeServiceAccessKey = (key, builder) => (client) => {
1443
- const { runtimeServices } = getCore(client);
1444
- const currentService = runtimeServices.getByKey(key);
1445
- if (currentService) return currentService;
1446
- const service = builder(client);
1447
- runtimeServices.register(key, service);
1448
- return service;
1449
- };
1450
-
1451
- //#endregion
1452
- //#region src/modules/wallets/walletProviderRegistry/createWalletProviderRegistry/createWalletProviderRegistry.ts
1453
- /**
1454
- * Creates a new wallet provider registry that manages wallet providers with priority-based registration.
1455
- *
1456
- * @returns The wallet provider registry instance
1457
- *
1458
- * @example
1459
- * ```typescript
1460
- * const registry = createWalletProviderRegistry();
1461
- *
1462
- * registry.register({
1463
- * priority: WalletProviderPriority.WALLET_SDK,
1464
- * walletProvider: myWalletProvider
1465
- * });
1466
- *
1467
- * const provider = registry.getByKey('my-wallet-key');
1468
- * const providers = registry.listProviders();
1469
- * ```
1470
- * @not-instrumented
1471
- */
1472
- const createWalletProviderRegistry = (client) => {
1473
- const registry = /* @__PURE__ */ new Map();
1474
- return {
1475
- getByKey: (key) => registry.get(key)?.walletProvider,
1476
- listProviderEntries: () => Array.from(registry.values()),
1477
- listProviders: () => Array.from(registry.values()).map((v) => v.walletProvider),
1478
- register: (args) => {
1479
- const existingEntry = registry.get(args.walletProvider.key);
1480
- if (existingEntry) {
1481
- if (existingEntry.priority < args.priority) {
1482
- registry.set(args.walletProvider.key, args);
1483
- emitEvent({
1484
- args: { walletProviderKey: args.walletProvider.key },
1485
- event: "walletProviderChanged"
1486
- }, client);
1487
- }
1488
- } else {
1489
- registry.set(args.walletProvider.key, args);
1490
- emitEvent({
1491
- args: { walletProvider: args.walletProvider },
1492
- event: "walletProviderRegistered"
1493
- }, client);
1494
- emitEvent({
1495
- args: { walletProviderKey: args.walletProvider.key },
1496
- event: "walletProviderChanged"
1497
- }, client);
1498
- }
1499
- },
1500
- unregister: (key) => {
1501
- registry.delete(key);
1502
- emitEvent({
1503
- args: { walletProviderKey: key },
1504
- event: "walletProviderUnregistered"
1505
- }, client);
1506
- }
1507
- };
1508
- };
1509
-
1510
- //#endregion
1511
- //#region src/modules/wallets/walletProviderRegistry/getWalletProviderRegistry/getWalletProviderRegistry.ts
1512
- /**
1513
- * This function provides access to a shared instance of the wallet provider registry.
1514
- *
1515
- * It ensures that the same registry instance is used throughout the client to maintaining
1516
- * consistency of registered wallet providers across different parts of the codebase.
1517
- *
1518
- * @returns The wallet provider registry instance
1519
- *
1520
- * @example
1521
- * ```typescript
1522
- * // Get the registry instance
1523
- * const registry = getWalletProviderRegistry();
1524
- *
1525
- * // Register a wallet provider
1526
- * registry.register({
1527
- * priority: WalletProviderPriority.WALLET_SDK,
1528
- * walletProvider: myWalletProvider
1529
- * });
1530
- *
1531
- * // Retrieve a specific provider
1532
- * const provider = registry.getByKey('metamaskevm');
1533
- * ```
1534
- */
1535
- const getWalletProviderRegistry = createRuntimeServiceAccessKey("walletProviderRegistry", (client) => createWalletProviderRegistry(client));
1536
-
1537
- //#endregion
1538
- //#region src/modules/wallets/walletProviderRegistry/walletProviderRegistry.types.ts
1539
- let WalletProviderPriority = /* @__PURE__ */ function(WalletProviderPriority$1) {
1540
- /**
1541
- * Highest priority should be used by wallet providers that implement
1542
- * the most reliable wallet integration.
1543
- * example: The SDK provided by the wallet provider.
1544
- */
1545
- WalletProviderPriority$1[WalletProviderPriority$1["WALLET_SDK"] = 100] = "WALLET_SDK";
1546
- /**
1547
- * Medium priority should be used by wallet providers that implement
1548
- * a wallet integration via some reliable standard.
1549
- * example: A wallet provider that uses EIP6963 announcement.
1550
- */
1551
- WalletProviderPriority$1[WalletProviderPriority$1["WALLET_SELF_ANNOUNCEMENT_STANDARD"] = 50] = "WALLET_SELF_ANNOUNCEMENT_STANDARD";
1552
- /**
1553
- * Low priority should be used by wallet providers that implement
1554
- * a wallet integration on a less reliable standard.
1555
- * example: A wallet provider that uses window.ethereum, where the
1556
- * window key can be overridden by other extensions.
1557
- */
1558
- WalletProviderPriority$1[WalletProviderPriority$1["WINDOW_INJECT"] = 20] = "WINDOW_INJECT";
1559
- return WalletProviderPriority$1;
1560
- }({});
1561
-
1562
- //#endregion
1563
- //#region src/modules/wallets/utils/getWalletProviderFromWalletAccount/getWalletProviderFromWalletAccount.ts
1564
- /** @not-instrumented */
1565
- const getWalletProviderFromWalletAccount = ({ walletAccount }, client) => {
1566
- const walletProvider = getWalletProviderRegistry(client).getByKey(walletAccount.walletProviderKey);
1567
- if (!walletProvider) throw new NoWalletProviderFoundError({ walletProviderKey: walletAccount.walletProviderKey });
1568
- return walletProvider;
1569
- };
1570
-
1571
- //#endregion
1572
- //#region src/modules/wallets/utils/getAvailableWalletProvidersFromWalletAccounts/getAvailableWalletProvidersFromWalletAccounts.ts
1573
- /** @not-instrumented */
1574
- const getAvailableWalletProvidersFromWalletAccounts = (client) => {
1575
- const core = getCore(client);
1576
- const walletProvidersMap = /* @__PURE__ */ new Map();
1577
- getWalletAccounts(client).forEach((walletAccount) => {
1578
- if (walletProvidersMap.has(walletAccount.walletProviderKey)) return;
1579
- try {
1580
- const walletProvider = getWalletProviderFromWalletAccount({ walletAccount }, client);
1581
- walletProvidersMap.set(walletAccount.walletProviderKey, walletProvider);
1582
- } catch (error) {
1583
- core.logger.debug("Wallet provider not found for wallet account", {
1584
- error,
1585
- walletAccount: walletAccount.address
1586
- });
1587
- }
1588
- });
1589
- return Array.from(walletProvidersMap.values());
1590
- };
1591
-
1592
- //#endregion
1593
- //#region src/modules/wallets/destroyWalletProviders/destroyWalletProviders.ts
1594
- /**
1595
- * Tear down every wallet provider on the client.
1596
- *
1597
- * Each provider's `destroy` is responsible for its own local + remote
1598
- * cleanup. We swallow errors so a failing destroy on one provider does not
1599
- * block teardown of the others (e.g. during logout).
1600
- *
1601
- * @not-instrumented
1602
- */
1603
- const destroyWalletProviders = async ({ reason }, client) => {
1604
- const core = getCore(client);
1605
- const walletProviders = getAvailableWalletProvidersFromWalletAccounts(client);
1606
- await Promise.all(walletProviders.map(async (walletProvider) => {
1607
- if (!walletProvider.destroy) return;
1608
- try {
1609
- await walletProvider.destroy({ reason });
1610
- } catch (err) {
1611
- core.logger.error(`Error destroying wallet provider ${walletProvider.key}`, err);
1612
- }
1613
- }));
1614
- };
1615
-
1616
- //#endregion
1617
- //#region src/modules/auth/consts.ts
1618
- const DYNAMIC_AUTH_COOKIE_NAME = "DYNAMIC_JWT_TOKEN";
1619
-
1620
- //#endregion
1621
- //#region src/modules/auth/logoutWithReason/logoutWithReason.ts
1622
- /**
1623
- * Logs the user out with an explicit reason.
1624
- *
1625
- * Revokes the session, clears auth state, terminates wallet providers, and
1626
- * emits the `logout` client event with the given reason. The reason is also
1627
- * captured as an argument on the function-instrumentation event, which is
1628
- * how Datadog distinguishes between different logout causes.
1629
- *
1630
- * Use this instead of the public `logout` when triggering a logout from
1631
- * internal or extension code — the caller owns the reason string, so the
1632
- * telemetry correctly attributes *why* the logout happened.
1633
- *
1634
- * @param params - The logout params.
1635
- * @param params.reason - Why the logout is being triggered. Extension authors
1636
- * needing a reason outside the SDK catalog can cast with `as LogoutReason`.
1637
- * @param client - The Dynamic client instance.
1638
- * @instrumented
1639
- */
1640
- const logoutWithReason = async ({ reason }, client) => {
1641
- const core = getCore(client);
1642
- core.logger.debug("[logoutWithReason] Logging out...", { reason });
1643
- await destroyWalletProviders({ reason }, client);
1644
- if (client.user !== null) {
1645
- const apiClient = createApiClient({ skipSessionExpiryLogout: true }, client);
1646
- try {
1647
- await apiClient.revokeSession({ environmentId: core.environmentId });
1648
- } catch (error) {
1649
- core.logger.error("Failed to revoke session", error);
1650
- }
1651
- /**
1652
- * This deletes the auth cookie if it exists.
1653
- * If the cookie doesn't exist, this sets a new cookie that expires immediately.
1654
- */
1655
- if (isCookieEnabled(client)) setCookie(`${DYNAMIC_AUTH_COOKIE_NAME}=; Max-Age=-99999999; path=/; SameSite=Lax`);
1656
- }
1657
- await core.keychain.removeKey("session");
1658
- core.state.set({
1659
- captchaToken: null,
1660
- elevatedAccessTokens: [],
1661
- legacyToken: null,
1662
- mfaToken: null,
1663
- sessionExpiresAt: null,
1664
- sessionKeys: null,
1665
- token: null,
1666
- unverifiedWalletAccounts: [],
1667
- user: null
1668
- });
1669
- emitEvent({
1670
- args: { reason },
1671
- event: "logout"
1672
- }, client);
1673
- fetchProjectSettings(client);
1674
- generateSessionKeys(client);
1675
- };
1676
- const __logoutWithReason_impl = logoutWithReason;
1677
- const __logoutWithReason_wrapped = instrumentFunction({
1678
- fn: __logoutWithReason_impl,
1679
- functionName: "logoutWithReason",
1680
- getCore: () => {
1681
- try {
1682
- return getCore(getDefaultClient());
1683
- } catch {
1684
- return;
1685
- }
1686
- }
1687
- });
1688
-
1689
- //#endregion
1690
- //#region src/modules/apiClient/utils/sessionExpiryLogoutMiddleware/createSessionExpiryLogoutMiddleware.ts
1691
- const UNAUTHORIZED_STATUS = 401;
1692
- /**
1693
- * Creates middleware that ends the local session when an *authenticated*
1694
- * request is rejected with a 401.
1695
- *
1696
- * A 401 on a request that carried an authenticated session means the backend
1697
- * rejected our credentials, so the local session is stale and must be cleared.
1698
- * The check is purely local (`client.user`) — we deliberately do not
1699
- * re-validate over the network, because the 401 itself is the rejection signal
1700
- * and re-validating would route back through this same middleware.
1701
- *
1702
- * Requests made without an authenticated session (e.g. pre-auth probes) are
1703
- * ignored — there is no session to invalidate. Endpoints that legitimately
1704
- * return 401 for non-session reasons opt out of this behavior by omitting the
1705
- * middleware (see `skipSessionExpiryLogout` on `createApiClient`).
1706
- *
1707
- * This middleware runs before the error-conversion middleware so it observes
1708
- * every 401 regardless of response body. The logout is fired as a side effect
1709
- * and the response is returned unchanged, so the downstream error middleware
1710
- * still throws the typed error to the caller.
1711
- *
1712
- * @param client - The Dynamic client instance.
1713
- * @not-instrumented
1714
- */
1715
- const createSessionExpiryLogoutMiddleware = (client) => ({ post: async (context) => {
1716
- if (context.response.status === UNAUTHORIZED_STATUS && client.user !== null) __logoutWithReason_wrapped({ reason: "session-revoked" }, client).catch((error) => {
1717
- getCore(client).logger.error("Failed to log out after unauthorized response", error);
1718
- });
1719
- return context.response;
1720
- } });
1721
-
1722
- //#endregion
1723
- //#region src/errors/UnauthorizedError.ts
1724
- var UnauthorizedError = class extends BaseError {
1725
- constructor({ cause }) {
1726
- super({
1727
- cause,
1728
- code: "unauthorized_error",
1729
- docsUrl: null,
1730
- name: "UnauthorizedError",
1731
- shortMessage: "Unauthorized"
1732
- });
1733
- }
1734
- };
1735
-
1736
- //#endregion
1737
- //#region src/modules/apiClient/utils/unauthorizedMiddleware/createUnauthorizedMiddleware.ts
1738
- /** @not-instrumented */
1739
- const createUnauthorizedMiddleware = () => ({ post: async (context) => {
1740
- if (context.response.status === 401) {
1741
- let cause = null;
1742
- try {
1743
- const errorBody = await context.response.clone().json();
1744
- if (errorBody && "error" in errorBody && typeof errorBody.error === "string") cause = new Error(errorBody.error);
1745
- } catch {}
1746
- throw new UnauthorizedError({ cause });
1747
- }
1748
- return context.response;
1749
- } });
1750
-
1751
- //#endregion
1752
- //#region src/modules/apiClient/createApiClient.ts
1753
- /**
1754
- * Returns a new instance of the SDK API client.
1755
- *
1756
- * This is not meant for storing, as it is very light we can create it whenever needed.
1757
- * @not-instrumented
1758
- */
1759
- const createApiClient = (options = {}, client) => {
1760
- const core = getCore(client);
1761
- const coreState = core.state.get();
1762
- const settings = {
1763
- basePath: core.apiBaseUrl,
1764
- headers: {
1765
- "Content-Type": "application/json",
1766
- [DYNAMIC_API_VERSION_HEADER]: `API/${DYNAMIC_SDK_API_VERSION}`,
1767
- [DYNAMIC_REQUEST_ID_HEADER]: randomString({ length: 50 }),
1768
- [DYNAMIC_SDK_SESSION_ID_HEADER]: core.sdkSessionId,
1769
- [DYNAMIC_SDK_VERSION_HEADER]: `${CLIENT_SDK_NAME}/${version}`,
1770
- ...core.getApiHeaders(),
1771
- ...options.headers
1772
- }
1773
- };
1774
- if (core.metadata?.universalLink) settings.headers["Origin"] = core.metadata.universalLink;
1775
- if (client.token) settings.headers.Authorization = `Bearer ${client.token}`;
1776
- if (client.projectSettings && isCookieEnabled(client)) settings.credentials = "include";
1777
- if (options.includeMfaToken && coreState.mfaToken) settings.headers[MFA_TOKEN_HEADER] = coreState.mfaToken;
1778
- if (options.elevatedAccessTokenScope) {
1779
- const elevatedToken = __getElevatedAccessToken_wrapped({ scope: options.elevatedAccessTokenScope }, client);
1780
- if (elevatedToken) settings.headers[ELEVATED_ACCESS_TOKEN_HEADER] = elevatedToken;
1781
- }
1782
- const sessionPublicKey = getSessionKeys(client)?.publicKey;
1783
- const isSessionPublicKeyHeaderPresent = settings.headers[SESSION_PUBLIC_KEY_HEADER] !== void 0;
1784
- if (sessionPublicKey && !isSessionPublicKeyHeaderPresent) settings.headers[SESSION_PUBLIC_KEY_HEADER] = sessionPublicKey;
1785
- return new SDKApi(new Configuration({
1786
- ...settings,
1787
- fetchApi: core.fetch,
1788
- middleware: [
1789
- createDeviceSignatureHeadersMiddleware(client),
1790
- ...options.skipSessionExpiryLogout ? [] : [createSessionExpiryLogoutMiddleware(client)],
1791
- createConvertToApiErrorMiddleware({ errorMappers: [...options.errorMappers || [], clientErrorMapper] }),
1792
- createUnauthorizedMiddleware()
1793
- ]
1794
- }));
1795
- };
1796
-
1797
- //#endregion
1798
- //#region src/utils/getNonce/fetchAndStoreNonces/fetchAndStoreNonces.ts
1799
- /**
1800
- * Fetches a batch of nonces from the API.
1801
- *
1802
- * Prefetching is critical for iOS deep link wallet providers (e.g. Phantom
1803
- * redirect). On iOS, a network request (like fetching a nonce) between a user
1804
- * action and a deeplink call will break the gesture chain, causing iOS to
1805
- * silently ignore the deeplink. By prefetching nonces ahead of time,
1806
- * `getNonce` can return synchronously from cache and the deeplink fires
1807
- * without an interrupting network round-trip.
1808
- *
1809
- * New nonces are **appended** to the existing pool so that unconsumed entries
1810
- * are not discarded by a background refetch.
1811
- * @not-instrumented
1812
- */
1813
- const fetchAndStoreNonces = async (client) => {
1814
- const core = getCore(client);
1815
- const { environmentId } = core;
1816
- const { nonces } = await createApiClient({}, client).getNonces({
1817
- count: NONCE_POOL_SIZE,
1818
- environmentId
1819
- });
1820
- const existing = core.state.get().prefetchedNonces;
1821
- core.state.set({
1822
- prefetchedNonces: [...existing, ...nonces],
1823
- prefetchedNoncesExpiration: Date.now() + NONCE_POOL_EXPIRATION_TIME
1824
- });
1825
- };
1826
-
1827
1122
  //#endregion
1828
1123
  //#region src/constants.ts
1829
1124
  const SDK_API_CORE_VERSION = dependencies["@dynamic-labs/sdk-api-core"];
@@ -1854,5 +1149,5 @@ var InvalidParamError = class extends BaseError {
1854
1149
  };
1855
1150
 
1856
1151
  //#endregion
1857
- export { scrubParameters as $, InvalidWalletProviderKeyError as A, getNonce as B, formatWalletProviderKey as C, formatWalletAccountId as D, CHAINS_INFO_MAP as E, onceEvent as F, InvalidExternalAuthError as G, MfaRateLimitedError as H, setCookie as I, isCookieEnabled as J, APIError as K, createDeviceSignatureHeadersMiddleware as L, emitEvent as M, offEvent as N, normalizeAddress as O, onEvent as P, instrumentFunction as Q, getHeadersForNonceSignedByDeviceSigners as R, getWalletAccountsFromState as S, getChainFromVerifiedCredentialChain as T, MfaInvalidOtpError as U, SandboxMaximumThresholdReachedError as V, LinkCredentialError as W, ValueMustBeDefinedError as X, assertDefined as Y, __getElevatedAccessToken_wrapped as Z, generateSessionKeys as _, DYNAMIC_ICONIC_SPRITE_URL as a, DYNAMIC_SDK_API_VERSION as at, isSignedIn as b, createApiClient as c, setDefaultClient as ct, DYNAMIC_AUTH_COOKIE_NAME as d, getCore as dt, DEFAULT_PII_FIELDS as et, getWalletProviderFromWalletAccount as f, name as ft, NoWalletProviderFoundError as g, createRuntimeServiceAccessKey as h, DYNAMIC_WAAS_METADATA as i, CLIENT_SDK_NAME as it, retryOnFail as j, splitWalletProviderKey as k, UnauthorizedError as l, ClientNotFoundError as lt, getWalletProviderRegistry as m, DEFAULT_WAAS_BASE_API_URL as n, extractSessionId as nt, SDK_API_CORE_VERSION as o, NONCE_POOL_SIZE as ot, WalletProviderPriority as p, version as pt, getSessionKeys as q, DEFAULT_WAAS_BASE_MPC_RELAY_API_URL as r, randomString as rt, fetchAndStoreNonces as s, getDefaultClient as st, InvalidParamError as t, getUserAgent as tt, __logoutWithReason_wrapped as u, BaseError as ut, fetchProjectSettings as v, normalizeWalletNameWithChain as w, getWalletAccounts as x, createStorageKeySchema as y, getDeviceSigner as z };
1858
- //# sourceMappingURL=InvalidParamError-BZ0LHaml.esm.js.map
1152
+ export { getUserAgent as A, getCore as B, isCookieEnabled as C, instrumentFunction as D, __getElevatedAccessToken_wrapped as E, NONCE_POOL_SIZE as F, version as H, getDefaultClient as I, setDefaultClient as L, randomString as M, CLIENT_SDK_NAME as N, scrubParameters as O, DYNAMIC_SDK_API_VERSION as P, ClientNotFoundError as R, getSessionKeys as S, ValueMustBeDefinedError as T, name as V, MfaRateLimitedError as _, DYNAMIC_ICONIC_SPRITE_URL as a, InvalidExternalAuthError as b, CHAINS_INFO_MAP as c, UnauthorizedError as d, createDeviceSignatureHeadersMiddleware as f, SandboxMaximumThresholdReachedError as g, getNonce as h, DYNAMIC_WAAS_METADATA as i, extractSessionId as j, DEFAULT_PII_FIELDS as k, fetchAndStoreNonces as l, getDeviceSigner as m, DEFAULT_WAAS_BASE_API_URL as n, SDK_API_CORE_VERSION as o, getHeadersForNonceSignedByDeviceSigners as p, DEFAULT_WAAS_BASE_MPC_RELAY_API_URL as r, getChainFromVerifiedCredentialChain as s, InvalidParamError as t, createApiClient as u, MfaInvalidOtpError as v, assertDefined as w, APIError as x, LinkCredentialError as y, BaseError as z };
1153
+ //# sourceMappingURL=InvalidParamError-fQLJaGBW.esm.js.map