nylas-types 0.1.1

Type definitions for Nylas API v3
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
//! Grant types for Nylas API v3.
//!
//! Grants represent authenticated connections to email and calendar providers.

use serde::{Deserialize, Serialize};

use crate::common::{GrantId, Provider};

/// Custom authentication settings for different providers
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CustomAuthSettings {
    /// Google OAuth settings
    Google {
        /// Google OAuth refresh token
        refresh_token: String,

        /// Google client ID
        #[serde(skip_serializing_if = "Option::is_none")]
        client_id: Option<String>,

        /// Google client secret
        #[serde(skip_serializing_if = "Option::is_none")]
        client_secret: Option<String>,
    },

    /// Microsoft OAuth settings
    Microsoft {
        /// Microsoft OAuth refresh token
        refresh_token: String,

        /// Microsoft client ID
        #[serde(skip_serializing_if = "Option::is_none")]
        client_id: Option<String>,

        /// Microsoft client secret
        #[serde(skip_serializing_if = "Option::is_none")]
        client_secret: Option<String>,
    },

    /// IMAP credentials
    Imap {
        /// IMAP host
        imap_host: String,

        /// IMAP port
        imap_port: u16,

        /// IMAP username
        imap_username: String,

        /// IMAP password
        imap_password: String,

        /// SMTP host
        smtp_host: String,

        /// SMTP port
        smtp_port: u16,

        /// SMTP username
        #[serde(skip_serializing_if = "Option::is_none")]
        smtp_username: Option<String>,

        /// SMTP password
        #[serde(skip_serializing_if = "Option::is_none")]
        smtp_password: Option<String>,
    },
}

/// Grant settings (OAuth token or custom credentials)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GrantSettings {
    /// Use access token from hosted OAuth
    AccessToken {
        /// Access token
        access_token: String,
    },

    /// Use custom authentication
    Custom(CustomAuthSettings),
}

/// Grant status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GrantStatus {
    /// Grant is valid and active.
    Valid,
    /// Grant is invalid or expired.
    Invalid,
}

/// Grant model.
///
/// Represents a Nylas grant which provides access to a user's account.
///
/// # Example
///
/// ```
/// # use nylas_types::{Grant, GrantId, Provider, GrantStatus};
/// let grant = Grant {
///     id: GrantId::new("grant_123"),
///     provider: Provider::Google,
///     grant_status: Some(GrantStatus::Valid),
///     email: Some("user@example.com".to_string()),
///     scope: Some(vec!["https://www.googleapis.com/auth/gmail.readonly".to_string()]),
///     user_timezone: None,
///     created_at: Some(1234567890),
///     updated_at: Some(1234567890),
///     provider_user_id: None,
///     ip: None,
///     state: None,
///     user_agent: None,
///     settings: None,
///     metadata: None,
/// };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grant {
    /// Unique identifier for the grant.
    pub id: GrantId,

    /// Provider for this grant.
    pub provider: Provider,

    /// Grant status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grant_status: Option<GrantStatus>,

    /// Email address associated with this grant.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,

    /// OAuth scopes granted to this connection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Vec<String>>,

    /// User's timezone.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_timezone: Option<String>,

    /// Created timestamp (Unix time).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<i64>,

    /// Updated timestamp (Unix time).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<i64>,

    /// Provider-specific user identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider_user_id: Option<String>,

    /// IP address from the authentication request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip: Option<String>,

    /// OAuth state parameter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,

    /// User agent from the authentication request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_agent: Option<String>,

    /// Provider-specific settings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub settings: Option<serde_json::Value>,

    /// Custom metadata (key-value pairs).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

/// Request to create a new grant.
///
/// Grants can be created from OAuth tokens or custom authentication credentials.
///
/// # Example
///
/// ```
/// # use nylas_types::{CreateGrantRequest, Provider, GrantSettings};
/// // Create from OAuth access token
/// let request = CreateGrantRequest::from_access_token(
///     Provider::Google,
///     "oauth_access_token".to_string(),
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CreateGrantRequest {
    /// Provider type.
    pub provider: Provider,

    /// Grant settings (OAuth or custom)
    pub settings: GrantSettings,

    /// Grant state (defaults to "valid")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<GrantStatus>,

    /// OAuth scopes to request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Vec<String>>,

    /// Custom metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

impl CreateGrantRequest {
    /// Create a builder for CreateGrantRequest.
    pub fn builder(provider: Provider) -> CreateGrantRequestBuilder {
        CreateGrantRequestBuilder::new(provider)
    }

    /// Create from OAuth access token
    ///
    /// # Example
    ///
    /// ```
    /// # use nylas_types::{CreateGrantRequest, Provider};
    /// let request = CreateGrantRequest::from_access_token(
    ///     Provider::Google,
    ///     "oauth_token_123".to_string(),
    /// );
    /// assert_eq!(request.provider, Provider::Google);
    /// ```
    pub fn from_access_token(provider: Provider, access_token: String) -> Self {
        Self {
            provider,
            settings: GrantSettings::AccessToken { access_token },
            state: None,
            scope: None,
            metadata: None,
        }
    }

    /// Create from custom authentication settings
    ///
    /// # Example
    ///
    /// ```
    /// # use nylas_types::{CreateGrantRequest, Provider, CustomAuthSettings};
    /// let custom_auth = CustomAuthSettings::Imap {
    ///     imap_host: "imap.example.com".to_string(),
    ///     imap_port: 993,
    ///     imap_username: "user@example.com".to_string(),
    ///     imap_password: "password".to_string(),
    ///     smtp_host: "smtp.example.com".to_string(),
    ///     smtp_port: 587,
    ///     smtp_username: None,
    ///     smtp_password: None,
    /// };
    ///
    /// let request = CreateGrantRequest::from_custom_auth(
    ///     Provider::Imap,
    ///     custom_auth,
    /// );
    /// assert_eq!(request.provider, Provider::Imap);
    /// ```
    pub fn from_custom_auth(provider: Provider, settings: CustomAuthSettings) -> Self {
        Self {
            provider,
            settings: GrantSettings::Custom(settings),
            state: None,
            scope: None,
            metadata: None,
        }
    }
}

/// Builder for CreateGrantRequest.
#[derive(Debug, Clone)]
pub struct CreateGrantRequestBuilder {
    provider: Provider,
    settings: Option<GrantSettings>,
    grant_status: Option<GrantStatus>,
    scope: Option<Vec<String>>,
    metadata: Option<serde_json::Value>,
}

impl CreateGrantRequestBuilder {
    /// Create a new builder.
    pub fn new(provider: Provider) -> Self {
        Self {
            provider,
            settings: None,
            grant_status: None,
            scope: None,
            metadata: None,
        }
    }

    /// Set grant settings (OAuth token or custom auth).
    pub fn settings(mut self, settings: GrantSettings) -> Self {
        self.settings = Some(settings);
        self
    }

    /// Set access token (shorthand for OAuth token).
    pub fn access_token(mut self, token: String) -> Self {
        self.settings = Some(GrantSettings::AccessToken {
            access_token: token,
        });
        self
    }

    /// Set custom authentication settings.
    pub fn custom_auth(mut self, auth: CustomAuthSettings) -> Self {
        self.settings = Some(GrantSettings::Custom(auth));
        self
    }

    /// Set grant status.
    pub fn grant_status(mut self, status: GrantStatus) -> Self {
        self.grant_status = Some(status);
        self
    }

    /// Set OAuth scopes.
    pub fn scope(mut self, scope: Vec<String>) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Set custom metadata.
    pub fn metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Build the CreateGrantRequest.
    ///
    /// # Panics
    ///
    /// Panics if settings are not provided.
    pub fn build(self) -> CreateGrantRequest {
        CreateGrantRequest {
            provider: self.provider,
            settings: self.settings.expect("settings are required"),
            state: self.grant_status,
            scope: self.scope,
            metadata: self.metadata,
        }
    }
}

/// Request to update a grant.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct UpdateGrantRequest {
    /// Update grant settings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub settings: Option<GrantSettings>,

    /// Update grant state.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<GrantStatus>,

    /// Update OAuth scopes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Vec<String>>,

    /// Update custom metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

impl UpdateGrantRequest {
    /// Create a builder for UpdateGrantRequest.
    pub fn builder() -> UpdateGrantRequestBuilder {
        UpdateGrantRequestBuilder::default()
    }
}

/// Builder for UpdateGrantRequest.
#[derive(Debug, Clone, Default)]
pub struct UpdateGrantRequestBuilder {
    settings: Option<GrantSettings>,
    state: Option<GrantStatus>,
    scope: Option<Vec<String>>,
    metadata: Option<serde_json::Value>,
}

impl UpdateGrantRequestBuilder {
    /// Set grant settings.
    pub fn settings(mut self, settings: GrantSettings) -> Self {
        self.settings = Some(settings);
        self
    }

    /// Set grant state.
    pub fn state(mut self, state: GrantStatus) -> Self {
        self.state = Some(state);
        self
    }

    /// Set OAuth scopes.
    pub fn scope(mut self, scope: Vec<String>) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Set custom metadata.
    pub fn metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Build the UpdateGrantRequest.
    pub fn build(self) -> UpdateGrantRequest {
        UpdateGrantRequest {
            settings: self.settings,
            state: self.state,
            scope: self.scope,
            metadata: self.metadata,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_grant_serialization() {
        let grant = Grant {
            id: GrantId::new("grant_123"),
            provider: Provider::Google,
            grant_status: Some(GrantStatus::Valid),
            email: Some("user@example.com".to_string()),
            scope: Some(vec![
                "https://www.googleapis.com/auth/gmail.readonly".to_string()
            ]),
            user_timezone: None,
            created_at: Some(1234567890),
            updated_at: Some(1234567890),
            provider_user_id: None,
            ip: None,
            state: None,
            user_agent: None,
            settings: None,
            metadata: None,
        };

        let json = serde_json::to_string(&grant).unwrap();
        assert!(json.contains("grant_123"));
        assert!(json.contains("google"));
        assert!(json.contains("user@example.com"));
    }

    #[test]
    fn test_grant_deserialization() {
        let json = r#"{
            "id": "grant_123",
            "provider": "google",
            "grant_status": "valid",
            "email": "user@example.com",
            "scope": ["https://www.googleapis.com/auth/gmail.readonly"],
            "created_at": 1234567890,
            "updated_at": 1234567890
        }"#;

        let grant: Grant = serde_json::from_str(json).unwrap();
        assert_eq!(grant.id.as_str(), "grant_123");
        assert_eq!(grant.provider, Provider::Google);
        assert_eq!(grant.grant_status, Some(GrantStatus::Valid));
        assert_eq!(grant.email, Some("user@example.com".to_string()));
    }

    #[test]
    fn test_grant_status_serialization() {
        assert_eq!(
            serde_json::to_string(&GrantStatus::Valid).unwrap(),
            r#""valid""#
        );
        assert_eq!(
            serde_json::to_string(&GrantStatus::Invalid).unwrap(),
            r#""invalid""#
        );
    }

    #[test]
    fn test_create_grant_request_builder() {
        let request = CreateGrantRequest::builder(Provider::Google)
            .access_token("token_123".to_string())
            .scope(vec![
                "https://www.googleapis.com/auth/gmail.readonly".to_string()
            ])
            .grant_status(GrantStatus::Valid)
            .build();

        assert_eq!(request.provider, Provider::Google);
        assert!(request.scope.is_some());
        assert_eq!(request.state, Some(GrantStatus::Valid));
        assert!(request.metadata.is_none());
    }

    #[test]
    fn test_create_grant_request_with_metadata() {
        let metadata = serde_json::json!({"team": "engineering"});
        let request = CreateGrantRequest::builder(Provider::Microsoft)
            .access_token("token_456".to_string())
            .metadata(metadata.clone())
            .build();

        assert_eq!(request.provider, Provider::Microsoft);
        assert_eq!(request.metadata, Some(metadata));
    }

    #[test]
    fn test_create_grant_from_access_token() {
        let request =
            CreateGrantRequest::from_access_token(Provider::Google, "token_123".to_string());

        assert_eq!(request.provider, Provider::Google);
        assert!(matches!(
            request.settings,
            GrantSettings::AccessToken { .. }
        ));
    }

    #[test]
    fn test_create_grant_from_custom_auth() {
        let custom_auth = CustomAuthSettings::Imap {
            imap_host: "imap.example.com".to_string(),
            imap_port: 993,
            imap_username: "user@example.com".to_string(),
            imap_password: "password".to_string(),
            smtp_host: "smtp.example.com".to_string(),
            smtp_port: 587,
            smtp_username: None,
            smtp_password: None,
        };

        let request = CreateGrantRequest::from_custom_auth(Provider::Imap, custom_auth);

        assert_eq!(request.provider, Provider::Imap);
        assert!(matches!(request.settings, GrantSettings::Custom(_)));
    }

    #[test]
    fn test_update_grant_request_builder() {
        let metadata = serde_json::json!({"updated": true});
        let request = UpdateGrantRequest::builder()
            .metadata(metadata.clone())
            .scope(vec!["new_scope".to_string()])
            .state(GrantStatus::Invalid)
            .build();

        assert_eq!(request.metadata, Some(metadata));
        assert_eq!(request.scope, Some(vec!["new_scope".to_string()]));
        assert_eq!(request.state, Some(GrantStatus::Invalid));
        assert!(request.settings.is_none());
    }

    #[test]
    fn test_update_grant_request_default() {
        let request = UpdateGrantRequest::default();
        assert!(request.settings.is_none());
        assert!(request.state.is_none());
        assert!(request.scope.is_none());
        assert!(request.metadata.is_none());
    }
}