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