@connect-xyz/auth-js 1.2.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -44,26 +44,19 @@ declare type AppEvent<TType extends string = string, TData = Record<string, unkn
44
44
  * auth.destroy();
45
45
  * ```
46
46
  */
47
- declare class Auth {
48
- private config;
49
- private state;
50
- /**
51
- * Create a new Auth instance
52
- * @param config - Configuration options for the Auth SDK
53
- */
54
- constructor(config: AuthConfig);
55
- /**
56
- * Get the current environment
57
- */
58
- private get environment();
59
- /**
60
- * Load the web component script if not already loaded
61
- */
62
- private ensureScriptLoaded;
63
- /**
64
- * Create the web component element
65
- */
66
- private createWebComponent;
47
+ declare class Auth extends BaseJsSdk<AuthConfig> {
48
+ protected errorMessages: {
49
+ readonly ALREADY_RENDERED: "Auth widget is already rendered. Call destroy() before rendering again.";
50
+ readonly NOT_RENDERED: "Auth widget is not rendered. Call render() first.";
51
+ readonly INVALID_CONTAINER: "Invalid container element provided.";
52
+ readonly SCRIPT_LOAD_FAILED: "Failed to load the Connect Auth script.";
53
+ readonly WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded.";
54
+ };
55
+ protected scriptUrls: {
56
+ sandbox: string;
57
+ production: string;
58
+ };
59
+ protected webComponentTag: string;
67
60
  /**
68
61
  * Render the Auth widget to a container element
69
62
  * @param container - The container element to render the widget into
@@ -76,19 +69,19 @@ declare class Auth {
76
69
  */
77
70
  updateConfig(config: Partial<AuthConfig>): void;
78
71
  /**
79
- * Destroy the Auth widget and clean up resources
72
+ * Get the current configuration
73
+ * @returns The current configuration object
80
74
  */
81
- destroy(): void;
75
+ getConfig(): Readonly<AuthConfig>;
82
76
  /**
83
77
  * Check if the Auth widget is currently rendered
84
78
  * @returns True if the widget is rendered, false otherwise
85
79
  */
86
80
  isRendered(): boolean;
87
81
  /**
88
- * Get the current configuration
89
- * @returns The current configuration object
82
+ * Destroy the Auth widget and clean up resources
90
83
  */
91
- getConfig(): Readonly<AuthConfig>;
84
+ destroy(): void;
92
85
  }
93
86
  export { Auth }
94
87
  export default Auth;
@@ -102,21 +95,34 @@ declare type AuthCallbacks = CommonCallbacks<AuthEvent> & {
102
95
  onDeposit?: (deposit: DepositCompletedPayload) => void;
103
96
  };
104
97
 
98
+ export declare interface AuthConfig extends BaseConfig<AuthEvent>, AuthCallbacks {
99
+ }
100
+
101
+ /**
102
+ * Auth event structure for auth-specific events
103
+ */
104
+ declare type AuthEvent = AppEvent<AuthEventType, DepositSubmittedEventData>;
105
+
105
106
  /**
106
- * Configuration options for the Auth SDK
107
+ * Auth event type literals
108
+ */
109
+ declare type AuthEventType = 'deposit.submitted';
110
+
111
+ /**
112
+ * Configuration options for the SDK
107
113
  */
108
- export declare interface AuthConfig extends AuthCallbacks {
114
+ declare interface BaseConfig<TEvent = AppEvent> extends CommonCallbacks<TEvent> {
109
115
  /**
110
- * JWT token used for authentication with the Connect Auth service
116
+ * JWT token used for authentication
111
117
  */
112
118
  jwt: string;
113
119
  /**
114
- * Target environment for the Connect Auth service
120
+ * Target environment
115
121
  * @default 'production'
116
122
  */
117
123
  env?: Environment;
118
124
  /**
119
- * Theme mode for the Connect Auth interface
125
+ * Theme mode
120
126
  * @default 'auto'
121
127
  *
122
128
  * Available themes:
@@ -127,28 +133,54 @@ export declare interface AuthConfig extends AuthCallbacks {
127
133
  theme?: Theme;
128
134
  }
129
135
 
130
- /**
131
- * Auth event structure for auth-specific events
132
- */
133
- declare type AuthEvent = AppEvent<AuthEventType, DepositSubmittedEventData>;
134
-
135
- /**
136
- * Auth event type literals
137
- */
138
- declare type AuthEventType = 'deposit.submitted';
136
+ declare type BaseErrorMessageKeys = 'ALREADY_RENDERED' | 'NOT_RENDERED' | 'INVALID_CONTAINER' | 'SCRIPT_LOAD_FAILED' | 'WEB_COMPONENT_NOT_DEFINED';
139
137
 
140
- /**
141
- * Internal state of the Auth SDK
142
- */
143
- export declare interface AuthState {
144
- /** Whether the SDK is initialized */
145
- initialized: boolean;
146
- /** Whether the web component script is loaded */
147
- scriptLoaded: boolean;
148
- /** The container element where the auth widget is rendered */
149
- container: HTMLElement | null;
150
- /** The web component element */
151
- element: HTMLElement | null;
138
+ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig> {
139
+ private config;
140
+ private state;
141
+ private scriptLoadingPromise?;
142
+ protected abstract errorMessages: Record<BaseErrorMessageKeys, string>;
143
+ protected abstract scriptUrls: Record<Environment, string>;
144
+ protected abstract webComponentTag: string;
145
+ constructor(config: Config);
146
+ /**
147
+ * Render the widget to a container element
148
+ * @param container - The container element to render the widget into
149
+ * @returns Promise that resolves when the widget is rendered
150
+ */
151
+ render(container: HTMLElement): Promise<void>;
152
+ /**
153
+ * Update the configuration of the widget
154
+ * @param config - Partial configuration to update
155
+ * @returns void
156
+ */
157
+ updateConfig(config: Partial<Config>): void;
158
+ /**
159
+ * Destroy the widget and clean up resources
160
+ */
161
+ destroy(): void;
162
+ /**
163
+ * Check if the widget is currently rendered
164
+ * @returns True if the widget is rendered, false otherwise
165
+ */
166
+ isRendered(): boolean;
167
+ /**
168
+ * Get the current configuration
169
+ * @returns The current configuration object
170
+ */
171
+ getConfig(): Readonly<Config>;
172
+ private getEnvironment;
173
+ private getScriptId;
174
+ private isScriptLoaded;
175
+ private getWebComponent;
176
+ private getScriptUrl;
177
+ private loadScript;
178
+ private waitForWebComponent;
179
+ /**
180
+ * Load the web component script if not already loaded
181
+ */
182
+ protected ensureScriptLoaded(): Promise<void>;
183
+ private createWebComponent;
152
184
  }
153
185
 
154
186
  /**
@@ -164,18 +196,7 @@ declare type CommonCallbacks<TEvent = AppEvent> = {
164
196
  onEvent?: (event: TEvent) => void;
165
197
  };
166
198
 
167
- /**
168
- * ConnectAuth element interface
169
- */
170
- export declare interface ConnectAuthElement extends HTMLElement {
171
- jwt: string;
172
- env?: Environment;
173
- theme?: Theme;
174
- onError?: (errorData: ErrorPayload) => void;
175
- onClose?: () => void;
176
- onDeposit?: (depositData: DepositCompletedPayload) => void;
177
- onEvent?: (eventData: AuthEvent) => void;
178
- }
199
+ export declare type ConnectAuthElement = SdkElement<AuthConfig>;
179
200
 
180
201
  /**
181
202
  * Deposit completed payload structure for deposit callbacks
@@ -217,14 +238,14 @@ declare type DepositSubmittedEventData = {
217
238
  };
218
239
 
219
240
  /**
220
- * Environment configuration for the Auth SDK
241
+ * Environment configuration for the SDK
221
242
  */
222
243
  export declare type Environment = 'sandbox' | 'production';
223
244
 
224
245
  /**
225
246
  * Generic error codes for all Connect applications
226
247
  */
227
- declare enum ErrorCode {
248
+ export declare enum ErrorCode {
228
249
  /** Network connectivity error */
229
250
  NETWORK_ERROR = 'network_error',
230
251
  /** Authentication or session expired error */
@@ -252,7 +273,12 @@ declare type ErrorPayload = {
252
273
  };
253
274
 
254
275
  /**
255
- * Theme configuration for the Auth SDK
276
+ * Generic HTMLElement representing a web component with custom config
277
+ */
278
+ declare type SdkElement<Config extends BaseConfig<never>> = HTMLElement & Config;
279
+
280
+ /**
281
+ * Theme configuration for the SDK
256
282
  *
257
283
  * - `"auto"` - Automatically detect system preference (light/dark mode)
258
284
  * - `"light"` - Force light theme
package/dist/index.js CHANGED
@@ -1,78 +1,15 @@
1
- var l = Object.defineProperty;
2
- var E = (n, t, e) => t in n ? l(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var d = (n, t, e) => E(n, typeof t != "symbol" ? t + "" : t, e);
4
- const u = {
5
- sandbox: "https://sdk.sandbox.connect.xyz/auth-web/index.js",
6
- production: "https://sdk.connect.xyz/auth-web/index.js"
7
- }, m = "connect-auth-script", p = "connect-auth", c = "production", r = {
8
- ALREADY_RENDERED: "Auth widget is already rendered. Call destroy() before rendering again.",
9
- NOT_RENDERED: "Auth widget is not rendered. Call render() first.",
10
- INVALID_CONTAINER: "Invalid container element provided.",
11
- SCRIPT_LOAD_FAILED: "Failed to load the Connect Auth script.",
12
- WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded.",
13
- INVALID_JWT: "JWT token is required and must be a string."
14
- }, a = /* @__PURE__ */ new Map();
15
- function f(n) {
16
- return u[n];
17
- }
18
- function h(n) {
19
- return `${m}-${n}`;
20
- }
21
- function w(n) {
22
- const t = h(n);
23
- return !!document.getElementById(t);
24
- }
25
- async function D(n) {
26
- const t = h(n);
27
- if (w(n))
28
- return Promise.resolve();
29
- if (a.has(t))
30
- return a.get(t);
31
- const e = new Promise((i, s) => {
32
- const o = document.createElement("script");
33
- o.id = t, o.src = f(n), o.type = "module", o.async = !0, o.onload = () => {
34
- setTimeout(() => {
35
- customElements.get("connect-auth") ? i() : s(new Error(r.WEB_COMPONENT_NOT_DEFINED));
36
- }, 0);
37
- }, o.onerror = () => {
38
- a.delete(t), s(new Error(`${r.SCRIPT_LOAD_FAILED} (${n})`));
39
- }, document.head.appendChild(o);
40
- });
41
- a.set(t, e);
42
- try {
43
- await e;
44
- } catch (i) {
45
- throw a.delete(t), i;
46
- }
47
- return e;
48
- }
49
- async function N(n = 5e3) {
50
- const t = "connect-auth";
51
- return customElements.get(t) ? Promise.resolve() : new Promise((e, i) => {
52
- const s = setTimeout(() => {
53
- i(new Error(`Timeout waiting for ${t} to be defined`));
54
- }, n);
55
- customElements.whenDefined(t).then(() => {
56
- clearTimeout(s), e();
57
- }).catch((o) => {
58
- clearTimeout(s), i(o);
59
- });
60
- });
61
- }
62
- class I {
63
- /**
64
- * Create a new Auth instance
65
- * @param config - Configuration options for the Auth SDK
66
- */
67
- constructor(t) {
68
- d(this, "config");
69
- d(this, "state");
70
- if (!t.jwt || typeof t.jwt != "string")
71
- throw new Error(r.INVALID_JWT);
1
+ const s = "production", d = "JWT token is required and must be a string.";
2
+ class c {
3
+ config;
4
+ state;
5
+ scriptLoadingPromise;
6
+ constructor(e) {
7
+ if (!e.jwt || typeof e.jwt != "string")
8
+ throw new Error(d);
72
9
  this.config = {
73
- ...t,
74
- env: t.env || c,
75
- theme: t.theme
10
+ ...e,
11
+ env: e.env || s,
12
+ theme: e.theme
76
13
  }, this.state = {
77
14
  initialized: !1,
78
15
  scriptLoaded: !1,
@@ -81,10 +18,105 @@ class I {
81
18
  };
82
19
  }
83
20
  /**
84
- * Get the current environment
21
+ * Render the widget to a container element
22
+ * @param container - The container element to render the widget into
23
+ * @returns Promise that resolves when the widget is rendered
85
24
  */
86
- get environment() {
87
- return this.config.env || c;
25
+ async render(e) {
26
+ if (!e || !(e instanceof HTMLElement))
27
+ throw new Error(this.errorMessages.INVALID_CONTAINER);
28
+ if (this.state.initialized)
29
+ throw new Error(this.errorMessages.ALREADY_RENDERED);
30
+ try {
31
+ await this.ensureScriptLoaded();
32
+ const r = this.createWebComponent();
33
+ e.innerHTML = "", e.appendChild(r), this.state.container = e, this.state.element = r, this.state.initialized = !0;
34
+ } catch (r) {
35
+ throw console.error("Failed to render widget:", r), r;
36
+ }
37
+ }
38
+ /**
39
+ * Update the configuration of the widget
40
+ * @param config - Partial configuration to update
41
+ * @returns void
42
+ */
43
+ updateConfig(e) {
44
+ if (!this.state.initialized || !this.state.element)
45
+ throw new Error(this.errorMessages.NOT_RENDERED);
46
+ const r = this.state.element;
47
+ Object.entries(e).forEach(([t, n]) => {
48
+ n && (this.config[t] = n, r[t] = n);
49
+ });
50
+ }
51
+ /**
52
+ * Destroy the widget and clean up resources
53
+ */
54
+ destroy() {
55
+ 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);
56
+ }
57
+ /**
58
+ * Check if the widget is currently rendered
59
+ * @returns True if the widget is rendered, false otherwise
60
+ */
61
+ isRendered() {
62
+ return this.state.initialized;
63
+ }
64
+ /**
65
+ * Get the current configuration
66
+ * @returns The current configuration object
67
+ */
68
+ getConfig() {
69
+ return { ...this.config };
70
+ }
71
+ getEnvironment() {
72
+ return this.config.env || s;
73
+ }
74
+ getScriptId() {
75
+ return `${this.webComponentTag}-script-${this.getEnvironment()}`;
76
+ }
77
+ isScriptLoaded() {
78
+ return !!document.getElementById(this.getScriptId());
79
+ }
80
+ getWebComponent() {
81
+ return customElements.get(this.webComponentTag);
82
+ }
83
+ getScriptUrl() {
84
+ return this.scriptUrls[this.getEnvironment()];
85
+ }
86
+ async loadScript() {
87
+ if (!this.isScriptLoaded()) {
88
+ if (this.scriptLoadingPromise)
89
+ return this.scriptLoadingPromise;
90
+ this.scriptLoadingPromise = new Promise((e, r) => {
91
+ const t = document.createElement("script");
92
+ t.id = this.getScriptId(), t.src = this.getScriptUrl(), t.type = "module", t.async = !0, t.onload = () => {
93
+ setTimeout(() => {
94
+ this.getWebComponent() ? e() : r(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
95
+ }, 0);
96
+ }, t.onerror = () => {
97
+ this.scriptLoadingPromise = void 0, r(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
98
+ }, document.head.appendChild(t);
99
+ });
100
+ try {
101
+ await this.scriptLoadingPromise;
102
+ } catch (e) {
103
+ throw this.scriptLoadingPromise = void 0, e;
104
+ }
105
+ return this.scriptLoadingPromise;
106
+ }
107
+ }
108
+ async waitForWebComponent(e = 5e3) {
109
+ if (!this.getWebComponent())
110
+ return new Promise((r, t) => {
111
+ const n = setTimeout(() => {
112
+ t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
113
+ }, e);
114
+ customElements.whenDefined(this.webComponentTag).then(() => {
115
+ clearTimeout(n), r();
116
+ }).catch((a) => {
117
+ clearTimeout(n), t(a);
118
+ });
119
+ });
88
120
  }
89
121
  /**
90
122
  * Load the web component script if not already loaded
@@ -92,68 +124,73 @@ class I {
92
124
  async ensureScriptLoaded() {
93
125
  if (!this.state.scriptLoaded)
94
126
  try {
95
- await D(this.environment), await N(), this.state.scriptLoaded = !0;
96
- } catch (t) {
97
- throw console.error("Failed to load Connect Auth script:", t), t;
127
+ await this.loadScript(), await this.waitForWebComponent(), this.state.scriptLoaded = !0;
128
+ } catch (e) {
129
+ throw console.error("Failed to load Connect script:", e), e;
98
130
  }
99
131
  }
100
- /**
101
- * Create the web component element
102
- */
103
132
  createWebComponent() {
104
- const t = document.createElement(p);
105
- return t.jwt = this.config.jwt, t.theme = this.config.theme, this.config.env && (t.env = this.config.env), this.config.onError && (t.onError = this.config.onError), this.config.onClose && (t.onClose = this.config.onClose), this.config.onDeposit && (t.onDeposit = this.config.onDeposit), this.config.onEvent && (t.onEvent = this.config.onEvent), t;
133
+ const e = document.createElement(this.webComponentTag);
134
+ return Object.entries(this.config).forEach(([r, t]) => {
135
+ t && (e[r] = t);
136
+ }), e;
106
137
  }
138
+ }
139
+ var o;
140
+ (function(i) {
141
+ i.NETWORK_ERROR = "network_error", i.AUTH_ERROR = "auth_error", i.NOT_FOUND_ERROR = "not_found_error", i.VALIDATION_ERROR = "validation_error", i.SERVER_ERROR = "server_error", i.CLIENT_ERROR = "client_error", i.UNKNOWN_ERROR = "unknown_error";
142
+ })(o || (o = {}));
143
+ class h extends c {
144
+ errorMessages = {
145
+ ALREADY_RENDERED: "Auth widget is already rendered. Call destroy() before rendering again.",
146
+ NOT_RENDERED: "Auth widget is not rendered. Call render() first.",
147
+ INVALID_CONTAINER: "Invalid container element provided.",
148
+ SCRIPT_LOAD_FAILED: "Failed to load the Connect Auth script.",
149
+ WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded."
150
+ };
151
+ scriptUrls = {
152
+ sandbox: "https://sdk.sandbox.connect.xyz/auth-web/index.js",
153
+ production: "https://sdk.connect.xyz/auth-web/index.js"
154
+ };
155
+ webComponentTag = "connect-auth";
107
156
  /**
108
157
  * Render the Auth widget to a container element
109
158
  * @param container - The container element to render the widget into
110
159
  * @returns Promise that resolves when the widget is rendered
111
160
  */
112
- async render(t) {
113
- if (!t || !(t instanceof HTMLElement))
114
- throw new Error(r.INVALID_CONTAINER);
115
- if (this.state.initialized)
116
- throw new Error(r.ALREADY_RENDERED);
117
- try {
118
- await this.ensureScriptLoaded();
119
- const e = this.createWebComponent();
120
- t.innerHTML = "", t.appendChild(e), this.state.container = t, this.state.element = e, this.state.initialized = !0;
121
- } catch (e) {
122
- throw console.error("Failed to render Auth widget:", e), e;
123
- }
161
+ render(e) {
162
+ return super.render(e);
124
163
  }
125
164
  /**
126
165
  * Update the configuration of the Auth widget
127
166
  * @param config - Partial configuration to update
128
167
  */
129
- updateConfig(t) {
130
- if (!this.state.initialized || !this.state.element)
131
- throw new Error(r.NOT_RENDERED);
132
- const e = this.state.element;
133
- t.jwt && (this.config.jwt = t.jwt, e.jwt = t.jwt), t.theme !== void 0 && (this.config.theme = t.theme, e.theme = t.theme), t.onError !== void 0 && (this.config.onError = t.onError, e.onError = t.onError), t.onClose !== void 0 && (this.config.onClose = t.onClose, e.onClose = t.onClose), t.onDeposit !== void 0 && (this.config.onDeposit = t.onDeposit, e.onDeposit = t.onDeposit), t.onEvent !== void 0 && (this.config.onEvent = t.onEvent, e.onEvent = t.onEvent);
168
+ updateConfig(e) {
169
+ return super.updateConfig(e);
134
170
  }
135
171
  /**
136
- * Destroy the Auth widget and clean up resources
172
+ * Get the current configuration
173
+ * @returns The current configuration object
137
174
  */
138
- destroy() {
139
- 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);
175
+ getConfig() {
176
+ return super.getConfig();
140
177
  }
141
178
  /**
142
179
  * Check if the Auth widget is currently rendered
143
180
  * @returns True if the widget is rendered, false otherwise
144
181
  */
145
182
  isRendered() {
146
- return this.state.initialized;
183
+ return super.isRendered();
147
184
  }
148
185
  /**
149
- * Get the current configuration
150
- * @returns The current configuration object
186
+ * Destroy the Auth widget and clean up resources
151
187
  */
152
- getConfig() {
153
- return { ...this.config };
188
+ destroy() {
189
+ return super.destroy();
154
190
  }
155
191
  }
156
192
  export {
157
- I as Auth,
158
- I as default
193
+ h as Auth,
194
+ o as ErrorCode,
195
+ h as default
159
196
  };
@@ -1 +1 @@
1
- (function(n,i){typeof exports=="object"&&typeof module<"u"?i(exports):typeof define=="function"&&define.amd?define(["exports"],i):(n=typeof globalThis<"u"?globalThis:n||self,i(n.Auth={}))})(this,function(n){"use strict";var T=Object.defineProperty;var C=(n,i,s)=>i in n?T(n,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):n[i]=s;var l=(n,i,s)=>C(n,typeof i!="symbol"?i+"":i,s);const i={sandbox:"https://sdk.sandbox.connect.xyz/auth-web/index.js",production:"https://sdk.connect.xyz/auth-web/index.js"},s="connect-auth-script",f="connect-auth",u="production",a={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.",INVALID_JWT:"JWT token is required and must be a string."},c=new Map;function p(o){return i[o]}function E(o){return`${s}-${o}`}function w(o){const e=E(o);return!!document.getElementById(e)}async function D(o){const e=E(o);if(w(o))return Promise.resolve();if(c.has(e))return c.get(e);const t=new Promise((d,h)=>{const r=document.createElement("script");r.id=e,r.src=p(o),r.type="module",r.async=!0,r.onload=()=>{setTimeout(()=>{customElements.get("connect-auth")?d():h(new Error(a.WEB_COMPONENT_NOT_DEFINED))},0)},r.onerror=()=>{c.delete(e),h(new Error(`${a.SCRIPT_LOAD_FAILED} (${o})`))},document.head.appendChild(r)});c.set(e,t);try{await t}catch(d){throw c.delete(e),d}return t}async function N(o=5e3){const e="connect-auth";return customElements.get(e)?Promise.resolve():new Promise((t,d)=>{const h=setTimeout(()=>{d(new Error(`Timeout waiting for ${e} to be defined`))},o);customElements.whenDefined(e).then(()=>{clearTimeout(h),t()}).catch(r=>{clearTimeout(h),d(r)})})}class m{constructor(e){l(this,"config");l(this,"state");if(!e.jwt||typeof e.jwt!="string")throw new Error(a.INVALID_JWT);this.config={...e,env:e.env||u,theme:e.theme},this.state={initialized:!1,scriptLoaded:!1,container:null,element:null}}get environment(){return this.config.env||u}async ensureScriptLoaded(){if(!this.state.scriptLoaded)try{await D(this.environment),await N(),this.state.scriptLoaded=!0}catch(e){throw console.error("Failed to load Connect Auth script:",e),e}}createWebComponent(){const e=document.createElement(f);return e.jwt=this.config.jwt,e.theme=this.config.theme,this.config.env&&(e.env=this.config.env),this.config.onError&&(e.onError=this.config.onError),this.config.onClose&&(e.onClose=this.config.onClose),this.config.onDeposit&&(e.onDeposit=this.config.onDeposit),this.config.onEvent&&(e.onEvent=this.config.onEvent),e}async render(e){if(!e||!(e instanceof HTMLElement))throw new Error(a.INVALID_CONTAINER);if(this.state.initialized)throw new Error(a.ALREADY_RENDERED);try{await this.ensureScriptLoaded();const t=this.createWebComponent();e.innerHTML="",e.appendChild(t),this.state.container=e,this.state.element=t,this.state.initialized=!0}catch(t){throw console.error("Failed to render Auth widget:",t),t}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(a.NOT_RENDERED);const t=this.state.element;e.jwt&&(this.config.jwt=e.jwt,t.jwt=e.jwt),e.theme!==void 0&&(this.config.theme=e.theme,t.theme=e.theme),e.onError!==void 0&&(this.config.onError=e.onError,t.onError=e.onError),e.onClose!==void 0&&(this.config.onClose=e.onClose,t.onClose=e.onClose),e.onDeposit!==void 0&&(this.config.onDeposit=e.onDeposit,t.onDeposit=e.onDeposit),e.onEvent!==void 0&&(this.config.onEvent=e.onEvent,t.onEvent=e.onEvent)}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}}}n.Auth=m,n.default=m,Object.defineProperties(n,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
1
+ (function(r,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(r=typeof globalThis<"u"?globalThis:r||self,s(r.Auth={}))})(this,function(r){"use strict";const s="production",d="JWT token is required and must be a string.";class h{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(d);this.config={...e,env:e.env||s,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,o])=>{o&&(this.config[t]=o,i[t]=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||s}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getScriptUrl(){return 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 o=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),i()}).catch(c=>{clearTimeout(o),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}}r.ErrorCode=void 0,function(n){n.NETWORK_ERROR="network_error",n.AUTH_ERROR="auth_error",n.NOT_FOUND_ERROR="not_found_error",n.VALIDATION_ERROR="validation_error",n.SERVER_ERROR="server_error",n.CLIENT_ERROR="client_error",n.UNKNOWN_ERROR="unknown_error"}(r.ErrorCode||(r.ErrorCode={}));class a extends h{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()}}r.Auth=a,r.default=a,Object.defineProperties(r,{__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.2.0",
3
+ "version": "1.7.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",