posemesh-domain-http 1.5.3

HTTP client library for interacting with AukiLabs domain data services, supporting both native and WebAssembly targets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use crate::domain_client::DomainClient as r_DomainClient;
use crate::domain_client::ListDomainsQuery as r_ListDomainsQuery;
use crate::domain_data::{
    DownloadQuery as r_DownloadQuery, UploadDomainData as r_UploadDomainData,
};
use crate::reconstruction::JobRequest as r_JobRequest;
use serde_wasm_bindgen::{from_value, to_value};
use wasm_bindgen::prelude::*;
use wasm_bindgen::{JsError, JsValue};
use wasm_bindgen_futures::{
    future_to_promise,
    js_sys::{Promise, Uint8Array},
};
use wasm_streams::readable::sys;

#[wasm_bindgen(typescript_custom_section)]
const TS_APPEND_CONTENT: &'static str = r#"

export type DownloadQuery = { ids: string[], name: string | null, data_type: string | null };
export type UploadDomainData = { id?: string, name?: string, data_type?: string, data: Uint8Array };
export type DomainDataMetadata = { id: string, name: string, data_type: string, size: number, created_at: string, updated_at: string };
export type DomainData = { metadata: DomainDataMetadata, data: Uint8Array };
export type DomainServer = { id: string, url: string, organization_id: string, name: string };
export type DomainWithServer = { id: string, name: string, organization_id: string, domain_server_id: string, redirect_url: string | null, domain_server: DomainServer };
export type JobRequest = { data_ids: string[], processing_type: string, server_api_key: string, server_url: string };
/**
 * ListDomainsQuery specifies the parameters for listing domains the caller has access to.
 *
 * - org: (required) The organization to list domains from:
 *   - "own": returns domains in your own organization.
 *   - a UUID: returns domains in that specific organization.
 *   - "all": returns domains across all organizations. When filtering by 'portal' (see below), this works without restrictions.
 *     Otherwise, 'domain_server_id' is required and the domain server must belong to your org.
 *     Not available for app tokens without a portal filter.
 * - portal_id: (optional) Full UUID of a portal to filter domains. Mutually exclusive with 'portal_short_id'.
 * - portal_short_id: (optional) Short ID of a portal to filter domains. Mutually exclusive with 'portal_id'.
 * - domain_server_id: (optional) UUID of the domain server to filter domains. Ignored if a portal filter is active.
 */
export type ListDomainsQuery = { portal_id?: string | null, portal_short_id?: string | null, org: string, domain_server_id?: string | null };

/**
 * Signs in with application credentials to obtain a DomainClient instance. Make sure to call .free() to free the memory when you are done with the client.
 *
 * @param api_url - The base URL for the API service.
 * @param dds_url - The URL for the Domain Discovery Service.
 * @param client_id - Unique identifier for this client.
 * @param app_key - Application key for authentication.
 * @param app_secret - Application secret for authentication.
 * @returns Promise that resolves to a DomainClient instance.
 *
 * @example
 * const client = await signInWithAppCredential(
 *   "https://api.auki.network",
 *   "https://dds.auki.network",
 *   "my-client-id",
 *   "app-key-123",
 *   "app-secret-456"
 * );
 * client.free(); // free the memory when you are done with the client
 */
export function signInWithAppCredential(
    api_url: string,
    dds_url: string,
    client_id: string,
    app_key: string,
    app_secret: string
): Promise<DomainClient>;

/**
 * Signs in with user credentials to obtain a DomainClient instance. Make sure to call .free() to free the memory when you are done with the client.
 *
 * @param api_url - The base URL for the API service.
 * @param dds_url - The URL for the Domain Discovery Service.
 * @param client_id - Unique identifier for this client.
 * @param email - User's email address.
 * @param password - User's password.
 * @param remember_password - Set to `true` if you want to automatically relogin with the same credentials after refreshtoken expires, it is NOT recommended to set to `true` in client side as storing credentials in the browser increases security risks (e.g., XSS attacks).
 * @returns Promise that resolves to a DomainClient instance.
 *
 * @example
 * const client = await signInWithUserCredential(
 *   "https://api.auki.network",
 *   "https://dds.auki.network",
 *   "my-client-id",
 *   "user@example.com",
 *   "password123",
 *   false
 * );
 * client.free(); // free the memory when you are done with the client
 */
export function signInWithUserCredential(
    api_url: string,
    dds_url: string,
    client_id: string,
    email: string,
    password: string,
    logout: boolean
): Promise<DomainClient>;

"#;

/// WASM wrapper for DomainClient that provides JavaScript bindings
///
/// This struct wraps the Rust DomainClient and exposes its functionality
/// to JavaScript through WASM bindings. It handles authentication,
/// domain data upload/download, and metadata operations.
#[wasm_bindgen(getter_with_clone)]
pub struct DomainClient {
    domain_client: r_DomainClient,
}

#[wasm_bindgen(js_name = "signInWithAppCredential")]
pub fn sign_in_with_app_credential(
    api_url: String,
    dds_url: String,
    client_id: String,
    app_key: String,
    app_secret: String,
) -> Promise {
    let future = async move {
        let res = r_DomainClient::new_with_app_credential(
            &api_url,
            &dds_url,
            &client_id,
            &app_key,
            &app_secret,
        )
        .await;
        match res {
            Ok(domain_client) => Ok(JsValue::from(DomainClient {
                domain_client: domain_client,
            })),
            Err(e) => Err(JsError::new(&e.to_string()).into()),
        }
    };
    future_to_promise(future)
}

#[wasm_bindgen(js_name = "signInWithUserCredential")]
pub fn sign_in_with_user_credential(
    api_url: String,
    dds_url: String,
    client_id: String,
    email: String,
    password: String,
    remember_password: bool,
) -> Promise {
    let future = async move {
        let res = r_DomainClient::new_with_user_credential(
            &api_url,
            &dds_url,
            &client_id,
            &email,
            &password,
            remember_password,
        )
        .await;
        match res {
            Ok(domain_client) => Ok(JsValue::from(DomainClient {
                domain_client: domain_client,
            })),
            Err(e) => Err(JsError::new(&e.to_string()).into()),
        }
    };
    future_to_promise(future)
}

#[wasm_bindgen]
impl DomainClient {
    /// Constructs a new DomainClient instance. Make sure to call .free() to free the memory when you are done with the client.
    ///
    /// # Arguments
    /// * `api_url` - The base URL for the API service.
    /// * `dds_url` - The URL for the Domain Discovery Service.
    /// * `client_id` - Unique identifier for this client.
    ///
    /// # Returns
    /// * `Self` - A new DomainClient instance.
    ///
    /// # Example
    /// ```javascript
    /// const client = new DomainClient(
    ///     "https://api.example.com".to_string(),
    ///     "https://dds.example.com".to_string(),
    ///     "my-client-id".to_string()
    /// );
    ///
    /// // free the memory when you are done with the client
    /// client.free();
    /// ```
    ///
    #[wasm_bindgen(constructor)]
    pub fn new(api_url: String, dds_url: String, client_id: String) -> Self {
        Self {
            domain_client: r_DomainClient::new(&api_url, &dds_url, &client_id),
        }
    }

    /// Returns a new DomainClient instance with the given OIDC access token for authentication. Make sure to call .free() to free the memory when you are done with the client.
    ///
    /// # Arguments
    /// * `oidc_access_token` - The OIDC access access token.
    ///
    /// # Returns
    /// * `Self` - A new DomainClient instance with the token applied.
    ///
    /// # Example
    /// ```javascript
    /// const client_with_token = client.withOIDCAccessToken("your-oidc-token");
    ///
    /// // free the memory when you are done with the client
    /// client_with_token.free();
    /// ```
    #[wasm_bindgen(js_name = "withOIDCAccessToken")]
    pub fn with_oidc_access_token(&self, oidc_access_token: String) -> Self {
        Self {
            domain_client: self
                .domain_client
                .with_oidc_access_token(&oidc_access_token),
        }
    }

    /// Downloads metadata for domain data matching the query.
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `query` - The query `DownloadQuery` parameters for filtering data.
    ///
    /// # Returns
    /// * `Promise<DomainDataMetadata[]>` - Resolves to an array of DomainDataMetadata.
    ///
    /// # Example
    /// ```javascript
    /// let metadata: DomainDataMetadata[] = await client.downloadDomainDataMetadata(
    ///     "domain-123",
    ///     { ids: [], name: null, data_type: "data type" }
    /// );
    /// ```
    #[wasm_bindgen(js_name = "downloadDomainDataMetadata")]
    pub fn download_domain_data_metadata(&self, domain_id: String, query: JsValue) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let parse = from_value::<r_DownloadQuery>(query);
            if let Err(e) = parse {
                return Err(JsError::new(&e.to_string()).into());
            }
            let query = parse.unwrap();
            let res = domain_client.download_metadata(&domain_id, &query).await;
            match res {
                Ok(data) => match to_value(&data) {
                    Ok(value) => Ok(value),
                    Err(e) => Err(JsError::new(&e.to_string()).into()),
                },
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// Downloads domain data matching the query, including the data bytes.
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `query` - The query `DownloadQuery` parameters for filtering data.
    ///
    /// # Returns
    /// * `Promise<DomainData[]>` - Resolves to an array of DomainData.
    ///
    /// # Example
    /// ```javascript
    /// let data: DomainData[] = await client.downloadDomainData(
    ///     "domain-123",
    ///     { ids: [], name: null, data_type: "data type" }
    /// );
    /// ```
    #[wasm_bindgen(js_name = "downloadDomainData")]
    pub fn download_domain_data(&self, domain_id: String, query: JsValue) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let parse = from_value::<r_DownloadQuery>(query);
            if let Err(e) = parse {
                return Err(JsError::new(&e.to_string()).into());
            }
            let query = parse.unwrap();
            let res = domain_client.download_domain_data(&domain_id, &query).await;
            if let Err(e) = res {
                return Err(JsError::new(&e.to_string()).into());
            }
            let response = res.unwrap();

            to_value(&response).map_err(|e| JsError::new(&e.to_string()).into())
        };
        future_to_promise(future)
    }

    /// Downloads domain data as a readable stream, matching the query.
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `query` - The query `DownloadQuery` parameters for filtering data.
    ///
    /// # Returns
    /// * `ReadableStream<DomainData>` - A JavaScript ReadableStream of DomainData objects.
    ///
    /// # Example
    /// ```javascript
    /// let stream: ReadableStream<DomainData> = client.downloadDomainDataStream(
    ///     "domain-123",
    ///     { ids: [], name: null, data_type: "data type" }
    /// );
    /// ```
    #[wasm_bindgen(js_name = "downloadDomainDataStream")]
    pub fn download_domain_data_stream(
        &self,
        domain_id: String,
        query: JsValue,
    ) -> sys::ReadableStream {
        use futures::{SinkExt, StreamExt};
        use wasm_bindgen_futures::spawn_local;
        // We'll use a futures channel to push items into JS
        let (mut tx, rx) = futures::channel::mpsc::unbounded::<Result<JsValue, JsValue>>();
        let domain_client = self.domain_client.clone();
        // Spawn a Rust async task that sends data
        spawn_local(async move {
            let query = match from_value::<r_DownloadQuery>(query) {
                Ok(q) => q,
                Err(e) => {
                    tx.send(Err(JsError::new(&e.to_string()).into())).await.ok();
                    return;
                }
            };
            let res = domain_client
                .download_domain_data_stream(&domain_id, &query)
                .await;
            if let Ok(mut download_rx) = res {
                while let Some(result) = download_rx.next().await {
                    match result {
                        Ok(data) => match to_value(&data) {
                            Ok(value) => {
                                tx.send(Ok(value)).await.ok();
                            }
                            Err(e) => {
                                tx.send(Err(JsError::new(&e.to_string()).into())).await.ok();
                            }
                        },
                        Err(e) => {
                            tx.send(Err(JsError::new(&e.to_string()).into())).await.ok();
                        }
                    }
                }
            }
        });

        wasm_streams::ReadableStream::into_raw(wasm_streams::ReadableStream::from_stream(rx))
    }

    /// Uploads domain data (create or update):
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `data`: `UploadDomainData[]` - The array of UploadDomainData objects.
    ///
    /// # Returns
    /// * `Promise<DomainDataMetadata[]>` - Resolves to an array of DomainDataMetadata.
    ///
    /// # Example
    /// ```javascript
    /// let result: DomainDataMetadata[] = await client.uploadDomainData(
    ///     "domain-123",
    ///     [{
    ///         name: "test",
    ///         data_type: "test",
    ///         data: new Uint8Array([1, 2, 3])
    ///     }, {
    ///         id: "data-id-456",
    ///         data: new Uint8Array([1, 2, 3])
    ///     }]
    /// ] as UploadDomainData[]
    /// );
    /// ```
    #[wasm_bindgen(js_name = "uploadDomainData")]
    pub fn upload_domain_data(&self, domain_id: String, data: JsValue) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            match from_value::<Vec<r_UploadDomainData>>(data) {
                Ok(upload) => {
                    let res = domain_client.upload_domain_data(&domain_id, upload).await;
                    match res {
                        Ok(data) => match to_value(&data) {
                            Ok(value) => Ok(value),
                            Err(e) => Err(JsError::new(&e.to_string()).into()),
                        },
                        Err(e) => Err(JsError::new(&e.to_string()).into()),
                    }
                }
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// Downloads the raw data bytes for a specific domain data object by its ID.
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `id` - The ID of the data object to download.
    ///
    /// # Returns
    /// * `Promise<Uint8Array>` - Resolves to a Uint8Array containing the data bytes.
    ///
    /// # Example
    /// ```javascript
    /// let bytes: Uint8Array = await client.downloadDomainDataById(
    ///     "domain-123",
    ///     "data-id-456"
    /// );
    /// ```
    #[wasm_bindgen(js_name = "downloadDomainDataById")]
    pub fn download_domain_data_by_id(&self, domain_id: String, id: String) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let res = domain_client
                .download_domain_data_by_id(&domain_id, &id)
                .await;
            match res {
                Ok(data) => Ok(JsValue::from(Uint8Array::from(data.as_slice()))),
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// Deletes a domain data object by ID.
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `id` - The ID of the data object to delete.
    ///
    /// # Returns
    /// * `Promise<void>` - Resolves when the deletion is complete.
    ///
    /// # Example
    /// ```javascript
    /// await client.deleteDomainDataById(
    ///     "domain-123",
    ///     "data-id-456"
    /// );
    /// ```
    #[wasm_bindgen(js_name = "deleteDomainDataById")]
    pub fn delete_domain_data_by_id(&self, domain_id: String, id: String) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let res = domain_client
                .delete_domain_data_by_id(&domain_id, &id)
                .await;
            match res {
                Ok(()) => Ok(JsValue::undefined()),
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// Triggers a reconstruction job
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain.
    /// * `request` - The `JobRequest` object containing reconstruction job parameters.
    ///
    /// # Returns
    /// * `Promise`
    ///
    /// # Example
    /// ```javascript
    /// let result: string = await client.submitJobV1(
    ///     "domain-123",
    ///     {
    ///         data_ids: ["data-id-1", "data-id-2"],
    ///         server_url: "https://processing-server.example.com" // reconstruction server url
    ///     } as JobRequest
    /// );
    /// ```
    #[wasm_bindgen(js_name = "submitJobV1")]
    pub fn submit_job_v1(&self, domain_id: String, request: JsValue) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            match from_value::<r_JobRequest>(request) {
                Ok(process_request) => {
                    let res = domain_client
                        .submit_job_request_v1(&domain_id, &process_request)
                        .await;
                    match res {
                        Ok(response) => {
                            let body = response
                                .text()
                                .await
                                .map_err(|e| JsError::new(&e.to_string()))?;
                            Ok(JsValue::from_str(&body))
                        }
                        Err(e) => Err(JsError::new(&e.to_string()).into()),
                    }
                }
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// # ListDomains returns a list of domains the caller has access to.
    ///
    /// # Arguments
    /// * `query` - The `ListDomainsQuery` object containing the query parameters.
    ///
    /// # Returns
    /// * `Promise<ListDomainsResponse>` - Resolves to a ListDomainsResponse object.
    ///
    /// # Example
    /// ```javascript
    /// let domains: ListDomainsResponse = await client.listDomains({ org: "own", domain_server_id: "domain-server-123" });
    /// ```
    #[wasm_bindgen(js_name = "listDomains")]
    pub fn list_domains(&self, query: JsValue) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let query = match from_value::<r_ListDomainsQuery>(query) {
                Ok(q) => q,
                Err(e) => {
                    return Err(JsError::new(&e.to_string()).into());
                }
            };
            let res = domain_client.list_domains(&query).await;
            match res {
                Ok(response) => match to_value(&response.domains) {
                    Ok(value) => Ok(value),
                    Err(e) => Err(JsError::new(&e.to_string()).into()),
                },
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// Creates domain
    ///
    /// # Arguments
    /// * `name` - The name of the domain.
    /// * `domain_server_id` - The ID of the domain server.
    /// * `domain_server_url` - The URL of the domain server.
    /// * `redirect_url` - The redirect URL of the domain.
    ///
    /// # Returns
    /// * `Promise<DomainWithServer>` - Resolves to a DomainWithServer object.
    ///
    /// # Example
    /// ```javascript
    /// let domain: DomainWithServer = await client.createDomain("test domain", "domain-server-id", "https://domain-server.example.com", "https://redirect.example.com");
    /// ```
    #[wasm_bindgen(js_name = "createDomain")]
    pub fn create_domain(
        &self,
        name: String,
        domain_server_id: Option<String>,
        domain_server_url: Option<String>,
        redirect_url: Option<String>,
    ) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let res = domain_client
                .create_domain(&name, domain_server_id, domain_server_url, redirect_url)
                .await;
            match res {
                Ok(domain) => match to_value(&domain.domain) {
                    Ok(value) => Ok(value),
                    Err(e) => Err(JsError::new(&e.to_string()).into()),
                },
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }

    /// Deletes a domain
    ///
    /// # Arguments
    /// * `domain_id` - The ID of the domain to delete.
    ///
    /// # Returns
    /// * `Promise<void>` - Resolves when the deletion is complete.
    ///
    /// # Example
    /// ```javascript
    /// await client.deleteDomain("domain-123");
    /// ```
    #[wasm_bindgen(js_name = "deleteDomain")]
    pub fn delete_domain(&self, domain_id: String) -> Promise {
        let domain_client = self.domain_client.clone();
        let future = async move {
            let res = domain_client.delete_domain(&domain_id).await;
            match res {
                Ok(()) => Ok(JsValue::undefined()),
                Err(e) => Err(JsError::new(&e.to_string()).into()),
            }
        };
        future_to_promise(future)
    }
}

/// Initializes the WASM module with logging and error handling
///
/// This function is automatically called when the WASM module is loaded.
/// It sets up console error handling for panics and configures tracing
/// for comprehensive logging in the browser environment.
///
/// # Example
/// ```javascript
/// // This is automatically called when the WASM module loads
/// // No manual call needed
/// ```
#[wasm_bindgen(start)]
pub fn start() -> Result<(), JsValue> {
    // print pretty errors in wasm https://github.com/rustwasm/console_error_panic_hook
    // This is not needed for tracing_wasm to work, but it is a common tool for getting proper error line numbers for panics.
    console_error_panic_hook::set_once();

    // Configure tracing for WASM with comprehensive settings for async operations
    let config = tracing_wasm::WASMLayerConfigBuilder::new()
        .set_max_level(tracing::Level::DEBUG)
        .build();

    tracing_wasm::set_as_global_default_with_config(config);

    // Ensure tracing is properly initialized
    tracing::info!("Starting log for DOMAIN-HTTP");

    Ok(())
}