@connect-xyz/withdraw-js 0.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,226 @@
1
+ # @connect-xyz/withdraw-js
2
+
3
+ A JavaScript SDK that enables frontend applications to seamlessly integrate with the Connect Withdraw product.
4
+
5
+ Connect Withdraw provides a secure way for end users to withdraw their funds. Learn more in the [Connect Withdraw documentation](https://docs.zerohash.com/docs/withdraw).
6
+
7
+ ## Installation
8
+
9
+ ### Via NPM (recommended)
10
+
11
+ ```bash
12
+ npm install @connect-xyz/withdraw-js
13
+ ```
14
+
15
+ ```javascript
16
+ import { Withdraw } from '@connect-xyz/withdraw-js';
17
+ ```
18
+
19
+ ### Via CDN
20
+
21
+ You can import the script in your index file and use the Withdraw class provided by it.
22
+
23
+ ```html
24
+ <script
25
+ type="module"
26
+ src="https://sdk.connect.xyz/withdraw-js/index.js"
27
+ ></script>
28
+ ```
29
+
30
+ Or you can directly import in your javascript code.
31
+
32
+ ```javascript
33
+ import { Withdraw } from 'https://sdk.connect.xyz/withdraw-js/index.js';
34
+ ```
35
+
36
+ ## Getting Started
37
+
38
+ Follow these simple steps to integrate Connect Withdraw into your frontend application:
39
+
40
+ ### 1. Import the Withdraw module
41
+
42
+ ```tsx
43
+ import { Withdraw } from '@connect-xyz/withdraw-js';
44
+ ```
45
+
46
+ ### 1.1 Or import via CDN
47
+
48
+ ```javascript
49
+ import { Withdraw } from 'https://sdk.connect.xyz/withdraw-js/index.js';
50
+ ```
51
+
52
+ ### 2. Initialize the Withdraw module into Your App
53
+
54
+ ```javascript
55
+ // Create a Withdraw instance with configuration
56
+ const withdraw = new Withdraw({
57
+ jwt: 'your-jwt-token',
58
+ env: 'production', // or 'sandbox'
59
+ onError: ({ error, reason }) => {
60
+ console.error('Withdraw error:', error, 'Reason:', reason);
61
+ },
62
+ onClose: () => {
63
+ console.log('Withdraw widget closed');
64
+ },
65
+ onWithdrawal: ({ data }) => {
66
+ console.log('Withdrawal completed:', data);
67
+ },
68
+ onEvent: ({ type, data }) => {
69
+ console.log('Event received:', type, data);
70
+ },
71
+ });
72
+
73
+ // Render the widget to a container element
74
+ const container = document.getElementById('withdraw-container');
75
+ await withdraw.render(container);
76
+
77
+ // Update configuration dynamically
78
+ withdraw.updateConfig({
79
+ jwt: 'new-jwt-token',
80
+ onError: newErrorHandler,
81
+ });
82
+
83
+ // Check if rendered
84
+ if (withdraw.isRendered()) {
85
+ console.log('Widget is active');
86
+ }
87
+
88
+ // Clean up when done
89
+ withdraw.destroy();
90
+ ```
91
+
92
+ ## API Reference
93
+
94
+ ### Withdraw widget Props
95
+
96
+ | Prop | Type | Required | Default | Description |
97
+ | -------------- | --------------------------------- | -------- | -------------- | -------------------------------------------------- |
98
+ | `jwt` | `string` | Yes | - | JWT token for authentication with Connect Withdraw |
99
+ | `env` | `"production" \| "sandbox"` | No | `"production"` | Target environment |
100
+ | `onError` | `({ errorCode, reason }) => void` | No | - | Callback for error events |
101
+ | `onClose` | `() => void` | No | - | Callback when the widget is closed |
102
+ | `onWithdrawal` | `({ data }) => void` | No | - | Callback for withdrawal completed |
103
+ | `onEvent` | `({ type, data }) => void` | No | - | Callback for general events |
104
+
105
+ ### Constructor
106
+
107
+ ```javascript
108
+ new Withdraw(config: WithdrawConfig)
109
+ ```
110
+
111
+ Creates a new Withdraw instance with the provided configuration.
112
+
113
+ #### Parameters
114
+
115
+ - `config` (WithdrawConfig): Configuration object
116
+ - `jwt` (string, required): JWT token for authentication
117
+ - `env` (string, optional): Environment - 'production' (default) or 'sandbox'
118
+ - `onError` (function, optional): Error callback
119
+ - `onClose` (function, optional): Close callback
120
+ - `onWithdrawal` (function, optional): Withdrawal callback
121
+ - `onEvent` (function, optional): General event callback
122
+
123
+ ### Methods
124
+
125
+ #### `render(container: HTMLElement): Promise<void>`
126
+
127
+ Renders the Withdraw widget to the specified container element.
128
+
129
+ ```javascript
130
+ await withdraw.render(document.getElementById('withdraw-container'));
131
+ ```
132
+
133
+ #### `updateConfig(config: Partial<WithdrawConfig>): void`
134
+
135
+ Updates the configuration of an already rendered widget.
136
+
137
+ ```javascript
138
+ withdraw.updateConfig({
139
+ jwt: 'new-token',
140
+ onError: newErrorHandler,
141
+ });
142
+ ```
143
+
144
+ #### `destroy(): void`
145
+
146
+ Removes the widget from the DOM and cleans up resources.
147
+
148
+ ```javascript
149
+ withdraw.destroy();
150
+ ```
151
+
152
+ #### `isRendered(): boolean`
153
+
154
+ Returns whether the widget is currently rendered.
155
+
156
+ ```javascript
157
+ if (withdraw.isRendered()) {
158
+ // Widget is active
159
+ }
160
+ ```
161
+
162
+ #### `getConfig(): WithdrawConfig`
163
+
164
+ Returns a copy of the current configuration.
165
+
166
+ ```javascript
167
+ const config = withdraw.getConfig();
168
+ console.log('Current JWT:', config.jwt);
169
+ ```
170
+
171
+ ## Callback Functions
172
+
173
+ For detailed information about callback events and their payloads, see the [Withdraw SDK Callbacks documentation](https://docs.zerohash.com/docs/front-end-callbacks).
174
+
175
+ ### onError
176
+
177
+ Called when an error occurs in the Withdraw widget.
178
+
179
+ ```javascript
180
+ onError: ({ errorCode, reason }) => {
181
+ // errorCode: Error code
182
+ // reason: Human-readable error description
183
+ };
184
+ ```
185
+
186
+ ### onClose
187
+
188
+ Called when the Withdraw widget is closed by the user.
189
+
190
+ ```javascript
191
+ onClose: () => {
192
+ // Handle close event
193
+ };
194
+ ```
195
+
196
+ ### onWithdrawal
197
+
198
+ Called when a withdrawal is completed.
199
+
200
+ ```javascript
201
+ onWithdrawal: ({ data }) => {
202
+ // data: Object containing withdrawal details
203
+ };
204
+ ```
205
+
206
+ ### onEvent
207
+
208
+ Called for general events from the Withdraw widget.
209
+
210
+ ```javascript
211
+ onEvent: ({ type, data }) => {
212
+ // type: Event type string
213
+ // data: Event-specific data object
214
+ };
215
+ ```
216
+
217
+ ## Browser Support
218
+
219
+ - Chrome/Edge 90+
220
+ - Firefox 88+
221
+ - Safari 14+
222
+ - All modern browsers with Web Components support
223
+
224
+ ## More Information & Support
225
+
226
+ For comprehensive documentation or support about Connect Withdraw, visit our [Documentation Page](https://docs.zerohash.com/).
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Connect Withdraw Javascript SDK
3
+ *
4
+ * A programmatic JavaScript SDK for integrating the Connect Withdraw widget
5
+ * into web applications without requiring HTML custom elements.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+
10
+ /**
11
+ * Generic app event structure
12
+ * @template TType - Event type string
13
+ * @template TData - Event data payload
14
+ */
15
+ declare type AppEvent<TType extends string = string, TData = Record<string, unknown>> = {
16
+ /** The type of event that occurred */
17
+ type: TType;
18
+ /** Data associated with the event */
19
+ data: TData;
20
+ };
21
+
22
+ /**
23
+ * Configuration options for the SDK
24
+ */
25
+ declare interface BaseConfig<TEvent = AppEvent> extends CommonCallbacks<TEvent> {
26
+ /**
27
+ * JWT token used for authentication
28
+ */
29
+ jwt: string;
30
+ /**
31
+ * Target environment
32
+ * @default 'production'
33
+ */
34
+ env?: Environment;
35
+ /**
36
+ * Theme mode
37
+ * @default 'auto'
38
+ *
39
+ * Available themes:
40
+ * - `'auto'` - Automatically detect system preference (light/dark mode)
41
+ * - `'light'` - Force light theme
42
+ * - `'dark'` - Force dark theme
43
+ */
44
+ theme?: Theme;
45
+ }
46
+
47
+ declare type BaseErrorMessageKeys = 'ALREADY_RENDERED' | 'NOT_RENDERED' | 'INVALID_CONTAINER' | 'SCRIPT_LOAD_FAILED' | 'WEB_COMPONENT_NOT_DEFINED';
48
+
49
+ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig> {
50
+ private config;
51
+ private state;
52
+ private scriptLoadingPromise?;
53
+ protected abstract errorMessages: Record<BaseErrorMessageKeys, string>;
54
+ protected abstract scriptUrls: Record<Environment, string>;
55
+ protected abstract webComponentTag: string;
56
+ constructor(config: Config);
57
+ /**
58
+ * Render the widget to a container element
59
+ * @param container - The container element to render the widget into
60
+ * @returns Promise that resolves when the widget is rendered
61
+ */
62
+ render(container: HTMLElement): Promise<void>;
63
+ /**
64
+ * Update the configuration of the widget
65
+ * @param config - Partial configuration to update
66
+ * @returns void
67
+ */
68
+ updateConfig(config: Partial<Config>): void;
69
+ /**
70
+ * Destroy the widget and clean up resources
71
+ */
72
+ destroy(): void;
73
+ /**
74
+ * Check if the widget is currently rendered
75
+ * @returns True if the widget is rendered, false otherwise
76
+ */
77
+ isRendered(): boolean;
78
+ /**
79
+ * Get the current configuration
80
+ * @returns The current configuration object
81
+ */
82
+ getConfig(): Readonly<Config>;
83
+ private getEnvironment;
84
+ private getScriptId;
85
+ private isScriptLoaded;
86
+ private getWebComponent;
87
+ private getScriptUrl;
88
+ private loadScript;
89
+ private waitForWebComponent;
90
+ /**
91
+ * Load the web component script if not already loaded
92
+ */
93
+ protected ensureScriptLoaded(): Promise<void>;
94
+ private createWebComponent;
95
+ }
96
+
97
+ /**
98
+ * Common callback function types shared across all Connect apps
99
+ * @template TEvent - The event type for onEvent callback
100
+ */
101
+ declare type CommonCallbacks<TEvent = AppEvent> = {
102
+ /** Called when an error occurs */
103
+ onError?: (error: ErrorPayload) => void;
104
+ /** Called when the component is closed */
105
+ onClose?: () => void;
106
+ /** Called when a general event occurs */
107
+ onEvent?: (event: TEvent) => void;
108
+ };
109
+
110
+ export declare type ConnectWithdrawElement = SdkElement<WithdrawConfig>;
111
+
112
+ /**
113
+ * Environment configuration for the SDK
114
+ */
115
+ export declare type Environment = 'sandbox' | 'production';
116
+
117
+ /**
118
+ * Generic error codes for all Connect applications
119
+ */
120
+ export declare enum ErrorCode {
121
+ /** Network connectivity error */
122
+ NETWORK_ERROR = 'network_error',
123
+ /** Authentication or session expired error */
124
+ AUTH_ERROR = 'auth_error',
125
+ /** Resource not found error */
126
+ NOT_FOUND_ERROR = 'not_found_error',
127
+ /** Validation error from user input */
128
+ VALIDATION_ERROR = 'validation_error',
129
+ /** Server error (5xx) */
130
+ SERVER_ERROR = 'server_error',
131
+ /** Client error (4xx) */
132
+ CLIENT_ERROR = 'client_error',
133
+ /** Unknown or unexpected error */
134
+ UNKNOWN_ERROR = 'unknown_error',
135
+ }
136
+
137
+ /**
138
+ * Generic error payload structure for error callbacks
139
+ */
140
+ declare type ErrorPayload = {
141
+ /** Error code indicating the type of error */
142
+ errorCode: ErrorCode;
143
+ /** Human-readable reason for the error */
144
+ reason: string;
145
+ };
146
+
147
+ /**
148
+ * Generic HTMLElement representing a web component with custom config
149
+ */
150
+ declare type SdkElement<Config extends BaseConfig<never>> = HTMLElement & Config;
151
+
152
+ /**
153
+ * Theme configuration for the SDK
154
+ *
155
+ * - `"auto"` - Automatically detect system preference (light/dark mode)
156
+ * - `"light"` - Force light theme
157
+ * - `"dark"` - Force dark theme
158
+ */
159
+ declare type Theme = 'auto' | 'light' | 'dark';
160
+
161
+ /**
162
+ * Withdraw SDK class for programmatic control of the Connect Withdraw widget
163
+ *
164
+ * @example
165
+ * ```javascript
166
+ * const withdraw = new Withdraw({
167
+ * jwt: 'your-jwt-token',
168
+ * env: 'production',
169
+ * theme: 'dark', // 'auto' | 'light' | 'dark'
170
+ * onError: ({ error, reason }) => console.error(error, reason),
171
+ * onClose: () => console.log('Withdraw closed'),
172
+ * onWithdrawal: ({ data }) => console.log('Withdrawal', data),
173
+ * onEvent: ({ type, data }) => console.log('Event', type, data)
174
+ * });
175
+ *
176
+ * // Render to a container
177
+ * await withdraw.render(document.getElementById('withdraw-container'))
178
+ *
179
+ * // Update configuration
180
+ * withdraw.updateConfig({ jwt: 'new-token', theme: 'light' })
181
+ *
182
+ * // Clean up
183
+ * withdraw.destroy()
184
+ * ```
185
+ */
186
+ declare class Withdraw extends BaseJsSdk<WithdrawConfig> {
187
+ protected errorMessages: {
188
+ ALREADY_RENDERED: string;
189
+ NOT_RENDERED: string;
190
+ INVALID_CONTAINER: string;
191
+ SCRIPT_LOAD_FAILED: string;
192
+ WEB_COMPONENT_NOT_DEFINED: string;
193
+ INVALID_JWT: string;
194
+ };
195
+ protected scriptUrls: {
196
+ sandbox: string;
197
+ production: string;
198
+ };
199
+ protected webComponentTag: string;
200
+ /**
201
+ * Render the Withdraw widget to a container element
202
+ * @param container - The container element to render the widget into
203
+ * @returns Promise that resolves when the widget is rendered
204
+ */
205
+ render(container: HTMLElement): Promise<void>;
206
+ /**
207
+ * Update the configuration of the Withdraw widget
208
+ * @param config - Partial configuration to update
209
+ */
210
+ updateConfig(config: Partial<WithdrawConfig>): void;
211
+ /**
212
+ * Get the current configuration
213
+ * @returns The current configuration object
214
+ */
215
+ getConfig(): Readonly<WithdrawConfig>;
216
+ /**
217
+ * Check if the Withdraw widget is currently rendered
218
+ * @returns True if the widget is rendered, false otherwise
219
+ */
220
+ isRendered(): boolean;
221
+ /**
222
+ * Destroy the Withdraw widget and clean up resources
223
+ */
224
+ destroy(): void;
225
+ }
226
+ export { Withdraw }
227
+ export default Withdraw;
228
+
229
+ declare type WithdrawalCompletedPayload = {
230
+ /** Data associated with the withdrawal */
231
+ data: {
232
+ /** Unique identifier for the withdrawal */
233
+ withdrawalId: string;
234
+ /** Current status of the withdrawal */
235
+ status: WithdrawalStatus;
236
+ /** Asset identifier (e.g., 'btc', 'eth') */
237
+ assetId: string;
238
+ /** Network identifier (e.g., 'bitcoin', 'ethereum') */
239
+ networkId: string;
240
+ /** Amount being withdrawn */
241
+ amount?: string;
242
+ };
243
+ };
244
+
245
+ /**
246
+ * Withdrawal initiated event data
247
+ */
248
+ declare type WithdrawalInitiatedEventData = {
249
+ /** Unique identifier for the withdrawal */
250
+ withdrawalId: string;
251
+ };
252
+
253
+ declare type WithdrawalStatus = {
254
+ /** Status value */
255
+ value: string;
256
+ /** Human-readable details about the status */
257
+ details: string;
258
+ /** Timestamp when the status occurred (ISO 8601 format) */
259
+ occurredAt: string;
260
+ };
261
+
262
+ /**
263
+ * Callback function types for Connect Withdraw components
264
+ * Extends common callbacks with withdraw-specific callbacks
265
+ */
266
+ declare type WithdrawCallbacks = CommonCallbacks<WithdrawEvent> & {
267
+ /** Called when a withdrawal action occurs */
268
+ onWithdrawal?: (withdrawal: WithdrawalCompletedPayload) => void;
269
+ };
270
+
271
+ export declare interface WithdrawConfig extends BaseConfig<WithdrawEvent>, WithdrawCallbacks {
272
+ }
273
+
274
+ /**
275
+ * Withdraw event structure
276
+ */
277
+ declare type WithdrawEvent = AppEvent<WithdrawEventType, WithdrawalInitiatedEventData>;
278
+
279
+ /**
280
+ * Withdraw event type literals
281
+ */
282
+ declare type WithdrawEventType = 'withdrawal.initiated' | 'withdrawal.submitted' | 'withdrawal.completed';
283
+
284
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,197 @@
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);
9
+ this.config = {
10
+ ...e,
11
+ env: e.env || s,
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 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
+ });
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(([r, t]) => {
135
+ t && (e[r] = t);
136
+ }), e;
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: "Withdraw widget is already rendered. Call destroy() before rendering again.",
146
+ NOT_RENDERED: "Withdraw widget is not rendered. Call render() first.",
147
+ INVALID_CONTAINER: "Invalid container element provided.",
148
+ SCRIPT_LOAD_FAILED: "Failed to load the Connect Withdraw script.",
149
+ WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded.",
150
+ INVALID_JWT: "JWT token is required and must be a string."
151
+ };
152
+ scriptUrls = {
153
+ sandbox: "https://sdk.sandbox.connect.xyz/withdraw-web/index.js",
154
+ production: "https://sdk.connect.xyz/withdraw-web/index.js"
155
+ };
156
+ webComponentTag = "connect-withdraw";
157
+ /**
158
+ * Render the Withdraw widget to a container element
159
+ * @param container - The container element to render the widget into
160
+ * @returns Promise that resolves when the widget is rendered
161
+ */
162
+ render(e) {
163
+ return super.render(e);
164
+ }
165
+ /**
166
+ * Update the configuration of the Withdraw widget
167
+ * @param config - Partial configuration to update
168
+ */
169
+ updateConfig(e) {
170
+ return super.updateConfig(e);
171
+ }
172
+ /**
173
+ * Get the current configuration
174
+ * @returns The current configuration object
175
+ */
176
+ getConfig() {
177
+ return super.getConfig();
178
+ }
179
+ /**
180
+ * Check if the Withdraw widget is currently rendered
181
+ * @returns True if the widget is rendered, false otherwise
182
+ */
183
+ isRendered() {
184
+ return super.isRendered();
185
+ }
186
+ /**
187
+ * Destroy the Withdraw widget and clean up resources
188
+ */
189
+ destroy() {
190
+ return super.destroy();
191
+ }
192
+ }
193
+ export {
194
+ o as ErrorCode,
195
+ h as Withdraw,
196
+ h as default
197
+ };
@@ -0,0 +1 @@
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.Withdraw={}))})(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:"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()}}r.Withdraw=a,r.default=a,Object.defineProperties(r,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@connect-xyz/withdraw-js",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ "./package.json": "./package.json",
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "!**/*.tsbuildinfo"
19
+ ],
20
+ "nx": {
21
+ "name": "withdraw-js"
22
+ }
23
+ }