@connect-xyz/withdraw-js 0.43.2 → 0.45.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.
package/dist/index.d.ts CHANGED
@@ -199,21 +199,22 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
199
199
  return customElements.get(this.webComponentTag);
200
200
  }
201
201
 
202
- private getScriptUrl() {
203
- // Support local development with Vite
202
+ private getEffectiveScriptUrls(): Record<string, string> {
203
+ // Support local development with Vite: an internal build pins the script
204
+ // URL for the configured env, bypassing the CDN maps entirely.
204
205
  if (typeof import.meta !== 'undefined' && import.meta.env?.['VITE_INTERNAL_BUILD'] === 'true') {
205
- return import.meta.env['VITE_SCRIPT_URL'] || this.scriptUrls[this.getEnvironment()];
206
+ const override = import.meta.env['VITE_SCRIPT_URL'];
207
+ if (override) return { [this.getEnvironment()]: override };
206
208
  }
207
209
 
208
- // Route EU partners (region claim in JWT) to EU-hosted assets without
209
- // changing the public `env` contract — falls back to the configured env
210
- // when no EU URL is registered for that environment.
211
- const effectiveEnv = resolveEnvByRegion(this.getEnvironment(), this.config.jwt);
212
- return this.scriptUrls[effectiveEnv] ?? this.scriptUrls[this.getEnvironment()];
210
+ return this.scriptUrls;
213
211
  }
214
212
 
215
213
  private async loadScript() {
216
- if (this.isScriptLoaded()) {
214
+ // When the element is already defined or another instance's script tag is
215
+ // in flight, defer to waitForWebComponent — the shared loader would no-op
216
+ // for those cases and never settle this promise.
217
+ if (this.getWebComponent() || this.isScriptLoaded()) {
217
218
  return;
218
219
  }
219
220
 
@@ -221,29 +222,28 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
221
222
  return this.scriptLoadingPromise;
222
223
  }
223
224
 
225
+ // The shared loader also reports failures to Faro (with JWT claims for
226
+ // partner/participant context) and removes a failed tag so a later
227
+ // render() call can retry cleanly.
224
228
  this.scriptLoadingPromise = new Promise<void>((resolve, reject) => {
225
- const script = document.createElement('script');
226
- script.id = this.getScriptId();
227
- script.src = this.getScriptUrl();
228
- script.type = 'module';
229
- script.async = true;
230
-
231
- script.onload = () => {
232
- setTimeout(() => {
233
- if (this.getWebComponent()) {
234
- resolve();
235
- } else {
236
- reject(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
237
- }
238
- }, 0);
239
- };
240
-
241
- script.onerror = () => {
242
- this.scriptLoadingPromise = undefined;
243
- reject(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
244
- };
245
-
246
- document.head.appendChild(script);
229
+ loadWebComponentScript({
230
+ webComponentTag: this.webComponentTag,
231
+ appName: this.webComponentTag,
232
+ scriptUrls: this.getEffectiveScriptUrls(),
233
+ collectorUrls: FARO_COLLECTOR_URLS,
234
+ env: this.getEnvironment(),
235
+ jwt: this.config.jwt,
236
+ onLoad: resolve,
237
+ onError: (info) => {
238
+ reject(
239
+ new Error(
240
+ info.reason === 'not-defined'
241
+ ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED
242
+ : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`
243
+ )
244
+ );
245
+ },
246
+ });
247
247
  });
248
248
 
249
249
  try {
package/dist/index.js CHANGED
@@ -1,30 +1,148 @@
1
- const d = "production", h = "JWT token is required and must be a string.", l = (r) => {
2
- if (!r || typeof r != "string")
1
+ const T = "production", W = "JWT token is required and must be a string.", z = {
2
+ dev: "https://grafana-faro-collector.dev.0hash.com/collect",
3
+ cert: "https://grafana-faro-collector.cert.zerohash.com/collect",
4
+ prod: "https://grafana-faro-collector.zerohash.com/collect",
5
+ "eu-cert": "https://grafana-faro-collector.cert.zerohash.eu/collect",
6
+ "eu-prod": "https://grafana-faro-collector.zerohash.eu/collect",
7
+ sandbox: "https://grafana-faro-collector.cert.zerohash.com/collect",
8
+ production: "https://grafana-faro-collector.zerohash.com/collect"
9
+ }, M = (e) => {
10
+ if (!e || typeof e != "string")
3
11
  return null;
4
- const e = r.split(".");
5
- if (e.length < 2)
12
+ const t = e.split(".");
13
+ if (t.length < 2)
6
14
  return null;
7
15
  try {
8
- const n = e[1].replace(/-/g, "+").replace(/_/g, "/"), t = n + "===".slice(0, (4 - n.length % 4) % 4), i = typeof atob < "u" ? atob(t) : Buffer.from(t, "base64").toString("utf-8"), a = JSON.parse(i)?.payload?.region;
9
- if (typeof a != "string")
16
+ const r = t[1].replace(/-/g, "+").replace(/_/g, "/"), n = r + "===".slice(0, (4 - r.length % 4) % 4), o = typeof atob < "u" ? atob(n) : Buffer.from(n, "base64").toString("utf-8"), c = JSON.parse(o)?.payload?.region;
17
+ if (typeof c != "string")
10
18
  return null;
11
- const s = a.toLowerCase();
19
+ const s = c.toLowerCase();
12
20
  return s === "us" || s === "eu" ? s : null;
13
21
  } catch {
14
22
  return null;
15
23
  }
16
- }, u = (r, e) => l(e) !== "eu" ? r : r === "cert" ? "eu-cert" : r === "prod" ? "eu-prod" : r;
17
- class p {
24
+ }, L = (e, t) => M(t) !== "eu" ? e : e === "cert" ? "eu-cert" : e === "prod" ? "eu-prod" : e, P = (e) => {
25
+ if (!e || typeof e != "string")
26
+ return {};
27
+ const t = e.split(".");
28
+ if (t.length < 2)
29
+ return {};
30
+ try {
31
+ const r = t[1].replace(/-/g, "+").replace(/_/g, "/"), n = r + "===".slice(0, (4 - r.length % 4) % 4), o = typeof atob < "u" ? atob(n) : Buffer.from(n, "base64").toString("utf-8"), a = JSON.parse(o), c = a?.payload ?? {}, s = (d) => typeof d == "string" && d.length > 0 ? d : void 0;
32
+ return {
33
+ participantCode: s(c.participant_code),
34
+ platformName: s(c.platform_name),
35
+ platformCode: s(a.platform_code),
36
+ region: s(c.region)
37
+ };
38
+ } catch {
39
+ return {};
40
+ }
41
+ }, C = (e, t, r) => {
42
+ const n = L(t, r);
43
+ return e[n] ?? e[t] ?? e.prod;
44
+ }, U = (e, t, r) => {
45
+ const n = L(t, r);
46
+ return e[n] ?? e[t];
47
+ }, E = () => {
48
+ }, F = () => {
49
+ const e = new Uint8Array(8);
50
+ return globalThis.crypto.getRandomValues(e), Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
51
+ }, k = (e, t) => {
52
+ const r = F(), n = globalThis.__ZH_WEB_SDK_VERSION__, o = {};
53
+ e.claims.participantCode && (o.participant_code = e.claims.participantCode), e.claims.platformName && (o.platform_name = e.claims.platformName), e.claims.platformCode && (o.platform_code = e.claims.platformCode), e.claims.region && (o.region = e.claims.region), n && (o.zh_web_sdk_version = n);
54
+ const a = {
55
+ meta: {
56
+ app: { name: e.appName, version: t ?? "unknown", environment: e.env },
57
+ session: { id: r, attributes: o },
58
+ browser: typeof navigator < "u" ? { userAgent: navigator.userAgent } : void 0,
59
+ page: typeof window < "u" ? { url: window.location.origin } : void 0
60
+ },
61
+ logs: [
62
+ {
63
+ message: `Failed to load the script for ${e.webComponentTag} from ${e.env} environment.`,
64
+ level: "error",
65
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
66
+ context: {
67
+ web_component: e.webComponentTag,
68
+ script_url: e.scriptUrl,
69
+ reason: e.reason,
70
+ tried_fallback: String(e.triedFallback),
71
+ elapsed_ms: String(e.elapsedMs)
72
+ }
73
+ }
74
+ ]
75
+ };
76
+ return { sessionId: r, payload: a };
77
+ }, x = (e, t, r) => {
78
+ if (!e || typeof fetch > "u")
79
+ return;
80
+ const { sessionId: n, payload: o } = k(t, r);
81
+ try {
82
+ fetch(e, {
83
+ method: "POST",
84
+ headers: { "Content-Type": "application/json", "x-faro-session-id": n },
85
+ body: JSON.stringify(o),
86
+ keepalive: !0
87
+ }).catch(() => {
88
+ });
89
+ } catch {
90
+ }
91
+ }, B = (e) => {
92
+ const { webComponentTag: t, appName: r, appVersion: n, scriptUrls: o, fallbackScriptUrls: a, collectorUrls: c, env: s, jwt: d, timeoutMs: O = 15e3, onLoad: S, onError: I } = e;
93
+ if (typeof document > "u")
94
+ return E;
95
+ const u = `${t}-script-${s}`;
96
+ if (customElements.get(t) || document.getElementById(u))
97
+ return E;
98
+ const v = P(d), D = e.report ?? ((l) => x(c && U(c, s, d), l, n));
99
+ let m = !1, _ = 0, f;
100
+ const h = () => {
101
+ f !== void 0 && clearTimeout(f);
102
+ }, g = (l, p, i) => {
103
+ if (m)
104
+ return;
105
+ const A = Math.round(performance.now() - _), y = {
106
+ webComponentTag: t,
107
+ appName: r,
108
+ env: s,
109
+ scriptUrl: p,
110
+ reason: l,
111
+ triedFallback: i,
112
+ elapsedMs: A,
113
+ claims: v
114
+ };
115
+ D(y);
116
+ const w = i ? void 0 : C(a ?? {}, s, d);
117
+ if (w && w !== p) {
118
+ R(w, !0);
119
+ return;
120
+ }
121
+ m = !0, h(), document.getElementById(u)?.remove(), I?.(y);
122
+ }, R = (l, p) => {
123
+ h(), _ = performance.now();
124
+ const i = document.createElement("script");
125
+ i.id = u, i.src = l, i.type = "module", i.async = !0, i.onload = () => {
126
+ setTimeout(() => {
127
+ m || (customElements.get(t) ? (m = !0, h(), S?.()) : g("not-defined", l, p));
128
+ }, 0);
129
+ }, i.onerror = () => g("network", l, p), f = setTimeout(() => g("timeout", l, p), O), document.getElementById(u)?.remove(), document.head.appendChild(i);
130
+ }, b = C(o, s, d);
131
+ return b ? (R(b, !1), () => {
132
+ m = !0, h();
133
+ }) : E;
134
+ };
135
+ class V {
18
136
  config;
19
137
  state;
20
138
  scriptLoadingPromise;
21
- constructor(e) {
22
- if (!e.jwt || typeof e.jwt != "string")
23
- throw new Error(h);
139
+ constructor(t) {
140
+ if (!t.jwt || typeof t.jwt != "string")
141
+ throw new Error(W);
24
142
  this.config = {
25
- ...e,
26
- env: e.env || d,
27
- theme: e.theme
143
+ ...t,
144
+ env: t.env || T,
145
+ theme: t.theme
28
146
  }, this.state = {
29
147
  initialized: !1,
30
148
  scriptLoaded: !1,
@@ -37,17 +155,17 @@ class p {
37
155
  * @param container - The container element to render the widget into
38
156
  * @returns Promise that resolves when the widget is rendered
39
157
  */
40
- async render(e) {
41
- if (!e || !(e instanceof HTMLElement))
158
+ async render(t) {
159
+ if (!t || !(t instanceof HTMLElement))
42
160
  throw new Error(this.errorMessages.INVALID_CONTAINER);
43
161
  if (this.state.initialized)
44
162
  throw new Error(this.errorMessages.ALREADY_RENDERED);
45
163
  try {
46
164
  await this.ensureScriptLoaded();
47
- const n = this.createWebComponent();
48
- e.innerHTML = "", e.appendChild(n), this.state.container = e, this.state.element = n, this.state.initialized = !0;
49
- } catch (n) {
50
- throw console.error("Failed to render widget:", n), n;
165
+ const r = this.createWebComponent();
166
+ t.innerHTML = "", t.appendChild(r), this.state.container = t, this.state.element = r, this.state.initialized = !0;
167
+ } catch (r) {
168
+ throw console.error("Failed to render widget:", r), r;
51
169
  }
52
170
  }
53
171
  /**
@@ -55,12 +173,12 @@ class p {
55
173
  * @param config - Partial configuration to update
56
174
  * @returns void
57
175
  */
58
- updateConfig(e) {
176
+ updateConfig(t) {
59
177
  if (!this.state.initialized || !this.state.element)
60
178
  throw new Error(this.errorMessages.NOT_RENDERED);
61
- const n = this.state.element;
62
- Object.entries(e).forEach(([t, i]) => {
63
- i && (this.config[t] = i, n[t] = i);
179
+ const r = this.state.element;
180
+ Object.entries(t).forEach(([n, o]) => {
181
+ o && (this.config[n] = o, r[n] = o);
64
182
  });
65
183
  }
66
184
  /**
@@ -84,7 +202,7 @@ class p {
84
202
  return { ...this.config };
85
203
  }
86
204
  getEnvironment() {
87
- return this.config.env || d;
205
+ return this.config.env || T;
88
206
  }
89
207
  getScriptId() {
90
208
  return `${this.webComponentTag}-script-${this.getEnvironment()}`;
@@ -95,42 +213,45 @@ class p {
95
213
  getWebComponent() {
96
214
  return customElements.get(this.webComponentTag);
97
215
  }
98
- getScriptUrl() {
99
- const e = u(this.getEnvironment(), this.config.jwt);
100
- return this.scriptUrls[e] ?? this.scriptUrls[this.getEnvironment()];
216
+ getEffectiveScriptUrls() {
217
+ return this.scriptUrls;
101
218
  }
102
219
  async loadScript() {
103
- if (!this.isScriptLoaded()) {
220
+ if (!(this.getWebComponent() || this.isScriptLoaded())) {
104
221
  if (this.scriptLoadingPromise)
105
222
  return this.scriptLoadingPromise;
106
- this.scriptLoadingPromise = new Promise((e, n) => {
107
- const t = document.createElement("script");
108
- t.id = this.getScriptId(), t.src = this.getScriptUrl(), t.type = "module", t.async = !0, t.onload = () => {
109
- setTimeout(() => {
110
- this.getWebComponent() ? e() : n(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
111
- }, 0);
112
- }, t.onerror = () => {
113
- this.scriptLoadingPromise = void 0, n(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
114
- }, document.head.appendChild(t);
223
+ this.scriptLoadingPromise = new Promise((t, r) => {
224
+ B({
225
+ webComponentTag: this.webComponentTag,
226
+ appName: this.webComponentTag,
227
+ scriptUrls: this.getEffectiveScriptUrls(),
228
+ collectorUrls: z,
229
+ env: this.getEnvironment(),
230
+ jwt: this.config.jwt,
231
+ onLoad: t,
232
+ onError: (n) => {
233
+ r(new Error(n.reason === "not-defined" ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
234
+ }
235
+ });
115
236
  });
116
237
  try {
117
238
  await this.scriptLoadingPromise;
118
- } catch (e) {
119
- throw this.scriptLoadingPromise = void 0, e;
239
+ } catch (t) {
240
+ throw this.scriptLoadingPromise = void 0, t;
120
241
  }
121
242
  return this.scriptLoadingPromise;
122
243
  }
123
244
  }
124
- async waitForWebComponent(e = 5e3) {
245
+ async waitForWebComponent(t = 5e3) {
125
246
  if (!this.getWebComponent())
126
- return new Promise((n, t) => {
127
- const i = setTimeout(() => {
128
- t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
129
- }, e);
247
+ return new Promise((r, n) => {
248
+ const o = setTimeout(() => {
249
+ n(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
250
+ }, t);
130
251
  customElements.whenDefined(this.webComponentTag).then(() => {
131
- clearTimeout(i), n();
132
- }).catch((o) => {
133
- clearTimeout(i), t(o);
252
+ clearTimeout(o), r();
253
+ }).catch((a) => {
254
+ clearTimeout(o), n(a);
134
255
  });
135
256
  });
136
257
  }
@@ -141,22 +262,22 @@ class p {
141
262
  if (!this.state.scriptLoaded)
142
263
  try {
143
264
  await this.loadScript(), await this.waitForWebComponent(), this.state.scriptLoaded = !0;
144
- } catch (e) {
145
- throw console.error("Failed to load Connect script:", e), e;
265
+ } catch (t) {
266
+ throw console.error("Failed to load Connect script:", t), t;
146
267
  }
147
268
  }
148
269
  createWebComponent() {
149
- const e = document.createElement(this.webComponentTag);
150
- return Object.entries(this.config).forEach(([n, t]) => {
151
- t && (e[n] = t);
152
- }), e;
270
+ const t = document.createElement(this.webComponentTag);
271
+ return Object.entries(this.config).forEach(([r, n]) => {
272
+ n && (t[r] = n);
273
+ }), t;
153
274
  }
154
275
  }
155
- var c;
156
- (function(r) {
157
- r.NETWORK_ERROR = "network_error", r.AUTH_ERROR = "auth_error", r.NOT_FOUND_ERROR = "not_found_error", r.VALIDATION_ERROR = "validation_error", r.SERVER_ERROR = "server_error", r.CLIENT_ERROR = "client_error", r.UNKNOWN_ERROR = "unknown_error";
158
- })(c || (c = {}));
159
- class g extends p {
276
+ var N;
277
+ (function(e) {
278
+ e.NETWORK_ERROR = "network_error", e.AUTH_ERROR = "auth_error", e.NOT_FOUND_ERROR = "not_found_error", e.VALIDATION_ERROR = "validation_error", e.SERVER_ERROR = "server_error", e.CLIENT_ERROR = "client_error", e.UNKNOWN_ERROR = "unknown_error";
279
+ })(N || (N = {}));
280
+ class j extends V {
160
281
  errorMessages = {
161
282
  ALREADY_RENDERED: "Withdraw widget is already rendered. Call destroy() before rendering again.",
162
283
  NOT_RENDERED: "Withdraw widget is not rendered. Call render() first.",
@@ -175,15 +296,15 @@ class g extends p {
175
296
  * @param container - The container element to render the widget into
176
297
  * @returns Promise that resolves when the widget is rendered
177
298
  */
178
- render(e) {
179
- return super.render(e);
299
+ render(t) {
300
+ return super.render(t);
180
301
  }
181
302
  /**
182
303
  * Update the configuration of the Withdraw widget
183
304
  * @param config - Partial configuration to update
184
305
  */
185
- updateConfig(e) {
186
- return super.updateConfig(e);
306
+ updateConfig(t) {
307
+ return super.updateConfig(t);
187
308
  }
188
309
  /**
189
310
  * Get the current configuration
@@ -207,7 +328,7 @@ class g extends p {
207
328
  }
208
329
  }
209
330
  export {
210
- c as ErrorCode,
211
- g as Withdraw,
212
- g as default
331
+ N as ErrorCode,
332
+ j as Withdraw,
333
+ j as default
213
334
  };
@@ -1 +1 @@
1
- (function(n,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(n=typeof globalThis<"u"?globalThis:n||self,o(n.Withdraw={}))})(this,(function(n){"use strict";const o="production",l="JWT token is required and must be a string.",u=r=>{if(!r||typeof r!="string")return null;const e=r.split(".");if(e.length<2)return null;try{const i=e[1].replace(/-/g,"+").replace(/_/g,"/"),t=i+"===".slice(0,(4-i.length%4)%4),s=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf-8"),h=JSON.parse(s)?.payload?.region;if(typeof h!="string")return null;const a=h.toLowerCase();return a==="us"||a==="eu"?a:null}catch{return null}},p=(r,e)=>u(e)!=="eu"?r:r==="cert"?"eu-cert":r==="prod"?"eu-prod":r;class m{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(l);this.config={...e,env:e.env||o,theme:e.theme},this.state={initialized:!1,scriptLoaded:!1,container:null,element:null}}async render(e){if(!e||!(e instanceof HTMLElement))throw new Error(this.errorMessages.INVALID_CONTAINER);if(this.state.initialized)throw new Error(this.errorMessages.ALREADY_RENDERED);try{await this.ensureScriptLoaded();const i=this.createWebComponent();e.innerHTML="",e.appendChild(i),this.state.container=e,this.state.element=i,this.state.initialized=!0}catch(i){throw console.error("Failed to render widget:",i),i}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const i=this.state.element;Object.entries(e).forEach(([t,s])=>{s&&(this.config[t]=s,i[t]=s)})}destroy(){this.state.initialized&&(this.state.element&&this.state.element.parentNode&&this.state.element.parentNode.removeChild(this.state.element),this.state.container&&(this.state.container.innerHTML=""),this.state.container=null,this.state.element=null,this.state.initialized=!1)}isRendered(){return this.state.initialized}getConfig(){return{...this.config}}getEnvironment(){return this.config.env||o}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getScriptUrl(){const e=p(this.getEnvironment(),this.config.jwt);return this.scriptUrls[e]??this.scriptUrls[this.getEnvironment()]}async loadScript(){if(!this.isScriptLoaded()){if(this.scriptLoadingPromise)return this.scriptLoadingPromise;this.scriptLoadingPromise=new Promise((e,i)=>{const t=document.createElement("script");t.id=this.getScriptId(),t.src=this.getScriptUrl(),t.type="module",t.async=!0,t.onload=()=>{setTimeout(()=>{this.getWebComponent()?e():i(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED))},0)},t.onerror=()=>{this.scriptLoadingPromise=void 0,i(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`))},document.head.appendChild(t)});try{await this.scriptLoadingPromise}catch(e){throw this.scriptLoadingPromise=void 0,e}return this.scriptLoadingPromise}}async waitForWebComponent(e=5e3){if(!this.getWebComponent())return new Promise((i,t)=>{const s=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(s),i()}).catch(c=>{clearTimeout(s),t(c)})})}async ensureScriptLoaded(){if(!this.state.scriptLoaded)try{await this.loadScript(),await this.waitForWebComponent(),this.state.scriptLoaded=!0}catch(e){throw console.error("Failed to load Connect script:",e),e}}createWebComponent(){const e=document.createElement(this.webComponentTag);return Object.entries(this.config).forEach(([i,t])=>{t&&(e[i]=t)}),e}}n.ErrorCode=void 0,(function(r){r.NETWORK_ERROR="network_error",r.AUTH_ERROR="auth_error",r.NOT_FOUND_ERROR="not_found_error",r.VALIDATION_ERROR="validation_error",r.SERVER_ERROR="server_error",r.CLIENT_ERROR="client_error",r.UNKNOWN_ERROR="unknown_error"})(n.ErrorCode||(n.ErrorCode={}));class d extends m{errorMessages={ALREADY_RENDERED:"Withdraw widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"Withdraw widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect Withdraw script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded.",INVALID_JWT:"JWT token is required and must be a string."};scriptUrls={sandbox:"https://sdk.sandbox.connect.xyz/withdraw-web/index.js",production:"https://sdk.connect.xyz/withdraw-web/index.js"};webComponentTag="connect-withdraw";render(e){return super.render(e)}updateConfig(e){return super.updateConfig(e)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}n.Withdraw=d,n.default=d,Object.defineProperties(n,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
1
+ (function(s,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(s=typeof globalThis<"u"?globalThis:s||self,u(s.Withdraw={}))})(this,(function(s){"use strict";const u="production",L="JWT token is required and must be a string.",I={dev:"https://grafana-faro-collector.dev.0hash.com/collect",cert:"https://grafana-faro-collector.cert.zerohash.com/collect",prod:"https://grafana-faro-collector.zerohash.com/collect","eu-cert":"https://grafana-faro-collector.cert.zerohash.eu/collect","eu-prod":"https://grafana-faro-collector.zerohash.eu/collect",sandbox:"https://grafana-faro-collector.cert.zerohash.com/collect",production:"https://grafana-faro-collector.zerohash.com/collect"},v=e=>{if(!e||typeof e!="string")return null;const t=e.split(".");if(t.length<2)return null;try{const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=r+"===".slice(0,(4-r.length%4)%4),o=typeof atob<"u"?atob(n):Buffer.from(n,"base64").toString("utf-8"),d=JSON.parse(o)?.payload?.region;if(typeof d!="string")return null;const i=d.toLowerCase();return i==="us"||i==="eu"?i:null}catch{return null}},R=(e,t)=>v(t)!=="eu"?e:e==="cert"?"eu-cert":e==="prod"?"eu-prod":e,D=e=>{if(!e||typeof e!="string")return{};const t=e.split(".");if(t.length<2)return{};try{const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=r+"===".slice(0,(4-r.length%4)%4),o=typeof atob<"u"?atob(n):Buffer.from(n,"base64").toString("utf-8"),c=JSON.parse(o),d=c?.payload??{},i=l=>typeof l=="string"&&l.length>0?l:void 0;return{participantCode:i(d.participant_code),platformName:i(d.platform_name),platformCode:i(c.platform_code),region:i(d.region)}}catch{return{}}},y=(e,t,r)=>{const n=R(t,r);return e[n]??e[t]??e.prod},A=(e,t,r)=>{const n=R(t,r);return e[n]??e[t]},w=()=>{},W=()=>{const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},M=(e,t)=>{const r=W(),n=globalThis.__ZH_WEB_SDK_VERSION__,o={};e.claims.participantCode&&(o.participant_code=e.claims.participantCode),e.claims.platformName&&(o.platform_name=e.claims.platformName),e.claims.platformCode&&(o.platform_code=e.claims.platformCode),e.claims.region&&(o.region=e.claims.region),n&&(o.zh_web_sdk_version=n);const c={meta:{app:{name:e.appName,version:t??"unknown",environment:e.env},session:{id:r,attributes:o},browser:typeof navigator<"u"?{userAgent:navigator.userAgent}:void 0,page:typeof window<"u"?{url:window.location.origin}:void 0},logs:[{message:`Failed to load the script for ${e.webComponentTag} from ${e.env} environment.`,level:"error",timestamp:new Date().toISOString(),context:{web_component:e.webComponentTag,script_url:e.scriptUrl,reason:e.reason,tried_fallback:String(e.triedFallback),elapsed_ms:String(e.elapsedMs)}}]};return{sessionId:r,payload:c}},z=(e,t,r)=>{if(!e||typeof fetch>"u")return;const{sessionId:n,payload:o}=M(t,r);try{fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-faro-session-id":n},body:JSON.stringify(o),keepalive:!0}).catch(()=>{})}catch{}},P=e=>{const{webComponentTag:t,appName:r,appVersion:n,scriptUrls:o,fallbackScriptUrls:c,collectorUrls:d,env:i,jwt:l,timeoutMs:F=15e3,onLoad:j,onError:k}=e;if(typeof document>"u")return w;const h=`${t}-script-${i}`;if(customElements.get(t)||document.getElementById(h))return w;const B=D(l),V=e.report??(p=>z(d&&A(d,i,l),p,n));let f=!1,C=0,E;const g=()=>{E!==void 0&&clearTimeout(E)},_=(p,m,a)=>{if(f)return;const J=Math.round(performance.now()-C),O={webComponentTag:t,appName:r,env:i,scriptUrl:m,reason:p,triedFallback:a,elapsedMs:J,claims:B};V(O);const b=a?void 0:y(c??{},i,l);if(b&&b!==m){N(b,!0);return}f=!0,g(),document.getElementById(h)?.remove(),k?.(O)},N=(p,m)=>{g(),C=performance.now();const a=document.createElement("script");a.id=h,a.src=p,a.type="module",a.async=!0,a.onload=()=>{setTimeout(()=>{f||(customElements.get(t)?(f=!0,g(),j?.()):_("not-defined",p,m))},0)},a.onerror=()=>_("network",p,m),E=setTimeout(()=>_("timeout",p,m),F),document.getElementById(h)?.remove(),document.head.appendChild(a)},S=y(o,i,l);return S?(N(S,!1),()=>{f=!0,g()}):w};class U{config;state;scriptLoadingPromise;constructor(t){if(!t.jwt||typeof t.jwt!="string")throw new Error(L);this.config={...t,env:t.env||u,theme:t.theme},this.state={initialized:!1,scriptLoaded:!1,container:null,element:null}}async render(t){if(!t||!(t instanceof HTMLElement))throw new Error(this.errorMessages.INVALID_CONTAINER);if(this.state.initialized)throw new Error(this.errorMessages.ALREADY_RENDERED);try{await this.ensureScriptLoaded();const r=this.createWebComponent();t.innerHTML="",t.appendChild(r),this.state.container=t,this.state.element=r,this.state.initialized=!0}catch(r){throw console.error("Failed to render widget:",r),r}}updateConfig(t){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const r=this.state.element;Object.entries(t).forEach(([n,o])=>{o&&(this.config[n]=o,r[n]=o)})}destroy(){this.state.initialized&&(this.state.element&&this.state.element.parentNode&&this.state.element.parentNode.removeChild(this.state.element),this.state.container&&(this.state.container.innerHTML=""),this.state.container=null,this.state.element=null,this.state.initialized=!1)}isRendered(){return this.state.initialized}getConfig(){return{...this.config}}getEnvironment(){return this.config.env||u}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getEffectiveScriptUrls(){return this.scriptUrls}async loadScript(){if(!(this.getWebComponent()||this.isScriptLoaded())){if(this.scriptLoadingPromise)return this.scriptLoadingPromise;this.scriptLoadingPromise=new Promise((t,r)=>{P({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:I,env:this.getEnvironment(),jwt:this.config.jwt,onLoad:t,onError:n=>{r(new Error(n.reason==="not-defined"?this.errorMessages.WEB_COMPONENT_NOT_DEFINED:`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`))}})});try{await this.scriptLoadingPromise}catch(t){throw this.scriptLoadingPromise=void 0,t}return this.scriptLoadingPromise}}async waitForWebComponent(t=5e3){if(!this.getWebComponent())return new Promise((r,n)=>{const o=setTimeout(()=>{n(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},t);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),r()}).catch(c=>{clearTimeout(o),n(c)})})}async ensureScriptLoaded(){if(!this.state.scriptLoaded)try{await this.loadScript(),await this.waitForWebComponent(),this.state.scriptLoaded=!0}catch(t){throw console.error("Failed to load Connect script:",t),t}}createWebComponent(){const t=document.createElement(this.webComponentTag);return Object.entries(this.config).forEach(([r,n])=>{n&&(t[r]=n)}),t}}s.ErrorCode=void 0,(function(e){e.NETWORK_ERROR="network_error",e.AUTH_ERROR="auth_error",e.NOT_FOUND_ERROR="not_found_error",e.VALIDATION_ERROR="validation_error",e.SERVER_ERROR="server_error",e.CLIENT_ERROR="client_error",e.UNKNOWN_ERROR="unknown_error"})(s.ErrorCode||(s.ErrorCode={}));class T extends U{errorMessages={ALREADY_RENDERED:"Withdraw widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"Withdraw widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect Withdraw script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded.",INVALID_JWT:"JWT token is required and must be a string."};scriptUrls={sandbox:"https://sdk.sandbox.connect.xyz/withdraw-web/index.js",production:"https://sdk.connect.xyz/withdraw-web/index.js"};webComponentTag="connect-withdraw";render(t){return super.render(t)}updateConfig(t){return super.updateConfig(t)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}s.Withdraw=T,s.default=T,Object.defineProperties(s,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@connect-xyz/withdraw-js",
3
- "version": "0.43.2",
3
+ "version": "0.45.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",