@connect-xyz/auth-js 1.60.2 → 1.62.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
@@ -284,21 +284,22 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
284
284
  return customElements.get(this.webComponentTag);
285
285
  }
286
286
 
287
- private getScriptUrl() {
288
- // Support local development with Vite
287
+ private getEffectiveScriptUrls(): Record<string, string> {
288
+ // Support local development with Vite: an internal build pins the script
289
+ // URL for the configured env, bypassing the CDN maps entirely.
289
290
  if (typeof import.meta !== 'undefined' && import.meta.env?.['VITE_INTERNAL_BUILD'] === 'true') {
290
- return import.meta.env['VITE_SCRIPT_URL'] || this.scriptUrls[this.getEnvironment()];
291
+ const override = import.meta.env['VITE_SCRIPT_URL'];
292
+ if (override) return { [this.getEnvironment()]: override };
291
293
  }
292
294
 
293
- // Route EU partners (region claim in JWT) to EU-hosted assets without
294
- // changing the public `env` contract — falls back to the configured env
295
- // when no EU URL is registered for that environment.
296
- const effectiveEnv = resolveEnvByRegion(this.getEnvironment(), this.config.jwt);
297
- return this.scriptUrls[effectiveEnv] ?? this.scriptUrls[this.getEnvironment()];
295
+ return this.scriptUrls;
298
296
  }
299
297
 
300
298
  private async loadScript() {
301
- if (this.isScriptLoaded()) {
299
+ // When the element is already defined or another instance's script tag is
300
+ // in flight, defer to waitForWebComponent — the shared loader would no-op
301
+ // for those cases and never settle this promise.
302
+ if (this.getWebComponent() || this.isScriptLoaded()) {
302
303
  return;
303
304
  }
304
305
 
@@ -306,29 +307,28 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
306
307
  return this.scriptLoadingPromise;
307
308
  }
308
309
 
310
+ // The shared loader also reports failures to Faro (with JWT claims for
311
+ // partner/participant context) and removes a failed tag so a later
312
+ // render() call can retry cleanly.
309
313
  this.scriptLoadingPromise = new Promise<void>((resolve, reject) => {
310
- const script = document.createElement('script');
311
- script.id = this.getScriptId();
312
- script.src = this.getScriptUrl();
313
- script.type = 'module';
314
- script.async = true;
315
-
316
- script.onload = () => {
317
- setTimeout(() => {
318
- if (this.getWebComponent()) {
319
- resolve();
320
- } else {
321
- reject(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
322
- }
323
- }, 0);
324
- };
325
-
326
- script.onerror = () => {
327
- this.scriptLoadingPromise = undefined;
328
- reject(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
329
- };
330
-
331
- document.head.appendChild(script);
314
+ loadWebComponentScript({
315
+ webComponentTag: this.webComponentTag,
316
+ appName: this.webComponentTag,
317
+ scriptUrls: this.getEffectiveScriptUrls(),
318
+ collectorUrls: FARO_COLLECTOR_URLS,
319
+ env: this.getEnvironment(),
320
+ jwt: this.config.jwt,
321
+ onLoad: resolve,
322
+ onError: (info) => {
323
+ reject(
324
+ new Error(
325
+ info.reason === 'not-defined'
326
+ ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED
327
+ : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`
328
+ )
329
+ );
330
+ },
331
+ });
332
332
  });
333
333
 
334
334
  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 C = "production", z = "JWT token is required and must be a string.", M = {
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
+ }, W = (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
+ }, O = (e, t) => W(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
+ }, T = (e, t, r) => {
42
+ const n = O(t, r);
43
+ return e[n] ?? e[t] ?? e.prod;
44
+ }, U = (e, t, r) => {
45
+ const n = O(t, r);
46
+ return e[n] ?? e[t];
47
+ }, _ = () => {
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: S = 15e3, onLoad: L, onError: I } = e;
93
+ if (typeof document > "u")
94
+ return _;
95
+ const m = `${t}-script-${s}`;
96
+ if (customElements.get(t) || document.getElementById(m))
97
+ return _;
98
+ const v = P(d), A = e.report ?? ((l) => x(c && U(c, s, d), l, n));
99
+ let u = !1, w = 0, f;
100
+ const h = () => {
101
+ f !== void 0 && clearTimeout(f);
102
+ }, g = (l, p, i) => {
103
+ if (u)
104
+ return;
105
+ const D = Math.round(performance.now() - w), y = {
106
+ webComponentTag: t,
107
+ appName: r,
108
+ env: s,
109
+ scriptUrl: p,
110
+ reason: l,
111
+ triedFallback: i,
112
+ elapsedMs: D,
113
+ claims: v
114
+ };
115
+ A(y);
116
+ const E = i ? void 0 : T(a ?? {}, s, d);
117
+ if (E && E !== p) {
118
+ R(E, !0);
119
+ return;
120
+ }
121
+ u = !0, h(), document.getElementById(m)?.remove(), I?.(y);
122
+ }, R = (l, p) => {
123
+ h(), w = performance.now();
124
+ const i = document.createElement("script");
125
+ i.id = m, i.src = l, i.type = "module", i.async = !0, i.onload = () => {
126
+ setTimeout(() => {
127
+ u || (customElements.get(t) ? (u = !0, h(), L?.()) : g("not-defined", l, p));
128
+ }, 0);
129
+ }, i.onerror = () => g("network", l, p), f = setTimeout(() => g("timeout", l, p), S), document.getElementById(m)?.remove(), document.head.appendChild(i);
130
+ }, b = T(o, s, d);
131
+ return b ? (R(b, !1), () => {
132
+ u = !0, h();
133
+ }) : _;
134
+ };
135
+ class j {
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(z);
24
142
  this.config = {
25
- ...e,
26
- env: e.env || d,
27
- theme: e.theme
143
+ ...t,
144
+ env: t.env || C,
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 || C;
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: M,
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 V extends j {
160
281
  errorMessages = {
161
282
  ALREADY_RENDERED: "Auth widget is already rendered. Call destroy() before rendering again.",
162
283
  NOT_RENDERED: "Auth widget is not rendered. Call render() first.",
@@ -174,15 +295,15 @@ class g extends p {
174
295
  * @param container - The container element to render the widget into
175
296
  * @returns Promise that resolves when the widget is rendered
176
297
  */
177
- render(e) {
178
- return super.render(e);
298
+ render(t) {
299
+ return super.render(t);
179
300
  }
180
301
  /**
181
302
  * Update the configuration of the Auth widget
182
303
  * @param config - Partial configuration to update
183
304
  */
184
- updateConfig(e) {
185
- return super.updateConfig(e);
305
+ updateConfig(t) {
306
+ return super.updateConfig(t);
186
307
  }
187
308
  /**
188
309
  * Get the current configuration
@@ -206,7 +327,7 @@ class g extends p {
206
327
  }
207
328
  }
208
329
  export {
209
- g as Auth,
210
- c as ErrorCode,
211
- g as default
330
+ V as Auth,
331
+ N as ErrorCode,
332
+ V as default
212
333
  };
@@ -1 +1 @@
1
- (function(i,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(i=typeof globalThis<"u"?globalThis:i||self,o(i.Auth={}))})(this,(function(i){"use strict";const o="production",u="JWT token is required and must be a string.",l=r=>{if(!r||typeof r!="string")return null;const e=r.split(".");if(e.length<2)return null;try{const n=e[1].replace(/-/g,"+").replace(/_/g,"/"),t=n+"===".slice(0,(4-n.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)=>l(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(u);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 n=this.createWebComponent();e.innerHTML="",e.appendChild(n),this.state.container=e,this.state.element=n,this.state.initialized=!0}catch(n){throw console.error("Failed to render widget:",n),n}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const n=this.state.element;Object.entries(e).forEach(([t,s])=>{s&&(this.config[t]=s,n[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,n)=>{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():n(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED))},0)},t.onerror=()=>{this.scriptLoadingPromise=void 0,n(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((n,t)=>{const s=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(s),n()}).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(([n,t])=>{t&&(e[n]=t)}),e}}i.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"})(i.ErrorCode||(i.ErrorCode={}));class d extends m{errorMessages={ALREADY_RENDERED:"Auth widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"Auth widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect Auth script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={sandbox:"https://sdk.sandbox.connect.xyz/auth-web/index.js",production:"https://sdk.connect.xyz/auth-web/index.js"};webComponentTag="connect-auth";render(e){return super.render(e)}updateConfig(e){return super.updateConfig(e)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}i.Auth=d,i.default=d,Object.defineProperties(i,{__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.Auth={}))})(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,A=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},D=(e,t,r)=>{const n=R(t,r);return e[n]??e[t]},E=()=>{},M=()=>{const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},z=(e,t)=>{const r=M(),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}},W=(e,t,r)=>{if(!e||typeof fetch>"u")return;const{sessionId:n,payload:o}=z(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 E;const h=`${t}-script-${i}`;if(customElements.get(t)||document.getElementById(h))return E;const B=A(l),V=e.report??(p=>W(d&&D(d,i,l),p,n));let f=!1,T=0,_;const g=()=>{_!==void 0&&clearTimeout(_)},w=(p,m,a)=>{if(f)return;const $=Math.round(performance.now()-T),O={webComponentTag:t,appName:r,env:i,scriptUrl:m,reason:p,triedFallback:a,elapsedMs:$,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(),T=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?.()):w("not-defined",p,m))},0)},a.onerror=()=>w("network",p,m),_=setTimeout(()=>w("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()}):E};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 C extends U{errorMessages={ALREADY_RENDERED:"Auth widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"Auth widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect Auth script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={sandbox:"https://sdk.sandbox.connect.xyz/auth-web/index.js",production:"https://sdk.connect.xyz/auth-web/index.js"};webComponentTag="connect-auth";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.Auth=C,s.default=C,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/auth-js",
3
- "version": "1.60.2",
3
+ "version": "1.62.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",