@ozura/elements 1.1.0 → 1.2.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.
@@ -1,144 +1,3 @@
1
- /**
2
- * errors.ts — error types and normalisation for OzElements.
3
- *
4
- * Three normalisation functions:
5
- * - normalizeVaultError — maps raw vault /tokenize errors to user-facing messages (card flows)
6
- * - normalizeBankVaultError — maps raw vault /tokenize errors to user-facing messages (bank/ACH flows)
7
- * - normalizeCardSaleError — maps raw cardSale API errors to user-facing messages
8
- *
9
- * Error keys in normalizeCardSaleError are taken directly from checkout's
10
- * errorMapping.ts so the same error strings produce the same user-facing copy.
11
- */
12
- const OZ_ERROR_CODES = new Set(['network', 'timeout', 'auth', 'validation', 'server', 'config', 'unknown']);
13
- /** Returns true and narrows to OzErrorCode when `value` is a valid member of the union. */
14
- function isOzErrorCode(value) {
15
- return typeof value === 'string' && OZ_ERROR_CODES.has(value);
16
- }
17
- class OzError extends Error {
18
- constructor(message, raw, errorCode) {
19
- super(message);
20
- this.name = 'OzError';
21
- this.raw = raw !== null && raw !== void 0 ? raw : message;
22
- this.errorCode = errorCode !== null && errorCode !== void 0 ? errorCode : 'unknown';
23
- this.retryable = this.errorCode === 'network' || this.errorCode === 'timeout' || this.errorCode === 'server';
24
- }
25
- }
26
- /** Shared patterns that apply to both card and bank vault errors. */
27
- function normalizeCommonVaultError(msg) {
28
- if (msg.includes('api key') || msg.includes('unauthorized') || msg.includes('authentication') || msg.includes('forbidden')) {
29
- return 'Authentication failed. Check your vault API key configuration.';
30
- }
31
- if (msg.includes('network') || msg.includes('failed to fetch') || msg.includes('networkerror')) {
32
- return 'A network error occurred. Please check your connection and try again.';
33
- }
34
- if (msg.includes('timeout') || msg.includes('timed out')) {
35
- return 'The request timed out. Please try again.';
36
- }
37
- if (msg.includes('http 5') || msg.includes('500') || msg.includes('502') || msg.includes('503')) {
38
- return 'A server error occurred. Please try again shortly.';
39
- }
40
- return null;
41
- }
42
- /**
43
- * Maps a raw vault /tokenize error string to a user-facing message for card flows.
44
- * Falls back to the original string if no pattern matches.
45
- */
46
- function normalizeVaultError(raw) {
47
- const msg = raw.toLowerCase();
48
- if (msg.includes('card number') || msg.includes('invalid card') || msg.includes('luhn')) {
49
- return 'The card number is invalid. Please check and try again.';
50
- }
51
- if (msg.includes('expir')) {
52
- return 'The card expiration date is invalid or the card has expired.';
53
- }
54
- if (msg.includes('cvv') || msg.includes('cvc') || msg.includes('security code')) {
55
- return 'The CVV code is invalid. Please check and try again.';
56
- }
57
- if (msg.includes('insufficient') || msg.includes('funds')) {
58
- return 'Your card has insufficient funds. Please use a different card.';
59
- }
60
- if (msg.includes('declined') || msg.includes('do not honor')) {
61
- return 'Your card was declined. Please try a different card or contact your bank.';
62
- }
63
- const common = normalizeCommonVaultError(msg);
64
- if (common)
65
- return common;
66
- return raw;
67
- }
68
- /**
69
- * Maps a raw vault /tokenize error string to a user-facing message for bank (ACH) flows.
70
- * Uses bank-specific pattern matching so card-specific messages are never shown for
71
- * bank errors. Falls back to the original string if no pattern matches.
72
- */
73
- function normalizeBankVaultError(raw) {
74
- const msg = raw.toLowerCase();
75
- if (msg.includes('account number') || msg.includes('account_number') || msg.includes('invalid account')) {
76
- return 'The bank account number is invalid. Please check and try again.';
77
- }
78
- if (msg.includes('routing number') || msg.includes('routing_number') || msg.includes('invalid routing') || /\baba\b/.test(msg)) {
79
- return 'The routing number is invalid. Please check and try again.';
80
- }
81
- const common = normalizeCommonVaultError(msg);
82
- if (common)
83
- return common;
84
- return raw;
85
- }
86
- // ─── cardSale error map (mirrors checkout/src/utils/errorMapping.ts exactly) ─
87
- const CARD_SALE_ERROR_MAP = [
88
- ['Insufficient Funds', 'Your card has insufficient funds. Please use a different payment method.'],
89
- ['Invalid card number', 'The card number you entered is invalid. Please check and try again.'],
90
- ['Card expired', 'Your card has expired. Please use a different card.'],
91
- ['CVV Verification Failed', 'The CVV code you entered is incorrect. Please check and try again.'],
92
- ['Address Verification Failed', 'The billing address does not match your card. Please verify your address.'],
93
- ['Do Not Honor', 'Your card was declined. Please contact your bank or use a different payment method.'],
94
- ['Declined', 'Your card was declined. Please contact your bank or use a different payment method.'],
95
- ['Surcharge is currently not supported', 'Surcharge fees are not supported at this time.'],
96
- ['Surcharge percent must be between', 'Surcharge fees are not supported at this time.'],
97
- ['Forbidden - API key', 'Authentication failed. Please refresh the page.'],
98
- ['Api Key is invalid', 'Authentication failed. Please refresh the page.'],
99
- ['API key not found', 'Authentication failed. Please refresh the page.'],
100
- ['Access token expired', 'Your session has expired. Please refresh the page.'],
101
- ['Access token is invalid', 'Authentication failed. Please refresh the page.'],
102
- ['Unauthorized', 'Authentication failed. Please refresh the page.'],
103
- ['Too Many Requests', 'Too many requests. Please wait a moment and try again.'],
104
- ['Rate limit exceeded', 'System is busy. Please wait a moment and try again.'],
105
- ['No processor integrations found', 'Payment processing is not configured for this merchant. Please contact the merchant for assistance.'],
106
- ['processor integration', 'Payment processing is temporarily unavailable. Please try again later or contact the merchant.'],
107
- ['Invalid zipcode', 'The ZIP code you entered is invalid. Please check and try again.'],
108
- ['failed to save to database', 'Your payment was processed but we encountered an issue. Please contact support.'],
109
- ['CASHBACK UNAVAIL', 'This transaction type is not supported. Please try again or use a different payment method.'],
110
- ];
111
- /**
112
- * Maps a raw Ozura Pay API cardSale error string to a user-facing message.
113
- *
114
- * Uses the exact same error key table as checkout's `getUserFriendlyError()` in
115
- * errorMapping.ts so both surfaces produce identical copy for the same errors.
116
- *
117
- * Falls back to the original string when it's under 100 characters, or to a
118
- * generic message for long/opaque server errors — matching checkout's fallback
119
- * behaviour exactly.
120
- *
121
- * **Trade-off:** Short unrecognised strings (e.g. processor codes like
122
- * `"PROC_TIMEOUT"`) are passed through verbatim. This intentionally mirrors
123
- * checkout so the same raw Pay API errors produce the same user-facing text on
124
- * both surfaces. If the Pay API ever returns internal codes that should never
125
- * reach the UI, the fix belongs in the Pay API error normalisation layer rather
126
- * than here.
127
- */
128
- function normalizeCardSaleError(raw) {
129
- if (!raw)
130
- return 'Payment processing failed. Please try again.';
131
- for (const [key, message] of CARD_SALE_ERROR_MAP) {
132
- if (raw.toLowerCase().includes(key.toLowerCase())) {
133
- return message;
134
- }
135
- }
136
- // Checkout fallback: pass through short errors, genericise long ones
137
- if (raw.length < 100)
138
- return raw;
139
- return 'Payment processing failed. Please try again or contact support.';
140
- }
141
-
142
1
  const THEME_DEFAULT = {
143
2
  base: {
144
3
  color: '#1a1a2e',
@@ -303,6 +162,147 @@ function mergeAppearanceWithElementStyle(appearance, elementStyle) {
303
162
  return mergeStyleConfigs(appearance, elementStyle);
304
163
  }
305
164
 
165
+ /**
166
+ * errors.ts — error types and normalisation for OzElements.
167
+ *
168
+ * Three normalisation functions:
169
+ * - normalizeVaultError — maps raw vault /tokenize errors to user-facing messages (card flows)
170
+ * - normalizeBankVaultError — maps raw vault /tokenize errors to user-facing messages (bank/ACH flows)
171
+ * - normalizeCardSaleError — maps raw cardSale API errors to user-facing messages
172
+ *
173
+ * Error keys in normalizeCardSaleError are taken directly from checkout's
174
+ * errorMapping.ts so the same error strings produce the same user-facing copy.
175
+ */
176
+ const OZ_ERROR_CODES = new Set(['network', 'timeout', 'auth', 'validation', 'server', 'config', 'unknown']);
177
+ /** Returns true and narrows to OzErrorCode when `value` is a valid member of the union. */
178
+ function isOzErrorCode(value) {
179
+ return typeof value === 'string' && OZ_ERROR_CODES.has(value);
180
+ }
181
+ class OzError extends Error {
182
+ constructor(message, raw, errorCode) {
183
+ super(message);
184
+ this.name = 'OzError';
185
+ this.raw = raw !== null && raw !== void 0 ? raw : message;
186
+ this.errorCode = errorCode !== null && errorCode !== void 0 ? errorCode : 'unknown';
187
+ this.retryable = this.errorCode === 'network' || this.errorCode === 'timeout' || this.errorCode === 'server';
188
+ }
189
+ }
190
+ /** Shared patterns that apply to both card and bank vault errors. */
191
+ function normalizeCommonVaultError(msg) {
192
+ if (msg.includes('api key') || msg.includes('unauthorized') || msg.includes('authentication') || msg.includes('forbidden')) {
193
+ return 'Authentication failed. Check your vault API key configuration.';
194
+ }
195
+ if (msg.includes('network') || msg.includes('failed to fetch') || msg.includes('networkerror')) {
196
+ return 'A network error occurred. Please check your connection and try again.';
197
+ }
198
+ if (msg.includes('timeout') || msg.includes('timed out')) {
199
+ return 'The request timed out. Please try again.';
200
+ }
201
+ if (msg.includes('http 5') || msg.includes('500') || msg.includes('502') || msg.includes('503')) {
202
+ return 'A server error occurred. Please try again shortly.';
203
+ }
204
+ return null;
205
+ }
206
+ /**
207
+ * Maps a raw vault /tokenize error string to a user-facing message for card flows.
208
+ * Falls back to the original string if no pattern matches.
209
+ */
210
+ function normalizeVaultError(raw) {
211
+ const msg = raw.toLowerCase();
212
+ if (msg.includes('card number') || msg.includes('invalid card') || msg.includes('luhn')) {
213
+ return 'The card number is invalid. Please check and try again.';
214
+ }
215
+ if (msg.includes('expir')) {
216
+ return 'The card expiration date is invalid or the card has expired.';
217
+ }
218
+ if (msg.includes('cvv') || msg.includes('cvc') || msg.includes('security code')) {
219
+ return 'The CVV code is invalid. Please check and try again.';
220
+ }
221
+ if (msg.includes('insufficient') || msg.includes('funds')) {
222
+ return 'Your card has insufficient funds. Please use a different card.';
223
+ }
224
+ if (msg.includes('declined') || msg.includes('do not honor')) {
225
+ return 'Your card was declined. Please try a different card or contact your bank.';
226
+ }
227
+ const common = normalizeCommonVaultError(msg);
228
+ if (common)
229
+ return common;
230
+ return raw;
231
+ }
232
+ /**
233
+ * Maps a raw vault /tokenize error string to a user-facing message for bank (ACH) flows.
234
+ * Uses bank-specific pattern matching so card-specific messages are never shown for
235
+ * bank errors. Falls back to the original string if no pattern matches.
236
+ */
237
+ function normalizeBankVaultError(raw) {
238
+ const msg = raw.toLowerCase();
239
+ if (msg.includes('account number') || msg.includes('account_number') || msg.includes('invalid account')) {
240
+ return 'The bank account number is invalid. Please check and try again.';
241
+ }
242
+ if (msg.includes('routing number') || msg.includes('routing_number') || msg.includes('invalid routing') || /\baba\b/.test(msg)) {
243
+ return 'The routing number is invalid. Please check and try again.';
244
+ }
245
+ const common = normalizeCommonVaultError(msg);
246
+ if (common)
247
+ return common;
248
+ return raw;
249
+ }
250
+ // ─── cardSale error map (mirrors checkout/src/utils/errorMapping.ts exactly) ─
251
+ const CARD_SALE_ERROR_MAP = [
252
+ ['Insufficient Funds', 'Your card has insufficient funds. Please use a different payment method.'],
253
+ ['Invalid card number', 'The card number you entered is invalid. Please check and try again.'],
254
+ ['Card expired', 'Your card has expired. Please use a different card.'],
255
+ ['CVV Verification Failed', 'The CVV code you entered is incorrect. Please check and try again.'],
256
+ ['Address Verification Failed', 'The billing address does not match your card. Please verify your address.'],
257
+ ['Do Not Honor', 'Your card was declined. Please contact your bank or use a different payment method.'],
258
+ ['Declined', 'Your card was declined. Please contact your bank or use a different payment method.'],
259
+ ['Surcharge is currently not supported', 'Surcharge fees are not supported at this time.'],
260
+ ['Surcharge percent must be between', 'Surcharge fees are not supported at this time.'],
261
+ ['Forbidden - API key', 'Authentication failed. Please refresh the page.'],
262
+ ['Api Key is invalid', 'Authentication failed. Please refresh the page.'],
263
+ ['API key not found', 'Authentication failed. Please refresh the page.'],
264
+ ['Access token expired', 'Your session has expired. Please refresh the page.'],
265
+ ['Access token is invalid', 'Authentication failed. Please refresh the page.'],
266
+ ['Unauthorized', 'Authentication failed. Please refresh the page.'],
267
+ ['Too Many Requests', 'Too many requests. Please wait a moment and try again.'],
268
+ ['Rate limit exceeded', 'System is busy. Please wait a moment and try again.'],
269
+ ['No processor integrations found', 'Payment processing is not configured for this merchant. Please contact the merchant for assistance.'],
270
+ ['processor integration', 'Payment processing is temporarily unavailable. Please try again later or contact the merchant.'],
271
+ ['Invalid zipcode', 'The ZIP code you entered is invalid. Please check and try again.'],
272
+ ['failed to save to database', 'Your payment was processed but we encountered an issue. Please contact support.'],
273
+ ['CASHBACK UNAVAIL', 'This transaction type is not supported. Please try again or use a different payment method.'],
274
+ ];
275
+ /**
276
+ * Maps a raw Ozura Pay API cardSale error string to a user-facing message.
277
+ *
278
+ * Uses the exact same error key table as checkout's `getUserFriendlyError()` in
279
+ * errorMapping.ts so both surfaces produce identical copy for the same errors.
280
+ *
281
+ * Falls back to the original string when it's under 100 characters, or to a
282
+ * generic message for long/opaque server errors — matching checkout's fallback
283
+ * behaviour exactly.
284
+ *
285
+ * **Trade-off:** Short unrecognised strings (e.g. processor codes like
286
+ * `"PROC_TIMEOUT"`) are passed through verbatim. This intentionally mirrors
287
+ * checkout so the same raw Pay API errors produce the same user-facing text on
288
+ * both surfaces. If the Pay API ever returns internal codes that should never
289
+ * reach the UI, the fix belongs in the Pay API error normalisation layer rather
290
+ * than here.
291
+ */
292
+ function normalizeCardSaleError(raw) {
293
+ if (!raw)
294
+ return 'Payment processing failed. Please try again.';
295
+ for (const [key, message] of CARD_SALE_ERROR_MAP) {
296
+ if (raw.toLowerCase().includes(key.toLowerCase())) {
297
+ return message;
298
+ }
299
+ }
300
+ // Checkout fallback: pass through short errors, genericise long ones
301
+ if (raw.length < 100)
302
+ return raw;
303
+ return 'Payment processing failed. Please try again or contact support.';
304
+ }
305
+
306
306
  /**
307
307
  * Generates a RFC 4122 v4 UUID.
308
308
  *
@@ -890,6 +890,85 @@ function validateBilling(billing) {
890
890
  */
891
891
  const PROTOCOL_VERSION = 1;
892
892
 
893
+ /**
894
+ * Creates a `getSessionKey` callback for `OzVault.create()` and `<OzElements>`.
895
+ *
896
+ * This is the recommended way to wire the SDK to your backend session endpoint.
897
+ * If you don't need custom headers or auth logic, pass `sessionUrl` directly to
898
+ * `OzVault.create()` or `<OzElements>` — it calls this helper internally.
899
+ *
900
+ * The callback POSTs `{ sessionId }` to `url` and reads `sessionKey` (or the
901
+ * legacy `waxKey`) from the JSON response, so it is compatible with both the
902
+ * new `createSessionMiddleware` and the old `createMintWaxMiddleware` backends.
903
+ *
904
+ * Each call enforces a **10-second timeout**. On pure network failures
905
+ * (offline, DNS, connection refused) the request is retried **once after 750ms**.
906
+ * HTTP 4xx/5xx errors are never retried — they indicate misconfiguration.
907
+ *
908
+ * @param url - Absolute or relative URL of your session endpoint, e.g. `'/api/oz-session'`.
909
+ *
910
+ * @example
911
+ * // Simplest — just pass sessionUrl, no need to call this directly
912
+ * const vault = await OzVault.create({ pubKey: 'pk_live_...', sessionUrl: '/api/oz-session' });
913
+ *
914
+ * @example
915
+ * // Manual — use when you need custom headers
916
+ * const vault = await OzVault.create({
917
+ * pubKey: 'pk_live_...',
918
+ * getSessionKey: createSessionFetcher('/api/oz-session'),
919
+ * });
920
+ */
921
+ function createSessionFetcher(url) {
922
+ const TIMEOUT_MS = 10000;
923
+ // Each attempt gets its own AbortController so a timeout on attempt 1 does
924
+ // not bleed into the retry.
925
+ const attemptFetch = (sessionId) => {
926
+ const controller = new AbortController();
927
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
928
+ return fetch(url, {
929
+ method: 'POST',
930
+ headers: { 'Content-Type': 'application/json' },
931
+ body: JSON.stringify({ sessionId }),
932
+ signal: controller.signal,
933
+ }).finally(() => clearTimeout(timer));
934
+ };
935
+ return async (sessionId) => {
936
+ let res;
937
+ try {
938
+ res = await attemptFetch(sessionId);
939
+ }
940
+ catch (firstErr) {
941
+ // Timeout/abort — don't retry, we already waited the full duration.
942
+ if (firstErr instanceof Error && (firstErr.name === 'AbortError' || firstErr.name === 'TimeoutError')) {
943
+ throw new OzError(`Session endpoint timed out after ${TIMEOUT_MS / 1000}s (${url})`, undefined, 'timeout');
944
+ }
945
+ // Pure network error — retry once after a short pause.
946
+ await new Promise(resolve => setTimeout(resolve, 750));
947
+ try {
948
+ res = await attemptFetch(sessionId);
949
+ }
950
+ catch (retryErr) {
951
+ const msg = retryErr instanceof Error ? retryErr.message : 'Network error';
952
+ throw new OzError(`Could not reach session endpoint (${url}): ${msg}`, undefined, 'network');
953
+ }
954
+ }
955
+ const data = await res.json().catch(() => ({}));
956
+ if (!res.ok) {
957
+ throw new OzError(typeof data.error === 'string' && data.error
958
+ ? data.error
959
+ : `Session endpoint returned HTTP ${res.status}`, undefined, res.status >= 500 ? 'server' : res.status === 401 || res.status === 403 ? 'auth' : 'validation');
960
+ }
961
+ // Accept both new `sessionKey` and legacy `waxKey` for backward compatibility
962
+ // with backends that haven't migrated to createSessionMiddleware yet.
963
+ const key = (typeof data.sessionKey === 'string' ? data.sessionKey : '') ||
964
+ (typeof data.waxKey === 'string' ? data.waxKey : '');
965
+ if (!key.trim()) {
966
+ throw new OzError('Session endpoint response is missing sessionKey. Check your /api/oz-session implementation.', undefined, 'validation');
967
+ }
968
+ return key;
969
+ };
970
+ }
971
+
893
972
  function isCardMetadata(v) {
894
973
  return !!v && typeof v === 'object' && typeof v.last4 === 'string';
895
974
  }
@@ -929,7 +1008,7 @@ class OzVault {
929
1008
  * @internal
930
1009
  */
931
1010
  constructor(options, waxKey, tokenizationSessionId) {
932
- var _a, _b, _c, _d;
1011
+ var _a, _b, _c, _d, _e;
933
1012
  this.elements = new Map();
934
1013
  this.elementsByType = new Map();
935
1014
  this.bankElementsByType = new Map();
@@ -963,7 +1042,12 @@ class OzVault {
963
1042
  this.fonts = (_a = options.fonts) !== null && _a !== void 0 ? _a : [];
964
1043
  this.resolvedAppearance = resolveAppearance(options.appearance);
965
1044
  this.vaultId = `vault-${uuid()}`;
966
- this._maxTokenizeCalls = (_b = options.maxTokenizeCalls) !== null && _b !== void 0 ? _b : 3;
1045
+ // sessionLimit takes precedence over legacy maxTokenizeCalls.
1046
+ // null means unlimited — use Infinity so the ">=" check never triggers.
1047
+ const rawLimit = options.sessionLimit !== undefined
1048
+ ? options.sessionLimit
1049
+ : ((_b = options.maxTokenizeCalls) !== null && _b !== void 0 ? _b : 3);
1050
+ this._maxTokenizeCalls = rawLimit === null ? Infinity : rawLimit;
967
1051
  this._debug = (_c = options.debug) !== null && _c !== void 0 ? _c : false;
968
1052
  this.boundHandleMessage = this.handleMessage.bind(this);
969
1053
  window.addEventListener('message', this.boundHandleMessage);
@@ -979,7 +1063,8 @@ class OzVault {
979
1063
  }
980
1064
  }, timeout);
981
1065
  }
982
- this._onWaxRefresh = options.onWaxRefresh;
1066
+ // onSessionRefresh takes precedence over legacy onWaxRefresh
1067
+ this._onWaxRefresh = (_e = options.onSessionRefresh) !== null && _e !== void 0 ? _e : options.onWaxRefresh;
983
1068
  this._onReady = options.onReady;
984
1069
  this.log('vault created', { vaultId: this.vaultId, frameBaseUrl: this.frameBaseUrl, maxTokenizeCalls: this._maxTokenizeCalls });
985
1070
  }
@@ -987,51 +1072,63 @@ class OzVault {
987
1072
  * Creates and returns a ready `OzVault` instance.
988
1073
  *
989
1074
  * Internally this:
990
- * 1. Generates a `tokenizationSessionId` (UUID).
1075
+ * 1. Generates a session UUID.
991
1076
  * 2. Starts loading the hidden tokenizer iframe immediately.
992
- * 3. Calls `options.fetchWaxKey(tokenizationSessionId)` concurrently — your
993
- * backend mints a session-bound wax key from the vault and returns it.
994
- * 4. Resolves with the vault instance once the wax key is stored. The iframe
1077
+ * 3. Fetches a session key from your backend concurrently — either via
1078
+ * `sessionUrl` (simplest), `getSessionKey` (custom headers/auth), or the
1079
+ * deprecated `fetchWaxKey` callback.
1080
+ * 4. Resolves with the vault instance once the session key is stored. The iframe
995
1081
  * has been loading the whole time, so `isReady` may already be true or
996
1082
  * will fire shortly after.
997
1083
  *
998
1084
  * The returned vault is ready to create elements immediately. `createToken()`
999
1085
  * additionally requires `vault.isReady` (tokenizer iframe loaded).
1000
1086
  *
1001
- * @throws {OzError} if `fetchWaxKey` throws, returns a non-string value, or returns an empty/whitespace-only string.
1087
+ * @throws {OzError} if the session fetch fails, times out, or returns an empty string.
1002
1088
  */
1003
1089
  static async create(options, signal) {
1004
1090
  if (!options.pubKey || !options.pubKey.trim()) {
1005
1091
  throw new OzError('pubKey is required in options. Obtain your public key from the Ozura admin.');
1006
1092
  }
1007
- if (typeof options.fetchWaxKey !== 'function') {
1008
- throw new OzError('fetchWaxKey must be a function. See OzVault.create() docs for the expected signature.');
1093
+ // Normalize the session callback. Priority: sessionUrl > getSessionKey > fetchWaxKey (deprecated).
1094
+ // This allows merchants to use the clean new API without touching legacy code.
1095
+ let resolvedFetchKey;
1096
+ if (options.sessionUrl) {
1097
+ resolvedFetchKey = createSessionFetcher(options.sessionUrl);
1098
+ }
1099
+ else if (typeof options.getSessionKey === 'function') {
1100
+ resolvedFetchKey = options.getSessionKey;
1101
+ }
1102
+ else if (typeof options.fetchWaxKey === 'function') {
1103
+ resolvedFetchKey = options.fetchWaxKey;
1104
+ }
1105
+ else {
1106
+ throw new OzError('A session URL or callback is required. Pass sessionUrl, getSessionKey, or fetchWaxKey to OzVault.create().');
1009
1107
  }
1010
1108
  const tokenizationSessionId = uuid();
1011
1109
  // Construct the vault immediately — this mounts the tokenizer iframe so it
1012
- // starts loading while fetchWaxKey is in flight. The waxKey field starts
1013
- // empty and is set below before create() returns.
1110
+ // starts loading while the session fetch is in flight.
1014
1111
  const vault = new OzVault(options, '', tokenizationSessionId);
1015
1112
  // If the caller provides an AbortSignal (e.g. React useEffect cleanup),
1016
1113
  // destroy the vault immediately on abort so the tokenizer iframe and message
1017
- // listener are removed synchronously rather than waiting for fetchWaxKey to
1018
- // settle. This eliminates the brief double-iframe window in React StrictMode.
1114
+ // listener are removed synchronously rather than waiting for the session fetch
1115
+ // to settle. This eliminates the brief double-iframe window in React StrictMode.
1019
1116
  const onAbort = () => vault.destroy();
1020
1117
  signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onAbort, { once: true });
1021
1118
  let waxKey;
1022
1119
  try {
1023
- waxKey = await options.fetchWaxKey(tokenizationSessionId);
1120
+ waxKey = await resolvedFetchKey(tokenizationSessionId);
1024
1121
  }
1025
1122
  catch (err) {
1026
1123
  signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
1027
1124
  vault.destroy();
1028
1125
  if (signal === null || signal === void 0 ? void 0 : signal.aborted)
1029
1126
  throw new OzError('OzVault.create() was cancelled.');
1030
- // Preserve errorCode/retryable from OzError (e.g. timeout/network from createFetchWaxKey)
1127
+ // Preserve errorCode/retryable from OzError (e.g. timeout/network from createSessionFetcher)
1031
1128
  // so callers can distinguish transient failures from config errors.
1032
1129
  const originalCode = err instanceof OzError ? err.errorCode : undefined;
1033
1130
  const msg = err instanceof Error ? err.message : 'Unknown error';
1034
- throw new OzError(`fetchWaxKey threw an error: ${msg}`, undefined, originalCode);
1131
+ throw new OzError(`Session fetch threw an error: ${msg}`, undefined, originalCode);
1035
1132
  }
1036
1133
  signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onAbort);
1037
1134
  if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
@@ -1040,11 +1137,11 @@ class OzVault {
1040
1137
  }
1041
1138
  if (typeof waxKey !== 'string' || !waxKey.trim()) {
1042
1139
  vault.destroy();
1043
- throw new OzError('fetchWaxKey must return a non-empty wax key string. Check your mint endpoint.');
1140
+ throw new OzError('Session fetch returned an empty key. Check your session endpoint response — it must return { sessionKey: "..." }.');
1044
1141
  }
1045
1142
  // Static methods can access private fields of instances of the same class.
1046
1143
  vault.waxKey = waxKey;
1047
- vault._storedFetchWaxKey = options.fetchWaxKey;
1144
+ vault._storedFetchWaxKey = resolvedFetchKey;
1048
1145
  // If the tokenizer iframe fired OZ_FRAME_READY before fetchWaxKey resolved,
1049
1146
  // the OZ_INIT sent at that point had an empty waxKey. Send a follow-up now
1050
1147
  // so the tokenizer has the key stored before any createToken() call.
@@ -1710,9 +1807,9 @@ class OzVault {
1710
1807
  // key without waiting for a vault rejection.
1711
1808
  this._tokenizeSuccessCount++;
1712
1809
  if (this._tokenizeSuccessCount >= this._maxTokenizeCalls) {
1713
- this.log('proactive wax key refresh triggered', { tokenizeSuccessCount: this._tokenizeSuccessCount, maxTokenizeCalls: this._maxTokenizeCalls });
1810
+ this.log('proactive session key refresh triggered', { tokenizeSuccessCount: this._tokenizeSuccessCount, maxTokenizeCalls: this._maxTokenizeCalls });
1714
1811
  this.refreshWaxKey().catch((err) => {
1715
- console.warn('[OzVault] Post-budget wax key refresh failed:', err instanceof Error ? err.message : err);
1812
+ console.warn('[OzVault] Post-budget session key refresh failed:', err instanceof Error ? err.message : err);
1716
1813
  });
1717
1814
  }
1718
1815
  }
@@ -1870,9 +1967,9 @@ class OzVault {
1870
1967
  // Same proactive refresh logic as card tokenization.
1871
1968
  this._tokenizeSuccessCount++;
1872
1969
  if (this._tokenizeSuccessCount >= this._maxTokenizeCalls) {
1873
- this.log('proactive wax key refresh triggered', { tokenizeSuccessCount: this._tokenizeSuccessCount, maxTokenizeCalls: this._maxTokenizeCalls });
1970
+ this.log('proactive session key refresh triggered', { tokenizeSuccessCount: this._tokenizeSuccessCount, maxTokenizeCalls: this._maxTokenizeCalls });
1874
1971
  this.refreshWaxKey().catch((err) => {
1875
- console.warn('[OzVault] Post-budget wax key refresh failed:', err instanceof Error ? err.message : err);
1972
+ console.warn('[OzVault] Post-budget session key refresh failed:', err instanceof Error ? err.message : err);
1876
1973
  });
1877
1974
  }
1878
1975
  }
@@ -1958,83 +2055,5 @@ class OzVault {
1958
2055
  }
1959
2056
  }
1960
2057
 
1961
- /**
1962
- * Creates a ready-to-use `fetchWaxKey` callback for `OzVault.create()` and `<OzElements>`.
1963
- *
1964
- * Calls your backend mint endpoint with `{ sessionId }` and returns the wax key string.
1965
- * Throws on non-OK responses or a missing `waxKey` field so the vault can surface the
1966
- * error through its normal error path.
1967
- *
1968
- * Each call enforces a 10-second per-attempt timeout. On a pure network-level
1969
- * failure (connection refused, DNS failure, etc.) the call is retried once after
1970
- * 750ms before throwing. HTTP errors (4xx/5xx) are never retried — they indicate
1971
- * an endpoint misconfiguration or an invalid key, not a transient failure.
1972
- *
1973
- * The mint endpoint is typically the one-line `createMintWaxHandler` / `createMintWaxMiddleware`
1974
- * from `@ozura/elements/server`.
1975
- *
1976
- * @param mintUrl - Absolute or relative URL of your wax-key mint endpoint, e.g. `'/api/mint-wax'`.
1977
- *
1978
- * @example
1979
- * // Vanilla JS
1980
- * const vault = await OzVault.create({
1981
- * pubKey: 'pk_live_...',
1982
- * fetchWaxKey: createFetchWaxKey('/api/mint-wax'),
1983
- * });
1984
- *
1985
- * @example
1986
- * // React
1987
- * <OzElements pubKey="pk_live_..." fetchWaxKey={createFetchWaxKey('/api/mint-wax')}>
1988
- */
1989
- function createFetchWaxKey(mintUrl) {
1990
- const TIMEOUT_MS = 10000;
1991
- // Each attempt gets its own AbortController so a timeout on attempt 1 does
1992
- // not bleed into the retry. Uses AbortController + setTimeout instead of
1993
- // AbortSignal.timeout() to support environments without that API.
1994
- const attemptFetch = (sessionId) => {
1995
- const controller = new AbortController();
1996
- const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
1997
- return fetch(mintUrl, {
1998
- method: 'POST',
1999
- headers: { 'Content-Type': 'application/json' },
2000
- body: JSON.stringify({ sessionId }),
2001
- signal: controller.signal,
2002
- }).finally(() => clearTimeout(timer));
2003
- };
2004
- return async (sessionId) => {
2005
- let res;
2006
- try {
2007
- res = await attemptFetch(sessionId);
2008
- }
2009
- catch (firstErr) {
2010
- // Abort/timeout should not be retried — the server received nothing or
2011
- // we already waited the full timeout duration.
2012
- if (firstErr instanceof Error && (firstErr.name === 'AbortError' || firstErr.name === 'TimeoutError')) {
2013
- throw new OzError(`Wax key mint timed out after ${TIMEOUT_MS / 1000}s (${mintUrl})`, undefined, 'timeout');
2014
- }
2015
- // Pure network error (offline, DNS, connection refused) — retry once
2016
- // after a short pause in case of a transient blip.
2017
- await new Promise(resolve => setTimeout(resolve, 750));
2018
- try {
2019
- res = await attemptFetch(sessionId);
2020
- }
2021
- catch (retryErr) {
2022
- const msg = retryErr instanceof Error ? retryErr.message : 'Network error';
2023
- throw new OzError(`Could not reach wax key mint endpoint (${mintUrl}): ${msg}`, undefined, 'network');
2024
- }
2025
- }
2026
- const data = await res.json().catch(() => ({}));
2027
- if (!res.ok) {
2028
- throw new OzError(typeof data.error === 'string' && data.error
2029
- ? data.error
2030
- : `Wax key mint failed (HTTP ${res.status})`, undefined, res.status >= 500 ? 'server' : res.status === 401 || res.status === 403 ? 'auth' : 'validation');
2031
- }
2032
- if (typeof data.waxKey !== 'string' || !data.waxKey.trim()) {
2033
- throw new OzError('Mint endpoint response is missing waxKey. Check your /api/mint-wax implementation.', undefined, 'validation');
2034
- }
2035
- return data.waxKey;
2036
- };
2037
- }
2038
-
2039
- export { OzElement, OzError, OzVault, createFetchWaxKey, normalizeBankVaultError, normalizeCardSaleError, normalizeVaultError };
2058
+ export { OzElement, OzError, OzVault, createSessionFetcher as createFetchWaxKey, createSessionFetcher, normalizeBankVaultError, normalizeCardSaleError, normalizeVaultError };
2040
2059
  //# sourceMappingURL=oz-elements.esm.js.map