@zerohash-sdk/fiat-deposits-js 1.1.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/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # @zerohash-sdk/fiat-deposits-js
2
+
3
+ A JavaScript SDK that enables frontend applications to seamlessly integrate with the Connect Fiat Deposits product.
4
+
5
+ Connect Fiat Deposits provides a secure, customizable flow for depositing fiat currency directly within your application.
6
+
7
+ ## Installation
8
+
9
+ ### Via NPM (recommended)
10
+
11
+ ```bash
12
+ npm install @zerohash-sdk/fiat-deposits-js
13
+ ```
14
+
15
+ ```javascript
16
+ import { FiatDeposits } from '@zerohash-sdk/fiat-deposits-js';
17
+ ```
18
+
19
+ ### Via CDN
20
+
21
+ ```html
22
+ <script
23
+ type="module"
24
+ src="https://sdk.connect.xyz/fiat-deposits-web/index.js"
25
+ ></script>
26
+ ```
27
+
28
+ Or import directly in your JavaScript code:
29
+
30
+ ```javascript
31
+ import { FiatDeposits } from 'https://sdk.connect.xyz/fiat-deposits-web/index.js';
32
+ ```
33
+
34
+ ## Getting Started
35
+
36
+ ### 1. Import the FiatDeposits module
37
+
38
+ ```javascript
39
+ import { FiatDeposits } from '@zerohash-sdk/fiat-deposits-js';
40
+ ```
41
+
42
+ ### 2. Initialize and render the widget
43
+
44
+ ```javascript
45
+ const fiatDeposits = new FiatDeposits({
46
+ jwt: 'your-jwt-token',
47
+ env: 'prod',
48
+ theme: 'auto',
49
+ onCompleted: ({ amountDeposited, assetSymbol }) => {
50
+ console.log('Deposit completed:', amountDeposited, assetSymbol);
51
+ },
52
+ onError: ({ errorCode, reason }) => {
53
+ console.error('Error:', errorCode, 'Reason:', reason);
54
+ },
55
+ onClose: () => console.log('Widget closed'),
56
+ onEvent: ({ type, data }) => console.log('Event:', type, data),
57
+ onLoaded: () => console.log('Widget loaded and ready'),
58
+ });
59
+
60
+ await fiatDeposits.render(document.getElementById('fiat-deposits-container'));
61
+
62
+ fiatDeposits.destroy();
63
+ ```
64
+
65
+ ### 2.1 Using TypeScript (optional)
66
+
67
+ ```typescript
68
+ import { FiatDeposits, FiatDepositsConfig } from '@zerohash-sdk/fiat-deposits-js';
69
+
70
+ const config: FiatDepositsConfig = {
71
+ jwt: 'your-jwt-token',
72
+ env: 'cert',
73
+ onCompleted: ({ amountDeposited, assetSymbol }) => {
74
+ console.log(amountDeposited, assetSymbol);
75
+ },
76
+ };
77
+
78
+ const fiatDeposits = new FiatDeposits(config);
79
+ await fiatDeposits.render(document.getElementById('container')!);
80
+ ```
81
+
82
+ ## API Reference
83
+
84
+ ### Configuration
85
+
86
+ | Prop | Type | Required | Default | Description |
87
+ | ------------- | -------------------------------------------- | -------- | -------- | ----------------------------------------------------- |
88
+ | `jwt` | `string` | Yes | - | JWT token for authentication with Connect |
89
+ | `env` | `"prod" \| "cert" \| "dev" \| "local"` | No | `"prod"` | Target environment |
90
+ | `theme` | `"auto" \| "light" \| "dark"` | No | `"auto"` | Theme mode for the interface |
91
+ | `onCompleted` | `({ amountDeposited, assetSymbol }) => void` | No | - | Callback when the deposit flow completes successfully |
92
+ | `onError` | `({ errorCode, reason }) => void` | No | - | Callback for error events |
93
+ | `onClose` | `() => void` | No | - | Callback when the widget is closed |
94
+ | `onEvent` | `({ type, data }) => void` | No | - | Callback for general events |
95
+ | `onLoaded` | `() => void` | No | - | Callback when the widget is loaded and ready |
96
+
97
+ ### Methods
98
+
99
+ #### `render(container: HTMLElement): Promise<void>`
100
+
101
+ #### `updateConfig(config: Partial<FiatDepositsConfig>): void`
102
+
103
+ #### `destroy(): void`
104
+
105
+ #### `isRendered(): boolean`
106
+
107
+ #### `getConfig(): FiatDepositsConfig`
108
+
109
+ ## Browser Support
110
+
111
+ - Chrome/Edge 90+
112
+ - Firefox 88+
113
+ - Safari 14+
114
+ - All modern browsers with Web Components support
115
+
116
+ ## More Information & Support
117
+
118
+ For comprehensive documentation or support about Connect, visit our [Documentation Page](https://docs.zerohash.com/).
@@ -0,0 +1,463 @@
1
+ /**
2
+ * Generic app event structure
3
+ * @template TType - Event type string
4
+ * @template TData - Event data payload
5
+ */
6
+ declare type AppEvent<TType extends string = string, TData = Record<string, unknown>> = {
7
+ /** The type of event that occurred */
8
+ type: TType;
9
+ /** Data associated with the event */
10
+ data: TData;
11
+ };
12
+
13
+ /**
14
+ * Configuration options for the SDK
15
+ */
16
+ declare interface BaseConfig<TEvent = AppEvent> extends CommonCallbacks<TEvent> {
17
+ /**
18
+ * JWT token used for authentication
19
+ */
20
+ jwt: string;
21
+
22
+ /**
23
+ * Target environment
24
+ * @default 'production'
25
+ */
26
+ env?: Environment;
27
+
28
+ /**
29
+ * Theme mode
30
+ * @default 'auto'
31
+ *
32
+ * Available themes:
33
+ * - `'auto'` - Automatically detect system preference (light/dark mode)
34
+ * - `'light'` - Force light theme
35
+ * - `'dark'` - Force dark theme
36
+ */
37
+ theme?: Theme;
38
+ }
39
+
40
+ declare type BaseErrorMessageKeys =
41
+ | 'ALREADY_RENDERED'
42
+ | 'NOT_RENDERED'
43
+ | 'INVALID_CONTAINER'
44
+ | 'SCRIPT_LOAD_FAILED'
45
+ | 'WEB_COMPONENT_NOT_DEFINED';
46
+
47
+ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig> {
48
+ private config: Config;
49
+ private state: SdkState;
50
+ private scriptLoadingPromise?: Promise<void>;
51
+
52
+ protected abstract errorMessages: Record<BaseErrorMessageKeys, string>;
53
+ protected abstract scriptUrls: Record<string, string>;
54
+ protected abstract webComponentTag: string;
55
+
56
+ constructor(config: Config) {
57
+ if (!config.jwt || typeof config.jwt !== 'string') {
58
+ throw new Error(INVALID_JWT_ERROR_MESSAGE);
59
+ }
60
+
61
+ this.config = {
62
+ ...config,
63
+ env: config.env || DEFAULT_ENVIRONMENT,
64
+ theme: config.theme,
65
+ };
66
+
67
+ this.state = {
68
+ initialized: false,
69
+ scriptLoaded: false,
70
+ container: null,
71
+ element: null,
72
+ };
73
+ }
74
+
75
+ /**
76
+ * Render the widget to a container element
77
+ * @param container - The container element to render the widget into
78
+ * @returns Promise that resolves when the widget is rendered
79
+ */
80
+ async render(container: HTMLElement): Promise<void> {
81
+ // Validate container
82
+ if (!container || !(container instanceof HTMLElement)) {
83
+ throw new Error(this.errorMessages.INVALID_CONTAINER);
84
+ }
85
+
86
+ // Check if already rendered
87
+ if (this.state.initialized) {
88
+ throw new Error(this.errorMessages.ALREADY_RENDERED);
89
+ }
90
+
91
+ try {
92
+ // Ensure script is loaded
93
+ await this.ensureScriptLoaded();
94
+
95
+ // Create and append the web component
96
+ const element = this.createWebComponent();
97
+
98
+ // Clear the container and append the element
99
+ container.innerHTML = '';
100
+ container.appendChild(element);
101
+
102
+ // Update state
103
+ this.state.container = container;
104
+ this.state.element = element;
105
+ this.state.initialized = true;
106
+ } catch (error) {
107
+ console.error('Failed to render widget:', error);
108
+ throw error;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Update the configuration of the widget
114
+ * @param config - Partial configuration to update
115
+ * @returns void
116
+ */
117
+ updateConfig(config: Partial<Config>): void {
118
+ if (!this.state.initialized || !this.state.element) {
119
+ throw new Error(this.errorMessages.NOT_RENDERED);
120
+ }
121
+
122
+ const element = this.state.element as SdkElement<Config>;
123
+
124
+ Object.entries(config).forEach(([key, value]) => {
125
+ if (value) {
126
+ this.config[key as keyof Config] = value;
127
+ element[key as keyof Config] = value;
128
+ }
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Destroy the widget and clean up resources
134
+ */
135
+ destroy(): void {
136
+ if (!this.state.initialized) {
137
+ return; // Nothing to destroy
138
+ }
139
+
140
+ // Remove the element from the container
141
+ if (this.state.element && this.state.element.parentNode) {
142
+ this.state.element.parentNode.removeChild(this.state.element);
143
+ }
144
+
145
+ // Clear the container
146
+ if (this.state.container) {
147
+ this.state.container.innerHTML = '';
148
+ }
149
+
150
+ // Reset state
151
+ this.state.container = null;
152
+ this.state.element = null;
153
+ this.state.initialized = false;
154
+ }
155
+
156
+ /**
157
+ * Check if the widget is currently rendered
158
+ * @returns True if the widget is rendered, false otherwise
159
+ */
160
+ isRendered(): boolean {
161
+ return this.state.initialized;
162
+ }
163
+
164
+ /**
165
+ * Get the current configuration
166
+ * @returns The current configuration object
167
+ */
168
+ getConfig(): Readonly<Config> {
169
+ return { ...this.config };
170
+ }
171
+
172
+ private getEnvironment(): Environment {
173
+ return this.config.env || DEFAULT_ENVIRONMENT;
174
+ }
175
+
176
+ private getScriptId() {
177
+ return `${this.webComponentTag}-script-${this.getEnvironment()}`;
178
+ }
179
+
180
+ private isScriptLoaded() {
181
+ return !!document.getElementById(this.getScriptId());
182
+ }
183
+
184
+ private getWebComponent() {
185
+ return customElements.get(this.webComponentTag);
186
+ }
187
+
188
+ private getScriptUrl() {
189
+ // Support local development with Vite
190
+ if (typeof import.meta !== 'undefined' && import.meta.env?.['VITE_INTERNAL_BUILD'] === 'true') {
191
+ return import.meta.env['VITE_SCRIPT_URL'] || this.scriptUrls[this.getEnvironment()];
192
+ }
193
+
194
+ return this.scriptUrls[this.getEnvironment()];
195
+ }
196
+
197
+ private async loadScript() {
198
+ if (this.isScriptLoaded()) {
199
+ return;
200
+ }
201
+
202
+ if (this.scriptLoadingPromise) {
203
+ return this.scriptLoadingPromise;
204
+ }
205
+
206
+ this.scriptLoadingPromise = new Promise<void>((resolve, reject) => {
207
+ const script = document.createElement('script');
208
+ script.id = this.getScriptId();
209
+ script.src = this.getScriptUrl();
210
+ script.type = 'module';
211
+ script.async = true;
212
+
213
+ script.onload = () => {
214
+ setTimeout(() => {
215
+ if (this.getWebComponent()) {
216
+ resolve();
217
+ } else {
218
+ reject(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
219
+ }
220
+ }, 0);
221
+ };
222
+
223
+ script.onerror = () => {
224
+ this.scriptLoadingPromise = undefined;
225
+ reject(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
226
+ };
227
+
228
+ document.head.appendChild(script);
229
+ });
230
+
231
+ try {
232
+ await this.scriptLoadingPromise;
233
+ } catch (error) {
234
+ this.scriptLoadingPromise = undefined;
235
+ throw error;
236
+ }
237
+
238
+ return this.scriptLoadingPromise;
239
+ }
240
+
241
+ private async waitForWebComponent(timeout = 5000) {
242
+ if (this.getWebComponent()) {
243
+ return;
244
+ }
245
+
246
+ return new Promise<void>((resolve, reject) => {
247
+ const timeoutId = setTimeout(() => {
248
+ reject(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
249
+ }, timeout);
250
+
251
+ customElements
252
+ .whenDefined(this.webComponentTag)
253
+ .then(() => {
254
+ clearTimeout(timeoutId);
255
+ resolve();
256
+ })
257
+ .catch((error) => {
258
+ clearTimeout(timeoutId);
259
+ reject(error);
260
+ });
261
+ });
262
+ }
263
+
264
+ /**
265
+ * Load the web component script if not already loaded
266
+ */
267
+ protected async ensureScriptLoaded(): Promise<void> {
268
+ if (this.state.scriptLoaded) {
269
+ return;
270
+ }
271
+
272
+ try {
273
+ await this.loadScript();
274
+ await this.waitForWebComponent();
275
+ this.state.scriptLoaded = true;
276
+ } catch (error) {
277
+ console.error('Failed to load Connect script:', error);
278
+ throw error;
279
+ }
280
+ }
281
+
282
+ private createWebComponent() {
283
+ const element = document.createElement(this.webComponentTag) as SdkElement<Config>;
284
+
285
+ Object.entries(this.config).forEach(([key, value]) => {
286
+ if (value) {
287
+ element[key as keyof Config] = value;
288
+ }
289
+ });
290
+
291
+ return element;
292
+ }
293
+ }
294
+
295
+ /**
296
+ * Common callback function types shared across all Connect apps
297
+ * @template TEvent - The event type for onEvent callback
298
+ */
299
+ declare type CommonCallbacks<TEvent = AppEvent> = {
300
+ /** Called when an error occurs */
301
+ onError?: (error: ErrorPayload) => void;
302
+ /** Called when the component is closed */
303
+ onClose?: () => void;
304
+ /** Called when a general event occurs */
305
+ onEvent?: (event: TEvent) => void;
306
+ /** Called when the widget has loaded and is ready */
307
+ onLoaded?: () => void;
308
+ };
309
+
310
+ export declare type ConnectFiatDepositsElement = SdkElement<FiatDepositsConfig>;
311
+
312
+ /**
313
+ * Environment configuration for the SDK
314
+ */
315
+ declare type Environment = 'local' | 'dev' | 'cert' | 'prod' | 'sandbox' | 'production';
316
+
317
+ /**
318
+ * Generic error codes for all Connect applications
319
+ */
320
+ declare enum ErrorCode {
321
+ /** Network connectivity error */
322
+ NETWORK_ERROR = 'network_error',
323
+ /** Authentication or session expired error */
324
+ AUTH_ERROR = 'auth_error',
325
+ /** Resource not found error */
326
+ NOT_FOUND_ERROR = 'not_found_error',
327
+ /** Validation error from user input */
328
+ VALIDATION_ERROR = 'validation_error',
329
+ /** Server error (5xx) */
330
+ SERVER_ERROR = 'server_error',
331
+ /** Client error (4xx) */
332
+ CLIENT_ERROR = 'client_error',
333
+ /** Unknown or unexpected error */
334
+ UNKNOWN_ERROR = 'unknown_error',
335
+ }
336
+
337
+ /**
338
+ * Generic error payload structure for error callbacks
339
+ */
340
+ declare type ErrorPayload = {
341
+ /** Error code indicating the type of error */
342
+ errorCode: ErrorCode;
343
+ /** Human-readable reason for the error */
344
+ reason: string;
345
+ };
346
+
347
+ /**
348
+ * FiatDeposits SDK class for programmatic control of the Connect Fiat Deposits widget.
349
+ *
350
+ * Renders the `zerohash-fiat-deposits` web component, which handles the iframe
351
+ * and postMessage communication internally.
352
+ *
353
+ * @example
354
+ * ```javascript
355
+ * const fiatDeposits = new FiatDeposits({
356
+ * jwt: 'your-jwt-token',
357
+ * env: 'prod',
358
+ * theme: 'auto',
359
+ * onCompleted: ({ amountDeposited }) => console.log('Deposited', amountDeposited),
360
+ * onClose: () => console.log('Closed'),
361
+ * onError: ({ errorCode, reason }) => console.error(errorCode, reason),
362
+ * });
363
+ *
364
+ * // Render to a container
365
+ * await fiatDeposits.render(document.getElementById('fiat-deposits-container'));
366
+ *
367
+ * // Update configuration
368
+ * fiatDeposits.updateConfig({ jwt: 'new-token', theme: 'dark' });
369
+ *
370
+ * // Clean up
371
+ * fiatDeposits.destroy();
372
+ * ```
373
+ */
374
+ export declare class FiatDeposits extends BaseJsSdk<FiatDepositsConfig> {
375
+ protected errorMessages: {
376
+ ALREADY_RENDERED: string;
377
+ NOT_RENDERED: string;
378
+ INVALID_CONTAINER: string;
379
+ SCRIPT_LOAD_FAILED: string;
380
+ WEB_COMPONENT_NOT_DEFINED: string;
381
+ };
382
+ protected scriptUrls: {
383
+ local: string;
384
+ dev: string;
385
+ cert: string;
386
+ prod: string;
387
+ sandbox: string;
388
+ production: string;
389
+ };
390
+ protected webComponentTag: string;
391
+ /**
392
+ * Render the FiatDeposits widget to a container element
393
+ * @param container - The container element to render the widget into
394
+ * @returns Promise that resolves when the widget is rendered
395
+ */
396
+ render(container: HTMLElement): Promise<void>;
397
+ /**
398
+ * Update the configuration of the FiatDeposits widget
399
+ * @param config - Partial configuration to update
400
+ */
401
+ updateConfig(config: Partial<FiatDepositsConfig>): void;
402
+ /**
403
+ * Get the current configuration
404
+ * @returns The current configuration object
405
+ */
406
+ getConfig(): Readonly<FiatDepositsConfig>;
407
+ /**
408
+ * Check if the FiatDeposits widget is currently rendered
409
+ * @returns True if the widget is rendered, false otherwise
410
+ */
411
+ isRendered(): boolean;
412
+ /**
413
+ * Destroy the FiatDeposits widget and clean up resources
414
+ */
415
+ destroy(): void;
416
+ }
417
+
418
+ declare type FiatDepositsCallbacks = CommonCallbacks<FiatDepositsEvent> & {
419
+ /** Called when the flow is successfully completed */
420
+ onCompleted?: (data: FiatDepositsCompletedData) => void;
421
+ };
422
+
423
+ declare type FiatDepositsCompletedData = {
424
+ amountDeposited: string;
425
+ assetSymbol: string;
426
+ };
427
+
428
+ export declare interface FiatDepositsConfig extends BaseConfig<FiatDepositsEvent>, FiatDepositsCallbacks {
429
+ }
430
+
431
+ declare type FiatDepositsEvent = AppEvent<FiatDepositsEventType>;
432
+
433
+ declare type FiatDepositsEventType = string;
434
+
435
+ /**
436
+ * Generic HTMLElement representing a web component with custom config
437
+ */
438
+ declare type SdkElement<Config extends BaseConfig<never>> = HTMLElement & Config;
439
+
440
+ /**
441
+ * Internal state of the SDK
442
+ */
443
+ declare interface SdkState {
444
+ /** Whether the SDK is initialized */
445
+ initialized: boolean;
446
+ /** Whether the web component script is loaded */
447
+ scriptLoaded: boolean;
448
+ /** The container element where the widget is rendered */
449
+ container: HTMLElement | null;
450
+ /** The web component element */
451
+ element: HTMLElement | null;
452
+ }
453
+
454
+ /**
455
+ * Theme configuration for the SDK
456
+ *
457
+ * - `"auto"` - Automatically detect system preference (light/dark mode)
458
+ * - `"light"` - Force light theme
459
+ * - `"dark"` - Force dark theme
460
+ */
461
+ declare type Theme = 'auto' | 'light' | 'dark';
462
+
463
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,198 @@
1
+ const n = "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);
9
+ this.config = {
10
+ ...e,
11
+ env: e.env || n,
12
+ theme: e.theme
13
+ }, this.state = {
14
+ initialized: !1,
15
+ scriptLoaded: !1,
16
+ container: null,
17
+ element: null
18
+ };
19
+ }
20
+ /**
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
24
+ */
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 i = this.createWebComponent();
33
+ e.innerHTML = "", e.appendChild(i), this.state.container = e, this.state.element = i, this.state.initialized = !0;
34
+ } catch (i) {
35
+ throw console.error("Failed to render widget:", i), i;
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 i = this.state.element;
47
+ Object.entries(e).forEach(([t, s]) => {
48
+ s && (this.config[t] = s, i[t] = s);
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 || n;
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, i) => {
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() : i(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
95
+ }, 0);
96
+ }, t.onerror = () => {
97
+ this.scriptLoadingPromise = void 0, i(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((i, t) => {
111
+ const s = setTimeout(() => {
112
+ t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
113
+ }, e);
114
+ customElements.whenDefined(this.webComponentTag).then(() => {
115
+ clearTimeout(s), i();
116
+ }).catch((a) => {
117
+ clearTimeout(s), t(a);
118
+ });
119
+ });
120
+ }
121
+ /**
122
+ * Load the web component script if not already loaded
123
+ */
124
+ async ensureScriptLoaded() {
125
+ if (!this.state.scriptLoaded)
126
+ try {
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;
130
+ }
131
+ }
132
+ createWebComponent() {
133
+ const e = document.createElement(this.webComponentTag);
134
+ return Object.entries(this.config).forEach(([i, t]) => {
135
+ t && (e[i] = t);
136
+ }), e;
137
+ }
138
+ }
139
+ var o;
140
+ (function(r) {
141
+ 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";
142
+ })(o || (o = {}));
143
+ class h extends c {
144
+ errorMessages = {
145
+ ALREADY_RENDERED: "FiatDeposits widget is already rendered. Call destroy() before rendering again.",
146
+ NOT_RENDERED: "FiatDeposits widget is not rendered. Call render() first.",
147
+ INVALID_CONTAINER: "Invalid container element provided.",
148
+ SCRIPT_LOAD_FAILED: "Failed to load the Connect FiatDeposits script.",
149
+ WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded."
150
+ };
151
+ scriptUrls = {
152
+ local: "http://localhost:5173/fiat-deposits-web/index.js",
153
+ dev: "https://connect-sdk.dev.0hash.com/fiat-deposits-web/index.js",
154
+ cert: "https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",
155
+ prod: "https://sdk.connect.xyz/fiat-deposits-web/index.js",
156
+ sandbox: "https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",
157
+ production: "https://sdk.connect.xyz/fiat-deposits-web/index.js"
158
+ };
159
+ webComponentTag = "zerohash-fiat-deposits";
160
+ /**
161
+ * Render the FiatDeposits widget to a container element
162
+ * @param container - The container element to render the widget into
163
+ * @returns Promise that resolves when the widget is rendered
164
+ */
165
+ render(e) {
166
+ return super.render(e);
167
+ }
168
+ /**
169
+ * Update the configuration of the FiatDeposits widget
170
+ * @param config - Partial configuration to update
171
+ */
172
+ updateConfig(e) {
173
+ return super.updateConfig(e);
174
+ }
175
+ /**
176
+ * Get the current configuration
177
+ * @returns The current configuration object
178
+ */
179
+ getConfig() {
180
+ return super.getConfig();
181
+ }
182
+ /**
183
+ * Check if the FiatDeposits widget is currently rendered
184
+ * @returns True if the widget is rendered, false otherwise
185
+ */
186
+ isRendered() {
187
+ return super.isRendered();
188
+ }
189
+ /**
190
+ * Destroy the FiatDeposits widget and clean up resources
191
+ */
192
+ destroy() {
193
+ return super.destroy();
194
+ }
195
+ }
196
+ export {
197
+ h as FiatDeposits
198
+ };
@@ -0,0 +1 @@
1
+ (function(r,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(r=typeof globalThis<"u"?globalThis:r||self,n(r.FiatDeposits={}))})(this,(function(r){"use strict";const n="production",d="JWT token is required and must be a string.";class c{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(d);this.config={...e,env:e.env||n,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||n}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(p=>{clearTimeout(o),t(p)})})}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}}var a;(function(s){s.NETWORK_ERROR="network_error",s.AUTH_ERROR="auth_error",s.NOT_FOUND_ERROR="not_found_error",s.VALIDATION_ERROR="validation_error",s.SERVER_ERROR="server_error",s.CLIENT_ERROR="client_error",s.UNKNOWN_ERROR="unknown_error"})(a||(a={}));class h extends c{errorMessages={ALREADY_RENDERED:"FiatDeposits widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"FiatDeposits widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect FiatDeposits script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/fiat-deposits-web/index.js",dev:"https://connect-sdk.dev.0hash.com/fiat-deposits-web/index.js",cert:"https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",prod:"https://sdk.connect.xyz/fiat-deposits-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",production:"https://sdk.connect.xyz/fiat-deposits-web/index.js"};webComponentTag="zerohash-fiat-deposits";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.FiatDeposits=h,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@zerohash-sdk/fiat-deposits-js",
3
+ "version": "1.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "license": "MIT",
10
+ "exports": {
11
+ "./package.json": "./package.json",
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "default": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "!**/*.tsbuildinfo"
21
+ ],
22
+ "nx": {
23
+ "name": "fiat-deposits-js"
24
+ }
25
+ }